three.min.js 802 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '57dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. String.prototype.trim = String.prototype.trim || function () {
  16. return this.replace( /^\s+|\s+$/g, '' );
  17. };
  18. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  19. THREE.extend = function ( obj, source ) {
  20. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  21. if ( Object.keys ) {
  22. var keys = Object.keys( source );
  23. for (var i = 0, il = keys.length; i < il; i++) {
  24. var prop = keys[i];
  25. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  26. }
  27. } else {
  28. var safeHasOwnProperty = {}.hasOwnProperty;
  29. for ( var prop in source ) {
  30. if ( safeHasOwnProperty.call( source, prop ) ) {
  31. obj[prop] = source[prop];
  32. }
  33. }
  34. }
  35. return obj;
  36. };
  37. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  38. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  39. // requestAnimationFrame polyfill by Erik Möller
  40. // fixes from Paul Irish and Tino Zijdel
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  45. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( window.requestAnimationFrame === undefined ) {
  49. window.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  57. }() );
  58. // GL STATE CONSTANTS
  59. THREE.CullFaceNone = 0;
  60. THREE.CullFaceBack = 1;
  61. THREE.CullFaceFront = 2;
  62. THREE.CullFaceFrontBack = 3;
  63. THREE.FrontFaceDirectionCW = 0;
  64. THREE.FrontFaceDirectionCCW = 1;
  65. // SHADOWING TYPES
  66. THREE.BasicShadowMap = 0;
  67. THREE.PCFShadowMap = 1;
  68. THREE.PCFSoftShadowMap = 2;
  69. // MATERIAL CONSTANTS
  70. // side
  71. THREE.FrontSide = 0;
  72. THREE.BackSide = 1;
  73. THREE.DoubleSide = 2;
  74. // shading
  75. THREE.NoShading = 0;
  76. THREE.FlatShading = 1;
  77. THREE.SmoothShading = 2;
  78. // colors
  79. THREE.NoColors = 0;
  80. THREE.FaceColors = 1;
  81. THREE.VertexColors = 2;
  82. // blending modes
  83. THREE.NoBlending = 0;
  84. THREE.NormalBlending = 1;
  85. THREE.AdditiveBlending = 2;
  86. THREE.SubtractiveBlending = 3;
  87. THREE.MultiplyBlending = 4;
  88. THREE.CustomBlending = 5;
  89. // custom blending equations
  90. // (numbers start from 100 not to clash with other
  91. // mappings to OpenGL constants defined in Texture.js)
  92. THREE.AddEquation = 100;
  93. THREE.SubtractEquation = 101;
  94. THREE.ReverseSubtractEquation = 102;
  95. // custom blending destination factors
  96. THREE.ZeroFactor = 200;
  97. THREE.OneFactor = 201;
  98. THREE.SrcColorFactor = 202;
  99. THREE.OneMinusSrcColorFactor = 203;
  100. THREE.SrcAlphaFactor = 204;
  101. THREE.OneMinusSrcAlphaFactor = 205;
  102. THREE.DstAlphaFactor = 206;
  103. THREE.OneMinusDstAlphaFactor = 207;
  104. // custom blending source factors
  105. //THREE.ZeroFactor = 200;
  106. //THREE.OneFactor = 201;
  107. //THREE.SrcAlphaFactor = 204;
  108. //THREE.OneMinusSrcAlphaFactor = 205;
  109. //THREE.DstAlphaFactor = 206;
  110. //THREE.OneMinusDstAlphaFactor = 207;
  111. THREE.DstColorFactor = 208;
  112. THREE.OneMinusDstColorFactor = 209;
  113. THREE.SrcAlphaSaturateFactor = 210;
  114. // TEXTURE CONSTANTS
  115. THREE.MultiplyOperation = 0;
  116. THREE.MixOperation = 1;
  117. THREE.AddOperation = 2;
  118. // Mapping modes
  119. THREE.UVMapping = function () {};
  120. THREE.CubeReflectionMapping = function () {};
  121. THREE.CubeRefractionMapping = function () {};
  122. THREE.SphericalReflectionMapping = function () {};
  123. THREE.SphericalRefractionMapping = function () {};
  124. // Wrapping modes
  125. THREE.RepeatWrapping = 1000;
  126. THREE.ClampToEdgeWrapping = 1001;
  127. THREE.MirroredRepeatWrapping = 1002;
  128. // Filters
  129. THREE.NearestFilter = 1003;
  130. THREE.NearestMipMapNearestFilter = 1004;
  131. THREE.NearestMipMapLinearFilter = 1005;
  132. THREE.LinearFilter = 1006;
  133. THREE.LinearMipMapNearestFilter = 1007;
  134. THREE.LinearMipMapLinearFilter = 1008;
  135. // Data types
  136. THREE.UnsignedByteType = 1009;
  137. THREE.ByteType = 1010;
  138. THREE.ShortType = 1011;
  139. THREE.UnsignedShortType = 1012;
  140. THREE.IntType = 1013;
  141. THREE.UnsignedIntType = 1014;
  142. THREE.FloatType = 1015;
  143. // Pixel types
  144. //THREE.UnsignedByteType = 1009;
  145. THREE.UnsignedShort4444Type = 1016;
  146. THREE.UnsignedShort5551Type = 1017;
  147. THREE.UnsignedShort565Type = 1018;
  148. // Pixel formats
  149. THREE.AlphaFormat = 1019;
  150. THREE.RGBFormat = 1020;
  151. THREE.RGBAFormat = 1021;
  152. THREE.LuminanceFormat = 1022;
  153. THREE.LuminanceAlphaFormat = 1023;
  154. // Compressed texture formats
  155. THREE.RGB_S3TC_DXT1_Format = 2001;
  156. THREE.RGBA_S3TC_DXT1_Format = 2002;
  157. THREE.RGBA_S3TC_DXT3_Format = 2003;
  158. THREE.RGBA_S3TC_DXT5_Format = 2004;
  159. /*
  160. // Potential future PVRTC compressed texture formats
  161. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  162. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  163. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  164. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  165. */
  166. /**
  167. * @author mrdoob / http://mrdoob.com/
  168. */
  169. THREE.Color = function ( value ) {
  170. if ( value !== undefined ) this.set( value );
  171. return this;
  172. };
  173. THREE.extend( THREE.Color.prototype, {
  174. r: 1, g: 1, b: 1,
  175. set: function ( value ) {
  176. switch ( typeof value ) {
  177. case "number":
  178. this.setHex( value );
  179. break;
  180. case "string":
  181. this.setStyle( value );
  182. break;
  183. }
  184. },
  185. setHex: function ( hex ) {
  186. hex = Math.floor( hex );
  187. this.r = ( hex >> 16 & 255 ) / 255;
  188. this.g = ( hex >> 8 & 255 ) / 255;
  189. this.b = ( hex & 255 ) / 255;
  190. return this;
  191. },
  192. setRGB: function ( r, g, b ) {
  193. this.r = r;
  194. this.g = g;
  195. this.b = b;
  196. return this;
  197. },
  198. setHSV: function ( h, s, v ) {
  199. console.log( 'DEPRECATED: Color\'s .setHSV() will be removed. Use .setHSL( h, s, l ) instead.' );
  200. return this.setHSL(h,s*v/((h=(2-s)*v)<1?h:2-h),h/2); // https://gist.github.com/xpansive/1337890
  201. },
  202. setHSL: function ( h, s, l ) {
  203. // h,s,l ranges are in 0.0 - 1.0
  204. if ( s === 0 ) {
  205. this.r = this.g = this.b = l;
  206. } else {
  207. var hue2rgb = function ( p, q, t ) {
  208. if ( t < 0 ) t += 1;
  209. if ( t > 1 ) t -= 1;
  210. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  211. if ( t < 1 / 2 ) return q;
  212. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  213. return p;
  214. };
  215. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  216. var q = ( 2 * l ) - p;
  217. this.r = hue2rgb( q, p, h + 1 / 3 );
  218. this.g = hue2rgb( q, p, h );
  219. this.b = hue2rgb( q, p, h - 1 / 3 );
  220. }
  221. return this;
  222. },
  223. setStyle: function ( style ) {
  224. // rgb(255,0,0)
  225. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  226. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  227. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  228. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  229. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  230. return this;
  231. }
  232. // rgb(100%,0%,0%)
  233. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  234. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  235. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  236. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  237. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  238. return this;
  239. }
  240. // #ff0000
  241. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  242. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  243. this.setHex( parseInt( color[ 1 ], 16 ) );
  244. return this;
  245. }
  246. // #f00
  247. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  248. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  249. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  250. return this;
  251. }
  252. // red
  253. if ( /^(\w+)$/i.test( style ) ) {
  254. this.setHex( THREE.ColorKeywords[ style ] );
  255. return this;
  256. }
  257. },
  258. copy: function ( color ) {
  259. this.r = color.r;
  260. this.g = color.g;
  261. this.b = color.b;
  262. return this;
  263. },
  264. copyGammaToLinear: function ( color ) {
  265. this.r = color.r * color.r;
  266. this.g = color.g * color.g;
  267. this.b = color.b * color.b;
  268. return this;
  269. },
  270. copyLinearToGamma: function ( color ) {
  271. this.r = Math.sqrt( color.r );
  272. this.g = Math.sqrt( color.g );
  273. this.b = Math.sqrt( color.b );
  274. return this;
  275. },
  276. convertGammaToLinear: function () {
  277. var r = this.r, g = this.g, b = this.b;
  278. this.r = r * r;
  279. this.g = g * g;
  280. this.b = b * b;
  281. return this;
  282. },
  283. convertLinearToGamma: function () {
  284. this.r = Math.sqrt( this.r );
  285. this.g = Math.sqrt( this.g );
  286. this.b = Math.sqrt( this.b );
  287. return this;
  288. },
  289. getHex: function () {
  290. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  291. },
  292. getHexString: function () {
  293. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  294. },
  295. getHSL: function () {
  296. var hsl = { h: 0, s: 0, l: 0 };
  297. return function () {
  298. // h,s,l ranges are in 0.0 - 1.0
  299. var r = this.r, g = this.g, b = this.b;
  300. var max = Math.max( r, g, b );
  301. var min = Math.min( r, g, b );
  302. var hue, saturation;
  303. var lightness = ( min + max ) / 2.0;
  304. if ( min === max ) {
  305. hue = 0;
  306. saturation = 0;
  307. } else {
  308. var delta = max - min;
  309. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  310. switch ( max ) {
  311. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  312. case g: hue = ( b - r ) / delta + 2; break;
  313. case b: hue = ( r - g ) / delta + 4; break;
  314. }
  315. hue /= 6;
  316. }
  317. hsl.h = hue;
  318. hsl.s = saturation;
  319. hsl.l = lightness;
  320. return hsl;
  321. };
  322. }(),
  323. getStyle: function () {
  324. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  325. },
  326. offsetHSL: function ( h, s, l ) {
  327. var hsl = this.getHSL();
  328. hsl.h += h; hsl.s += s; hsl.l += l;
  329. this.setHSL( hsl.h, hsl.s, hsl.l );
  330. return this;
  331. },
  332. add: function ( color ) {
  333. this.r += color.r;
  334. this.g += color.g;
  335. this.b += color.b;
  336. return this;
  337. },
  338. addColors: function ( color1, color2 ) {
  339. this.r = color1.r + color2.r;
  340. this.g = color1.g + color2.g;
  341. this.b = color1.b + color2.b;
  342. return this;
  343. },
  344. addScalar: function ( s ) {
  345. this.r += s;
  346. this.g += s;
  347. this.b += s;
  348. return this;
  349. },
  350. multiply: function ( color ) {
  351. this.r *= color.r;
  352. this.g *= color.g;
  353. this.b *= color.b;
  354. return this;
  355. },
  356. multiplyScalar: function ( s ) {
  357. this.r *= s;
  358. this.g *= s;
  359. this.b *= s;
  360. return this;
  361. },
  362. lerp: function ( color, alpha ) {
  363. this.r += ( color.r - this.r ) * alpha;
  364. this.g += ( color.g - this.g ) * alpha;
  365. this.b += ( color.b - this.b ) * alpha;
  366. return this;
  367. },
  368. equals: function ( c ) {
  369. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  370. },
  371. clone: function () {
  372. return new THREE.Color().setRGB( this.r, this.g, this.b );
  373. }
  374. } );
  375. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  376. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  377. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  378. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  379. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  380. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  381. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  382. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  383. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  384. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  385. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  386. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  387. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  388. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  389. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  390. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  391. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  392. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  393. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  394. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  395. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  396. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  397. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  398. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  399. /**
  400. * @author mikael emtinger / http://gomo.se/
  401. * @author alteredq / http://alteredqualia.com/
  402. * @author WestLangley / http://github.com/WestLangley
  403. * @author bhouston / http://exocortex.com
  404. */
  405. THREE.Quaternion = function( x, y, z, w ) {
  406. this.x = x || 0;
  407. this.y = y || 0;
  408. this.z = z || 0;
  409. this.w = ( w !== undefined ) ? w : 1;
  410. };
  411. THREE.extend( THREE.Quaternion.prototype, {
  412. set: function ( x, y, z, w ) {
  413. this.x = x;
  414. this.y = y;
  415. this.z = z;
  416. this.w = w;
  417. return this;
  418. },
  419. copy: function ( q ) {
  420. this.x = q.x;
  421. this.y = q.y;
  422. this.z = q.z;
  423. this.w = q.w;
  424. return this;
  425. },
  426. setFromEuler: function ( v, order ) {
  427. // http://www.mathworks.com/matlabcentral/fileexchange/
  428. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  429. // content/SpinCalc.m
  430. var c1 = Math.cos( v.x / 2 );
  431. var c2 = Math.cos( v.y / 2 );
  432. var c3 = Math.cos( v.z / 2 );
  433. var s1 = Math.sin( v.x / 2 );
  434. var s2 = Math.sin( v.y / 2 );
  435. var s3 = Math.sin( v.z / 2 );
  436. if ( order === undefined || order === 'XYZ' ) {
  437. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  438. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  439. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  440. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  441. } else if ( order === 'YXZ' ) {
  442. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  443. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  444. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  445. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  446. } else if ( order === 'ZXY' ) {
  447. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  448. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  449. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  450. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  451. } else if ( order === 'ZYX' ) {
  452. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  453. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  454. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  455. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  456. } else if ( order === 'YZX' ) {
  457. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  458. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  459. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  460. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  461. } else if ( order === 'XZY' ) {
  462. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  463. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  464. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  465. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  466. }
  467. return this;
  468. },
  469. setFromAxisAngle: function ( axis, angle ) {
  470. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  471. // axis have to be normalized
  472. var halfAngle = angle / 2,
  473. s = Math.sin( halfAngle );
  474. this.x = axis.x * s;
  475. this.y = axis.y * s;
  476. this.z = axis.z * s;
  477. this.w = Math.cos( halfAngle );
  478. return this;
  479. },
  480. setFromRotationMatrix: function ( m ) {
  481. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  482. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  483. var te = m.elements,
  484. m11 = te[0], m12 = te[4], m13 = te[8],
  485. m21 = te[1], m22 = te[5], m23 = te[9],
  486. m31 = te[2], m32 = te[6], m33 = te[10],
  487. trace = m11 + m22 + m33,
  488. s;
  489. if ( trace > 0 ) {
  490. s = 0.5 / Math.sqrt( trace + 1.0 );
  491. this.w = 0.25 / s;
  492. this.x = ( m32 - m23 ) * s;
  493. this.y = ( m13 - m31 ) * s;
  494. this.z = ( m21 - m12 ) * s;
  495. } else if ( m11 > m22 && m11 > m33 ) {
  496. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  497. this.w = (m32 - m23 ) / s;
  498. this.x = 0.25 * s;
  499. this.y = (m12 + m21 ) / s;
  500. this.z = (m13 + m31 ) / s;
  501. } else if ( m22 > m33 ) {
  502. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  503. this.w = (m13 - m31 ) / s;
  504. this.x = (m12 + m21 ) / s;
  505. this.y = 0.25 * s;
  506. this.z = (m23 + m32 ) / s;
  507. } else {
  508. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  509. this.w = ( m21 - m12 ) / s;
  510. this.x = ( m13 + m31 ) / s;
  511. this.y = ( m23 + m32 ) / s;
  512. this.z = 0.25 * s;
  513. }
  514. return this;
  515. },
  516. inverse: function () {
  517. this.conjugate().normalize();
  518. return this;
  519. },
  520. conjugate: function () {
  521. this.x *= -1;
  522. this.y *= -1;
  523. this.z *= -1;
  524. return this;
  525. },
  526. lengthSq: function () {
  527. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  528. },
  529. length: function () {
  530. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  531. },
  532. normalize: function () {
  533. var l = this.length();
  534. if ( l === 0 ) {
  535. this.x = 0;
  536. this.y = 0;
  537. this.z = 0;
  538. this.w = 1;
  539. } else {
  540. l = 1 / l;
  541. this.x = this.x * l;
  542. this.y = this.y * l;
  543. this.z = this.z * l;
  544. this.w = this.w * l;
  545. }
  546. return this;
  547. },
  548. multiply: function ( q, p ) {
  549. if ( p !== undefined ) {
  550. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  551. return this.multiplyQuaternions( q, p );
  552. }
  553. return this.multiplyQuaternions( this, q );
  554. },
  555. multiplyQuaternions: function ( a, b ) {
  556. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  557. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  558. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  559. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  560. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  561. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  562. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  563. return this;
  564. },
  565. multiplyVector3: function ( vector ) {
  566. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  567. return vector.applyQuaternion( this );
  568. },
  569. slerp: function ( qb, t ) {
  570. var x = this.x, y = this.y, z = this.z, w = this.w;
  571. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  572. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  573. if ( cosHalfTheta < 0 ) {
  574. this.w = -qb.w;
  575. this.x = -qb.x;
  576. this.y = -qb.y;
  577. this.z = -qb.z;
  578. cosHalfTheta = -cosHalfTheta;
  579. } else {
  580. this.copy( qb );
  581. }
  582. if ( cosHalfTheta >= 1.0 ) {
  583. this.w = w;
  584. this.x = x;
  585. this.y = y;
  586. this.z = z;
  587. return this;
  588. }
  589. var halfTheta = Math.acos( cosHalfTheta );
  590. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  591. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  592. this.w = 0.5 * ( w + this.w );
  593. this.x = 0.5 * ( x + this.x );
  594. this.y = 0.5 * ( y + this.y );
  595. this.z = 0.5 * ( z + this.z );
  596. return this;
  597. }
  598. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  599. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  600. this.w = ( w * ratioA + this.w * ratioB );
  601. this.x = ( x * ratioA + this.x * ratioB );
  602. this.y = ( y * ratioA + this.y * ratioB );
  603. this.z = ( z * ratioA + this.z * ratioB );
  604. return this;
  605. },
  606. equals: function ( v ) {
  607. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  608. },
  609. clone: function () {
  610. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  611. }
  612. } );
  613. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  614. return qm.copy( qa ).slerp( qb, t );
  615. }
  616. /**
  617. * @author mrdoob / http://mrdoob.com/
  618. * @author philogb / http://blog.thejit.org/
  619. * @author egraether / http://egraether.com/
  620. * @author zz85 / http://www.lab4games.net/zz85/blog
  621. */
  622. THREE.Vector2 = function ( x, y ) {
  623. this.x = x || 0;
  624. this.y = y || 0;
  625. };
  626. THREE.extend( THREE.Vector2.prototype, {
  627. set: function ( x, y ) {
  628. this.x = x;
  629. this.y = y;
  630. return this;
  631. },
  632. setX: function ( x ) {
  633. this.x = x;
  634. return this;
  635. },
  636. setY: function ( y ) {
  637. this.y = y;
  638. return this;
  639. },
  640. setComponent: function ( index, value ) {
  641. switch ( index ) {
  642. case 0: this.x = value; break;
  643. case 1: this.y = value; break;
  644. default: throw new Error( "index is out of range: " + index );
  645. }
  646. },
  647. getComponent: function ( index ) {
  648. switch ( index ) {
  649. case 0: return this.x;
  650. case 1: return this.y;
  651. default: throw new Error( "index is out of range: " + index );
  652. }
  653. },
  654. copy: function ( v ) {
  655. this.x = v.x;
  656. this.y = v.y;
  657. return this;
  658. },
  659. add: function ( v, w ) {
  660. if ( w !== undefined ) {
  661. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  662. return this.addVectors( v, w );
  663. }
  664. this.x += v.x;
  665. this.y += v.y;
  666. return this;
  667. },
  668. addVectors: function ( a, b ) {
  669. this.x = a.x + b.x;
  670. this.y = a.y + b.y;
  671. return this;
  672. },
  673. addScalar: function ( s ) {
  674. this.x += s;
  675. this.y += s;
  676. return this;
  677. },
  678. sub: function ( v, w ) {
  679. if ( w !== undefined ) {
  680. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  681. return this.subVectors( v, w );
  682. }
  683. this.x -= v.x;
  684. this.y -= v.y;
  685. return this;
  686. },
  687. subVectors: function ( a, b ) {
  688. this.x = a.x - b.x;
  689. this.y = a.y - b.y;
  690. return this;
  691. },
  692. multiplyScalar: function ( s ) {
  693. this.x *= s;
  694. this.y *= s;
  695. return this;
  696. },
  697. divideScalar: function ( s ) {
  698. if ( s !== 0 ) {
  699. this.x /= s;
  700. this.y /= s;
  701. } else {
  702. this.set( 0, 0 );
  703. }
  704. return this;
  705. },
  706. min: function ( v ) {
  707. if ( this.x > v.x ) {
  708. this.x = v.x;
  709. }
  710. if ( this.y > v.y ) {
  711. this.y = v.y;
  712. }
  713. return this;
  714. },
  715. max: function ( v ) {
  716. if ( this.x < v.x ) {
  717. this.x = v.x;
  718. }
  719. if ( this.y < v.y ) {
  720. this.y = v.y;
  721. }
  722. return this;
  723. },
  724. clamp: function ( min, max ) {
  725. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  726. if ( this.x < min.x ) {
  727. this.x = min.x;
  728. } else if ( this.x > max.x ) {
  729. this.x = max.x;
  730. }
  731. if ( this.y < min.y ) {
  732. this.y = min.y;
  733. } else if ( this.y > max.y ) {
  734. this.y = max.y;
  735. }
  736. return this;
  737. },
  738. negate: function() {
  739. return this.multiplyScalar( - 1 );
  740. },
  741. dot: function ( v ) {
  742. return this.x * v.x + this.y * v.y;
  743. },
  744. lengthSq: function () {
  745. return this.x * this.x + this.y * this.y;
  746. },
  747. length: function () {
  748. return Math.sqrt( this.x * this.x + this.y * this.y );
  749. },
  750. normalize: function () {
  751. return this.divideScalar( this.length() );
  752. },
  753. distanceTo: function ( v ) {
  754. return Math.sqrt( this.distanceToSquared( v ) );
  755. },
  756. distanceToSquared: function ( v ) {
  757. var dx = this.x - v.x, dy = this.y - v.y;
  758. return dx * dx + dy * dy;
  759. },
  760. setLength: function ( l ) {
  761. var oldLength = this.length();
  762. if ( oldLength !== 0 && l !== oldLength ) {
  763. this.multiplyScalar( l / oldLength );
  764. }
  765. return this;
  766. },
  767. lerp: function ( v, alpha ) {
  768. this.x += ( v.x - this.x ) * alpha;
  769. this.y += ( v.y - this.y ) * alpha;
  770. return this;
  771. },
  772. equals: function( v ) {
  773. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  774. },
  775. toArray: function () {
  776. return [ this.x, this.y ];
  777. },
  778. clone: function () {
  779. return new THREE.Vector2( this.x, this.y );
  780. }
  781. } );
  782. /**
  783. * @author mrdoob / http://mrdoob.com/
  784. * @author *kile / http://kile.stravaganza.org/
  785. * @author philogb / http://blog.thejit.org/
  786. * @author mikael emtinger / http://gomo.se/
  787. * @author egraether / http://egraether.com/
  788. * @author WestLangley / http://github.com/WestLangley
  789. */
  790. THREE.Vector3 = function ( x, y, z ) {
  791. this.x = x || 0;
  792. this.y = y || 0;
  793. this.z = z || 0;
  794. };
  795. THREE.extend( THREE.Vector3.prototype, {
  796. set: function ( x, y, z ) {
  797. this.x = x;
  798. this.y = y;
  799. this.z = z;
  800. return this;
  801. },
  802. setX: function ( x ) {
  803. this.x = x;
  804. return this;
  805. },
  806. setY: function ( y ) {
  807. this.y = y;
  808. return this;
  809. },
  810. setZ: function ( z ) {
  811. this.z = z;
  812. return this;
  813. },
  814. setComponent: function ( index, value ) {
  815. switch ( index ) {
  816. case 0: this.x = value; break;
  817. case 1: this.y = value; break;
  818. case 2: this.z = value; break;
  819. default: throw new Error( "index is out of range: " + index );
  820. }
  821. },
  822. getComponent: function ( index ) {
  823. switch ( index ) {
  824. case 0: return this.x;
  825. case 1: return this.y;
  826. case 2: return this.z;
  827. default: throw new Error( "index is out of range: " + index );
  828. }
  829. },
  830. copy: function ( v ) {
  831. this.x = v.x;
  832. this.y = v.y;
  833. this.z = v.z;
  834. return this;
  835. },
  836. add: function ( v, w ) {
  837. if ( w !== undefined ) {
  838. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  839. return this.addVectors( v, w );
  840. }
  841. this.x += v.x;
  842. this.y += v.y;
  843. this.z += v.z;
  844. return this;
  845. },
  846. addScalar: function ( s ) {
  847. this.x += s;
  848. this.y += s;
  849. this.z += s;
  850. return this;
  851. },
  852. addVectors: function ( a, b ) {
  853. this.x = a.x + b.x;
  854. this.y = a.y + b.y;
  855. this.z = a.z + b.z;
  856. return this;
  857. },
  858. sub: function ( v, w ) {
  859. if ( w !== undefined ) {
  860. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  861. return this.subVectors( v, w );
  862. }
  863. this.x -= v.x;
  864. this.y -= v.y;
  865. this.z -= v.z;
  866. return this;
  867. },
  868. subVectors: function ( a, b ) {
  869. this.x = a.x - b.x;
  870. this.y = a.y - b.y;
  871. this.z = a.z - b.z;
  872. return this;
  873. },
  874. multiply: function ( v, w ) {
  875. if ( w !== undefined ) {
  876. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  877. return this.multiplyVectors( v, w );
  878. }
  879. this.x *= v.x;
  880. this.y *= v.y;
  881. this.z *= v.z;
  882. return this;
  883. },
  884. multiplyScalar: function ( s ) {
  885. this.x *= s;
  886. this.y *= s;
  887. this.z *= s;
  888. return this;
  889. },
  890. multiplyVectors: function ( a, b ) {
  891. this.x = a.x * b.x;
  892. this.y = a.y * b.y;
  893. this.z = a.z * b.z;
  894. return this;
  895. },
  896. applyMatrix3: function ( m ) {
  897. var x = this.x;
  898. var y = this.y;
  899. var z = this.z;
  900. var e = m.elements;
  901. this.x = e[0] * x + e[3] * y + e[6] * z;
  902. this.y = e[1] * x + e[4] * y + e[7] * z;
  903. this.z = e[2] * x + e[5] * y + e[8] * z;
  904. return this;
  905. },
  906. applyMatrix4: function ( m ) {
  907. // input: THREE.Matrix4 affine matrix
  908. var x = this.x, y = this.y, z = this.z;
  909. var e = m.elements;
  910. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  911. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  912. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  913. return this;
  914. },
  915. applyProjection: function ( m ) {
  916. // input: THREE.Matrix4 projection matrix
  917. var x = this.x, y = this.y, z = this.z;
  918. var e = m.elements;
  919. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  920. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  921. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  922. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  923. return this;
  924. },
  925. applyQuaternion: function ( q ) {
  926. var x = this.x;
  927. var y = this.y;
  928. var z = this.z;
  929. var qx = q.x;
  930. var qy = q.y;
  931. var qz = q.z;
  932. var qw = q.w;
  933. // calculate quat * vector
  934. var ix = qw * x + qy * z - qz * y;
  935. var iy = qw * y + qz * x - qx * z;
  936. var iz = qw * z + qx * y - qy * x;
  937. var iw = -qx * x - qy * y - qz * z;
  938. // calculate result * inverse quat
  939. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  940. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  941. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  942. return this;
  943. },
  944. applyEuler: function () {
  945. var q1 = new THREE.Quaternion();
  946. return function ( v, eulerOrder ) {
  947. var quaternion = q1.setFromEuler( v, eulerOrder );
  948. this.applyQuaternion( quaternion );
  949. return this;
  950. };
  951. }(),
  952. applyAxisAngle: function () {
  953. var q1 = new THREE.Quaternion();
  954. return function ( axis, angle ) {
  955. var quaternion = q1.setFromAxisAngle( axis, angle );
  956. this.applyQuaternion( quaternion );
  957. return this;
  958. };
  959. }(),
  960. transformDirection: function ( m ) {
  961. // input: THREE.Matrix4 affine matrix
  962. // vector interpreted as a direction
  963. var x = this.x, y = this.y, z = this.z;
  964. var e = m.elements;
  965. this.x = e[0] * x + e[4] * y + e[8] * z;
  966. this.y = e[1] * x + e[5] * y + e[9] * z;
  967. this.z = e[2] * x + e[6] * y + e[10] * z;
  968. this.normalize();
  969. return this;
  970. },
  971. divide: function ( v ) {
  972. this.x /= v.x;
  973. this.y /= v.y;
  974. this.z /= v.z;
  975. return this;
  976. },
  977. divideScalar: function ( s ) {
  978. if ( s !== 0 ) {
  979. this.x /= s;
  980. this.y /= s;
  981. this.z /= s;
  982. } else {
  983. this.x = 0;
  984. this.y = 0;
  985. this.z = 0;
  986. }
  987. return this;
  988. },
  989. min: function ( v ) {
  990. if ( this.x > v.x ) {
  991. this.x = v.x;
  992. }
  993. if ( this.y > v.y ) {
  994. this.y = v.y;
  995. }
  996. if ( this.z > v.z ) {
  997. this.z = v.z;
  998. }
  999. return this;
  1000. },
  1001. max: function ( v ) {
  1002. if ( this.x < v.x ) {
  1003. this.x = v.x;
  1004. }
  1005. if ( this.y < v.y ) {
  1006. this.y = v.y;
  1007. }
  1008. if ( this.z < v.z ) {
  1009. this.z = v.z;
  1010. }
  1011. return this;
  1012. },
  1013. clamp: function ( min, max ) {
  1014. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1015. if ( this.x < min.x ) {
  1016. this.x = min.x;
  1017. } else if ( this.x > max.x ) {
  1018. this.x = max.x;
  1019. }
  1020. if ( this.y < min.y ) {
  1021. this.y = min.y;
  1022. } else if ( this.y > max.y ) {
  1023. this.y = max.y;
  1024. }
  1025. if ( this.z < min.z ) {
  1026. this.z = min.z;
  1027. } else if ( this.z > max.z ) {
  1028. this.z = max.z;
  1029. }
  1030. return this;
  1031. },
  1032. negate: function () {
  1033. return this.multiplyScalar( - 1 );
  1034. },
  1035. dot: function ( v ) {
  1036. return this.x * v.x + this.y * v.y + this.z * v.z;
  1037. },
  1038. lengthSq: function () {
  1039. return this.x * this.x + this.y * this.y + this.z * this.z;
  1040. },
  1041. length: function () {
  1042. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1043. },
  1044. lengthManhattan: function () {
  1045. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1046. },
  1047. normalize: function () {
  1048. return this.divideScalar( this.length() );
  1049. },
  1050. setLength: function ( l ) {
  1051. var oldLength = this.length();
  1052. if ( oldLength !== 0 && l !== oldLength ) {
  1053. this.multiplyScalar( l / oldLength );
  1054. }
  1055. return this;
  1056. },
  1057. lerp: function ( v, alpha ) {
  1058. this.x += ( v.x - this.x ) * alpha;
  1059. this.y += ( v.y - this.y ) * alpha;
  1060. this.z += ( v.z - this.z ) * alpha;
  1061. return this;
  1062. },
  1063. cross: function ( v, w ) {
  1064. if ( w !== undefined ) {
  1065. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1066. return this.crossVectors( v, w );
  1067. }
  1068. var x = this.x, y = this.y, z = this.z;
  1069. this.x = y * v.z - z * v.y;
  1070. this.y = z * v.x - x * v.z;
  1071. this.z = x * v.y - y * v.x;
  1072. return this;
  1073. },
  1074. crossVectors: function ( a, b ) {
  1075. this.x = a.y * b.z - a.z * b.y;
  1076. this.y = a.z * b.x - a.x * b.z;
  1077. this.z = a.x * b.y - a.y * b.x;
  1078. return this;
  1079. },
  1080. projectOnVector: function () {
  1081. var v1 = new THREE.Vector3();
  1082. return function( vector ) {
  1083. v1.copy( vector ).normalize();
  1084. var d = this.dot( v1 );
  1085. return this.copy( v1 ).multiplyScalar( d );
  1086. };
  1087. }(),
  1088. projectOnPlane: function () {
  1089. var v1 = new THREE.Vector3();
  1090. return function( planeNormal ) {
  1091. v1.copy( this ).projectOnVector( planeNormal );
  1092. return this.sub( v1 );
  1093. }
  1094. }(),
  1095. reflect: function () {
  1096. var v1 = new THREE.Vector3();
  1097. return function ( vector ) {
  1098. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1099. return this.subVectors( v1, this );
  1100. }
  1101. }(),
  1102. angleTo: function ( v ) {
  1103. var theta = this.dot( v ) / ( this.length() * v.length() );
  1104. // clamp, to handle numerical problems
  1105. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1106. },
  1107. distanceTo: function ( v ) {
  1108. return Math.sqrt( this.distanceToSquared( v ) );
  1109. },
  1110. distanceToSquared: function ( v ) {
  1111. var dx = this.x - v.x;
  1112. var dy = this.y - v.y;
  1113. var dz = this.z - v.z;
  1114. return dx * dx + dy * dy + dz * dz;
  1115. },
  1116. setEulerFromRotationMatrix: function ( m, order ) {
  1117. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1118. // clamp, to handle numerical problems
  1119. function clamp( x ) {
  1120. return Math.min( Math.max( x, -1 ), 1 );
  1121. }
  1122. var te = m.elements;
  1123. var m11 = te[0], m12 = te[4], m13 = te[8];
  1124. var m21 = te[1], m22 = te[5], m23 = te[9];
  1125. var m31 = te[2], m32 = te[6], m33 = te[10];
  1126. if ( order === undefined || order === 'XYZ' ) {
  1127. this.y = Math.asin( clamp( m13 ) );
  1128. if ( Math.abs( m13 ) < 0.99999 ) {
  1129. this.x = Math.atan2( - m23, m33 );
  1130. this.z = Math.atan2( - m12, m11 );
  1131. } else {
  1132. this.x = Math.atan2( m32, m22 );
  1133. this.z = 0;
  1134. }
  1135. } else if ( order === 'YXZ' ) {
  1136. this.x = Math.asin( - clamp( m23 ) );
  1137. if ( Math.abs( m23 ) < 0.99999 ) {
  1138. this.y = Math.atan2( m13, m33 );
  1139. this.z = Math.atan2( m21, m22 );
  1140. } else {
  1141. this.y = Math.atan2( - m31, m11 );
  1142. this.z = 0;
  1143. }
  1144. } else if ( order === 'ZXY' ) {
  1145. this.x = Math.asin( clamp( m32 ) );
  1146. if ( Math.abs( m32 ) < 0.99999 ) {
  1147. this.y = Math.atan2( - m31, m33 );
  1148. this.z = Math.atan2( - m12, m22 );
  1149. } else {
  1150. this.y = 0;
  1151. this.z = Math.atan2( m21, m11 );
  1152. }
  1153. } else if ( order === 'ZYX' ) {
  1154. this.y = Math.asin( - clamp( m31 ) );
  1155. if ( Math.abs( m31 ) < 0.99999 ) {
  1156. this.x = Math.atan2( m32, m33 );
  1157. this.z = Math.atan2( m21, m11 );
  1158. } else {
  1159. this.x = 0;
  1160. this.z = Math.atan2( - m12, m22 );
  1161. }
  1162. } else if ( order === 'YZX' ) {
  1163. this.z = Math.asin( clamp( m21 ) );
  1164. if ( Math.abs( m21 ) < 0.99999 ) {
  1165. this.x = Math.atan2( - m23, m22 );
  1166. this.y = Math.atan2( - m31, m11 );
  1167. } else {
  1168. this.x = 0;
  1169. this.y = Math.atan2( m13, m33 );
  1170. }
  1171. } else if ( order === 'XZY' ) {
  1172. this.z = Math.asin( - clamp( m12 ) );
  1173. if ( Math.abs( m12 ) < 0.99999 ) {
  1174. this.x = Math.atan2( m32, m22 );
  1175. this.y = Math.atan2( m13, m11 );
  1176. } else {
  1177. this.x = Math.atan2( - m23, m33 );
  1178. this.y = 0;
  1179. }
  1180. }
  1181. return this;
  1182. },
  1183. setEulerFromQuaternion: function ( q, order ) {
  1184. // q is assumed to be normalized
  1185. // clamp, to handle numerical problems
  1186. function clamp( x ) {
  1187. return Math.min( Math.max( x, -1 ), 1 );
  1188. }
  1189. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1190. var sqx = q.x * q.x;
  1191. var sqy = q.y * q.y;
  1192. var sqz = q.z * q.z;
  1193. var sqw = q.w * q.w;
  1194. if ( order === undefined || order === 'XYZ' ) {
  1195. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1196. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1197. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1198. } else if ( order === 'YXZ' ) {
  1199. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1200. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1201. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1202. } else if ( order === 'ZXY' ) {
  1203. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1204. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1205. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1206. } else if ( order === 'ZYX' ) {
  1207. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1208. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1209. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1210. } else if ( order === 'YZX' ) {
  1211. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1212. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1213. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1214. } else if ( order === 'XZY' ) {
  1215. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1216. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1217. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1218. }
  1219. return this;
  1220. },
  1221. getPositionFromMatrix: function ( m ) {
  1222. this.x = m.elements[12];
  1223. this.y = m.elements[13];
  1224. this.z = m.elements[14];
  1225. return this;
  1226. },
  1227. getScaleFromMatrix: function ( m ) {
  1228. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1229. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1230. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1231. this.x = sx;
  1232. this.y = sy;
  1233. this.z = sz;
  1234. return this;
  1235. },
  1236. getColumnFromMatrix: function ( index, matrix ) {
  1237. var offset = index * 4;
  1238. var me = matrix.elements;
  1239. this.x = me[ offset ];
  1240. this.y = me[ offset + 1 ];
  1241. this.z = me[ offset + 2 ];
  1242. return this;
  1243. },
  1244. equals: function ( v ) {
  1245. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1246. },
  1247. toArray: function () {
  1248. return [ this.x, this.y, this.z ];
  1249. },
  1250. clone: function () {
  1251. return new THREE.Vector3( this.x, this.y, this.z );
  1252. }
  1253. } );
  1254. /**
  1255. * @author supereggbert / http://www.paulbrunt.co.uk/
  1256. * @author philogb / http://blog.thejit.org/
  1257. * @author mikael emtinger / http://gomo.se/
  1258. * @author egraether / http://egraether.com/
  1259. * @author WestLangley / http://github.com/WestLangley
  1260. */
  1261. THREE.Vector4 = function ( x, y, z, w ) {
  1262. this.x = x || 0;
  1263. this.y = y || 0;
  1264. this.z = z || 0;
  1265. this.w = ( w !== undefined ) ? w : 1;
  1266. };
  1267. THREE.extend( THREE.Vector4.prototype, {
  1268. set: function ( x, y, z, w ) {
  1269. this.x = x;
  1270. this.y = y;
  1271. this.z = z;
  1272. this.w = w;
  1273. return this;
  1274. },
  1275. setX: function ( x ) {
  1276. this.x = x;
  1277. return this;
  1278. },
  1279. setY: function ( y ) {
  1280. this.y = y;
  1281. return this;
  1282. },
  1283. setZ: function ( z ) {
  1284. this.z = z;
  1285. return this;
  1286. },
  1287. setW: function ( w ) {
  1288. this.w = w;
  1289. return this;
  1290. },
  1291. setComponent: function ( index, value ) {
  1292. switch ( index ) {
  1293. case 0: this.x = value; break;
  1294. case 1: this.y = value; break;
  1295. case 2: this.z = value; break;
  1296. case 3: this.w = value; break;
  1297. default: throw new Error( "index is out of range: " + index );
  1298. }
  1299. },
  1300. getComponent: function ( index ) {
  1301. switch ( index ) {
  1302. case 0: return this.x;
  1303. case 1: return this.y;
  1304. case 2: return this.z;
  1305. case 3: return this.w;
  1306. default: throw new Error( "index is out of range: " + index );
  1307. }
  1308. },
  1309. copy: function ( v ) {
  1310. this.x = v.x;
  1311. this.y = v.y;
  1312. this.z = v.z;
  1313. this.w = ( v.w !== undefined ) ? v.w : 1;
  1314. return this;
  1315. },
  1316. add: function ( v, w ) {
  1317. if ( w !== undefined ) {
  1318. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1319. return this.addVectors( v, w );
  1320. }
  1321. this.x += v.x;
  1322. this.y += v.y;
  1323. this.z += v.z;
  1324. this.w += v.w;
  1325. return this;
  1326. },
  1327. addScalar: function ( s ) {
  1328. this.x += s;
  1329. this.y += s;
  1330. this.z += s;
  1331. this.w += s;
  1332. return this;
  1333. },
  1334. addVectors: function ( a, b ) {
  1335. this.x = a.x + b.x;
  1336. this.y = a.y + b.y;
  1337. this.z = a.z + b.z;
  1338. this.w = a.w + b.w;
  1339. return this;
  1340. },
  1341. sub: function ( v, w ) {
  1342. if ( w !== undefined ) {
  1343. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1344. return this.subVectors( v, w );
  1345. }
  1346. this.x -= v.x;
  1347. this.y -= v.y;
  1348. this.z -= v.z;
  1349. this.w -= v.w;
  1350. return this;
  1351. },
  1352. subVectors: function ( a, b ) {
  1353. this.x = a.x - b.x;
  1354. this.y = a.y - b.y;
  1355. this.z = a.z - b.z;
  1356. this.w = a.w - b.w;
  1357. return this;
  1358. },
  1359. multiplyScalar: function ( s ) {
  1360. this.x *= s;
  1361. this.y *= s;
  1362. this.z *= s;
  1363. this.w *= s;
  1364. return this;
  1365. },
  1366. applyMatrix4: function ( m ) {
  1367. var x = this.x;
  1368. var y = this.y;
  1369. var z = this.z;
  1370. var w = this.w;
  1371. var e = m.elements;
  1372. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1373. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1374. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1375. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1376. return this;
  1377. },
  1378. divideScalar: function ( s ) {
  1379. if ( s !== 0 ) {
  1380. this.x /= s;
  1381. this.y /= s;
  1382. this.z /= s;
  1383. this.w /= s;
  1384. } else {
  1385. this.x = 0;
  1386. this.y = 0;
  1387. this.z = 0;
  1388. this.w = 1;
  1389. }
  1390. return this;
  1391. },
  1392. setAxisAngleFromQuaternion: function ( q ) {
  1393. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1394. // q is assumed to be normalized
  1395. this.w = 2 * Math.acos( q.w );
  1396. var s = Math.sqrt( 1 - q.w * q.w );
  1397. if ( s < 0.0001 ) {
  1398. this.x = 1;
  1399. this.y = 0;
  1400. this.z = 0;
  1401. } else {
  1402. this.x = q.x / s;
  1403. this.y = q.y / s;
  1404. this.z = q.z / s;
  1405. }
  1406. return this;
  1407. },
  1408. setAxisAngleFromRotationMatrix: function ( m ) {
  1409. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1410. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1411. var angle, x, y, z, // variables for result
  1412. epsilon = 0.01, // margin to allow for rounding errors
  1413. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1414. te = m.elements,
  1415. m11 = te[0], m12 = te[4], m13 = te[8],
  1416. m21 = te[1], m22 = te[5], m23 = te[9],
  1417. m31 = te[2], m32 = te[6], m33 = te[10];
  1418. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1419. && ( Math.abs( m13 - m31 ) < epsilon )
  1420. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1421. // singularity found
  1422. // first check for identity matrix which must have +1 for all terms
  1423. // in leading diagonal and zero in other terms
  1424. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1425. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1426. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1427. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1428. // this singularity is identity matrix so angle = 0
  1429. this.set( 1, 0, 0, 0 );
  1430. return this; // zero angle, arbitrary axis
  1431. }
  1432. // otherwise this singularity is angle = 180
  1433. angle = Math.PI;
  1434. var xx = ( m11 + 1 ) / 2;
  1435. var yy = ( m22 + 1 ) / 2;
  1436. var zz = ( m33 + 1 ) / 2;
  1437. var xy = ( m12 + m21 ) / 4;
  1438. var xz = ( m13 + m31 ) / 4;
  1439. var yz = ( m23 + m32 ) / 4;
  1440. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1441. if ( xx < epsilon ) {
  1442. x = 0;
  1443. y = 0.707106781;
  1444. z = 0.707106781;
  1445. } else {
  1446. x = Math.sqrt( xx );
  1447. y = xy / x;
  1448. z = xz / x;
  1449. }
  1450. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1451. if ( yy < epsilon ) {
  1452. x = 0.707106781;
  1453. y = 0;
  1454. z = 0.707106781;
  1455. } else {
  1456. y = Math.sqrt( yy );
  1457. x = xy / y;
  1458. z = yz / y;
  1459. }
  1460. } else { // m33 is the largest diagonal term so base result on this
  1461. if ( zz < epsilon ) {
  1462. x = 0.707106781;
  1463. y = 0.707106781;
  1464. z = 0;
  1465. } else {
  1466. z = Math.sqrt( zz );
  1467. x = xz / z;
  1468. y = yz / z;
  1469. }
  1470. }
  1471. this.set( x, y, z, angle );
  1472. return this; // return 180 deg rotation
  1473. }
  1474. // as we have reached here there are no singularities so we can handle normally
  1475. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1476. + ( m13 - m31 ) * ( m13 - m31 )
  1477. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1478. if ( Math.abs( s ) < 0.001 ) s = 1;
  1479. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1480. // caught by singularity test above, but I've left it in just in case
  1481. this.x = ( m32 - m23 ) / s;
  1482. this.y = ( m13 - m31 ) / s;
  1483. this.z = ( m21 - m12 ) / s;
  1484. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1485. return this;
  1486. },
  1487. min: function ( v ) {
  1488. if ( this.x > v.x ) {
  1489. this.x = v.x;
  1490. }
  1491. if ( this.y > v.y ) {
  1492. this.y = v.y;
  1493. }
  1494. if ( this.z > v.z ) {
  1495. this.z = v.z;
  1496. }
  1497. if ( this.w > v.w ) {
  1498. this.w = v.w;
  1499. }
  1500. return this;
  1501. },
  1502. max: function ( v ) {
  1503. if ( this.x < v.x ) {
  1504. this.x = v.x;
  1505. }
  1506. if ( this.y < v.y ) {
  1507. this.y = v.y;
  1508. }
  1509. if ( this.z < v.z ) {
  1510. this.z = v.z;
  1511. }
  1512. if ( this.w < v.w ) {
  1513. this.w = v.w;
  1514. }
  1515. return this;
  1516. },
  1517. clamp: function ( min, max ) {
  1518. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1519. if ( this.x < min.x ) {
  1520. this.x = min.x;
  1521. } else if ( this.x > max.x ) {
  1522. this.x = max.x;
  1523. }
  1524. if ( this.y < min.y ) {
  1525. this.y = min.y;
  1526. } else if ( this.y > max.y ) {
  1527. this.y = max.y;
  1528. }
  1529. if ( this.z < min.z ) {
  1530. this.z = min.z;
  1531. } else if ( this.z > max.z ) {
  1532. this.z = max.z;
  1533. }
  1534. if ( this.w < min.w ) {
  1535. this.w = min.w;
  1536. } else if ( this.w > max.w ) {
  1537. this.w = max.w;
  1538. }
  1539. return this;
  1540. },
  1541. negate: function() {
  1542. return this.multiplyScalar( -1 );
  1543. },
  1544. dot: function ( v ) {
  1545. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1546. },
  1547. lengthSq: function () {
  1548. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1549. },
  1550. length: function () {
  1551. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1552. },
  1553. lengthManhattan: function () {
  1554. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1555. },
  1556. normalize: function () {
  1557. return this.divideScalar( this.length() );
  1558. },
  1559. setLength: function ( l ) {
  1560. var oldLength = this.length();
  1561. if ( oldLength !== 0 && l !== oldLength ) {
  1562. this.multiplyScalar( l / oldLength );
  1563. }
  1564. return this;
  1565. },
  1566. lerp: function ( v, alpha ) {
  1567. this.x += ( v.x - this.x ) * alpha;
  1568. this.y += ( v.y - this.y ) * alpha;
  1569. this.z += ( v.z - this.z ) * alpha;
  1570. this.w += ( v.w - this.w ) * alpha;
  1571. return this;
  1572. },
  1573. equals: function ( v ) {
  1574. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1575. },
  1576. toArray: function () {
  1577. return [ this.x, this.y, this.z, this.w ];
  1578. },
  1579. clone: function () {
  1580. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1581. }
  1582. } );
  1583. /**
  1584. * @author bhouston / http://exocortex.com
  1585. */
  1586. THREE.Box2 = function ( min, max ) {
  1587. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1588. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1589. };
  1590. THREE.extend( THREE.Box2.prototype, {
  1591. set: function ( min, max ) {
  1592. this.min.copy( min );
  1593. this.max.copy( max );
  1594. return this;
  1595. },
  1596. setFromPoints: function ( points ) {
  1597. if ( points.length > 0 ) {
  1598. var point = points[ 0 ];
  1599. this.min.copy( point );
  1600. this.max.copy( point );
  1601. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1602. point = points[ i ];
  1603. if ( point.x < this.min.x ) {
  1604. this.min.x = point.x;
  1605. } else if ( point.x > this.max.x ) {
  1606. this.max.x = point.x;
  1607. }
  1608. if ( point.y < this.min.y ) {
  1609. this.min.y = point.y;
  1610. } else if ( point.y > this.max.y ) {
  1611. this.max.y = point.y;
  1612. }
  1613. }
  1614. } else {
  1615. this.makeEmpty();
  1616. }
  1617. return this;
  1618. },
  1619. setFromCenterAndSize: function() {
  1620. var v1 = new THREE.Vector2();
  1621. return function ( center, size ) {
  1622. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1623. this.min.copy( center ).sub( halfSize );
  1624. this.max.copy( center ).add( halfSize );
  1625. return this;
  1626. };
  1627. }(),
  1628. copy: function ( box ) {
  1629. this.min.copy( box.min );
  1630. this.max.copy( box.max );
  1631. return this;
  1632. },
  1633. makeEmpty: function () {
  1634. this.min.x = this.min.y = Infinity;
  1635. this.max.x = this.max.y = -Infinity;
  1636. return this;
  1637. },
  1638. empty: function () {
  1639. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1640. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1641. },
  1642. center: function ( optionalTarget ) {
  1643. var result = optionalTarget || new THREE.Vector2();
  1644. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1645. },
  1646. size: function ( optionalTarget ) {
  1647. var result = optionalTarget || new THREE.Vector2();
  1648. return result.subVectors( this.max, this.min );
  1649. },
  1650. expandByPoint: function ( point ) {
  1651. this.min.min( point );
  1652. this.max.max( point );
  1653. return this;
  1654. },
  1655. expandByVector: function ( vector ) {
  1656. this.min.sub( vector );
  1657. this.max.add( vector );
  1658. return this;
  1659. },
  1660. expandByScalar: function ( scalar ) {
  1661. this.min.addScalar( -scalar );
  1662. this.max.addScalar( scalar );
  1663. return this;
  1664. },
  1665. containsPoint: function ( point ) {
  1666. if ( point.x < this.min.x || point.x > this.max.x ||
  1667. point.y < this.min.y || point.y > this.max.y ) {
  1668. return false;
  1669. }
  1670. return true;
  1671. },
  1672. containsBox: function ( box ) {
  1673. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1674. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1675. return true;
  1676. }
  1677. return false;
  1678. },
  1679. getParameter: function ( point ) {
  1680. // This can potentially have a divide by zero if the box
  1681. // has a size dimension of 0.
  1682. return new THREE.Vector2(
  1683. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1684. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1685. );
  1686. },
  1687. isIntersectionBox: function ( box ) {
  1688. // using 6 splitting planes to rule out intersections.
  1689. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1690. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1691. return false;
  1692. }
  1693. return true;
  1694. },
  1695. clampPoint: function ( point, optionalTarget ) {
  1696. var result = optionalTarget || new THREE.Vector2();
  1697. return result.copy( point ).clamp( this.min, this.max );
  1698. },
  1699. distanceToPoint: function() {
  1700. var v1 = new THREE.Vector2();
  1701. return function ( point ) {
  1702. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1703. return clampedPoint.sub( point ).length();
  1704. };
  1705. }(),
  1706. intersect: function ( box ) {
  1707. this.min.max( box.min );
  1708. this.max.min( box.max );
  1709. return this;
  1710. },
  1711. union: function ( box ) {
  1712. this.min.min( box.min );
  1713. this.max.max( box.max );
  1714. return this;
  1715. },
  1716. translate: function ( offset ) {
  1717. this.min.add( offset );
  1718. this.max.add( offset );
  1719. return this;
  1720. },
  1721. equals: function ( box ) {
  1722. return box.min.equals( this.min ) && box.max.equals( this.max );
  1723. },
  1724. clone: function () {
  1725. return new THREE.Box2().copy( this );
  1726. }
  1727. } );
  1728. /**
  1729. * @author bhouston / http://exocortex.com
  1730. */
  1731. THREE.Box3 = function ( min, max ) {
  1732. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1733. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1734. };
  1735. THREE.extend( THREE.Box3.prototype, {
  1736. set: function ( min, max ) {
  1737. this.min.copy( min );
  1738. this.max.copy( max );
  1739. return this;
  1740. },
  1741. setFromPoints: function ( points ) {
  1742. if ( points.length > 0 ) {
  1743. var point = points[ 0 ];
  1744. this.min.copy( point );
  1745. this.max.copy( point );
  1746. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1747. point = points[ i ];
  1748. if ( point.x < this.min.x ) {
  1749. this.min.x = point.x;
  1750. } else if ( point.x > this.max.x ) {
  1751. this.max.x = point.x;
  1752. }
  1753. if ( point.y < this.min.y ) {
  1754. this.min.y = point.y;
  1755. } else if ( point.y > this.max.y ) {
  1756. this.max.y = point.y;
  1757. }
  1758. if ( point.z < this.min.z ) {
  1759. this.min.z = point.z;
  1760. } else if ( point.z > this.max.z ) {
  1761. this.max.z = point.z;
  1762. }
  1763. }
  1764. } else {
  1765. this.makeEmpty();
  1766. }
  1767. return this;
  1768. },
  1769. setFromCenterAndSize: function() {
  1770. var v1 = new THREE.Vector3();
  1771. return function ( center, size ) {
  1772. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1773. this.min.copy( center ).sub( halfSize );
  1774. this.max.copy( center ).add( halfSize );
  1775. return this;
  1776. };
  1777. }(),
  1778. copy: function ( box ) {
  1779. this.min.copy( box.min );
  1780. this.max.copy( box.max );
  1781. return this;
  1782. },
  1783. makeEmpty: function () {
  1784. this.min.x = this.min.y = this.min.z = Infinity;
  1785. this.max.x = this.max.y = this.max.z = -Infinity;
  1786. return this;
  1787. },
  1788. empty: function () {
  1789. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1790. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1791. },
  1792. center: function ( optionalTarget ) {
  1793. var result = optionalTarget || new THREE.Vector3();
  1794. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1795. },
  1796. size: function ( optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector3();
  1798. return result.subVectors( this.max, this.min );
  1799. },
  1800. expandByPoint: function ( point ) {
  1801. this.min.min( point );
  1802. this.max.max( point );
  1803. return this;
  1804. },
  1805. expandByVector: function ( vector ) {
  1806. this.min.sub( vector );
  1807. this.max.add( vector );
  1808. return this;
  1809. },
  1810. expandByScalar: function ( scalar ) {
  1811. this.min.addScalar( -scalar );
  1812. this.max.addScalar( scalar );
  1813. return this;
  1814. },
  1815. containsPoint: function ( point ) {
  1816. if ( point.x < this.min.x || point.x > this.max.x ||
  1817. point.y < this.min.y || point.y > this.max.y ||
  1818. point.z < this.min.z || point.z > this.max.z ) {
  1819. return false;
  1820. }
  1821. return true;
  1822. },
  1823. containsBox: function ( box ) {
  1824. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1825. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1826. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1827. return true;
  1828. }
  1829. return false;
  1830. },
  1831. getParameter: function ( point ) {
  1832. // This can potentially have a divide by zero if the box
  1833. // has a size dimension of 0.
  1834. return new THREE.Vector3(
  1835. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1836. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1837. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1838. );
  1839. },
  1840. isIntersectionBox: function ( box ) {
  1841. // using 6 splitting planes to rule out intersections.
  1842. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1843. box.max.y < this.min.y || box.min.y > this.max.y ||
  1844. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1845. return false;
  1846. }
  1847. return true;
  1848. },
  1849. clampPoint: function ( point, optionalTarget ) {
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return result.copy( point ).clamp( this.min, this.max );
  1852. },
  1853. distanceToPoint: function() {
  1854. var v1 = new THREE.Vector3();
  1855. return function ( point ) {
  1856. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1857. return clampedPoint.sub( point ).length();
  1858. };
  1859. }(),
  1860. getBoundingSphere: function() {
  1861. var v1 = new THREE.Vector3();
  1862. return function ( optionalTarget ) {
  1863. var result = optionalTarget || new THREE.Sphere();
  1864. result.center = this.center();
  1865. result.radius = this.size( v1 ).length() * 0.5;
  1866. return result;
  1867. };
  1868. }(),
  1869. intersect: function ( box ) {
  1870. this.min.max( box.min );
  1871. this.max.min( box.max );
  1872. return this;
  1873. },
  1874. union: function ( box ) {
  1875. this.min.min( box.min );
  1876. this.max.max( box.max );
  1877. return this;
  1878. },
  1879. applyMatrix4: function() {
  1880. var points = [
  1881. new THREE.Vector3(),
  1882. new THREE.Vector3(),
  1883. new THREE.Vector3(),
  1884. new THREE.Vector3(),
  1885. new THREE.Vector3(),
  1886. new THREE.Vector3(),
  1887. new THREE.Vector3(),
  1888. new THREE.Vector3()
  1889. ];
  1890. return function ( matrix ) {
  1891. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1892. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1893. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1894. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1895. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1896. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1897. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1898. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1899. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1900. this.makeEmpty();
  1901. this.setFromPoints( points );
  1902. return this;
  1903. };
  1904. }(),
  1905. translate: function ( offset ) {
  1906. this.min.add( offset );
  1907. this.max.add( offset );
  1908. return this;
  1909. },
  1910. equals: function ( box ) {
  1911. return box.min.equals( this.min ) && box.max.equals( this.max );
  1912. },
  1913. clone: function () {
  1914. return new THREE.Box3().copy( this );
  1915. }
  1916. } );
  1917. /**
  1918. * @author alteredq / http://alteredqualia.com/
  1919. * @author WestLangley / http://github.com/WestLangley
  1920. * @author bhouston / http://exocortex.com
  1921. */
  1922. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1923. this.elements = new Float32Array(9);
  1924. this.set(
  1925. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1926. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1927. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1928. );
  1929. };
  1930. THREE.extend( THREE.Matrix3.prototype, {
  1931. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1932. var te = this.elements;
  1933. te[0] = n11; te[3] = n12; te[6] = n13;
  1934. te[1] = n21; te[4] = n22; te[7] = n23;
  1935. te[2] = n31; te[5] = n32; te[8] = n33;
  1936. return this;
  1937. },
  1938. identity: function () {
  1939. this.set(
  1940. 1, 0, 0,
  1941. 0, 1, 0,
  1942. 0, 0, 1
  1943. );
  1944. return this;
  1945. },
  1946. copy: function ( m ) {
  1947. var me = m.elements;
  1948. this.set(
  1949. me[0], me[3], me[6],
  1950. me[1], me[4], me[7],
  1951. me[2], me[5], me[8]
  1952. );
  1953. return this;
  1954. },
  1955. multiplyVector3: function ( vector ) {
  1956. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  1957. return vector.applyMatrix3( this );
  1958. },
  1959. multiplyVector3Array: function() {
  1960. var v1 = new THREE.Vector3();
  1961. return function ( a ) {
  1962. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1963. v1.x = a[ i ];
  1964. v1.y = a[ i + 1 ];
  1965. v1.z = a[ i + 2 ];
  1966. v1.applyMatrix3(this);
  1967. a[ i ] = v1.x;
  1968. a[ i + 1 ] = v1.y;
  1969. a[ i + 2 ] = v1.z;
  1970. }
  1971. return a;
  1972. };
  1973. }(),
  1974. multiplyScalar: function ( s ) {
  1975. var te = this.elements;
  1976. te[0] *= s; te[3] *= s; te[6] *= s;
  1977. te[1] *= s; te[4] *= s; te[7] *= s;
  1978. te[2] *= s; te[5] *= s; te[8] *= s;
  1979. return this;
  1980. },
  1981. determinant: function () {
  1982. var te = this.elements;
  1983. var a = te[0], b = te[1], c = te[2],
  1984. d = te[3], e = te[4], f = te[5],
  1985. g = te[6], h = te[7], i = te[8];
  1986. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1987. },
  1988. getInverse: function ( matrix, throwOnInvertible ) {
  1989. // input: THREE.Matrix4
  1990. // ( based on http://code.google.com/p/webgl-mjs/ )
  1991. var me = matrix.elements;
  1992. var te = this.elements;
  1993. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1994. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1995. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1996. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1997. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1998. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1999. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2000. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2001. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2002. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2003. // no inverse
  2004. if ( det === 0 ) {
  2005. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2006. if ( throwOnInvertible || false ) {
  2007. throw new Error( msg );
  2008. } else {
  2009. console.warn( msg );
  2010. }
  2011. this.identity();
  2012. return this;
  2013. }
  2014. this.multiplyScalar( 1.0 / det );
  2015. return this;
  2016. },
  2017. transpose: function () {
  2018. var tmp, m = this.elements;
  2019. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2020. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2021. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2022. return this;
  2023. },
  2024. getNormalMatrix: function ( m ) {
  2025. // input: THREE.Matrix4
  2026. this.getInverse( m ).transpose();
  2027. return this;
  2028. },
  2029. transposeIntoArray: function ( r ) {
  2030. var m = this.elements;
  2031. r[ 0 ] = m[ 0 ];
  2032. r[ 1 ] = m[ 3 ];
  2033. r[ 2 ] = m[ 6 ];
  2034. r[ 3 ] = m[ 1 ];
  2035. r[ 4 ] = m[ 4 ];
  2036. r[ 5 ] = m[ 7 ];
  2037. r[ 6 ] = m[ 2 ];
  2038. r[ 7 ] = m[ 5 ];
  2039. r[ 8 ] = m[ 8 ];
  2040. return this;
  2041. },
  2042. clone: function () {
  2043. var te = this.elements;
  2044. return new THREE.Matrix3(
  2045. te[0], te[3], te[6],
  2046. te[1], te[4], te[7],
  2047. te[2], te[5], te[8]
  2048. );
  2049. }
  2050. } );
  2051. /**
  2052. * @author mrdoob / http://mrdoob.com/
  2053. * @author supereggbert / http://www.paulbrunt.co.uk/
  2054. * @author philogb / http://blog.thejit.org/
  2055. * @author jordi_ros / http://plattsoft.com
  2056. * @author D1plo1d / http://github.com/D1plo1d
  2057. * @author alteredq / http://alteredqualia.com/
  2058. * @author mikael emtinger / http://gomo.se/
  2059. * @author timknip / http://www.floorplanner.com/
  2060. * @author bhouston / http://exocortex.com
  2061. * @author WestLangley / http://github.com/WestLangley
  2062. */
  2063. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2064. var te = this.elements = new Float32Array( 16 );
  2065. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2066. // we should not support semi specification of Matrix4, it is just weird.
  2067. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2068. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2069. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2070. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2071. };
  2072. THREE.extend( THREE.Matrix4.prototype, {
  2073. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2074. var te = this.elements;
  2075. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2076. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2077. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2078. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2079. return this;
  2080. },
  2081. identity: function () {
  2082. this.set(
  2083. 1, 0, 0, 0,
  2084. 0, 1, 0, 0,
  2085. 0, 0, 1, 0,
  2086. 0, 0, 0, 1
  2087. );
  2088. return this;
  2089. },
  2090. copy: function ( m ) {
  2091. var me = m.elements;
  2092. this.set(
  2093. me[0], me[4], me[8], me[12],
  2094. me[1], me[5], me[9], me[13],
  2095. me[2], me[6], me[10], me[14],
  2096. me[3], me[7], me[11], me[15]
  2097. );
  2098. return this;
  2099. },
  2100. setRotationFromEuler: function ( v, order ) {
  2101. var te = this.elements;
  2102. var x = v.x, y = v.y, z = v.z;
  2103. var a = Math.cos( x ), b = Math.sin( x );
  2104. var c = Math.cos( y ), d = Math.sin( y );
  2105. var e = Math.cos( z ), f = Math.sin( z );
  2106. if ( order === undefined || order === 'XYZ' ) {
  2107. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2108. te[0] = c * e;
  2109. te[4] = - c * f;
  2110. te[8] = d;
  2111. te[1] = af + be * d;
  2112. te[5] = ae - bf * d;
  2113. te[9] = - b * c;
  2114. te[2] = bf - ae * d;
  2115. te[6] = be + af * d;
  2116. te[10] = a * c;
  2117. } else if ( order === 'YXZ' ) {
  2118. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2119. te[0] = ce + df * b;
  2120. te[4] = de * b - cf;
  2121. te[8] = a * d;
  2122. te[1] = a * f;
  2123. te[5] = a * e;
  2124. te[9] = - b;
  2125. te[2] = cf * b - de;
  2126. te[6] = df + ce * b;
  2127. te[10] = a * c;
  2128. } else if ( order === 'ZXY' ) {
  2129. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2130. te[0] = ce - df * b;
  2131. te[4] = - a * f;
  2132. te[8] = de + cf * b;
  2133. te[1] = cf + de * b;
  2134. te[5] = a * e;
  2135. te[9] = df - ce * b;
  2136. te[2] = - a * d;
  2137. te[6] = b;
  2138. te[10] = a * c;
  2139. } else if ( order === 'ZYX' ) {
  2140. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2141. te[0] = c * e;
  2142. te[4] = be * d - af;
  2143. te[8] = ae * d + bf;
  2144. te[1] = c * f;
  2145. te[5] = bf * d + ae;
  2146. te[9] = af * d - be;
  2147. te[2] = - d;
  2148. te[6] = b * c;
  2149. te[10] = a * c;
  2150. } else if ( order === 'YZX' ) {
  2151. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2152. te[0] = c * e;
  2153. te[4] = bd - ac * f;
  2154. te[8] = bc * f + ad;
  2155. te[1] = f;
  2156. te[5] = a * e;
  2157. te[9] = - b * e;
  2158. te[2] = - d * e;
  2159. te[6] = ad * f + bc;
  2160. te[10] = ac - bd * f;
  2161. } else if ( order === 'XZY' ) {
  2162. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2163. te[0] = c * e;
  2164. te[4] = - f;
  2165. te[8] = d * e;
  2166. te[1] = ac * f + bd;
  2167. te[5] = a * e;
  2168. te[9] = ad * f - bc;
  2169. te[2] = bc * f - ad;
  2170. te[6] = b * e;
  2171. te[10] = bd * f + ac;
  2172. }
  2173. return this;
  2174. },
  2175. setRotationFromQuaternion: function ( q ) {
  2176. var te = this.elements;
  2177. var x = q.x, y = q.y, z = q.z, w = q.w;
  2178. var x2 = x + x, y2 = y + y, z2 = z + z;
  2179. var xx = x * x2, xy = x * y2, xz = x * z2;
  2180. var yy = y * y2, yz = y * z2, zz = z * z2;
  2181. var wx = w * x2, wy = w * y2, wz = w * z2;
  2182. te[0] = 1 - ( yy + zz );
  2183. te[4] = xy - wz;
  2184. te[8] = xz + wy;
  2185. te[1] = xy + wz;
  2186. te[5] = 1 - ( xx + zz );
  2187. te[9] = yz - wx;
  2188. te[2] = xz - wy;
  2189. te[6] = yz + wx;
  2190. te[10] = 1 - ( xx + yy );
  2191. return this;
  2192. },
  2193. lookAt: function() {
  2194. var x = new THREE.Vector3();
  2195. var y = new THREE.Vector3();
  2196. var z = new THREE.Vector3();
  2197. return function ( eye, target, up ) {
  2198. var te = this.elements;
  2199. z.subVectors( eye, target ).normalize();
  2200. if ( z.length() === 0 ) {
  2201. z.z = 1;
  2202. }
  2203. x.crossVectors( up, z ).normalize();
  2204. if ( x.length() === 0 ) {
  2205. z.x += 0.0001;
  2206. x.crossVectors( up, z ).normalize();
  2207. }
  2208. y.crossVectors( z, x );
  2209. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2210. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2211. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2212. return this;
  2213. };
  2214. }(),
  2215. multiply: function ( m, n ) {
  2216. if ( n !== undefined ) {
  2217. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2218. return this.multiplyMatrices( m, n );
  2219. }
  2220. return this.multiplyMatrices( this, m );
  2221. },
  2222. multiplyMatrices: function ( a, b ) {
  2223. var ae = a.elements;
  2224. var be = b.elements;
  2225. var te = this.elements;
  2226. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2227. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2228. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2229. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2230. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2231. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2232. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2233. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2234. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2235. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2236. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2237. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2238. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2239. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2240. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2241. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2242. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2243. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2244. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2245. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2246. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2247. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2248. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2249. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2250. return this;
  2251. },
  2252. multiplyToArray: function ( a, b, r ) {
  2253. var te = this.elements;
  2254. this.multiplyMatrices( a, b );
  2255. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2256. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2257. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2258. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2259. return this;
  2260. },
  2261. multiplyScalar: function ( s ) {
  2262. var te = this.elements;
  2263. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2264. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2265. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2266. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2267. return this;
  2268. },
  2269. multiplyVector3: function ( vector ) {
  2270. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2271. return vector.applyProjection( this );
  2272. },
  2273. multiplyVector4: function ( vector ) {
  2274. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2275. return vector.applyMatrix4( this );
  2276. },
  2277. multiplyVector3Array: function() {
  2278. var v1 = new THREE.Vector3();
  2279. return function ( a ) {
  2280. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2281. v1.x = a[ i ];
  2282. v1.y = a[ i + 1 ];
  2283. v1.z = a[ i + 2 ];
  2284. v1.applyProjection( this );
  2285. a[ i ] = v1.x;
  2286. a[ i + 1 ] = v1.y;
  2287. a[ i + 2 ] = v1.z;
  2288. }
  2289. return a;
  2290. };
  2291. }(),
  2292. rotateAxis: function ( v ) {
  2293. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2294. v.transformDirection( this );
  2295. },
  2296. crossVector: function ( a ) {
  2297. var te = this.elements;
  2298. var v = new THREE.Vector4();
  2299. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2300. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2301. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2302. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2303. return v;
  2304. },
  2305. determinant: function () {
  2306. var te = this.elements;
  2307. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2308. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2309. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2310. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2311. //TODO: make this more efficient
  2312. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2313. return (
  2314. n41 * (
  2315. +n14 * n23 * n32
  2316. -n13 * n24 * n32
  2317. -n14 * n22 * n33
  2318. +n12 * n24 * n33
  2319. +n13 * n22 * n34
  2320. -n12 * n23 * n34
  2321. ) +
  2322. n42 * (
  2323. +n11 * n23 * n34
  2324. -n11 * n24 * n33
  2325. +n14 * n21 * n33
  2326. -n13 * n21 * n34
  2327. +n13 * n24 * n31
  2328. -n14 * n23 * n31
  2329. ) +
  2330. n43 * (
  2331. +n11 * n24 * n32
  2332. -n11 * n22 * n34
  2333. -n14 * n21 * n32
  2334. +n12 * n21 * n34
  2335. +n14 * n22 * n31
  2336. -n12 * n24 * n31
  2337. ) +
  2338. n44 * (
  2339. -n13 * n22 * n31
  2340. -n11 * n23 * n32
  2341. +n11 * n22 * n33
  2342. +n13 * n21 * n32
  2343. -n12 * n21 * n33
  2344. +n12 * n23 * n31
  2345. )
  2346. );
  2347. },
  2348. transpose: function () {
  2349. var te = this.elements;
  2350. var tmp;
  2351. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2352. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2353. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2354. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2355. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2356. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2357. return this;
  2358. },
  2359. flattenToArray: function ( flat ) {
  2360. var te = this.elements;
  2361. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2362. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2363. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2364. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2365. return flat;
  2366. },
  2367. flattenToArrayOffset: function( flat, offset ) {
  2368. var te = this.elements;
  2369. flat[ offset ] = te[0];
  2370. flat[ offset + 1 ] = te[1];
  2371. flat[ offset + 2 ] = te[2];
  2372. flat[ offset + 3 ] = te[3];
  2373. flat[ offset + 4 ] = te[4];
  2374. flat[ offset + 5 ] = te[5];
  2375. flat[ offset + 6 ] = te[6];
  2376. flat[ offset + 7 ] = te[7];
  2377. flat[ offset + 8 ] = te[8];
  2378. flat[ offset + 9 ] = te[9];
  2379. flat[ offset + 10 ] = te[10];
  2380. flat[ offset + 11 ] = te[11];
  2381. flat[ offset + 12 ] = te[12];
  2382. flat[ offset + 13 ] = te[13];
  2383. flat[ offset + 14 ] = te[14];
  2384. flat[ offset + 15 ] = te[15];
  2385. return flat;
  2386. },
  2387. getPosition: function() {
  2388. var v1 = new THREE.Vector3();
  2389. return function () {
  2390. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2391. var te = this.elements;
  2392. return v1.set( te[12], te[13], te[14] );
  2393. };
  2394. }(),
  2395. setPosition: function ( v ) {
  2396. var te = this.elements;
  2397. te[12] = v.x;
  2398. te[13] = v.y;
  2399. te[14] = v.z;
  2400. return this;
  2401. },
  2402. getInverse: function ( m, throwOnInvertible ) {
  2403. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2404. var te = this.elements;
  2405. var me = m.elements;
  2406. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2407. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2408. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2409. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2410. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2411. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2412. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2413. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2414. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2415. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2416. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2417. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2418. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2419. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2420. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2421. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2422. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2423. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2424. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2425. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2426. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2427. if ( det == 0 ) {
  2428. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2429. if ( throwOnInvertible || false ) {
  2430. throw new Error( msg );
  2431. } else {
  2432. console.warn( msg );
  2433. }
  2434. this.identity();
  2435. return this;
  2436. }
  2437. this.multiplyScalar( 1 / det );
  2438. return this;
  2439. },
  2440. compose: function() {
  2441. var mRotation = new THREE.Matrix4();
  2442. var mScale = new THREE.Matrix4();
  2443. return function ( position, quaternion, scale ) {
  2444. var te = this.elements;
  2445. mRotation.identity();
  2446. mRotation.setRotationFromQuaternion( quaternion );
  2447. mScale.makeScale( scale.x, scale.y, scale.z );
  2448. this.multiplyMatrices( mRotation, mScale );
  2449. te[12] = position.x;
  2450. te[13] = position.y;
  2451. te[14] = position.z;
  2452. return this;
  2453. };
  2454. }(),
  2455. decompose: function() {
  2456. var x = new THREE.Vector3(),
  2457. y = new THREE.Vector3(),
  2458. z = new THREE.Vector3(),
  2459. matrix = new THREE.Matrix4();
  2460. return function ( position, quaternion, scale ) {
  2461. var te = this.elements;
  2462. // grab the axis vectors
  2463. x.set( te[0], te[1], te[2] );
  2464. y.set( te[4], te[5], te[6] );
  2465. z.set( te[8], te[9], te[10] );
  2466. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2467. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2468. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2469. scale.x = x.length();
  2470. scale.y = y.length();
  2471. scale.z = z.length();
  2472. position.x = te[12];
  2473. position.y = te[13];
  2474. position.z = te[14];
  2475. // scale the rotation part
  2476. matrix.copy( this );
  2477. matrix.elements[0] /= scale.x;
  2478. matrix.elements[1] /= scale.x;
  2479. matrix.elements[2] /= scale.x;
  2480. matrix.elements[4] /= scale.y;
  2481. matrix.elements[5] /= scale.y;
  2482. matrix.elements[6] /= scale.y;
  2483. matrix.elements[8] /= scale.z;
  2484. matrix.elements[9] /= scale.z;
  2485. matrix.elements[10] /= scale.z;
  2486. quaternion.setFromRotationMatrix( matrix );
  2487. return [ position, quaternion, scale ];
  2488. };
  2489. }(),
  2490. extractPosition: function ( m ) {
  2491. var te = this.elements;
  2492. var me = m.elements;
  2493. te[12] = me[12];
  2494. te[13] = me[13];
  2495. te[14] = me[14];
  2496. return this;
  2497. },
  2498. extractRotation: function() {
  2499. var v1 = new THREE.Vector3();
  2500. return function ( m ) {
  2501. var te = this.elements;
  2502. var me = m.elements;
  2503. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2504. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2505. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2506. te[0] = me[0] * scaleX;
  2507. te[1] = me[1] * scaleX;
  2508. te[2] = me[2] * scaleX;
  2509. te[4] = me[4] * scaleY;
  2510. te[5] = me[5] * scaleY;
  2511. te[6] = me[6] * scaleY;
  2512. te[8] = me[8] * scaleZ;
  2513. te[9] = me[9] * scaleZ;
  2514. te[10] = me[10] * scaleZ;
  2515. return this;
  2516. };
  2517. }(),
  2518. translate: function ( v ) {
  2519. var te = this.elements;
  2520. var x = v.x, y = v.y, z = v.z;
  2521. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2522. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2523. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2524. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2525. return this;
  2526. },
  2527. rotateX: function ( angle ) {
  2528. var te = this.elements;
  2529. var m12 = te[4];
  2530. var m22 = te[5];
  2531. var m32 = te[6];
  2532. var m42 = te[7];
  2533. var m13 = te[8];
  2534. var m23 = te[9];
  2535. var m33 = te[10];
  2536. var m43 = te[11];
  2537. var c = Math.cos( angle );
  2538. var s = Math.sin( angle );
  2539. te[4] = c * m12 + s * m13;
  2540. te[5] = c * m22 + s * m23;
  2541. te[6] = c * m32 + s * m33;
  2542. te[7] = c * m42 + s * m43;
  2543. te[8] = c * m13 - s * m12;
  2544. te[9] = c * m23 - s * m22;
  2545. te[10] = c * m33 - s * m32;
  2546. te[11] = c * m43 - s * m42;
  2547. return this;
  2548. },
  2549. rotateY: function ( angle ) {
  2550. var te = this.elements;
  2551. var m11 = te[0];
  2552. var m21 = te[1];
  2553. var m31 = te[2];
  2554. var m41 = te[3];
  2555. var m13 = te[8];
  2556. var m23 = te[9];
  2557. var m33 = te[10];
  2558. var m43 = te[11];
  2559. var c = Math.cos( angle );
  2560. var s = Math.sin( angle );
  2561. te[0] = c * m11 - s * m13;
  2562. te[1] = c * m21 - s * m23;
  2563. te[2] = c * m31 - s * m33;
  2564. te[3] = c * m41 - s * m43;
  2565. te[8] = c * m13 + s * m11;
  2566. te[9] = c * m23 + s * m21;
  2567. te[10] = c * m33 + s * m31;
  2568. te[11] = c * m43 + s * m41;
  2569. return this;
  2570. },
  2571. rotateZ: function ( angle ) {
  2572. var te = this.elements;
  2573. var m11 = te[0];
  2574. var m21 = te[1];
  2575. var m31 = te[2];
  2576. var m41 = te[3];
  2577. var m12 = te[4];
  2578. var m22 = te[5];
  2579. var m32 = te[6];
  2580. var m42 = te[7];
  2581. var c = Math.cos( angle );
  2582. var s = Math.sin( angle );
  2583. te[0] = c * m11 + s * m12;
  2584. te[1] = c * m21 + s * m22;
  2585. te[2] = c * m31 + s * m32;
  2586. te[3] = c * m41 + s * m42;
  2587. te[4] = c * m12 - s * m11;
  2588. te[5] = c * m22 - s * m21;
  2589. te[6] = c * m32 - s * m31;
  2590. te[7] = c * m42 - s * m41;
  2591. return this;
  2592. },
  2593. rotateByAxis: function ( axis, angle ) {
  2594. var te = this.elements;
  2595. // optimize by checking axis
  2596. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2597. return this.rotateX( angle );
  2598. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2599. return this.rotateY( angle );
  2600. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2601. return this.rotateZ( angle );
  2602. }
  2603. var x = axis.x, y = axis.y, z = axis.z;
  2604. var n = Math.sqrt(x * x + y * y + z * z);
  2605. x /= n;
  2606. y /= n;
  2607. z /= n;
  2608. var xx = x * x, yy = y * y, zz = z * z;
  2609. var c = Math.cos( angle );
  2610. var s = Math.sin( angle );
  2611. var oneMinusCosine = 1 - c;
  2612. var xy = x * y * oneMinusCosine;
  2613. var xz = x * z * oneMinusCosine;
  2614. var yz = y * z * oneMinusCosine;
  2615. var xs = x * s;
  2616. var ys = y * s;
  2617. var zs = z * s;
  2618. var r11 = xx + (1 - xx) * c;
  2619. var r21 = xy + zs;
  2620. var r31 = xz - ys;
  2621. var r12 = xy - zs;
  2622. var r22 = yy + (1 - yy) * c;
  2623. var r32 = yz + xs;
  2624. var r13 = xz + ys;
  2625. var r23 = yz - xs;
  2626. var r33 = zz + (1 - zz) * c;
  2627. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2628. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2629. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2630. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2631. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2632. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2633. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2634. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2635. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2636. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2637. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2638. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2639. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2640. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2641. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2642. return this;
  2643. },
  2644. scale: function ( v ) {
  2645. var te = this.elements;
  2646. var x = v.x, y = v.y, z = v.z;
  2647. te[0] *= x; te[4] *= y; te[8] *= z;
  2648. te[1] *= x; te[5] *= y; te[9] *= z;
  2649. te[2] *= x; te[6] *= y; te[10] *= z;
  2650. te[3] *= x; te[7] *= y; te[11] *= z;
  2651. return this;
  2652. },
  2653. getMaxScaleOnAxis: function () {
  2654. var te = this.elements;
  2655. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2656. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2657. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2658. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2659. },
  2660. makeTranslation: function ( x, y, z ) {
  2661. this.set(
  2662. 1, 0, 0, x,
  2663. 0, 1, 0, y,
  2664. 0, 0, 1, z,
  2665. 0, 0, 0, 1
  2666. );
  2667. return this;
  2668. },
  2669. makeRotationX: function ( theta ) {
  2670. var c = Math.cos( theta ), s = Math.sin( theta );
  2671. this.set(
  2672. 1, 0, 0, 0,
  2673. 0, c, -s, 0,
  2674. 0, s, c, 0,
  2675. 0, 0, 0, 1
  2676. );
  2677. return this;
  2678. },
  2679. makeRotationY: function ( theta ) {
  2680. var c = Math.cos( theta ), s = Math.sin( theta );
  2681. this.set(
  2682. c, 0, s, 0,
  2683. 0, 1, 0, 0,
  2684. -s, 0, c, 0,
  2685. 0, 0, 0, 1
  2686. );
  2687. return this;
  2688. },
  2689. makeRotationZ: function ( theta ) {
  2690. var c = Math.cos( theta ), s = Math.sin( theta );
  2691. this.set(
  2692. c, -s, 0, 0,
  2693. s, c, 0, 0,
  2694. 0, 0, 1, 0,
  2695. 0, 0, 0, 1
  2696. );
  2697. return this;
  2698. },
  2699. makeRotationAxis: function ( axis, angle ) {
  2700. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2701. var c = Math.cos( angle );
  2702. var s = Math.sin( angle );
  2703. var t = 1 - c;
  2704. var x = axis.x, y = axis.y, z = axis.z;
  2705. var tx = t * x, ty = t * y;
  2706. this.set(
  2707. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2708. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2709. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2710. 0, 0, 0, 1
  2711. );
  2712. return this;
  2713. },
  2714. makeScale: function ( x, y, z ) {
  2715. this.set(
  2716. x, 0, 0, 0,
  2717. 0, y, 0, 0,
  2718. 0, 0, z, 0,
  2719. 0, 0, 0, 1
  2720. );
  2721. return this;
  2722. },
  2723. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2724. var te = this.elements;
  2725. var x = 2 * near / ( right - left );
  2726. var y = 2 * near / ( top - bottom );
  2727. var a = ( right + left ) / ( right - left );
  2728. var b = ( top + bottom ) / ( top - bottom );
  2729. var c = - ( far + near ) / ( far - near );
  2730. var d = - 2 * far * near / ( far - near );
  2731. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2732. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2733. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2734. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2735. return this;
  2736. },
  2737. makePerspective: function ( fov, aspect, near, far ) {
  2738. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2739. var ymin = - ymax;
  2740. var xmin = ymin * aspect;
  2741. var xmax = ymax * aspect;
  2742. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2743. },
  2744. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2745. var te = this.elements;
  2746. var w = right - left;
  2747. var h = top - bottom;
  2748. var p = far - near;
  2749. var x = ( right + left ) / w;
  2750. var y = ( top + bottom ) / h;
  2751. var z = ( far + near ) / p;
  2752. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2753. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2754. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2755. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2756. return this;
  2757. },
  2758. clone: function () {
  2759. var te = this.elements;
  2760. return new THREE.Matrix4(
  2761. te[0], te[4], te[8], te[12],
  2762. te[1], te[5], te[9], te[13],
  2763. te[2], te[6], te[10], te[14],
  2764. te[3], te[7], te[11], te[15]
  2765. );
  2766. }
  2767. } );
  2768. /**
  2769. * @author bhouston / http://exocortex.com
  2770. */
  2771. THREE.Ray = function ( origin, direction ) {
  2772. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2773. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2774. };
  2775. THREE.extend( THREE.Ray.prototype, {
  2776. set: function ( origin, direction ) {
  2777. this.origin.copy( origin );
  2778. this.direction.copy( direction );
  2779. return this;
  2780. },
  2781. copy: function ( ray ) {
  2782. this.origin.copy( ray.origin );
  2783. this.direction.copy( ray.direction );
  2784. return this;
  2785. },
  2786. at: function( t, optionalTarget ) {
  2787. var result = optionalTarget || new THREE.Vector3();
  2788. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2789. },
  2790. recast: function() {
  2791. var v1 = new THREE.Vector3();
  2792. return function ( t ) {
  2793. this.origin.copy( this.at( t, v1 ) );
  2794. return this;
  2795. };
  2796. }(),
  2797. closestPointToPoint: function ( point, optionalTarget ) {
  2798. var result = optionalTarget || new THREE.Vector3();
  2799. result.subVectors( point, this.origin );
  2800. var directionDistance = result.dot( this.direction );
  2801. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2802. },
  2803. distanceToPoint: function() {
  2804. var v1 = new THREE.Vector3();
  2805. return function ( point ) {
  2806. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2807. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2808. return v1.distanceTo( point );
  2809. };
  2810. }(),
  2811. isIntersectionSphere: function( sphere ) {
  2812. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2813. },
  2814. isIntersectionPlane: function ( plane ) {
  2815. // check if the line and plane are non-perpendicular, if they
  2816. // eventually they will intersect.
  2817. var denominator = plane.normal.dot( this.direction );
  2818. if ( denominator != 0 ) {
  2819. return true;
  2820. }
  2821. // line is coplanar, return origin
  2822. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2823. return true;
  2824. }
  2825. return false;
  2826. },
  2827. distanceToPlane: function ( plane ) {
  2828. var denominator = plane.normal.dot( this.direction );
  2829. if ( denominator == 0 ) {
  2830. // line is coplanar, return origin
  2831. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2832. return 0;
  2833. }
  2834. // Unsure if this is the correct method to handle this case.
  2835. return undefined;
  2836. }
  2837. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2838. return t;
  2839. },
  2840. intersectPlane: function ( plane, optionalTarget ) {
  2841. var t = this.distanceToPlane( plane );
  2842. if ( t === undefined ) {
  2843. return undefined;
  2844. }
  2845. return this.at( t, optionalTarget );
  2846. },
  2847. applyMatrix4: function ( matrix4 ) {
  2848. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2849. this.origin.applyMatrix4( matrix4 );
  2850. this.direction.sub( this.origin );
  2851. return this;
  2852. },
  2853. equals: function ( ray ) {
  2854. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2855. },
  2856. clone: function () {
  2857. return new THREE.Ray().copy( this );
  2858. }
  2859. } );
  2860. /**
  2861. * @author bhouston / http://exocortex.com
  2862. * @author mrdoob / http://mrdoob.com/
  2863. */
  2864. THREE.Sphere = function ( center, radius ) {
  2865. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2866. this.radius = ( radius !== undefined ) ? radius : 0;
  2867. };
  2868. THREE.extend( THREE.Sphere.prototype, {
  2869. set: function ( center, radius ) {
  2870. this.center.copy( center );
  2871. this.radius = radius;
  2872. return this;
  2873. },
  2874. setFromCenterAndPoints: function ( center, points ) {
  2875. var maxRadiusSq = 0;
  2876. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2877. var radiusSq = center.distanceToSquared( points[ i ] );
  2878. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2879. }
  2880. this.center = center;
  2881. this.radius = Math.sqrt( maxRadiusSq );
  2882. return this;
  2883. },
  2884. copy: function ( sphere ) {
  2885. this.center.copy( sphere.center );
  2886. this.radius = sphere.radius;
  2887. return this;
  2888. },
  2889. empty: function () {
  2890. return ( this.radius <= 0 );
  2891. },
  2892. containsPoint: function ( point ) {
  2893. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2894. },
  2895. distanceToPoint: function ( point ) {
  2896. return ( point.distanceTo( this.center ) - this.radius );
  2897. },
  2898. intersectsSphere: function ( sphere ) {
  2899. var radiusSum = this.radius + sphere.radius;
  2900. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2901. },
  2902. clampPoint: function ( point, optionalTarget ) {
  2903. var deltaLengthSq = this.center.distanceToSquared( point );
  2904. var result = optionalTarget || new THREE.Vector3();
  2905. result.copy( point );
  2906. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2907. result.sub( this.center ).normalize();
  2908. result.multiplyScalar( this.radius ).add( this.center );
  2909. }
  2910. return result;
  2911. },
  2912. getBoundingBox: function ( optionalTarget ) {
  2913. var box = optionalTarget || new THREE.Box3();
  2914. box.set( this.center, this.center );
  2915. box.expandByScalar( this.radius );
  2916. return box;
  2917. },
  2918. applyMatrix4: function ( matrix ) {
  2919. this.center.applyMatrix4( matrix );
  2920. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2921. return this;
  2922. },
  2923. translate: function ( offset ) {
  2924. this.center.add( offset );
  2925. return this;
  2926. },
  2927. equals: function ( sphere ) {
  2928. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2929. },
  2930. clone: function () {
  2931. return new THREE.Sphere().copy( this );
  2932. }
  2933. } );
  2934. /**
  2935. * @author mrdoob / http://mrdoob.com/
  2936. * @author alteredq / http://alteredqualia.com/
  2937. * @author bhouston / http://exocortex.com
  2938. */
  2939. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2940. this.planes = [
  2941. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2942. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2943. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2944. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2945. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2946. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2947. ];
  2948. };
  2949. THREE.extend( THREE.Frustum.prototype, {
  2950. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2951. var planes = this.planes;
  2952. planes[0].copy( p0 );
  2953. planes[1].copy( p1 );
  2954. planes[2].copy( p2 );
  2955. planes[3].copy( p3 );
  2956. planes[4].copy( p4 );
  2957. planes[5].copy( p5 );
  2958. return this;
  2959. },
  2960. copy: function ( frustum ) {
  2961. var planes = this.planes;
  2962. for( var i = 0; i < 6; i ++ ) {
  2963. planes[i].copy( frustum.planes[i] );
  2964. }
  2965. return this;
  2966. },
  2967. setFromMatrix: function ( m ) {
  2968. var planes = this.planes;
  2969. var me = m.elements;
  2970. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2971. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2972. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2973. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2974. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2975. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2976. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2977. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2978. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2979. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2980. return this;
  2981. },
  2982. intersectsObject: function () {
  2983. var center = new THREE.Vector3();
  2984. return function ( object ) {
  2985. // this method is expanded inlined for performance reasons.
  2986. var matrix = object.matrixWorld;
  2987. var planes = this.planes;
  2988. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2989. center.getPositionFromMatrix( matrix );
  2990. for ( var i = 0; i < 6; i ++ ) {
  2991. var distance = planes[ i ].distanceToPoint( center );
  2992. if ( distance < negRadius ) {
  2993. return false;
  2994. }
  2995. }
  2996. return true;
  2997. };
  2998. }(),
  2999. intersectsSphere: function ( sphere ) {
  3000. var planes = this.planes;
  3001. var center = sphere.center;
  3002. var negRadius = -sphere.radius;
  3003. for ( var i = 0; i < 6; i ++ ) {
  3004. var distance = planes[ i ].distanceToPoint( center );
  3005. if ( distance < negRadius ) {
  3006. return false;
  3007. }
  3008. }
  3009. return true;
  3010. },
  3011. containsPoint: function ( point ) {
  3012. var planes = this.planes;
  3013. for ( var i = 0; i < 6; i ++ ) {
  3014. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3015. return false;
  3016. }
  3017. }
  3018. return true;
  3019. },
  3020. clone: function () {
  3021. return new THREE.Frustum().copy( this );
  3022. }
  3023. } );
  3024. /**
  3025. * @author bhouston / http://exocortex.com
  3026. */
  3027. THREE.Plane = function ( normal, constant ) {
  3028. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3029. this.constant = ( constant !== undefined ) ? constant : 0;
  3030. };
  3031. THREE.extend( THREE.Plane.prototype, {
  3032. set: function ( normal, constant ) {
  3033. this.normal.copy( normal );
  3034. this.constant = constant;
  3035. return this;
  3036. },
  3037. setComponents: function ( x, y, z, w ) {
  3038. this.normal.set( x, y, z );
  3039. this.constant = w;
  3040. return this;
  3041. },
  3042. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3043. this.normal.copy( normal );
  3044. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3045. return this;
  3046. },
  3047. setFromCoplanarPoints: function() {
  3048. var v1 = new THREE.Vector3();
  3049. var v2 = new THREE.Vector3();
  3050. return function ( a, b, c ) {
  3051. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3052. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3053. this.setFromNormalAndCoplanarPoint( normal, a );
  3054. return this;
  3055. };
  3056. }(),
  3057. copy: function ( plane ) {
  3058. this.normal.copy( plane.normal );
  3059. this.constant = plane.constant;
  3060. return this;
  3061. },
  3062. normalize: function () {
  3063. // Note: will lead to a divide by zero if the plane is invalid.
  3064. var inverseNormalLength = 1.0 / this.normal.length();
  3065. this.normal.multiplyScalar( inverseNormalLength );
  3066. this.constant *= inverseNormalLength;
  3067. return this;
  3068. },
  3069. negate: function () {
  3070. this.constant *= -1;
  3071. this.normal.negate();
  3072. return this;
  3073. },
  3074. distanceToPoint: function ( point ) {
  3075. return this.normal.dot( point ) + this.constant;
  3076. },
  3077. distanceToSphere: function ( sphere ) {
  3078. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3079. },
  3080. projectPoint: function ( point, optionalTarget ) {
  3081. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3082. },
  3083. orthoPoint: function ( point, optionalTarget ) {
  3084. var perpendicularMagnitude = this.distanceToPoint( point );
  3085. var result = optionalTarget || new THREE.Vector3();
  3086. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3087. },
  3088. isIntersectionLine: function ( line ) {
  3089. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3090. var startSign = this.distanceToPoint( line.start );
  3091. var endSign = this.distanceToPoint( line.end );
  3092. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3093. },
  3094. intersectLine: function() {
  3095. var v1 = new THREE.Vector3();
  3096. return function ( line, optionalTarget ) {
  3097. var result = optionalTarget || new THREE.Vector3();
  3098. var direction = line.delta( v1 );
  3099. var denominator = this.normal.dot( direction );
  3100. if ( denominator == 0 ) {
  3101. // line is coplanar, return origin
  3102. if( this.distanceToPoint( line.start ) == 0 ) {
  3103. return result.copy( line.start );
  3104. }
  3105. // Unsure if this is the correct method to handle this case.
  3106. return undefined;
  3107. }
  3108. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3109. if( t < 0 || t > 1 ) {
  3110. return undefined;
  3111. }
  3112. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3113. };
  3114. }(),
  3115. coplanarPoint: function ( optionalTarget ) {
  3116. var result = optionalTarget || new THREE.Vector3();
  3117. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3118. },
  3119. applyMatrix4: function() {
  3120. var v1 = new THREE.Vector3();
  3121. var v2 = new THREE.Vector3();
  3122. return function ( matrix, optionalNormalMatrix ) {
  3123. // compute new normal based on theory here:
  3124. // http://www.songho.ca/opengl/gl_normaltransform.html
  3125. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3126. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3127. var newCoplanarPoint = this.coplanarPoint( v2 );
  3128. newCoplanarPoint.applyMatrix4( matrix );
  3129. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3130. return this;
  3131. };
  3132. }(),
  3133. translate: function ( offset ) {
  3134. this.constant = this.constant - offset.dot( this.normal );
  3135. return this;
  3136. },
  3137. equals: function ( plane ) {
  3138. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3139. },
  3140. clone: function () {
  3141. return new THREE.Plane().copy( this );
  3142. }
  3143. } );
  3144. /**
  3145. * @author alteredq / http://alteredqualia.com/
  3146. */
  3147. THREE.Math = {
  3148. // Clamp value to range <a, b>
  3149. clamp: function ( x, a, b ) {
  3150. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3151. },
  3152. // Clamp value to range <a, inf)
  3153. clampBottom: function ( x, a ) {
  3154. return x < a ? a : x;
  3155. },
  3156. // Linear mapping from range <a1, a2> to range <b1, b2>
  3157. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3158. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3159. },
  3160. // http://en.wikipedia.org/wiki/Smoothstep
  3161. smoothstep: function ( x, min, max ) {
  3162. if ( x <= min ) return 0;
  3163. if ( x >= max ) return 1;
  3164. x = ( x - min )/( max - min );
  3165. return x*x*(3 - 2*x);
  3166. },
  3167. smootherstep: function ( x, min, max ) {
  3168. if ( x <= min ) return 0;
  3169. if ( x >= max ) return 1;
  3170. x = ( x - min )/( max - min );
  3171. return x*x*x*(x*(x*6 - 15) + 10);
  3172. },
  3173. // Random float from <0, 1> with 16 bits of randomness
  3174. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3175. random16: function () {
  3176. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3177. },
  3178. // Random integer from <low, high> interval
  3179. randInt: function ( low, high ) {
  3180. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3181. },
  3182. // Random float from <low, high> interval
  3183. randFloat: function ( low, high ) {
  3184. return low + Math.random() * ( high - low );
  3185. },
  3186. // Random float from <-range/2, range/2> interval
  3187. randFloatSpread: function ( range ) {
  3188. return range * ( 0.5 - Math.random() );
  3189. },
  3190. sign: function ( x ) {
  3191. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3192. },
  3193. degToRad: function() {
  3194. var degreeToRadiansFactor = Math.PI / 180;
  3195. return function ( degrees ) {
  3196. return degrees * degreeToRadiansFactor;
  3197. };
  3198. }(),
  3199. radToDeg: function() {
  3200. var radianToDegreesFactor = 180 / Math.PI;
  3201. return function ( radians ) {
  3202. return radians * radianToDegreesFactor;
  3203. };
  3204. }()
  3205. };
  3206. /**
  3207. * Spline from Tween.js, slightly optimized (and trashed)
  3208. * http://sole.github.com/tween.js/examples/05_spline.html
  3209. *
  3210. * @author mrdoob / http://mrdoob.com/
  3211. * @author alteredq / http://alteredqualia.com/
  3212. */
  3213. THREE.Spline = function ( points ) {
  3214. this.points = points;
  3215. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3216. point, intPoint, weight, w2, w3,
  3217. pa, pb, pc, pd;
  3218. this.initFromArray = function( a ) {
  3219. this.points = [];
  3220. for ( var i = 0; i < a.length; i++ ) {
  3221. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3222. }
  3223. };
  3224. this.getPoint = function ( k ) {
  3225. point = ( this.points.length - 1 ) * k;
  3226. intPoint = Math.floor( point );
  3227. weight = point - intPoint;
  3228. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3229. c[ 1 ] = intPoint;
  3230. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3231. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3232. pa = this.points[ c[ 0 ] ];
  3233. pb = this.points[ c[ 1 ] ];
  3234. pc = this.points[ c[ 2 ] ];
  3235. pd = this.points[ c[ 3 ] ];
  3236. w2 = weight * weight;
  3237. w3 = weight * w2;
  3238. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3239. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3240. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3241. return v3;
  3242. };
  3243. this.getControlPointsArray = function () {
  3244. var i, p, l = this.points.length,
  3245. coords = [];
  3246. for ( i = 0; i < l; i ++ ) {
  3247. p = this.points[ i ];
  3248. coords[ i ] = [ p.x, p.y, p.z ];
  3249. }
  3250. return coords;
  3251. };
  3252. // approximate length by summing linear segments
  3253. this.getLength = function ( nSubDivisions ) {
  3254. var i, index, nSamples, position,
  3255. point = 0, intPoint = 0, oldIntPoint = 0,
  3256. oldPosition = new THREE.Vector3(),
  3257. tmpVec = new THREE.Vector3(),
  3258. chunkLengths = [],
  3259. totalLength = 0;
  3260. // first point has 0 length
  3261. chunkLengths[ 0 ] = 0;
  3262. if ( !nSubDivisions ) nSubDivisions = 100;
  3263. nSamples = this.points.length * nSubDivisions;
  3264. oldPosition.copy( this.points[ 0 ] );
  3265. for ( i = 1; i < nSamples; i ++ ) {
  3266. index = i / nSamples;
  3267. position = this.getPoint( index );
  3268. tmpVec.copy( position );
  3269. totalLength += tmpVec.distanceTo( oldPosition );
  3270. oldPosition.copy( position );
  3271. point = ( this.points.length - 1 ) * index;
  3272. intPoint = Math.floor( point );
  3273. if ( intPoint != oldIntPoint ) {
  3274. chunkLengths[ intPoint ] = totalLength;
  3275. oldIntPoint = intPoint;
  3276. }
  3277. }
  3278. // last point ends with total length
  3279. chunkLengths[ chunkLengths.length ] = totalLength;
  3280. return { chunks: chunkLengths, total: totalLength };
  3281. };
  3282. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3283. var i, j,
  3284. index, indexCurrent, indexNext,
  3285. linearDistance, realDistance,
  3286. sampling, position,
  3287. newpoints = [],
  3288. tmpVec = new THREE.Vector3(),
  3289. sl = this.getLength();
  3290. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3291. for ( i = 1; i < this.points.length; i++ ) {
  3292. //tmpVec.copy( this.points[ i - 1 ] );
  3293. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3294. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3295. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3296. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3297. indexNext = i / ( this.points.length - 1 );
  3298. for ( j = 1; j < sampling - 1; j++ ) {
  3299. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3300. position = this.getPoint( index );
  3301. newpoints.push( tmpVec.copy( position ).clone() );
  3302. }
  3303. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3304. }
  3305. this.points = newpoints;
  3306. };
  3307. // Catmull-Rom
  3308. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3309. var v0 = ( p2 - p0 ) * 0.5,
  3310. v1 = ( p3 - p1 ) * 0.5;
  3311. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3312. };
  3313. };
  3314. /**
  3315. * @author bhouston / http://exocortex.com
  3316. * @author mrdoob / http://mrdoob.com/
  3317. */
  3318. THREE.Triangle = function ( a, b, c ) {
  3319. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3320. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3321. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3322. };
  3323. THREE.Triangle.normal = function() {
  3324. var v0 = new THREE.Vector3();
  3325. return function( a, b, c, optionalTarget ) {
  3326. var result = optionalTarget || new THREE.Vector3();
  3327. result.subVectors( c, b );
  3328. v0.subVectors( a, b );
  3329. result.cross( v0 );
  3330. var resultLengthSq = result.lengthSq();
  3331. if( resultLengthSq > 0 ) {
  3332. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3333. }
  3334. return result.set( 0, 0, 0 );
  3335. };
  3336. }();
  3337. // static/instance method to calculate barycoordinates
  3338. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3339. THREE.Triangle.barycoordFromPoint = function() {
  3340. var v0 = new THREE.Vector3(),
  3341. v1 = new THREE.Vector3(),
  3342. v2 = new THREE.Vector3();
  3343. return function ( point, a, b, c, optionalTarget ) {
  3344. v0.subVectors( c, a );
  3345. v1.subVectors( b, a );
  3346. v2.subVectors( point, a );
  3347. var dot00 = v0.dot( v0 );
  3348. var dot01 = v0.dot( v1 );
  3349. var dot02 = v0.dot( v2 );
  3350. var dot11 = v1.dot( v1 );
  3351. var dot12 = v1.dot( v2 );
  3352. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3353. var result = optionalTarget || new THREE.Vector3();
  3354. // colinear or singular triangle
  3355. if( denom == 0 ) {
  3356. // arbitrary location outside of triangle?
  3357. // not sure if this is the best idea, maybe should be returning undefined
  3358. return result.set( -2, -1, -1 );
  3359. }
  3360. var invDenom = 1 / denom;
  3361. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3362. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3363. // barycoordinates must always sum to 1
  3364. return result.set( 1 - u - v, v, u );
  3365. };
  3366. }();
  3367. THREE.Triangle.containsPoint = function() {
  3368. var v1 = new THREE.Vector3();
  3369. return function ( point, a, b, c ) {
  3370. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3371. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3372. };
  3373. }();
  3374. THREE.extend( THREE.Triangle.prototype, {
  3375. constructor: THREE.Triangle,
  3376. set: function ( a, b, c ) {
  3377. this.a.copy( a );
  3378. this.b.copy( b );
  3379. this.c.copy( c );
  3380. return this;
  3381. },
  3382. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3383. this.a.copy( points[i0] );
  3384. this.b.copy( points[i1] );
  3385. this.c.copy( points[i2] );
  3386. return this;
  3387. },
  3388. copy: function ( triangle ) {
  3389. this.a.copy( triangle.a );
  3390. this.b.copy( triangle.b );
  3391. this.c.copy( triangle.c );
  3392. return this;
  3393. },
  3394. area: function() {
  3395. var v0 = new THREE.Vector3();
  3396. var v1 = new THREE.Vector3();
  3397. return function () {
  3398. v0.subVectors( this.c, this.b );
  3399. v1.subVectors( this.a, this.b );
  3400. return v0.cross( v1 ).length() * 0.5;
  3401. };
  3402. }(),
  3403. midpoint: function ( optionalTarget ) {
  3404. var result = optionalTarget || new THREE.Vector3();
  3405. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3406. },
  3407. normal: function ( optionalTarget ) {
  3408. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3409. },
  3410. plane: function ( optionalTarget ) {
  3411. var result = optionalTarget || new THREE.Plane();
  3412. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3413. },
  3414. barycoordFromPoint: function ( point, optionalTarget ) {
  3415. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3416. },
  3417. containsPoint: function ( point ) {
  3418. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3419. },
  3420. equals: function ( triangle ) {
  3421. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3422. },
  3423. clone: function () {
  3424. return new THREE.Triangle().copy( this );
  3425. }
  3426. } );
  3427. /**
  3428. * @author mrdoob / http://mrdoob.com/
  3429. */
  3430. THREE.Vertex = function ( v ) {
  3431. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3432. return v;
  3433. };
  3434. /**
  3435. * @author mrdoob / http://mrdoob.com/
  3436. */
  3437. THREE.UV = function ( u, v ) {
  3438. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3439. return new THREE.Vector2( u, v );
  3440. };
  3441. /**
  3442. * @author alteredq / http://alteredqualia.com/
  3443. */
  3444. THREE.Clock = function ( autoStart ) {
  3445. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3446. this.startTime = 0;
  3447. this.oldTime = 0;
  3448. this.elapsedTime = 0;
  3449. this.running = false;
  3450. };
  3451. THREE.extend( THREE.Clock.prototype, {
  3452. start: function () {
  3453. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3454. ? window.performance.now()
  3455. : Date.now();
  3456. this.oldTime = this.startTime;
  3457. this.running = true;
  3458. },
  3459. stop: function () {
  3460. this.getElapsedTime();
  3461. this.running = false;
  3462. },
  3463. getElapsedTime: function () {
  3464. this.getDelta();
  3465. return this.elapsedTime;
  3466. },
  3467. getDelta: function () {
  3468. var diff = 0;
  3469. if ( this.autoStart && ! this.running ) {
  3470. this.start();
  3471. }
  3472. if ( this.running ) {
  3473. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3474. ? window.performance.now()
  3475. : Date.now();
  3476. diff = 0.001 * ( newTime - this.oldTime );
  3477. this.oldTime = newTime;
  3478. this.elapsedTime += diff;
  3479. }
  3480. return diff;
  3481. }
  3482. } );
  3483. /**
  3484. * https://github.com/mrdoob/eventdispatcher.js/
  3485. */
  3486. THREE.EventDispatcher = function () {
  3487. var listeners = {};
  3488. this.addEventListener = function ( type, listener ) {
  3489. if ( listeners[ type ] === undefined ) {
  3490. listeners[ type ] = [];
  3491. }
  3492. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3493. listeners[ type ].push( listener );
  3494. }
  3495. };
  3496. this.removeEventListener = function ( type, listener ) {
  3497. var index = listeners[ type ].indexOf( listener );
  3498. if ( index !== - 1 ) {
  3499. listeners[ type ].splice( index, 1 );
  3500. }
  3501. };
  3502. this.dispatchEvent = function ( event ) {
  3503. var listenerArray = listeners[ event.type ];
  3504. if ( listenerArray !== undefined ) {
  3505. event.target = this;
  3506. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3507. listenerArray[ i ].call( this, event );
  3508. }
  3509. }
  3510. };
  3511. };
  3512. /**
  3513. * @author mrdoob / http://mrdoob.com/
  3514. * @author bhouston / http://exocortex.com/
  3515. */
  3516. ( function ( THREE ) {
  3517. THREE.Raycaster = function ( origin, direction, near, far ) {
  3518. this.ray = new THREE.Ray( origin, direction );
  3519. // normalized ray.direction required for accurate distance calculations
  3520. if( this.ray.direction.lengthSq() > 0 ) {
  3521. this.ray.direction.normalize();
  3522. }
  3523. this.near = near || 0;
  3524. this.far = far || Infinity;
  3525. };
  3526. var sphere = new THREE.Sphere();
  3527. var localRay = new THREE.Ray();
  3528. var facePlane = new THREE.Plane();
  3529. var intersectPoint = new THREE.Vector3();
  3530. var matrixPosition = new THREE.Vector3();
  3531. var inverseMatrix = new THREE.Matrix4();
  3532. var descSort = function ( a, b ) {
  3533. return a.distance - b.distance;
  3534. };
  3535. var intersectObject = function ( object, raycaster, intersects ) {
  3536. if ( object instanceof THREE.Particle ) {
  3537. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3538. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3539. if ( distance > object.scale.x ) {
  3540. return intersects;
  3541. }
  3542. intersects.push( {
  3543. distance: distance,
  3544. point: object.position,
  3545. face: null,
  3546. object: object
  3547. } );
  3548. } else if ( object instanceof THREE.Mesh ) {
  3549. // Checking boundingSphere distance to ray
  3550. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3551. sphere.set(
  3552. matrixPosition,
  3553. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3554. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3555. return intersects;
  3556. }
  3557. // Checking faces
  3558. var geometry = object.geometry;
  3559. var vertices = geometry.vertices;
  3560. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3561. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3562. var side = object.material.side;
  3563. var a, b, c, d;
  3564. var precision = raycaster.precision;
  3565. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3566. inverseMatrix.getInverse( object.matrixWorld );
  3567. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3568. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3569. var face = geometry.faces[ f ];
  3570. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3571. if ( material === undefined ) continue;
  3572. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3573. var planeDistance = localRay.distanceToPlane( facePlane );
  3574. // bail if raycaster and plane are parallel
  3575. if ( Math.abs( planeDistance ) < precision ) continue;
  3576. // if negative distance, then plane is behind raycaster
  3577. if ( planeDistance < 0 ) continue;
  3578. // check if we hit the wrong side of a single sided face
  3579. side = material.side;
  3580. if( side !== THREE.DoubleSide ) {
  3581. var planeSign = localRay.direction.dot( facePlane.normal );
  3582. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3583. }
  3584. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3585. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3586. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3587. if ( face instanceof THREE.Face3 ) {
  3588. a = vertices[ face.a ];
  3589. b = vertices[ face.b ];
  3590. c = vertices[ face.c ];
  3591. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3592. } else if ( face instanceof THREE.Face4 ) {
  3593. a = vertices[ face.a ];
  3594. b = vertices[ face.b ];
  3595. c = vertices[ face.c ];
  3596. d = vertices[ face.d ];
  3597. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3598. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3599. } else {
  3600. // This is added because if we call out of this if/else group when none of the cases
  3601. // match it will add a point to the intersection list erroneously.
  3602. throw Error( "face type not supported" );
  3603. }
  3604. intersects.push( {
  3605. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3606. point: raycaster.ray.at( planeDistance ),
  3607. face: face,
  3608. faceIndex: f,
  3609. object: object
  3610. } );
  3611. }
  3612. }
  3613. };
  3614. var intersectDescendants = function ( object, raycaster, intersects ) {
  3615. var descendants = object.getDescendants();
  3616. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3617. intersectObject( descendants[ i ], raycaster, intersects );
  3618. }
  3619. };
  3620. //
  3621. THREE.Raycaster.prototype.precision = 0.0001;
  3622. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3623. this.ray.set( origin, direction );
  3624. // normalized ray.direction required for accurate distance calculations
  3625. if( this.ray.direction.length() > 0 ) {
  3626. this.ray.direction.normalize();
  3627. }
  3628. };
  3629. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3630. var intersects = [];
  3631. if ( recursive === true ) {
  3632. intersectDescendants( object, this, intersects );
  3633. }
  3634. intersectObject( object, this, intersects );
  3635. intersects.sort( descSort );
  3636. return intersects;
  3637. };
  3638. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3639. var intersects = [];
  3640. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3641. intersectObject( objects[ i ], this, intersects );
  3642. if ( recursive === true ) {
  3643. intersectDescendants( objects[ i ], this, intersects );
  3644. }
  3645. }
  3646. intersects.sort( descSort );
  3647. return intersects;
  3648. };
  3649. }( THREE ) );
  3650. /**
  3651. * @author mrdoob / http://mrdoob.com/
  3652. * @author mikael emtinger / http://gomo.se/
  3653. * @author alteredq / http://alteredqualia.com/
  3654. * @author WestLangley / http://github.com/WestLangley
  3655. */
  3656. THREE.Object3D = function () {
  3657. this.id = THREE.Object3DIdCount ++;
  3658. this.name = '';
  3659. this.parent = undefined;
  3660. this.children = [];
  3661. this.up = new THREE.Vector3( 0, 1, 0 );
  3662. this.position = new THREE.Vector3();
  3663. this.rotation = new THREE.Vector3();
  3664. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3665. this.scale = new THREE.Vector3( 1, 1, 1 );
  3666. this.renderDepth = null;
  3667. this.rotationAutoUpdate = true;
  3668. this.matrix = new THREE.Matrix4();
  3669. this.matrixWorld = new THREE.Matrix4();
  3670. this.matrixRotationWorld = new THREE.Matrix4();
  3671. this.matrixAutoUpdate = true;
  3672. this.matrixWorldNeedsUpdate = true;
  3673. this.quaternion = new THREE.Quaternion();
  3674. this.useQuaternion = false;
  3675. this.visible = true;
  3676. this.castShadow = false;
  3677. this.receiveShadow = false;
  3678. this.frustumCulled = true;
  3679. this.userData = {};
  3680. };
  3681. THREE.Object3D.prototype = {
  3682. constructor: THREE.Object3D,
  3683. applyMatrix: function () {
  3684. var m1 = new THREE.Matrix4();
  3685. return function ( matrix ) {
  3686. this.matrix.multiplyMatrices( matrix, this.matrix );
  3687. this.position.getPositionFromMatrix( this.matrix );
  3688. this.scale.getScaleFromMatrix( this.matrix );
  3689. m1.extractRotation( this.matrix );
  3690. if ( this.useQuaternion === true ) {
  3691. this.quaternion.setFromRotationMatrix( m1 );
  3692. } else {
  3693. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3694. }
  3695. }
  3696. }(),
  3697. translate: function () {
  3698. var v1 = new THREE.Vector3();
  3699. return function ( distance, axis ) {
  3700. // axis is assumed to be normalized
  3701. v1.copy( axis );
  3702. if ( this.useQuaternion === true ) {
  3703. v1.applyQuaternion( this.quaternion );
  3704. } else {
  3705. v1.applyEuler( this.rotation, this.eulerOrder );
  3706. }
  3707. v1.multiplyScalar( distance );
  3708. this.position.add( v1 );
  3709. return this;
  3710. };
  3711. }(),
  3712. translateX: function () {
  3713. var v1 = new THREE.Vector3( 1, 0, 0 );
  3714. return function ( distance ) {
  3715. return this.translate( distance, v1 );
  3716. };
  3717. }(),
  3718. translateY: function () {
  3719. var v1 = new THREE.Vector3( 0, 1, 0 );
  3720. return function ( distance ) {
  3721. return this.translate( distance, v1 );
  3722. };
  3723. }(),
  3724. translateZ: function () {
  3725. var v1 = new THREE.Vector3( 0, 0, 1 );
  3726. return function ( distance ) {
  3727. return this.translate( distance, v1 );
  3728. };
  3729. }(),
  3730. localToWorld: function ( vector ) {
  3731. return vector.applyMatrix4( this.matrixWorld );
  3732. },
  3733. worldToLocal: function () {
  3734. var m1 = new THREE.Matrix4();
  3735. return function ( vector ) {
  3736. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3737. };
  3738. }(),
  3739. lookAt: function () {
  3740. // This routine does not support objects with rotated and/or translated parent(s)
  3741. var m1 = new THREE.Matrix4();
  3742. return function ( vector ) {
  3743. m1.lookAt( vector, this.position, this.up );
  3744. if ( this.useQuaternion === true ) {
  3745. this.quaternion.setFromRotationMatrix( m1 );
  3746. } else {
  3747. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3748. }
  3749. };
  3750. }(),
  3751. add: function ( object ) {
  3752. if ( object === this ) {
  3753. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3754. return;
  3755. }
  3756. if ( object instanceof THREE.Object3D ) {
  3757. if ( object.parent !== undefined ) {
  3758. object.parent.remove( object );
  3759. }
  3760. object.parent = this;
  3761. this.children.push( object );
  3762. // add to scene
  3763. var scene = this;
  3764. while ( scene.parent !== undefined ) {
  3765. scene = scene.parent;
  3766. }
  3767. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3768. scene.__addObject( object );
  3769. }
  3770. }
  3771. },
  3772. remove: function ( object ) {
  3773. var index = this.children.indexOf( object );
  3774. if ( index !== - 1 ) {
  3775. object.parent = undefined;
  3776. this.children.splice( index, 1 );
  3777. // remove from scene
  3778. var scene = this;
  3779. while ( scene.parent !== undefined ) {
  3780. scene = scene.parent;
  3781. }
  3782. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3783. scene.__removeObject( object );
  3784. }
  3785. }
  3786. },
  3787. traverse: function ( callback ) {
  3788. callback( this );
  3789. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3790. this.children[ i ].traverse( callback );
  3791. }
  3792. },
  3793. getChildByName: function ( name, recursive ) {
  3794. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3795. var child = this.children[ i ];
  3796. if ( child.name === name ) {
  3797. return child;
  3798. }
  3799. if ( recursive === true ) {
  3800. child = child.getChildByName( name, recursive );
  3801. if ( child !== undefined ) {
  3802. return child;
  3803. }
  3804. }
  3805. }
  3806. return undefined;
  3807. },
  3808. getDescendants: function ( array ) {
  3809. if ( array === undefined ) array = [];
  3810. Array.prototype.push.apply( array, this.children );
  3811. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3812. this.children[ i ].getDescendants( array );
  3813. }
  3814. return array;
  3815. },
  3816. updateMatrix: function () {
  3817. this.matrix.setPosition( this.position );
  3818. if ( this.useQuaternion === false ) {
  3819. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3820. } else {
  3821. this.matrix.setRotationFromQuaternion( this.quaternion );
  3822. }
  3823. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3824. this.matrix.scale( this.scale );
  3825. }
  3826. this.matrixWorldNeedsUpdate = true;
  3827. },
  3828. updateMatrixWorld: function ( force ) {
  3829. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3830. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3831. if ( this.parent === undefined ) {
  3832. this.matrixWorld.copy( this.matrix );
  3833. } else {
  3834. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3835. }
  3836. this.matrixWorldNeedsUpdate = false;
  3837. force = true;
  3838. }
  3839. // update children
  3840. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3841. this.children[ i ].updateMatrixWorld( force );
  3842. }
  3843. },
  3844. clone: function ( object ) {
  3845. if ( object === undefined ) object = new THREE.Object3D();
  3846. object.name = this.name;
  3847. object.up.copy( this.up );
  3848. object.position.copy( this.position );
  3849. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3850. object.eulerOrder = this.eulerOrder;
  3851. object.scale.copy( this.scale );
  3852. object.renderDepth = this.renderDepth;
  3853. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3854. object.matrix.copy( this.matrix );
  3855. object.matrixWorld.copy( this.matrixWorld );
  3856. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3857. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3858. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3859. object.quaternion.copy( this.quaternion );
  3860. object.useQuaternion = this.useQuaternion;
  3861. object.visible = this.visible;
  3862. object.castShadow = this.castShadow;
  3863. object.receiveShadow = this.receiveShadow;
  3864. object.frustumCulled = this.frustumCulled;
  3865. for ( var i = 0; i < this.children.length; i ++ ) {
  3866. var child = this.children[ i ];
  3867. object.add( child.clone() );
  3868. }
  3869. return object;
  3870. }
  3871. };
  3872. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3873. THREE.Object3DIdCount = 0;
  3874. /**
  3875. * @author mrdoob / http://mrdoob.com/
  3876. * @author supereggbert / http://www.paulbrunt.co.uk/
  3877. * @author julianwa / https://github.com/julianwa
  3878. */
  3879. THREE.Projector = function () {
  3880. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3881. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3882. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3883. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3884. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3885. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3886. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3887. _vector3 = new THREE.Vector3(),
  3888. _vector4 = new THREE.Vector4(),
  3889. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3890. _boundingBox = new THREE.Box3(),
  3891. _points3 = new Array( 3 ),
  3892. _points4 = new Array( 4 ),
  3893. _viewMatrix = new THREE.Matrix4(),
  3894. _viewProjectionMatrix = new THREE.Matrix4(),
  3895. _modelMatrix,
  3896. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3897. _normalMatrix = new THREE.Matrix3(),
  3898. _normalViewMatrix = new THREE.Matrix3(),
  3899. _centroid = new THREE.Vector3(),
  3900. _frustum = new THREE.Frustum(),
  3901. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3902. _clippedVertex2PositionScreen = new THREE.Vector4();
  3903. this.projectVector = function ( vector, camera ) {
  3904. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3905. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3906. return vector.applyProjection( _viewProjectionMatrix );
  3907. };
  3908. this.unprojectVector = function ( vector, camera ) {
  3909. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3910. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3911. return vector.applyProjection( _viewProjectionMatrix );
  3912. };
  3913. this.pickingRay = function ( vector, camera ) {
  3914. // set two vectors with opposing z values
  3915. vector.z = -1.0;
  3916. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3917. this.unprojectVector( vector, camera );
  3918. this.unprojectVector( end, camera );
  3919. // find direction from vector to end
  3920. end.sub( vector ).normalize();
  3921. return new THREE.Raycaster( vector, end );
  3922. };
  3923. var projectGraph = function ( root, sortObjects ) {
  3924. _objectCount = 0;
  3925. _renderData.objects.length = 0;
  3926. _renderData.sprites.length = 0;
  3927. _renderData.lights.length = 0;
  3928. var projectObject = function ( parent ) {
  3929. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3930. var object = parent.children[ c ];
  3931. if ( object.visible === false ) continue;
  3932. if ( object instanceof THREE.Light ) {
  3933. _renderData.lights.push( object );
  3934. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3935. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3936. _object = getNextObjectInPool();
  3937. _object.object = object;
  3938. if ( object.renderDepth !== null ) {
  3939. _object.z = object.renderDepth;
  3940. } else {
  3941. _vector3.getPositionFromMatrix( object.matrixWorld );
  3942. _vector3.applyProjection( _viewProjectionMatrix );
  3943. _object.z = _vector3.z;
  3944. }
  3945. _renderData.objects.push( _object );
  3946. }
  3947. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3948. _object = getNextObjectInPool();
  3949. _object.object = object;
  3950. // TODO: Find an elegant and performant solution and remove this dupe code.
  3951. if ( object.renderDepth !== null ) {
  3952. _object.z = object.renderDepth;
  3953. } else {
  3954. _vector3.getPositionFromMatrix( object.matrixWorld );
  3955. _vector3.applyProjection( _viewProjectionMatrix );
  3956. _object.z = _vector3.z;
  3957. }
  3958. _renderData.sprites.push( _object );
  3959. } else {
  3960. _object = getNextObjectInPool();
  3961. _object.object = object;
  3962. if ( object.renderDepth !== null ) {
  3963. _object.z = object.renderDepth;
  3964. } else {
  3965. _vector3.getPositionFromMatrix( object.matrixWorld );
  3966. _vector3.applyProjection( _viewProjectionMatrix );
  3967. _object.z = _vector3.z;
  3968. }
  3969. _renderData.objects.push( _object );
  3970. }
  3971. projectObject( object );
  3972. }
  3973. };
  3974. projectObject( root );
  3975. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3976. return _renderData;
  3977. };
  3978. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3979. var visible = false,
  3980. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3981. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3982. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3983. _face3Count = 0;
  3984. _face4Count = 0;
  3985. _lineCount = 0;
  3986. _particleCount = 0;
  3987. _renderData.elements.length = 0;
  3988. scene.updateMatrixWorld();
  3989. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3990. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3991. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3992. _normalViewMatrix.getInverse( _viewMatrix );
  3993. _normalViewMatrix.transpose();
  3994. _frustum.setFromMatrix( _viewProjectionMatrix );
  3995. _renderData = projectGraph( scene, sortObjects );
  3996. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3997. object = _renderData.objects[ o ].object;
  3998. _modelMatrix = object.matrixWorld;
  3999. _vertexCount = 0;
  4000. if ( object instanceof THREE.Mesh ) {
  4001. geometry = object.geometry;
  4002. vertices = geometry.vertices;
  4003. faces = geometry.faces;
  4004. faceVertexUvs = geometry.faceVertexUvs;
  4005. _normalMatrix.getInverse( _modelMatrix );
  4006. _normalMatrix.transpose();
  4007. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4008. objectMaterials = isFaceMaterial === true ? object.material : null;
  4009. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4010. _vertex = getNextVertexInPool();
  4011. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4012. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4013. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4014. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4015. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4016. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4017. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4018. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4019. }
  4020. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4021. face = faces[ f ];
  4022. var material = isFaceMaterial === true
  4023. ? objectMaterials.materials[ face.materialIndex ]
  4024. : object.material;
  4025. if ( material === undefined ) continue;
  4026. var side = material.side;
  4027. if ( face instanceof THREE.Face3 ) {
  4028. v1 = _vertexPool[ face.a ];
  4029. v2 = _vertexPool[ face.b ];
  4030. v3 = _vertexPool[ face.c ];
  4031. _points3[ 0 ] = v1.positionScreen;
  4032. _points3[ 1 ] = v2.positionScreen;
  4033. _points3[ 2 ] = v3.positionScreen;
  4034. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4035. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4036. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4037. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4038. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4039. _face = getNextFace3InPool();
  4040. _face.v1.copy( v1 );
  4041. _face.v2.copy( v2 );
  4042. _face.v3.copy( v3 );
  4043. } else {
  4044. continue;
  4045. }
  4046. } else {
  4047. continue;
  4048. }
  4049. } else if ( face instanceof THREE.Face4 ) {
  4050. v1 = _vertexPool[ face.a ];
  4051. v2 = _vertexPool[ face.b ];
  4052. v3 = _vertexPool[ face.c ];
  4053. v4 = _vertexPool[ face.d ];
  4054. _points4[ 0 ] = v1.positionScreen;
  4055. _points4[ 1 ] = v2.positionScreen;
  4056. _points4[ 2 ] = v3.positionScreen;
  4057. _points4[ 3 ] = v4.positionScreen;
  4058. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4059. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4060. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4061. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4062. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4063. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4064. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4065. _face = getNextFace4InPool();
  4066. _face.v1.copy( v1 );
  4067. _face.v2.copy( v2 );
  4068. _face.v3.copy( v3 );
  4069. _face.v4.copy( v4 );
  4070. } else {
  4071. continue;
  4072. }
  4073. } else {
  4074. continue;
  4075. }
  4076. }
  4077. _face.normalModel.copy( face.normal );
  4078. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4079. _face.normalModel.negate();
  4080. }
  4081. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4082. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4083. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4084. faceVertexNormals = face.vertexNormals;
  4085. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4086. var normalModel = _face.vertexNormalsModel[ n ];
  4087. normalModel.copy( faceVertexNormals[ n ] );
  4088. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4089. normalModel.negate();
  4090. }
  4091. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4092. var normalModelView = _face.vertexNormalsModelView[ n ];
  4093. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4094. }
  4095. _face.vertexNormalsLength = faceVertexNormals.length;
  4096. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4097. uvs = faceVertexUvs[ c ][ f ];
  4098. if ( uvs === undefined ) continue;
  4099. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4100. _face.uvs[ c ][ u ] = uvs[ u ];
  4101. }
  4102. }
  4103. _face.color = face.color;
  4104. _face.material = material;
  4105. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4106. _face.z = _centroid.z;
  4107. _renderData.elements.push( _face );
  4108. }
  4109. } else if ( object instanceof THREE.Line ) {
  4110. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4111. vertices = object.geometry.vertices;
  4112. v1 = getNextVertexInPool();
  4113. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4114. // Handle LineStrip and LinePieces
  4115. var step = object.type === THREE.LinePieces ? 2 : 1;
  4116. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4117. v1 = getNextVertexInPool();
  4118. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4119. if ( ( v + 1 ) % step > 0 ) continue;
  4120. v2 = _vertexPool[ _vertexCount - 2 ];
  4121. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4122. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4123. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4124. // Perform the perspective divide
  4125. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4126. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4127. _line = getNextLineInPool();
  4128. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4129. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4130. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4131. _line.material = object.material;
  4132. _renderData.elements.push( _line );
  4133. }
  4134. }
  4135. }
  4136. }
  4137. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4138. object = _renderData.sprites[ o ].object;
  4139. _modelMatrix = object.matrixWorld;
  4140. if ( object instanceof THREE.Particle ) {
  4141. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4142. _vector4.applyMatrix4( _viewProjectionMatrix );
  4143. _vector4.z /= _vector4.w;
  4144. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4145. _particle = getNextParticleInPool();
  4146. _particle.object = object;
  4147. _particle.x = _vector4.x / _vector4.w;
  4148. _particle.y = _vector4.y / _vector4.w;
  4149. _particle.z = _vector4.z;
  4150. _particle.rotation = object.rotation.z;
  4151. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4152. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4153. _particle.material = object.material;
  4154. _renderData.elements.push( _particle );
  4155. }
  4156. }
  4157. }
  4158. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4159. return _renderData;
  4160. };
  4161. // Pools
  4162. function getNextObjectInPool() {
  4163. if ( _objectCount === _objectPoolLength ) {
  4164. var object = new THREE.RenderableObject();
  4165. _objectPool.push( object );
  4166. _objectPoolLength ++;
  4167. _objectCount ++;
  4168. return object;
  4169. }
  4170. return _objectPool[ _objectCount ++ ];
  4171. }
  4172. function getNextVertexInPool() {
  4173. if ( _vertexCount === _vertexPoolLength ) {
  4174. var vertex = new THREE.RenderableVertex();
  4175. _vertexPool.push( vertex );
  4176. _vertexPoolLength ++;
  4177. _vertexCount ++;
  4178. return vertex;
  4179. }
  4180. return _vertexPool[ _vertexCount ++ ];
  4181. }
  4182. function getNextFace3InPool() {
  4183. if ( _face3Count === _face3PoolLength ) {
  4184. var face = new THREE.RenderableFace3();
  4185. _face3Pool.push( face );
  4186. _face3PoolLength ++;
  4187. _face3Count ++;
  4188. return face;
  4189. }
  4190. return _face3Pool[ _face3Count ++ ];
  4191. }
  4192. function getNextFace4InPool() {
  4193. if ( _face4Count === _face4PoolLength ) {
  4194. var face = new THREE.RenderableFace4();
  4195. _face4Pool.push( face );
  4196. _face4PoolLength ++;
  4197. _face4Count ++;
  4198. return face;
  4199. }
  4200. return _face4Pool[ _face4Count ++ ];
  4201. }
  4202. function getNextLineInPool() {
  4203. if ( _lineCount === _linePoolLength ) {
  4204. var line = new THREE.RenderableLine();
  4205. _linePool.push( line );
  4206. _linePoolLength ++;
  4207. _lineCount ++
  4208. return line;
  4209. }
  4210. return _linePool[ _lineCount ++ ];
  4211. }
  4212. function getNextParticleInPool() {
  4213. if ( _particleCount === _particlePoolLength ) {
  4214. var particle = new THREE.RenderableParticle();
  4215. _particlePool.push( particle );
  4216. _particlePoolLength ++;
  4217. _particleCount ++
  4218. return particle;
  4219. }
  4220. return _particlePool[ _particleCount ++ ];
  4221. }
  4222. //
  4223. function painterSort( a, b ) {
  4224. return b.z - a.z;
  4225. }
  4226. function clipLine( s1, s2 ) {
  4227. var alpha1 = 0, alpha2 = 1,
  4228. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4229. // Z = -1 and Z = +1, respectively.
  4230. bc1near = s1.z + s1.w,
  4231. bc2near = s2.z + s2.w,
  4232. bc1far = - s1.z + s1.w,
  4233. bc2far = - s2.z + s2.w;
  4234. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4235. // Both vertices lie entirely within all clip planes.
  4236. return true;
  4237. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4238. // Both vertices lie entirely outside one of the clip planes.
  4239. return false;
  4240. } else {
  4241. // The line segment spans at least one clip plane.
  4242. if ( bc1near < 0 ) {
  4243. // v1 lies outside the near plane, v2 inside
  4244. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4245. } else if ( bc2near < 0 ) {
  4246. // v2 lies outside the near plane, v1 inside
  4247. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4248. }
  4249. if ( bc1far < 0 ) {
  4250. // v1 lies outside the far plane, v2 inside
  4251. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4252. } else if ( bc2far < 0 ) {
  4253. // v2 lies outside the far plane, v2 inside
  4254. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4255. }
  4256. if ( alpha2 < alpha1 ) {
  4257. // The line segment spans two boundaries, but is outside both of them.
  4258. // (This can't happen when we're only clipping against just near/far but good
  4259. // to leave the check here for future usage if other clip planes are added.)
  4260. return false;
  4261. } else {
  4262. // Update the s1 and s2 vertices to match the clipped line segment.
  4263. s1.lerp( s2, alpha1 );
  4264. s2.lerp( s1, 1 - alpha2 );
  4265. return true;
  4266. }
  4267. }
  4268. }
  4269. };
  4270. /**
  4271. * @author mrdoob / http://mrdoob.com/
  4272. * @author alteredq / http://alteredqualia.com/
  4273. */
  4274. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4275. this.a = a;
  4276. this.b = b;
  4277. this.c = c;
  4278. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4279. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4280. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4281. this.vertexColors = color instanceof Array ? color : [];
  4282. this.vertexTangents = [];
  4283. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4284. this.centroid = new THREE.Vector3();
  4285. };
  4286. THREE.Face3.prototype = {
  4287. constructor: THREE.Face3,
  4288. clone: function () {
  4289. var face = new THREE.Face3( this.a, this.b, this.c );
  4290. face.normal.copy( this.normal );
  4291. face.color.copy( this.color );
  4292. face.centroid.copy( this.centroid );
  4293. face.materialIndex = this.materialIndex;
  4294. var i, il;
  4295. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4296. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4297. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4298. return face;
  4299. }
  4300. };
  4301. /**
  4302. * @author mrdoob / http://mrdoob.com/
  4303. * @author alteredq / http://alteredqualia.com/
  4304. */
  4305. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4306. this.a = a;
  4307. this.b = b;
  4308. this.c = c;
  4309. this.d = d;
  4310. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4311. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4312. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4313. this.vertexColors = color instanceof Array ? color : [];
  4314. this.vertexTangents = [];
  4315. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4316. this.centroid = new THREE.Vector3();
  4317. };
  4318. THREE.Face4.prototype = {
  4319. constructor: THREE.Face4,
  4320. clone: function () {
  4321. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4322. face.normal.copy( this.normal );
  4323. face.color.copy( this.color );
  4324. face.centroid.copy( this.centroid );
  4325. face.materialIndex = this.materialIndex;
  4326. var i, il;
  4327. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4328. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4329. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4330. return face;
  4331. }
  4332. };
  4333. /**
  4334. * @author mrdoob / http://mrdoob.com/
  4335. * @author kile / http://kile.stravaganza.org/
  4336. * @author alteredq / http://alteredqualia.com/
  4337. * @author mikael emtinger / http://gomo.se/
  4338. * @author zz85 / http://www.lab4games.net/zz85/blog
  4339. * @author bhouston / http://exocortex.com
  4340. */
  4341. THREE.Geometry = function () {
  4342. THREE.EventDispatcher.call( this );
  4343. this.id = THREE.GeometryIdCount ++;
  4344. this.name = '';
  4345. this.vertices = [];
  4346. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4347. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4348. this.faces = [];
  4349. this.faceUvs = [[]];
  4350. this.faceVertexUvs = [[]];
  4351. this.morphTargets = [];
  4352. this.morphColors = [];
  4353. this.morphNormals = [];
  4354. this.skinWeights = [];
  4355. this.skinIndices = [];
  4356. this.lineDistances = [];
  4357. this.boundingBox = null;
  4358. this.boundingSphere = null;
  4359. this.hasTangents = false;
  4360. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4361. // update flags
  4362. this.verticesNeedUpdate = false;
  4363. this.elementsNeedUpdate = false;
  4364. this.uvsNeedUpdate = false;
  4365. this.normalsNeedUpdate = false;
  4366. this.tangentsNeedUpdate = false;
  4367. this.colorsNeedUpdate = false;
  4368. this.lineDistancesNeedUpdate = false;
  4369. this.buffersNeedUpdate = false;
  4370. };
  4371. THREE.Geometry.prototype = {
  4372. constructor: THREE.Geometry,
  4373. applyMatrix: function ( matrix ) {
  4374. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4375. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4376. var vertex = this.vertices[ i ];
  4377. vertex.applyMatrix4( matrix );
  4378. }
  4379. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4380. var face = this.faces[ i ];
  4381. face.normal.applyMatrix3( normalMatrix ).normalize();
  4382. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4383. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4384. }
  4385. face.centroid.applyMatrix4( matrix );
  4386. }
  4387. },
  4388. computeCentroids: function () {
  4389. var f, fl, face;
  4390. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4391. face = this.faces[ f ];
  4392. face.centroid.set( 0, 0, 0 );
  4393. if ( face instanceof THREE.Face3 ) {
  4394. face.centroid.add( this.vertices[ face.a ] );
  4395. face.centroid.add( this.vertices[ face.b ] );
  4396. face.centroid.add( this.vertices[ face.c ] );
  4397. face.centroid.divideScalar( 3 );
  4398. } else if ( face instanceof THREE.Face4 ) {
  4399. face.centroid.add( this.vertices[ face.a ] );
  4400. face.centroid.add( this.vertices[ face.b ] );
  4401. face.centroid.add( this.vertices[ face.c ] );
  4402. face.centroid.add( this.vertices[ face.d ] );
  4403. face.centroid.divideScalar( 4 );
  4404. }
  4405. }
  4406. },
  4407. computeFaceNormals: function () {
  4408. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4409. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4410. var face = this.faces[ f ];
  4411. var vA = this.vertices[ face.a ];
  4412. var vB = this.vertices[ face.b ];
  4413. var vC = this.vertices[ face.c ];
  4414. cb.subVectors( vC, vB );
  4415. ab.subVectors( vA, vB );
  4416. cb.cross( ab );
  4417. cb.normalize();
  4418. face.normal.copy( cb );
  4419. }
  4420. },
  4421. computeVertexNormals: function ( areaWeighted ) {
  4422. var v, vl, f, fl, face, vertices;
  4423. // create internal buffers for reuse when calling this method repeatedly
  4424. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4425. if ( this.__tmpVertices === undefined ) {
  4426. this.__tmpVertices = new Array( this.vertices.length );
  4427. vertices = this.__tmpVertices;
  4428. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4429. vertices[ v ] = new THREE.Vector3();
  4430. }
  4431. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4432. face = this.faces[ f ];
  4433. if ( face instanceof THREE.Face3 ) {
  4434. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4435. } else if ( face instanceof THREE.Face4 ) {
  4436. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4437. }
  4438. }
  4439. } else {
  4440. vertices = this.__tmpVertices;
  4441. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4442. vertices[ v ].set( 0, 0, 0 );
  4443. }
  4444. }
  4445. if ( areaWeighted ) {
  4446. // vertex normals weighted by triangle areas
  4447. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4448. var vA, vB, vC, vD;
  4449. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4450. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4451. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4452. face = this.faces[ f ];
  4453. if ( face instanceof THREE.Face3 ) {
  4454. vA = this.vertices[ face.a ];
  4455. vB = this.vertices[ face.b ];
  4456. vC = this.vertices[ face.c ];
  4457. cb.subVectors( vC, vB );
  4458. ab.subVectors( vA, vB );
  4459. cb.cross( ab );
  4460. vertices[ face.a ].add( cb );
  4461. vertices[ face.b ].add( cb );
  4462. vertices[ face.c ].add( cb );
  4463. } else if ( face instanceof THREE.Face4 ) {
  4464. vA = this.vertices[ face.a ];
  4465. vB = this.vertices[ face.b ];
  4466. vC = this.vertices[ face.c ];
  4467. vD = this.vertices[ face.d ];
  4468. // abd
  4469. db.subVectors( vD, vB );
  4470. ab.subVectors( vA, vB );
  4471. db.cross( ab );
  4472. vertices[ face.a ].add( db );
  4473. vertices[ face.b ].add( db );
  4474. vertices[ face.d ].add( db );
  4475. // bcd
  4476. dc.subVectors( vD, vC );
  4477. bc.subVectors( vB, vC );
  4478. dc.cross( bc );
  4479. vertices[ face.b ].add( dc );
  4480. vertices[ face.c ].add( dc );
  4481. vertices[ face.d ].add( dc );
  4482. }
  4483. }
  4484. } else {
  4485. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4486. face = this.faces[ f ];
  4487. if ( face instanceof THREE.Face3 ) {
  4488. vertices[ face.a ].add( face.normal );
  4489. vertices[ face.b ].add( face.normal );
  4490. vertices[ face.c ].add( face.normal );
  4491. } else if ( face instanceof THREE.Face4 ) {
  4492. vertices[ face.a ].add( face.normal );
  4493. vertices[ face.b ].add( face.normal );
  4494. vertices[ face.c ].add( face.normal );
  4495. vertices[ face.d ].add( face.normal );
  4496. }
  4497. }
  4498. }
  4499. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4500. vertices[ v ].normalize();
  4501. }
  4502. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4503. face = this.faces[ f ];
  4504. if ( face instanceof THREE.Face3 ) {
  4505. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4506. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4507. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4508. } else if ( face instanceof THREE.Face4 ) {
  4509. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4510. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4511. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4512. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4513. }
  4514. }
  4515. },
  4516. computeMorphNormals: function () {
  4517. var i, il, f, fl, face;
  4518. // save original normals
  4519. // - create temp variables on first access
  4520. // otherwise just copy (for faster repeated calls)
  4521. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4522. face = this.faces[ f ];
  4523. if ( ! face.__originalFaceNormal ) {
  4524. face.__originalFaceNormal = face.normal.clone();
  4525. } else {
  4526. face.__originalFaceNormal.copy( face.normal );
  4527. }
  4528. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4529. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4530. if ( ! face.__originalVertexNormals[ i ] ) {
  4531. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4532. } else {
  4533. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4534. }
  4535. }
  4536. }
  4537. // use temp geometry to compute face and vertex normals for each morph
  4538. var tmpGeo = new THREE.Geometry();
  4539. tmpGeo.faces = this.faces;
  4540. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4541. // create on first access
  4542. if ( ! this.morphNormals[ i ] ) {
  4543. this.morphNormals[ i ] = {};
  4544. this.morphNormals[ i ].faceNormals = [];
  4545. this.morphNormals[ i ].vertexNormals = [];
  4546. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4547. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4548. var faceNormal, vertexNormals;
  4549. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4550. face = this.faces[ f ];
  4551. faceNormal = new THREE.Vector3();
  4552. if ( face instanceof THREE.Face3 ) {
  4553. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4554. } else {
  4555. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4556. }
  4557. dstNormalsFace.push( faceNormal );
  4558. dstNormalsVertex.push( vertexNormals );
  4559. }
  4560. }
  4561. var morphNormals = this.morphNormals[ i ];
  4562. // set vertices to morph target
  4563. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4564. // compute morph normals
  4565. tmpGeo.computeFaceNormals();
  4566. tmpGeo.computeVertexNormals();
  4567. // store morph normals
  4568. var faceNormal, vertexNormals;
  4569. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4570. face = this.faces[ f ];
  4571. faceNormal = morphNormals.faceNormals[ f ];
  4572. vertexNormals = morphNormals.vertexNormals[ f ];
  4573. faceNormal.copy( face.normal );
  4574. if ( face instanceof THREE.Face3 ) {
  4575. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4576. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4577. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4578. } else {
  4579. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4580. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4581. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4582. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4583. }
  4584. }
  4585. }
  4586. // restore original normals
  4587. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4588. face = this.faces[ f ];
  4589. face.normal = face.__originalFaceNormal;
  4590. face.vertexNormals = face.__originalVertexNormals;
  4591. }
  4592. },
  4593. computeTangents: function () {
  4594. // based on http://www.terathon.com/code/tangent.html
  4595. // tangents go to vertices
  4596. var f, fl, v, vl, i, il, vertexIndex,
  4597. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4598. x1, x2, y1, y2, z1, z2,
  4599. s1, s2, t1, t2, r, t, test,
  4600. tan1 = [], tan2 = [],
  4601. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4602. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4603. n = new THREE.Vector3(), w;
  4604. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4605. tan1[ v ] = new THREE.Vector3();
  4606. tan2[ v ] = new THREE.Vector3();
  4607. }
  4608. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4609. vA = context.vertices[ a ];
  4610. vB = context.vertices[ b ];
  4611. vC = context.vertices[ c ];
  4612. uvA = uv[ ua ];
  4613. uvB = uv[ ub ];
  4614. uvC = uv[ uc ];
  4615. x1 = vB.x - vA.x;
  4616. x2 = vC.x - vA.x;
  4617. y1 = vB.y - vA.y;
  4618. y2 = vC.y - vA.y;
  4619. z1 = vB.z - vA.z;
  4620. z2 = vC.z - vA.z;
  4621. s1 = uvB.x - uvA.x;
  4622. s2 = uvC.x - uvA.x;
  4623. t1 = uvB.y - uvA.y;
  4624. t2 = uvC.y - uvA.y;
  4625. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4626. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4627. ( t2 * y1 - t1 * y2 ) * r,
  4628. ( t2 * z1 - t1 * z2 ) * r );
  4629. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4630. ( s1 * y2 - s2 * y1 ) * r,
  4631. ( s1 * z2 - s2 * z1 ) * r );
  4632. tan1[ a ].add( sdir );
  4633. tan1[ b ].add( sdir );
  4634. tan1[ c ].add( sdir );
  4635. tan2[ a ].add( tdir );
  4636. tan2[ b ].add( tdir );
  4637. tan2[ c ].add( tdir );
  4638. }
  4639. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4640. face = this.faces[ f ];
  4641. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4642. if ( face instanceof THREE.Face3 ) {
  4643. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4644. } else if ( face instanceof THREE.Face4 ) {
  4645. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4646. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4647. }
  4648. }
  4649. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4650. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4651. face = this.faces[ f ];
  4652. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4653. n.copy( face.vertexNormals[ i ] );
  4654. vertexIndex = face[ faceIndex[ i ] ];
  4655. t = tan1[ vertexIndex ];
  4656. // Gram-Schmidt orthogonalize
  4657. tmp.copy( t );
  4658. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4659. // Calculate handedness
  4660. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4661. test = tmp2.dot( tan2[ vertexIndex ] );
  4662. w = (test < 0.0) ? -1.0 : 1.0;
  4663. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4664. }
  4665. }
  4666. this.hasTangents = true;
  4667. },
  4668. computeLineDistances: function ( ) {
  4669. var d = 0;
  4670. var vertices = this.vertices;
  4671. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4672. if ( i > 0 ) {
  4673. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4674. }
  4675. this.lineDistances[ i ] = d;
  4676. }
  4677. },
  4678. computeBoundingBox: function () {
  4679. if ( this.boundingBox === null ) {
  4680. this.boundingBox = new THREE.Box3();
  4681. }
  4682. this.boundingBox.setFromPoints( this.vertices );
  4683. },
  4684. computeBoundingSphere: function () {
  4685. if ( this.boundingSphere === null ) {
  4686. this.boundingSphere = new THREE.Sphere();
  4687. }
  4688. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4689. },
  4690. /*
  4691. * Checks for duplicate vertices with hashmap.
  4692. * Duplicated vertices are removed
  4693. * and faces' vertices are updated.
  4694. */
  4695. mergeVertices: function () {
  4696. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4697. var unique = [], changes = [];
  4698. var v, key;
  4699. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4700. var precision = Math.pow( 10, precisionPoints );
  4701. var i,il, face;
  4702. var indices, k, j, jl, u;
  4703. // reset cache of vertices as it now will be changing.
  4704. this.__tmpVertices = undefined;
  4705. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4706. v = this.vertices[ i ];
  4707. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4708. if ( verticesMap[ key ] === undefined ) {
  4709. verticesMap[ key ] = i;
  4710. unique.push( this.vertices[ i ] );
  4711. changes[ i ] = unique.length - 1;
  4712. } else {
  4713. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4714. changes[ i ] = changes[ verticesMap[ key ] ];
  4715. }
  4716. };
  4717. // if faces are completely degenerate after merging vertices, we
  4718. // have to remove them from the geometry.
  4719. var faceIndicesToRemove = [];
  4720. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4721. face = this.faces[ i ];
  4722. if ( face instanceof THREE.Face3 ) {
  4723. face.a = changes[ face.a ];
  4724. face.b = changes[ face.b ];
  4725. face.c = changes[ face.c ];
  4726. indices = [ face.a, face.b, face.c ];
  4727. var dupIndex = -1;
  4728. // if any duplicate vertices are found in a Face3
  4729. // we have to remove the face as nothing can be saved
  4730. for ( var n = 0; n < 3; n ++ ) {
  4731. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4732. dupIndex = n;
  4733. faceIndicesToRemove.push( i );
  4734. break;
  4735. }
  4736. }
  4737. } else if ( face instanceof THREE.Face4 ) {
  4738. face.a = changes[ face.a ];
  4739. face.b = changes[ face.b ];
  4740. face.c = changes[ face.c ];
  4741. face.d = changes[ face.d ];
  4742. // check dups in (a, b, c, d) and convert to -> face3
  4743. indices = [ face.a, face.b, face.c, face.d ];
  4744. var dupIndex = -1;
  4745. for ( var n = 0; n < 4; n ++ ) {
  4746. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4747. // if more than one duplicated vertex is found
  4748. // we can't generate any valid Face3's, thus
  4749. // we need to remove this face complete.
  4750. if ( dupIndex >= 0 ) {
  4751. faceIndicesToRemove.push( i );
  4752. }
  4753. dupIndex = n;
  4754. }
  4755. }
  4756. if ( dupIndex >= 0 ) {
  4757. indices.splice( dupIndex, 1 );
  4758. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4759. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4760. u = this.faceVertexUvs[ j ][ i ];
  4761. if ( u ) {
  4762. u.splice( dupIndex, 1 );
  4763. }
  4764. }
  4765. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4766. newFace.vertexNormals = face.vertexNormals;
  4767. newFace.vertexNormals.splice( dupIndex, 1 );
  4768. }
  4769. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4770. newFace.vertexColors = face.vertexColors;
  4771. newFace.vertexColors.splice( dupIndex, 1 );
  4772. }
  4773. this.faces[ i ] = newFace;
  4774. }
  4775. }
  4776. }
  4777. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4778. this.faces.splice( i, 1 );
  4779. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4780. this.faceVertexUvs[ j ].splice( i, 1 );
  4781. }
  4782. }
  4783. // Use unique set of vertices
  4784. var diff = this.vertices.length - unique.length;
  4785. this.vertices = unique;
  4786. return diff;
  4787. },
  4788. clone: function () {
  4789. var geometry = new THREE.Geometry();
  4790. var vertices = this.vertices;
  4791. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4792. geometry.vertices.push( vertices[ i ].clone() );
  4793. }
  4794. var faces = this.faces;
  4795. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4796. geometry.faces.push( faces[ i ].clone() );
  4797. }
  4798. var uvs = this.faceVertexUvs[ 0 ];
  4799. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4800. var uv = uvs[ i ], uvCopy = [];
  4801. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4802. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4803. }
  4804. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4805. }
  4806. return geometry;
  4807. },
  4808. dispose: function () {
  4809. this.dispatchEvent( { type: 'dispose' } );
  4810. }
  4811. };
  4812. THREE.GeometryIdCount = 0;
  4813. /**
  4814. * @author alteredq / http://alteredqualia.com/
  4815. */
  4816. THREE.BufferGeometry = function () {
  4817. THREE.EventDispatcher.call( this );
  4818. this.id = THREE.GeometryIdCount ++;
  4819. // attributes
  4820. this.attributes = {};
  4821. // attributes typed arrays are kept only if dynamic flag is set
  4822. this.dynamic = false;
  4823. // offsets for chunks when using indexed elements
  4824. this.offsets = [];
  4825. // boundings
  4826. this.boundingBox = null;
  4827. this.boundingSphere = null;
  4828. this.hasTangents = false;
  4829. // for compatibility
  4830. this.morphTargets = [];
  4831. };
  4832. THREE.BufferGeometry.prototype = {
  4833. constructor : THREE.BufferGeometry,
  4834. applyMatrix: function ( matrix ) {
  4835. var positionArray;
  4836. var normalArray;
  4837. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4838. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4839. if ( positionArray !== undefined ) {
  4840. matrix.multiplyVector3Array( positionArray );
  4841. this.verticesNeedUpdate = true;
  4842. }
  4843. if ( normalArray !== undefined ) {
  4844. var normalMatrix = new THREE.Matrix3();
  4845. normalMatrix.getInverse( matrix ).transpose();
  4846. normalMatrix.multiplyVector3Array( normalArray );
  4847. this.normalizeNormals();
  4848. this.normalsNeedUpdate = true;
  4849. }
  4850. },
  4851. computeBoundingBox: function () {
  4852. if ( this.boundingBox === null ) {
  4853. this.boundingBox = new THREE.Box3();
  4854. }
  4855. var positions = this.attributes[ "position" ].array;
  4856. if ( positions ) {
  4857. var bb = this.boundingBox;
  4858. var x, y, z;
  4859. if( positions.length >= 3 ) {
  4860. bb.min.x = bb.max.x = positions[ 0 ];
  4861. bb.min.y = bb.max.y = positions[ 1 ];
  4862. bb.min.z = bb.max.z = positions[ 2 ];
  4863. }
  4864. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4865. x = positions[ i ];
  4866. y = positions[ i + 1 ];
  4867. z = positions[ i + 2 ];
  4868. // bounding box
  4869. if ( x < bb.min.x ) {
  4870. bb.min.x = x;
  4871. } else if ( x > bb.max.x ) {
  4872. bb.max.x = x;
  4873. }
  4874. if ( y < bb.min.y ) {
  4875. bb.min.y = y;
  4876. } else if ( y > bb.max.y ) {
  4877. bb.max.y = y;
  4878. }
  4879. if ( z < bb.min.z ) {
  4880. bb.min.z = z;
  4881. } else if ( z > bb.max.z ) {
  4882. bb.max.z = z;
  4883. }
  4884. }
  4885. }
  4886. if ( positions === undefined || positions.length === 0 ) {
  4887. this.boundingBox.min.set( 0, 0, 0 );
  4888. this.boundingBox.max.set( 0, 0, 0 );
  4889. }
  4890. },
  4891. computeBoundingSphere: function () {
  4892. if ( this.boundingSphere === null ) {
  4893. this.boundingSphere = new THREE.Sphere();
  4894. }
  4895. var positions = this.attributes[ "position" ].array;
  4896. if ( positions ) {
  4897. var radiusSq, maxRadiusSq = 0;
  4898. var x, y, z;
  4899. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4900. x = positions[ i ];
  4901. y = positions[ i + 1 ];
  4902. z = positions[ i + 2 ];
  4903. radiusSq = x * x + y * y + z * z;
  4904. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4905. }
  4906. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4907. }
  4908. },
  4909. computeVertexNormals: function () {
  4910. if ( this.attributes[ "position" ] ) {
  4911. var i, il;
  4912. var j, jl;
  4913. var nVertexElements = this.attributes[ "position" ].array.length;
  4914. if ( this.attributes[ "normal" ] === undefined ) {
  4915. this.attributes[ "normal" ] = {
  4916. itemSize: 3,
  4917. array: new Float32Array( nVertexElements ),
  4918. numItems: nVertexElements
  4919. };
  4920. } else {
  4921. // reset existing normals to zero
  4922. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4923. this.attributes[ "normal" ].array[ i ] = 0;
  4924. }
  4925. }
  4926. var positions = this.attributes[ "position" ].array;
  4927. var normals = this.attributes[ "normal" ].array;
  4928. var vA, vB, vC, x, y, z,
  4929. pA = new THREE.Vector3(),
  4930. pB = new THREE.Vector3(),
  4931. pC = new THREE.Vector3(),
  4932. cb = new THREE.Vector3(),
  4933. ab = new THREE.Vector3();
  4934. // indexed elements
  4935. if ( this.attributes[ "index" ] ) {
  4936. var indices = this.attributes[ "index" ].array;
  4937. var offsets = this.offsets;
  4938. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4939. var start = offsets[ j ].start;
  4940. var count = offsets[ j ].count;
  4941. var index = offsets[ j ].index;
  4942. for ( i = start, il = start + count; i < il; i += 3 ) {
  4943. vA = index + indices[ i ];
  4944. vB = index + indices[ i + 1 ];
  4945. vC = index + indices[ i + 2 ];
  4946. x = positions[ vA * 3 ];
  4947. y = positions[ vA * 3 + 1 ];
  4948. z = positions[ vA * 3 + 2 ];
  4949. pA.set( x, y, z );
  4950. x = positions[ vB * 3 ];
  4951. y = positions[ vB * 3 + 1 ];
  4952. z = positions[ vB * 3 + 2 ];
  4953. pB.set( x, y, z );
  4954. x = positions[ vC * 3 ];
  4955. y = positions[ vC * 3 + 1 ];
  4956. z = positions[ vC * 3 + 2 ];
  4957. pC.set( x, y, z );
  4958. cb.subVectors( pC, pB );
  4959. ab.subVectors( pA, pB );
  4960. cb.cross( ab );
  4961. normals[ vA * 3 ] += cb.x;
  4962. normals[ vA * 3 + 1 ] += cb.y;
  4963. normals[ vA * 3 + 2 ] += cb.z;
  4964. normals[ vB * 3 ] += cb.x;
  4965. normals[ vB * 3 + 1 ] += cb.y;
  4966. normals[ vB * 3 + 2 ] += cb.z;
  4967. normals[ vC * 3 ] += cb.x;
  4968. normals[ vC * 3 + 1 ] += cb.y;
  4969. normals[ vC * 3 + 2 ] += cb.z;
  4970. }
  4971. }
  4972. // non-indexed elements (unconnected triangle soup)
  4973. } else {
  4974. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4975. x = positions[ i ];
  4976. y = positions[ i + 1 ];
  4977. z = positions[ i + 2 ];
  4978. pA.set( x, y, z );
  4979. x = positions[ i + 3 ];
  4980. y = positions[ i + 4 ];
  4981. z = positions[ i + 5 ];
  4982. pB.set( x, y, z );
  4983. x = positions[ i + 6 ];
  4984. y = positions[ i + 7 ];
  4985. z = positions[ i + 8 ];
  4986. pC.set( x, y, z );
  4987. cb.subVectors( pC, pB );
  4988. ab.subVectors( pA, pB );
  4989. cb.cross( ab );
  4990. normals[ i ] = cb.x;
  4991. normals[ i + 1 ] = cb.y;
  4992. normals[ i + 2 ] = cb.z;
  4993. normals[ i + 3 ] = cb.x;
  4994. normals[ i + 4 ] = cb.y;
  4995. normals[ i + 5 ] = cb.z;
  4996. normals[ i + 6 ] = cb.x;
  4997. normals[ i + 7 ] = cb.y;
  4998. normals[ i + 8 ] = cb.z;
  4999. }
  5000. }
  5001. this.normalizeNormals();
  5002. this.normalsNeedUpdate = true;
  5003. }
  5004. },
  5005. normalizeNormals: function () {
  5006. var normals = this.attributes[ "normal" ].array;
  5007. var x, y, z, n;
  5008. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5009. x = normals[ i ];
  5010. y = normals[ i + 1 ];
  5011. z = normals[ i + 2 ];
  5012. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5013. normals[ i ] *= n;
  5014. normals[ i + 1 ] *= n;
  5015. normals[ i + 2 ] *= n;
  5016. }
  5017. },
  5018. computeTangents: function () {
  5019. // based on http://www.terathon.com/code/tangent.html
  5020. // (per vertex tangents)
  5021. if ( this.attributes[ "index" ] === undefined ||
  5022. this.attributes[ "position" ] === undefined ||
  5023. this.attributes[ "normal" ] === undefined ||
  5024. this.attributes[ "uv" ] === undefined ) {
  5025. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5026. return;
  5027. }
  5028. var indices = this.attributes[ "index" ].array;
  5029. var positions = this.attributes[ "position" ].array;
  5030. var normals = this.attributes[ "normal" ].array;
  5031. var uvs = this.attributes[ "uv" ].array;
  5032. var nVertices = positions.length / 3;
  5033. if ( this.attributes[ "tangent" ] === undefined ) {
  5034. var nTangentElements = 4 * nVertices;
  5035. this.attributes[ "tangent" ] = {
  5036. itemSize: 4,
  5037. array: new Float32Array( nTangentElements ),
  5038. numItems: nTangentElements
  5039. };
  5040. }
  5041. var tangents = this.attributes[ "tangent" ].array;
  5042. var tan1 = [], tan2 = [];
  5043. for ( var k = 0; k < nVertices; k ++ ) {
  5044. tan1[ k ] = new THREE.Vector3();
  5045. tan2[ k ] = new THREE.Vector3();
  5046. }
  5047. var xA, yA, zA,
  5048. xB, yB, zB,
  5049. xC, yC, zC,
  5050. uA, vA,
  5051. uB, vB,
  5052. uC, vC,
  5053. x1, x2, y1, y2, z1, z2,
  5054. s1, s2, t1, t2, r;
  5055. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5056. function handleTriangle( a, b, c ) {
  5057. xA = positions[ a * 3 ];
  5058. yA = positions[ a * 3 + 1 ];
  5059. zA = positions[ a * 3 + 2 ];
  5060. xB = positions[ b * 3 ];
  5061. yB = positions[ b * 3 + 1 ];
  5062. zB = positions[ b * 3 + 2 ];
  5063. xC = positions[ c * 3 ];
  5064. yC = positions[ c * 3 + 1 ];
  5065. zC = positions[ c * 3 + 2 ];
  5066. uA = uvs[ a * 2 ];
  5067. vA = uvs[ a * 2 + 1 ];
  5068. uB = uvs[ b * 2 ];
  5069. vB = uvs[ b * 2 + 1 ];
  5070. uC = uvs[ c * 2 ];
  5071. vC = uvs[ c * 2 + 1 ];
  5072. x1 = xB - xA;
  5073. x2 = xC - xA;
  5074. y1 = yB - yA;
  5075. y2 = yC - yA;
  5076. z1 = zB - zA;
  5077. z2 = zC - zA;
  5078. s1 = uB - uA;
  5079. s2 = uC - uA;
  5080. t1 = vB - vA;
  5081. t2 = vC - vA;
  5082. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5083. sdir.set(
  5084. ( t2 * x1 - t1 * x2 ) * r,
  5085. ( t2 * y1 - t1 * y2 ) * r,
  5086. ( t2 * z1 - t1 * z2 ) * r
  5087. );
  5088. tdir.set(
  5089. ( s1 * x2 - s2 * x1 ) * r,
  5090. ( s1 * y2 - s2 * y1 ) * r,
  5091. ( s1 * z2 - s2 * z1 ) * r
  5092. );
  5093. tan1[ a ].add( sdir );
  5094. tan1[ b ].add( sdir );
  5095. tan1[ c ].add( sdir );
  5096. tan2[ a ].add( tdir );
  5097. tan2[ b ].add( tdir );
  5098. tan2[ c ].add( tdir );
  5099. }
  5100. var i, il;
  5101. var j, jl;
  5102. var iA, iB, iC;
  5103. var offsets = this.offsets;
  5104. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5105. var start = offsets[ j ].start;
  5106. var count = offsets[ j ].count;
  5107. var index = offsets[ j ].index;
  5108. for ( i = start, il = start + count; i < il; i += 3 ) {
  5109. iA = index + indices[ i ];
  5110. iB = index + indices[ i + 1 ];
  5111. iC = index + indices[ i + 2 ];
  5112. handleTriangle( iA, iB, iC );
  5113. }
  5114. }
  5115. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5116. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5117. var w, t, test;
  5118. function handleVertex( v ) {
  5119. n.x = normals[ v * 3 ];
  5120. n.y = normals[ v * 3 + 1 ];
  5121. n.z = normals[ v * 3 + 2 ];
  5122. n2.copy( n );
  5123. t = tan1[ v ];
  5124. // Gram-Schmidt orthogonalize
  5125. tmp.copy( t );
  5126. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5127. // Calculate handedness
  5128. tmp2.crossVectors( n2, t );
  5129. test = tmp2.dot( tan2[ v ] );
  5130. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5131. tangents[ v * 4 ] = tmp.x;
  5132. tangents[ v * 4 + 1 ] = tmp.y;
  5133. tangents[ v * 4 + 2 ] = tmp.z;
  5134. tangents[ v * 4 + 3 ] = w;
  5135. }
  5136. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5137. var start = offsets[ j ].start;
  5138. var count = offsets[ j ].count;
  5139. var index = offsets[ j ].index;
  5140. for ( i = start, il = start + count; i < il; i += 3 ) {
  5141. iA = index + indices[ i ];
  5142. iB = index + indices[ i + 1 ];
  5143. iC = index + indices[ i + 2 ];
  5144. handleVertex( iA );
  5145. handleVertex( iB );
  5146. handleVertex( iC );
  5147. }
  5148. }
  5149. this.hasTangents = true;
  5150. this.tangentsNeedUpdate = true;
  5151. },
  5152. dispose: function () {
  5153. this.dispatchEvent( { type: 'dispose' } );
  5154. }
  5155. };
  5156. /**
  5157. * @author mrdoob / http://mrdoob.com/
  5158. * @author mikael emtinger / http://gomo.se/
  5159. * @author WestLangley / http://github.com/WestLangley
  5160. */
  5161. THREE.Camera = function () {
  5162. THREE.Object3D.call( this );
  5163. this.matrixWorldInverse = new THREE.Matrix4();
  5164. this.projectionMatrix = new THREE.Matrix4();
  5165. this.projectionMatrixInverse = new THREE.Matrix4();
  5166. };
  5167. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5168. THREE.Camera.prototype.lookAt = function () {
  5169. // This routine does not support cameras with rotated and/or translated parent(s)
  5170. var m1 = new THREE.Matrix4();
  5171. return function ( vector ) {
  5172. m1.lookAt( this.position, vector, this.up );
  5173. if ( this.useQuaternion === true ) {
  5174. this.quaternion.setFromRotationMatrix( m1 );
  5175. } else {
  5176. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5177. }
  5178. };
  5179. }();
  5180. /**
  5181. * @author alteredq / http://alteredqualia.com/
  5182. */
  5183. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5184. THREE.Camera.call( this );
  5185. this.left = left;
  5186. this.right = right;
  5187. this.top = top;
  5188. this.bottom = bottom;
  5189. this.near = ( near !== undefined ) ? near : 0.1;
  5190. this.far = ( far !== undefined ) ? far : 2000;
  5191. this.updateProjectionMatrix();
  5192. };
  5193. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5194. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5195. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5196. };
  5197. /**
  5198. * @author mrdoob / http://mrdoob.com/
  5199. * @author greggman / http://games.greggman.com/
  5200. * @author zz85 / http://www.lab4games.net/zz85/blog
  5201. */
  5202. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5203. THREE.Camera.call( this );
  5204. this.fov = fov !== undefined ? fov : 50;
  5205. this.aspect = aspect !== undefined ? aspect : 1;
  5206. this.near = near !== undefined ? near : 0.1;
  5207. this.far = far !== undefined ? far : 2000;
  5208. this.updateProjectionMatrix();
  5209. };
  5210. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5211. /**
  5212. * Uses Focal Length (in mm) to estimate and set FOV
  5213. * 35mm (fullframe) camera is used if frame size is not specified;
  5214. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5215. */
  5216. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5217. if ( frameHeight === undefined ) frameHeight = 24;
  5218. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5219. this.updateProjectionMatrix();
  5220. }
  5221. /**
  5222. * Sets an offset in a larger frustum. This is useful for multi-window or
  5223. * multi-monitor/multi-machine setups.
  5224. *
  5225. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5226. * the monitors are in grid like this
  5227. *
  5228. * +---+---+---+
  5229. * | A | B | C |
  5230. * +---+---+---+
  5231. * | D | E | F |
  5232. * +---+---+---+
  5233. *
  5234. * then for each monitor you would call it like this
  5235. *
  5236. * var w = 1920;
  5237. * var h = 1080;
  5238. * var fullWidth = w * 3;
  5239. * var fullHeight = h * 2;
  5240. *
  5241. * --A--
  5242. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5243. * --B--
  5244. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5245. * --C--
  5246. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5247. * --D--
  5248. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5249. * --E--
  5250. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5251. * --F--
  5252. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5253. *
  5254. * Note there is no reason monitors have to be the same size or in a grid.
  5255. */
  5256. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5257. this.fullWidth = fullWidth;
  5258. this.fullHeight = fullHeight;
  5259. this.x = x;
  5260. this.y = y;
  5261. this.width = width;
  5262. this.height = height;
  5263. this.updateProjectionMatrix();
  5264. };
  5265. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5266. if ( this.fullWidth ) {
  5267. var aspect = this.fullWidth / this.fullHeight;
  5268. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5269. var bottom = -top;
  5270. var left = aspect * bottom;
  5271. var right = aspect * top;
  5272. var width = Math.abs( right - left );
  5273. var height = Math.abs( top - bottom );
  5274. this.projectionMatrix.makeFrustum(
  5275. left + this.x * width / this.fullWidth,
  5276. left + ( this.x + this.width ) * width / this.fullWidth,
  5277. top - ( this.y + this.height ) * height / this.fullHeight,
  5278. top - this.y * height / this.fullHeight,
  5279. this.near,
  5280. this.far
  5281. );
  5282. } else {
  5283. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5284. }
  5285. };
  5286. /**
  5287. * @author mrdoob / http://mrdoob.com/
  5288. * @author alteredq / http://alteredqualia.com/
  5289. */
  5290. THREE.Light = function ( hex ) {
  5291. THREE.Object3D.call( this );
  5292. this.color = new THREE.Color( hex );
  5293. };
  5294. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5295. /**
  5296. * @author mrdoob / http://mrdoob.com/
  5297. */
  5298. THREE.AmbientLight = function ( hex ) {
  5299. THREE.Light.call( this, hex );
  5300. };
  5301. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5302. /**
  5303. * @author MPanknin / http://www.redplant.de/
  5304. * @author alteredq / http://alteredqualia.com/
  5305. */
  5306. THREE.AreaLight = function ( hex, intensity ) {
  5307. THREE.Light.call( this, hex );
  5308. this.normal = new THREE.Vector3( 0, -1, 0 );
  5309. this.right = new THREE.Vector3( 1, 0, 0 );
  5310. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5311. this.width = 1.0;
  5312. this.height = 1.0;
  5313. this.constantAttenuation = 1.5;
  5314. this.linearAttenuation = 0.5;
  5315. this.quadraticAttenuation = 0.1;
  5316. };
  5317. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5318. /**
  5319. * @author mrdoob / http://mrdoob.com/
  5320. * @author alteredq / http://alteredqualia.com/
  5321. */
  5322. THREE.DirectionalLight = function ( hex, intensity ) {
  5323. THREE.Light.call( this, hex );
  5324. this.position = new THREE.Vector3( 0, 1, 0 );
  5325. this.target = new THREE.Object3D();
  5326. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5327. this.castShadow = false;
  5328. this.onlyShadow = false;
  5329. //
  5330. this.shadowCameraNear = 50;
  5331. this.shadowCameraFar = 5000;
  5332. this.shadowCameraLeft = -500;
  5333. this.shadowCameraRight = 500;
  5334. this.shadowCameraTop = 500;
  5335. this.shadowCameraBottom = -500;
  5336. this.shadowCameraVisible = false;
  5337. this.shadowBias = 0;
  5338. this.shadowDarkness = 0.5;
  5339. this.shadowMapWidth = 512;
  5340. this.shadowMapHeight = 512;
  5341. //
  5342. this.shadowCascade = false;
  5343. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5344. this.shadowCascadeCount = 2;
  5345. this.shadowCascadeBias = [ 0, 0, 0 ];
  5346. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5347. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5348. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5349. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5350. this.shadowCascadeArray = [];
  5351. //
  5352. this.shadowMap = null;
  5353. this.shadowMapSize = null;
  5354. this.shadowCamera = null;
  5355. this.shadowMatrix = null;
  5356. };
  5357. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5358. /**
  5359. * @author alteredq / http://alteredqualia.com/
  5360. */
  5361. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5362. THREE.Light.call( this, skyColorHex );
  5363. this.groundColor = new THREE.Color( groundColorHex );
  5364. this.position = new THREE.Vector3( 0, 100, 0 );
  5365. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5366. };
  5367. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5368. /**
  5369. * @author mrdoob / http://mrdoob.com/
  5370. */
  5371. THREE.PointLight = function ( hex, intensity, distance ) {
  5372. THREE.Light.call( this, hex );
  5373. this.position = new THREE.Vector3( 0, 0, 0 );
  5374. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5375. this.distance = ( distance !== undefined ) ? distance : 0;
  5376. };
  5377. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5378. /**
  5379. * @author alteredq / http://alteredqualia.com/
  5380. */
  5381. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5382. THREE.Light.call( this, hex );
  5383. this.position = new THREE.Vector3( 0, 1, 0 );
  5384. this.target = new THREE.Object3D();
  5385. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5386. this.distance = ( distance !== undefined ) ? distance : 0;
  5387. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5388. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5389. this.castShadow = false;
  5390. this.onlyShadow = false;
  5391. //
  5392. this.shadowCameraNear = 50;
  5393. this.shadowCameraFar = 5000;
  5394. this.shadowCameraFov = 50;
  5395. this.shadowCameraVisible = false;
  5396. this.shadowBias = 0;
  5397. this.shadowDarkness = 0.5;
  5398. this.shadowMapWidth = 512;
  5399. this.shadowMapHeight = 512;
  5400. //
  5401. this.shadowMap = null;
  5402. this.shadowMapSize = null;
  5403. this.shadowCamera = null;
  5404. this.shadowMatrix = null;
  5405. };
  5406. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5407. /**
  5408. * @author alteredq / http://alteredqualia.com/
  5409. */
  5410. THREE.Loader = function ( showStatus ) {
  5411. this.showStatus = showStatus;
  5412. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5413. this.onLoadStart = function () {};
  5414. this.onLoadProgress = function () {};
  5415. this.onLoadComplete = function () {};
  5416. };
  5417. THREE.Loader.prototype = {
  5418. constructor: THREE.Loader,
  5419. crossOrigin: 'anonymous',
  5420. addStatusElement: function () {
  5421. var e = document.createElement( "div" );
  5422. e.style.position = "absolute";
  5423. e.style.right = "0px";
  5424. e.style.top = "0px";
  5425. e.style.fontSize = "0.8em";
  5426. e.style.textAlign = "left";
  5427. e.style.background = "rgba(0,0,0,0.25)";
  5428. e.style.color = "#fff";
  5429. e.style.width = "120px";
  5430. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5431. e.style.zIndex = 1000;
  5432. e.innerHTML = "Loading ...";
  5433. return e;
  5434. },
  5435. updateProgress: function ( progress ) {
  5436. var message = "Loaded ";
  5437. if ( progress.total ) {
  5438. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5439. } else {
  5440. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5441. }
  5442. this.statusDomElement.innerHTML = message;
  5443. },
  5444. extractUrlBase: function ( url ) {
  5445. var parts = url.split( '/' );
  5446. parts.pop();
  5447. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5448. },
  5449. initMaterials: function ( materials, texturePath ) {
  5450. var array = [];
  5451. for ( var i = 0; i < materials.length; ++ i ) {
  5452. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5453. }
  5454. return array;
  5455. },
  5456. needsTangents: function ( materials ) {
  5457. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5458. var m = materials[ i ];
  5459. if ( m instanceof THREE.ShaderMaterial ) return true;
  5460. }
  5461. return false;
  5462. },
  5463. createMaterial: function ( m, texturePath ) {
  5464. var _this = this;
  5465. function is_pow2( n ) {
  5466. var l = Math.log( n ) / Math.LN2;
  5467. return Math.floor( l ) == l;
  5468. }
  5469. function nearest_pow2( n ) {
  5470. var l = Math.log( n ) / Math.LN2;
  5471. return Math.pow( 2, Math.round( l ) );
  5472. }
  5473. function load_image( where, url ) {
  5474. var image = new Image();
  5475. image.onload = function () {
  5476. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5477. var width = nearest_pow2( this.width );
  5478. var height = nearest_pow2( this.height );
  5479. where.image.width = width;
  5480. where.image.height = height;
  5481. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5482. } else {
  5483. where.image = this;
  5484. }
  5485. where.needsUpdate = true;
  5486. };
  5487. image.crossOrigin = _this.crossOrigin;
  5488. image.src = url;
  5489. }
  5490. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5491. var isCompressed = /\.dds$/i.test( sourceFile );
  5492. var fullPath = texturePath + "/" + sourceFile;
  5493. if ( isCompressed ) {
  5494. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5495. where[ name ] = texture;
  5496. } else {
  5497. var texture = document.createElement( 'canvas' );
  5498. where[ name ] = new THREE.Texture( texture );
  5499. }
  5500. where[ name ].sourceFile = sourceFile;
  5501. if( repeat ) {
  5502. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5503. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5504. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5505. }
  5506. if ( offset ) {
  5507. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5508. }
  5509. if ( wrap ) {
  5510. var wrapMap = {
  5511. "repeat": THREE.RepeatWrapping,
  5512. "mirror": THREE.MirroredRepeatWrapping
  5513. }
  5514. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5515. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5516. }
  5517. if ( anisotropy ) {
  5518. where[ name ].anisotropy = anisotropy;
  5519. }
  5520. if ( ! isCompressed ) {
  5521. load_image( where[ name ], fullPath );
  5522. }
  5523. }
  5524. function rgb2hex( rgb ) {
  5525. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5526. }
  5527. // defaults
  5528. var mtype = "MeshLambertMaterial";
  5529. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5530. // parameters from model file
  5531. if ( m.shading ) {
  5532. var shading = m.shading.toLowerCase();
  5533. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5534. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5535. }
  5536. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5537. mpars.blending = THREE[ m.blending ];
  5538. }
  5539. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5540. mpars.transparent = m.transparent;
  5541. }
  5542. if ( m.depthTest !== undefined ) {
  5543. mpars.depthTest = m.depthTest;
  5544. }
  5545. if ( m.depthWrite !== undefined ) {
  5546. mpars.depthWrite = m.depthWrite;
  5547. }
  5548. if ( m.visible !== undefined ) {
  5549. mpars.visible = m.visible;
  5550. }
  5551. if ( m.flipSided !== undefined ) {
  5552. mpars.side = THREE.BackSide;
  5553. }
  5554. if ( m.doubleSided !== undefined ) {
  5555. mpars.side = THREE.DoubleSide;
  5556. }
  5557. if ( m.wireframe !== undefined ) {
  5558. mpars.wireframe = m.wireframe;
  5559. }
  5560. if ( m.vertexColors !== undefined ) {
  5561. if ( m.vertexColors === "face" ) {
  5562. mpars.vertexColors = THREE.FaceColors;
  5563. } else if ( m.vertexColors ) {
  5564. mpars.vertexColors = THREE.VertexColors;
  5565. }
  5566. }
  5567. // colors
  5568. if ( m.colorDiffuse ) {
  5569. mpars.color = rgb2hex( m.colorDiffuse );
  5570. } else if ( m.DbgColor ) {
  5571. mpars.color = m.DbgColor;
  5572. }
  5573. if ( m.colorSpecular ) {
  5574. mpars.specular = rgb2hex( m.colorSpecular );
  5575. }
  5576. if ( m.colorAmbient ) {
  5577. mpars.ambient = rgb2hex( m.colorAmbient );
  5578. }
  5579. // modifiers
  5580. if ( m.transparency ) {
  5581. mpars.opacity = m.transparency;
  5582. }
  5583. if ( m.specularCoef ) {
  5584. mpars.shininess = m.specularCoef;
  5585. }
  5586. // textures
  5587. if ( m.mapDiffuse && texturePath ) {
  5588. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5589. }
  5590. if ( m.mapLight && texturePath ) {
  5591. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5592. }
  5593. if ( m.mapBump && texturePath ) {
  5594. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5595. }
  5596. if ( m.mapNormal && texturePath ) {
  5597. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5598. }
  5599. if ( m.mapSpecular && texturePath ) {
  5600. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5601. }
  5602. //
  5603. if ( m.mapBumpScale ) {
  5604. mpars.bumpScale = m.mapBumpScale;
  5605. }
  5606. // special case for normal mapped material
  5607. if ( m.mapNormal ) {
  5608. var shader = THREE.ShaderLib[ "normalmap" ];
  5609. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5610. uniforms[ "tNormal" ].value = mpars.normalMap;
  5611. if ( m.mapNormalFactor ) {
  5612. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5613. }
  5614. if ( mpars.map ) {
  5615. uniforms[ "tDiffuse" ].value = mpars.map;
  5616. uniforms[ "enableDiffuse" ].value = true;
  5617. }
  5618. if ( mpars.specularMap ) {
  5619. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5620. uniforms[ "enableSpecular" ].value = true;
  5621. }
  5622. if ( mpars.lightMap ) {
  5623. uniforms[ "tAO" ].value = mpars.lightMap;
  5624. uniforms[ "enableAO" ].value = true;
  5625. }
  5626. // for the moment don't handle displacement texture
  5627. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5628. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5629. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5630. uniforms[ "uShininess" ].value = mpars.shininess;
  5631. if ( mpars.opacity !== undefined ) {
  5632. uniforms[ "uOpacity" ].value = mpars.opacity;
  5633. }
  5634. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5635. var material = new THREE.ShaderMaterial( parameters );
  5636. if ( mpars.transparent ) {
  5637. material.transparent = true;
  5638. }
  5639. } else {
  5640. var material = new THREE[ mtype ]( mpars );
  5641. }
  5642. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5643. return material;
  5644. }
  5645. };
  5646. /**
  5647. * @author mrdoob / http://mrdoob.com/
  5648. */
  5649. THREE.ImageLoader = function () {
  5650. THREE.EventDispatcher.call( this );
  5651. this.crossOrigin = null;
  5652. };
  5653. THREE.ImageLoader.prototype = {
  5654. constructor: THREE.ImageLoader,
  5655. load: function ( url, image ) {
  5656. var scope = this;
  5657. if ( image === undefined ) image = new Image();
  5658. image.addEventListener( 'load', function () {
  5659. scope.dispatchEvent( { type: 'load', content: image } );
  5660. }, false );
  5661. image.addEventListener( 'error', function () {
  5662. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5663. }, false );
  5664. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5665. image.src = url;
  5666. }
  5667. }
  5668. /**
  5669. * @author mrdoob / http://mrdoob.com/
  5670. * @author alteredq / http://alteredqualia.com/
  5671. */
  5672. THREE.JSONLoader = function ( showStatus ) {
  5673. THREE.Loader.call( this, showStatus );
  5674. this.withCredentials = false;
  5675. };
  5676. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5677. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5678. var scope = this;
  5679. // todo: unify load API to for easier SceneLoader use
  5680. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5681. this.onLoadStart();
  5682. this.loadAjaxJSON( this, url, callback, texturePath );
  5683. };
  5684. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5685. var xhr = new XMLHttpRequest();
  5686. var length = 0;
  5687. xhr.onreadystatechange = function () {
  5688. if ( xhr.readyState === xhr.DONE ) {
  5689. if ( xhr.status === 200 || xhr.status === 0 ) {
  5690. if ( xhr.responseText ) {
  5691. var json = JSON.parse( xhr.responseText );
  5692. var result = context.parse( json, texturePath );
  5693. callback( result.geometry, result.material );
  5694. } else {
  5695. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5696. }
  5697. // in context of more complex asset initialization
  5698. // do not block on single failed file
  5699. // maybe should go even one more level up
  5700. context.onLoadComplete();
  5701. } else {
  5702. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5703. }
  5704. } else if ( xhr.readyState === xhr.LOADING ) {
  5705. if ( callbackProgress ) {
  5706. if ( length === 0 ) {
  5707. length = xhr.getResponseHeader( "Content-Length" );
  5708. }
  5709. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5710. }
  5711. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5712. length = xhr.getResponseHeader( "Content-Length" );
  5713. }
  5714. };
  5715. xhr.open( "GET", url, true );
  5716. xhr.withCredentials = this.withCredentials;
  5717. xhr.send( null );
  5718. };
  5719. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  5720. var scope = this,
  5721. geometry = new THREE.Geometry(),
  5722. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5723. parseModel( scale );
  5724. parseSkin();
  5725. parseMorphing( scale );
  5726. geometry.computeCentroids();
  5727. geometry.computeFaceNormals();
  5728. function parseModel( scale ) {
  5729. function isBitSet( value, position ) {
  5730. return value & ( 1 << position );
  5731. }
  5732. var i, j, fi,
  5733. offset, zLength, nVertices,
  5734. colorIndex, normalIndex, uvIndex, materialIndex,
  5735. type,
  5736. isQuad,
  5737. hasMaterial,
  5738. hasFaceUv, hasFaceVertexUv,
  5739. hasFaceNormal, hasFaceVertexNormal,
  5740. hasFaceColor, hasFaceVertexColor,
  5741. vertex, face, color, normal,
  5742. uvLayer, uvs, u, v,
  5743. faces = json.faces,
  5744. vertices = json.vertices,
  5745. normals = json.normals,
  5746. colors = json.colors,
  5747. nUvLayers = 0;
  5748. // disregard empty arrays
  5749. for ( i = 0; i < json.uvs.length; i++ ) {
  5750. if ( json.uvs[ i ].length ) nUvLayers ++;
  5751. }
  5752. for ( i = 0; i < nUvLayers; i++ ) {
  5753. geometry.faceUvs[ i ] = [];
  5754. geometry.faceVertexUvs[ i ] = [];
  5755. }
  5756. offset = 0;
  5757. zLength = vertices.length;
  5758. while ( offset < zLength ) {
  5759. vertex = new THREE.Vector3();
  5760. vertex.x = vertices[ offset ++ ] * scale;
  5761. vertex.y = vertices[ offset ++ ] * scale;
  5762. vertex.z = vertices[ offset ++ ] * scale;
  5763. geometry.vertices.push( vertex );
  5764. }
  5765. offset = 0;
  5766. zLength = faces.length;
  5767. while ( offset < zLength ) {
  5768. type = faces[ offset ++ ];
  5769. isQuad = isBitSet( type, 0 );
  5770. hasMaterial = isBitSet( type, 1 );
  5771. hasFaceUv = isBitSet( type, 2 );
  5772. hasFaceVertexUv = isBitSet( type, 3 );
  5773. hasFaceNormal = isBitSet( type, 4 );
  5774. hasFaceVertexNormal = isBitSet( type, 5 );
  5775. hasFaceColor = isBitSet( type, 6 );
  5776. hasFaceVertexColor = isBitSet( type, 7 );
  5777. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5778. if ( isQuad ) {
  5779. face = new THREE.Face4();
  5780. face.a = faces[ offset ++ ];
  5781. face.b = faces[ offset ++ ];
  5782. face.c = faces[ offset ++ ];
  5783. face.d = faces[ offset ++ ];
  5784. nVertices = 4;
  5785. } else {
  5786. face = new THREE.Face3();
  5787. face.a = faces[ offset ++ ];
  5788. face.b = faces[ offset ++ ];
  5789. face.c = faces[ offset ++ ];
  5790. nVertices = 3;
  5791. }
  5792. if ( hasMaterial ) {
  5793. materialIndex = faces[ offset ++ ];
  5794. face.materialIndex = materialIndex;
  5795. }
  5796. // to get face <=> uv index correspondence
  5797. fi = geometry.faces.length;
  5798. if ( hasFaceUv ) {
  5799. for ( i = 0; i < nUvLayers; i++ ) {
  5800. uvLayer = json.uvs[ i ];
  5801. uvIndex = faces[ offset ++ ];
  5802. u = uvLayer[ uvIndex * 2 ];
  5803. v = uvLayer[ uvIndex * 2 + 1 ];
  5804. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5805. }
  5806. }
  5807. if ( hasFaceVertexUv ) {
  5808. for ( i = 0; i < nUvLayers; i++ ) {
  5809. uvLayer = json.uvs[ i ];
  5810. uvs = [];
  5811. for ( j = 0; j < nVertices; j ++ ) {
  5812. uvIndex = faces[ offset ++ ];
  5813. u = uvLayer[ uvIndex * 2 ];
  5814. v = uvLayer[ uvIndex * 2 + 1 ];
  5815. uvs[ j ] = new THREE.Vector2( u, v );
  5816. }
  5817. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5818. }
  5819. }
  5820. if ( hasFaceNormal ) {
  5821. normalIndex = faces[ offset ++ ] * 3;
  5822. normal = new THREE.Vector3();
  5823. normal.x = normals[ normalIndex ++ ];
  5824. normal.y = normals[ normalIndex ++ ];
  5825. normal.z = normals[ normalIndex ];
  5826. face.normal = normal;
  5827. }
  5828. if ( hasFaceVertexNormal ) {
  5829. for ( i = 0; i < nVertices; i++ ) {
  5830. normalIndex = faces[ offset ++ ] * 3;
  5831. normal = new THREE.Vector3();
  5832. normal.x = normals[ normalIndex ++ ];
  5833. normal.y = normals[ normalIndex ++ ];
  5834. normal.z = normals[ normalIndex ];
  5835. face.vertexNormals.push( normal );
  5836. }
  5837. }
  5838. if ( hasFaceColor ) {
  5839. colorIndex = faces[ offset ++ ];
  5840. color = new THREE.Color( colors[ colorIndex ] );
  5841. face.color = color;
  5842. }
  5843. if ( hasFaceVertexColor ) {
  5844. for ( i = 0; i < nVertices; i++ ) {
  5845. colorIndex = faces[ offset ++ ];
  5846. color = new THREE.Color( colors[ colorIndex ] );
  5847. face.vertexColors.push( color );
  5848. }
  5849. }
  5850. geometry.faces.push( face );
  5851. }
  5852. };
  5853. function parseSkin() {
  5854. var i, l, x, y, z, w, a, b, c, d;
  5855. if ( json.skinWeights ) {
  5856. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5857. x = json.skinWeights[ i ];
  5858. y = json.skinWeights[ i + 1 ];
  5859. z = 0;
  5860. w = 0;
  5861. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5862. }
  5863. }
  5864. if ( json.skinIndices ) {
  5865. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5866. a = json.skinIndices[ i ];
  5867. b = json.skinIndices[ i + 1 ];
  5868. c = 0;
  5869. d = 0;
  5870. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5871. }
  5872. }
  5873. geometry.bones = json.bones;
  5874. geometry.animation = json.animation;
  5875. };
  5876. function parseMorphing( scale ) {
  5877. if ( json.morphTargets !== undefined ) {
  5878. var i, l, v, vl, dstVertices, srcVertices;
  5879. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5880. geometry.morphTargets[ i ] = {};
  5881. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5882. geometry.morphTargets[ i ].vertices = [];
  5883. dstVertices = geometry.morphTargets[ i ].vertices;
  5884. srcVertices = json.morphTargets [ i ].vertices;
  5885. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5886. var vertex = new THREE.Vector3();
  5887. vertex.x = srcVertices[ v ] * scale;
  5888. vertex.y = srcVertices[ v + 1 ] * scale;
  5889. vertex.z = srcVertices[ v + 2 ] * scale;
  5890. dstVertices.push( vertex );
  5891. }
  5892. }
  5893. }
  5894. if ( json.morphColors !== undefined ) {
  5895. var i, l, c, cl, dstColors, srcColors, color;
  5896. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5897. geometry.morphColors[ i ] = {};
  5898. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5899. geometry.morphColors[ i ].colors = [];
  5900. dstColors = geometry.morphColors[ i ].colors;
  5901. srcColors = json.morphColors [ i ].colors;
  5902. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5903. color = new THREE.Color( 0xffaa00 );
  5904. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5905. dstColors.push( color );
  5906. }
  5907. }
  5908. }
  5909. };
  5910. var materials = this.initMaterials( json.materials, texturePath );
  5911. if ( this.needsTangents( materials ) ) {
  5912. geometry.computeTangents();
  5913. }
  5914. return {
  5915. geometry: geometry,
  5916. materials: materials
  5917. };
  5918. };
  5919. /**
  5920. * @author mrdoob / http://mrdoob.com/
  5921. */
  5922. THREE.LoadingMonitor = function () {
  5923. THREE.EventDispatcher.call( this );
  5924. var scope = this;
  5925. var loaded = 0;
  5926. var total = 0;
  5927. var onLoad = function ( event ) {
  5928. loaded ++;
  5929. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5930. if ( loaded === total ) {
  5931. scope.dispatchEvent( { type: 'load' } );
  5932. }
  5933. };
  5934. this.add = function ( loader ) {
  5935. total ++;
  5936. loader.addEventListener( 'load', onLoad, false );
  5937. };
  5938. };
  5939. /**
  5940. * @author alteredq / http://alteredqualia.com/
  5941. */
  5942. THREE.SceneLoader = function () {
  5943. this.onLoadStart = function () {};
  5944. this.onLoadProgress = function() {};
  5945. this.onLoadComplete = function () {};
  5946. this.callbackSync = function () {};
  5947. this.callbackProgress = function () {};
  5948. this.geometryHandlerMap = {};
  5949. this.hierarchyHandlerMap = {};
  5950. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5951. };
  5952. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5953. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5954. var scope = this;
  5955. var xhr = new XMLHttpRequest();
  5956. xhr.onreadystatechange = function () {
  5957. if ( xhr.readyState === 4 ) {
  5958. if ( xhr.status === 200 || xhr.status === 0 ) {
  5959. var json = JSON.parse( xhr.responseText );
  5960. scope.parse( json, callbackFinished, url );
  5961. } else {
  5962. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5963. }
  5964. }
  5965. };
  5966. xhr.open( "GET", url, true );
  5967. xhr.send( null );
  5968. };
  5969. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5970. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5971. };
  5972. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5973. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5974. };
  5975. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5976. var scope = this;
  5977. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5978. var geometry, material, camera, fog,
  5979. texture, images, color,
  5980. light, hex, intensity,
  5981. counter_models, counter_textures,
  5982. total_models, total_textures,
  5983. result;
  5984. var target_array = [];
  5985. var data = json;
  5986. // async geometry loaders
  5987. for ( var typeID in this.geometryHandlerMap ) {
  5988. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5989. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5990. }
  5991. // async hierachy loaders
  5992. for ( var typeID in this.hierarchyHandlerMap ) {
  5993. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5994. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5995. }
  5996. counter_models = 0;
  5997. counter_textures = 0;
  5998. result = {
  5999. scene: new THREE.Scene(),
  6000. geometries: {},
  6001. face_materials: {},
  6002. materials: {},
  6003. textures: {},
  6004. objects: {},
  6005. cameras: {},
  6006. lights: {},
  6007. fogs: {},
  6008. empties: {},
  6009. groups: {}
  6010. };
  6011. if ( data.transform ) {
  6012. var position = data.transform.position,
  6013. rotation = data.transform.rotation,
  6014. scale = data.transform.scale;
  6015. if ( position )
  6016. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6017. if ( rotation )
  6018. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6019. if ( scale )
  6020. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6021. if ( position || rotation || scale ) {
  6022. result.scene.updateMatrix();
  6023. result.scene.updateMatrixWorld();
  6024. }
  6025. }
  6026. function get_url( source_url, url_type ) {
  6027. if ( url_type == "relativeToHTML" ) {
  6028. return source_url;
  6029. } else {
  6030. return urlBase + "/" + source_url;
  6031. }
  6032. };
  6033. // toplevel loader function, delegates to handle_children
  6034. function handle_objects() {
  6035. handle_children( result.scene, data.objects );
  6036. }
  6037. // handle all the children from the loaded json and attach them to given parent
  6038. function handle_children( parent, children ) {
  6039. var mat, dst, pos, rot, scl, quat;
  6040. for ( var objID in children ) {
  6041. // check by id if child has already been handled,
  6042. // if not, create new object
  6043. if ( result.objects[ objID ] === undefined ) {
  6044. var objJSON = children[ objID ];
  6045. var object = null;
  6046. // meshes
  6047. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6048. if ( objJSON.loading === undefined ) {
  6049. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6050. "position": 1, "rotation": 1, "scale" : 1,
  6051. "visible": 1, "children": 1, "userData": 1,
  6052. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6053. var loaderParameters = {};
  6054. for ( var parType in objJSON ) {
  6055. if ( ! ( parType in reservedTypes ) ) {
  6056. loaderParameters[ parType ] = objJSON[ parType ];
  6057. }
  6058. }
  6059. material = result.materials[ objJSON.material ];
  6060. objJSON.loading = true;
  6061. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6062. // ColladaLoader
  6063. if ( loader.options ) {
  6064. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6065. // UTF8Loader
  6066. // OBJLoader
  6067. } else {
  6068. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6069. }
  6070. }
  6071. } else if ( objJSON.geometry !== undefined ) {
  6072. geometry = result.geometries[ objJSON.geometry ];
  6073. // geometry already loaded
  6074. if ( geometry ) {
  6075. var needsTangents = false;
  6076. material = result.materials[ objJSON.material ];
  6077. needsTangents = material instanceof THREE.ShaderMaterial;
  6078. pos = objJSON.position;
  6079. rot = objJSON.rotation;
  6080. scl = objJSON.scale;
  6081. mat = objJSON.matrix;
  6082. quat = objJSON.quaternion;
  6083. // use materials from the model file
  6084. // if there is no material specified in the object
  6085. if ( ! objJSON.material ) {
  6086. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6087. }
  6088. // use materials from the model file
  6089. // if there is just empty face material
  6090. // (must create new material as each model has its own face material)
  6091. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6092. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6093. }
  6094. if ( material instanceof THREE.MeshFaceMaterial ) {
  6095. for ( var i = 0; i < material.materials.length; i ++ ) {
  6096. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6097. }
  6098. }
  6099. if ( needsTangents ) {
  6100. geometry.computeTangents();
  6101. }
  6102. if ( objJSON.skin ) {
  6103. object = new THREE.SkinnedMesh( geometry, material );
  6104. } else if ( objJSON.morph ) {
  6105. object = new THREE.MorphAnimMesh( geometry, material );
  6106. if ( objJSON.duration !== undefined ) {
  6107. object.duration = objJSON.duration;
  6108. }
  6109. if ( objJSON.time !== undefined ) {
  6110. object.time = objJSON.time;
  6111. }
  6112. if ( objJSON.mirroredLoop !== undefined ) {
  6113. object.mirroredLoop = objJSON.mirroredLoop;
  6114. }
  6115. if ( material.morphNormals ) {
  6116. geometry.computeMorphNormals();
  6117. }
  6118. } else {
  6119. object = new THREE.Mesh( geometry, material );
  6120. }
  6121. object.name = objID;
  6122. if ( mat ) {
  6123. object.matrixAutoUpdate = false;
  6124. object.matrix.set(
  6125. mat[0], mat[1], mat[2], mat[3],
  6126. mat[4], mat[5], mat[6], mat[7],
  6127. mat[8], mat[9], mat[10], mat[11],
  6128. mat[12], mat[13], mat[14], mat[15]
  6129. );
  6130. } else {
  6131. object.position.set( pos[0], pos[1], pos[2] );
  6132. if ( quat ) {
  6133. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6134. object.useQuaternion = true;
  6135. } else {
  6136. object.rotation.set( rot[0], rot[1], rot[2] );
  6137. }
  6138. object.scale.set( scl[0], scl[1], scl[2] );
  6139. }
  6140. object.visible = objJSON.visible;
  6141. object.castShadow = objJSON.castShadow;
  6142. object.receiveShadow = objJSON.receiveShadow;
  6143. parent.add( object );
  6144. result.objects[ objID ] = object;
  6145. }
  6146. // lights
  6147. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6148. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6149. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6150. if ( objJSON.type === "DirectionalLight" ) {
  6151. pos = objJSON.direction;
  6152. light = new THREE.DirectionalLight( hex, intensity );
  6153. light.position.set( pos[0], pos[1], pos[2] );
  6154. if ( objJSON.target ) {
  6155. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6156. // kill existing default target
  6157. // otherwise it gets added to scene when parent gets added
  6158. light.target = null;
  6159. }
  6160. } else if ( objJSON.type === "PointLight" ) {
  6161. pos = objJSON.position;
  6162. dst = objJSON.distance;
  6163. light = new THREE.PointLight( hex, intensity, dst );
  6164. light.position.set( pos[0], pos[1], pos[2] );
  6165. } else if ( objJSON.type === "AmbientLight" ) {
  6166. light = new THREE.AmbientLight( hex );
  6167. }
  6168. parent.add( light );
  6169. light.name = objID;
  6170. result.lights[ objID ] = light;
  6171. result.objects[ objID ] = light;
  6172. // cameras
  6173. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6174. if ( objJSON.type === "PerspectiveCamera" ) {
  6175. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6176. } else if ( objJSON.type === "OrthographicCamera" ) {
  6177. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6178. }
  6179. pos = objJSON.position;
  6180. camera.position.set( pos[0], pos[1], pos[2] );
  6181. parent.add( camera );
  6182. camera.name = objID;
  6183. result.cameras[ objID ] = camera;
  6184. result.objects[ objID ] = camera;
  6185. // pure Object3D
  6186. } else {
  6187. pos = objJSON.position;
  6188. rot = objJSON.rotation;
  6189. scl = objJSON.scale;
  6190. quat = objJSON.quaternion;
  6191. object = new THREE.Object3D();
  6192. object.name = objID;
  6193. object.position.set( pos[0], pos[1], pos[2] );
  6194. if ( quat ) {
  6195. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6196. object.useQuaternion = true;
  6197. } else {
  6198. object.rotation.set( rot[0], rot[1], rot[2] );
  6199. }
  6200. object.scale.set( scl[0], scl[1], scl[2] );
  6201. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6202. parent.add( object );
  6203. result.objects[ objID ] = object;
  6204. result.empties[ objID ] = object;
  6205. }
  6206. if ( object ) {
  6207. if ( objJSON.userData !== undefined ) {
  6208. for ( var key in objJSON.userData ) {
  6209. var value = objJSON.userData[ key ];
  6210. object.userData[ key ] = value;
  6211. }
  6212. }
  6213. if ( objJSON.groups !== undefined ) {
  6214. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6215. var groupID = objJSON.groups[ i ];
  6216. if ( result.groups[ groupID ] === undefined ) {
  6217. result.groups[ groupID ] = [];
  6218. }
  6219. result.groups[ groupID ].push( objID );
  6220. }
  6221. }
  6222. if ( objJSON.children !== undefined ) {
  6223. handle_children( object, objJSON.children );
  6224. }
  6225. }
  6226. }
  6227. }
  6228. };
  6229. function handle_mesh( geo, mat, id ) {
  6230. result.geometries[ id ] = geo;
  6231. result.face_materials[ id ] = mat;
  6232. handle_objects();
  6233. };
  6234. function handle_hierarchy( node, id, parent, material, obj ) {
  6235. var p = obj.position;
  6236. var r = obj.rotation;
  6237. var q = obj.quaternion;
  6238. var s = obj.scale;
  6239. node.position.set( p[0], p[1], p[2] );
  6240. if ( q ) {
  6241. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6242. node.useQuaternion = true;
  6243. } else {
  6244. node.rotation.set( r[0], r[1], r[2] );
  6245. }
  6246. node.scale.set( s[0], s[1], s[2] );
  6247. // override children materials
  6248. // if object material was specified in JSON explicitly
  6249. if ( material ) {
  6250. node.traverse( function ( child ) {
  6251. child.material = material;
  6252. } );
  6253. }
  6254. // override children visibility
  6255. // with root node visibility as specified in JSON
  6256. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6257. node.traverse( function ( child ) {
  6258. child.visible = visible;
  6259. } );
  6260. parent.add( node );
  6261. node.name = id;
  6262. result.objects[ id ] = node;
  6263. handle_objects();
  6264. };
  6265. function create_callback_geometry( id ) {
  6266. return function( geo, mat ) {
  6267. handle_mesh( geo, mat, id );
  6268. counter_models -= 1;
  6269. scope.onLoadComplete();
  6270. async_callback_gate();
  6271. }
  6272. };
  6273. function create_callback_hierachy( id, parent, material, obj ) {
  6274. return function( event ) {
  6275. var result;
  6276. // loaders which use EventDispatcher
  6277. if ( event.content ) {
  6278. result = event.content;
  6279. // ColladaLoader
  6280. } else if ( event.dae ) {
  6281. result = event.scene;
  6282. // UTF8Loader
  6283. } else {
  6284. result = event;
  6285. }
  6286. handle_hierarchy( result, id, parent, material, obj );
  6287. counter_models -= 1;
  6288. scope.onLoadComplete();
  6289. async_callback_gate();
  6290. }
  6291. };
  6292. function create_callback_embed( id ) {
  6293. return function( geo, mat ) {
  6294. result.geometries[ id ] = geo;
  6295. result.face_materials[ id ] = mat;
  6296. }
  6297. };
  6298. function async_callback_gate() {
  6299. var progress = {
  6300. totalModels : total_models,
  6301. totalTextures : total_textures,
  6302. loadedModels : total_models - counter_models,
  6303. loadedTextures : total_textures - counter_textures
  6304. };
  6305. scope.callbackProgress( progress, result );
  6306. scope.onLoadProgress();
  6307. if ( counter_models === 0 && counter_textures === 0 ) {
  6308. finalize();
  6309. callbackFinished( result );
  6310. }
  6311. };
  6312. function finalize() {
  6313. // take care of targets which could be asynchronously loaded objects
  6314. for ( var i = 0; i < target_array.length; i ++ ) {
  6315. var ta = target_array[ i ];
  6316. var target = result.objects[ ta.targetName ];
  6317. if ( target ) {
  6318. ta.object.target = target;
  6319. } else {
  6320. // if there was error and target of specified name doesn't exist in the scene file
  6321. // create instead dummy target
  6322. // (target must be added to scene explicitly as parent is already added)
  6323. ta.object.target = new THREE.Object3D();
  6324. result.scene.add( ta.object.target );
  6325. }
  6326. ta.object.target.userData.targetInverse = ta.object;
  6327. }
  6328. };
  6329. var callbackTexture = function ( count ) {
  6330. counter_textures -= count;
  6331. async_callback_gate();
  6332. scope.onLoadComplete();
  6333. };
  6334. // must use this instead of just directly calling callbackTexture
  6335. // because of closure in the calling context loop
  6336. var generateTextureCallback = function ( count ) {
  6337. return function() {
  6338. callbackTexture( count );
  6339. };
  6340. };
  6341. // first go synchronous elements
  6342. // fogs
  6343. var fogID, fogJSON;
  6344. for ( fogID in data.fogs ) {
  6345. fogJSON = data.fogs[ fogID ];
  6346. if ( fogJSON.type === "linear" ) {
  6347. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6348. } else if ( fogJSON.type === "exp2" ) {
  6349. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6350. }
  6351. color = fogJSON.color;
  6352. fog.color.setRGB( color[0], color[1], color[2] );
  6353. result.fogs[ fogID ] = fog;
  6354. }
  6355. // now come potentially asynchronous elements
  6356. // geometries
  6357. // count how many geometries will be loaded asynchronously
  6358. var geoID, geoJSON;
  6359. for ( geoID in data.geometries ) {
  6360. geoJSON = data.geometries[ geoID ];
  6361. if ( geoJSON.type in this.geometryHandlerMap ) {
  6362. counter_models += 1;
  6363. scope.onLoadStart();
  6364. }
  6365. }
  6366. // count how many hierarchies will be loaded asynchronously
  6367. var objID, objJSON;
  6368. for ( objID in data.objects ) {
  6369. objJSON = data.objects[ objID ];
  6370. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6371. counter_models += 1;
  6372. scope.onLoadStart();
  6373. }
  6374. }
  6375. total_models = counter_models;
  6376. for ( geoID in data.geometries ) {
  6377. geoJSON = data.geometries[ geoID ];
  6378. if ( geoJSON.type === "cube" ) {
  6379. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6380. result.geometries[ geoID ] = geometry;
  6381. } else if ( geoJSON.type === "plane" ) {
  6382. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6383. result.geometries[ geoID ] = geometry;
  6384. } else if ( geoJSON.type === "sphere" ) {
  6385. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6386. result.geometries[ geoID ] = geometry;
  6387. } else if ( geoJSON.type === "cylinder" ) {
  6388. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6389. result.geometries[ geoID ] = geometry;
  6390. } else if ( geoJSON.type === "torus" ) {
  6391. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6392. result.geometries[ geoID ] = geometry;
  6393. } else if ( geoJSON.type === "icosahedron" ) {
  6394. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6395. result.geometries[ geoID ] = geometry;
  6396. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6397. var loaderParameters = {};
  6398. for ( var parType in geoJSON ) {
  6399. if ( parType !== "type" && parType !== "url" ) {
  6400. loaderParameters[ parType ] = geoJSON[ parType ];
  6401. }
  6402. }
  6403. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6404. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6405. } else if ( geoJSON.type === "embedded" ) {
  6406. var modelJson = data.embeds[ geoJSON.id ],
  6407. texture_path = "";
  6408. // pass metadata along to jsonLoader so it knows the format version
  6409. modelJson.metadata = data.metadata;
  6410. if ( modelJson ) {
  6411. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6412. var model = jsonLoader.parse( modelJson, texture_path );
  6413. create_callback_embed( geoID )( model.geometry, model.material );
  6414. }
  6415. }
  6416. }
  6417. // textures
  6418. // count how many textures will be loaded asynchronously
  6419. var textureID, textureJSON;
  6420. for ( textureID in data.textures ) {
  6421. textureJSON = data.textures[ textureID ];
  6422. if ( textureJSON.url instanceof Array ) {
  6423. counter_textures += textureJSON.url.length;
  6424. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6425. scope.onLoadStart();
  6426. }
  6427. } else {
  6428. counter_textures += 1;
  6429. scope.onLoadStart();
  6430. }
  6431. }
  6432. total_textures = counter_textures;
  6433. for ( textureID in data.textures ) {
  6434. textureJSON = data.textures[ textureID ];
  6435. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6436. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6437. }
  6438. if ( textureJSON.url instanceof Array ) {
  6439. var count = textureJSON.url.length;
  6440. var url_array = [];
  6441. for( var i = 0; i < count; i ++ ) {
  6442. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6443. }
  6444. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6445. if ( isCompressed ) {
  6446. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6447. } else {
  6448. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6449. }
  6450. } else {
  6451. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6452. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6453. var textureCallback = generateTextureCallback( 1 );
  6454. if ( isCompressed ) {
  6455. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6456. } else {
  6457. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6458. }
  6459. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6460. texture.minFilter = THREE[ textureJSON.minFilter ];
  6461. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6462. texture.magFilter = THREE[ textureJSON.magFilter ];
  6463. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6464. if ( textureJSON.repeat ) {
  6465. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6466. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6467. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6468. }
  6469. if ( textureJSON.offset ) {
  6470. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6471. }
  6472. // handle wrap after repeat so that default repeat can be overriden
  6473. if ( textureJSON.wrap ) {
  6474. var wrapMap = {
  6475. "repeat" : THREE.RepeatWrapping,
  6476. "mirror" : THREE.MirroredRepeatWrapping
  6477. }
  6478. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6479. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6480. }
  6481. }
  6482. result.textures[ textureID ] = texture;
  6483. }
  6484. // materials
  6485. var matID, matJSON;
  6486. var parID;
  6487. for ( matID in data.materials ) {
  6488. matJSON = data.materials[ matID ];
  6489. for ( parID in matJSON.parameters ) {
  6490. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6491. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6492. } else if ( parID === "shading" ) {
  6493. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6494. } else if ( parID === "side" ) {
  6495. if ( matJSON.parameters[ parID ] == "double" ) {
  6496. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6497. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6498. matJSON.parameters[ parID ] = THREE.BackSide;
  6499. } else {
  6500. matJSON.parameters[ parID ] = THREE.FrontSide;
  6501. }
  6502. } else if ( parID === "blending" ) {
  6503. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6504. } else if ( parID === "combine" ) {
  6505. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6506. } else if ( parID === "vertexColors" ) {
  6507. if ( matJSON.parameters[ parID ] == "face" ) {
  6508. matJSON.parameters[ parID ] = THREE.FaceColors;
  6509. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6510. } else if ( matJSON.parameters[ parID ] ) {
  6511. matJSON.parameters[ parID ] = THREE.VertexColors;
  6512. }
  6513. } else if ( parID === "wrapRGB" ) {
  6514. var v3 = matJSON.parameters[ parID ];
  6515. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6516. }
  6517. }
  6518. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6519. matJSON.parameters.transparent = true;
  6520. }
  6521. if ( matJSON.parameters.normalMap ) {
  6522. var shader = THREE.ShaderLib[ "normalmap" ];
  6523. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6524. var diffuse = matJSON.parameters.color;
  6525. var specular = matJSON.parameters.specular;
  6526. var ambient = matJSON.parameters.ambient;
  6527. var shininess = matJSON.parameters.shininess;
  6528. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6529. if ( matJSON.parameters.normalScale ) {
  6530. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6531. }
  6532. if ( matJSON.parameters.map ) {
  6533. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6534. uniforms[ "enableDiffuse" ].value = true;
  6535. }
  6536. if ( matJSON.parameters.envMap ) {
  6537. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6538. uniforms[ "enableReflection" ].value = true;
  6539. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6540. }
  6541. if ( matJSON.parameters.lightMap ) {
  6542. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6543. uniforms[ "enableAO" ].value = true;
  6544. }
  6545. if ( matJSON.parameters.specularMap ) {
  6546. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6547. uniforms[ "enableSpecular" ].value = true;
  6548. }
  6549. if ( matJSON.parameters.displacementMap ) {
  6550. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6551. uniforms[ "enableDisplacement" ].value = true;
  6552. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6553. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6554. }
  6555. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6556. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6557. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6558. uniforms[ "uShininess" ].value = shininess;
  6559. if ( matJSON.parameters.opacity ) {
  6560. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6561. }
  6562. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6563. material = new THREE.ShaderMaterial( parameters );
  6564. } else {
  6565. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6566. }
  6567. result.materials[ matID ] = material;
  6568. }
  6569. // second pass through all materials to initialize MeshFaceMaterials
  6570. // that could be referring to other materials out of order
  6571. for ( matID in data.materials ) {
  6572. matJSON = data.materials[ matID ];
  6573. if ( matJSON.parameters.materials ) {
  6574. var materialArray = [];
  6575. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6576. var label = matJSON.parameters.materials[ i ];
  6577. materialArray.push( result.materials[ label ] );
  6578. }
  6579. result.materials[ matID ].materials = materialArray;
  6580. }
  6581. }
  6582. // objects ( synchronous init of procedural primitives )
  6583. handle_objects();
  6584. // defaults
  6585. if ( result.cameras && data.defaults.camera ) {
  6586. result.currentCamera = result.cameras[ data.defaults.camera ];
  6587. }
  6588. if ( result.fogs && data.defaults.fog ) {
  6589. result.scene.fog = result.fogs[ data.defaults.fog ];
  6590. }
  6591. // synchronous callback
  6592. scope.callbackSync( result );
  6593. // just in case there are no async elements
  6594. async_callback_gate();
  6595. };
  6596. /**
  6597. * @author mrdoob / http://mrdoob.com/
  6598. */
  6599. THREE.TextureLoader = function () {
  6600. THREE.EventDispatcher.call( this );
  6601. this.crossOrigin = null;
  6602. };
  6603. THREE.TextureLoader.prototype = {
  6604. constructor: THREE.TextureLoader,
  6605. load: function ( url ) {
  6606. var scope = this;
  6607. var image = new Image();
  6608. image.addEventListener( 'load', function () {
  6609. var texture = new THREE.Texture( image );
  6610. texture.needsUpdate = true;
  6611. scope.dispatchEvent( { type: 'load', content: texture } );
  6612. }, false );
  6613. image.addEventListener( 'error', function () {
  6614. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6615. }, false );
  6616. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6617. image.src = url;
  6618. }
  6619. }
  6620. /**
  6621. * @author mrdoob / http://mrdoob.com/
  6622. * @author alteredq / http://alteredqualia.com/
  6623. */
  6624. THREE.Material = function () {
  6625. THREE.EventDispatcher.call( this );
  6626. this.id = THREE.MaterialIdCount ++;
  6627. this.name = '';
  6628. this.side = THREE.FrontSide;
  6629. this.opacity = 1;
  6630. this.transparent = false;
  6631. this.blending = THREE.NormalBlending;
  6632. this.blendSrc = THREE.SrcAlphaFactor;
  6633. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6634. this.blendEquation = THREE.AddEquation;
  6635. this.depthTest = true;
  6636. this.depthWrite = true;
  6637. this.polygonOffset = false;
  6638. this.polygonOffsetFactor = 0;
  6639. this.polygonOffsetUnits = 0;
  6640. this.alphaTest = 0;
  6641. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6642. this.visible = true;
  6643. this.needsUpdate = true;
  6644. };
  6645. THREE.Material.prototype.setValues = function ( values ) {
  6646. if ( values === undefined ) return;
  6647. for ( var key in values ) {
  6648. var newValue = values[ key ];
  6649. if ( newValue === undefined ) {
  6650. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6651. continue;
  6652. }
  6653. if ( key in this ) {
  6654. var currentValue = this[ key ];
  6655. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6656. currentValue.copy( newValue );
  6657. } else if ( currentValue instanceof THREE.Color ) {
  6658. currentValue.set( newValue );
  6659. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6660. currentValue.copy( newValue );
  6661. } else {
  6662. this[ key ] = newValue;
  6663. }
  6664. }
  6665. }
  6666. };
  6667. THREE.Material.prototype.clone = function ( material ) {
  6668. if ( material === undefined ) material = new THREE.Material();
  6669. material.name = this.name;
  6670. material.side = this.side;
  6671. material.opacity = this.opacity;
  6672. material.transparent = this.transparent;
  6673. material.blending = this.blending;
  6674. material.blendSrc = this.blendSrc;
  6675. material.blendDst = this.blendDst;
  6676. material.blendEquation = this.blendEquation;
  6677. material.depthTest = this.depthTest;
  6678. material.depthWrite = this.depthWrite;
  6679. material.polygonOffset = this.polygonOffset;
  6680. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6681. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6682. material.alphaTest = this.alphaTest;
  6683. material.overdraw = this.overdraw;
  6684. material.visible = this.visible;
  6685. return material;
  6686. };
  6687. THREE.Material.prototype.dispose = function () {
  6688. this.dispatchEvent( { type: 'dispose' } );
  6689. };
  6690. THREE.MaterialIdCount = 0;
  6691. /**
  6692. * @author mrdoob / http://mrdoob.com/
  6693. * @author alteredq / http://alteredqualia.com/
  6694. *
  6695. * parameters = {
  6696. * color: <hex>,
  6697. * opacity: <float>,
  6698. *
  6699. * blending: THREE.NormalBlending,
  6700. * depthTest: <bool>,
  6701. * depthWrite: <bool>,
  6702. *
  6703. * linewidth: <float>,
  6704. * linecap: "round",
  6705. * linejoin: "round",
  6706. *
  6707. * vertexColors: <bool>
  6708. *
  6709. * fog: <bool>
  6710. * }
  6711. */
  6712. THREE.LineBasicMaterial = function ( parameters ) {
  6713. THREE.Material.call( this );
  6714. this.color = new THREE.Color( 0xffffff );
  6715. this.linewidth = 1;
  6716. this.linecap = 'round';
  6717. this.linejoin = 'round';
  6718. this.vertexColors = false;
  6719. this.fog = true;
  6720. this.setValues( parameters );
  6721. };
  6722. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6723. THREE.LineBasicMaterial.prototype.clone = function () {
  6724. var material = new THREE.LineBasicMaterial();
  6725. THREE.Material.prototype.clone.call( this, material );
  6726. material.color.copy( this.color );
  6727. material.linewidth = this.linewidth;
  6728. material.linecap = this.linecap;
  6729. material.linejoin = this.linejoin;
  6730. material.vertexColors = this.vertexColors;
  6731. material.fog = this.fog;
  6732. return material;
  6733. };
  6734. /**
  6735. * @author alteredq / http://alteredqualia.com/
  6736. *
  6737. * parameters = {
  6738. * color: <hex>,
  6739. * opacity: <float>,
  6740. *
  6741. * blending: THREE.NormalBlending,
  6742. * depthTest: <bool>,
  6743. * depthWrite: <bool>,
  6744. *
  6745. * linewidth: <float>,
  6746. *
  6747. * scale: <float>,
  6748. * dashSize: <float>,
  6749. * gapSize: <float>,
  6750. *
  6751. * vertexColors: <bool>
  6752. *
  6753. * fog: <bool>
  6754. * }
  6755. */
  6756. THREE.LineDashedMaterial = function ( parameters ) {
  6757. THREE.Material.call( this );
  6758. this.color = new THREE.Color( 0xffffff );
  6759. this.linewidth = 1;
  6760. this.scale = 1;
  6761. this.dashSize = 3;
  6762. this.gapSize = 1;
  6763. this.vertexColors = false;
  6764. this.fog = true;
  6765. this.setValues( parameters );
  6766. };
  6767. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6768. THREE.LineDashedMaterial.prototype.clone = function () {
  6769. var material = new THREE.LineDashedMaterial();
  6770. THREE.Material.prototype.clone.call( this, material );
  6771. material.color.copy( this.color );
  6772. material.linewidth = this.linewidth;
  6773. material.scale = this.scale;
  6774. material.dashSize = this.dashSize;
  6775. material.gapSize = this.gapSize;
  6776. material.vertexColors = this.vertexColors;
  6777. material.fog = this.fog;
  6778. return material;
  6779. };
  6780. /**
  6781. * @author mrdoob / http://mrdoob.com/
  6782. * @author alteredq / http://alteredqualia.com/
  6783. *
  6784. * parameters = {
  6785. * color: <hex>,
  6786. * opacity: <float>,
  6787. * map: new THREE.Texture( <Image> ),
  6788. *
  6789. * lightMap: new THREE.Texture( <Image> ),
  6790. *
  6791. * specularMap: new THREE.Texture( <Image> ),
  6792. *
  6793. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6794. * combine: THREE.Multiply,
  6795. * reflectivity: <float>,
  6796. * refractionRatio: <float>,
  6797. *
  6798. * shading: THREE.SmoothShading,
  6799. * blending: THREE.NormalBlending,
  6800. * depthTest: <bool>,
  6801. * depthWrite: <bool>,
  6802. *
  6803. * wireframe: <boolean>,
  6804. * wireframeLinewidth: <float>,
  6805. *
  6806. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6807. *
  6808. * skinning: <bool>,
  6809. * morphTargets: <bool>,
  6810. *
  6811. * fog: <bool>
  6812. * }
  6813. */
  6814. THREE.MeshBasicMaterial = function ( parameters ) {
  6815. THREE.Material.call( this );
  6816. this.color = new THREE.Color( 0xffffff ); // emissive
  6817. this.map = null;
  6818. this.lightMap = null;
  6819. this.specularMap = null;
  6820. this.envMap = null;
  6821. this.combine = THREE.MultiplyOperation;
  6822. this.reflectivity = 1;
  6823. this.refractionRatio = 0.98;
  6824. this.fog = true;
  6825. this.shading = THREE.SmoothShading;
  6826. this.wireframe = false;
  6827. this.wireframeLinewidth = 1;
  6828. this.wireframeLinecap = 'round';
  6829. this.wireframeLinejoin = 'round';
  6830. this.vertexColors = THREE.NoColors;
  6831. this.skinning = false;
  6832. this.morphTargets = false;
  6833. this.setValues( parameters );
  6834. };
  6835. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6836. THREE.MeshBasicMaterial.prototype.clone = function () {
  6837. var material = new THREE.MeshBasicMaterial();
  6838. THREE.Material.prototype.clone.call( this, material );
  6839. material.color.copy( this.color );
  6840. material.map = this.map;
  6841. material.lightMap = this.lightMap;
  6842. material.specularMap = this.specularMap;
  6843. material.envMap = this.envMap;
  6844. material.combine = this.combine;
  6845. material.reflectivity = this.reflectivity;
  6846. material.refractionRatio = this.refractionRatio;
  6847. material.fog = this.fog;
  6848. material.shading = this.shading;
  6849. material.wireframe = this.wireframe;
  6850. material.wireframeLinewidth = this.wireframeLinewidth;
  6851. material.wireframeLinecap = this.wireframeLinecap;
  6852. material.wireframeLinejoin = this.wireframeLinejoin;
  6853. material.vertexColors = this.vertexColors;
  6854. material.skinning = this.skinning;
  6855. material.morphTargets = this.morphTargets;
  6856. return material;
  6857. };
  6858. /**
  6859. * @author mrdoob / http://mrdoob.com/
  6860. * @author alteredq / http://alteredqualia.com/
  6861. *
  6862. * parameters = {
  6863. * color: <hex>,
  6864. * ambient: <hex>,
  6865. * emissive: <hex>,
  6866. * opacity: <float>,
  6867. *
  6868. * map: new THREE.Texture( <Image> ),
  6869. *
  6870. * lightMap: new THREE.Texture( <Image> ),
  6871. *
  6872. * specularMap: new THREE.Texture( <Image> ),
  6873. *
  6874. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6875. * combine: THREE.Multiply,
  6876. * reflectivity: <float>,
  6877. * refractionRatio: <float>,
  6878. *
  6879. * shading: THREE.SmoothShading,
  6880. * blending: THREE.NormalBlending,
  6881. * depthTest: <bool>,
  6882. * depthWrite: <bool>,
  6883. *
  6884. * wireframe: <boolean>,
  6885. * wireframeLinewidth: <float>,
  6886. *
  6887. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6888. *
  6889. * skinning: <bool>,
  6890. * morphTargets: <bool>,
  6891. * morphNormals: <bool>,
  6892. *
  6893. * fog: <bool>
  6894. * }
  6895. */
  6896. THREE.MeshLambertMaterial = function ( parameters ) {
  6897. THREE.Material.call( this );
  6898. this.color = new THREE.Color( 0xffffff ); // diffuse
  6899. this.ambient = new THREE.Color( 0xffffff );
  6900. this.emissive = new THREE.Color( 0x000000 );
  6901. this.wrapAround = false;
  6902. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6903. this.map = null;
  6904. this.lightMap = null;
  6905. this.specularMap = null;
  6906. this.envMap = null;
  6907. this.combine = THREE.MultiplyOperation;
  6908. this.reflectivity = 1;
  6909. this.refractionRatio = 0.98;
  6910. this.fog = true;
  6911. this.shading = THREE.SmoothShading;
  6912. this.wireframe = false;
  6913. this.wireframeLinewidth = 1;
  6914. this.wireframeLinecap = 'round';
  6915. this.wireframeLinejoin = 'round';
  6916. this.vertexColors = THREE.NoColors;
  6917. this.skinning = false;
  6918. this.morphTargets = false;
  6919. this.morphNormals = false;
  6920. this.setValues( parameters );
  6921. };
  6922. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6923. THREE.MeshLambertMaterial.prototype.clone = function () {
  6924. var material = new THREE.MeshLambertMaterial();
  6925. THREE.Material.prototype.clone.call( this, material );
  6926. material.color.copy( this.color );
  6927. material.ambient.copy( this.ambient );
  6928. material.emissive.copy( this.emissive );
  6929. material.wrapAround = this.wrapAround;
  6930. material.wrapRGB.copy( this.wrapRGB );
  6931. material.map = this.map;
  6932. material.lightMap = this.lightMap;
  6933. material.specularMap = this.specularMap;
  6934. material.envMap = this.envMap;
  6935. material.combine = this.combine;
  6936. material.reflectivity = this.reflectivity;
  6937. material.refractionRatio = this.refractionRatio;
  6938. material.fog = this.fog;
  6939. material.shading = this.shading;
  6940. material.wireframe = this.wireframe;
  6941. material.wireframeLinewidth = this.wireframeLinewidth;
  6942. material.wireframeLinecap = this.wireframeLinecap;
  6943. material.wireframeLinejoin = this.wireframeLinejoin;
  6944. material.vertexColors = this.vertexColors;
  6945. material.skinning = this.skinning;
  6946. material.morphTargets = this.morphTargets;
  6947. material.morphNormals = this.morphNormals;
  6948. return material;
  6949. };
  6950. /**
  6951. * @author mrdoob / http://mrdoob.com/
  6952. * @author alteredq / http://alteredqualia.com/
  6953. *
  6954. * parameters = {
  6955. * color: <hex>,
  6956. * ambient: <hex>,
  6957. * emissive: <hex>,
  6958. * specular: <hex>,
  6959. * shininess: <float>,
  6960. * opacity: <float>,
  6961. *
  6962. * map: new THREE.Texture( <Image> ),
  6963. *
  6964. * lightMap: new THREE.Texture( <Image> ),
  6965. *
  6966. * bumpMap: new THREE.Texture( <Image> ),
  6967. * bumpScale: <float>,
  6968. *
  6969. * normalMap: new THREE.Texture( <Image> ),
  6970. * normalScale: <Vector2>,
  6971. *
  6972. * specularMap: new THREE.Texture( <Image> ),
  6973. *
  6974. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6975. * combine: THREE.Multiply,
  6976. * reflectivity: <float>,
  6977. * refractionRatio: <float>,
  6978. *
  6979. * shading: THREE.SmoothShading,
  6980. * blending: THREE.NormalBlending,
  6981. * depthTest: <bool>,
  6982. * depthWrite: <bool>,
  6983. *
  6984. * wireframe: <boolean>,
  6985. * wireframeLinewidth: <float>,
  6986. *
  6987. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6988. *
  6989. * skinning: <bool>,
  6990. * morphTargets: <bool>,
  6991. * morphNormals: <bool>,
  6992. *
  6993. * fog: <bool>
  6994. * }
  6995. */
  6996. THREE.MeshPhongMaterial = function ( parameters ) {
  6997. THREE.Material.call( this );
  6998. this.color = new THREE.Color( 0xffffff ); // diffuse
  6999. this.ambient = new THREE.Color( 0xffffff );
  7000. this.emissive = new THREE.Color( 0x000000 );
  7001. this.specular = new THREE.Color( 0x111111 );
  7002. this.shininess = 30;
  7003. this.metal = false;
  7004. this.perPixel = true;
  7005. this.wrapAround = false;
  7006. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7007. this.map = null;
  7008. this.lightMap = null;
  7009. this.bumpMap = null;
  7010. this.bumpScale = 1;
  7011. this.normalMap = null;
  7012. this.normalScale = new THREE.Vector2( 1, 1 );
  7013. this.specularMap = null;
  7014. this.envMap = null;
  7015. this.combine = THREE.MultiplyOperation;
  7016. this.reflectivity = 1;
  7017. this.refractionRatio = 0.98;
  7018. this.fog = true;
  7019. this.shading = THREE.SmoothShading;
  7020. this.wireframe = false;
  7021. this.wireframeLinewidth = 1;
  7022. this.wireframeLinecap = 'round';
  7023. this.wireframeLinejoin = 'round';
  7024. this.vertexColors = THREE.NoColors;
  7025. this.skinning = false;
  7026. this.morphTargets = false;
  7027. this.morphNormals = false;
  7028. this.setValues( parameters );
  7029. };
  7030. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7031. THREE.MeshPhongMaterial.prototype.clone = function () {
  7032. var material = new THREE.MeshPhongMaterial();
  7033. THREE.Material.prototype.clone.call( this, material );
  7034. material.color.copy( this.color );
  7035. material.ambient.copy( this.ambient );
  7036. material.emissive.copy( this.emissive );
  7037. material.specular.copy( this.specular );
  7038. material.shininess = this.shininess;
  7039. material.metal = this.metal;
  7040. material.perPixel = this.perPixel;
  7041. material.wrapAround = this.wrapAround;
  7042. material.wrapRGB.copy( this.wrapRGB );
  7043. material.map = this.map;
  7044. material.lightMap = this.lightMap;
  7045. material.bumpMap = this.bumpMap;
  7046. material.bumpScale = this.bumpScale;
  7047. material.normalMap = this.normalMap;
  7048. material.normalScale.copy( this.normalScale );
  7049. material.specularMap = this.specularMap;
  7050. material.envMap = this.envMap;
  7051. material.combine = this.combine;
  7052. material.reflectivity = this.reflectivity;
  7053. material.refractionRatio = this.refractionRatio;
  7054. material.fog = this.fog;
  7055. material.shading = this.shading;
  7056. material.wireframe = this.wireframe;
  7057. material.wireframeLinewidth = this.wireframeLinewidth;
  7058. material.wireframeLinecap = this.wireframeLinecap;
  7059. material.wireframeLinejoin = this.wireframeLinejoin;
  7060. material.vertexColors = this.vertexColors;
  7061. material.skinning = this.skinning;
  7062. material.morphTargets = this.morphTargets;
  7063. material.morphNormals = this.morphNormals;
  7064. return material;
  7065. };
  7066. /**
  7067. * @author mrdoob / http://mrdoob.com/
  7068. * @author alteredq / http://alteredqualia.com/
  7069. *
  7070. * parameters = {
  7071. * opacity: <float>,
  7072. *
  7073. * blending: THREE.NormalBlending,
  7074. * depthTest: <bool>,
  7075. * depthWrite: <bool>,
  7076. *
  7077. * wireframe: <boolean>,
  7078. * wireframeLinewidth: <float>
  7079. * }
  7080. */
  7081. THREE.MeshDepthMaterial = function ( parameters ) {
  7082. THREE.Material.call( this );
  7083. this.wireframe = false;
  7084. this.wireframeLinewidth = 1;
  7085. this.setValues( parameters );
  7086. };
  7087. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7088. THREE.MeshDepthMaterial.prototype.clone = function () {
  7089. var material = new THREE.LineBasicMaterial();
  7090. THREE.Material.prototype.clone.call( this, material );
  7091. material.wireframe = this.wireframe;
  7092. material.wireframeLinewidth = this.wireframeLinewidth;
  7093. return material;
  7094. };
  7095. /**
  7096. * @author mrdoob / http://mrdoob.com/
  7097. *
  7098. * parameters = {
  7099. * opacity: <float>,
  7100. *
  7101. * shading: THREE.FlatShading,
  7102. * blending: THREE.NormalBlending,
  7103. * depthTest: <bool>,
  7104. * depthWrite: <bool>,
  7105. *
  7106. * wireframe: <boolean>,
  7107. * wireframeLinewidth: <float>
  7108. * }
  7109. */
  7110. THREE.MeshNormalMaterial = function ( parameters ) {
  7111. THREE.Material.call( this, parameters );
  7112. this.shading = THREE.FlatShading;
  7113. this.wireframe = false;
  7114. this.wireframeLinewidth = 1;
  7115. this.setValues( parameters );
  7116. };
  7117. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7118. THREE.MeshNormalMaterial.prototype.clone = function () {
  7119. var material = new THREE.MeshNormalMaterial();
  7120. THREE.Material.prototype.clone.call( this, material );
  7121. material.shading = this.shading;
  7122. material.wireframe = this.wireframe;
  7123. material.wireframeLinewidth = this.wireframeLinewidth;
  7124. return material;
  7125. };
  7126. /**
  7127. * @author mrdoob / http://mrdoob.com/
  7128. */
  7129. THREE.MeshFaceMaterial = function ( materials ) {
  7130. this.materials = materials instanceof Array ? materials : [];
  7131. };
  7132. THREE.MeshFaceMaterial.prototype.clone = function () {
  7133. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7134. };
  7135. /**
  7136. * @author mrdoob / http://mrdoob.com/
  7137. * @author alteredq / http://alteredqualia.com/
  7138. *
  7139. * parameters = {
  7140. * color: <hex>,
  7141. * opacity: <float>,
  7142. * map: new THREE.Texture( <Image> ),
  7143. *
  7144. * size: <float>,
  7145. *
  7146. * blending: THREE.NormalBlending,
  7147. * depthTest: <bool>,
  7148. * depthWrite: <bool>,
  7149. *
  7150. * vertexColors: <bool>,
  7151. *
  7152. * fog: <bool>
  7153. * }
  7154. */
  7155. THREE.ParticleBasicMaterial = function ( parameters ) {
  7156. THREE.Material.call( this );
  7157. this.color = new THREE.Color( 0xffffff );
  7158. this.map = null;
  7159. this.size = 1;
  7160. this.sizeAttenuation = true;
  7161. this.vertexColors = false;
  7162. this.fog = true;
  7163. this.setValues( parameters );
  7164. };
  7165. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7166. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7167. var material = new THREE.ParticleBasicMaterial();
  7168. THREE.Material.prototype.clone.call( this, material );
  7169. material.color.copy( this.color );
  7170. material.map = this.map;
  7171. material.size = this.size;
  7172. material.sizeAttenuation = this.sizeAttenuation;
  7173. material.vertexColors = this.vertexColors;
  7174. material.fog = this.fog;
  7175. return material;
  7176. };
  7177. /**
  7178. * @author mrdoob / http://mrdoob.com/
  7179. *
  7180. * parameters = {
  7181. * color: <hex>,
  7182. * program: <function>,
  7183. * opacity: <float>,
  7184. * blending: THREE.NormalBlending
  7185. * }
  7186. */
  7187. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7188. THREE.Material.call( this );
  7189. this.color = new THREE.Color( 0xffffff );
  7190. this.program = function ( context, color ) {};
  7191. this.setValues( parameters );
  7192. };
  7193. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7194. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7195. var material = new THREE.ParticleCanvasMaterial();
  7196. THREE.Material.prototype.clone.call( this, material );
  7197. material.color.copy( this.color );
  7198. material.program = this.program;
  7199. return material;
  7200. };
  7201. /**
  7202. * @author alteredq / http://alteredqualia.com/
  7203. *
  7204. * parameters = {
  7205. * fragmentShader: <string>,
  7206. * vertexShader: <string>,
  7207. *
  7208. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7209. *
  7210. * defines: { "label" : "value" },
  7211. *
  7212. * shading: THREE.SmoothShading,
  7213. * blending: THREE.NormalBlending,
  7214. * depthTest: <bool>,
  7215. * depthWrite: <bool>,
  7216. *
  7217. * wireframe: <boolean>,
  7218. * wireframeLinewidth: <float>,
  7219. *
  7220. * lights: <bool>,
  7221. *
  7222. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7223. *
  7224. * skinning: <bool>,
  7225. * morphTargets: <bool>,
  7226. * morphNormals: <bool>,
  7227. *
  7228. * fog: <bool>
  7229. * }
  7230. */
  7231. THREE.ShaderMaterial = function ( parameters ) {
  7232. THREE.Material.call( this );
  7233. this.fragmentShader = "void main() {}";
  7234. this.vertexShader = "void main() {}";
  7235. this.uniforms = {};
  7236. this.defines = {};
  7237. this.attributes = null;
  7238. this.shading = THREE.SmoothShading;
  7239. this.wireframe = false;
  7240. this.wireframeLinewidth = 1;
  7241. this.fog = false; // set to use scene fog
  7242. this.lights = false; // set to use scene lights
  7243. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7244. this.skinning = false; // set to use skinning attribute streams
  7245. this.morphTargets = false; // set to use morph targets
  7246. this.morphNormals = false; // set to use morph normals
  7247. this.setValues( parameters );
  7248. };
  7249. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7250. THREE.ShaderMaterial.prototype.clone = function () {
  7251. var material = new THREE.ShaderMaterial();
  7252. THREE.Material.prototype.clone.call( this, material );
  7253. material.fragmentShader = this.fragmentShader;
  7254. material.vertexShader = this.vertexShader;
  7255. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7256. material.attributes = this.attributes;
  7257. material.defines = this.defines;
  7258. material.shading = this.shading;
  7259. material.wireframe = this.wireframe;
  7260. material.wireframeLinewidth = this.wireframeLinewidth;
  7261. material.fog = this.fog;
  7262. material.lights = this.lights;
  7263. material.vertexColors = this.vertexColors;
  7264. material.skinning = this.skinning;
  7265. material.morphTargets = this.morphTargets;
  7266. material.morphNormals = this.morphNormals;
  7267. return material;
  7268. };
  7269. /**
  7270. * @author alteredq / http://alteredqualia.com/
  7271. *
  7272. * parameters = {
  7273. * color: <hex>,
  7274. * opacity: <float>,
  7275. * map: new THREE.Texture( <Image> ),
  7276. *
  7277. * blending: THREE.NormalBlending,
  7278. * depthTest: <bool>,
  7279. * depthWrite: <bool>,
  7280. *
  7281. * useScreenCoordinates: <bool>,
  7282. * sizeAttenuation: <bool>,
  7283. * scaleByViewport: <bool>,
  7284. * alignment: THREE.SpriteAlignment.center,
  7285. *
  7286. * uvOffset: new THREE.Vector2(),
  7287. * uvScale: new THREE.Vector2(),
  7288. *
  7289. * fog: <bool>
  7290. * }
  7291. */
  7292. THREE.SpriteMaterial = function ( parameters ) {
  7293. THREE.Material.call( this );
  7294. // defaults
  7295. this.color = new THREE.Color( 0xffffff );
  7296. this.map = new THREE.Texture();
  7297. this.useScreenCoordinates = true;
  7298. this.depthTest = !this.useScreenCoordinates;
  7299. this.sizeAttenuation = !this.useScreenCoordinates;
  7300. this.scaleByViewport = !this.sizeAttenuation;
  7301. this.alignment = THREE.SpriteAlignment.center.clone();
  7302. this.fog = false;
  7303. this.uvOffset = new THREE.Vector2( 0, 0 );
  7304. this.uvScale = new THREE.Vector2( 1, 1 );
  7305. // set parameters
  7306. this.setValues( parameters );
  7307. // override coupled defaults if not specified explicitly by parameters
  7308. parameters = parameters || {};
  7309. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7310. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7311. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7312. };
  7313. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7314. THREE.SpriteMaterial.prototype.clone = function () {
  7315. var material = new THREE.SpriteMaterial();
  7316. THREE.Material.prototype.clone.call( this, material );
  7317. material.color.copy( this.color );
  7318. material.map = this.map;
  7319. material.useScreenCoordinates = this.useScreenCoordinates;
  7320. material.sizeAttenuation = this.sizeAttenuation;
  7321. material.scaleByViewport = this.scaleByViewport;
  7322. material.alignment.copy( this.alignment );
  7323. material.uvOffset.copy( this.uvOffset );
  7324. material.uvScale.copy( this.uvScale );
  7325. material.fog = this.fog;
  7326. return material;
  7327. };
  7328. // Alignment enums
  7329. THREE.SpriteAlignment = {};
  7330. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7331. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7332. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7333. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7334. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7335. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7336. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7337. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7338. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7339. /**
  7340. * @author mrdoob / http://mrdoob.com/
  7341. * @author alteredq / http://alteredqualia.com/
  7342. * @author szimek / https://github.com/szimek/
  7343. */
  7344. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7345. THREE.EventDispatcher.call( this );
  7346. this.id = THREE.TextureIdCount ++;
  7347. this.name = '';
  7348. this.image = image;
  7349. this.mipmaps = [];
  7350. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7351. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7352. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7353. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7354. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7355. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7356. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7357. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7358. this.offset = new THREE.Vector2( 0, 0 );
  7359. this.repeat = new THREE.Vector2( 1, 1 );
  7360. this.generateMipmaps = true;
  7361. this.premultiplyAlpha = false;
  7362. this.flipY = true;
  7363. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7364. this.needsUpdate = false;
  7365. this.onUpdate = null;
  7366. };
  7367. THREE.Texture.prototype = {
  7368. constructor: THREE.Texture,
  7369. clone: function ( texture ) {
  7370. if ( texture === undefined ) texture = new THREE.Texture();
  7371. texture.image = this.image;
  7372. texture.mipmaps = this.mipmaps.slice(0);
  7373. texture.mapping = this.mapping;
  7374. texture.wrapS = this.wrapS;
  7375. texture.wrapT = this.wrapT;
  7376. texture.magFilter = this.magFilter;
  7377. texture.minFilter = this.minFilter;
  7378. texture.anisotropy = this.anisotropy;
  7379. texture.format = this.format;
  7380. texture.type = this.type;
  7381. texture.offset.copy( this.offset );
  7382. texture.repeat.copy( this.repeat );
  7383. texture.generateMipmaps = this.generateMipmaps;
  7384. texture.premultiplyAlpha = this.premultiplyAlpha;
  7385. texture.flipY = this.flipY;
  7386. texture.unpackAlignment = this.unpackAlignment;
  7387. return texture;
  7388. },
  7389. dispose: function () {
  7390. this.dispatchEvent( { type: 'dispose' } );
  7391. }
  7392. };
  7393. THREE.TextureIdCount = 0;
  7394. /**
  7395. * @author alteredq / http://alteredqualia.com/
  7396. */
  7397. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7398. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7399. this.image = { width: width, height: height };
  7400. this.mipmaps = mipmaps;
  7401. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7402. };
  7403. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7404. THREE.CompressedTexture.prototype.clone = function () {
  7405. var texture = new THREE.CompressedTexture();
  7406. THREE.Texture.prototype.clone.call( this, texture );
  7407. return texture;
  7408. };
  7409. /**
  7410. * @author alteredq / http://alteredqualia.com/
  7411. */
  7412. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7413. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7414. this.image = { data: data, width: width, height: height };
  7415. };
  7416. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7417. THREE.DataTexture.prototype.clone = function () {
  7418. var texture = new THREE.DataTexture();
  7419. THREE.Texture.prototype.clone.call( this, texture );
  7420. return texture;
  7421. };
  7422. /**
  7423. * @author mrdoob / http://mrdoob.com/
  7424. */
  7425. THREE.Particle = function ( material ) {
  7426. THREE.Object3D.call( this );
  7427. this.material = material;
  7428. };
  7429. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7430. THREE.Particle.prototype.clone = function ( object ) {
  7431. if ( object === undefined ) object = new THREE.Particle( this.material );
  7432. THREE.Object3D.prototype.clone.call( this, object );
  7433. return object;
  7434. };
  7435. /**
  7436. * @author alteredq / http://alteredqualia.com/
  7437. */
  7438. THREE.ParticleSystem = function ( geometry, material ) {
  7439. THREE.Object3D.call( this );
  7440. this.geometry = geometry;
  7441. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7442. this.sortParticles = false;
  7443. if ( this.geometry ) {
  7444. // calc bound radius
  7445. if( this.geometry.boundingSphere === null ) {
  7446. this.geometry.computeBoundingSphere();
  7447. }
  7448. }
  7449. this.frustumCulled = false;
  7450. };
  7451. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7452. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7453. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7454. object.sortParticles = this.sortParticles;
  7455. THREE.Object3D.prototype.clone.call( this, object );
  7456. return object;
  7457. };
  7458. /**
  7459. * @author mrdoob / http://mrdoob.com/
  7460. */
  7461. THREE.Line = function ( geometry, material, type ) {
  7462. THREE.Object3D.call( this );
  7463. this.geometry = geometry;
  7464. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7465. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7466. if ( this.geometry ) {
  7467. if ( ! this.geometry.boundingSphere ) {
  7468. this.geometry.computeBoundingSphere();
  7469. }
  7470. }
  7471. };
  7472. THREE.LineStrip = 0;
  7473. THREE.LinePieces = 1;
  7474. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7475. THREE.Line.prototype.clone = function ( object ) {
  7476. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7477. THREE.Object3D.prototype.clone.call( this, object );
  7478. return object;
  7479. };
  7480. /**
  7481. * @author mrdoob / http://mrdoob.com/
  7482. * @author alteredq / http://alteredqualia.com/
  7483. * @author mikael emtinger / http://gomo.se/
  7484. * @author jonobr1 / http://jonobr1.com/
  7485. */
  7486. THREE.Mesh = function ( geometry, material ) {
  7487. THREE.Object3D.call( this );
  7488. this.geometry = geometry;
  7489. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7490. if ( this.geometry !== undefined ) {
  7491. if ( this.geometry.boundingSphere === null ) {
  7492. this.geometry.computeBoundingSphere();
  7493. }
  7494. this.updateMorphTargets();
  7495. }
  7496. };
  7497. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7498. THREE.Mesh.prototype.updateMorphTargets = function () {
  7499. if ( this.geometry.morphTargets.length > 0 ) {
  7500. this.morphTargetBase = -1;
  7501. this.morphTargetForcedOrder = [];
  7502. this.morphTargetInfluences = [];
  7503. this.morphTargetDictionary = {};
  7504. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7505. this.morphTargetInfluences.push( 0 );
  7506. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7507. }
  7508. }
  7509. };
  7510. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7511. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7512. return this.morphTargetDictionary[ name ];
  7513. }
  7514. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7515. return 0;
  7516. };
  7517. THREE.Mesh.prototype.clone = function ( object ) {
  7518. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7519. THREE.Object3D.prototype.clone.call( this, object );
  7520. return object;
  7521. };
  7522. /**
  7523. * @author mikael emtinger / http://gomo.se/
  7524. * @author alteredq / http://alteredqualia.com/
  7525. */
  7526. THREE.Bone = function( belongsToSkin ) {
  7527. THREE.Object3D.call( this );
  7528. this.skin = belongsToSkin;
  7529. this.skinMatrix = new THREE.Matrix4();
  7530. };
  7531. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7532. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7533. // update local
  7534. if ( this.matrixAutoUpdate ) {
  7535. forceUpdate |= this.updateMatrix();
  7536. }
  7537. // update skin matrix
  7538. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7539. if( parentSkinMatrix ) {
  7540. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7541. } else {
  7542. this.skinMatrix.copy( this.matrix );
  7543. }
  7544. this.matrixWorldNeedsUpdate = false;
  7545. forceUpdate = true;
  7546. }
  7547. // update children
  7548. var child, i, l = this.children.length;
  7549. for ( i = 0; i < l; i ++ ) {
  7550. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7551. }
  7552. };
  7553. /**
  7554. * @author mikael emtinger / http://gomo.se/
  7555. * @author alteredq / http://alteredqualia.com/
  7556. */
  7557. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7558. THREE.Mesh.call( this, geometry, material );
  7559. //
  7560. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7561. // init bones
  7562. this.identityMatrix = new THREE.Matrix4();
  7563. this.bones = [];
  7564. this.boneMatrices = [];
  7565. var b, bone, gbone, p, q, s;
  7566. if ( this.geometry && this.geometry.bones !== undefined ) {
  7567. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7568. gbone = this.geometry.bones[ b ];
  7569. p = gbone.pos;
  7570. q = gbone.rotq;
  7571. s = gbone.scl;
  7572. bone = this.addBone();
  7573. bone.name = gbone.name;
  7574. bone.position.set( p[0], p[1], p[2] );
  7575. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7576. bone.useQuaternion = true;
  7577. if ( s !== undefined ) {
  7578. bone.scale.set( s[0], s[1], s[2] );
  7579. } else {
  7580. bone.scale.set( 1, 1, 1 );
  7581. }
  7582. }
  7583. for ( b = 0; b < this.bones.length; b ++ ) {
  7584. gbone = this.geometry.bones[ b ];
  7585. bone = this.bones[ b ];
  7586. if ( gbone.parent === -1 ) {
  7587. this.add( bone );
  7588. } else {
  7589. this.bones[ gbone.parent ].add( bone );
  7590. }
  7591. }
  7592. //
  7593. var nBones = this.bones.length;
  7594. if ( this.useVertexTexture ) {
  7595. // layout (1 matrix = 4 pixels)
  7596. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7597. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7598. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7599. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7600. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7601. var size;
  7602. if ( nBones > 256 )
  7603. size = 64;
  7604. else if ( nBones > 64 )
  7605. size = 32;
  7606. else if ( nBones > 16 )
  7607. size = 16;
  7608. else
  7609. size = 8;
  7610. this.boneTextureWidth = size;
  7611. this.boneTextureHeight = size;
  7612. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7613. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7614. this.boneTexture.minFilter = THREE.NearestFilter;
  7615. this.boneTexture.magFilter = THREE.NearestFilter;
  7616. this.boneTexture.generateMipmaps = false;
  7617. this.boneTexture.flipY = false;
  7618. } else {
  7619. this.boneMatrices = new Float32Array( 16 * nBones );
  7620. }
  7621. this.pose();
  7622. }
  7623. };
  7624. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7625. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7626. if ( bone === undefined ) {
  7627. bone = new THREE.Bone( this );
  7628. }
  7629. this.bones.push( bone );
  7630. return bone;
  7631. };
  7632. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7633. this.matrixAutoUpdate && this.updateMatrix();
  7634. // update matrixWorld
  7635. if ( this.matrixWorldNeedsUpdate || force ) {
  7636. if ( this.parent ) {
  7637. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7638. } else {
  7639. this.matrixWorld.copy( this.matrix );
  7640. }
  7641. this.matrixWorldNeedsUpdate = false;
  7642. force = true;
  7643. }
  7644. // update children
  7645. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7646. var child = this.children[ i ];
  7647. if ( child instanceof THREE.Bone ) {
  7648. child.update( this.identityMatrix, false );
  7649. } else {
  7650. child.updateMatrixWorld( true );
  7651. }
  7652. }
  7653. // make a snapshot of the bones' rest position
  7654. if ( this.boneInverses == undefined ) {
  7655. this.boneInverses = [];
  7656. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7657. var inverse = new THREE.Matrix4();
  7658. inverse.getInverse( this.bones[ b ].skinMatrix );
  7659. this.boneInverses.push( inverse );
  7660. }
  7661. }
  7662. // flatten bone matrices to array
  7663. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7664. // compute the offset between the current and the original transform;
  7665. //TODO: we could get rid of this multiplication step if the skinMatrix
  7666. // was already representing the offset; however, this requires some
  7667. // major changes to the animation system
  7668. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7669. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7670. }
  7671. if ( this.useVertexTexture ) {
  7672. this.boneTexture.needsUpdate = true;
  7673. }
  7674. };
  7675. THREE.SkinnedMesh.prototype.pose = function () {
  7676. this.updateMatrixWorld( true );
  7677. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7678. // normalize weights
  7679. var sw = this.geometry.skinWeights[ i ];
  7680. var scale = 1.0 / sw.lengthManhattan();
  7681. if ( scale !== Infinity ) {
  7682. sw.multiplyScalar( scale );
  7683. } else {
  7684. sw.set( 1 ); // this will be normalized by the shader anyway
  7685. }
  7686. }
  7687. };
  7688. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7689. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7690. THREE.Mesh.prototype.clone.call( this, object );
  7691. return object;
  7692. };
  7693. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7694. /**
  7695. * @author alteredq / http://alteredqualia.com/
  7696. */
  7697. THREE.MorphAnimMesh = function ( geometry, material ) {
  7698. THREE.Mesh.call( this, geometry, material );
  7699. // API
  7700. this.duration = 1000; // milliseconds
  7701. this.mirroredLoop = false;
  7702. this.time = 0;
  7703. // internals
  7704. this.lastKeyframe = 0;
  7705. this.currentKeyframe = 0;
  7706. this.direction = 1;
  7707. this.directionBackwards = false;
  7708. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7709. };
  7710. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7711. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7712. this.startKeyframe = start;
  7713. this.endKeyframe = end;
  7714. this.length = this.endKeyframe - this.startKeyframe + 1;
  7715. };
  7716. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7717. this.direction = 1;
  7718. this.directionBackwards = false;
  7719. };
  7720. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7721. this.direction = -1;
  7722. this.directionBackwards = true;
  7723. };
  7724. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7725. var geometry = this.geometry;
  7726. if ( ! geometry.animations ) geometry.animations = {};
  7727. var firstAnimation, animations = geometry.animations;
  7728. var pattern = /([a-z]+)(\d+)/;
  7729. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7730. var morph = geometry.morphTargets[ i ];
  7731. var parts = morph.name.match( pattern );
  7732. if ( parts && parts.length > 1 ) {
  7733. var label = parts[ 1 ];
  7734. var num = parts[ 2 ];
  7735. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7736. var animation = animations[ label ];
  7737. if ( i < animation.start ) animation.start = i;
  7738. if ( i > animation.end ) animation.end = i;
  7739. if ( ! firstAnimation ) firstAnimation = label;
  7740. }
  7741. }
  7742. geometry.firstAnimation = firstAnimation;
  7743. };
  7744. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7745. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7746. this.geometry.animations[ label ] = { start: start, end: end };
  7747. };
  7748. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7749. var animation = this.geometry.animations[ label ];
  7750. if ( animation ) {
  7751. this.setFrameRange( animation.start, animation.end );
  7752. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7753. this.time = 0;
  7754. } else {
  7755. console.warn( "animation[" + label + "] undefined" );
  7756. }
  7757. };
  7758. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7759. var frameTime = this.duration / this.length;
  7760. this.time += this.direction * delta;
  7761. if ( this.mirroredLoop ) {
  7762. if ( this.time > this.duration || this.time < 0 ) {
  7763. this.direction *= -1;
  7764. if ( this.time > this.duration ) {
  7765. this.time = this.duration;
  7766. this.directionBackwards = true;
  7767. }
  7768. if ( this.time < 0 ) {
  7769. this.time = 0;
  7770. this.directionBackwards = false;
  7771. }
  7772. }
  7773. } else {
  7774. this.time = this.time % this.duration;
  7775. if ( this.time < 0 ) this.time += this.duration;
  7776. }
  7777. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7778. if ( keyframe !== this.currentKeyframe ) {
  7779. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7780. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7781. this.morphTargetInfluences[ keyframe ] = 0;
  7782. this.lastKeyframe = this.currentKeyframe;
  7783. this.currentKeyframe = keyframe;
  7784. }
  7785. var mix = ( this.time % frameTime ) / frameTime;
  7786. if ( this.directionBackwards ) {
  7787. mix = 1 - mix;
  7788. }
  7789. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7790. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7791. };
  7792. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7793. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7794. object.duration = this.duration;
  7795. object.mirroredLoop = this.mirroredLoop;
  7796. object.time = this.time;
  7797. object.lastKeyframe = this.lastKeyframe;
  7798. object.currentKeyframe = this.currentKeyframe;
  7799. object.direction = this.direction;
  7800. object.directionBackwards = this.directionBackwards;
  7801. THREE.Mesh.prototype.clone.call( this, object );
  7802. return object;
  7803. };
  7804. /**
  7805. * @author alteredq / http://alteredqualia.com/
  7806. */
  7807. THREE.Ribbon = function ( geometry, material ) {
  7808. THREE.Object3D.call( this );
  7809. this.geometry = geometry;
  7810. this.material = material;
  7811. };
  7812. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7813. THREE.Ribbon.prototype.clone = function ( object ) {
  7814. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7815. THREE.Object3D.prototype.clone.call( this, object );
  7816. return object;
  7817. };
  7818. /**
  7819. * @author mikael emtinger / http://gomo.se/
  7820. * @author alteredq / http://alteredqualia.com/
  7821. * @author mrdoob / http://mrdoob.com/
  7822. */
  7823. THREE.LOD = function () {
  7824. THREE.Object3D.call( this );
  7825. this.LODs = [];
  7826. };
  7827. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7828. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7829. if ( visibleAtDistance === undefined ) {
  7830. visibleAtDistance = 0;
  7831. }
  7832. visibleAtDistance = Math.abs( visibleAtDistance );
  7833. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7834. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7835. break;
  7836. }
  7837. }
  7838. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7839. this.add( object3D );
  7840. };
  7841. THREE.LOD.prototype.update = function ( camera ) {
  7842. if ( this.LODs.length > 1 ) {
  7843. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7844. var inverse = camera.matrixWorldInverse;
  7845. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7846. this.LODs[ 0 ].object3D.visible = true;
  7847. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7848. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7849. this.LODs[ l - 1 ].object3D.visible = false;
  7850. this.LODs[ l ].object3D.visible = true;
  7851. } else {
  7852. break;
  7853. }
  7854. }
  7855. for( ; l < this.LODs.length; l ++ ) {
  7856. this.LODs[ l ].object3D.visible = false;
  7857. }
  7858. }
  7859. };
  7860. THREE.LOD.prototype.clone = function () {
  7861. // TODO
  7862. };
  7863. /**
  7864. * @author mikael emtinger / http://gomo.se/
  7865. * @author alteredq / http://alteredqualia.com/
  7866. */
  7867. THREE.Sprite = function ( material ) {
  7868. THREE.Object3D.call( this );
  7869. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7870. this.rotation3d = this.rotation;
  7871. this.rotation = 0;
  7872. };
  7873. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7874. /*
  7875. * Custom update matrix
  7876. */
  7877. THREE.Sprite.prototype.updateMatrix = function () {
  7878. this.matrix.setPosition( this.position );
  7879. this.rotation3d.set( 0, 0, this.rotation );
  7880. this.matrix.setRotationFromEuler( this.rotation3d );
  7881. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7882. this.matrix.scale( this.scale );
  7883. }
  7884. this.matrixWorldNeedsUpdate = true;
  7885. };
  7886. THREE.Sprite.prototype.clone = function ( object ) {
  7887. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7888. THREE.Object3D.prototype.clone.call( this, object );
  7889. return object;
  7890. };
  7891. /**
  7892. * @author mrdoob / http://mrdoob.com/
  7893. */
  7894. THREE.Scene = function () {
  7895. THREE.Object3D.call( this );
  7896. this.fog = null;
  7897. this.overrideMaterial = null;
  7898. this.matrixAutoUpdate = false;
  7899. this.__objects = [];
  7900. this.__lights = [];
  7901. this.__objectsAdded = [];
  7902. this.__objectsRemoved = [];
  7903. };
  7904. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7905. THREE.Scene.prototype.__addObject = function ( object ) {
  7906. if ( object instanceof THREE.Light ) {
  7907. if ( this.__lights.indexOf( object ) === - 1 ) {
  7908. this.__lights.push( object );
  7909. }
  7910. if ( object.target && object.target.parent === undefined ) {
  7911. this.add( object.target );
  7912. }
  7913. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7914. if ( this.__objects.indexOf( object ) === - 1 ) {
  7915. this.__objects.push( object );
  7916. this.__objectsAdded.push( object );
  7917. // check if previously removed
  7918. var i = this.__objectsRemoved.indexOf( object );
  7919. if ( i !== -1 ) {
  7920. this.__objectsRemoved.splice( i, 1 );
  7921. }
  7922. }
  7923. }
  7924. for ( var c = 0; c < object.children.length; c ++ ) {
  7925. this.__addObject( object.children[ c ] );
  7926. }
  7927. };
  7928. THREE.Scene.prototype.__removeObject = function ( object ) {
  7929. if ( object instanceof THREE.Light ) {
  7930. var i = this.__lights.indexOf( object );
  7931. if ( i !== -1 ) {
  7932. this.__lights.splice( i, 1 );
  7933. }
  7934. } else if ( !( object instanceof THREE.Camera ) ) {
  7935. var i = this.__objects.indexOf( object );
  7936. if( i !== -1 ) {
  7937. this.__objects.splice( i, 1 );
  7938. this.__objectsRemoved.push( object );
  7939. // check if previously added
  7940. var ai = this.__objectsAdded.indexOf( object );
  7941. if ( ai !== -1 ) {
  7942. this.__objectsAdded.splice( ai, 1 );
  7943. }
  7944. }
  7945. }
  7946. for ( var c = 0; c < object.children.length; c ++ ) {
  7947. this.__removeObject( object.children[ c ] );
  7948. }
  7949. };
  7950. /**
  7951. * @author mrdoob / http://mrdoob.com/
  7952. * @author alteredq / http://alteredqualia.com/
  7953. */
  7954. THREE.Fog = function ( hex, near, far ) {
  7955. this.name = '';
  7956. this.color = new THREE.Color( hex );
  7957. this.near = ( near !== undefined ) ? near : 1;
  7958. this.far = ( far !== undefined ) ? far : 1000;
  7959. };
  7960. THREE.Fog.prototype.clone = function () {
  7961. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7962. };
  7963. /**
  7964. * @author mrdoob / http://mrdoob.com/
  7965. * @author alteredq / http://alteredqualia.com/
  7966. */
  7967. THREE.FogExp2 = function ( hex, density ) {
  7968. this.name = '';
  7969. this.color = new THREE.Color( hex );
  7970. this.density = ( density !== undefined ) ? density : 0.00025;
  7971. };
  7972. THREE.FogExp2.prototype.clone = function () {
  7973. return new THREE.FogExp2( this.color.getHex(), this.density );
  7974. };
  7975. /**
  7976. * @author mrdoob / http://mrdoob.com/
  7977. */
  7978. THREE.CanvasRenderer = function ( parameters ) {
  7979. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7980. var smoothstep = THREE.Math.smoothstep;
  7981. parameters = parameters || {};
  7982. var _this = this,
  7983. _renderData, _elements, _lights,
  7984. _projector = new THREE.Projector(),
  7985. _canvas = parameters.canvas !== undefined
  7986. ? parameters.canvas
  7987. : document.createElement( 'canvas' ),
  7988. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7989. _context = _canvas.getContext( '2d' ),
  7990. _clearColor = new THREE.Color( 0x000000 ),
  7991. _clearOpacity = 0,
  7992. _contextGlobalAlpha = 1,
  7993. _contextGlobalCompositeOperation = 0,
  7994. _contextStrokeStyle = null,
  7995. _contextFillStyle = null,
  7996. _contextLineWidth = null,
  7997. _contextLineCap = null,
  7998. _contextLineJoin = null,
  7999. _contextDashSize = null,
  8000. _contextGapSize = 0,
  8001. _v1, _v2, _v3, _v4,
  8002. _v5 = new THREE.RenderableVertex(),
  8003. _v6 = new THREE.RenderableVertex(),
  8004. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8005. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8006. _color = new THREE.Color(),
  8007. _color1 = new THREE.Color(),
  8008. _color2 = new THREE.Color(),
  8009. _color3 = new THREE.Color(),
  8010. _color4 = new THREE.Color(),
  8011. _diffuseColor = new THREE.Color(),
  8012. _emissiveColor = new THREE.Color(),
  8013. _lightColor = new THREE.Color(),
  8014. _patterns = {}, _imagedatas = {},
  8015. _near, _far,
  8016. _image, _uvs,
  8017. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8018. _clipBox = new THREE.Box2(),
  8019. _clearBox = new THREE.Box2(),
  8020. _elemBox = new THREE.Box2(),
  8021. _ambientLight = new THREE.Color(),
  8022. _directionalLights = new THREE.Color(),
  8023. _pointLights = new THREE.Color(),
  8024. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8025. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8026. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8027. _pixelMap = document.createElement( 'canvas' );
  8028. _pixelMap.width = _pixelMap.height = 2;
  8029. _pixelMapContext = _pixelMap.getContext( '2d' );
  8030. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8031. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8032. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8033. _pixelMapData = _pixelMapImage.data;
  8034. _gradientMap = document.createElement( 'canvas' );
  8035. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8036. _gradientMapContext = _gradientMap.getContext( '2d' );
  8037. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8038. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8039. _gradientMapQuality --; // Fix UVs
  8040. // dash+gap fallbacks for Firefox and everything else
  8041. if ( _context.setLineDash === undefined ) {
  8042. if ( _context.mozDash !== undefined ) {
  8043. _context.setLineDash = function ( values ) {
  8044. _context.mozDash = values[ 0 ] !== null ? values : null;
  8045. }
  8046. } else {
  8047. _context.setLineDash = function () {}
  8048. }
  8049. }
  8050. this.domElement = _canvas;
  8051. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8052. ? parameters.devicePixelRatio
  8053. : window.devicePixelRatio !== undefined
  8054. ? window.devicePixelRatio
  8055. : 1;
  8056. this.autoClear = true;
  8057. this.sortObjects = true;
  8058. this.sortElements = true;
  8059. this.info = {
  8060. render: {
  8061. vertices: 0,
  8062. faces: 0
  8063. }
  8064. }
  8065. // WebGLRenderer compatibility
  8066. this.supportsVertexTextures = function () {};
  8067. this.setFaceCulling = function () {};
  8068. this.setSize = function ( width, height ) {
  8069. _canvasWidth = width * this.devicePixelRatio;
  8070. _canvasHeight = height * this.devicePixelRatio;
  8071. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8072. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8073. _canvas.width = _canvasWidth;
  8074. _canvas.height = _canvasHeight;
  8075. _canvas.style.width = width + 'px';
  8076. _canvas.style.height = height + 'px';
  8077. _clipBox.set(
  8078. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8079. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8080. );
  8081. _clearBox.set(
  8082. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8083. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8084. );
  8085. _contextGlobalAlpha = 1;
  8086. _contextGlobalCompositeOperation = 0;
  8087. _contextStrokeStyle = null;
  8088. _contextFillStyle = null;
  8089. _contextLineWidth = null;
  8090. _contextLineCap = null;
  8091. _contextLineJoin = null;
  8092. };
  8093. this.setClearColor = function ( color, opacity ) {
  8094. _clearColor.copy( color );
  8095. _clearOpacity = opacity !== undefined ? opacity : 1;
  8096. _clearBox.set(
  8097. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8098. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8099. );
  8100. };
  8101. this.setClearColorHex = function ( hex, opacity ) {
  8102. _clearColor.setHex( hex );
  8103. _clearOpacity = opacity !== undefined ? opacity : 1;
  8104. _clearBox.set(
  8105. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8106. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8107. );
  8108. };
  8109. this.getMaxAnisotropy = function () {
  8110. return 0;
  8111. };
  8112. this.clear = function () {
  8113. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8114. if ( _clearBox.empty() === false ) {
  8115. _clearBox.intersect( _clipBox );
  8116. _clearBox.expandByScalar( 2 );
  8117. if ( _clearOpacity < 1 ) {
  8118. _context.clearRect(
  8119. _clearBox.min.x | 0,
  8120. _clearBox.min.y | 0,
  8121. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8122. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8123. );
  8124. }
  8125. if ( _clearOpacity > 0 ) {
  8126. setBlending( THREE.NormalBlending );
  8127. setOpacity( 1 );
  8128. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8129. _context.fillRect(
  8130. _clearBox.min.x | 0,
  8131. _clearBox.min.y | 0,
  8132. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8133. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8134. );
  8135. }
  8136. _clearBox.makeEmpty();
  8137. }
  8138. };
  8139. this.render = function ( scene, camera ) {
  8140. if ( camera instanceof THREE.Camera === false ) {
  8141. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8142. return;
  8143. }
  8144. if ( this.autoClear === true ) {
  8145. this.clear();
  8146. }
  8147. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8148. _this.info.render.vertices = 0;
  8149. _this.info.render.faces = 0;
  8150. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8151. _elements = _renderData.elements;
  8152. _lights = _renderData.lights;
  8153. /* DEBUG
  8154. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8155. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8156. */
  8157. calculateLights();
  8158. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8159. var element = _elements[ e ];
  8160. var material = element.material;
  8161. if ( material === undefined || material.visible === false ) continue;
  8162. _elemBox.makeEmpty();
  8163. if ( element instanceof THREE.RenderableParticle ) {
  8164. _v1 = element;
  8165. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8166. renderParticle( _v1, element, material );
  8167. } else if ( element instanceof THREE.RenderableLine ) {
  8168. _v1 = element.v1; _v2 = element.v2;
  8169. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8170. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8171. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8172. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8173. renderLine( _v1, _v2, element, material );
  8174. }
  8175. } else if ( element instanceof THREE.RenderableFace3 ) {
  8176. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8177. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8178. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8179. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8180. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8181. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8182. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8183. if ( material.overdraw === true ) {
  8184. expand( _v1.positionScreen, _v2.positionScreen );
  8185. expand( _v2.positionScreen, _v3.positionScreen );
  8186. expand( _v3.positionScreen, _v1.positionScreen );
  8187. }
  8188. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8189. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8190. } else if ( element instanceof THREE.RenderableFace4 ) {
  8191. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8192. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8193. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8194. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8195. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8196. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8197. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8198. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8199. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8200. _v5.positionScreen.copy( _v2.positionScreen );
  8201. _v6.positionScreen.copy( _v4.positionScreen );
  8202. if ( material.overdraw === true ) {
  8203. expand( _v1.positionScreen, _v2.positionScreen );
  8204. expand( _v2.positionScreen, _v4.positionScreen );
  8205. expand( _v4.positionScreen, _v1.positionScreen );
  8206. expand( _v3.positionScreen, _v5.positionScreen );
  8207. expand( _v3.positionScreen, _v6.positionScreen );
  8208. }
  8209. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8210. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8211. }
  8212. /* DEBUG
  8213. setLineWidth( 1 );
  8214. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8215. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8216. */
  8217. _clearBox.union( _elemBox );
  8218. }
  8219. /* DEBUG
  8220. setLineWidth( 1 );
  8221. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8222. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8223. */
  8224. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8225. //
  8226. function calculateLights() {
  8227. _ambientLight.setRGB( 0, 0, 0 );
  8228. _directionalLights.setRGB( 0, 0, 0 );
  8229. _pointLights.setRGB( 0, 0, 0 );
  8230. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8231. var light = _lights[ l ];
  8232. var lightColor = light.color;
  8233. if ( light instanceof THREE.AmbientLight ) {
  8234. _ambientLight.add( lightColor );
  8235. } else if ( light instanceof THREE.DirectionalLight ) {
  8236. // for particles
  8237. _directionalLights.add( lightColor );
  8238. } else if ( light instanceof THREE.PointLight ) {
  8239. // for particles
  8240. _pointLights.add( lightColor );
  8241. }
  8242. }
  8243. }
  8244. function calculateLight( position, normal, color ) {
  8245. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8246. var light = _lights[ l ];
  8247. _lightColor.copy( light.color );
  8248. if ( light instanceof THREE.DirectionalLight ) {
  8249. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8250. var amount = normal.dot( lightPosition );
  8251. if ( amount <= 0 ) continue;
  8252. amount *= light.intensity;
  8253. color.add( _lightColor.multiplyScalar( amount ) );
  8254. } else if ( light instanceof THREE.PointLight ) {
  8255. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8256. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8257. if ( amount <= 0 ) continue;
  8258. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8259. if ( amount == 0 ) continue;
  8260. amount *= light.intensity;
  8261. color.add( _lightColor.multiplyScalar( amount ) );
  8262. }
  8263. }
  8264. }
  8265. function renderParticle( v1, element, material ) {
  8266. setOpacity( material.opacity );
  8267. setBlending( material.blending );
  8268. var width, height, scaleX, scaleY,
  8269. bitmap, bitmapWidth, bitmapHeight;
  8270. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8271. if ( material.map === null ) {
  8272. scaleX = element.object.scale.x;
  8273. scaleY = element.object.scale.y;
  8274. // TODO: Be able to disable this
  8275. scaleX *= element.scale.x * _canvasWidthHalf;
  8276. scaleY *= element.scale.y * _canvasHeightHalf;
  8277. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8278. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8279. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8280. return;
  8281. }
  8282. setFillStyle( material.color.getStyle() );
  8283. _context.save();
  8284. _context.translate( v1.x, v1.y );
  8285. _context.rotate( - element.rotation );
  8286. _context.scale( scaleX, scaleY );
  8287. _context.fillRect( -1, -1, 2, 2 );
  8288. _context.restore();
  8289. } else {
  8290. bitmap = material.map.image;
  8291. bitmapWidth = bitmap.width >> 1;
  8292. bitmapHeight = bitmap.height >> 1;
  8293. scaleX = element.scale.x * _canvasWidthHalf;
  8294. scaleY = element.scale.y * _canvasHeightHalf;
  8295. width = scaleX * bitmapWidth;
  8296. height = scaleY * bitmapHeight;
  8297. // TODO: Rotations break this...
  8298. _elemBox.min.set( v1.x - width, v1.y - height );
  8299. _elemBox.max.set( v1.x + width, v1.y + height );
  8300. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8301. return;
  8302. }
  8303. _context.save();
  8304. _context.translate( v1.x, v1.y );
  8305. _context.rotate( - element.rotation );
  8306. _context.scale( scaleX, - scaleY );
  8307. _context.translate( - bitmapWidth, - bitmapHeight );
  8308. _context.drawImage( bitmap, 0, 0 );
  8309. _context.restore();
  8310. }
  8311. /* DEBUG
  8312. setStrokeStyle( 'rgb(255,255,0)' );
  8313. _context.beginPath();
  8314. _context.moveTo( v1.x - 10, v1.y );
  8315. _context.lineTo( v1.x + 10, v1.y );
  8316. _context.moveTo( v1.x, v1.y - 10 );
  8317. _context.lineTo( v1.x, v1.y + 10 );
  8318. _context.stroke();
  8319. */
  8320. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8321. width = element.scale.x * _canvasWidthHalf;
  8322. height = element.scale.y * _canvasHeightHalf;
  8323. _elemBox.min.set( v1.x - width, v1.y - height );
  8324. _elemBox.max.set( v1.x + width, v1.y + height );
  8325. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8326. return;
  8327. }
  8328. setStrokeStyle( material.color.getStyle() );
  8329. setFillStyle( material.color.getStyle() );
  8330. _context.save();
  8331. _context.translate( v1.x, v1.y );
  8332. _context.rotate( - element.rotation );
  8333. _context.scale( width, height );
  8334. material.program( _context );
  8335. _context.restore();
  8336. }
  8337. }
  8338. function renderLine( v1, v2, element, material ) {
  8339. setOpacity( material.opacity );
  8340. setBlending( material.blending );
  8341. _context.beginPath();
  8342. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8343. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8344. if ( material instanceof THREE.LineBasicMaterial ) {
  8345. setLineWidth( material.linewidth );
  8346. setLineCap( material.linecap );
  8347. setLineJoin( material.linejoin );
  8348. setStrokeStyle( material.color.getStyle() );
  8349. _context.stroke();
  8350. _elemBox.expandByScalar( material.linewidth * 2 );
  8351. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8352. setLineWidth( material.linewidth );
  8353. setLineCap( material.linecap );
  8354. setLineJoin( material.linejoin );
  8355. setStrokeStyle( material.color.getStyle() );
  8356. setDashAndGap( material.dashSize, material.gapSize );
  8357. _context.stroke();
  8358. _elemBox.expandByScalar( material.linewidth * 2 );
  8359. setDashAndGap( null, null );
  8360. }
  8361. }
  8362. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8363. _this.info.render.vertices += 3;
  8364. _this.info.render.faces ++;
  8365. setOpacity( material.opacity );
  8366. setBlending( material.blending );
  8367. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8368. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8369. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8370. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8371. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8372. _diffuseColor.copy( material.color );
  8373. _emissiveColor.copy( material.emissive );
  8374. if ( material.vertexColors === THREE.FaceColors ) {
  8375. _diffuseColor.multiply( element.color );
  8376. }
  8377. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8378. _color1.copy( _ambientLight );
  8379. _color2.copy( _ambientLight );
  8380. _color3.copy( _ambientLight );
  8381. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8382. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8383. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8384. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8385. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8386. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8387. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8388. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8389. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8390. } else {
  8391. _color.copy( _ambientLight );
  8392. calculateLight( element.centroidModel, element.normalModel, _color );
  8393. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8394. material.wireframe === true
  8395. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8396. : fillPath( _color );
  8397. }
  8398. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8399. if ( material.map !== null ) {
  8400. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8401. _uvs = element.uvs[ 0 ];
  8402. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  8403. }
  8404. } else if ( material.envMap !== null ) {
  8405. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8406. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8407. _uv1x = 0.5 * _vector3.x + 0.5;
  8408. _uv1y = 0.5 * _vector3.y + 0.5;
  8409. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8410. _uv2x = 0.5 * _vector3.x + 0.5;
  8411. _uv2y = 0.5 * _vector3.y + 0.5;
  8412. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8413. _uv3x = 0.5 * _vector3.x + 0.5;
  8414. _uv3y = 0.5 * _vector3.y + 0.5;
  8415. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8416. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8417. }*/
  8418. } else {
  8419. _color.copy( material.color );
  8420. if ( material.vertexColors === THREE.FaceColors ) {
  8421. _color.multiply( element.color );
  8422. }
  8423. material.wireframe === true
  8424. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8425. : fillPath( _color );
  8426. }
  8427. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8428. _near = camera.near;
  8429. _far = camera.far;
  8430. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8431. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8432. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8433. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8434. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8435. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8436. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8437. var normal;
  8438. if ( material.shading == THREE.FlatShading ) {
  8439. normal = element.normalModelView;
  8440. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8441. material.wireframe === true
  8442. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8443. : fillPath( _color );
  8444. } else if ( material.shading == THREE.SmoothShading ) {
  8445. normal = element.vertexNormalsModelView[ uv1 ];
  8446. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8447. normal = element.vertexNormalsModelView[ uv2 ];
  8448. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8449. normal = element.vertexNormalsModelView[ uv3 ];
  8450. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8451. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8452. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8453. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8454. }
  8455. }
  8456. }
  8457. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8458. _this.info.render.vertices += 4;
  8459. _this.info.render.faces ++;
  8460. setOpacity( material.opacity );
  8461. setBlending( material.blending );
  8462. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8463. // Let renderFace3() handle this
  8464. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8465. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8466. return;
  8467. }
  8468. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8469. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8470. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8471. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8472. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8473. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8474. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8475. _diffuseColor.copy( material.color );
  8476. _emissiveColor.copy( material.emissive );
  8477. if ( material.vertexColors === THREE.FaceColors ) {
  8478. _diffuseColor.multiply( element.color );
  8479. }
  8480. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8481. _color1.copy( _ambientLight );
  8482. _color2.copy( _ambientLight );
  8483. _color3.copy( _ambientLight );
  8484. _color4.copy( _ambientLight );
  8485. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8486. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8487. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8488. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8489. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8490. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8491. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8492. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8493. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8494. // TODO: UVs are incorrect, v4->v3?
  8495. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8496. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8497. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8498. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8499. } else {
  8500. _color.copy( _ambientLight );
  8501. calculateLight( element.centroidModel, element.normalModel, _color );
  8502. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8503. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8504. material.wireframe === true
  8505. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8506. : fillPath( _color );
  8507. }
  8508. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8509. _color.copy( material.color );
  8510. if ( material.vertexColors === THREE.FaceColors ) {
  8511. _color.multiply( element.color );
  8512. }
  8513. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8514. material.wireframe === true
  8515. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8516. : fillPath( _color );
  8517. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8518. var normal;
  8519. if ( material.shading == THREE.FlatShading ) {
  8520. normal = element.normalModelView;
  8521. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8522. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8523. material.wireframe === true
  8524. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8525. : fillPath( _color );
  8526. } else if ( material.shading == THREE.SmoothShading ) {
  8527. normal = element.vertexNormalsModelView[ 0 ];
  8528. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8529. normal = element.vertexNormalsModelView[ 1 ];
  8530. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8531. normal = element.vertexNormalsModelView[ 3 ];
  8532. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8533. normal = element.vertexNormalsModelView[ 2 ];
  8534. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8535. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8536. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8537. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8538. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8539. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8540. }
  8541. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8542. _near = camera.near;
  8543. _far = camera.far;
  8544. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8545. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8546. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8547. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8548. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8549. // TODO: UVs are incorrect, v4->v3?
  8550. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8551. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8552. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8553. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8554. }
  8555. }
  8556. //
  8557. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8558. _context.beginPath();
  8559. _context.moveTo( x0, y0 );
  8560. _context.lineTo( x1, y1 );
  8561. _context.lineTo( x2, y2 );
  8562. _context.closePath();
  8563. }
  8564. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8565. _context.beginPath();
  8566. _context.moveTo( x0, y0 );
  8567. _context.lineTo( x1, y1 );
  8568. _context.lineTo( x2, y2 );
  8569. _context.lineTo( x3, y3 );
  8570. _context.closePath();
  8571. }
  8572. function strokePath( color, linewidth, linecap, linejoin ) {
  8573. setLineWidth( linewidth );
  8574. setLineCap( linecap );
  8575. setLineJoin( linejoin );
  8576. setStrokeStyle( color.getStyle() );
  8577. _context.stroke();
  8578. _elemBox.expandByScalar( linewidth * 2 );
  8579. }
  8580. function fillPath( color ) {
  8581. setFillStyle( color.getStyle() );
  8582. _context.fill();
  8583. }
  8584. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8585. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8586. if ( texture.needsUpdate === true ) {
  8587. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8588. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8589. _patterns[ texture.id ] = _context.createPattern(
  8590. texture.image, repeatX === true && repeatY === true
  8591. ? 'repeat'
  8592. : repeatX === true && repeatY === false
  8593. ? 'repeat-x'
  8594. : repeatX === false && repeatY === true
  8595. ? 'repeat-y'
  8596. : 'no-repeat'
  8597. );
  8598. texture.needsUpdate = false;
  8599. }
  8600. _patterns[ texture.id ] === undefined
  8601. ? setFillStyle( 'rgba(0,0,0,1)' )
  8602. : setFillStyle( _patterns[ texture.id ] );
  8603. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8604. var a, b, c, d, e, f, det, idet,
  8605. offsetX = texture.offset.x / texture.repeat.x,
  8606. offsetY = texture.offset.y / texture.repeat.y,
  8607. width = texture.image.width * texture.repeat.x,
  8608. height = texture.image.height * texture.repeat.y;
  8609. u0 = ( u0 + offsetX ) * width;
  8610. v0 = ( 1.0 - v0 + offsetY ) * height;
  8611. u1 = ( u1 + offsetX ) * width;
  8612. v1 = ( 1.0 - v1 + offsetY ) * height;
  8613. u2 = ( u2 + offsetX ) * width;
  8614. v2 = ( 1.0 - v2 + offsetY ) * height;
  8615. x1 -= x0; y1 -= y0;
  8616. x2 -= x0; y2 -= y0;
  8617. u1 -= u0; v1 -= v0;
  8618. u2 -= u0; v2 -= v0;
  8619. det = u1 * v2 - u2 * v1;
  8620. if ( det === 0 ) {
  8621. if ( _imagedatas[ texture.id ] === undefined ) {
  8622. var canvas = document.createElement( 'canvas' )
  8623. canvas.width = texture.image.width;
  8624. canvas.height = texture.image.height;
  8625. var context = canvas.getContext( '2d' );
  8626. context.drawImage( texture.image, 0, 0 );
  8627. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8628. }
  8629. var data = _imagedatas[ texture.id ];
  8630. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8631. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8632. fillPath( _color );
  8633. return;
  8634. }
  8635. idet = 1 / det;
  8636. a = ( v2 * x1 - v1 * x2 ) * idet;
  8637. b = ( v2 * y1 - v1 * y2 ) * idet;
  8638. c = ( u1 * x2 - u2 * x1 ) * idet;
  8639. d = ( u1 * y2 - u2 * y1 ) * idet;
  8640. e = x0 - a * u0 - c * v0;
  8641. f = y0 - b * u0 - d * v0;
  8642. _context.save();
  8643. _context.transform( a, b, c, d, e, f );
  8644. _context.fill();
  8645. _context.restore();
  8646. }
  8647. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8648. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8649. var a, b, c, d, e, f, det, idet,
  8650. width = image.width - 1,
  8651. height = image.height - 1;
  8652. u0 *= width; v0 *= height;
  8653. u1 *= width; v1 *= height;
  8654. u2 *= width; v2 *= height;
  8655. x1 -= x0; y1 -= y0;
  8656. x2 -= x0; y2 -= y0;
  8657. u1 -= u0; v1 -= v0;
  8658. u2 -= u0; v2 -= v0;
  8659. det = u1 * v2 - u2 * v1;
  8660. idet = 1 / det;
  8661. a = ( v2 * x1 - v1 * x2 ) * idet;
  8662. b = ( v2 * y1 - v1 * y2 ) * idet;
  8663. c = ( u1 * x2 - u2 * x1 ) * idet;
  8664. d = ( u1 * y2 - u2 * y1 ) * idet;
  8665. e = x0 - a * u0 - c * v0;
  8666. f = y0 - b * u0 - d * v0;
  8667. _context.save();
  8668. _context.transform( a, b, c, d, e, f );
  8669. _context.clip();
  8670. _context.drawImage( image, 0, 0 );
  8671. _context.restore();
  8672. }
  8673. function getGradientTexture( color1, color2, color3, color4 ) {
  8674. // http://mrdoob.com/blog/post/710
  8675. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8676. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8677. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8678. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8679. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8680. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8681. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8682. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8683. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8684. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8685. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8686. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8687. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8688. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8689. return _gradientMap;
  8690. }
  8691. // Hide anti-alias gaps
  8692. function expand( v1, v2 ) {
  8693. var x = v2.x - v1.x, y = v2.y - v1.y,
  8694. det = x * x + y * y, idet;
  8695. if ( det === 0 ) return;
  8696. idet = 1 / Math.sqrt( det );
  8697. x *= idet; y *= idet;
  8698. v2.x += x; v2.y += y;
  8699. v1.x -= x; v1.y -= y;
  8700. }
  8701. };
  8702. // Context cached methods.
  8703. function setOpacity( value ) {
  8704. if ( _contextGlobalAlpha !== value ) {
  8705. _context.globalAlpha = value;
  8706. _contextGlobalAlpha = value;
  8707. }
  8708. }
  8709. function setBlending( value ) {
  8710. if ( _contextGlobalCompositeOperation !== value ) {
  8711. if ( value === THREE.NormalBlending ) {
  8712. _context.globalCompositeOperation = 'source-over';
  8713. } else if ( value === THREE.AdditiveBlending ) {
  8714. _context.globalCompositeOperation = 'lighter';
  8715. } else if ( value === THREE.SubtractiveBlending ) {
  8716. _context.globalCompositeOperation = 'darker';
  8717. }
  8718. _contextGlobalCompositeOperation = value;
  8719. }
  8720. }
  8721. function setLineWidth( value ) {
  8722. if ( _contextLineWidth !== value ) {
  8723. _context.lineWidth = value;
  8724. _contextLineWidth = value;
  8725. }
  8726. }
  8727. function setLineCap( value ) {
  8728. // "butt", "round", "square"
  8729. if ( _contextLineCap !== value ) {
  8730. _context.lineCap = value;
  8731. _contextLineCap = value;
  8732. }
  8733. }
  8734. function setLineJoin( value ) {
  8735. // "round", "bevel", "miter"
  8736. if ( _contextLineJoin !== value ) {
  8737. _context.lineJoin = value;
  8738. _contextLineJoin = value;
  8739. }
  8740. }
  8741. function setStrokeStyle( value ) {
  8742. if ( _contextStrokeStyle !== value ) {
  8743. _context.strokeStyle = value;
  8744. _contextStrokeStyle = value;
  8745. }
  8746. }
  8747. function setFillStyle( value ) {
  8748. if ( _contextFillStyle !== value ) {
  8749. _context.fillStyle = value;
  8750. _contextFillStyle = value;
  8751. }
  8752. }
  8753. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8754. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8755. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8756. _contextDashSize = dashSizeValue;
  8757. _contextGapSize = gapSizeValue;
  8758. }
  8759. }
  8760. };
  8761. /**
  8762. * @author alteredq / http://alteredqualia.com/
  8763. * @author mrdoob / http://mrdoob.com/
  8764. * @author mikael emtinger / http://gomo.se/
  8765. */
  8766. THREE.ShaderChunk = {
  8767. // FOG
  8768. fog_pars_fragment: [
  8769. "#ifdef USE_FOG",
  8770. "uniform vec3 fogColor;",
  8771. "#ifdef FOG_EXP2",
  8772. "uniform float fogDensity;",
  8773. "#else",
  8774. "uniform float fogNear;",
  8775. "uniform float fogFar;",
  8776. "#endif",
  8777. "#endif"
  8778. ].join("\n"),
  8779. fog_fragment: [
  8780. "#ifdef USE_FOG",
  8781. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8782. "#ifdef FOG_EXP2",
  8783. "const float LOG2 = 1.442695;",
  8784. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8785. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8786. "#else",
  8787. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8788. "#endif",
  8789. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8790. "#endif"
  8791. ].join("\n"),
  8792. // ENVIRONMENT MAP
  8793. envmap_pars_fragment: [
  8794. "#ifdef USE_ENVMAP",
  8795. "uniform float reflectivity;",
  8796. "uniform samplerCube envMap;",
  8797. "uniform float flipEnvMap;",
  8798. "uniform int combine;",
  8799. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8800. "uniform bool useRefract;",
  8801. "uniform float refractionRatio;",
  8802. "#else",
  8803. "varying vec3 vReflect;",
  8804. "#endif",
  8805. "#endif"
  8806. ].join("\n"),
  8807. envmap_fragment: [
  8808. "#ifdef USE_ENVMAP",
  8809. "vec3 reflectVec;",
  8810. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8811. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8812. "if ( useRefract ) {",
  8813. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8814. "} else { ",
  8815. "reflectVec = reflect( cameraToVertex, normal );",
  8816. "}",
  8817. "#else",
  8818. "reflectVec = vReflect;",
  8819. "#endif",
  8820. "#ifdef DOUBLE_SIDED",
  8821. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8822. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8823. "#else",
  8824. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8825. "#endif",
  8826. "#ifdef GAMMA_INPUT",
  8827. "cubeColor.xyz *= cubeColor.xyz;",
  8828. "#endif",
  8829. "if ( combine == 1 ) {",
  8830. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8831. "} else if ( combine == 2 ) {",
  8832. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8833. "} else {",
  8834. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8835. "}",
  8836. "#endif"
  8837. ].join("\n"),
  8838. envmap_pars_vertex: [
  8839. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8840. "varying vec3 vReflect;",
  8841. "uniform float refractionRatio;",
  8842. "uniform bool useRefract;",
  8843. "#endif"
  8844. ].join("\n"),
  8845. worldpos_vertex : [
  8846. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8847. "#ifdef USE_SKINNING",
  8848. "vec4 worldPosition = modelMatrix * skinned;",
  8849. "#endif",
  8850. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8851. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8852. "#endif",
  8853. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8854. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8855. "#endif",
  8856. "#endif"
  8857. ].join("\n"),
  8858. envmap_vertex : [
  8859. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8860. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8861. "worldNormal = normalize( worldNormal );",
  8862. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8863. "if ( useRefract ) {",
  8864. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8865. "} else {",
  8866. "vReflect = reflect( cameraToVertex, worldNormal );",
  8867. "}",
  8868. "#endif"
  8869. ].join("\n"),
  8870. // COLOR MAP (particles)
  8871. map_particle_pars_fragment: [
  8872. "#ifdef USE_MAP",
  8873. "uniform sampler2D map;",
  8874. "#endif"
  8875. ].join("\n"),
  8876. map_particle_fragment: [
  8877. "#ifdef USE_MAP",
  8878. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8879. "#endif"
  8880. ].join("\n"),
  8881. // COLOR MAP (triangles)
  8882. map_pars_vertex: [
  8883. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8884. "varying vec2 vUv;",
  8885. "uniform vec4 offsetRepeat;",
  8886. "#endif"
  8887. ].join("\n"),
  8888. map_pars_fragment: [
  8889. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8890. "varying vec2 vUv;",
  8891. "#endif",
  8892. "#ifdef USE_MAP",
  8893. "uniform sampler2D map;",
  8894. "#endif"
  8895. ].join("\n"),
  8896. map_vertex: [
  8897. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8898. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8899. "#endif"
  8900. ].join("\n"),
  8901. map_fragment: [
  8902. "#ifdef USE_MAP",
  8903. "vec4 texelColor = texture2D( map, vUv );",
  8904. "#ifdef GAMMA_INPUT",
  8905. "texelColor.xyz *= texelColor.xyz;",
  8906. "#endif",
  8907. "gl_FragColor = gl_FragColor * texelColor;",
  8908. "#endif"
  8909. ].join("\n"),
  8910. // LIGHT MAP
  8911. lightmap_pars_fragment: [
  8912. "#ifdef USE_LIGHTMAP",
  8913. "varying vec2 vUv2;",
  8914. "uniform sampler2D lightMap;",
  8915. "#endif"
  8916. ].join("\n"),
  8917. lightmap_pars_vertex: [
  8918. "#ifdef USE_LIGHTMAP",
  8919. "varying vec2 vUv2;",
  8920. "#endif"
  8921. ].join("\n"),
  8922. lightmap_fragment: [
  8923. "#ifdef USE_LIGHTMAP",
  8924. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8925. "#endif"
  8926. ].join("\n"),
  8927. lightmap_vertex: [
  8928. "#ifdef USE_LIGHTMAP",
  8929. "vUv2 = uv2;",
  8930. "#endif"
  8931. ].join("\n"),
  8932. // BUMP MAP
  8933. bumpmap_pars_fragment: [
  8934. "#ifdef USE_BUMPMAP",
  8935. "uniform sampler2D bumpMap;",
  8936. "uniform float bumpScale;",
  8937. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8938. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8939. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8940. "vec2 dHdxy_fwd() {",
  8941. "vec2 dSTdx = dFdx( vUv );",
  8942. "vec2 dSTdy = dFdy( vUv );",
  8943. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8944. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8945. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8946. "return vec2( dBx, dBy );",
  8947. "}",
  8948. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8949. "vec3 vSigmaX = dFdx( surf_pos );",
  8950. "vec3 vSigmaY = dFdy( surf_pos );",
  8951. "vec3 vN = surf_norm;", // normalized
  8952. "vec3 R1 = cross( vSigmaY, vN );",
  8953. "vec3 R2 = cross( vN, vSigmaX );",
  8954. "float fDet = dot( vSigmaX, R1 );",
  8955. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8956. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8957. "}",
  8958. "#endif"
  8959. ].join("\n"),
  8960. // NORMAL MAP
  8961. normalmap_pars_fragment: [
  8962. "#ifdef USE_NORMALMAP",
  8963. "uniform sampler2D normalMap;",
  8964. "uniform vec2 normalScale;",
  8965. // Per-Pixel Tangent Space Normal Mapping
  8966. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8967. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8968. "vec3 q0 = dFdx( eye_pos.xyz );",
  8969. "vec3 q1 = dFdy( eye_pos.xyz );",
  8970. "vec2 st0 = dFdx( vUv.st );",
  8971. "vec2 st1 = dFdy( vUv.st );",
  8972. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8973. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8974. "vec3 N = normalize( surf_norm );",
  8975. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8976. "mapN.xy = normalScale * mapN.xy;",
  8977. "mat3 tsn = mat3( S, T, N );",
  8978. "return normalize( tsn * mapN );",
  8979. "}",
  8980. "#endif"
  8981. ].join("\n"),
  8982. // SPECULAR MAP
  8983. specularmap_pars_fragment: [
  8984. "#ifdef USE_SPECULARMAP",
  8985. "uniform sampler2D specularMap;",
  8986. "#endif"
  8987. ].join("\n"),
  8988. specularmap_fragment: [
  8989. "float specularStrength;",
  8990. "#ifdef USE_SPECULARMAP",
  8991. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8992. "specularStrength = texelSpecular.r;",
  8993. "#else",
  8994. "specularStrength = 1.0;",
  8995. "#endif"
  8996. ].join("\n"),
  8997. // LIGHTS LAMBERT
  8998. lights_lambert_pars_vertex: [
  8999. "uniform vec3 ambient;",
  9000. "uniform vec3 diffuse;",
  9001. "uniform vec3 emissive;",
  9002. "uniform vec3 ambientLightColor;",
  9003. "#if MAX_DIR_LIGHTS > 0",
  9004. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9005. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9006. "#endif",
  9007. "#if MAX_HEMI_LIGHTS > 0",
  9008. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9009. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9010. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9011. "#endif",
  9012. "#if MAX_POINT_LIGHTS > 0",
  9013. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9014. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9015. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9016. "#endif",
  9017. "#if MAX_SPOT_LIGHTS > 0",
  9018. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9019. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9020. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9021. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9022. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9023. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9024. "#endif",
  9025. "#ifdef WRAP_AROUND",
  9026. "uniform vec3 wrapRGB;",
  9027. "#endif"
  9028. ].join("\n"),
  9029. lights_lambert_vertex: [
  9030. "vLightFront = vec3( 0.0 );",
  9031. "#ifdef DOUBLE_SIDED",
  9032. "vLightBack = vec3( 0.0 );",
  9033. "#endif",
  9034. "transformedNormal = normalize( transformedNormal );",
  9035. "#if MAX_DIR_LIGHTS > 0",
  9036. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9037. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9038. "vec3 dirVector = normalize( lDirection.xyz );",
  9039. "float dotProduct = dot( transformedNormal, dirVector );",
  9040. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9041. "#ifdef DOUBLE_SIDED",
  9042. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9043. "#ifdef WRAP_AROUND",
  9044. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9045. "#endif",
  9046. "#endif",
  9047. "#ifdef WRAP_AROUND",
  9048. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9049. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9050. "#ifdef DOUBLE_SIDED",
  9051. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9052. "#endif",
  9053. "#endif",
  9054. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9055. "#ifdef DOUBLE_SIDED",
  9056. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9057. "#endif",
  9058. "}",
  9059. "#endif",
  9060. "#if MAX_POINT_LIGHTS > 0",
  9061. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9062. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9063. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9064. "float lDistance = 1.0;",
  9065. "if ( pointLightDistance[ i ] > 0.0 )",
  9066. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9067. "lVector = normalize( lVector );",
  9068. "float dotProduct = dot( transformedNormal, lVector );",
  9069. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9070. "#ifdef DOUBLE_SIDED",
  9071. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9072. "#ifdef WRAP_AROUND",
  9073. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9074. "#endif",
  9075. "#endif",
  9076. "#ifdef WRAP_AROUND",
  9077. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9078. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9079. "#ifdef DOUBLE_SIDED",
  9080. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9081. "#endif",
  9082. "#endif",
  9083. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9084. "#ifdef DOUBLE_SIDED",
  9085. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9086. "#endif",
  9087. "}",
  9088. "#endif",
  9089. "#if MAX_SPOT_LIGHTS > 0",
  9090. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9091. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9092. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9093. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9094. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9095. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9096. "float lDistance = 1.0;",
  9097. "if ( spotLightDistance[ i ] > 0.0 )",
  9098. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9099. "lVector = normalize( lVector );",
  9100. "float dotProduct = dot( transformedNormal, lVector );",
  9101. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9102. "#ifdef DOUBLE_SIDED",
  9103. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9104. "#ifdef WRAP_AROUND",
  9105. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9106. "#endif",
  9107. "#endif",
  9108. "#ifdef WRAP_AROUND",
  9109. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9110. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9111. "#ifdef DOUBLE_SIDED",
  9112. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9113. "#endif",
  9114. "#endif",
  9115. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9116. "#ifdef DOUBLE_SIDED",
  9117. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9118. "#endif",
  9119. "}",
  9120. "}",
  9121. "#endif",
  9122. "#if MAX_HEMI_LIGHTS > 0",
  9123. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9124. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9125. "vec3 lVector = normalize( lDirection.xyz );",
  9126. "float dotProduct = dot( transformedNormal, lVector );",
  9127. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9128. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9129. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9130. "#ifdef DOUBLE_SIDED",
  9131. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9132. "#endif",
  9133. "}",
  9134. "#endif",
  9135. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9136. "#ifdef DOUBLE_SIDED",
  9137. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9138. "#endif"
  9139. ].join("\n"),
  9140. // LIGHTS PHONG
  9141. lights_phong_pars_vertex: [
  9142. "#ifndef PHONG_PER_PIXEL",
  9143. "#if MAX_POINT_LIGHTS > 0",
  9144. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9145. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9146. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9147. "#endif",
  9148. "#if MAX_SPOT_LIGHTS > 0",
  9149. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9150. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9151. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9152. "#endif",
  9153. "#endif",
  9154. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9155. "varying vec3 vWorldPosition;",
  9156. "#endif"
  9157. ].join("\n"),
  9158. lights_phong_vertex: [
  9159. "#ifndef PHONG_PER_PIXEL",
  9160. "#if MAX_POINT_LIGHTS > 0",
  9161. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9162. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9163. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9164. "float lDistance = 1.0;",
  9165. "if ( pointLightDistance[ i ] > 0.0 )",
  9166. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9167. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9168. "}",
  9169. "#endif",
  9170. "#if MAX_SPOT_LIGHTS > 0",
  9171. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9172. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9173. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9174. "float lDistance = 1.0;",
  9175. "if ( spotLightDistance[ i ] > 0.0 )",
  9176. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9177. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9178. "}",
  9179. "#endif",
  9180. "#endif",
  9181. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9182. "vWorldPosition = worldPosition.xyz;",
  9183. "#endif"
  9184. ].join("\n"),
  9185. lights_phong_pars_fragment: [
  9186. "uniform vec3 ambientLightColor;",
  9187. "#if MAX_DIR_LIGHTS > 0",
  9188. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9189. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9190. "#endif",
  9191. "#if MAX_HEMI_LIGHTS > 0",
  9192. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9193. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9194. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9195. "#endif",
  9196. "#if MAX_POINT_LIGHTS > 0",
  9197. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9198. "#ifdef PHONG_PER_PIXEL",
  9199. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9200. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9201. "#else",
  9202. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9203. "#endif",
  9204. "#endif",
  9205. "#if MAX_SPOT_LIGHTS > 0",
  9206. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9207. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9208. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9209. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9210. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9211. "#ifdef PHONG_PER_PIXEL",
  9212. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9213. "#else",
  9214. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9215. "#endif",
  9216. "#endif",
  9217. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9218. "varying vec3 vWorldPosition;",
  9219. "#endif",
  9220. "#ifdef WRAP_AROUND",
  9221. "uniform vec3 wrapRGB;",
  9222. "#endif",
  9223. "varying vec3 vViewPosition;",
  9224. "varying vec3 vNormal;"
  9225. ].join("\n"),
  9226. lights_phong_fragment: [
  9227. "vec3 normal = normalize( vNormal );",
  9228. "vec3 viewPosition = normalize( vViewPosition );",
  9229. "#ifdef DOUBLE_SIDED",
  9230. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9231. "#endif",
  9232. "#ifdef USE_NORMALMAP",
  9233. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9234. "#elif defined( USE_BUMPMAP )",
  9235. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9236. "#endif",
  9237. "#if MAX_POINT_LIGHTS > 0",
  9238. "vec3 pointDiffuse = vec3( 0.0 );",
  9239. "vec3 pointSpecular = vec3( 0.0 );",
  9240. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9241. "#ifdef PHONG_PER_PIXEL",
  9242. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9243. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9244. "float lDistance = 1.0;",
  9245. "if ( pointLightDistance[ i ] > 0.0 )",
  9246. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9247. "lVector = normalize( lVector );",
  9248. "#else",
  9249. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9250. "float lDistance = vPointLight[ i ].w;",
  9251. "#endif",
  9252. // diffuse
  9253. "float dotProduct = dot( normal, lVector );",
  9254. "#ifdef WRAP_AROUND",
  9255. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9256. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9257. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9258. "#else",
  9259. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9260. "#endif",
  9261. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9262. // specular
  9263. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9264. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9265. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9266. "#ifdef PHYSICALLY_BASED_SHADING",
  9267. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9268. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9269. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9270. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9271. "#else",
  9272. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9273. "#endif",
  9274. "}",
  9275. "#endif",
  9276. "#if MAX_SPOT_LIGHTS > 0",
  9277. "vec3 spotDiffuse = vec3( 0.0 );",
  9278. "vec3 spotSpecular = vec3( 0.0 );",
  9279. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9280. "#ifdef PHONG_PER_PIXEL",
  9281. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9282. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9283. "float lDistance = 1.0;",
  9284. "if ( spotLightDistance[ i ] > 0.0 )",
  9285. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9286. "lVector = normalize( lVector );",
  9287. "#else",
  9288. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9289. "float lDistance = vSpotLight[ i ].w;",
  9290. "#endif",
  9291. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9292. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9293. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9294. // diffuse
  9295. "float dotProduct = dot( normal, lVector );",
  9296. "#ifdef WRAP_AROUND",
  9297. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9298. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9299. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9300. "#else",
  9301. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9302. "#endif",
  9303. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9304. // specular
  9305. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9306. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9307. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9308. "#ifdef PHYSICALLY_BASED_SHADING",
  9309. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9310. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9311. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9312. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9313. "#else",
  9314. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9315. "#endif",
  9316. "}",
  9317. "}",
  9318. "#endif",
  9319. "#if MAX_DIR_LIGHTS > 0",
  9320. "vec3 dirDiffuse = vec3( 0.0 );",
  9321. "vec3 dirSpecular = vec3( 0.0 );" ,
  9322. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9323. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9324. "vec3 dirVector = normalize( lDirection.xyz );",
  9325. // diffuse
  9326. "float dotProduct = dot( normal, dirVector );",
  9327. "#ifdef WRAP_AROUND",
  9328. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9329. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9330. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9331. "#else",
  9332. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9333. "#endif",
  9334. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9335. // specular
  9336. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9337. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9338. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9339. "#ifdef PHYSICALLY_BASED_SHADING",
  9340. /*
  9341. // fresnel term from skin shader
  9342. "const float F0 = 0.128;",
  9343. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9344. "float exponential = pow( base, 5.0 );",
  9345. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9346. */
  9347. /*
  9348. // fresnel term from fresnel shader
  9349. "const float mFresnelBias = 0.08;",
  9350. "const float mFresnelScale = 0.3;",
  9351. "const float mFresnelPower = 5.0;",
  9352. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9353. */
  9354. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9355. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9356. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9357. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9358. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9359. "#else",
  9360. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9361. "#endif",
  9362. "}",
  9363. "#endif",
  9364. "#if MAX_HEMI_LIGHTS > 0",
  9365. "vec3 hemiDiffuse = vec3( 0.0 );",
  9366. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9367. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9368. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9369. "vec3 lVector = normalize( lDirection.xyz );",
  9370. // diffuse
  9371. "float dotProduct = dot( normal, lVector );",
  9372. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9373. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9374. "hemiDiffuse += diffuse * hemiColor;",
  9375. // specular (sky light)
  9376. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9377. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9378. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9379. // specular (ground light)
  9380. "vec3 lVectorGround = -lVector;",
  9381. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9382. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9383. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9384. "#ifdef PHYSICALLY_BASED_SHADING",
  9385. "float dotProductGround = dot( normal, lVectorGround );",
  9386. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9387. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9388. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9389. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9390. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9391. "#else",
  9392. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9393. "#endif",
  9394. "}",
  9395. "#endif",
  9396. "vec3 totalDiffuse = vec3( 0.0 );",
  9397. "vec3 totalSpecular = vec3( 0.0 );",
  9398. "#if MAX_DIR_LIGHTS > 0",
  9399. "totalDiffuse += dirDiffuse;",
  9400. "totalSpecular += dirSpecular;",
  9401. "#endif",
  9402. "#if MAX_HEMI_LIGHTS > 0",
  9403. "totalDiffuse += hemiDiffuse;",
  9404. "totalSpecular += hemiSpecular;",
  9405. "#endif",
  9406. "#if MAX_POINT_LIGHTS > 0",
  9407. "totalDiffuse += pointDiffuse;",
  9408. "totalSpecular += pointSpecular;",
  9409. "#endif",
  9410. "#if MAX_SPOT_LIGHTS > 0",
  9411. "totalDiffuse += spotDiffuse;",
  9412. "totalSpecular += spotSpecular;",
  9413. "#endif",
  9414. "#ifdef METAL",
  9415. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9416. "#else",
  9417. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9418. "#endif"
  9419. ].join("\n"),
  9420. // VERTEX COLORS
  9421. color_pars_fragment: [
  9422. "#ifdef USE_COLOR",
  9423. "varying vec3 vColor;",
  9424. "#endif"
  9425. ].join("\n"),
  9426. color_fragment: [
  9427. "#ifdef USE_COLOR",
  9428. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9429. "#endif"
  9430. ].join("\n"),
  9431. color_pars_vertex: [
  9432. "#ifdef USE_COLOR",
  9433. "varying vec3 vColor;",
  9434. "#endif"
  9435. ].join("\n"),
  9436. color_vertex: [
  9437. "#ifdef USE_COLOR",
  9438. "#ifdef GAMMA_INPUT",
  9439. "vColor = color * color;",
  9440. "#else",
  9441. "vColor = color;",
  9442. "#endif",
  9443. "#endif"
  9444. ].join("\n"),
  9445. // SKINNING
  9446. skinning_pars_vertex: [
  9447. "#ifdef USE_SKINNING",
  9448. "#ifdef BONE_TEXTURE",
  9449. "uniform sampler2D boneTexture;",
  9450. "mat4 getBoneMatrix( const in float i ) {",
  9451. "float j = i * 4.0;",
  9452. "float x = mod( j, N_BONE_PIXEL_X );",
  9453. "float y = floor( j / N_BONE_PIXEL_X );",
  9454. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9455. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9456. "y = dy * ( y + 0.5 );",
  9457. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9458. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9459. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9460. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9461. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9462. "return bone;",
  9463. "}",
  9464. "#else",
  9465. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9466. "mat4 getBoneMatrix( const in float i ) {",
  9467. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9468. "return bone;",
  9469. "}",
  9470. "#endif",
  9471. "#endif"
  9472. ].join("\n"),
  9473. skinbase_vertex: [
  9474. "#ifdef USE_SKINNING",
  9475. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9476. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9477. "#endif"
  9478. ].join("\n"),
  9479. skinning_vertex: [
  9480. "#ifdef USE_SKINNING",
  9481. "#ifdef USE_MORPHTARGETS",
  9482. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9483. "#else",
  9484. "vec4 skinVertex = vec4( position, 1.0 );",
  9485. "#endif",
  9486. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9487. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9488. "#endif"
  9489. ].join("\n"),
  9490. // MORPHING
  9491. morphtarget_pars_vertex: [
  9492. "#ifdef USE_MORPHTARGETS",
  9493. "#ifndef USE_MORPHNORMALS",
  9494. "uniform float morphTargetInfluences[ 8 ];",
  9495. "#else",
  9496. "uniform float morphTargetInfluences[ 4 ];",
  9497. "#endif",
  9498. "#endif"
  9499. ].join("\n"),
  9500. morphtarget_vertex: [
  9501. "#ifdef USE_MORPHTARGETS",
  9502. "vec3 morphed = vec3( 0.0 );",
  9503. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9504. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9505. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9506. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9507. "#ifndef USE_MORPHNORMALS",
  9508. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9509. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9510. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9511. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9512. "#endif",
  9513. "morphed += position;",
  9514. "#endif"
  9515. ].join("\n"),
  9516. default_vertex : [
  9517. "vec4 mvPosition;",
  9518. "#ifdef USE_SKINNING",
  9519. "mvPosition = modelViewMatrix * skinned;",
  9520. "#endif",
  9521. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9522. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9523. "#endif",
  9524. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9525. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9526. "#endif",
  9527. "gl_Position = projectionMatrix * mvPosition;"
  9528. ].join("\n"),
  9529. morphnormal_vertex: [
  9530. "#ifdef USE_MORPHNORMALS",
  9531. "vec3 morphedNormal = vec3( 0.0 );",
  9532. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9533. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9534. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9535. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9536. "morphedNormal += normal;",
  9537. "#endif"
  9538. ].join("\n"),
  9539. skinnormal_vertex: [
  9540. "#ifdef USE_SKINNING",
  9541. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9542. "skinMatrix += skinWeight.y * boneMatY;",
  9543. "#ifdef USE_MORPHNORMALS",
  9544. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9545. "#else",
  9546. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9547. "#endif",
  9548. "#endif"
  9549. ].join("\n"),
  9550. defaultnormal_vertex: [
  9551. "vec3 objectNormal;",
  9552. "#ifdef USE_SKINNING",
  9553. "objectNormal = skinnedNormal.xyz;",
  9554. "#endif",
  9555. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9556. "objectNormal = morphedNormal;",
  9557. "#endif",
  9558. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9559. "objectNormal = normal;",
  9560. "#endif",
  9561. "#ifdef FLIP_SIDED",
  9562. "objectNormal = -objectNormal;",
  9563. "#endif",
  9564. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9565. ].join("\n"),
  9566. // SHADOW MAP
  9567. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9568. // http://spidergl.org/example.php?id=6
  9569. // http://fabiensanglard.net/shadowmapping
  9570. shadowmap_pars_fragment: [
  9571. "#ifdef USE_SHADOWMAP",
  9572. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9573. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9574. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9575. "uniform float shadowBias[ MAX_SHADOWS ];",
  9576. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9577. "float unpackDepth( const in vec4 rgba_depth ) {",
  9578. "const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  9579. "float depth = dot( rgba_depth, bit_shift );",
  9580. "return depth;",
  9581. "}",
  9582. "#endif"
  9583. ].join("\n"),
  9584. shadowmap_fragment: [
  9585. "#ifdef USE_SHADOWMAP",
  9586. "#ifdef SHADOWMAP_DEBUG",
  9587. "vec3 frustumColors[3];",
  9588. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9589. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9590. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9591. "#endif",
  9592. "#ifdef SHADOWMAP_CASCADE",
  9593. "int inFrustumCount = 0;",
  9594. "#endif",
  9595. "float fDepth;",
  9596. "vec3 shadowColor = vec3( 1.0 );",
  9597. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9598. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9599. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9600. // "if ( all( something, something ) )" using this instead
  9601. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9602. "bool inFrustum = all( inFrustumVec );",
  9603. // don't shadow pixels outside of light frustum
  9604. // use just first frustum (for cascades)
  9605. // don't shadow pixels behind far plane of light frustum
  9606. "#ifdef SHADOWMAP_CASCADE",
  9607. "inFrustumCount += int( inFrustum );",
  9608. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9609. "#else",
  9610. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9611. "#endif",
  9612. "bool frustumTest = all( frustumTestVec );",
  9613. "if ( frustumTest ) {",
  9614. "shadowCoord.z += shadowBias[ i ];",
  9615. "#if defined( SHADOWMAP_TYPE_PCF )",
  9616. // Percentage-close filtering
  9617. // (9 pixel kernel)
  9618. // http://fabiensanglard.net/shadowmappingPCF/
  9619. "float shadow = 0.0;",
  9620. /*
  9621. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9622. // must enroll loop manually
  9623. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9624. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9625. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9626. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9627. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9628. "float fDepth = unpackDepth( rgbaDepth );",
  9629. "if ( fDepth < shadowCoord.z )",
  9630. "shadow += 1.0;",
  9631. "}",
  9632. "shadow /= 9.0;",
  9633. */
  9634. "const float shadowDelta = 1.0 / 9.0;",
  9635. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9636. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9637. "float dx0 = -1.25 * xPixelOffset;",
  9638. "float dy0 = -1.25 * yPixelOffset;",
  9639. "float dx1 = 1.25 * xPixelOffset;",
  9640. "float dy1 = 1.25 * yPixelOffset;",
  9641. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9642. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9643. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9644. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9645. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9646. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9647. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9648. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9649. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9650. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9651. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9652. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9653. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9654. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9655. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9656. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9657. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9658. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9659. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9660. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9661. // Percentage-close filtering
  9662. // (9 pixel kernel)
  9663. // http://fabiensanglard.net/shadowmappingPCF/
  9664. "float shadow = 0.0;",
  9665. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9666. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9667. "float dx0 = -1.0 * xPixelOffset;",
  9668. "float dy0 = -1.0 * yPixelOffset;",
  9669. "float dx1 = 1.0 * xPixelOffset;",
  9670. "float dy1 = 1.0 * yPixelOffset;",
  9671. "mat3 shadowKernel;",
  9672. "mat3 depthKernel;",
  9673. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9674. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9675. "else shadowKernel[0][0] = 0.0;",
  9676. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9677. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9678. "else shadowKernel[0][1] = 0.0;",
  9679. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9680. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9681. "else shadowKernel[0][2] = 0.0;",
  9682. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9683. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9684. "else shadowKernel[1][0] = 0.0;",
  9685. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9686. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9687. "else shadowKernel[1][1] = 0.0;",
  9688. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9689. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9690. "else shadowKernel[1][2] = 0.0;",
  9691. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9692. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9693. "else shadowKernel[2][0] = 0.0;",
  9694. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9695. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9696. "else shadowKernel[2][1] = 0.0;",
  9697. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9698. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9699. "else shadowKernel[2][2] = 0.0;",
  9700. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9701. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9702. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9703. "vec4 shadowValues;",
  9704. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9705. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9706. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9707. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9708. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9709. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9710. "#else",
  9711. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9712. "float fDepth = unpackDepth( rgbaDepth );",
  9713. "if ( fDepth < shadowCoord.z )",
  9714. // spot with multiple shadows is darker
  9715. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9716. // spot with multiple shadows has the same color as single shadow spot
  9717. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9718. "#endif",
  9719. "}",
  9720. "#ifdef SHADOWMAP_DEBUG",
  9721. "#ifdef SHADOWMAP_CASCADE",
  9722. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9723. "#else",
  9724. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9725. "#endif",
  9726. "#endif",
  9727. "}",
  9728. "#ifdef GAMMA_OUTPUT",
  9729. "shadowColor *= shadowColor;",
  9730. "#endif",
  9731. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9732. "#endif"
  9733. ].join("\n"),
  9734. shadowmap_pars_vertex: [
  9735. "#ifdef USE_SHADOWMAP",
  9736. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9737. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9738. "#endif"
  9739. ].join("\n"),
  9740. shadowmap_vertex: [
  9741. "#ifdef USE_SHADOWMAP",
  9742. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9743. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9744. "}",
  9745. "#endif"
  9746. ].join("\n"),
  9747. // ALPHATEST
  9748. alphatest_fragment: [
  9749. "#ifdef ALPHATEST",
  9750. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9751. "#endif"
  9752. ].join("\n"),
  9753. // LINEAR SPACE
  9754. linear_to_gamma_fragment: [
  9755. "#ifdef GAMMA_OUTPUT",
  9756. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9757. "#endif"
  9758. ].join("\n")
  9759. };
  9760. THREE.UniformsUtils = {
  9761. merge: function ( uniforms ) {
  9762. var u, p, tmp, merged = {};
  9763. for ( u = 0; u < uniforms.length; u ++ ) {
  9764. tmp = this.clone( uniforms[ u ] );
  9765. for ( p in tmp ) {
  9766. merged[ p ] = tmp[ p ];
  9767. }
  9768. }
  9769. return merged;
  9770. },
  9771. clone: function ( uniforms_src ) {
  9772. var u, p, parameter, parameter_src, uniforms_dst = {};
  9773. for ( u in uniforms_src ) {
  9774. uniforms_dst[ u ] = {};
  9775. for ( p in uniforms_src[ u ] ) {
  9776. parameter_src = uniforms_src[ u ][ p ];
  9777. if ( parameter_src instanceof THREE.Color ||
  9778. parameter_src instanceof THREE.Vector2 ||
  9779. parameter_src instanceof THREE.Vector3 ||
  9780. parameter_src instanceof THREE.Vector4 ||
  9781. parameter_src instanceof THREE.Matrix4 ||
  9782. parameter_src instanceof THREE.Texture ) {
  9783. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9784. } else if ( parameter_src instanceof Array ) {
  9785. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9786. } else {
  9787. uniforms_dst[ u ][ p ] = parameter_src;
  9788. }
  9789. }
  9790. }
  9791. return uniforms_dst;
  9792. }
  9793. };
  9794. THREE.UniformsLib = {
  9795. common: {
  9796. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9797. "opacity" : { type: "f", value: 1.0 },
  9798. "map" : { type: "t", value: null },
  9799. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9800. "lightMap" : { type: "t", value: null },
  9801. "specularMap" : { type: "t", value: null },
  9802. "envMap" : { type: "t", value: null },
  9803. "flipEnvMap" : { type: "f", value: -1 },
  9804. "useRefract" : { type: "i", value: 0 },
  9805. "reflectivity" : { type: "f", value: 1.0 },
  9806. "refractionRatio" : { type: "f", value: 0.98 },
  9807. "combine" : { type: "i", value: 0 },
  9808. "morphTargetInfluences" : { type: "f", value: 0 }
  9809. },
  9810. bump: {
  9811. "bumpMap" : { type: "t", value: null },
  9812. "bumpScale" : { type: "f", value: 1 }
  9813. },
  9814. normalmap: {
  9815. "normalMap" : { type: "t", value: null },
  9816. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9817. },
  9818. fog : {
  9819. "fogDensity" : { type: "f", value: 0.00025 },
  9820. "fogNear" : { type: "f", value: 1 },
  9821. "fogFar" : { type: "f", value: 2000 },
  9822. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9823. },
  9824. lights: {
  9825. "ambientLightColor" : { type: "fv", value: [] },
  9826. "directionalLightDirection" : { type: "fv", value: [] },
  9827. "directionalLightColor" : { type: "fv", value: [] },
  9828. "hemisphereLightDirection" : { type: "fv", value: [] },
  9829. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9830. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9831. "pointLightColor" : { type: "fv", value: [] },
  9832. "pointLightPosition" : { type: "fv", value: [] },
  9833. "pointLightDistance" : { type: "fv1", value: [] },
  9834. "spotLightColor" : { type: "fv", value: [] },
  9835. "spotLightPosition" : { type: "fv", value: [] },
  9836. "spotLightDirection" : { type: "fv", value: [] },
  9837. "spotLightDistance" : { type: "fv1", value: [] },
  9838. "spotLightAngleCos" : { type: "fv1", value: [] },
  9839. "spotLightExponent" : { type: "fv1", value: [] }
  9840. },
  9841. particle: {
  9842. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9843. "opacity" : { type: "f", value: 1.0 },
  9844. "size" : { type: "f", value: 1.0 },
  9845. "scale" : { type: "f", value: 1.0 },
  9846. "map" : { type: "t", value: null },
  9847. "fogDensity" : { type: "f", value: 0.00025 },
  9848. "fogNear" : { type: "f", value: 1 },
  9849. "fogFar" : { type: "f", value: 2000 },
  9850. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9851. },
  9852. shadowmap: {
  9853. "shadowMap": { type: "tv", value: [] },
  9854. "shadowMapSize": { type: "v2v", value: [] },
  9855. "shadowBias" : { type: "fv1", value: [] },
  9856. "shadowDarkness": { type: "fv1", value: [] },
  9857. "shadowMatrix" : { type: "m4v", value: [] }
  9858. }
  9859. };
  9860. THREE.ShaderLib = {
  9861. 'basic': {
  9862. uniforms: THREE.UniformsUtils.merge( [
  9863. THREE.UniformsLib[ "common" ],
  9864. THREE.UniformsLib[ "fog" ],
  9865. THREE.UniformsLib[ "shadowmap" ]
  9866. ] ),
  9867. vertexShader: [
  9868. THREE.ShaderChunk[ "map_pars_vertex" ],
  9869. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9870. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9871. THREE.ShaderChunk[ "color_pars_vertex" ],
  9872. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9873. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9874. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9875. "void main() {",
  9876. THREE.ShaderChunk[ "map_vertex" ],
  9877. THREE.ShaderChunk[ "lightmap_vertex" ],
  9878. THREE.ShaderChunk[ "color_vertex" ],
  9879. THREE.ShaderChunk[ "skinbase_vertex" ],
  9880. "#ifdef USE_ENVMAP",
  9881. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9882. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9883. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9884. "#endif",
  9885. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9886. THREE.ShaderChunk[ "skinning_vertex" ],
  9887. THREE.ShaderChunk[ "default_vertex" ],
  9888. THREE.ShaderChunk[ "worldpos_vertex" ],
  9889. THREE.ShaderChunk[ "envmap_vertex" ],
  9890. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9891. "}"
  9892. ].join("\n"),
  9893. fragmentShader: [
  9894. "uniform vec3 diffuse;",
  9895. "uniform float opacity;",
  9896. THREE.ShaderChunk[ "color_pars_fragment" ],
  9897. THREE.ShaderChunk[ "map_pars_fragment" ],
  9898. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9899. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9900. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9901. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9902. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9903. "void main() {",
  9904. "gl_FragColor = vec4( diffuse, opacity );",
  9905. THREE.ShaderChunk[ "map_fragment" ],
  9906. THREE.ShaderChunk[ "alphatest_fragment" ],
  9907. THREE.ShaderChunk[ "specularmap_fragment" ],
  9908. THREE.ShaderChunk[ "lightmap_fragment" ],
  9909. THREE.ShaderChunk[ "color_fragment" ],
  9910. THREE.ShaderChunk[ "envmap_fragment" ],
  9911. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9912. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9913. THREE.ShaderChunk[ "fog_fragment" ],
  9914. "}"
  9915. ].join("\n")
  9916. },
  9917. 'lambert': {
  9918. uniforms: THREE.UniformsUtils.merge( [
  9919. THREE.UniformsLib[ "common" ],
  9920. THREE.UniformsLib[ "fog" ],
  9921. THREE.UniformsLib[ "lights" ],
  9922. THREE.UniformsLib[ "shadowmap" ],
  9923. {
  9924. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9925. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9926. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9927. }
  9928. ] ),
  9929. vertexShader: [
  9930. "#define LAMBERT",
  9931. "varying vec3 vLightFront;",
  9932. "#ifdef DOUBLE_SIDED",
  9933. "varying vec3 vLightBack;",
  9934. "#endif",
  9935. THREE.ShaderChunk[ "map_pars_vertex" ],
  9936. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9937. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9938. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9939. THREE.ShaderChunk[ "color_pars_vertex" ],
  9940. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9941. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9942. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9943. "void main() {",
  9944. THREE.ShaderChunk[ "map_vertex" ],
  9945. THREE.ShaderChunk[ "lightmap_vertex" ],
  9946. THREE.ShaderChunk[ "color_vertex" ],
  9947. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9948. THREE.ShaderChunk[ "skinbase_vertex" ],
  9949. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9950. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9951. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9952. THREE.ShaderChunk[ "skinning_vertex" ],
  9953. THREE.ShaderChunk[ "default_vertex" ],
  9954. THREE.ShaderChunk[ "worldpos_vertex" ],
  9955. THREE.ShaderChunk[ "envmap_vertex" ],
  9956. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9957. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9958. "}"
  9959. ].join("\n"),
  9960. fragmentShader: [
  9961. "uniform float opacity;",
  9962. "varying vec3 vLightFront;",
  9963. "#ifdef DOUBLE_SIDED",
  9964. "varying vec3 vLightBack;",
  9965. "#endif",
  9966. THREE.ShaderChunk[ "color_pars_fragment" ],
  9967. THREE.ShaderChunk[ "map_pars_fragment" ],
  9968. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9969. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9970. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9971. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9972. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9973. "void main() {",
  9974. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9975. THREE.ShaderChunk[ "map_fragment" ],
  9976. THREE.ShaderChunk[ "alphatest_fragment" ],
  9977. THREE.ShaderChunk[ "specularmap_fragment" ],
  9978. "#ifdef DOUBLE_SIDED",
  9979. //"float isFront = float( gl_FrontFacing );",
  9980. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9981. "if ( gl_FrontFacing )",
  9982. "gl_FragColor.xyz *= vLightFront;",
  9983. "else",
  9984. "gl_FragColor.xyz *= vLightBack;",
  9985. "#else",
  9986. "gl_FragColor.xyz *= vLightFront;",
  9987. "#endif",
  9988. THREE.ShaderChunk[ "lightmap_fragment" ],
  9989. THREE.ShaderChunk[ "color_fragment" ],
  9990. THREE.ShaderChunk[ "envmap_fragment" ],
  9991. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9992. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9993. THREE.ShaderChunk[ "fog_fragment" ],
  9994. "}"
  9995. ].join("\n")
  9996. },
  9997. 'phong': {
  9998. uniforms: THREE.UniformsUtils.merge( [
  9999. THREE.UniformsLib[ "common" ],
  10000. THREE.UniformsLib[ "bump" ],
  10001. THREE.UniformsLib[ "normalmap" ],
  10002. THREE.UniformsLib[ "fog" ],
  10003. THREE.UniformsLib[ "lights" ],
  10004. THREE.UniformsLib[ "shadowmap" ],
  10005. {
  10006. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10007. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10008. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10009. "shininess": { type: "f", value: 30 },
  10010. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10011. }
  10012. ] ),
  10013. vertexShader: [
  10014. "#define PHONG",
  10015. "varying vec3 vViewPosition;",
  10016. "varying vec3 vNormal;",
  10017. THREE.ShaderChunk[ "map_pars_vertex" ],
  10018. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10019. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10020. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10021. THREE.ShaderChunk[ "color_pars_vertex" ],
  10022. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10023. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10024. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10025. "void main() {",
  10026. THREE.ShaderChunk[ "map_vertex" ],
  10027. THREE.ShaderChunk[ "lightmap_vertex" ],
  10028. THREE.ShaderChunk[ "color_vertex" ],
  10029. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10030. THREE.ShaderChunk[ "skinbase_vertex" ],
  10031. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10032. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10033. "vNormal = normalize( transformedNormal );",
  10034. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10035. THREE.ShaderChunk[ "skinning_vertex" ],
  10036. THREE.ShaderChunk[ "default_vertex" ],
  10037. "vViewPosition = -mvPosition.xyz;",
  10038. THREE.ShaderChunk[ "worldpos_vertex" ],
  10039. THREE.ShaderChunk[ "envmap_vertex" ],
  10040. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10041. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10042. "}"
  10043. ].join("\n"),
  10044. fragmentShader: [
  10045. "uniform vec3 diffuse;",
  10046. "uniform float opacity;",
  10047. "uniform vec3 ambient;",
  10048. "uniform vec3 emissive;",
  10049. "uniform vec3 specular;",
  10050. "uniform float shininess;",
  10051. THREE.ShaderChunk[ "color_pars_fragment" ],
  10052. THREE.ShaderChunk[ "map_pars_fragment" ],
  10053. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10054. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10055. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10056. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10057. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10058. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10059. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10060. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10061. "void main() {",
  10062. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10063. THREE.ShaderChunk[ "map_fragment" ],
  10064. THREE.ShaderChunk[ "alphatest_fragment" ],
  10065. THREE.ShaderChunk[ "specularmap_fragment" ],
  10066. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10067. THREE.ShaderChunk[ "lightmap_fragment" ],
  10068. THREE.ShaderChunk[ "color_fragment" ],
  10069. THREE.ShaderChunk[ "envmap_fragment" ],
  10070. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10071. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10072. THREE.ShaderChunk[ "fog_fragment" ],
  10073. "}"
  10074. ].join("\n")
  10075. },
  10076. 'particle_basic': {
  10077. uniforms: THREE.UniformsUtils.merge( [
  10078. THREE.UniformsLib[ "particle" ],
  10079. THREE.UniformsLib[ "shadowmap" ]
  10080. ] ),
  10081. vertexShader: [
  10082. "uniform float size;",
  10083. "uniform float scale;",
  10084. THREE.ShaderChunk[ "color_pars_vertex" ],
  10085. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10086. "void main() {",
  10087. THREE.ShaderChunk[ "color_vertex" ],
  10088. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10089. "#ifdef USE_SIZEATTENUATION",
  10090. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10091. "#else",
  10092. "gl_PointSize = size;",
  10093. "#endif",
  10094. "gl_Position = projectionMatrix * mvPosition;",
  10095. THREE.ShaderChunk[ "worldpos_vertex" ],
  10096. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10097. "}"
  10098. ].join("\n"),
  10099. fragmentShader: [
  10100. "uniform vec3 psColor;",
  10101. "uniform float opacity;",
  10102. THREE.ShaderChunk[ "color_pars_fragment" ],
  10103. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10104. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10105. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10106. "void main() {",
  10107. "gl_FragColor = vec4( psColor, opacity );",
  10108. THREE.ShaderChunk[ "map_particle_fragment" ],
  10109. THREE.ShaderChunk[ "alphatest_fragment" ],
  10110. THREE.ShaderChunk[ "color_fragment" ],
  10111. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10112. THREE.ShaderChunk[ "fog_fragment" ],
  10113. "}"
  10114. ].join("\n")
  10115. },
  10116. 'dashed': {
  10117. uniforms: THREE.UniformsUtils.merge( [
  10118. THREE.UniformsLib[ "common" ],
  10119. THREE.UniformsLib[ "fog" ],
  10120. {
  10121. "scale": { type: "f", value: 1 },
  10122. "dashSize": { type: "f", value: 1 },
  10123. "totalSize": { type: "f", value: 2 }
  10124. }
  10125. ] ),
  10126. vertexShader: [
  10127. "uniform float scale;",
  10128. "attribute float lineDistance;",
  10129. "varying float vLineDistance;",
  10130. THREE.ShaderChunk[ "color_pars_vertex" ],
  10131. "void main() {",
  10132. THREE.ShaderChunk[ "color_vertex" ],
  10133. "vLineDistance = scale * lineDistance;",
  10134. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10135. "gl_Position = projectionMatrix * mvPosition;",
  10136. "}"
  10137. ].join("\n"),
  10138. fragmentShader: [
  10139. "uniform vec3 diffuse;",
  10140. "uniform float opacity;",
  10141. "uniform float dashSize;",
  10142. "uniform float totalSize;",
  10143. "varying float vLineDistance;",
  10144. THREE.ShaderChunk[ "color_pars_fragment" ],
  10145. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10146. "void main() {",
  10147. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10148. "discard;",
  10149. "}",
  10150. "gl_FragColor = vec4( diffuse, opacity );",
  10151. THREE.ShaderChunk[ "color_fragment" ],
  10152. THREE.ShaderChunk[ "fog_fragment" ],
  10153. "}"
  10154. ].join("\n")
  10155. },
  10156. 'depth': {
  10157. uniforms: {
  10158. "mNear": { type: "f", value: 1.0 },
  10159. "mFar" : { type: "f", value: 2000.0 },
  10160. "opacity" : { type: "f", value: 1.0 }
  10161. },
  10162. vertexShader: [
  10163. "void main() {",
  10164. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10165. "}"
  10166. ].join("\n"),
  10167. fragmentShader: [
  10168. "uniform float mNear;",
  10169. "uniform float mFar;",
  10170. "uniform float opacity;",
  10171. "void main() {",
  10172. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10173. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10174. "gl_FragColor = vec4( vec3( color ), opacity );",
  10175. "}"
  10176. ].join("\n")
  10177. },
  10178. 'normal': {
  10179. uniforms: {
  10180. "opacity" : { type: "f", value: 1.0 }
  10181. },
  10182. vertexShader: [
  10183. "varying vec3 vNormal;",
  10184. "void main() {",
  10185. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10186. "vNormal = normalize( normalMatrix * normal );",
  10187. "gl_Position = projectionMatrix * mvPosition;",
  10188. "}"
  10189. ].join("\n"),
  10190. fragmentShader: [
  10191. "uniform float opacity;",
  10192. "varying vec3 vNormal;",
  10193. "void main() {",
  10194. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10195. "}"
  10196. ].join("\n")
  10197. },
  10198. /* -------------------------------------------------------------------------
  10199. // Normal map shader
  10200. // - Blinn-Phong
  10201. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10202. // - point and directional lights (use with "lights: true" material option)
  10203. ------------------------------------------------------------------------- */
  10204. 'normalmap' : {
  10205. uniforms: THREE.UniformsUtils.merge( [
  10206. THREE.UniformsLib[ "fog" ],
  10207. THREE.UniformsLib[ "lights" ],
  10208. THREE.UniformsLib[ "shadowmap" ],
  10209. {
  10210. "enableAO" : { type: "i", value: 0 },
  10211. "enableDiffuse" : { type: "i", value: 0 },
  10212. "enableSpecular" : { type: "i", value: 0 },
  10213. "enableReflection": { type: "i", value: 0 },
  10214. "enableDisplacement": { type: "i", value: 0 },
  10215. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10216. "tDiffuse" : { type: "t", value: null },
  10217. "tCube" : { type: "t", value: null },
  10218. "tNormal" : { type: "t", value: null },
  10219. "tSpecular" : { type: "t", value: null },
  10220. "tAO" : { type: "t", value: null },
  10221. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10222. "uDisplacementBias": { type: "f", value: 0.0 },
  10223. "uDisplacementScale": { type: "f", value: 1.0 },
  10224. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10225. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10226. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10227. "uShininess": { type: "f", value: 30 },
  10228. "uOpacity": { type: "f", value: 1 },
  10229. "useRefract": { type: "i", value: 0 },
  10230. "uRefractionRatio": { type: "f", value: 0.98 },
  10231. "uReflectivity": { type: "f", value: 0.5 },
  10232. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10233. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10234. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10235. }
  10236. ] ),
  10237. fragmentShader: [
  10238. "uniform vec3 uAmbientColor;",
  10239. "uniform vec3 uDiffuseColor;",
  10240. "uniform vec3 uSpecularColor;",
  10241. "uniform float uShininess;",
  10242. "uniform float uOpacity;",
  10243. "uniform bool enableDiffuse;",
  10244. "uniform bool enableSpecular;",
  10245. "uniform bool enableAO;",
  10246. "uniform bool enableReflection;",
  10247. "uniform sampler2D tDiffuse;",
  10248. "uniform sampler2D tNormal;",
  10249. "uniform sampler2D tSpecular;",
  10250. "uniform sampler2D tAO;",
  10251. "uniform samplerCube tCube;",
  10252. "uniform vec2 uNormalScale;",
  10253. "uniform bool useRefract;",
  10254. "uniform float uRefractionRatio;",
  10255. "uniform float uReflectivity;",
  10256. "varying vec3 vTangent;",
  10257. "varying vec3 vBinormal;",
  10258. "varying vec3 vNormal;",
  10259. "varying vec2 vUv;",
  10260. "uniform vec3 ambientLightColor;",
  10261. "#if MAX_DIR_LIGHTS > 0",
  10262. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10263. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10264. "#endif",
  10265. "#if MAX_HEMI_LIGHTS > 0",
  10266. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10267. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10268. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10269. "#endif",
  10270. "#if MAX_POINT_LIGHTS > 0",
  10271. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10272. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10273. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10274. "#endif",
  10275. "#if MAX_SPOT_LIGHTS > 0",
  10276. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10277. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10278. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10279. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10280. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10281. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10282. "#endif",
  10283. "#ifdef WRAP_AROUND",
  10284. "uniform vec3 wrapRGB;",
  10285. "#endif",
  10286. "varying vec3 vWorldPosition;",
  10287. "varying vec3 vViewPosition;",
  10288. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10289. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10290. "void main() {",
  10291. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10292. "vec3 specularTex = vec3( 1.0 );",
  10293. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10294. "normalTex.xy *= uNormalScale;",
  10295. "normalTex = normalize( normalTex );",
  10296. "if( enableDiffuse ) {",
  10297. "#ifdef GAMMA_INPUT",
  10298. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10299. "texelColor.xyz *= texelColor.xyz;",
  10300. "gl_FragColor = gl_FragColor * texelColor;",
  10301. "#else",
  10302. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10303. "#endif",
  10304. "}",
  10305. "if( enableAO ) {",
  10306. "#ifdef GAMMA_INPUT",
  10307. "vec4 aoColor = texture2D( tAO, vUv );",
  10308. "aoColor.xyz *= aoColor.xyz;",
  10309. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10310. "#else",
  10311. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10312. "#endif",
  10313. "}",
  10314. "if( enableSpecular )",
  10315. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10316. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10317. "vec3 finalNormal = tsb * normalTex;",
  10318. "#ifdef FLIP_SIDED",
  10319. "finalNormal = -finalNormal;",
  10320. "#endif",
  10321. "vec3 normal = normalize( finalNormal );",
  10322. "vec3 viewPosition = normalize( vViewPosition );",
  10323. // point lights
  10324. "#if MAX_POINT_LIGHTS > 0",
  10325. "vec3 pointDiffuse = vec3( 0.0 );",
  10326. "vec3 pointSpecular = vec3( 0.0 );",
  10327. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10328. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10329. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10330. "float pointDistance = 1.0;",
  10331. "if ( pointLightDistance[ i ] > 0.0 )",
  10332. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10333. "pointVector = normalize( pointVector );",
  10334. // diffuse
  10335. "#ifdef WRAP_AROUND",
  10336. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10337. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10338. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10339. "#else",
  10340. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10341. "#endif",
  10342. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10343. // specular
  10344. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10345. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10346. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10347. "#ifdef PHYSICALLY_BASED_SHADING",
  10348. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10349. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10350. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10351. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10352. "#else",
  10353. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10354. "#endif",
  10355. "}",
  10356. "#endif",
  10357. // spot lights
  10358. "#if MAX_SPOT_LIGHTS > 0",
  10359. "vec3 spotDiffuse = vec3( 0.0 );",
  10360. "vec3 spotSpecular = vec3( 0.0 );",
  10361. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10362. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10363. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10364. "float spotDistance = 1.0;",
  10365. "if ( spotLightDistance[ i ] > 0.0 )",
  10366. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10367. "spotVector = normalize( spotVector );",
  10368. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10369. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10370. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10371. // diffuse
  10372. "#ifdef WRAP_AROUND",
  10373. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10374. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10375. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10376. "#else",
  10377. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10378. "#endif",
  10379. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10380. // specular
  10381. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10382. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10383. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10384. "#ifdef PHYSICALLY_BASED_SHADING",
  10385. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10386. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10387. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10388. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10389. "#else",
  10390. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10391. "#endif",
  10392. "}",
  10393. "}",
  10394. "#endif",
  10395. // directional lights
  10396. "#if MAX_DIR_LIGHTS > 0",
  10397. "vec3 dirDiffuse = vec3( 0.0 );",
  10398. "vec3 dirSpecular = vec3( 0.0 );",
  10399. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10400. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10401. "vec3 dirVector = normalize( lDirection.xyz );",
  10402. // diffuse
  10403. "#ifdef WRAP_AROUND",
  10404. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10405. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10406. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10407. "#else",
  10408. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10409. "#endif",
  10410. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10411. // specular
  10412. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10413. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10414. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10415. "#ifdef PHYSICALLY_BASED_SHADING",
  10416. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10417. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10418. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10419. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10420. "#else",
  10421. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10422. "#endif",
  10423. "}",
  10424. "#endif",
  10425. // hemisphere lights
  10426. "#if MAX_HEMI_LIGHTS > 0",
  10427. "vec3 hemiDiffuse = vec3( 0.0 );",
  10428. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10429. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10430. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10431. "vec3 lVector = normalize( lDirection.xyz );",
  10432. // diffuse
  10433. "float dotProduct = dot( normal, lVector );",
  10434. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10435. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10436. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10437. // specular (sky light)
  10438. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10439. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10440. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10441. // specular (ground light)
  10442. "vec3 lVectorGround = -lVector;",
  10443. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10444. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10445. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10446. "#ifdef PHYSICALLY_BASED_SHADING",
  10447. "float dotProductGround = dot( normal, lVectorGround );",
  10448. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10449. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10450. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10451. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10452. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10453. "#else",
  10454. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10455. "#endif",
  10456. "}",
  10457. "#endif",
  10458. // all lights contribution summation
  10459. "vec3 totalDiffuse = vec3( 0.0 );",
  10460. "vec3 totalSpecular = vec3( 0.0 );",
  10461. "#if MAX_DIR_LIGHTS > 0",
  10462. "totalDiffuse += dirDiffuse;",
  10463. "totalSpecular += dirSpecular;",
  10464. "#endif",
  10465. "#if MAX_HEMI_LIGHTS > 0",
  10466. "totalDiffuse += hemiDiffuse;",
  10467. "totalSpecular += hemiSpecular;",
  10468. "#endif",
  10469. "#if MAX_POINT_LIGHTS > 0",
  10470. "totalDiffuse += pointDiffuse;",
  10471. "totalSpecular += pointSpecular;",
  10472. "#endif",
  10473. "#if MAX_SPOT_LIGHTS > 0",
  10474. "totalDiffuse += spotDiffuse;",
  10475. "totalSpecular += spotSpecular;",
  10476. "#endif",
  10477. "#ifdef METAL",
  10478. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10479. "#else",
  10480. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10481. "#endif",
  10482. "if ( enableReflection ) {",
  10483. "vec3 vReflect;",
  10484. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10485. "if ( useRefract ) {",
  10486. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10487. "} else {",
  10488. "vReflect = reflect( cameraToVertex, normal );",
  10489. "}",
  10490. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10491. "#ifdef GAMMA_INPUT",
  10492. "cubeColor.xyz *= cubeColor.xyz;",
  10493. "#endif",
  10494. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10495. "}",
  10496. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10497. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10498. THREE.ShaderChunk[ "fog_fragment" ],
  10499. "}"
  10500. ].join("\n"),
  10501. vertexShader: [
  10502. "attribute vec4 tangent;",
  10503. "uniform vec2 uOffset;",
  10504. "uniform vec2 uRepeat;",
  10505. "uniform bool enableDisplacement;",
  10506. "#ifdef VERTEX_TEXTURES",
  10507. "uniform sampler2D tDisplacement;",
  10508. "uniform float uDisplacementScale;",
  10509. "uniform float uDisplacementBias;",
  10510. "#endif",
  10511. "varying vec3 vTangent;",
  10512. "varying vec3 vBinormal;",
  10513. "varying vec3 vNormal;",
  10514. "varying vec2 vUv;",
  10515. "varying vec3 vWorldPosition;",
  10516. "varying vec3 vViewPosition;",
  10517. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10518. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10519. "void main() {",
  10520. THREE.ShaderChunk[ "skinbase_vertex" ],
  10521. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10522. // normal, tangent and binormal vectors
  10523. "#ifdef USE_SKINNING",
  10524. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10525. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10526. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10527. "#else",
  10528. "vNormal = normalize( normalMatrix * normal );",
  10529. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10530. "#endif",
  10531. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10532. "vUv = uv * uRepeat + uOffset;",
  10533. // displacement mapping
  10534. "vec3 displacedPosition;",
  10535. "#ifdef VERTEX_TEXTURES",
  10536. "if ( enableDisplacement ) {",
  10537. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10538. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10539. "displacedPosition = position + normalize( normal ) * df;",
  10540. "} else {",
  10541. "#ifdef USE_SKINNING",
  10542. "vec4 skinVertex = vec4( position, 1.0 );",
  10543. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10544. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10545. "displacedPosition = skinned.xyz;",
  10546. "#else",
  10547. "displacedPosition = position;",
  10548. "#endif",
  10549. "}",
  10550. "#else",
  10551. "#ifdef USE_SKINNING",
  10552. "vec4 skinVertex = vec4( position, 1.0 );",
  10553. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10554. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10555. "displacedPosition = skinned.xyz;",
  10556. "#else",
  10557. "displacedPosition = position;",
  10558. "#endif",
  10559. "#endif",
  10560. //
  10561. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10562. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10563. "gl_Position = projectionMatrix * mvPosition;",
  10564. //
  10565. "vWorldPosition = worldPosition.xyz;",
  10566. "vViewPosition = -mvPosition.xyz;",
  10567. // shadows
  10568. "#ifdef USE_SHADOWMAP",
  10569. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10570. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10571. "}",
  10572. "#endif",
  10573. "}"
  10574. ].join("\n")
  10575. },
  10576. /* -------------------------------------------------------------------------
  10577. // Cube map shader
  10578. ------------------------------------------------------------------------- */
  10579. 'cube': {
  10580. uniforms: { "tCube": { type: "t", value: null },
  10581. "tFlip": { type: "f", value: -1 } },
  10582. vertexShader: [
  10583. "varying vec3 vWorldPosition;",
  10584. "void main() {",
  10585. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10586. "vWorldPosition = worldPosition.xyz;",
  10587. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10588. "}"
  10589. ].join("\n"),
  10590. fragmentShader: [
  10591. "uniform samplerCube tCube;",
  10592. "uniform float tFlip;",
  10593. "varying vec3 vWorldPosition;",
  10594. "void main() {",
  10595. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10596. "}"
  10597. ].join("\n")
  10598. },
  10599. // Depth encoding into RGBA texture
  10600. // based on SpiderGL shadow map example
  10601. // http://spidergl.org/example.php?id=6
  10602. // originally from
  10603. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10604. // see also here:
  10605. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10606. 'depthRGBA': {
  10607. uniforms: {},
  10608. vertexShader: [
  10609. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10610. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10611. "void main() {",
  10612. THREE.ShaderChunk[ "skinbase_vertex" ],
  10613. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10614. THREE.ShaderChunk[ "skinning_vertex" ],
  10615. THREE.ShaderChunk[ "default_vertex" ],
  10616. "}"
  10617. ].join("\n"),
  10618. fragmentShader: [
  10619. "vec4 pack_depth( const in float depth ) {",
  10620. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10621. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10622. "vec4 res = fract( depth * bit_shift );",
  10623. "res -= res.xxyz * bit_mask;",
  10624. "return res;",
  10625. "}",
  10626. "void main() {",
  10627. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10628. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10629. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10630. //"gl_FragData[ 0 ] = pack_depth( z );",
  10631. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10632. "}"
  10633. ].join("\n")
  10634. }
  10635. };
  10636. /**
  10637. * @author supereggbert / http://www.paulbrunt.co.uk/
  10638. * @author mrdoob / http://mrdoob.com/
  10639. * @author alteredq / http://alteredqualia.com/
  10640. * @author szimek / https://github.com/szimek/
  10641. * @author gero3 / https://github.com/gero3/
  10642. */
  10643. THREE.WebGLRenderer = function ( parameters ) {
  10644. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10645. parameters = parameters || {};
  10646. var info = {
  10647. memory: {
  10648. programs: 0,
  10649. geometries: 0,
  10650. textures: 0
  10651. },
  10652. render: {
  10653. calls: 0,
  10654. vertices: 0,
  10655. faces: 0,
  10656. points: 0
  10657. }
  10658. };
  10659. var renderer = new THREE.WebGLRenderer.LowLevelRenderer(parameters);
  10660. var meshRenderer = new THREE.WebGLRenderer.MeshRenderer(renderer, info);
  10661. var particleRenderer = new THREE.WebGLRenderer.ParticleRenderer(renderer, info);
  10662. var lineRenderer = new THREE.WebGLRenderer.LineRenderer(renderer, info);
  10663. var ribbonRenderer = new THREE.WebGLRenderer.RibbonRenderer(renderer, info);
  10664. var shaderBuilder = new THREE.WebGLRenderer.ShaderBuilder(renderer, info);
  10665. // clearing
  10666. this.autoClear = true;
  10667. this.autoClearColor = true;
  10668. this.autoClearDepth = true;
  10669. this.autoClearStencil = true;
  10670. // scene graph
  10671. this.sortObjects = true;
  10672. this.autoUpdateObjects = true;
  10673. this.autoUpdateScene = true;
  10674. // physically based shading
  10675. this.gammaInput = false;
  10676. this.gammaOutput = false;
  10677. this.physicallyBasedShading = false;
  10678. // shadow map
  10679. this.shadowMapEnabled = false;
  10680. this.shadowMapAutoUpdate = true;
  10681. this.shadowMapType = THREE.PCFShadowMap;
  10682. this.shadowMapCullFace = THREE.CullFaceFront;
  10683. this.shadowMapDebug = false;
  10684. this.shadowMapCascade = false;
  10685. // morphs
  10686. this.maxMorphTargets = 8;
  10687. this.maxMorphNormals = 4;
  10688. // flags
  10689. this.autoScaleCubemaps = true;
  10690. // custom render plugins
  10691. this.renderPluginsPre = [];
  10692. this.renderPluginsPost = [];
  10693. // info
  10694. this.info = info;
  10695. // internal properties
  10696. var _this = this,
  10697. // internal state cache
  10698. _currentProgram = null,
  10699. _currentFramebuffer = null,
  10700. _currentMaterialId = -1,
  10701. _currentGeometryGroupHash = null,
  10702. _currentCamera = null,
  10703. _geometryGroupCounter = 0,
  10704. _usedTextureUnits = 0,
  10705. // GL state
  10706. _viewportX = 0,
  10707. _viewportY = 0,
  10708. _viewportWidth = 0,
  10709. _viewportHeight = 0,
  10710. _currentWidth = 0,
  10711. _currentHeight = 0,
  10712. _enabledAttributes = {},
  10713. // frustum
  10714. _frustum = new THREE.Frustum(),
  10715. // camera matrices cache
  10716. _projScreenMatrix = new THREE.Matrix4(),
  10717. _projScreenMatrixPS = new THREE.Matrix4(),
  10718. _vector3 = new THREE.Vector3(),
  10719. // light arrays cache
  10720. _direction = new THREE.Vector3(),
  10721. _lightsNeedUpdate = true,
  10722. _lights = {
  10723. ambient: [ 0, 0, 0 ],
  10724. directional: { length: 0, colors: [], positions: [] },
  10725. point: { length: 0, colors: [], positions: [], distances: [] },
  10726. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [] },
  10727. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10728. };
  10729. // initialize
  10730. this.context = renderer.getContext();
  10731. this.domElement = renderer.getDomElement();
  10732. this.getPrecision = renderer.getPrecision;
  10733. // low level API
  10734. this.getPrecision = renderer.getPrecision;
  10735. this.getContext = renderer.getContext;
  10736. this.supportsVertexTextures = renderer.supportsVertexTextures;
  10737. this.supportsFloatTextures = renderer.supportsFloatTextures;
  10738. this.supportsStandardDerivatives = renderer.supportsStandardDerivatives;
  10739. this.supportsCompressedTextureS3TC = renderer.supportsCompressedTextureS3TC;
  10740. this.getMaxAnisotropy = renderer.getMaxAnisotropy;
  10741. this.setSize = renderer.setSize;
  10742. this.setViewport = renderer.setViewport;
  10743. this.setScissor = renderer.setScissor;
  10744. this.enableScissorTest = renderer.enableScissorTest;
  10745. this.setDepthWrite = renderer.setDepthWrite;
  10746. this.setDepthTest = renderer.setDepthTest;
  10747. this.setRenderTarget = renderer.setRenderTarget;
  10748. this.setBlending = renderer.setBlending;
  10749. this.setTexture = renderer.setTexture;
  10750. this.setMaterialFaces = renderer.setMaterialFaces;
  10751. this.setFaceCulling = renderer.setFaceCulling;
  10752. // Clearing
  10753. this.setClearColorHex = renderer.setClearColorHex;
  10754. this.setClearColor = renderer.setClearColor;
  10755. this.getClearColor = renderer.getClearColor;
  10756. this.getClearAlpha = renderer.getClearAlpha;
  10757. this.clear = renderer.clear;
  10758. this.clearTarget = renderer.clearTarget;
  10759. // Plugins
  10760. this.addPostPlugin = function ( plugin ) {
  10761. plugin.init( this );
  10762. this.renderPluginsPost.push( plugin );
  10763. };
  10764. this.addPrePlugin = function ( plugin ) {
  10765. plugin.init( this );
  10766. this.renderPluginsPre.push( plugin );
  10767. };
  10768. // Rendering
  10769. this.updateShadowMap = function ( scene, camera ) {
  10770. _currentProgram = null;
  10771. _currentGeometryGroupHash = -1;
  10772. _currentMaterialId = -1;
  10773. _lightsNeedUpdate = true;
  10774. renderer.resetState();
  10775. this.shadowMapPlugin.update( scene, camera );
  10776. };
  10777. // Events
  10778. var onGeometryDispose = function ( event ) {
  10779. var geometry = event.target;
  10780. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10781. deallocateGeometry( geometry );
  10782. _this.info.memory.geometries --;
  10783. };
  10784. var onTextureDispose = function ( event ) {
  10785. var texture = event.target;
  10786. texture.removeEventListener( 'dispose', onTextureDispose );
  10787. deallocateTexture( texture );
  10788. _this.info.memory.textures --;
  10789. };
  10790. var onRenderTargetDispose = function ( event ) {
  10791. var renderTarget = event.target;
  10792. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10793. deallocateRenderTarget( renderTarget );
  10794. _this.info.memory.textures --;
  10795. };
  10796. var onMaterialDispose = function ( event ) {
  10797. var material = event.target;
  10798. material.removeEventListener( 'dispose', onMaterialDispose );
  10799. deallocateMaterial( material );
  10800. };
  10801. // Buffer deallocation
  10802. var deallocateGeometry = function ( geometry ) {
  10803. var m,ml;
  10804. geometry.__webglInit = undefined;
  10805. if ( geometry.__webglVertexBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglVertexBuffer );
  10806. if ( geometry.__webglNormalBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglNormalBuffer );
  10807. if ( geometry.__webglTangentBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglTangentBuffer );
  10808. if ( geometry.__webglColorBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglColorBuffer );
  10809. if ( geometry.__webglUVBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglUVBuffer );
  10810. if ( geometry.__webglUV2Buffer !== undefined ) renderer.deleteBuffer( geometry.__webglUV2Buffer );
  10811. if ( geometry.__webglSkinIndicesBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10812. if ( geometry.__webglSkinWeightsBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10813. if ( geometry.__webglFaceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglFaceBuffer );
  10814. if ( geometry.__webglLineBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineBuffer );
  10815. if ( geometry.__webglLineDistanceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10816. // geometry groups
  10817. if ( geometry.geometryGroups !== undefined ) {
  10818. for ( var g in geometry.geometryGroups ) {
  10819. var geometryGroup = geometry.geometryGroups[ g ];
  10820. if ( geometryGroup.numMorphTargets !== undefined ) {
  10821. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10822. renderer.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10823. }
  10824. }
  10825. if ( geometryGroup.numMorphNormals !== undefined ) {
  10826. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10827. renderer.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10828. }
  10829. }
  10830. deleteCustomAttributesBuffers( geometryGroup );
  10831. }
  10832. }
  10833. deleteCustomAttributesBuffers( geometry );
  10834. };
  10835. var deallocateTexture = function ( texture ) {
  10836. if ( texture.image && texture.image.__webglTextureCube ) {
  10837. // cube texture
  10838. renderer.deleteTexture( texture.image.__webglTextureCube );
  10839. } else {
  10840. // 2D texture
  10841. if ( ! texture.__webglInit ) return;
  10842. texture.__webglInit = false;
  10843. renderer.deleteTexture( texture.__webglTexture );
  10844. }
  10845. };
  10846. var deallocateRenderTarget = function ( renderTarget ) {
  10847. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10848. renderer.deleteTexture( renderTarget.__webglTexture );
  10849. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10850. for ( var i = 0; i < 6; i ++ ) {
  10851. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10852. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10853. }
  10854. } else {
  10855. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10856. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10857. }
  10858. };
  10859. var deallocateMaterial = function ( material ) {
  10860. var program = material.program;
  10861. if ( program === undefined ) return;
  10862. material.program = undefined;
  10863. // only deallocate GL program if this was the last use of shared program
  10864. // assumed there is only single copy of any program in the _programs list
  10865. // (that's how it's constructed)
  10866. shaderBuilder.removeProgram(program)
  10867. };
  10868. function deleteCustomAttributesBuffers( geometry ) {
  10869. if ( geometry.__webglCustomAttributesList ) {
  10870. for ( var id in geometry.__webglCustomAttributesList ) {
  10871. renderer.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10872. }
  10873. }
  10874. };
  10875. // Buffer initialization
  10876. function initCustomAttributes ( geometry, object ) {
  10877. var nvertices = geometry.vertices.length;
  10878. var material = object.material;
  10879. if ( material.attributes ) {
  10880. if ( geometry.__webglCustomAttributesList === undefined ) {
  10881. geometry.__webglCustomAttributesList = [];
  10882. }
  10883. for ( var a in material.attributes ) {
  10884. var attribute = material.attributes[ a ];
  10885. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10886. attribute.__webglInitialized = true;
  10887. var size = 1; // "f" and "i"
  10888. if ( attribute.type === "v2" ) size = 2;
  10889. else if ( attribute.type === "v3" ) size = 3;
  10890. else if ( attribute.type === "v4" ) size = 4;
  10891. else if ( attribute.type === "c" ) size = 3;
  10892. attribute.size = size;
  10893. attribute.array = new Float32Array( nvertices * size );
  10894. attribute.buffer = renderer.createBuffer();
  10895. attribute.buffer.belongsToAttribute = a;
  10896. attribute.needsUpdate = true;
  10897. }
  10898. geometry.__webglCustomAttributesList.push( attribute );
  10899. }
  10900. }
  10901. };
  10902. function getBufferMaterial( object, geometryGroup ) {
  10903. return object.material instanceof THREE.MeshFaceMaterial
  10904. ? object.material.materials[ geometryGroup.materialIndex ]
  10905. : object.material;
  10906. };
  10907. //
  10908. function initDirectBuffers( geometry ) {
  10909. var a, attribute;
  10910. for ( a in geometry.attributes ) {
  10911. attribute = geometry.attributes[ a ];
  10912. attribute.buffer = renderer.createBuffer();
  10913. if ( a === "index" ) {
  10914. renderer.setStaticIndexBuffer(attribute.buffer,attribute.array);
  10915. } else {
  10916. renderer.setStaticArrayBuffer(attribute.buffer,attribute.array);
  10917. }
  10918. }
  10919. };
  10920. // Buffer setting
  10921. function setDirectBuffers ( geometry, dispose ) {
  10922. var attributes = geometry.attributes;
  10923. var attributeName, attributeItem;
  10924. for ( attributeName in attributes ) {
  10925. attributeItem = attributes[ attributeName ];
  10926. if ( attributeItem.needsUpdate ) {
  10927. if ( attributeName === 'index' ) {
  10928. renderer.setDynamicIndexBuffer( attributeItem.buffer, attributeItem.array );
  10929. } else {
  10930. renderer.setDynamicArrayBuffer( attributeItem.buffer, attributeItem.array );
  10931. }
  10932. attributeItem.needsUpdate = false;
  10933. }
  10934. if ( dispose && ! attributeItem.dynamic ) {
  10935. delete attributeItem.array;
  10936. }
  10937. }
  10938. };
  10939. // Buffer rendering
  10940. this.renderBufferImmediate = function ( object, program, material ) {
  10941. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = renderer.createBuffer();
  10942. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = renderer.createBuffer();
  10943. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = renderer.createBuffer();
  10944. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = renderer.createBuffer();
  10945. if ( object.hasPositions ) {
  10946. renderer.setDynamicArrayBuffer( object.__webglVertexBuffer, object.positionArray);
  10947. renderer.setFloatAttribute(program.attributes.position, object.__webglVertexBuffer, 3, 0);
  10948. }
  10949. if ( object.hasNormals ) {
  10950. if ( material.shading === THREE.FlatShading ) {
  10951. var nx, ny, nz,
  10952. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10953. normalArray,
  10954. i, il = object.count * 3;
  10955. for( i = 0; i < il; i += 9 ) {
  10956. normalArray = object.normalArray;
  10957. nax = normalArray[ i ];
  10958. nay = normalArray[ i + 1 ];
  10959. naz = normalArray[ i + 2 ];
  10960. nbx = normalArray[ i + 3 ];
  10961. nby = normalArray[ i + 4 ];
  10962. nbz = normalArray[ i + 5 ];
  10963. ncx = normalArray[ i + 6 ];
  10964. ncy = normalArray[ i + 7 ];
  10965. ncz = normalArray[ i + 8 ];
  10966. nx = ( nax + nbx + ncx ) / 3;
  10967. ny = ( nay + nby + ncy ) / 3;
  10968. nz = ( naz + nbz + ncz ) / 3;
  10969. normalArray[ i ] = nx;
  10970. normalArray[ i + 1 ] = ny;
  10971. normalArray[ i + 2 ] = nz;
  10972. normalArray[ i + 3 ] = nx;
  10973. normalArray[ i + 4 ] = ny;
  10974. normalArray[ i + 5 ] = nz;
  10975. normalArray[ i + 6 ] = nx;
  10976. normalArray[ i + 7 ] = ny;
  10977. normalArray[ i + 8 ] = nz;
  10978. }
  10979. }
  10980. renderer.setDynamicArrayBuffer( object.__webglNormalBuffer, object.normalArray);
  10981. renderer.setFloatAttribute(program.attributes.normal, object.__webglNormalBuffer, 3, 0);
  10982. }
  10983. if ( object.hasUvs && material.map ) {
  10984. renderer.setDynamicArrayBuffer( object.__webglUvBuffer, object.uvArray);
  10985. renderer.setFloatAttribute(program.attributes.uv, object.__webglUvBuffer, 2, 0);
  10986. }
  10987. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10988. renderer.setDynamicArrayBuffer( object.__webglColorBuffer, object.colorArray);
  10989. renderer.setFloatAttribute(program.attributes.color, object.__webglColorBuffer, 3, 0);
  10990. }
  10991. renderer.drawTriangles(object.count );
  10992. object.count = 0;
  10993. };
  10994. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10995. if ( material.visible === false ) return;
  10996. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  10997. var attributeItem, attributeName, attributePointer, attributeSize;
  10998. program = setProgram( camera, lights, fog, material, object );
  10999. programAttributes = program.attributes;
  11000. geometryAttributes = geometry.attributes;
  11001. var updateBuffers = false,
  11002. wireframeBit = material.wireframe ? 1 : 0,
  11003. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11004. if ( geometryHash !== _currentGeometryGroupHash ) {
  11005. _currentGeometryGroupHash = geometryHash;
  11006. updateBuffers = true;
  11007. }
  11008. if ( updateBuffers ) {
  11009. renderer.disableAttributes();
  11010. }
  11011. // render mesh
  11012. if ( object instanceof THREE.Mesh ) {
  11013. var index = geometryAttributes[ "index" ];
  11014. // indexed triangles
  11015. if ( index ) {
  11016. var offsets = geometry.offsets;
  11017. // if there is more than 1 chunk
  11018. // must set attribute pointers to use new offsets for each chunk
  11019. // even if geometry and materials didn't change
  11020. if ( offsets.length > 1 ) updateBuffers = true;
  11021. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11022. var startIndex = offsets[ i ].index;
  11023. if ( updateBuffers ) {
  11024. for ( attributeName in geometryAttributes ) {
  11025. if ( attributeName === 'index' ) continue;
  11026. attributePointer = programAttributes[ attributeName ];
  11027. attributeItem = geometryAttributes[ attributeName ];
  11028. attributeSize = attributeItem.itemSize;
  11029. if ( attributePointer >= 0 ) {
  11030. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, startIndex * attributeSize * 4 );
  11031. }
  11032. }
  11033. }
  11034. // render indexed triangles
  11035. renderer.drawTriangleElements(index.buffer, offsets[ i ].count, offsets[ i ].start * 2);
  11036. _this.info.render.calls ++;
  11037. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11038. _this.info.render.faces += offsets[ i ].count / 3;
  11039. }
  11040. // non-indexed triangles
  11041. } else {
  11042. if ( updateBuffers ) {
  11043. for ( attributeName in geometryAttributes ) {
  11044. attributePointer = programAttributes[ attributeName ];
  11045. attributeItem = geometryAttributes[ attributeName ];
  11046. attributeSize = attributeItem.itemSize;
  11047. if ( attributePointer >= 0 ) {
  11048. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11049. }
  11050. }
  11051. }
  11052. var position = geometry.attributes[ "position" ];
  11053. // render non-indexed triangles
  11054. renderer.drawTriangles( position.numItems / 3)
  11055. _this.info.render.calls ++;
  11056. _this.info.render.vertices += position.numItems / 3;
  11057. _this.info.render.faces += position.numItems / 3 / 3;
  11058. }
  11059. // render particles
  11060. } else if ( object instanceof THREE.ParticleSystem ) {
  11061. if ( updateBuffers ) {
  11062. for ( attributeName in geometryAttributes ) {
  11063. attributePointer = programAttributes[ attributeName ];
  11064. attributeItem = geometryAttributes[ attributeName ];
  11065. attributeSize = attributeItem.itemSize;
  11066. if ( attributePointer >= 0 ) {
  11067. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11068. }
  11069. }
  11070. var position = geometryAttributes[ "position" ];
  11071. // render particles
  11072. renderer.drawPoints(position.numItems / 3);
  11073. _this.info.render.calls ++;
  11074. _this.info.render.points += position.numItems / 3;
  11075. }
  11076. } else if ( object instanceof THREE.Line ) {
  11077. if ( updateBuffers ) {
  11078. for ( attributeName in geometryAttributes ) {
  11079. attributePointer = programAttributes[ attributeName ];
  11080. attributeItem = geometryAttributes[ attributeName ];
  11081. attributeSize = attributeItem.itemSize;
  11082. if ( attributePointer >= 0 ) {
  11083. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11084. }
  11085. }
  11086. var position = geometryAttributes[ "position" ];
  11087. // render lines
  11088. renderer.setLineWidth( material.linewidth );
  11089. renderer.drawLineStrip(position.numItems / 3);
  11090. _this.info.render.calls ++;
  11091. _this.info.render.points += position.numItems;
  11092. }
  11093. }
  11094. };
  11095. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11096. if ( material.visible === false ) return;
  11097. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11098. program = setProgram( camera, lights, fog, material, object );
  11099. attributes = program.attributes;
  11100. var updateBuffers = false,
  11101. wireframeBit = material.wireframe ? 1 : 0,
  11102. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11103. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11104. _currentGeometryGroupHash = geometryGroupHash;
  11105. updateBuffers = true;
  11106. }
  11107. if ( updateBuffers ) {
  11108. renderer.disableAttributes();
  11109. }
  11110. // vertices
  11111. if ( !material.morphTargets && attributes.position >= 0 ) {
  11112. if ( updateBuffers ) {
  11113. renderer.setFloatAttribute(attributes.position , geometryGroup.__webglVertexBuffer, 3, 0);
  11114. }
  11115. } else {
  11116. if ( object.morphTargetBase ) {
  11117. setupMorphTargets( material, geometryGroup, object );
  11118. }
  11119. }
  11120. if ( updateBuffers ) {
  11121. // custom attributes
  11122. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11123. if ( geometryGroup.__webglCustomAttributesList ) {
  11124. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11125. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11126. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11127. renderer.setFloatAttribute(attributes[ attribute.buffer.belongsToAttribute ] , attribute.buffer, attribute.size, 0);
  11128. }
  11129. }
  11130. }
  11131. // colors
  11132. if ( attributes.color >= 0 ) {
  11133. renderer.setFloatAttribute(attributes.color , geometryGroup.__webglColorBuffer,3, 0);
  11134. }
  11135. // normals
  11136. if ( attributes.normal >= 0 ) {
  11137. renderer.setFloatAttribute(attributes.normal, geometryGroup.__webglNormalBuffer, 3, 0);
  11138. }
  11139. // tangents
  11140. if ( attributes.tangent >= 0 ) {
  11141. renderer.setFloatAttribute(attributes.tangent, geometryGroup.__webglTangentBuffer, 4, 0);
  11142. }
  11143. // uvs
  11144. if ( attributes.uv >= 0 ) {
  11145. renderer.setFloatAttribute(attributes.uv, geometryGroup.__webglUVBuffer, 2, 0);
  11146. }
  11147. if ( attributes.uv2 >= 0 ) {
  11148. renderer.setFloatAttribute(attributes.uv2, geometryGroup.__webglUV2Buffer, 2, 0);
  11149. }
  11150. if ( material.skinning &&
  11151. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11152. renderer.setFloatAttribute(attributes.skinIndex, geometryGroup.__webglSkinIndicesBuffer, 4, 0);
  11153. renderer.setFloatAttribute(attributes.skinWeight, geometryGroup.__webglSkinWeightsBuffer, 4, 0);
  11154. }
  11155. // line distances
  11156. if ( attributes.lineDistance >= 0 ) {
  11157. renderer.setFloatAttribute(attributes.lineDistance, geometryGroup.__webglLineDistanceBuffer, 1, 0);
  11158. }
  11159. }
  11160. // render mesh
  11161. if ( object instanceof THREE.Mesh ) {
  11162. // wireframe
  11163. if ( material.wireframe ) {
  11164. renderer.setLineWidth( material.wireframeLinewidth );
  11165. renderer.drawLineElements(geometryGroup.__webglLineBuffer,geometryGroup.__webglLineCount,0);
  11166. // triangles
  11167. } else {
  11168. renderer.drawTriangleElements( geometryGroup.__webglFaceBuffer, geometryGroup.__webglFaceCount, 0);
  11169. }
  11170. _this.info.render.calls ++;
  11171. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11172. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11173. // render lines
  11174. } else if ( object instanceof THREE.Line ) {
  11175. renderer.setLineWidth( material.linewidth );
  11176. if (object.type === THREE.LineStrip) {
  11177. renderer.drawLineStrip(geometryGroup.__webglLineCount);
  11178. } else {
  11179. renderer.drawLines(geometryGroup.__webglLineCount);
  11180. }
  11181. _this.info.render.calls ++;
  11182. // render particles
  11183. } else if ( object instanceof THREE.ParticleSystem ) {
  11184. renderer.drawPoints(geometryGroup.__webglParticleCount);
  11185. _this.info.render.calls ++;
  11186. _this.info.render.points += geometryGroup.__webglParticleCount;
  11187. // render ribbon
  11188. } else if ( object instanceof THREE.Ribbon ) {
  11189. renderer.drawTriangleStrip(geometryGroup.__webglVertexCount);
  11190. _this.info.render.calls ++;
  11191. }
  11192. };
  11193. function setupMorphTargets ( material, geometryGroup, object ) {
  11194. // set base
  11195. var attributes = material.program.attributes;
  11196. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  11197. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ], 3, 0);
  11198. } else if ( attributes.position >= 0 ) {
  11199. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglVertexBuffer, 3, 0);
  11200. }
  11201. if ( object.morphTargetForcedOrder.length ) {
  11202. // set forced order
  11203. var m = 0;
  11204. var order = object.morphTargetForcedOrder;
  11205. var influences = object.morphTargetInfluences;
  11206. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11207. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11208. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ], 3, 0);
  11209. }
  11210. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11211. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ], 3, 0);
  11212. }
  11213. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11214. m ++;
  11215. }
  11216. } else {
  11217. // find the most influencing
  11218. var influence, activeInfluenceIndices = [];
  11219. var influences = object.morphTargetInfluences;
  11220. var i, il = influences.length;
  11221. for ( i = 0; i < il; i ++ ) {
  11222. influence = influences[ i ];
  11223. if ( influence > 0 ) {
  11224. activeInfluenceIndices.push( [ influence, i ] );
  11225. }
  11226. }
  11227. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11228. activeInfluenceIndices.sort( numericalSort );
  11229. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11230. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11231. activeInfluenceIndices.sort( numericalSort );
  11232. } else if ( activeInfluenceIndices.length === 0 ) {
  11233. activeInfluenceIndices.push( [ 0, 0 ] );
  11234. };
  11235. var influenceIndex, m = 0;
  11236. while ( m < material.numSupportedMorphTargets ) {
  11237. if ( activeInfluenceIndices[ m ] ) {
  11238. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  11239. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11240. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ], 3, 0);
  11241. }
  11242. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11243. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ], 3, 0);
  11244. }
  11245. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11246. } else {
  11247. /*
  11248. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11249. if ( material.morphNormals ) {
  11250. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11251. }
  11252. */
  11253. object.__webglMorphTargetInfluences[ m ] = 0;
  11254. }
  11255. m ++;
  11256. }
  11257. }
  11258. // load updated influences uniform
  11259. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11260. renderer.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11261. }
  11262. };
  11263. // Sorting
  11264. function painterSortStable ( a, b ) {
  11265. if ( a.z !== b.z ) {
  11266. return b.z - a.z;
  11267. } else {
  11268. return a.id - b.id;
  11269. }
  11270. };
  11271. function numericalSort ( a, b ) {
  11272. return b[ 0 ] - a[ 0 ];
  11273. };
  11274. // Rendering
  11275. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11276. if ( camera instanceof THREE.Camera === false ) {
  11277. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11278. return;
  11279. }
  11280. var i, il,
  11281. webglObject, object,
  11282. renderList,
  11283. lights = scene.__lights,
  11284. fog = scene.fog;
  11285. // reset caching for this frame
  11286. _currentMaterialId = -1;
  11287. _lightsNeedUpdate = true;
  11288. // update scene graph
  11289. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11290. // update camera matrices and frustum
  11291. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11292. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11293. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  11294. _frustum.setFromMatrix( _projScreenMatrix );
  11295. // update WebGL objects
  11296. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11297. // custom render plugins (pre pass)
  11298. renderPlugins( this.renderPluginsPre, scene, camera );
  11299. //
  11300. _this.info.render.calls = 0;
  11301. _this.info.render.vertices = 0;
  11302. _this.info.render.faces = 0;
  11303. _this.info.render.points = 0;
  11304. renderer.setRenderTarget( renderTarget );
  11305. if ( this.autoClear || forceClear ) {
  11306. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11307. }
  11308. // set matrices for regular objects (frustum culled)
  11309. renderList = scene.__webglObjects;
  11310. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11311. webglObject = renderList[ i ];
  11312. object = webglObject.object;
  11313. webglObject.id = i;
  11314. webglObject.render = false;
  11315. if ( object.visible ) {
  11316. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  11317. setupMatrices( object, camera );
  11318. unrollBufferMaterial( webglObject );
  11319. webglObject.render = true;
  11320. if ( this.sortObjects === true ) {
  11321. if ( object.renderDepth !== null ) {
  11322. webglObject.z = object.renderDepth;
  11323. } else {
  11324. _vector3.getPositionFromMatrix( object.matrixWorld );
  11325. _vector3.applyProjection(_projScreenMatrix);
  11326. webglObject.z = _vector3.z;
  11327. }
  11328. }
  11329. }
  11330. }
  11331. }
  11332. if ( this.sortObjects ) {
  11333. renderList.sort( painterSortStable );
  11334. }
  11335. // set matrices for immediate objects
  11336. renderList = scene.__webglObjectsImmediate;
  11337. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11338. webglObject = renderList[ i ];
  11339. object = webglObject.object;
  11340. if ( object.visible ) {
  11341. setupMatrices( object, camera );
  11342. unrollImmediateBufferMaterial( webglObject );
  11343. }
  11344. }
  11345. if ( scene.overrideMaterial ) {
  11346. var material = scene.overrideMaterial;
  11347. renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11348. renderer.setDepthTest( material.depthTest );
  11349. renderer.setDepthWrite( material.depthWrite );
  11350. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11351. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11352. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11353. } else {
  11354. var material = null;
  11355. // opaque pass (front-to-back order)
  11356. renderer.setBlending( THREE.NoBlending );
  11357. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  11358. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  11359. // transparent pass (back-to-front order)
  11360. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  11361. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  11362. }
  11363. // custom render plugins (post pass)
  11364. renderPlugins( this.renderPluginsPost, scene, camera );
  11365. // Generate mipmap if we're using any kind of mipmap filtering
  11366. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11367. renderer.updateRenderTargetMipmap( renderTarget );
  11368. }
  11369. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11370. renderer.setDepthTest( true );
  11371. renderer.setDepthWrite( true );
  11372. // _gl.finish();
  11373. };
  11374. function renderPlugins( plugins, scene, camera ) {
  11375. if ( ! plugins.length ) return;
  11376. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11377. // reset state for plugin (to start from clean slate)
  11378. _currentProgram = null;
  11379. _currentCamera = null;
  11380. _currentGeometryGroupHash = -1;
  11381. _currentMaterialId = -1;
  11382. _lightsNeedUpdate = true;
  11383. renderer.resetState();
  11384. plugins[ i ].render( scene, camera, renderer.getCurrentWidth(), renderer.getCurrentWidth() );
  11385. // reset state after plugin (anything could have changed)
  11386. _currentProgram = null;
  11387. _currentCamera = null;
  11388. _currentGeometryGroupHash = -1;
  11389. _currentMaterialId = -1;
  11390. _lightsNeedUpdate = true;
  11391. renderer.resetState();
  11392. }
  11393. };
  11394. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11395. var webglObject, object, buffer, material, start, end, delta;
  11396. if ( reverse ) {
  11397. start = renderList.length - 1;
  11398. end = -1;
  11399. delta = -1;
  11400. } else {
  11401. start = 0;
  11402. end = renderList.length;
  11403. delta = 1;
  11404. }
  11405. for ( var i = start; i !== end; i += delta ) {
  11406. webglObject = renderList[ i ];
  11407. if ( webglObject.render ) {
  11408. object = webglObject.object;
  11409. buffer = webglObject.buffer;
  11410. if ( overrideMaterial ) {
  11411. material = overrideMaterial;
  11412. } else {
  11413. material = webglObject[ materialType ];
  11414. if ( ! material ) continue;
  11415. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11416. renderer.setDepthTest( material.depthTest );
  11417. renderer.setDepthWrite( material.depthWrite );
  11418. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11419. }
  11420. renderer.setMaterialFaces( material );
  11421. if ( buffer instanceof THREE.BufferGeometry ) {
  11422. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11423. } else {
  11424. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11425. }
  11426. }
  11427. }
  11428. };
  11429. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11430. var webglObject, object, material, program;
  11431. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11432. webglObject = renderList[ i ];
  11433. object = webglObject.object;
  11434. if ( object.visible ) {
  11435. if ( overrideMaterial ) {
  11436. material = overrideMaterial;
  11437. } else {
  11438. material = webglObject[ materialType ];
  11439. if ( ! material ) continue;
  11440. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11441. renderer.setDepthTest( material.depthTest );
  11442. renderer.setDepthWrite( material.depthWrite );
  11443. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11444. }
  11445. _this.renderImmediateObject( camera, lights, fog, material, object );
  11446. }
  11447. }
  11448. };
  11449. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11450. var program = setProgram( camera, lights, fog, material, object );
  11451. _currentGeometryGroupHash = -1;
  11452. renderer.setMaterialFaces( material );
  11453. if ( object.immediateRenderCallback ) {
  11454. object.immediateRenderCallback( program, renderer.getContext(), _frustum );
  11455. } else {
  11456. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11457. }
  11458. };
  11459. function unrollImmediateBufferMaterial ( globject ) {
  11460. var object = globject.object,
  11461. material = object.material;
  11462. if ( material.transparent ) {
  11463. globject.transparent = material;
  11464. globject.opaque = null;
  11465. } else {
  11466. globject.opaque = material;
  11467. globject.transparent = null;
  11468. }
  11469. };
  11470. function unrollBufferMaterial ( globject ) {
  11471. var object = globject.object,
  11472. buffer = globject.buffer,
  11473. material, materialIndex, meshMaterial;
  11474. meshMaterial = object.material;
  11475. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11476. materialIndex = buffer.materialIndex;
  11477. material = meshMaterial.materials[ materialIndex ];
  11478. if ( material.transparent ) {
  11479. globject.transparent = material;
  11480. globject.opaque = null;
  11481. } else {
  11482. globject.opaque = material;
  11483. globject.transparent = null;
  11484. }
  11485. } else {
  11486. material = meshMaterial;
  11487. if ( material ) {
  11488. if ( material.transparent ) {
  11489. globject.transparent = material;
  11490. globject.opaque = null;
  11491. } else {
  11492. globject.opaque = material;
  11493. globject.transparent = null;
  11494. }
  11495. }
  11496. }
  11497. };
  11498. // Geometry splitting
  11499. function sortFacesByMaterial ( geometry, material ) {
  11500. var f, fl, face, materialIndex, vertices,
  11501. groupHash, hash_map = {};
  11502. var numMorphTargets = geometry.morphTargets.length;
  11503. var numMorphNormals = geometry.morphNormals.length;
  11504. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11505. geometry.geometryGroups = {};
  11506. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11507. face = geometry.faces[ f ];
  11508. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  11509. if ( hash_map[ materialIndex ] === undefined ) {
  11510. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  11511. }
  11512. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  11513. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11514. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11515. }
  11516. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11517. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11518. hash_map[ materialIndex ].counter += 1;
  11519. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  11520. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11521. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11522. }
  11523. }
  11524. if ( face instanceof THREE.Face3 ) {
  11525. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11526. } else {
  11527. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11528. }
  11529. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11530. }
  11531. geometry.geometryGroupsList = [];
  11532. for ( var g in geometry.geometryGroups ) {
  11533. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11534. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11535. }
  11536. };
  11537. // Objects refresh
  11538. this.initWebGLObjects = function ( scene ) {
  11539. if ( !scene.__webglObjects ) {
  11540. scene.__webglObjects = [];
  11541. scene.__webglObjectsImmediate = [];
  11542. scene.__webglSprites = [];
  11543. scene.__webglFlares = [];
  11544. }
  11545. while ( scene.__objectsAdded.length ) {
  11546. addObject( scene.__objectsAdded[ 0 ], scene );
  11547. scene.__objectsAdded.splice( 0, 1 );
  11548. }
  11549. while ( scene.__objectsRemoved.length ) {
  11550. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11551. scene.__objectsRemoved.splice( 0, 1 );
  11552. }
  11553. // update must be called after objects adding / removal
  11554. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11555. updateObject( scene.__webglObjects[ o ].object );
  11556. }
  11557. };
  11558. // Objects adding
  11559. function addObject( object, scene ) {
  11560. var g, geometry, material, geometryGroup;
  11561. if ( ! object.__webglInit ) {
  11562. object.__webglInit = true;
  11563. object._modelViewMatrix = new THREE.Matrix4();
  11564. object._normalMatrix = new THREE.Matrix3();
  11565. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  11566. object.geometry.__webglInit = true;
  11567. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  11568. }
  11569. if ( object instanceof THREE.Mesh ) {
  11570. geometry = object.geometry;
  11571. material = object.material;
  11572. if ( geometry instanceof THREE.Geometry ) {
  11573. if ( geometry.geometryGroups === undefined ) {
  11574. sortFacesByMaterial( geometry, material );
  11575. }
  11576. // create separate VBOs per geometry chunk
  11577. for ( g in geometry.geometryGroups ) {
  11578. geometryGroup = geometry.geometryGroups[ g ];
  11579. // initialise VBO on the first access
  11580. if ( ! geometryGroup.__webglVertexBuffer ) {
  11581. meshRenderer.createBuffers( geometryGroup );
  11582. meshRenderer.initBuffers( geometryGroup, object );
  11583. geometry.verticesNeedUpdate = true;
  11584. geometry.morphTargetsNeedUpdate = true;
  11585. geometry.elementsNeedUpdate = true;
  11586. geometry.uvsNeedUpdate = true;
  11587. geometry.normalsNeedUpdate = true;
  11588. geometry.tangentsNeedUpdate = true;
  11589. geometry.colorsNeedUpdate = true;
  11590. }
  11591. }
  11592. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11593. initDirectBuffers( geometry );
  11594. }
  11595. } else if ( object instanceof THREE.Ribbon ) {
  11596. geometry = object.geometry;
  11597. if ( ! geometry.__webglVertexBuffer ) {
  11598. ribbonRenderer.createBuffers( geometry );
  11599. ribbonRenderer.initBuffers( geometry, object );
  11600. geometry.verticesNeedUpdate = true;
  11601. geometry.colorsNeedUpdate = true;
  11602. geometry.normalsNeedUpdate = true;
  11603. }
  11604. } else if ( object instanceof THREE.Line ) {
  11605. geometry = object.geometry;
  11606. if ( ! geometry.__webglVertexBuffer ) {
  11607. if ( geometry instanceof THREE.Geometry ) {
  11608. lineRenderer.createBuffers( geometry );
  11609. lineRenderer.initBuffers( geometry, object );
  11610. geometry.verticesNeedUpdate = true;
  11611. geometry.colorsNeedUpdate = true;
  11612. geometry.lineDistancesNeedUpdate = true;
  11613. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11614. initDirectBuffers( geometry );
  11615. }
  11616. }
  11617. } else if ( object instanceof THREE.ParticleSystem ) {
  11618. geometry = object.geometry;
  11619. if ( ! geometry.__webglVertexBuffer ) {
  11620. if ( geometry instanceof THREE.Geometry ) {
  11621. particleRenderer.createBuffers( geometry );
  11622. particleRenderer.initBuffers( geometry, object );
  11623. geometry.verticesNeedUpdate = true;
  11624. geometry.colorsNeedUpdate = true;
  11625. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11626. initDirectBuffers( geometry );
  11627. }
  11628. }
  11629. }
  11630. }
  11631. if ( ! object.__webglActive ) {
  11632. if ( object instanceof THREE.Mesh ) {
  11633. geometry = object.geometry;
  11634. if ( geometry instanceof THREE.BufferGeometry ) {
  11635. addBuffer( scene.__webglObjects, geometry, object );
  11636. } else if ( geometry instanceof THREE.Geometry ) {
  11637. for ( g in geometry.geometryGroups ) {
  11638. geometryGroup = geometry.geometryGroups[ g ];
  11639. addBuffer( scene.__webglObjects, geometryGroup, object );
  11640. }
  11641. }
  11642. } else if ( object instanceof THREE.Ribbon ||
  11643. object instanceof THREE.Line ||
  11644. object instanceof THREE.ParticleSystem ) {
  11645. geometry = object.geometry;
  11646. addBuffer( scene.__webglObjects, geometry, object );
  11647. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11648. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11649. } else if ( object instanceof THREE.Sprite ) {
  11650. scene.__webglSprites.push( object );
  11651. } else if ( object instanceof THREE.LensFlare ) {
  11652. scene.__webglFlares.push( object );
  11653. }
  11654. object.__webglActive = true;
  11655. }
  11656. };
  11657. function addBuffer ( objlist, buffer, object ) {
  11658. objlist.push(
  11659. {
  11660. id: null,
  11661. buffer: buffer,
  11662. object: object,
  11663. opaque: null,
  11664. transparent: null,
  11665. render: false,
  11666. z: 0
  11667. }
  11668. );
  11669. };
  11670. function addBufferImmediate ( objlist, object ) {
  11671. objlist.push(
  11672. {
  11673. object: object,
  11674. opaque: null,
  11675. transparent: null
  11676. }
  11677. );
  11678. };
  11679. // Objects updates
  11680. function updateObject ( object ) {
  11681. var geometry = object.geometry,
  11682. geometryGroup, customAttributesDirty, material;
  11683. if ( object instanceof THREE.Mesh ) {
  11684. if ( geometry instanceof THREE.BufferGeometry ) {
  11685. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11686. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11687. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11688. setDirectBuffers( geometry, !geometry.dynamic );
  11689. }
  11690. geometry.verticesNeedUpdate = false;
  11691. geometry.elementsNeedUpdate = false;
  11692. geometry.uvsNeedUpdate = false;
  11693. geometry.normalsNeedUpdate = false;
  11694. geometry.colorsNeedUpdate = false;
  11695. geometry.tangentsNeedUpdate = false;
  11696. } else {
  11697. // check all geometry groups
  11698. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11699. geometryGroup = geometry.geometryGroupsList[ i ];
  11700. material = getBufferMaterial( object, geometryGroup );
  11701. if ( geometry.buffersNeedUpdate ) {
  11702. meshRenderer.initBuffers( geometryGroup, object );
  11703. }
  11704. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11705. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11706. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11707. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11708. meshRenderer.setBuffers( geometryGroup, object, !geometry.dynamic, material );
  11709. }
  11710. }
  11711. geometry.verticesNeedUpdate = false;
  11712. geometry.morphTargetsNeedUpdate = false;
  11713. geometry.elementsNeedUpdate = false;
  11714. geometry.uvsNeedUpdate = false;
  11715. geometry.normalsNeedUpdate = false;
  11716. geometry.colorsNeedUpdate = false;
  11717. geometry.tangentsNeedUpdate = false;
  11718. geometry.buffersNeedUpdate = false;
  11719. material.attributes && clearCustomAttributes( material );
  11720. }
  11721. } else if ( object instanceof THREE.Ribbon ) {
  11722. material = getBufferMaterial( object, geometry );
  11723. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11724. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  11725. ribbonRenderer.setBuffers( geometry);
  11726. }
  11727. geometry.verticesNeedUpdate = false;
  11728. geometry.colorsNeedUpdate = false;
  11729. geometry.normalsNeedUpdate = false;
  11730. material.attributes && clearCustomAttributes( material );
  11731. } else if ( object instanceof THREE.Line ) {
  11732. if ( geometry instanceof THREE.BufferGeometry ) {
  11733. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11734. setDirectBuffers( geometry, !geometry.dynamic );
  11735. }
  11736. geometry.verticesNeedUpdate = false;
  11737. geometry.colorsNeedUpdate = false;
  11738. } else {
  11739. material = getBufferMaterial( object, geometry );
  11740. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11741. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  11742. lineRenderer.setBuffers( geometry);
  11743. }
  11744. geometry.verticesNeedUpdate = false;
  11745. geometry.colorsNeedUpdate = false;
  11746. geometry.lineDistancesNeedUpdate = false;
  11747. material.attributes && clearCustomAttributes( material );
  11748. }
  11749. } else if ( object instanceof THREE.ParticleSystem ) {
  11750. if ( geometry instanceof THREE.BufferGeometry ) {
  11751. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11752. setDirectBuffers( geometry, !geometry.dynamic );
  11753. }
  11754. geometry.verticesNeedUpdate = false;
  11755. geometry.colorsNeedUpdate = false;
  11756. } else {
  11757. material = getBufferMaterial( object, geometry );
  11758. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11759. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11760. particleRenderer.setBuffers( geometry, object, _projScreenMatrix);
  11761. }
  11762. geometry.verticesNeedUpdate = false;
  11763. geometry.colorsNeedUpdate = false;
  11764. material.attributes && clearCustomAttributes( material );
  11765. }
  11766. }
  11767. };
  11768. // Objects updates - custom attributes check
  11769. function areCustomAttributesDirty ( material ) {
  11770. for ( var a in material.attributes ) {
  11771. if ( material.attributes[ a ].needsUpdate ) return true;
  11772. }
  11773. return false;
  11774. };
  11775. function clearCustomAttributes ( material ) {
  11776. for ( var a in material.attributes ) {
  11777. material.attributes[ a ].needsUpdate = false;
  11778. }
  11779. };
  11780. // Objects removal
  11781. function removeObject ( object, scene ) {
  11782. if ( object instanceof THREE.Mesh ||
  11783. object instanceof THREE.ParticleSystem ||
  11784. object instanceof THREE.Ribbon ||
  11785. object instanceof THREE.Line ) {
  11786. removeInstances( scene.__webglObjects, object );
  11787. } else if ( object instanceof THREE.Sprite ) {
  11788. removeInstancesDirect( scene.__webglSprites, object );
  11789. } else if ( object instanceof THREE.LensFlare ) {
  11790. removeInstancesDirect( scene.__webglFlares, object );
  11791. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11792. removeInstances( scene.__webglObjectsImmediate, object );
  11793. }
  11794. object.__webglActive = false;
  11795. };
  11796. function removeInstances ( objlist, object ) {
  11797. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11798. if ( objlist[ o ].object === object ) {
  11799. objlist.splice( o, 1 );
  11800. }
  11801. }
  11802. };
  11803. function removeInstancesDirect ( objlist, object ) {
  11804. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11805. if ( objlist[ o ] === object ) {
  11806. objlist.splice( o, 1 );
  11807. }
  11808. }
  11809. };
  11810. // Materials
  11811. this.initMaterial = function ( material, lights, fog, object ) {
  11812. material.addEventListener( 'dispose', onMaterialDispose );
  11813. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11814. if ( material instanceof THREE.MeshDepthMaterial ) {
  11815. shaderID = 'depth';
  11816. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11817. shaderID = 'normal';
  11818. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11819. shaderID = 'basic';
  11820. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11821. shaderID = 'lambert';
  11822. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11823. shaderID = 'phong';
  11824. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11825. shaderID = 'basic';
  11826. } else if ( material instanceof THREE.LineDashedMaterial ) {
  11827. shaderID = 'dashed';
  11828. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11829. shaderID = 'particle_basic';
  11830. }
  11831. if ( shaderID ) {
  11832. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11833. }
  11834. // heuristics to create shader parameters according to lights in the scene
  11835. // (not to blow over maxLights budget)
  11836. maxLightCount = allocateLights( lights );
  11837. maxShadows = allocateShadows( lights );
  11838. maxBones = allocateBones( object );
  11839. parameters = {
  11840. map: !!material.map,
  11841. envMap: !!material.envMap,
  11842. lightMap: !!material.lightMap,
  11843. bumpMap: !!material.bumpMap,
  11844. normalMap: !!material.normalMap,
  11845. specularMap: !!material.specularMap,
  11846. vertexColors: material.vertexColors,
  11847. fog: fog,
  11848. useFog: material.fog,
  11849. fogExp: fog instanceof THREE.FogExp2,
  11850. sizeAttenuation: material.sizeAttenuation,
  11851. skinning: material.skinning,
  11852. maxBones: maxBones,
  11853. useVertexTexture: renderer.supportsBoneTextures && object && object.useVertexTexture,
  11854. boneTextureWidth: object && object.boneTextureWidth,
  11855. boneTextureHeight: object && object.boneTextureHeight,
  11856. morphTargets: material.morphTargets,
  11857. morphNormals: material.morphNormals,
  11858. maxMorphTargets: this.maxMorphTargets,
  11859. maxMorphNormals: this.maxMorphNormals,
  11860. maxDirLights: maxLightCount.directional,
  11861. maxPointLights: maxLightCount.point,
  11862. maxSpotLights: maxLightCount.spot,
  11863. maxHemiLights: maxLightCount.hemi,
  11864. maxShadows: maxShadows,
  11865. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11866. shadowMapType: this.shadowMapType,
  11867. shadowMapDebug: this.shadowMapDebug,
  11868. shadowMapCascade: this.shadowMapCascade,
  11869. alphaTest: material.alphaTest,
  11870. metal: material.metal,
  11871. perPixel: material.perPixel,
  11872. wrapAround: material.wrapAround,
  11873. doubleSided: material.side === THREE.DoubleSide,
  11874. flipSided: material.side === THREE.BackSide,
  11875. gammaInput : this.gammaInput,
  11876. gammaOutput : this.gammaOutput ,
  11877. physicallyBasedShading : this.physicallyBasedShading
  11878. };
  11879. material.program = shaderBuilder.buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  11880. var attributes = material.program.attributes;
  11881. if ( material.morphTargets ) {
  11882. material.numSupportedMorphTargets = 0;
  11883. var id, base = "morphTarget";
  11884. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11885. id = base + i;
  11886. if ( attributes[ id ] >= 0 ) {
  11887. material.numSupportedMorphTargets ++;
  11888. }
  11889. }
  11890. }
  11891. if ( material.morphNormals ) {
  11892. material.numSupportedMorphNormals = 0;
  11893. var id, base = "morphNormal";
  11894. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11895. id = base + i;
  11896. if ( attributes[ id ] >= 0 ) {
  11897. material.numSupportedMorphNormals ++;
  11898. }
  11899. }
  11900. }
  11901. material.uniformsList = [];
  11902. for ( u in material.uniforms ) {
  11903. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11904. }
  11905. };
  11906. function setMaterialShaders( material, shaders ) {
  11907. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11908. material.vertexShader = shaders.vertexShader;
  11909. material.fragmentShader = shaders.fragmentShader;
  11910. };
  11911. function setProgram( camera, lights, fog, material, object ) {
  11912. _usedTextureUnits = 0;
  11913. if ( material.needsUpdate ) {
  11914. if ( material.program ) deallocateMaterial( material );
  11915. _this.initMaterial( material, lights, fog, object );
  11916. material.needsUpdate = false;
  11917. }
  11918. if ( material.morphTargets ) {
  11919. if ( ! object.__webglMorphTargetInfluences ) {
  11920. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11921. }
  11922. }
  11923. var refreshMaterial = false;
  11924. var program = material.program,
  11925. p_uniforms = program.uniforms,
  11926. m_uniforms = material.uniforms;
  11927. if ( program !== _currentProgram ) {
  11928. renderer.useProgram( program );
  11929. _currentProgram = program;
  11930. refreshMaterial = true;
  11931. }
  11932. if ( material.id !== _currentMaterialId ) {
  11933. _currentMaterialId = material.id;
  11934. refreshMaterial = true;
  11935. }
  11936. if ( refreshMaterial || camera !== _currentCamera ) {
  11937. renderer.uniformMatrix4fv( p_uniforms.projectionMatrix, camera.projectionMatrix.elements );
  11938. if ( camera !== _currentCamera ) _currentCamera = camera;
  11939. }
  11940. // skinning uniforms must be set even if material didn't change
  11941. // auto-setting of texture unit for bone texture must go before other textures
  11942. // not sure why, but otherwise weird things happen
  11943. if ( material.skinning ) {
  11944. if ( renderer.supportsBoneTextures && object.useVertexTexture ) {
  11945. if ( p_uniforms.boneTexture !== null ) {
  11946. var textureUnit = getTextureUnit();
  11947. renderer.uniform1i( p_uniforms.boneTexture, textureUnit );
  11948. renderer.setTexture( object.boneTexture, textureUnit );
  11949. }
  11950. } else {
  11951. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11952. renderer.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, object.boneMatrices );
  11953. }
  11954. }
  11955. }
  11956. if ( refreshMaterial ) {
  11957. // refresh uniforms common to several materials
  11958. if ( fog && material.fog ) {
  11959. refreshUniformsFog( m_uniforms, fog );
  11960. }
  11961. if ( material instanceof THREE.MeshPhongMaterial ||
  11962. material instanceof THREE.MeshLambertMaterial ||
  11963. material.lights ) {
  11964. if ( _lightsNeedUpdate ) {
  11965. setupLights( program, lights );
  11966. _lightsNeedUpdate = false;
  11967. }
  11968. refreshUniformsLights( m_uniforms, _lights );
  11969. }
  11970. if ( material instanceof THREE.MeshBasicMaterial ||
  11971. material instanceof THREE.MeshLambertMaterial ||
  11972. material instanceof THREE.MeshPhongMaterial ) {
  11973. refreshUniformsCommon( m_uniforms, material );
  11974. }
  11975. // refresh single material specific uniforms
  11976. if ( material instanceof THREE.LineBasicMaterial ) {
  11977. refreshUniformsLine( m_uniforms, material );
  11978. } else if ( material instanceof THREE.LineDashedMaterial ) {
  11979. refreshUniformsLine( m_uniforms, material );
  11980. refreshUniformsDash( m_uniforms, material );
  11981. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11982. refreshUniformsParticle( m_uniforms, material );
  11983. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11984. refreshUniformsPhong( m_uniforms, material );
  11985. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11986. refreshUniformsLambert( m_uniforms, material );
  11987. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11988. m_uniforms.mNear.value = camera.near;
  11989. m_uniforms.mFar.value = camera.far;
  11990. m_uniforms.opacity.value = material.opacity;
  11991. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11992. m_uniforms.opacity.value = material.opacity;
  11993. }
  11994. if ( object.receiveShadow && ! material._shadowPass ) {
  11995. refreshUniformsShadow( m_uniforms, lights );
  11996. }
  11997. // load common uniforms
  11998. loadUniformsGeneric( program, material.uniformsList );
  11999. // load material specific uniforms
  12000. // (shader material also gets them for the sake of genericity)
  12001. if ( material instanceof THREE.ShaderMaterial ||
  12002. material instanceof THREE.MeshPhongMaterial ||
  12003. material.envMap ) {
  12004. if ( p_uniforms.cameraPosition !== null ) {
  12005. _vector3.getPositionFromMatrix( camera.matrixWorld );
  12006. renderer.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  12007. }
  12008. }
  12009. if ( material instanceof THREE.MeshPhongMaterial ||
  12010. material instanceof THREE.MeshLambertMaterial ||
  12011. material instanceof THREE.ShaderMaterial ||
  12012. material.skinning ) {
  12013. if ( p_uniforms.viewMatrix !== null ) {
  12014. renderer.uniformMatrix4fv( p_uniforms.viewMatrix, camera.matrixWorldInverse.elements );
  12015. }
  12016. }
  12017. }
  12018. loadUniformsMatrices( p_uniforms, object );
  12019. if ( p_uniforms.modelMatrix !== null ) {
  12020. renderer.uniformMatrix4fv( p_uniforms.modelMatrix, object.matrixWorld.elements );
  12021. }
  12022. return program;
  12023. };
  12024. // Uniforms (refresh uniforms objects)
  12025. function refreshUniformsCommon ( uniforms, material ) {
  12026. uniforms.opacity.value = material.opacity;
  12027. if ( _this.gammaInput ) {
  12028. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12029. } else {
  12030. uniforms.diffuse.value = material.color;
  12031. }
  12032. uniforms.map.value = material.map;
  12033. uniforms.lightMap.value = material.lightMap;
  12034. uniforms.specularMap.value = material.specularMap;
  12035. if ( material.bumpMap ) {
  12036. uniforms.bumpMap.value = material.bumpMap;
  12037. uniforms.bumpScale.value = material.bumpScale;
  12038. }
  12039. if ( material.normalMap ) {
  12040. uniforms.normalMap.value = material.normalMap;
  12041. uniforms.normalScale.value.copy( material.normalScale );
  12042. }
  12043. // uv repeat and offset setting priorities
  12044. // 1. color map
  12045. // 2. specular map
  12046. // 3. normal map
  12047. // 4. bump map
  12048. var uvScaleMap;
  12049. if ( material.map ) {
  12050. uvScaleMap = material.map;
  12051. } else if ( material.specularMap ) {
  12052. uvScaleMap = material.specularMap;
  12053. } else if ( material.normalMap ) {
  12054. uvScaleMap = material.normalMap;
  12055. } else if ( material.bumpMap ) {
  12056. uvScaleMap = material.bumpMap;
  12057. }
  12058. if ( uvScaleMap !== undefined ) {
  12059. var offset = uvScaleMap.offset;
  12060. var repeat = uvScaleMap.repeat;
  12061. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12062. }
  12063. uniforms.envMap.value = material.envMap;
  12064. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12065. if ( _this.gammaInput ) {
  12066. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12067. uniforms.reflectivity.value = material.reflectivity;
  12068. } else {
  12069. uniforms.reflectivity.value = material.reflectivity;
  12070. }
  12071. uniforms.refractionRatio.value = material.refractionRatio;
  12072. uniforms.combine.value = material.combine;
  12073. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12074. };
  12075. function refreshUniformsLine ( uniforms, material ) {
  12076. uniforms.diffuse.value = material.color;
  12077. uniforms.opacity.value = material.opacity;
  12078. };
  12079. function refreshUniformsDash ( uniforms, material ) {
  12080. uniforms.dashSize.value = material.dashSize;
  12081. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12082. uniforms.scale.value = material.scale;
  12083. };
  12084. function refreshUniformsParticle ( uniforms, material ) {
  12085. uniforms.psColor.value = material.color;
  12086. uniforms.opacity.value = material.opacity;
  12087. uniforms.size.value = material.size;
  12088. uniforms.scale.value = renderer.getDomElement().height / 2.0; // TODO: Cache this.
  12089. uniforms.map.value = material.map;
  12090. };
  12091. function refreshUniformsFog ( uniforms, fog ) {
  12092. uniforms.fogColor.value = fog.color;
  12093. if ( fog instanceof THREE.Fog ) {
  12094. uniforms.fogNear.value = fog.near;
  12095. uniforms.fogFar.value = fog.far;
  12096. } else if ( fog instanceof THREE.FogExp2 ) {
  12097. uniforms.fogDensity.value = fog.density;
  12098. }
  12099. };
  12100. function refreshUniformsPhong ( uniforms, material ) {
  12101. uniforms.shininess.value = material.shininess;
  12102. if ( _this.gammaInput ) {
  12103. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12104. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12105. uniforms.specular.value.copyGammaToLinear( material.specular );
  12106. } else {
  12107. uniforms.ambient.value = material.ambient;
  12108. uniforms.emissive.value = material.emissive;
  12109. uniforms.specular.value = material.specular;
  12110. }
  12111. if ( material.wrapAround ) {
  12112. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12113. }
  12114. };
  12115. function refreshUniformsLambert ( uniforms, material ) {
  12116. if ( _this.gammaInput ) {
  12117. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12118. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12119. } else {
  12120. uniforms.ambient.value = material.ambient;
  12121. uniforms.emissive.value = material.emissive;
  12122. }
  12123. if ( material.wrapAround ) {
  12124. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12125. }
  12126. };
  12127. function refreshUniformsLights ( uniforms, lights ) {
  12128. uniforms.ambientLightColor.value = lights.ambient;
  12129. uniforms.directionalLightColor.value = lights.directional.colors;
  12130. uniforms.directionalLightDirection.value = lights.directional.positions;
  12131. uniforms.pointLightColor.value = lights.point.colors;
  12132. uniforms.pointLightPosition.value = lights.point.positions;
  12133. uniforms.pointLightDistance.value = lights.point.distances;
  12134. uniforms.spotLightColor.value = lights.spot.colors;
  12135. uniforms.spotLightPosition.value = lights.spot.positions;
  12136. uniforms.spotLightDistance.value = lights.spot.distances;
  12137. uniforms.spotLightDirection.value = lights.spot.directions;
  12138. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12139. uniforms.spotLightExponent.value = lights.spot.exponents;
  12140. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12141. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12142. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12143. };
  12144. function refreshUniformsShadow ( uniforms, lights ) {
  12145. if ( uniforms.shadowMatrix ) {
  12146. var j = 0;
  12147. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12148. var light = lights[ i ];
  12149. if ( ! light.castShadow ) continue;
  12150. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12151. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12152. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12153. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12154. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12155. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12156. j ++;
  12157. }
  12158. }
  12159. }
  12160. };
  12161. // Uniforms (load to GPU)
  12162. function loadUniformsMatrices ( uniforms, object ) {
  12163. renderer.uniformMatrix4fv( uniforms.modelViewMatrix, object._modelViewMatrix.elements );
  12164. if ( uniforms.normalMatrix ) {
  12165. renderer.uniformMatrix3fv( uniforms.normalMatrix, object._normalMatrix.elements );
  12166. }
  12167. };
  12168. function getTextureUnit() {
  12169. var textureUnit = _usedTextureUnits;
  12170. if ( textureUnit >= renderer.maxTextures ) {
  12171. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + renderer.maxTextures );
  12172. }
  12173. _usedTextureUnits += 1;
  12174. return textureUnit;
  12175. };
  12176. function loadUniformsGeneric ( program, uniforms ) {
  12177. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12178. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12179. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12180. if ( !location ) continue;
  12181. uniform = uniforms[ j ][ 0 ];
  12182. type = uniform.type;
  12183. value = uniform.value;
  12184. if ( type === "i" ) { // single integer
  12185. renderer.uniform1i( location, value );
  12186. } else if ( type === "f" ) { // single float
  12187. renderer.uniform1f( location, value );
  12188. } else if ( type === "v2" ) { // single THREE.Vector2
  12189. renderer.uniform2f( location, value.x, value.y );
  12190. } else if ( type === "v3" ) { // single THREE.Vector3
  12191. renderer.uniform3f( location, value.x, value.y, value.z );
  12192. } else if ( type === "v4" ) { // single THREE.Vector4
  12193. renderer.uniform4f( location, value.x, value.y, value.z, value.w );
  12194. } else if ( type === "c" ) { // single THREE.Color
  12195. renderer.uniform3f( location, value.r, value.g, value.b );
  12196. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12197. renderer.uniform1iv( location, value );
  12198. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12199. renderer.uniform3iv( location, value );
  12200. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12201. renderer.uniform1fv( location, value );
  12202. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12203. renderer.uniform3fv( location, value );
  12204. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12205. if ( uniform._array === undefined ) {
  12206. uniform._array = new Float32Array( 2 * value.length );
  12207. }
  12208. for ( i = 0, il = value.length; i < il; i ++ ) {
  12209. offset = i * 2;
  12210. uniform._array[ offset ] = value[ i ].x;
  12211. uniform._array[ offset + 1 ] = value[ i ].y;
  12212. }
  12213. renderer.uniform2fv( location, uniform._array );
  12214. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12215. if ( uniform._array === undefined ) {
  12216. uniform._array = new Float32Array( 3 * value.length );
  12217. }
  12218. for ( i = 0, il = value.length; i < il; i ++ ) {
  12219. offset = i * 3;
  12220. uniform._array[ offset ] = value[ i ].x;
  12221. uniform._array[ offset + 1 ] = value[ i ].y;
  12222. uniform._array[ offset + 2 ] = value[ i ].z;
  12223. }
  12224. renderer.uniform3fv( location, uniform._array );
  12225. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12226. if ( uniform._array === undefined ) {
  12227. uniform._array = new Float32Array( 4 * value.length );
  12228. }
  12229. for ( i = 0, il = value.length; i < il; i ++ ) {
  12230. offset = i * 4;
  12231. uniform._array[ offset ] = value[ i ].x;
  12232. uniform._array[ offset + 1 ] = value[ i ].y;
  12233. uniform._array[ offset + 2 ] = value[ i ].z;
  12234. uniform._array[ offset + 3 ] = value[ i ].w;
  12235. }
  12236. renderer.uniform4fv( location, uniform._array );
  12237. } else if ( type === "m4") { // single THREE.Matrix4
  12238. if ( uniform._array === undefined ) {
  12239. uniform._array = new Float32Array( 16 );
  12240. }
  12241. value.flattenToArray( uniform._array );
  12242. renderer.uniformMatrix4fv( location, uniform._array );
  12243. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12244. if ( uniform._array === undefined ) {
  12245. uniform._array = new Float32Array( 16 * value.length );
  12246. }
  12247. for ( i = 0, il = value.length; i < il; i ++ ) {
  12248. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12249. }
  12250. renderer.uniformMatrix4fv( location, uniform._array );
  12251. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12252. texture = value;
  12253. textureUnit = getTextureUnit();
  12254. renderer.uniform1i( location, textureUnit );
  12255. if ( !texture ) continue;
  12256. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12257. renderer.setCubeTexture( texture, textureUnit );
  12258. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12259. renderer.setCubeTextureDynamic( texture, textureUnit );
  12260. } else {
  12261. renderer.setTexture( texture, textureUnit );
  12262. }
  12263. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12264. if ( uniform._array === undefined ) {
  12265. uniform._array = [];
  12266. }
  12267. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12268. uniform._array[ i ] = getTextureUnit();
  12269. }
  12270. renderer.uniform1iv( location, uniform._array );
  12271. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12272. texture = uniform.value[ i ];
  12273. textureUnit = uniform._array[ i ];
  12274. if ( !texture ) continue;
  12275. renderer.setTexture( texture, textureUnit );
  12276. }
  12277. }
  12278. }
  12279. };
  12280. function setupMatrices ( object, camera ) {
  12281. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12282. object._normalMatrix.getInverse( object._modelViewMatrix );
  12283. object._normalMatrix.transpose();
  12284. };
  12285. //
  12286. function setColorGamma( array, offset, color, intensitySq ) {
  12287. array[ offset ] = color.r * color.r * intensitySq;
  12288. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12289. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12290. };
  12291. function setColorLinear( array, offset, color, intensity ) {
  12292. array[ offset ] = color.r * intensity;
  12293. array[ offset + 1 ] = color.g * intensity;
  12294. array[ offset + 2 ] = color.b * intensity;
  12295. };
  12296. function setupLights ( program, lights ) {
  12297. var l, ll, light, n,
  12298. r = 0, g = 0, b = 0,
  12299. color, skyColor, groundColor,
  12300. intensity, intensitySq,
  12301. position,
  12302. distance,
  12303. zlights = _lights,
  12304. dirColors = zlights.directional.colors,
  12305. dirPositions = zlights.directional.positions,
  12306. pointColors = zlights.point.colors,
  12307. pointPositions = zlights.point.positions,
  12308. pointDistances = zlights.point.distances,
  12309. spotColors = zlights.spot.colors,
  12310. spotPositions = zlights.spot.positions,
  12311. spotDistances = zlights.spot.distances,
  12312. spotDirections = zlights.spot.directions,
  12313. spotAnglesCos = zlights.spot.anglesCos,
  12314. spotExponents = zlights.spot.exponents,
  12315. hemiSkyColors = zlights.hemi.skyColors,
  12316. hemiGroundColors = zlights.hemi.groundColors,
  12317. hemiPositions = zlights.hemi.positions,
  12318. dirLength = 0,
  12319. pointLength = 0,
  12320. spotLength = 0,
  12321. hemiLength = 0,
  12322. dirCount = 0,
  12323. pointCount = 0,
  12324. spotCount = 0,
  12325. hemiCount = 0,
  12326. dirOffset = 0,
  12327. pointOffset = 0,
  12328. spotOffset = 0,
  12329. hemiOffset = 0;
  12330. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12331. light = lights[ l ];
  12332. if ( light.onlyShadow ) continue;
  12333. color = light.color;
  12334. intensity = light.intensity;
  12335. distance = light.distance;
  12336. if ( light instanceof THREE.AmbientLight ) {
  12337. if ( ! light.visible ) continue;
  12338. if ( _this.gammaInput ) {
  12339. r += color.r * color.r;
  12340. g += color.g * color.g;
  12341. b += color.b * color.b;
  12342. } else {
  12343. r += color.r;
  12344. g += color.g;
  12345. b += color.b;
  12346. }
  12347. } else if ( light instanceof THREE.DirectionalLight ) {
  12348. dirCount += 1;
  12349. if ( ! light.visible ) continue;
  12350. _direction.getPositionFromMatrix( light.matrixWorld );
  12351. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  12352. _direction.sub( _vector3 );
  12353. _direction.normalize();
  12354. // skip lights with undefined direction
  12355. // these create troubles in OpenGL (making pixel black)
  12356. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  12357. dirOffset = dirLength * 3;
  12358. dirPositions[ dirOffset ] = _direction.x;
  12359. dirPositions[ dirOffset + 1 ] = _direction.y;
  12360. dirPositions[ dirOffset + 2 ] = _direction.z;
  12361. if ( _this.gammaInput ) {
  12362. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12363. } else {
  12364. setColorLinear( dirColors, dirOffset, color, intensity );
  12365. }
  12366. dirLength += 1;
  12367. } else if ( light instanceof THREE.PointLight ) {
  12368. pointCount += 1;
  12369. if ( ! light.visible ) continue;
  12370. pointOffset = pointLength * 3;
  12371. if ( _this.gammaInput ) {
  12372. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12373. } else {
  12374. setColorLinear( pointColors, pointOffset, color, intensity );
  12375. }
  12376. _vector3.getPositionFromMatrix( light.matrixWorld );
  12377. pointPositions[ pointOffset ] = _vector3.x;
  12378. pointPositions[ pointOffset + 1 ] = _vector3.y;
  12379. pointPositions[ pointOffset + 2 ] = _vector3.z;
  12380. pointDistances[ pointLength ] = distance;
  12381. pointLength += 1;
  12382. } else if ( light instanceof THREE.SpotLight ) {
  12383. spotCount += 1;
  12384. if ( ! light.visible ) continue;
  12385. spotOffset = spotLength * 3;
  12386. if ( _this.gammaInput ) {
  12387. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12388. } else {
  12389. setColorLinear( spotColors, spotOffset, color, intensity );
  12390. }
  12391. _vector3.getPositionFromMatrix( light.matrixWorld );
  12392. spotPositions[ spotOffset ] = _vector3.x;
  12393. spotPositions[ spotOffset + 1 ] = _vector3.y;
  12394. spotPositions[ spotOffset + 2 ] = _vector3.z;
  12395. spotDistances[ spotLength ] = distance;
  12396. _direction.copy( _vector3 );
  12397. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  12398. _direction.sub( _vector3 );
  12399. _direction.normalize();
  12400. spotDirections[ spotOffset ] = _direction.x;
  12401. spotDirections[ spotOffset + 1 ] = _direction.y;
  12402. spotDirections[ spotOffset + 2 ] = _direction.z;
  12403. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12404. spotExponents[ spotLength ] = light.exponent;
  12405. spotLength += 1;
  12406. } else if ( light instanceof THREE.HemisphereLight ) {
  12407. hemiCount += 1;
  12408. if ( ! light.visible ) continue;
  12409. _direction.getPositionFromMatrix( light.matrixWorld );
  12410. _direction.normalize();
  12411. // skip lights with undefined direction
  12412. // these create troubles in OpenGL (making pixel black)
  12413. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  12414. hemiOffset = hemiLength * 3;
  12415. hemiPositions[ hemiOffset ] = _direction.x;
  12416. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12417. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12418. skyColor = light.color;
  12419. groundColor = light.groundColor;
  12420. if ( _this.gammaInput ) {
  12421. intensitySq = intensity * intensity;
  12422. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12423. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12424. } else {
  12425. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12426. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12427. }
  12428. hemiLength += 1;
  12429. }
  12430. }
  12431. // null eventual remains from removed lights
  12432. // (this is to avoid if in shader)
  12433. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12434. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12435. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12436. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12437. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12438. zlights.directional.length = dirLength;
  12439. zlights.point.length = pointLength;
  12440. zlights.spot.length = spotLength;
  12441. zlights.hemi.length = hemiLength;
  12442. zlights.ambient[ 0 ] = r;
  12443. zlights.ambient[ 1 ] = g;
  12444. zlights.ambient[ 2 ] = b;
  12445. };
  12446. // Allocations
  12447. function allocateBones ( object ) {
  12448. if ( renderer.supportsBoneTextures && object && object.useVertexTexture ) {
  12449. return 1024;
  12450. } else {
  12451. // default for when object is not specified
  12452. // ( for example when prebuilding shader
  12453. // to be used with multiple objects )
  12454. //
  12455. // - leave some extra space for other uniforms
  12456. // - limit here is ANGLE's 254 max uniform vectors
  12457. // (up to 54 should be safe)
  12458. var nVertexUniforms = renderer.maxVertexUniformVectors
  12459. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12460. var maxBones = nVertexMatrices;
  12461. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12462. maxBones = Math.min( object.bones.length, maxBones );
  12463. if ( maxBones < object.bones.length ) {
  12464. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12465. }
  12466. }
  12467. return maxBones;
  12468. }
  12469. };
  12470. function allocateLights ( lights ) {
  12471. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  12472. dirLights = pointLights = spotLights = hemiLights = 0;
  12473. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12474. light = lights[ l ];
  12475. if ( light.onlyShadow ) continue;
  12476. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12477. if ( light instanceof THREE.PointLight ) pointLights ++;
  12478. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12479. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  12480. }
  12481. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  12482. };
  12483. function allocateShadows ( lights ) {
  12484. var l, ll, light, maxShadows = 0;
  12485. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12486. light = lights[ l ];
  12487. if ( ! light.castShadow ) continue;
  12488. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12489. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12490. }
  12491. return maxShadows;
  12492. };
  12493. // default plugins (order is important)
  12494. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12495. this.addPrePlugin( this.shadowMapPlugin );
  12496. this.addPostPlugin( new THREE.SpritePlugin() );
  12497. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12498. };
  12499. /*global THREE:false */
  12500. THREE.WebGLRenderer.LowLevelRenderer = function ( parameters ) {
  12501. parameters = parameters || {};
  12502. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12503. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12504. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  12505. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12506. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12507. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12508. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12509. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  12510. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  12511. _autoScaleCubemaps = true;
  12512. this.devicePixelRatio = parameters.devicePixelRatio !== undefined ? parameters.devicePixelRatio : window.devicePixelRatio !== undefined ? window.devicePixelRatio : 1;
  12513. var _currentWidth = 0, _currentHeight = 0;
  12514. var _gl;
  12515. var _glExtensionTextureFloat;
  12516. var _glExtensionStandardDerivatives;
  12517. var _glExtensionTextureFilterAnisotropic;
  12518. var _glExtensionCompressedTextureS3TC;
  12519. initGL();
  12520. setDefaultGLState();
  12521. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12522. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12523. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12524. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12525. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12526. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12527. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12528. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12529. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12530. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12531. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12532. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12533. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12534. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12535. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12536. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12537. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12538. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12539. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12540. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12541. // clamp precision to maximum available
  12542. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12543. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12544. if ( _precision === "highp" && ! highpAvailable ) {
  12545. if ( mediumpAvailable ) {
  12546. _precision = "mediump";
  12547. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12548. } else {
  12549. _precision = "lowp";
  12550. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12551. }
  12552. }
  12553. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12554. _precision = "lowp";
  12555. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12556. }
  12557. var _enabledAttributes = {},
  12558. _oldBlending,
  12559. _oldBlendEquation,
  12560. _oldBlendSrc,
  12561. _oldBlendDst,
  12562. _oldDoubleSided = -1,
  12563. _oldFlipSided = -1,
  12564. _oldDepthTest = -1,
  12565. _oldDepthWrite = -1,
  12566. _oldLineWidth = -1,
  12567. _viewportX = 0,
  12568. _viewportY = 0,
  12569. _viewportWidth = 0,
  12570. _viewportHeight = 0,
  12571. // GL state cache
  12572. _oldPolygonOffset = null,
  12573. _oldPolygonOffsetFactor = null,
  12574. _oldPolygonOffsetUnits = null,
  12575. _currentFramebuffer = null;
  12576. function initGL () {
  12577. try {
  12578. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12579. throw 'Error creating WebGL context.';
  12580. }
  12581. } catch ( error ) {
  12582. console.error( error );
  12583. }
  12584. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12585. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12586. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12587. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12588. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12589. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  12590. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  12591. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12592. if ( ! _glExtensionTextureFloat ) {
  12593. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12594. }
  12595. if ( ! _glExtensionStandardDerivatives ) {
  12596. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12597. }
  12598. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12599. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12600. }
  12601. if ( ! _glExtensionCompressedTextureS3TC ) {
  12602. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  12603. }
  12604. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12605. _gl.getShaderPrecisionFormat = function() {
  12606. return {
  12607. "rangeMin" : 1,
  12608. "rangeMax" : 1,
  12609. "precision" : 1
  12610. };
  12611. }
  12612. }
  12613. }
  12614. function setDefaultGLState () {
  12615. _gl.clearColor( 0, 0, 0, 1 );
  12616. _gl.clearDepth( 1 );
  12617. _gl.clearStencil( 0 );
  12618. _gl.enable( _gl.DEPTH_TEST );
  12619. _gl.depthFunc( _gl.LEQUAL );
  12620. _gl.frontFace( _gl.CCW );
  12621. _gl.cullFace( _gl.BACK );
  12622. _gl.enable( _gl.CULL_FACE );
  12623. _gl.enable( _gl.BLEND );
  12624. _gl.blendEquation( _gl.FUNC_ADD );
  12625. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12626. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12627. }
  12628. // Fallback filters for non-power-of-2 textures
  12629. function filterFallback ( f ) {
  12630. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12631. return _gl.NEAREST;
  12632. }
  12633. return _gl.LINEAR;
  12634. }
  12635. function getContext() {
  12636. return _gl;
  12637. }
  12638. function getDomElement(){
  12639. return _canvas;
  12640. }
  12641. function getPrecision() {
  12642. return _precision;
  12643. }
  12644. function getCurrentWidth(){
  12645. return _currentWidth;
  12646. }
  12647. function getCurrentHeight(){
  12648. return _currentHeight;
  12649. }
  12650. function supportsVertexTextures() {
  12651. return _supportsVertexTextures;
  12652. }
  12653. function supportsFloatTextures() {
  12654. return _glExtensionTextureFloat;
  12655. }
  12656. function supportsStandardDerivatives() {
  12657. return _glExtensionStandardDerivatives;
  12658. }
  12659. function supportsCompressedTextureS3TC() {
  12660. return _glExtensionCompressedTextureS3TC;
  12661. }
  12662. function getMaxAnisotropy() {
  12663. return _maxAnisotropy;
  12664. }
  12665. function setSize( width, height ) {
  12666. _canvas.width = width;
  12667. _canvas.height = height;
  12668. setViewport( 0, 0, _canvas.width, _canvas.height );
  12669. }
  12670. function setViewport( x, y, width, height ) {
  12671. _viewportX = x !== undefined ? x : 0;
  12672. _viewportY = y !== undefined ? y : 0;
  12673. _viewportWidth = width !== undefined ? width : _canvas.width;
  12674. _viewportHeight = height !== undefined ? height : _canvas.height;
  12675. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12676. }
  12677. function setScissor( x, y, width, height ) {
  12678. _gl.scissor( x, y, width, height );
  12679. }
  12680. function enableScissorTest( enable ) {
  12681. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12682. }
  12683. // Clearing
  12684. function setClearColorHex( hex, alpha ) {
  12685. _clearColor.setHex( hex );
  12686. _clearAlpha = alpha;
  12687. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12688. }
  12689. function setClearColor( color, alpha ) {
  12690. _clearColor.copy( color );
  12691. _clearAlpha = alpha;
  12692. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12693. }
  12694. function getClearColor() {
  12695. return _clearColor;
  12696. }
  12697. function getClearAlpha() {
  12698. return _clearAlpha;
  12699. }
  12700. function clear( color, depth, stencil ) {
  12701. var bits = 0;
  12702. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12703. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12704. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12705. _gl.clear( bits );
  12706. }
  12707. function clearTarget( renderTarget, color, depth, stencil ) {
  12708. setRenderTarget( renderTarget );
  12709. clear( color, depth, stencil );
  12710. }
  12711. function deleteBuffer(buffer){
  12712. _gl.deleteBuffer(buffer);
  12713. }
  12714. function deleteTexture(texture){
  12715. _gl.deleteTexture( texture );
  12716. }
  12717. function deleteFramebuffer(Framebuffer){
  12718. _gl.deleteFramebuffer(Framebuffer);
  12719. }
  12720. function deleteRenderbuffer(RenderBuffer){
  12721. _gl.deleteRenderbuffer(RenderBuffer);
  12722. }
  12723. function deleteProgram(RenderBuffer){
  12724. _gl.deleteProgram(RenderBuffer);
  12725. }
  12726. function createBuffer(){
  12727. return _gl.createBuffer();
  12728. }
  12729. function setStaticArrayBuffer(buffer,data){
  12730. bindArrayBuffer( buffer );
  12731. _gl.bufferData( _gl.ARRAY_BUFFER, data, _gl.STATIC_DRAW );
  12732. }
  12733. function setStaticIndexBuffer(buffer,data){
  12734. bindElementArrayBuffer( buffer );
  12735. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, data, _gl.STATIC_DRAW );
  12736. }
  12737. function setDynamicArrayBuffer(buffer,data){
  12738. bindArrayBuffer( buffer );
  12739. _gl.bufferData( _gl.ARRAY_BUFFER, data, _gl.DYNAMIC_DRAW );
  12740. }
  12741. function setDynamicIndexBuffer(buffer,data){
  12742. bindElementArrayBuffer( buffer );
  12743. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, data, _gl.DYNAMIC_DRAW );
  12744. }
  12745. function drawTriangles(count){
  12746. _gl.drawArrays( _gl.TRIANGLES, 0, count );
  12747. }
  12748. function drawTriangleStrip(count){
  12749. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, count );
  12750. }
  12751. function drawLines(count){
  12752. _gl.drawArrays( _gl.LINES, 0, count );
  12753. }
  12754. function drawLineStrip(count){
  12755. _gl.drawArrays( _gl.LINE_STRIP, 0, count );
  12756. }
  12757. function drawPoints(count){
  12758. _gl.drawArrays( _gl.POINTS, 0, count );
  12759. }
  12760. function drawTriangleElements(buffer,count,offset){
  12761. bindElementArrayBuffer( buffer );
  12762. _gl.drawElements( _gl.TRIANGLES, count, _gl.UNSIGNED_SHORT, offset ); // 2 bytes per Uint16
  12763. }
  12764. function drawLineElements(buffer,count,offset){
  12765. bindElementArrayBuffer( buffer );
  12766. _gl.drawElements( _gl.LINES, count, _gl.UNSIGNED_SHORT, offset ); // 2 bytes per Uint16
  12767. }
  12768. var _boundBuffer;
  12769. function bindArrayBuffer(buffer){
  12770. if (_boundBuffer != buffer){
  12771. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12772. _boundBuffer = buffer;
  12773. }
  12774. }
  12775. function bindElementArrayBuffer(buffer){
  12776. if (_boundBuffer != buffer){
  12777. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer );
  12778. _boundBuffer = buffer;
  12779. }
  12780. }
  12781. function enableAttribute( attribute ) {
  12782. if ( ! _enabledAttributes[ attribute ] ) {
  12783. _gl.enableVertexAttribArray( attribute );
  12784. _enabledAttributes[ attribute ] = true;
  12785. }
  12786. }
  12787. function disableAttributes() {
  12788. for ( var attribute in _enabledAttributes ) {
  12789. if ( _enabledAttributes[ attribute ] ) {
  12790. _gl.disableVertexAttribArray( attribute );
  12791. _enabledAttributes[ attribute ] = false;
  12792. }
  12793. }
  12794. }
  12795. function getAttribLocation( program, id ){
  12796. return _gl.getAttribLocation( program, id );
  12797. }
  12798. function setFloatAttribute(index,buffer,size,offset){
  12799. bindArrayBuffer( buffer );
  12800. enableAttribute( index );
  12801. _gl.vertexAttribPointer( index, size, _gl.FLOAT, false, 0, offset );
  12802. }
  12803. function getUniformLocation( program, id ){
  12804. return _gl.getUniformLocation( program, id );
  12805. }
  12806. function uniform1i(uniform,value){
  12807. _gl.uniform1i( uniform, value );
  12808. }
  12809. function uniform1f(uniform,value){
  12810. _gl.uniform1f( uniform, value );
  12811. }
  12812. function uniform2f(uniform,value1, value2){
  12813. _gl.uniform2f( uniform, value1, value2 );
  12814. }
  12815. function uniform3f(uniform, value1, value2, value3){
  12816. _gl.uniform3f( uniform, value1, value2, value3 );
  12817. }
  12818. function uniform4f(uniform, value1, value2, value3, value4){
  12819. _gl.uniform4f( uniform, value1, value2, value3, value4);
  12820. }
  12821. function uniform1iv(uniform,value){
  12822. _gl.uniform1iv( uniform, value );
  12823. }
  12824. function uniform2iv(uniform,value){
  12825. _gl.uniform2iv( uniform, value );
  12826. }
  12827. function uniform3iv(uniform,value){
  12828. _gl.uniform3iv( uniform, value );
  12829. }
  12830. function uniform1fv(uniform,value){
  12831. _gl.uniform1fv( uniform, value );
  12832. }
  12833. function uniform2fv(uniform,value){
  12834. _gl.uniform2fv( uniform, value );
  12835. }
  12836. function uniform3fv(uniform,value){
  12837. _gl.uniform3fv( uniform, value );
  12838. }
  12839. function uniform4fv(uniform,value){
  12840. _gl.uniform3fv( uniform, value );
  12841. }
  12842. function uniformMatrix3fv(location,value){
  12843. _gl.uniformMatrix3fv( location, false, value );
  12844. }
  12845. function uniformMatrix4fv(location,value){
  12846. _gl.uniformMatrix4fv( location, false, value );
  12847. }
  12848. function useProgram(program){
  12849. _gl.useProgram( program );
  12850. }
  12851. function setFaceCulling( cullFace, frontFaceDirection ) {
  12852. if ( cullFace === THREE.CullFaceNone ) {
  12853. _gl.disable( _gl.CULL_FACE );
  12854. } else {
  12855. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12856. _gl.frontFace( _gl.CW );
  12857. } else {
  12858. _gl.frontFace( _gl.CCW );
  12859. }
  12860. if ( cullFace === THREE.CullFaceBack ) {
  12861. _gl.cullFace( _gl.BACK );
  12862. } else if ( cullFace === THREE.CullFaceFront ) {
  12863. _gl.cullFace( _gl.FRONT );
  12864. } else {
  12865. _gl.cullFace( _gl.FRONT_AND_BACK );
  12866. }
  12867. _gl.enable( _gl.CULL_FACE );
  12868. }
  12869. }
  12870. function setMaterialFaces( material ) {
  12871. var doubleSided = material.side === THREE.DoubleSide;
  12872. var flipSided = material.side === THREE.BackSide;
  12873. if ( _oldDoubleSided !== doubleSided ) {
  12874. if ( doubleSided ) {
  12875. _gl.disable( _gl.CULL_FACE );
  12876. } else {
  12877. _gl.enable( _gl.CULL_FACE );
  12878. }
  12879. _oldDoubleSided = doubleSided;
  12880. }
  12881. if ( _oldFlipSided !== flipSided ) {
  12882. if ( flipSided ) {
  12883. _gl.frontFace( _gl.CW );
  12884. } else {
  12885. _gl.frontFace( _gl.CCW );
  12886. }
  12887. _oldFlipSided = flipSided;
  12888. }
  12889. }
  12890. function setPolygonOffset ( polygonoffset, factor, units ) {
  12891. if ( _oldPolygonOffset !== polygonoffset ) {
  12892. if ( polygonoffset ) {
  12893. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12894. } else {
  12895. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12896. }
  12897. _oldPolygonOffset = polygonoffset;
  12898. }
  12899. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12900. _gl.polygonOffset( factor, units );
  12901. _oldPolygonOffsetFactor = factor;
  12902. _oldPolygonOffsetUnits = units;
  12903. }
  12904. }
  12905. function setBlending( blending, blendEquation, blendSrc, blendDst ) {
  12906. if ( blending !== _oldBlending ) {
  12907. if ( blending === THREE.NoBlending ) {
  12908. _gl.disable( _gl.BLEND );
  12909. } else if ( blending === THREE.AdditiveBlending ) {
  12910. _gl.enable( _gl.BLEND );
  12911. _gl.blendEquation( _gl.FUNC_ADD );
  12912. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12913. } else if ( blending === THREE.SubtractiveBlending ) {
  12914. // TODO: Find blendFuncSeparate() combination
  12915. _gl.enable( _gl.BLEND );
  12916. _gl.blendEquation( _gl.FUNC_ADD );
  12917. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12918. } else if ( blending === THREE.MultiplyBlending ) {
  12919. // TODO: Find blendFuncSeparate() combination
  12920. _gl.enable( _gl.BLEND );
  12921. _gl.blendEquation( _gl.FUNC_ADD );
  12922. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12923. } else if ( blending === THREE.CustomBlending ) {
  12924. _gl.enable( _gl.BLEND );
  12925. } else {
  12926. _gl.enable( _gl.BLEND );
  12927. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12928. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12929. }
  12930. _oldBlending = blending;
  12931. }
  12932. if ( blending === THREE.CustomBlending ) {
  12933. if ( blendEquation !== _oldBlendEquation ) {
  12934. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12935. _oldBlendEquation = blendEquation;
  12936. }
  12937. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12938. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12939. _oldBlendSrc = blendSrc;
  12940. _oldBlendDst = blendDst;
  12941. }
  12942. } else {
  12943. _oldBlendEquation = null;
  12944. _oldBlendSrc = null;
  12945. _oldBlendDst = null;
  12946. }
  12947. }
  12948. function setDepthTest( depthTest ) {
  12949. if ( _oldDepthTest !== depthTest ) {
  12950. if ( depthTest ) {
  12951. _gl.enable( _gl.DEPTH_TEST );
  12952. } else {
  12953. _gl.disable( _gl.DEPTH_TEST );
  12954. }
  12955. _oldDepthTest = depthTest;
  12956. }
  12957. }
  12958. function setDepthWrite( depthWrite ) {
  12959. if ( _oldDepthWrite !== depthWrite ) {
  12960. _gl.depthMask( depthWrite );
  12961. _oldDepthWrite = depthWrite;
  12962. }
  12963. }
  12964. function setTexture( texture, slot ) {
  12965. if ( texture.needsUpdate ) {
  12966. if ( ! texture.__webglInit ) {
  12967. texture.__webglInit = true;
  12968. //texture.addEventListener( 'dispose', onTextureDispose );
  12969. texture.__webglTexture = _gl.createTexture();
  12970. //_this.info.memory.textures ++;
  12971. }
  12972. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12973. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12974. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12975. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12976. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  12977. var image = texture.image,
  12978. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12979. glFormat = paramThreeToGL( texture.format ),
  12980. glType = paramThreeToGL( texture.type );
  12981. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12982. var mipmap, mipmaps = texture.mipmaps;
  12983. if ( texture instanceof THREE.DataTexture ) {
  12984. // use manually created mipmaps if available
  12985. // if there are no manual mipmaps
  12986. // set 0 level mipmap and then use GL to generate other mipmap levels
  12987. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  12988. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  12989. mipmap = mipmaps[ i ];
  12990. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12991. }
  12992. texture.generateMipmaps = false;
  12993. } else {
  12994. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12995. }
  12996. } else if ( texture instanceof THREE.CompressedTexture ) {
  12997. // compressed textures can only use manually created mipmaps
  12998. // WebGL can't generate mipmaps for DDS textures
  12999. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13000. mipmap = mipmaps[ i ];
  13001. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13002. }
  13003. } else { // regular Texture (image, video, canvas)
  13004. // use manually created mipmaps if available
  13005. // if there are no manual mipmaps
  13006. // set 0 level mipmap and then use GL to generate other mipmap levels
  13007. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13008. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13009. mipmap = mipmaps[ i ];
  13010. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13011. }
  13012. texture.generateMipmaps = false;
  13013. } else {
  13014. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13015. }
  13016. }
  13017. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13018. texture.needsUpdate = false;
  13019. if ( texture.onUpdate ) texture.onUpdate();
  13020. } else {
  13021. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13022. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13023. }
  13024. }
  13025. function setCubeTexture ( texture, slot ) {
  13026. if ( texture.image.length === 6 ) {
  13027. if ( texture.needsUpdate ) {
  13028. if ( ! texture.image.__webglTextureCube ) {
  13029. texture.image.__webglTextureCube = _gl.createTexture();
  13030. }
  13031. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13032. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13033. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13034. var isCompressed = texture instanceof THREE.CompressedTexture;
  13035. var cubeImage = [];
  13036. for ( var i = 0; i < 6; i ++ ) {
  13037. if ( _autoScaleCubemaps && ! isCompressed ) {
  13038. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13039. } else {
  13040. cubeImage[ i ] = texture.image[ i ];
  13041. }
  13042. }
  13043. var image = cubeImage[ 0 ],
  13044. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13045. glFormat = paramThreeToGL( texture.format ),
  13046. glType = paramThreeToGL( texture.type );
  13047. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13048. for ( var i = 0; i < 6; i ++ ) {
  13049. if ( isCompressed ) {
  13050. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13051. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13052. mipmap = mipmaps[ j ];
  13053. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13054. }
  13055. } else {
  13056. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13057. }
  13058. }
  13059. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13060. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13061. }
  13062. texture.needsUpdate = false;
  13063. if ( texture.onUpdate ) texture.onUpdate();
  13064. } else {
  13065. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13066. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13067. }
  13068. }
  13069. }
  13070. // Textures
  13071. function isPowerOfTwo ( value ) {
  13072. return ( value & ( value - 1 ) ) === 0;
  13073. }
  13074. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13075. if ( isImagePowerOfTwo ) {
  13076. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13077. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13078. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13079. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13080. } else {
  13081. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13082. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13083. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13084. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13085. }
  13086. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13087. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13088. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13089. texture.__oldAnisotropy = texture.anisotropy;
  13090. }
  13091. }
  13092. }
  13093. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13094. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13095. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13096. }
  13097. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13098. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13099. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13100. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13101. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13102. /* For some reason this is not working. Defaulting to RGBA4.
  13103. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13104. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13105. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13106. */
  13107. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13108. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13109. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13110. } else {
  13111. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13112. }
  13113. }
  13114. function setRenderTarget( renderTarget ) {
  13115. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13116. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13117. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13118. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13119. //renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13120. renderTarget.__webglTexture = _gl.createTexture();
  13121. //_this.info.memory.textures ++;
  13122. // Setup texture, create render and frame buffers
  13123. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13124. glFormat = paramThreeToGL( renderTarget.format ),
  13125. glType = paramThreeToGL( renderTarget.type );
  13126. if ( isCube ) {
  13127. renderTarget.__webglFramebuffer = [];
  13128. renderTarget.__webglRenderbuffer = [];
  13129. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13130. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13131. for ( var i = 0; i < 6; i ++ ) {
  13132. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13133. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13134. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13135. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13136. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13137. }
  13138. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13139. } else {
  13140. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13141. if ( renderTarget.shareDepthFrom ) {
  13142. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13143. } else {
  13144. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13145. }
  13146. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13147. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13148. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13149. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13150. if ( renderTarget.shareDepthFrom ) {
  13151. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13152. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13153. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13154. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13155. }
  13156. } else {
  13157. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13158. }
  13159. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13160. }
  13161. // Release everything
  13162. if ( isCube ) {
  13163. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13164. } else {
  13165. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13166. }
  13167. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13168. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13169. }
  13170. var framebuffer, width, height, vx, vy;
  13171. if ( renderTarget ) {
  13172. if ( isCube ) {
  13173. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13174. } else {
  13175. framebuffer = renderTarget.__webglFramebuffer;
  13176. }
  13177. width = renderTarget.width;
  13178. height = renderTarget.height;
  13179. vx = 0;
  13180. vy = 0;
  13181. } else {
  13182. framebuffer = null;
  13183. width = _viewportWidth;
  13184. height = _viewportHeight;
  13185. vx = _viewportX;
  13186. vy = _viewportY;
  13187. }
  13188. if ( framebuffer !== _currentFramebuffer ) {
  13189. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13190. _gl.viewport( vx, vy, width, height );
  13191. _currentFramebuffer = framebuffer;
  13192. }
  13193. _currentWidth = width;
  13194. _currentHeight = height;
  13195. }
  13196. function clampToMaxSize ( image, maxSize ) {
  13197. if ( image.width <= maxSize && image.height <= maxSize ) {
  13198. return image;
  13199. }
  13200. // Warning: Scaling through the canvas will only work with images that use
  13201. // premultiplied alpha.
  13202. var maxDimension = Math.max( image.width, image.height );
  13203. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13204. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13205. var canvas = document.createElement( 'canvas' );
  13206. canvas.width = newWidth;
  13207. canvas.height = newHeight;
  13208. var ctx = canvas.getContext( "2d" );
  13209. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13210. return canvas;
  13211. }
  13212. function updateRenderTargetMipmap ( renderTarget ) {
  13213. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13214. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13215. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13216. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13217. } else {
  13218. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13219. _gl.generateMipmap( _gl.TEXTURE_2D );
  13220. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13221. }
  13222. }
  13223. function setCubeTextureDynamic ( texture, slot ) {
  13224. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13225. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13226. }
  13227. // Map three.js constants to WebGL constants
  13228. function paramThreeToGL ( p ) {
  13229. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13230. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13231. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13232. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13233. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13234. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13235. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13236. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13237. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13238. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13239. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13240. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13241. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13242. if ( p === THREE.ByteType ) return _gl.BYTE;
  13243. if ( p === THREE.ShortType ) return _gl.SHORT;
  13244. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13245. if ( p === THREE.IntType ) return _gl.INT;
  13246. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13247. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13248. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13249. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13250. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13251. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13252. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13253. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13254. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13255. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13256. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13257. if ( p === THREE.OneFactor ) return _gl.ONE;
  13258. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13259. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13260. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13261. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13262. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13263. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13264. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13265. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13266. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13267. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13268. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13269. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13270. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13271. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13272. }
  13273. return 0;
  13274. }
  13275. function compileShader(vertexShader, fragmentShader){
  13276. var program = _gl.createProgram();
  13277. var glFragmentShader = getShader( "fragment", fragmentShader );
  13278. var glVertexShader = getShader( "vertex", vertexShader );
  13279. _gl.attachShader( program, glVertexShader );
  13280. _gl.attachShader( program, glFragmentShader );
  13281. _gl.linkProgram( program );
  13282. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13283. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13284. }
  13285. // clean up
  13286. _gl.deleteShader( glFragmentShader );
  13287. _gl.deleteShader( glVertexShader );
  13288. return program;
  13289. }
  13290. function resetState(){
  13291. _oldBlending = -1;
  13292. _oldDepthTest = -1;
  13293. _oldDepthWrite = -1;
  13294. _oldDoubleSided = -1;
  13295. _oldFlipSided = -1;
  13296. }
  13297. function getShader ( type, string ) {
  13298. var shader;
  13299. if ( type === "fragment" ) {
  13300. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13301. } else if ( type === "vertex" ) {
  13302. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13303. }
  13304. _gl.shaderSource( shader, string );
  13305. _gl.compileShader( shader );
  13306. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13307. console.error( _gl.getShaderInfoLog( shader ) );
  13308. console.error( addLineNumbers( string ) );
  13309. return null;
  13310. }
  13311. return shader;
  13312. }
  13313. function addLineNumbers ( string ) {
  13314. var chunks = string.split( "\n" );
  13315. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13316. // Chrome reports shader errors on lines
  13317. // starting counting from 1
  13318. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13319. }
  13320. return chunks.join( "\n" );
  13321. }
  13322. function setLineWidth ( width ) {
  13323. if ( width !== _oldLineWidth ) {
  13324. _gl.lineWidth( width );
  13325. _oldLineWidth = width;
  13326. }
  13327. }
  13328. return {
  13329. context: _gl,
  13330. autoScaleCubemaps: _autoScaleCubemaps,
  13331. supportsBoneTextures: _supportsBoneTextures,
  13332. precision: _precision,
  13333. maxVertexUniformVectors: _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
  13334. // Methods
  13335. getContext: getContext,
  13336. getDomElement: getDomElement,
  13337. getPrecision: getPrecision,
  13338. getCurrentWidth: getCurrentWidth,
  13339. getCurrentHeight: getCurrentHeight,
  13340. supportsVertexTextures: supportsVertexTextures,
  13341. supportsFloatTextures: supportsFloatTextures,
  13342. supportsStandardDerivatives: supportsStandardDerivatives,
  13343. supportsCompressedTextureS3TC: supportsCompressedTextureS3TC,
  13344. getMaxAnisotropy: getMaxAnisotropy,
  13345. setRenderTarget: setRenderTarget,
  13346. setSize: setSize,
  13347. setViewport: setViewport,
  13348. setScissor: setScissor,
  13349. enableScissorTest: enableScissorTest,
  13350. setClearColorHex: setClearColorHex,
  13351. setClearColor: setClearColor,
  13352. getClearColor: getClearColor,
  13353. getClearAlpha: getClearAlpha,
  13354. clear: clear,
  13355. clearTarget: clearTarget,
  13356. deleteBuffer: deleteBuffer,
  13357. deleteTexture: deleteTexture,
  13358. deleteFramebuffer: deleteFramebuffer,
  13359. deleteRenderbuffer: deleteRenderbuffer,
  13360. deleteProgram: deleteProgram,
  13361. createBuffer: createBuffer,
  13362. setStaticArrayBuffer: setStaticArrayBuffer,
  13363. setStaticIndexBuffer: setStaticIndexBuffer,
  13364. setDynamicArrayBuffer: setDynamicArrayBuffer,
  13365. setDynamicIndexBuffer: setDynamicIndexBuffer,
  13366. drawTriangles: drawTriangles,
  13367. drawTriangleStrip: drawTriangleStrip,
  13368. drawLines: drawLines,
  13369. drawLineStrip: drawLineStrip,
  13370. drawPoints: drawPoints,
  13371. drawTriangleElements: drawTriangleElements,
  13372. drawLineElements: drawLineElements,
  13373. bindArrayBuffer: bindArrayBuffer,
  13374. bindElementArrayBuffer: bindElementArrayBuffer,
  13375. enableAttribute: enableAttribute,
  13376. disableAttributes: disableAttributes,
  13377. getAttribLocation: getAttribLocation,
  13378. setFloatAttribute: setFloatAttribute,
  13379. getUniformLocation: getUniformLocation,
  13380. uniform1i: uniform1i,
  13381. uniform1f: uniform1f,
  13382. uniform2f: uniform2f,
  13383. uniform3f: uniform3f,
  13384. uniform4f: uniform4f,
  13385. uniform1iv: uniform1iv,
  13386. uniform2iv: uniform2iv,
  13387. uniform3iv: uniform3iv,
  13388. uniform1fv: uniform1fv,
  13389. uniform2fv: uniform2fv,
  13390. uniform3fv: uniform3fv,
  13391. uniform4fv: uniform4fv,
  13392. uniformMatrix3fv: uniformMatrix3fv,
  13393. uniformMatrix4fv: uniformMatrix4fv,
  13394. useProgram: useProgram,
  13395. compileShader: compileShader,
  13396. setFaceCulling: setFaceCulling,
  13397. setMaterialFaces: setMaterialFaces,
  13398. setPolygonOffset: setPolygonOffset,
  13399. setBlending: setBlending,
  13400. setDepthTest: setDepthTest,
  13401. setDepthWrite: setDepthWrite,
  13402. setTexture: setTexture,
  13403. setCubeTexture: setCubeTexture,
  13404. updateRenderTargetMipmap: updateRenderTargetMipmap,
  13405. setCubeTextureDynamic: setCubeTextureDynamic,
  13406. paramThreeToGL: paramThreeToGL,
  13407. setLineWidth: setLineWidth,
  13408. resetState: resetState
  13409. }
  13410. };
  13411. THREE.WebGLRenderer.ShaderBuilder = function ( renderer, info ) {
  13412. this.renderer = renderer;
  13413. this.info = info;
  13414. this.programs = [],
  13415. this.programs_counter = 0;
  13416. };
  13417. THREE.extend( THREE.WebGLRenderer.ShaderBuilder.prototype, {
  13418. buildProgram: function ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13419. var renderer = this.renderer;
  13420. var p, pl, d, program, code;
  13421. var chunks = [];
  13422. // Generate code
  13423. if ( shaderID ) {
  13424. chunks.push( shaderID );
  13425. } else {
  13426. chunks.push( fragmentShader );
  13427. chunks.push( vertexShader );
  13428. }
  13429. for ( d in defines ) {
  13430. chunks.push( d );
  13431. chunks.push( defines[ d ] );
  13432. }
  13433. for ( p in parameters ) {
  13434. chunks.push( p );
  13435. chunks.push( parameters[ p ] );
  13436. }
  13437. code = chunks.join();
  13438. // Check if code has been already compiled
  13439. for ( p = 0, pl = this.programs.length; p < pl; p ++ ) {
  13440. var programInfo = this.programs[ p ];
  13441. if ( programInfo.code === code ) {
  13442. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13443. programInfo.usedTimes ++;
  13444. return programInfo.program;
  13445. }
  13446. }
  13447. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13448. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13449. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13450. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13451. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13452. }
  13453. //console.log( "building new program " );
  13454. //
  13455. var customDefines = this.generateDefines( defines );
  13456. //
  13457. var prefix_vertex = [
  13458. "precision " + renderer.precision + " float;",
  13459. customDefines,
  13460. renderer.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13461. parameters.gammaInput ? "#define GAMMA_INPUT" : "",
  13462. parameters.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13463. parameters.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13464. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13465. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13466. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13467. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13468. "#define MAX_SHADOWS " + parameters.maxShadows,
  13469. "#define MAX_BONES " + parameters.maxBones,
  13470. parameters.map ? "#define USE_MAP" : "",
  13471. parameters.envMap ? "#define USE_ENVMAP" : "",
  13472. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13473. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13474. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13475. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13476. parameters.vertexColors ? "#define USE_COLOR" : "",
  13477. parameters.skinning ? "#define USE_SKINNING" : "",
  13478. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13479. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13480. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13481. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13482. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13483. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13484. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13485. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13486. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13487. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13488. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13489. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13490. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13491. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13492. "uniform mat4 modelMatrix;",
  13493. "uniform mat4 modelViewMatrix;",
  13494. "uniform mat4 projectionMatrix;",
  13495. "uniform mat4 viewMatrix;",
  13496. "uniform mat3 normalMatrix;",
  13497. "uniform vec3 cameraPosition;",
  13498. "attribute vec3 position;",
  13499. "attribute vec3 normal;",
  13500. "attribute vec2 uv;",
  13501. "attribute vec2 uv2;",
  13502. "#ifdef USE_COLOR",
  13503. "attribute vec3 color;",
  13504. "#endif",
  13505. "#ifdef USE_MORPHTARGETS",
  13506. "attribute vec3 morphTarget0;",
  13507. "attribute vec3 morphTarget1;",
  13508. "attribute vec3 morphTarget2;",
  13509. "attribute vec3 morphTarget3;",
  13510. "#ifdef USE_MORPHNORMALS",
  13511. "attribute vec3 morphNormal0;",
  13512. "attribute vec3 morphNormal1;",
  13513. "attribute vec3 morphNormal2;",
  13514. "attribute vec3 morphNormal3;",
  13515. "#else",
  13516. "attribute vec3 morphTarget4;",
  13517. "attribute vec3 morphTarget5;",
  13518. "attribute vec3 morphTarget6;",
  13519. "attribute vec3 morphTarget7;",
  13520. "#endif",
  13521. "#endif",
  13522. "#ifdef USE_SKINNING",
  13523. "attribute vec4 skinIndex;",
  13524. "attribute vec4 skinWeight;",
  13525. "#endif",
  13526. ""
  13527. ].join("\n");
  13528. var prefix_fragment = [
  13529. "precision " + renderer.precision + " float;",
  13530. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13531. customDefines,
  13532. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13533. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13534. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13535. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13536. "#define MAX_SHADOWS " + parameters.maxShadows,
  13537. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13538. parameters.gammaInput ? "#define GAMMA_INPUT" : "",
  13539. parameters.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13540. parameters.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13541. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13542. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13543. parameters.map ? "#define USE_MAP" : "",
  13544. parameters.envMap ? "#define USE_ENVMAP" : "",
  13545. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13546. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13547. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13548. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13549. parameters.vertexColors ? "#define USE_COLOR" : "",
  13550. parameters.metal ? "#define METAL" : "",
  13551. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13552. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13553. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13554. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13555. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13556. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13557. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13558. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13559. "uniform mat4 viewMatrix;",
  13560. "uniform vec3 cameraPosition;",
  13561. ""
  13562. ].join("\n");
  13563. program = renderer.compileShader(prefix_vertex + vertexShader, prefix_fragment + fragmentShader);
  13564. //console.log( prefix_fragment + fragmentShader );
  13565. //console.log( prefix_vertex + vertexShader );
  13566. program.uniforms = {};
  13567. program.attributes = {};
  13568. var identifiers, u, a, i;
  13569. // cache uniform locations
  13570. identifiers = [
  13571. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13572. 'morphTargetInfluences'
  13573. ];
  13574. if ( parameters.useVertexTexture ) {
  13575. identifiers.push( 'boneTexture' );
  13576. } else {
  13577. identifiers.push( 'boneGlobalMatrices' );
  13578. }
  13579. for ( u in uniforms ) {
  13580. identifiers.push( u );
  13581. }
  13582. this.cacheUniformLocations( program, identifiers );
  13583. // cache attributes locations
  13584. identifiers = [
  13585. "position", "normal", "uv", "uv2", "tangent", "color",
  13586. "skinIndex", "skinWeight", "lineDistance"
  13587. ];
  13588. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13589. identifiers.push( "morphTarget" + i );
  13590. }
  13591. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13592. identifiers.push( "morphNormal" + i );
  13593. }
  13594. for ( a in attributes ) {
  13595. identifiers.push( a );
  13596. }
  13597. this.cacheAttributeLocations( program, identifiers );
  13598. program.id = this.programs_counter ++;
  13599. this.programs.push( { program: program, code: code, usedTimes: 1 } );
  13600. this.info.memory.programs = this.programs.length;
  13601. return program;
  13602. },
  13603. generateDefines: function ( defines ) {
  13604. var value, chunk, chunks = [];
  13605. for ( var d in defines ) {
  13606. value = defines[ d ];
  13607. if ( value === false ) continue;
  13608. chunk = "#define " + d + " " + value;
  13609. chunks.push( chunk );
  13610. }
  13611. return chunks.join( "\n" );
  13612. },
  13613. // Shader parameters cache
  13614. cacheUniformLocations: function ( program, identifiers ) {
  13615. var i, l, id, renderer = this.renderer;
  13616. for ( i = 0, l = identifiers.length; i < l; i ++ ) {
  13617. id = identifiers[ i ];
  13618. program.uniforms[ id ] = renderer.getUniformLocation( program, id );
  13619. }
  13620. },
  13621. cacheAttributeLocations: function ( program, identifiers ) {
  13622. var i, l, id, renderer = this.renderer;
  13623. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13624. id = identifiers[ i ];
  13625. program.attributes[ id ] = renderer.getAttribLocation( program, id );
  13626. }
  13627. },
  13628. removeProgram: function ( program ) {
  13629. var i, il, programInfo;
  13630. var deleteProgram = false;
  13631. var programs = this.programs;
  13632. for ( i = 0, il = programs.length; i < il; i ++ ) {
  13633. programInfo = programs[ i ];
  13634. if ( programInfo.program === program ) {
  13635. programInfo.usedTimes --;
  13636. if ( programInfo.usedTimes === 0 ) {
  13637. deleteProgram = true;
  13638. }
  13639. break;
  13640. }
  13641. }
  13642. if ( deleteProgram === true ) {
  13643. // avoid using array.splice, this is costlier than creating new array from scratch
  13644. var newPrograms = [];
  13645. for ( i = 0, il = programs.length; i < il; i ++ ) {
  13646. programInfo = programs[ i ];
  13647. if ( programInfo.program !== program ) {
  13648. newPrograms.push( programInfo );
  13649. }
  13650. }
  13651. this.programs = newPrograms;
  13652. this.renderer.deleteProgram( program );
  13653. this.info.memory.programs --;
  13654. }
  13655. }
  13656. } );
  13657. THREE.WebGLRenderer.Object3DRenderer = function ( lowlevelrenderer, info ) {
  13658. this.renderer = lowlevelrenderer;
  13659. this.info = info;
  13660. };
  13661. THREE.extend( THREE.WebGLRenderer.Object3DRenderer.prototype, {
  13662. getBufferMaterial: function ( object, geometryGroup ) {
  13663. return object.material instanceof THREE.MeshFaceMaterial
  13664. ? object.material.materials[ geometryGroup.materialIndex ]
  13665. : object.material;
  13666. },
  13667. bufferGuessUVType: function ( material ) {
  13668. // material must use some texture to require uvs
  13669. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  13670. return true;
  13671. }
  13672. return false;
  13673. },
  13674. bufferGuessNormalType: function ( material ) {
  13675. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  13676. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  13677. return false;
  13678. }
  13679. if ( this.materialNeedsSmoothNormals( material ) ) {
  13680. return THREE.SmoothShading;
  13681. } else {
  13682. return THREE.FlatShading;
  13683. }
  13684. },
  13685. materialNeedsSmoothNormals: function ( material ) {
  13686. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  13687. },
  13688. bufferGuessVertexColorType: function ( material ) {
  13689. if ( material.vertexColors ) {
  13690. return material.vertexColors;
  13691. }
  13692. return false;
  13693. },
  13694. initCustomAttributes: function ( geometry, object ) {
  13695. var nvertices = geometry.vertices.length;
  13696. var material = object.material;
  13697. if ( material.attributes ) {
  13698. if ( geometry.__webglCustomAttributesList === undefined ) {
  13699. geometry.__webglCustomAttributesList = [];
  13700. }
  13701. for ( var a in material.attributes ) {
  13702. var attribute = material.attributes[ a ];
  13703. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13704. attribute.__webglInitialized = true;
  13705. var size = 1; // "f" and "i"
  13706. if ( attribute.type === "v2" ) size = 2;
  13707. else if ( attribute.type === "v3" ) size = 3;
  13708. else if ( attribute.type === "v4" ) size = 4;
  13709. else if ( attribute.type === "c" ) size = 3;
  13710. attribute.size = size;
  13711. attribute.array = new Float32Array( nvertices * size );
  13712. attribute.buffer = this.renderer.createBuffer();
  13713. attribute.buffer.belongsToAttribute = a;
  13714. attribute.needsUpdate = true;
  13715. }
  13716. geometry.__webglCustomAttributesList.push( attribute );
  13717. }
  13718. }
  13719. },
  13720. numericalSort: function ( a, b ) {
  13721. return b[ 0 ] - a[ 0 ];
  13722. }
  13723. } );
  13724. THREE.WebGLRenderer.MeshRenderer = function ( lowlevelrenderer, info ) {
  13725. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  13726. };
  13727. THREE.WebGLRenderer.MeshRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  13728. THREE.extend( THREE.WebGLRenderer.MeshRenderer.prototype, {
  13729. createBuffers: function ( geometryGroup ) {
  13730. var renderer = this.renderer;
  13731. geometryGroup.__webglVertexBuffer = renderer.createBuffer();
  13732. geometryGroup.__webglNormalBuffer = renderer.createBuffer();
  13733. geometryGroup.__webglTangentBuffer = renderer.createBuffer();
  13734. geometryGroup.__webglColorBuffer = renderer.createBuffer();
  13735. geometryGroup.__webglUVBuffer = renderer.createBuffer();
  13736. geometryGroup.__webglUV2Buffer = renderer.createBuffer();
  13737. geometryGroup.__webglSkinIndicesBuffer = renderer.createBuffer();
  13738. geometryGroup.__webglSkinWeightsBuffer = renderer.createBuffer();
  13739. geometryGroup.__webglFaceBuffer = renderer.createBuffer();
  13740. geometryGroup.__webglLineBuffer = renderer.createBuffer();
  13741. var m, ml;
  13742. if ( geometryGroup.numMorphTargets ) {
  13743. geometryGroup.__webglMorphTargetsBuffers = [];
  13744. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13745. geometryGroup.__webglMorphTargetsBuffers.push( renderer.createBuffer() );
  13746. }
  13747. }
  13748. if ( geometryGroup.numMorphNormals ) {
  13749. geometryGroup.__webglMorphNormalsBuffers = [];
  13750. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13751. geometryGroup.__webglMorphNormalsBuffers.push( renderer.createBuffer() );
  13752. }
  13753. }
  13754. this.info.memory.geometries ++;
  13755. },
  13756. initBuffers: function ( geometryGroup, object ) {
  13757. var geometry = object.geometry,
  13758. faces3 = geometryGroup.faces3,
  13759. faces4 = geometryGroup.faces4,
  13760. nvertices = faces3.length * 3 + faces4.length * 4,
  13761. ntris = faces3.length * 1 + faces4.length * 2,
  13762. nlines = faces3.length * 3 + faces4.length * 4,
  13763. material = this.getBufferMaterial( object, geometryGroup ),
  13764. uvType = this.bufferGuessUVType( material ),
  13765. normalType = this.bufferGuessNormalType( material ),
  13766. vertexColorType = this.bufferGuessVertexColorType( material );
  13767. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  13768. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  13769. if ( normalType ) {
  13770. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  13771. }
  13772. if ( geometry.hasTangents ) {
  13773. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  13774. }
  13775. if ( vertexColorType ) {
  13776. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  13777. }
  13778. if ( uvType ) {
  13779. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  13780. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  13781. }
  13782. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  13783. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  13784. }
  13785. }
  13786. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  13787. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  13788. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  13789. }
  13790. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  13791. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  13792. var m, ml;
  13793. if ( geometryGroup.numMorphTargets ) {
  13794. geometryGroup.__morphTargetsArrays = [];
  13795. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13796. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  13797. }
  13798. }
  13799. if ( geometryGroup.numMorphNormals ) {
  13800. geometryGroup.__morphNormalsArrays = [];
  13801. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13802. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  13803. }
  13804. }
  13805. geometryGroup.__webglFaceCount = ntris * 3;
  13806. geometryGroup.__webglLineCount = nlines * 2;
  13807. // custom attributes
  13808. if ( material.attributes ) {
  13809. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  13810. geometryGroup.__webglCustomAttributesList = [];
  13811. }
  13812. for ( var a in material.attributes ) {
  13813. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  13814. // attribute buffers which are correctly indexed in the setMeshBuffers function
  13815. var originalAttribute = material.attributes[ a ];
  13816. var attribute = {};
  13817. for ( var property in originalAttribute ) {
  13818. attribute[ property ] = originalAttribute[ property ];
  13819. }
  13820. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13821. attribute.__webglInitialized = true;
  13822. var size = 1; // "f" and "i"
  13823. if( attribute.type === "v2" ) size = 2;
  13824. else if( attribute.type === "v3" ) size = 3;
  13825. else if( attribute.type === "v4" ) size = 4;
  13826. else if( attribute.type === "c" ) size = 3;
  13827. attribute.size = size;
  13828. attribute.array = new Float32Array( nvertices * size );
  13829. attribute.buffer = this.renderer.createBuffer();
  13830. attribute.buffer.belongsToAttribute = a;
  13831. originalAttribute.needsUpdate = true;
  13832. attribute.__original = originalAttribute;
  13833. }
  13834. geometryGroup.__webglCustomAttributesList.push( attribute );
  13835. }
  13836. }
  13837. geometryGroup.__inittedArrays = true;
  13838. },
  13839. setBuffers: function ( geometryGroup, object, dispose, material ) {
  13840. if ( ! geometryGroup.__inittedArrays ) {
  13841. return;
  13842. }
  13843. var renderer = this.renderer;
  13844. var normalType = this.bufferGuessNormalType( material ),
  13845. vertexColorType = this.bufferGuessVertexColorType( material ),
  13846. uvType = this.bufferGuessUVType( material ),
  13847. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13848. var f, fl, fi, face,
  13849. vertexNormals, faceNormal, normal,
  13850. vertexColors, faceColor,
  13851. vertexTangents,
  13852. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13853. c1, c2, c3, c4,
  13854. sw1, sw2, sw3, sw4,
  13855. si1, si2, si3, si4,
  13856. sa1, sa2, sa3, sa4,
  13857. sb1, sb2, sb3, sb4,
  13858. m, ml, i, il,
  13859. vn, uvi, uv2i,
  13860. vk, vkl, vka,
  13861. nka, chf, faceVertexNormals,
  13862. a,
  13863. vertexIndex = 0,
  13864. offset = 0,
  13865. offset_uv = 0,
  13866. offset_uv2 = 0,
  13867. offset_face = 0,
  13868. offset_normal = 0,
  13869. offset_tangent = 0,
  13870. offset_line = 0,
  13871. offset_color = 0,
  13872. offset_skin = 0,
  13873. offset_morphTarget = 0,
  13874. offset_custom = 0,
  13875. offset_customSrc = 0,
  13876. value,
  13877. vertexArray = geometryGroup.__vertexArray,
  13878. uvArray = geometryGroup.__uvArray,
  13879. uv2Array = geometryGroup.__uv2Array,
  13880. normalArray = geometryGroup.__normalArray,
  13881. tangentArray = geometryGroup.__tangentArray,
  13882. colorArray = geometryGroup.__colorArray,
  13883. skinIndexArray = geometryGroup.__skinIndexArray,
  13884. skinWeightArray = geometryGroup.__skinWeightArray,
  13885. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13886. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13887. customAttributes = geometryGroup.__webglCustomAttributesList,
  13888. customAttribute,
  13889. faceArray = geometryGroup.__faceArray,
  13890. lineArray = geometryGroup.__lineArray,
  13891. geometry = object.geometry, // this is shared for all chunks
  13892. dirtyVertices = geometry.verticesNeedUpdate,
  13893. dirtyElements = geometry.elementsNeedUpdate,
  13894. dirtyUvs = geometry.uvsNeedUpdate,
  13895. dirtyNormals = geometry.normalsNeedUpdate,
  13896. dirtyTangents = geometry.tangentsNeedUpdate,
  13897. dirtyColors = geometry.colorsNeedUpdate,
  13898. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13899. vertices = geometry.vertices,
  13900. chunk_faces3 = geometryGroup.faces3,
  13901. chunk_faces4 = geometryGroup.faces4,
  13902. obj_faces = geometry.faces,
  13903. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13904. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13905. obj_colors = geometry.colors,
  13906. obj_skinIndices = geometry.skinIndices,
  13907. obj_skinWeights = geometry.skinWeights,
  13908. morphTargets = geometry.morphTargets,
  13909. morphNormals = geometry.morphNormals;
  13910. if ( dirtyVertices ) {
  13911. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13912. face = obj_faces[ chunk_faces3[ f ] ];
  13913. v1 = vertices[ face.a ];
  13914. v2 = vertices[ face.b ];
  13915. v3 = vertices[ face.c ];
  13916. vertexArray[ offset ] = v1.x;
  13917. vertexArray[ offset + 1 ] = v1.y;
  13918. vertexArray[ offset + 2 ] = v1.z;
  13919. vertexArray[ offset + 3 ] = v2.x;
  13920. vertexArray[ offset + 4 ] = v2.y;
  13921. vertexArray[ offset + 5 ] = v2.z;
  13922. vertexArray[ offset + 6 ] = v3.x;
  13923. vertexArray[ offset + 7 ] = v3.y;
  13924. vertexArray[ offset + 8 ] = v3.z;
  13925. offset += 9;
  13926. }
  13927. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13928. face = obj_faces[ chunk_faces4[ f ] ];
  13929. v1 = vertices[ face.a ];
  13930. v2 = vertices[ face.b ];
  13931. v3 = vertices[ face.c ];
  13932. v4 = vertices[ face.d ];
  13933. vertexArray[ offset ] = v1.x;
  13934. vertexArray[ offset + 1 ] = v1.y;
  13935. vertexArray[ offset + 2 ] = v1.z;
  13936. vertexArray[ offset + 3 ] = v2.x;
  13937. vertexArray[ offset + 4 ] = v2.y;
  13938. vertexArray[ offset + 5 ] = v2.z;
  13939. vertexArray[ offset + 6 ] = v3.x;
  13940. vertexArray[ offset + 7 ] = v3.y;
  13941. vertexArray[ offset + 8 ] = v3.z;
  13942. vertexArray[ offset + 9 ] = v4.x;
  13943. vertexArray[ offset + 10 ] = v4.y;
  13944. vertexArray[ offset + 11 ] = v4.z;
  13945. offset += 12;
  13946. }
  13947. renderer.setDynamicArrayBuffer( geometryGroup.__webglVertexBuffer, vertexArray);
  13948. }
  13949. if ( dirtyMorphTargets ) {
  13950. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13951. offset_morphTarget = 0;
  13952. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13953. chf = chunk_faces3[ f ];
  13954. face = obj_faces[ chf ];
  13955. // morph positions
  13956. v1 = morphTargets[ vk ].vertices[ face.a ];
  13957. v2 = morphTargets[ vk ].vertices[ face.b ];
  13958. v3 = morphTargets[ vk ].vertices[ face.c ];
  13959. vka = morphTargetsArrays[ vk ];
  13960. vka[ offset_morphTarget ] = v1.x;
  13961. vka[ offset_morphTarget + 1 ] = v1.y;
  13962. vka[ offset_morphTarget + 2 ] = v1.z;
  13963. vka[ offset_morphTarget + 3 ] = v2.x;
  13964. vka[ offset_morphTarget + 4 ] = v2.y;
  13965. vka[ offset_morphTarget + 5 ] = v2.z;
  13966. vka[ offset_morphTarget + 6 ] = v3.x;
  13967. vka[ offset_morphTarget + 7 ] = v3.y;
  13968. vka[ offset_morphTarget + 8 ] = v3.z;
  13969. // morph normals
  13970. if ( material.morphNormals ) {
  13971. if ( needsSmoothNormals ) {
  13972. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13973. n1 = faceVertexNormals.a;
  13974. n2 = faceVertexNormals.b;
  13975. n3 = faceVertexNormals.c;
  13976. } else {
  13977. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13978. n2 = n1;
  13979. n3 = n1;
  13980. }
  13981. nka = morphNormalsArrays[ vk ];
  13982. nka[ offset_morphTarget ] = n1.x;
  13983. nka[ offset_morphTarget + 1 ] = n1.y;
  13984. nka[ offset_morphTarget + 2 ] = n1.z;
  13985. nka[ offset_morphTarget + 3 ] = n2.x;
  13986. nka[ offset_morphTarget + 4 ] = n2.y;
  13987. nka[ offset_morphTarget + 5 ] = n2.z;
  13988. nka[ offset_morphTarget + 6 ] = n3.x;
  13989. nka[ offset_morphTarget + 7 ] = n3.y;
  13990. nka[ offset_morphTarget + 8 ] = n3.z;
  13991. }
  13992. //
  13993. offset_morphTarget += 9;
  13994. }
  13995. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13996. chf = chunk_faces4[ f ];
  13997. face = obj_faces[ chf ];
  13998. // morph positions
  13999. v1 = morphTargets[ vk ].vertices[ face.a ];
  14000. v2 = morphTargets[ vk ].vertices[ face.b ];
  14001. v3 = morphTargets[ vk ].vertices[ face.c ];
  14002. v4 = morphTargets[ vk ].vertices[ face.d ];
  14003. vka = morphTargetsArrays[ vk ];
  14004. vka[ offset_morphTarget ] = v1.x;
  14005. vka[ offset_morphTarget + 1 ] = v1.y;
  14006. vka[ offset_morphTarget + 2 ] = v1.z;
  14007. vka[ offset_morphTarget + 3 ] = v2.x;
  14008. vka[ offset_morphTarget + 4 ] = v2.y;
  14009. vka[ offset_morphTarget + 5 ] = v2.z;
  14010. vka[ offset_morphTarget + 6 ] = v3.x;
  14011. vka[ offset_morphTarget + 7 ] = v3.y;
  14012. vka[ offset_morphTarget + 8 ] = v3.z;
  14013. vka[ offset_morphTarget + 9 ] = v4.x;
  14014. vka[ offset_morphTarget + 10 ] = v4.y;
  14015. vka[ offset_morphTarget + 11 ] = v4.z;
  14016. // morph normals
  14017. if ( material.morphNormals ) {
  14018. if ( needsSmoothNormals ) {
  14019. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  14020. n1 = faceVertexNormals.a;
  14021. n2 = faceVertexNormals.b;
  14022. n3 = faceVertexNormals.c;
  14023. n4 = faceVertexNormals.d;
  14024. } else {
  14025. n1 = morphNormals[ vk ].faceNormals[ chf ];
  14026. n2 = n1;
  14027. n3 = n1;
  14028. n4 = n1;
  14029. }
  14030. nka = morphNormalsArrays[ vk ];
  14031. nka[ offset_morphTarget ] = n1.x;
  14032. nka[ offset_morphTarget + 1 ] = n1.y;
  14033. nka[ offset_morphTarget + 2 ] = n1.z;
  14034. nka[ offset_morphTarget + 3 ] = n2.x;
  14035. nka[ offset_morphTarget + 4 ] = n2.y;
  14036. nka[ offset_morphTarget + 5 ] = n2.z;
  14037. nka[ offset_morphTarget + 6 ] = n3.x;
  14038. nka[ offset_morphTarget + 7 ] = n3.y;
  14039. nka[ offset_morphTarget + 8 ] = n3.z;
  14040. nka[ offset_morphTarget + 9 ] = n4.x;
  14041. nka[ offset_morphTarget + 10 ] = n4.y;
  14042. nka[ offset_morphTarget + 11 ] = n4.z;
  14043. }
  14044. //
  14045. offset_morphTarget += 12;
  14046. }
  14047. this.renderer.setDynamicArrayBuffer( geometryGroup.__webglMorphTargetsBuffers[ vk ], morphTargetsArrays[ vk ]);
  14048. if ( material.morphNormals ) {
  14049. this.renderer.setDynamicArrayBuffer( geometryGroup.__webglMorphNormalsBuffers[ vk ], morphNormalsArrays[ vk ]);
  14050. }
  14051. }
  14052. }
  14053. if ( obj_skinWeights.length ) {
  14054. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14055. face = obj_faces[ chunk_faces3[ f ] ];
  14056. // weights
  14057. sw1 = obj_skinWeights[ face.a ];
  14058. sw2 = obj_skinWeights[ face.b ];
  14059. sw3 = obj_skinWeights[ face.c ];
  14060. skinWeightArray[ offset_skin ] = sw1.x;
  14061. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14062. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14063. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14064. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14065. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14066. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14067. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14068. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14069. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14070. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14071. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14072. // indices
  14073. si1 = obj_skinIndices[ face.a ];
  14074. si2 = obj_skinIndices[ face.b ];
  14075. si3 = obj_skinIndices[ face.c ];
  14076. skinIndexArray[ offset_skin ] = si1.x;
  14077. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14078. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14079. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14080. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14081. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14082. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14083. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14084. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14085. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14086. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14087. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14088. offset_skin += 12;
  14089. }
  14090. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14091. face = obj_faces[ chunk_faces4[ f ] ];
  14092. // weights
  14093. sw1 = obj_skinWeights[ face.a ];
  14094. sw2 = obj_skinWeights[ face.b ];
  14095. sw3 = obj_skinWeights[ face.c ];
  14096. sw4 = obj_skinWeights[ face.d ];
  14097. skinWeightArray[ offset_skin ] = sw1.x;
  14098. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14099. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14100. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14101. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14102. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14103. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14104. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14105. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14106. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14107. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14108. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14109. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  14110. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  14111. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  14112. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  14113. // indices
  14114. si1 = obj_skinIndices[ face.a ];
  14115. si2 = obj_skinIndices[ face.b ];
  14116. si3 = obj_skinIndices[ face.c ];
  14117. si4 = obj_skinIndices[ face.d ];
  14118. skinIndexArray[ offset_skin ] = si1.x;
  14119. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14120. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14121. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14122. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14123. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14124. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14125. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14126. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14127. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14128. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14129. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14130. skinIndexArray[ offset_skin + 12 ] = si4.x;
  14131. skinIndexArray[ offset_skin + 13 ] = si4.y;
  14132. skinIndexArray[ offset_skin + 14 ] = si4.z;
  14133. skinIndexArray[ offset_skin + 15 ] = si4.w;
  14134. offset_skin += 16;
  14135. }
  14136. if ( offset_skin > 0 ) {
  14137. renderer.setDynamicArrayBuffer( geometryGroup.__webglSkinIndicesBuffer, skinIndexArray);
  14138. renderer.setDynamicArrayBuffer( geometryGroup.__webglSkinWeightsBuffer, skinWeightArray);
  14139. }
  14140. }
  14141. if ( dirtyColors && vertexColorType ) {
  14142. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14143. face = obj_faces[ chunk_faces3[ f ] ];
  14144. vertexColors = face.vertexColors;
  14145. faceColor = face.color;
  14146. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  14147. c1 = vertexColors[ 0 ];
  14148. c2 = vertexColors[ 1 ];
  14149. c3 = vertexColors[ 2 ];
  14150. } else {
  14151. c1 = faceColor;
  14152. c2 = faceColor;
  14153. c3 = faceColor;
  14154. }
  14155. colorArray[ offset_color ] = c1.r;
  14156. colorArray[ offset_color + 1 ] = c1.g;
  14157. colorArray[ offset_color + 2 ] = c1.b;
  14158. colorArray[ offset_color + 3 ] = c2.r;
  14159. colorArray[ offset_color + 4 ] = c2.g;
  14160. colorArray[ offset_color + 5 ] = c2.b;
  14161. colorArray[ offset_color + 6 ] = c3.r;
  14162. colorArray[ offset_color + 7 ] = c3.g;
  14163. colorArray[ offset_color + 8 ] = c3.b;
  14164. offset_color += 9;
  14165. }
  14166. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14167. face = obj_faces[ chunk_faces4[ f ] ];
  14168. vertexColors = face.vertexColors;
  14169. faceColor = face.color;
  14170. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  14171. c1 = vertexColors[ 0 ];
  14172. c2 = vertexColors[ 1 ];
  14173. c3 = vertexColors[ 2 ];
  14174. c4 = vertexColors[ 3 ];
  14175. } else {
  14176. c1 = faceColor;
  14177. c2 = faceColor;
  14178. c3 = faceColor;
  14179. c4 = faceColor;
  14180. }
  14181. colorArray[ offset_color ] = c1.r;
  14182. colorArray[ offset_color + 1 ] = c1.g;
  14183. colorArray[ offset_color + 2 ] = c1.b;
  14184. colorArray[ offset_color + 3 ] = c2.r;
  14185. colorArray[ offset_color + 4 ] = c2.g;
  14186. colorArray[ offset_color + 5 ] = c2.b;
  14187. colorArray[ offset_color + 6 ] = c3.r;
  14188. colorArray[ offset_color + 7 ] = c3.g;
  14189. colorArray[ offset_color + 8 ] = c3.b;
  14190. colorArray[ offset_color + 9 ] = c4.r;
  14191. colorArray[ offset_color + 10 ] = c4.g;
  14192. colorArray[ offset_color + 11 ] = c4.b;
  14193. offset_color += 12;
  14194. }
  14195. if ( offset_color > 0 ) {
  14196. renderer.setDynamicArrayBuffer( geometryGroup.__webglColorBuffer, colorArray);
  14197. }
  14198. }
  14199. if ( dirtyTangents && geometry.hasTangents ) {
  14200. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14201. face = obj_faces[ chunk_faces3[ f ] ];
  14202. vertexTangents = face.vertexTangents;
  14203. t1 = vertexTangents[ 0 ];
  14204. t2 = vertexTangents[ 1 ];
  14205. t3 = vertexTangents[ 2 ];
  14206. tangentArray[ offset_tangent ] = t1.x;
  14207. tangentArray[ offset_tangent + 1 ] = t1.y;
  14208. tangentArray[ offset_tangent + 2 ] = t1.z;
  14209. tangentArray[ offset_tangent + 3 ] = t1.w;
  14210. tangentArray[ offset_tangent + 4 ] = t2.x;
  14211. tangentArray[ offset_tangent + 5 ] = t2.y;
  14212. tangentArray[ offset_tangent + 6 ] = t2.z;
  14213. tangentArray[ offset_tangent + 7 ] = t2.w;
  14214. tangentArray[ offset_tangent + 8 ] = t3.x;
  14215. tangentArray[ offset_tangent + 9 ] = t3.y;
  14216. tangentArray[ offset_tangent + 10 ] = t3.z;
  14217. tangentArray[ offset_tangent + 11 ] = t3.w;
  14218. offset_tangent += 12;
  14219. }
  14220. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14221. face = obj_faces[ chunk_faces4[ f ] ];
  14222. vertexTangents = face.vertexTangents;
  14223. t1 = vertexTangents[ 0 ];
  14224. t2 = vertexTangents[ 1 ];
  14225. t3 = vertexTangents[ 2 ];
  14226. t4 = vertexTangents[ 3 ];
  14227. tangentArray[ offset_tangent ] = t1.x;
  14228. tangentArray[ offset_tangent + 1 ] = t1.y;
  14229. tangentArray[ offset_tangent + 2 ] = t1.z;
  14230. tangentArray[ offset_tangent + 3 ] = t1.w;
  14231. tangentArray[ offset_tangent + 4 ] = t2.x;
  14232. tangentArray[ offset_tangent + 5 ] = t2.y;
  14233. tangentArray[ offset_tangent + 6 ] = t2.z;
  14234. tangentArray[ offset_tangent + 7 ] = t2.w;
  14235. tangentArray[ offset_tangent + 8 ] = t3.x;
  14236. tangentArray[ offset_tangent + 9 ] = t3.y;
  14237. tangentArray[ offset_tangent + 10 ] = t3.z;
  14238. tangentArray[ offset_tangent + 11 ] = t3.w;
  14239. tangentArray[ offset_tangent + 12 ] = t4.x;
  14240. tangentArray[ offset_tangent + 13 ] = t4.y;
  14241. tangentArray[ offset_tangent + 14 ] = t4.z;
  14242. tangentArray[ offset_tangent + 15 ] = t4.w;
  14243. offset_tangent += 16;
  14244. }
  14245. renderer.setDynamicArrayBuffer( geometryGroup.__webglTangentBuffer, tangentArray);
  14246. }
  14247. if ( dirtyNormals && normalType ) {
  14248. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14249. face = obj_faces[ chunk_faces3[ f ] ];
  14250. vertexNormals = face.vertexNormals;
  14251. faceNormal = face.normal;
  14252. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  14253. for ( i = 0; i < 3; i ++ ) {
  14254. vn = vertexNormals[ i ];
  14255. normalArray[ offset_normal ] = vn.x;
  14256. normalArray[ offset_normal + 1 ] = vn.y;
  14257. normalArray[ offset_normal + 2 ] = vn.z;
  14258. offset_normal += 3;
  14259. }
  14260. } else {
  14261. for ( i = 0; i < 3; i ++ ) {
  14262. normalArray[ offset_normal ] = faceNormal.x;
  14263. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14264. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14265. offset_normal += 3;
  14266. }
  14267. }
  14268. }
  14269. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14270. face = obj_faces[ chunk_faces4[ f ] ];
  14271. vertexNormals = face.vertexNormals;
  14272. faceNormal = face.normal;
  14273. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  14274. for ( i = 0; i < 4; i ++ ) {
  14275. vn = vertexNormals[ i ];
  14276. normalArray[ offset_normal ] = vn.x;
  14277. normalArray[ offset_normal + 1 ] = vn.y;
  14278. normalArray[ offset_normal + 2 ] = vn.z;
  14279. offset_normal += 3;
  14280. }
  14281. } else {
  14282. for ( i = 0; i < 4; i ++ ) {
  14283. normalArray[ offset_normal ] = faceNormal.x;
  14284. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14285. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14286. offset_normal += 3;
  14287. }
  14288. }
  14289. }
  14290. renderer.setDynamicArrayBuffer( geometryGroup.__webglNormalBuffer, normalArray);
  14291. }
  14292. if ( dirtyUvs && obj_uvs && uvType ) {
  14293. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14294. fi = chunk_faces3[ f ];
  14295. uv = obj_uvs[ fi ];
  14296. if ( uv === undefined ) continue;
  14297. for ( i = 0; i < 3; i ++ ) {
  14298. uvi = uv[ i ];
  14299. uvArray[ offset_uv ] = uvi.x;
  14300. uvArray[ offset_uv + 1 ] = uvi.y;
  14301. offset_uv += 2;
  14302. }
  14303. }
  14304. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14305. fi = chunk_faces4[ f ];
  14306. uv = obj_uvs[ fi ];
  14307. if ( uv === undefined ) continue;
  14308. for ( i = 0; i < 4; i ++ ) {
  14309. uvi = uv[ i ];
  14310. uvArray[ offset_uv ] = uvi.x;
  14311. uvArray[ offset_uv + 1 ] = uvi.y;
  14312. offset_uv += 2;
  14313. }
  14314. }
  14315. if ( offset_uv > 0 ) {
  14316. renderer.setDynamicArrayBuffer( geometryGroup.__webglUVBuffer, uvArray);
  14317. }
  14318. }
  14319. if ( dirtyUvs && obj_uvs2 && uvType ) {
  14320. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14321. fi = chunk_faces3[ f ];
  14322. uv2 = obj_uvs2[ fi ];
  14323. if ( uv2 === undefined ) continue;
  14324. for ( i = 0; i < 3; i ++ ) {
  14325. uv2i = uv2[ i ];
  14326. uv2Array[ offset_uv2 ] = uv2i.x;
  14327. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14328. offset_uv2 += 2;
  14329. }
  14330. }
  14331. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14332. fi = chunk_faces4[ f ];
  14333. uv2 = obj_uvs2[ fi ];
  14334. if ( uv2 === undefined ) continue;
  14335. for ( i = 0; i < 4; i ++ ) {
  14336. uv2i = uv2[ i ];
  14337. uv2Array[ offset_uv2 ] = uv2i.x;
  14338. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14339. offset_uv2 += 2;
  14340. }
  14341. }
  14342. if ( offset_uv2 > 0 ) {
  14343. renderer.setDynamicArrayBuffer( geometryGroup.__webglUV2Buffer, uv2Array);
  14344. }
  14345. }
  14346. if ( dirtyElements ) {
  14347. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14348. faceArray[ offset_face ] = vertexIndex;
  14349. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14350. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  14351. offset_face += 3;
  14352. lineArray[ offset_line ] = vertexIndex;
  14353. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14354. lineArray[ offset_line + 2 ] = vertexIndex;
  14355. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  14356. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14357. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14358. offset_line += 6;
  14359. vertexIndex += 3;
  14360. }
  14361. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14362. faceArray[ offset_face ] = vertexIndex;
  14363. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14364. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  14365. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  14366. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  14367. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  14368. offset_face += 6;
  14369. lineArray[ offset_line ] = vertexIndex;
  14370. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14371. lineArray[ offset_line + 2 ] = vertexIndex;
  14372. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  14373. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14374. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14375. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  14376. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  14377. offset_line += 8;
  14378. vertexIndex += 4;
  14379. }
  14380. renderer.setDynamicIndexBuffer( geometryGroup.__webglFaceBuffer, faceArray);
  14381. renderer.setDynamicIndexBuffer( geometryGroup.__webglLineBuffer, lineArray);
  14382. }
  14383. if ( customAttributes ) {
  14384. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14385. customAttribute = customAttributes[ i ];
  14386. if ( ! customAttribute.__original.needsUpdate ) continue;
  14387. offset_custom = 0;
  14388. offset_customSrc = 0;
  14389. if ( customAttribute.size === 1 ) {
  14390. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14391. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14392. face = obj_faces[ chunk_faces3[ f ] ];
  14393. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14394. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14395. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14396. offset_custom += 3;
  14397. }
  14398. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14399. face = obj_faces[ chunk_faces4[ f ] ];
  14400. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14401. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14402. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14403. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  14404. offset_custom += 4;
  14405. }
  14406. } else if ( customAttribute.boundTo === "faces" ) {
  14407. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14408. value = customAttribute.value[ chunk_faces3[ f ] ];
  14409. customAttribute.array[ offset_custom ] = value;
  14410. customAttribute.array[ offset_custom + 1 ] = value;
  14411. customAttribute.array[ offset_custom + 2 ] = value;
  14412. offset_custom += 3;
  14413. }
  14414. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14415. value = customAttribute.value[ chunk_faces4[ f ] ];
  14416. customAttribute.array[ offset_custom ] = value;
  14417. customAttribute.array[ offset_custom + 1 ] = value;
  14418. customAttribute.array[ offset_custom + 2 ] = value;
  14419. customAttribute.array[ offset_custom + 3 ] = value;
  14420. offset_custom += 4;
  14421. }
  14422. }
  14423. } else if ( customAttribute.size === 2 ) {
  14424. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14425. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14426. face = obj_faces[ chunk_faces3[ f ] ];
  14427. v1 = customAttribute.value[ face.a ];
  14428. v2 = customAttribute.value[ face.b ];
  14429. v3 = customAttribute.value[ face.c ];
  14430. customAttribute.array[ offset_custom ] = v1.x;
  14431. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14432. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14433. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14434. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14435. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14436. offset_custom += 6;
  14437. }
  14438. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14439. face = obj_faces[ chunk_faces4[ f ] ];
  14440. v1 = customAttribute.value[ face.a ];
  14441. v2 = customAttribute.value[ face.b ];
  14442. v3 = customAttribute.value[ face.c ];
  14443. v4 = customAttribute.value[ face.d ];
  14444. customAttribute.array[ offset_custom ] = v1.x;
  14445. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14446. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14447. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14448. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14449. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14450. customAttribute.array[ offset_custom + 6 ] = v4.x;
  14451. customAttribute.array[ offset_custom + 7 ] = v4.y;
  14452. offset_custom += 8;
  14453. }
  14454. } else if ( customAttribute.boundTo === "faces" ) {
  14455. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14456. value = customAttribute.value[ chunk_faces3[ f ] ];
  14457. v1 = value;
  14458. v2 = value;
  14459. v3 = value;
  14460. customAttribute.array[ offset_custom ] = v1.x;
  14461. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14462. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14463. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14464. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14465. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14466. offset_custom += 6;
  14467. }
  14468. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14469. value = customAttribute.value[ chunk_faces4[ f ] ];
  14470. v1 = value;
  14471. v2 = value;
  14472. v3 = value;
  14473. v4 = value;
  14474. customAttribute.array[ offset_custom ] = v1.x;
  14475. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14476. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14477. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14478. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14479. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14480. customAttribute.array[ offset_custom + 6 ] = v4.x;
  14481. customAttribute.array[ offset_custom + 7 ] = v4.y;
  14482. offset_custom += 8;
  14483. }
  14484. }
  14485. } else if ( customAttribute.size === 3 ) {
  14486. var pp;
  14487. if ( customAttribute.type === "c" ) {
  14488. pp = [ "r", "g", "b" ];
  14489. } else {
  14490. pp = [ "x", "y", "z" ];
  14491. }
  14492. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14493. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14494. face = obj_faces[ chunk_faces3[ f ] ];
  14495. v1 = customAttribute.value[ face.a ];
  14496. v2 = customAttribute.value[ face.b ];
  14497. v3 = customAttribute.value[ face.c ];
  14498. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14499. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14500. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14501. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14502. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14503. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14504. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14505. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14506. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14507. offset_custom += 9;
  14508. }
  14509. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14510. face = obj_faces[ chunk_faces4[ f ] ];
  14511. v1 = customAttribute.value[ face.a ];
  14512. v2 = customAttribute.value[ face.b ];
  14513. v3 = customAttribute.value[ face.c ];
  14514. v4 = customAttribute.value[ face.d ];
  14515. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14516. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14517. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14518. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14519. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14520. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14521. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14522. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14523. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14524. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14525. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14526. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14527. offset_custom += 12;
  14528. }
  14529. } else if ( customAttribute.boundTo === "faces" ) {
  14530. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14531. value = customAttribute.value[ chunk_faces3[ f ] ];
  14532. v1 = value;
  14533. v2 = value;
  14534. v3 = value;
  14535. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14536. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14537. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14538. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14539. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14540. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14541. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14542. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14543. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14544. offset_custom += 9;
  14545. }
  14546. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14547. value = customAttribute.value[ chunk_faces4[ f ] ];
  14548. v1 = value;
  14549. v2 = value;
  14550. v3 = value;
  14551. v4 = value;
  14552. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14553. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14554. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14555. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14556. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14557. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14558. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14559. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14560. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14561. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14562. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14563. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14564. offset_custom += 12;
  14565. }
  14566. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14567. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14568. value = customAttribute.value[ chunk_faces3[ f ] ];
  14569. v1 = value[ 0 ];
  14570. v2 = value[ 1 ];
  14571. v3 = value[ 2 ];
  14572. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14573. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14574. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14575. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14576. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14577. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14578. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14579. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14580. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14581. offset_custom += 9;
  14582. }
  14583. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14584. value = customAttribute.value[ chunk_faces4[ f ] ];
  14585. v1 = value[ 0 ];
  14586. v2 = value[ 1 ];
  14587. v3 = value[ 2 ];
  14588. v4 = value[ 3 ];
  14589. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14590. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14591. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14592. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14593. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14594. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14595. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14596. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14597. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14598. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14599. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14600. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14601. offset_custom += 12;
  14602. }
  14603. }
  14604. } else if ( customAttribute.size === 4 ) {
  14605. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14606. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14607. face = obj_faces[ chunk_faces3[ f ] ];
  14608. v1 = customAttribute.value[ face.a ];
  14609. v2 = customAttribute.value[ face.b ];
  14610. v3 = customAttribute.value[ face.c ];
  14611. customAttribute.array[ offset_custom ] = v1.x;
  14612. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14613. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14614. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14615. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14616. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14617. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14618. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14619. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14620. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14621. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14622. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14623. offset_custom += 12;
  14624. }
  14625. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14626. face = obj_faces[ chunk_faces4[ f ] ];
  14627. v1 = customAttribute.value[ face.a ];
  14628. v2 = customAttribute.value[ face.b ];
  14629. v3 = customAttribute.value[ face.c ];
  14630. v4 = customAttribute.value[ face.d ];
  14631. customAttribute.array[ offset_custom ] = v1.x;
  14632. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14633. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14634. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14635. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14636. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14637. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14638. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14639. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14640. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14641. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14642. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14643. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14644. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14645. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14646. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14647. offset_custom += 16;
  14648. }
  14649. } else if ( customAttribute.boundTo === "faces" ) {
  14650. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14651. value = customAttribute.value[ chunk_faces3[ f ] ];
  14652. v1 = value;
  14653. v2 = value;
  14654. v3 = value;
  14655. customAttribute.array[ offset_custom ] = v1.x;
  14656. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14657. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14658. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14659. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14660. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14661. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14662. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14663. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14664. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14665. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14666. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14667. offset_custom += 12;
  14668. }
  14669. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14670. value = customAttribute.value[ chunk_faces4[ f ] ];
  14671. v1 = value;
  14672. v2 = value;
  14673. v3 = value;
  14674. v4 = value;
  14675. customAttribute.array[ offset_custom ] = v1.x;
  14676. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14677. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14678. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14679. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14680. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14681. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14682. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14683. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14684. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14685. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14686. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14687. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14688. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14689. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14690. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14691. offset_custom += 16;
  14692. }
  14693. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14694. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14695. value = customAttribute.value[ chunk_faces3[ f ] ];
  14696. v1 = value[ 0 ];
  14697. v2 = value[ 1 ];
  14698. v3 = value[ 2 ];
  14699. customAttribute.array[ offset_custom ] = v1.x;
  14700. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14701. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14702. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14703. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14704. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14705. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14706. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14707. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14708. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14709. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14710. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14711. offset_custom += 12;
  14712. }
  14713. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14714. value = customAttribute.value[ chunk_faces4[ f ] ];
  14715. v1 = value[ 0 ];
  14716. v2 = value[ 1 ];
  14717. v3 = value[ 2 ];
  14718. v4 = value[ 3 ];
  14719. customAttribute.array[ offset_custom ] = v1.x;
  14720. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14721. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14722. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14723. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14724. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14725. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14726. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14727. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14728. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14729. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14730. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14731. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14732. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14733. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14734. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14735. offset_custom += 16;
  14736. }
  14737. }
  14738. }
  14739. renderer.setDynamicArrayBuffer( customAttribute.buffer, customAttribute.array);
  14740. }
  14741. }
  14742. if ( dispose ) {
  14743. delete geometryGroup.__inittedArrays;
  14744. delete geometryGroup.__colorArray;
  14745. delete geometryGroup.__normalArray;
  14746. delete geometryGroup.__tangentArray;
  14747. delete geometryGroup.__uvArray;
  14748. delete geometryGroup.__uv2Array;
  14749. delete geometryGroup.__faceArray;
  14750. delete geometryGroup.__vertexArray;
  14751. delete geometryGroup.__lineArray;
  14752. delete geometryGroup.__skinIndexArray;
  14753. delete geometryGroup.__skinWeightArray;
  14754. }
  14755. }
  14756. } );
  14757. THREE.WebGLRenderer.ParticleRenderer = function ( lowlevelrenderer, info ) {
  14758. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  14759. };
  14760. THREE.WebGLRenderer.ParticleRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  14761. THREE.extend( THREE.WebGLRenderer.ParticleRenderer.prototype, {
  14762. createBuffers: function ( geometry ) {
  14763. var renderer = this.renderer;
  14764. geometry.__webglVertexBuffer = renderer.createBuffer();
  14765. geometry.__webglColorBuffer = renderer.createBuffer();
  14766. this.info.memory.geometries ++;
  14767. },
  14768. initBuffers: function ( geometry, object ) {
  14769. var nvertices = geometry.vertices.length;
  14770. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  14771. geometry.__colorArray = new Float32Array( nvertices * 3 );
  14772. geometry.__sortArray = [];
  14773. geometry.__webglParticleCount = nvertices;
  14774. this.initCustomAttributes ( geometry, object );
  14775. },
  14776. setBuffers: function ( geometry, object , projectionScreenMatrix ) {
  14777. var renderer = this.renderer;
  14778. var v, c, vertex, offset, index, color,
  14779. vertices = geometry.vertices,
  14780. vl = vertices.length,
  14781. colors = geometry.colors,
  14782. cl = colors.length,
  14783. vertexArray = geometry.__vertexArray,
  14784. colorArray = geometry.__colorArray,
  14785. sortArray = geometry.__sortArray,
  14786. dirtyVertices = geometry.verticesNeedUpdate,
  14787. dirtyElements = geometry.elementsNeedUpdate,
  14788. dirtyColors = geometry.colorsNeedUpdate,
  14789. customAttributes = geometry.__webglCustomAttributesList,
  14790. i, il,
  14791. a, ca, cal, value,
  14792. customAttribute;
  14793. var _projScreenMatrixPS = THREE.WebGLRenderer.ParticleRenderer._m1,
  14794. _vector3 = THREE.WebGLRenderer.ParticleRenderer._v1;
  14795. if ( object.sortParticles ) {
  14796. _projScreenMatrixPS.multiplyMatrices( projectionScreenMatrix, object.matrixWorld );
  14797. for ( v = 0; v < vl; v ++ ) {
  14798. vertex = vertices[ v ];
  14799. _vector3.copy( vertex );
  14800. _vector3.applyProjection(_projScreenMatrixPS);
  14801. sortArray[ v ] = [ _vector3.z, v ];
  14802. }
  14803. sortArray.sort( this.numericalSort );
  14804. for ( v = 0; v < vl; v ++ ) {
  14805. vertex = vertices[ sortArray[v][1] ];
  14806. offset = v * 3;
  14807. vertexArray[ offset ] = vertex.x;
  14808. vertexArray[ offset + 1 ] = vertex.y;
  14809. vertexArray[ offset + 2 ] = vertex.z;
  14810. }
  14811. for ( c = 0; c < cl; c ++ ) {
  14812. offset = c * 3;
  14813. color = colors[ sortArray[c][1] ];
  14814. colorArray[ offset ] = color.r;
  14815. colorArray[ offset + 1 ] = color.g;
  14816. colorArray[ offset + 2 ] = color.b;
  14817. }
  14818. if ( customAttributes ) {
  14819. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14820. customAttribute = customAttributes[ i ];
  14821. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  14822. offset = 0;
  14823. cal = customAttribute.value.length;
  14824. if ( customAttribute.size === 1 ) {
  14825. for ( ca = 0; ca < cal; ca ++ ) {
  14826. index = sortArray[ ca ][ 1 ];
  14827. customAttribute.array[ ca ] = customAttribute.value[ index ];
  14828. }
  14829. } else if ( customAttribute.size === 2 ) {
  14830. for ( ca = 0; ca < cal; ca ++ ) {
  14831. index = sortArray[ ca ][ 1 ];
  14832. value = customAttribute.value[ index ];
  14833. customAttribute.array[ offset ] = value.x;
  14834. customAttribute.array[ offset + 1 ] = value.y;
  14835. offset += 2;
  14836. }
  14837. } else if ( customAttribute.size === 3 ) {
  14838. if ( customAttribute.type === "c" ) {
  14839. for ( ca = 0; ca < cal; ca ++ ) {
  14840. index = sortArray[ ca ][ 1 ];
  14841. value = customAttribute.value[ index ];
  14842. customAttribute.array[ offset ] = value.r;
  14843. customAttribute.array[ offset + 1 ] = value.g;
  14844. customAttribute.array[ offset + 2 ] = value.b;
  14845. offset += 3;
  14846. }
  14847. } else {
  14848. for ( ca = 0; ca < cal; ca ++ ) {
  14849. index = sortArray[ ca ][ 1 ];
  14850. value = customAttribute.value[ index ];
  14851. customAttribute.array[ offset ] = value.x;
  14852. customAttribute.array[ offset + 1 ] = value.y;
  14853. customAttribute.array[ offset + 2 ] = value.z;
  14854. offset += 3;
  14855. }
  14856. }
  14857. } else if ( customAttribute.size === 4 ) {
  14858. for ( ca = 0; ca < cal; ca ++ ) {
  14859. index = sortArray[ ca ][ 1 ];
  14860. value = customAttribute.value[ index ];
  14861. customAttribute.array[ offset ] = value.x;
  14862. customAttribute.array[ offset + 1 ] = value.y;
  14863. customAttribute.array[ offset + 2 ] = value.z;
  14864. customAttribute.array[ offset + 3 ] = value.w;
  14865. offset += 4;
  14866. }
  14867. }
  14868. }
  14869. }
  14870. } else {
  14871. if ( dirtyVertices ) {
  14872. for ( v = 0; v < vl; v ++ ) {
  14873. vertex = vertices[ v ];
  14874. offset = v * 3;
  14875. vertexArray[ offset ] = vertex.x;
  14876. vertexArray[ offset + 1 ] = vertex.y;
  14877. vertexArray[ offset + 2 ] = vertex.z;
  14878. }
  14879. }
  14880. if ( dirtyColors ) {
  14881. for ( c = 0; c < cl; c ++ ) {
  14882. color = colors[ c ];
  14883. offset = c * 3;
  14884. colorArray[ offset ] = color.r;
  14885. colorArray[ offset + 1 ] = color.g;
  14886. colorArray[ offset + 2 ] = color.b;
  14887. }
  14888. }
  14889. if ( customAttributes ) {
  14890. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14891. customAttribute = customAttributes[ i ];
  14892. if ( customAttribute.needsUpdate &&
  14893. ( customAttribute.boundTo === undefined ||
  14894. customAttribute.boundTo === "vertices") ) {
  14895. cal = customAttribute.value.length;
  14896. offset = 0;
  14897. if ( customAttribute.size === 1 ) {
  14898. for ( ca = 0; ca < cal; ca ++ ) {
  14899. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  14900. }
  14901. } else if ( customAttribute.size === 2 ) {
  14902. for ( ca = 0; ca < cal; ca ++ ) {
  14903. value = customAttribute.value[ ca ];
  14904. customAttribute.array[ offset ] = value.x;
  14905. customAttribute.array[ offset + 1 ] = value.y;
  14906. offset += 2;
  14907. }
  14908. } else if ( customAttribute.size === 3 ) {
  14909. if ( customAttribute.type === "c" ) {
  14910. for ( ca = 0; ca < cal; ca ++ ) {
  14911. value = customAttribute.value[ ca ];
  14912. customAttribute.array[ offset ] = value.r;
  14913. customAttribute.array[ offset + 1 ] = value.g;
  14914. customAttribute.array[ offset + 2 ] = value.b;
  14915. offset += 3;
  14916. }
  14917. } else {
  14918. for ( ca = 0; ca < cal; ca ++ ) {
  14919. value = customAttribute.value[ ca ];
  14920. customAttribute.array[ offset ] = value.x;
  14921. customAttribute.array[ offset + 1 ] = value.y;
  14922. customAttribute.array[ offset + 2 ] = value.z;
  14923. offset += 3;
  14924. }
  14925. }
  14926. } else if ( customAttribute.size === 4 ) {
  14927. for ( ca = 0; ca < cal; ca ++ ) {
  14928. value = customAttribute.value[ ca ];
  14929. customAttribute.array[ offset ] = value.x;
  14930. customAttribute.array[ offset + 1 ] = value.y;
  14931. customAttribute.array[ offset + 2 ] = value.z;
  14932. customAttribute.array[ offset + 3 ] = value.w;
  14933. offset += 4;
  14934. }
  14935. }
  14936. }
  14937. }
  14938. }
  14939. }
  14940. if ( dirtyVertices || object.sortParticles ) {
  14941. renderer.setDynamicArrayBuffer(geometry.__webglVertexBuffer,vertexArray);
  14942. }
  14943. if ( dirtyColors || object.sortParticles ) {
  14944. renderer.setDynamicArrayBuffer(geometry.__webglColorBuffer,colorArray);
  14945. }
  14946. if ( customAttributes ) {
  14947. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14948. customAttribute = customAttributes[ i ];
  14949. if ( customAttribute.needsUpdate || object.sortParticles ) {
  14950. renderer.setDynamicArrayBuffer(customAttribute.buffer,customAttribute.array);
  14951. }
  14952. }
  14953. }
  14954. }
  14955. } );
  14956. THREE.WebGLRenderer.ParticleRenderer._m1 = new THREE.Matrix4();
  14957. THREE.WebGLRenderer.ParticleRenderer._v1 = new THREE.Vector3();
  14958. THREE.WebGLRenderer.LineRenderer = function ( lowlevelrenderer, info ) {
  14959. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  14960. };
  14961. THREE.WebGLRenderer.LineRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  14962. THREE.extend( THREE.WebGLRenderer.LineRenderer.prototype, {
  14963. createBuffers: function ( geometry ) {
  14964. var renderer = this.renderer;
  14965. geometry.__webglVertexBuffer = renderer.createBuffer();
  14966. geometry.__webglColorBuffer = renderer.createBuffer();
  14967. geometry.__webglLineDistanceBuffer = renderer.createBuffer();
  14968. this.info.memory.geometries ++;
  14969. },
  14970. initBuffers: function ( geometry, object ) {
  14971. var nvertices = geometry.vertices.length;
  14972. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  14973. geometry.__colorArray = new Float32Array( nvertices * 3 );
  14974. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  14975. geometry.__webglLineCount = nvertices;
  14976. this.initCustomAttributes ( geometry, object );
  14977. },
  14978. setBuffers: function ( geometry, object ) {
  14979. var renderer = this.renderer;
  14980. var v, c, d, vertex, offset, color,
  14981. vertices = geometry.vertices,
  14982. colors = geometry.colors,
  14983. lineDistances = geometry.lineDistances,
  14984. vl = vertices.length,
  14985. cl = colors.length,
  14986. dl = lineDistances.length,
  14987. vertexArray = geometry.__vertexArray,
  14988. colorArray = geometry.__colorArray,
  14989. lineDistanceArray = geometry.__lineDistanceArray,
  14990. dirtyVertices = geometry.verticesNeedUpdate,
  14991. dirtyColors = geometry.colorsNeedUpdate,
  14992. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  14993. customAttributes = geometry.__webglCustomAttributesList,
  14994. i, il,
  14995. a, ca, cal, value,
  14996. customAttribute;
  14997. if ( dirtyVertices ) {
  14998. for ( v = 0; v < vl; v ++ ) {
  14999. vertex = vertices[ v ];
  15000. offset = v * 3;
  15001. vertexArray[ offset ] = vertex.x;
  15002. vertexArray[ offset + 1 ] = vertex.y;
  15003. vertexArray[ offset + 2 ] = vertex.z;
  15004. }
  15005. renderer.setDynamicArrayBuffer(geometry.__webglVertexBuffer,vertexArray);
  15006. }
  15007. if ( dirtyColors ) {
  15008. for ( c = 0; c < cl; c ++ ) {
  15009. color = colors[ c ];
  15010. offset = c * 3;
  15011. colorArray[ offset ] = color.r;
  15012. colorArray[ offset + 1 ] = color.g;
  15013. colorArray[ offset + 2 ] = color.b;
  15014. }
  15015. renderer.setDynamicArrayBuffer(geometry.__webglColorBuffer,colorArray);
  15016. }
  15017. if ( dirtyLineDistances ) {
  15018. for ( d = 0; d < dl; d ++ ) {
  15019. lineDistanceArray[ d ] = lineDistances[ d ];
  15020. }
  15021. renderer.setDynamicArrayBuffer( geometry.__webglLineDistanceBuffer,lineDistanceArray);
  15022. }
  15023. if ( customAttributes ) {
  15024. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  15025. customAttribute = customAttributes[ i ];
  15026. if ( customAttribute.needsUpdate &&
  15027. ( customAttribute.boundTo === undefined ||
  15028. customAttribute.boundTo === "vertices" ) ) {
  15029. offset = 0;
  15030. cal = customAttribute.value.length;
  15031. if ( customAttribute.size === 1 ) {
  15032. for ( ca = 0; ca < cal; ca ++ ) {
  15033. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  15034. }
  15035. } else if ( customAttribute.size === 2 ) {
  15036. for ( ca = 0; ca < cal; ca ++ ) {
  15037. value = customAttribute.value[ ca ];
  15038. customAttribute.array[ offset ] = value.x;
  15039. customAttribute.array[ offset + 1 ] = value.y;
  15040. offset += 2;
  15041. }
  15042. } else if ( customAttribute.size === 3 ) {
  15043. if ( customAttribute.type === "c" ) {
  15044. for ( ca = 0; ca < cal; ca ++ ) {
  15045. value = customAttribute.value[ ca ];
  15046. customAttribute.array[ offset ] = value.r;
  15047. customAttribute.array[ offset + 1 ] = value.g;
  15048. customAttribute.array[ offset + 2 ] = value.b;
  15049. offset += 3;
  15050. }
  15051. } else {
  15052. for ( ca = 0; ca < cal; ca ++ ) {
  15053. value = customAttribute.value[ ca ];
  15054. customAttribute.array[ offset ] = value.x;
  15055. customAttribute.array[ offset + 1 ] = value.y;
  15056. customAttribute.array[ offset + 2 ] = value.z;
  15057. offset += 3;
  15058. }
  15059. }
  15060. } else if ( customAttribute.size === 4 ) {
  15061. for ( ca = 0; ca < cal; ca ++ ) {
  15062. value = customAttribute.value[ ca ];
  15063. customAttribute.array[ offset ] = value.x;
  15064. customAttribute.array[ offset + 1 ] = value.y;
  15065. customAttribute.array[ offset + 2 ] = value.z;
  15066. customAttribute.array[ offset + 3 ] = value.w;
  15067. offset += 4;
  15068. }
  15069. }
  15070. renderer.setDynamicArrayBuffer( customAttribute.buffer,customAttribute.array);
  15071. }
  15072. }
  15073. }
  15074. }
  15075. } );
  15076. THREE.WebGLRenderer.RibbonRenderer = function ( lowlevelrenderer, info ) {
  15077. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  15078. };
  15079. THREE.WebGLRenderer.RibbonRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  15080. THREE.extend( THREE.WebGLRenderer.RibbonRenderer.prototype, {
  15081. createBuffers: function ( geometry ) {
  15082. var renderer = this.renderer;
  15083. geometry.__webglVertexBuffer = renderer.createBuffer();
  15084. geometry.__webglColorBuffer = renderer.createBuffer();
  15085. geometry.__webglNormalBuffer = renderer.createBuffer();
  15086. this.info.memory.geometries ++;
  15087. },
  15088. initBuffers: function ( geometry, object ) {
  15089. var nvertices = geometry.vertices.length;
  15090. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  15091. geometry.__colorArray = new Float32Array( nvertices * 3 );
  15092. geometry.__normalArray = new Float32Array( nvertices * 3 );
  15093. geometry.__webglVertexCount = nvertices;
  15094. this.initCustomAttributes ( geometry, object );
  15095. },
  15096. setBuffers: function ( geometry, object , projectionScreenMatrix ) {
  15097. var renderer = this.renderer;
  15098. var v, c, n, vertex, offset, color, normal,
  15099. i, il, ca, cal, customAttribute, value,
  15100. vertices = geometry.vertices,
  15101. colors = geometry.colors,
  15102. normals = geometry.normals,
  15103. vl = vertices.length,
  15104. cl = colors.length,
  15105. nl = normals.length,
  15106. vertexArray = geometry.__vertexArray,
  15107. colorArray = geometry.__colorArray,
  15108. normalArray = geometry.__normalArray,
  15109. dirtyVertices = geometry.verticesNeedUpdate,
  15110. dirtyColors = geometry.colorsNeedUpdate,
  15111. dirtyNormals = geometry.normalsNeedUpdate,
  15112. customAttributes = geometry.__webglCustomAttributesList;
  15113. if ( dirtyVertices ) {
  15114. for ( v = 0; v < vl; v ++ ) {
  15115. vertex = vertices[ v ];
  15116. offset = v * 3;
  15117. vertexArray[ offset ] = vertex.x;
  15118. vertexArray[ offset + 1 ] = vertex.y;
  15119. vertexArray[ offset + 2 ] = vertex.z;
  15120. }
  15121. renderer.setDynamicArrayBuffer( geometry.__webglVertexBuffer,vertexArray);
  15122. }
  15123. if ( dirtyColors ) {
  15124. for ( c = 0; c < cl; c ++ ) {
  15125. color = colors[ c ];
  15126. offset = c * 3;
  15127. colorArray[ offset ] = color.r;
  15128. colorArray[ offset + 1 ] = color.g;
  15129. colorArray[ offset + 2 ] = color.b;
  15130. }
  15131. renderer.setDynamicArrayBuffer( geometry.__webglColorBuffer, colorArray);
  15132. }
  15133. if ( dirtyNormals ) {
  15134. for ( n = 0; n < nl; n ++ ) {
  15135. normal = normals[ n ];
  15136. offset = n * 3;
  15137. normalArray[ offset ] = normal.x;
  15138. normalArray[ offset + 1 ] = normal.y;
  15139. normalArray[ offset + 2 ] = normal.z;
  15140. }
  15141. renderer.setDynamicArrayBuffer( geometry.__webglNormalBuffer, normalArray);
  15142. }
  15143. if ( customAttributes ) {
  15144. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  15145. customAttribute = customAttributes[ i ];
  15146. if ( customAttribute.needsUpdate &&
  15147. ( customAttribute.boundTo === undefined ||
  15148. customAttribute.boundTo === "vertices" ) ) {
  15149. offset = 0;
  15150. cal = customAttribute.value.length;
  15151. if ( customAttribute.size === 1 ) {
  15152. for ( ca = 0; ca < cal; ca ++ ) {
  15153. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  15154. }
  15155. } else if ( customAttribute.size === 2 ) {
  15156. for ( ca = 0; ca < cal; ca ++ ) {
  15157. value = customAttribute.value[ ca ];
  15158. customAttribute.array[ offset ] = value.x;
  15159. customAttribute.array[ offset + 1 ] = value.y;
  15160. offset += 2;
  15161. }
  15162. } else if ( customAttribute.size === 3 ) {
  15163. if ( customAttribute.type === "c" ) {
  15164. for ( ca = 0; ca < cal; ca ++ ) {
  15165. value = customAttribute.value[ ca ];
  15166. customAttribute.array[ offset ] = value.r;
  15167. customAttribute.array[ offset + 1 ] = value.g;
  15168. customAttribute.array[ offset + 2 ] = value.b;
  15169. offset += 3;
  15170. }
  15171. } else {
  15172. for ( ca = 0; ca < cal; ca ++ ) {
  15173. value = customAttribute.value[ ca ];
  15174. customAttribute.array[ offset ] = value.x;
  15175. customAttribute.array[ offset + 1 ] = value.y;
  15176. customAttribute.array[ offset + 2 ] = value.z;
  15177. offset += 3;
  15178. }
  15179. }
  15180. } else if ( customAttribute.size === 4 ) {
  15181. for ( ca = 0; ca < cal; ca ++ ) {
  15182. value = customAttribute.value[ ca ];
  15183. customAttribute.array[ offset ] = value.x;
  15184. customAttribute.array[ offset + 1 ] = value.y;
  15185. customAttribute.array[ offset + 2 ] = value.z;
  15186. customAttribute.array[ offset + 3 ] = value.w;
  15187. offset += 4;
  15188. }
  15189. }
  15190. renderer.setDynamicArrayBuffer( customAttribute.buffer, customAttribute.array);
  15191. }
  15192. }
  15193. }
  15194. }
  15195. } );
  15196. /**
  15197. * @author szimek / https://github.com/szimek/
  15198. * @author alteredq / http://alteredqualia.com/
  15199. */
  15200. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15201. THREE.EventDispatcher.call( this );
  15202. this.width = width;
  15203. this.height = height;
  15204. options = options || {};
  15205. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15206. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15207. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15208. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15209. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15210. this.offset = new THREE.Vector2( 0, 0 );
  15211. this.repeat = new THREE.Vector2( 1, 1 );
  15212. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15213. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15214. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15215. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15216. this.generateMipmaps = true;
  15217. this.shareDepthFrom = null;
  15218. };
  15219. THREE.WebGLRenderTarget.prototype.clone = function() {
  15220. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15221. tmp.wrapS = this.wrapS;
  15222. tmp.wrapT = this.wrapT;
  15223. tmp.magFilter = this.magFilter;
  15224. tmp.minFilter = this.minFilter;
  15225. tmp.anisotropy = this.anisotropy;
  15226. tmp.offset.copy( this.offset );
  15227. tmp.repeat.copy( this.repeat );
  15228. tmp.format = this.format;
  15229. tmp.type = this.type;
  15230. tmp.depthBuffer = this.depthBuffer;
  15231. tmp.stencilBuffer = this.stencilBuffer;
  15232. tmp.generateMipmaps = this.generateMipmaps;
  15233. tmp.shareDepthFrom = this.shareDepthFrom;
  15234. return tmp;
  15235. };
  15236. THREE.WebGLRenderTarget.prototype.dispose = function () {
  15237. this.dispatchEvent( { type: 'dispose' } );
  15238. };
  15239. /**
  15240. * @author alteredq / http://alteredqualia.com
  15241. */
  15242. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15243. THREE.WebGLRenderTarget.call( this, width, height, options );
  15244. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15245. };
  15246. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15247. /**
  15248. * @author mrdoob / http://mrdoob.com/
  15249. */
  15250. THREE.RenderableVertex = function () {
  15251. this.positionWorld = new THREE.Vector3();
  15252. this.positionScreen = new THREE.Vector4();
  15253. this.visible = true;
  15254. };
  15255. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15256. this.positionWorld.copy( vertex.positionWorld );
  15257. this.positionScreen.copy( vertex.positionScreen );
  15258. };
  15259. /**
  15260. * @author mrdoob / http://mrdoob.com/
  15261. */
  15262. THREE.RenderableFace3 = function () {
  15263. this.v1 = new THREE.RenderableVertex();
  15264. this.v2 = new THREE.RenderableVertex();
  15265. this.v3 = new THREE.RenderableVertex();
  15266. this.centroidModel = new THREE.Vector3();
  15267. this.normalModel = new THREE.Vector3();
  15268. this.normalModelView = new THREE.Vector3();
  15269. this.vertexNormalsLength = 0;
  15270. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15271. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15272. this.color = null;
  15273. this.material = null;
  15274. this.uvs = [[]];
  15275. this.z = null;
  15276. };
  15277. /**
  15278. * @author mrdoob / http://mrdoob.com/
  15279. */
  15280. THREE.RenderableFace4 = function () {
  15281. this.v1 = new THREE.RenderableVertex();
  15282. this.v2 = new THREE.RenderableVertex();
  15283. this.v3 = new THREE.RenderableVertex();
  15284. this.v4 = new THREE.RenderableVertex();
  15285. this.centroidModel = new THREE.Vector3();
  15286. this.normalModel = new THREE.Vector3();
  15287. this.normalModelView = new THREE.Vector3();
  15288. this.vertexNormalsLength = 0;
  15289. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15290. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15291. this.color = null;
  15292. this.material = null;
  15293. this.uvs = [[]];
  15294. this.z = null;
  15295. };
  15296. /**
  15297. * @author mrdoob / http://mrdoob.com/
  15298. */
  15299. THREE.RenderableObject = function () {
  15300. this.object = null;
  15301. this.z = null;
  15302. };
  15303. /**
  15304. * @author mrdoob / http://mrdoob.com/
  15305. */
  15306. THREE.RenderableParticle = function () {
  15307. this.object = null;
  15308. this.x = null;
  15309. this.y = null;
  15310. this.z = null;
  15311. this.rotation = null;
  15312. this.scale = new THREE.Vector2();
  15313. this.material = null;
  15314. };
  15315. /**
  15316. * @author mrdoob / http://mrdoob.com/
  15317. */
  15318. THREE.RenderableLine = function () {
  15319. this.z = null;
  15320. this.v1 = new THREE.RenderableVertex();
  15321. this.v2 = new THREE.RenderableVertex();
  15322. this.material = null;
  15323. };
  15324. /**
  15325. * @author mrdoob / http://mrdoob.com/
  15326. * @author alteredq / http://alteredqualia.com/
  15327. */
  15328. THREE.GeometryUtils = {
  15329. // Merge two geometries or geometry and geometry from object (using object's transform)
  15330. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  15331. var matrix, normalMatrix,
  15332. vertexOffset = geometry1.vertices.length,
  15333. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15334. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15335. vertices1 = geometry1.vertices,
  15336. vertices2 = geometry2.vertices,
  15337. faces1 = geometry1.faces,
  15338. faces2 = geometry2.faces,
  15339. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15340. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15341. if ( object2 instanceof THREE.Mesh ) {
  15342. object2.matrixAutoUpdate && object2.updateMatrix();
  15343. matrix = object2.matrix;
  15344. normalMatrix = new THREE.Matrix3();
  15345. normalMatrix.getInverse( matrix );
  15346. normalMatrix.transpose();
  15347. }
  15348. // vertices
  15349. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15350. var vertex = vertices2[ i ];
  15351. var vertexCopy = vertex.clone();
  15352. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15353. vertices1.push( vertexCopy );
  15354. }
  15355. // faces
  15356. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15357. var face = faces2[ i ], faceCopy, normal, color,
  15358. faceVertexNormals = face.vertexNormals,
  15359. faceVertexColors = face.vertexColors;
  15360. if ( face instanceof THREE.Face3 ) {
  15361. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15362. } else if ( face instanceof THREE.Face4 ) {
  15363. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15364. }
  15365. faceCopy.normal.copy( face.normal );
  15366. if ( normalMatrix ) {
  15367. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15368. }
  15369. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15370. normal = faceVertexNormals[ j ].clone();
  15371. if ( normalMatrix ) {
  15372. normal.applyMatrix3( normalMatrix ).normalize();
  15373. }
  15374. faceCopy.vertexNormals.push( normal );
  15375. }
  15376. faceCopy.color.copy( face.color );
  15377. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15378. color = faceVertexColors[ j ];
  15379. faceCopy.vertexColors.push( color.clone() );
  15380. }
  15381. faceCopy.materialIndex = face.materialIndex;
  15382. faceCopy.centroid.copy( face.centroid );
  15383. if ( matrix ) {
  15384. faceCopy.centroid.applyMatrix4( matrix );
  15385. }
  15386. faces1.push( faceCopy );
  15387. }
  15388. // uvs
  15389. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15390. var uv = uvs2[ i ], uvCopy = [];
  15391. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15392. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15393. }
  15394. uvs1.push( uvCopy );
  15395. }
  15396. },
  15397. removeMaterials: function ( geometry, materialIndexArray ) {
  15398. var materialIndexMap = {};
  15399. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15400. materialIndexMap[ materialIndexArray[i] ] = true;
  15401. }
  15402. var face, newFaces = [];
  15403. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15404. face = geometry.faces[ i ];
  15405. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15406. }
  15407. geometry.faces = newFaces;
  15408. },
  15409. // Get random point in triangle (via barycentric coordinates)
  15410. // (uniform distribution)
  15411. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15412. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15413. var a, b, c,
  15414. point = new THREE.Vector3(),
  15415. tmp = THREE.GeometryUtils.__v1;
  15416. a = THREE.GeometryUtils.random();
  15417. b = THREE.GeometryUtils.random();
  15418. if ( ( a + b ) > 1 ) {
  15419. a = 1 - a;
  15420. b = 1 - b;
  15421. }
  15422. c = 1 - a - b;
  15423. point.copy( vectorA );
  15424. point.multiplyScalar( a );
  15425. tmp.copy( vectorB );
  15426. tmp.multiplyScalar( b );
  15427. point.add( tmp );
  15428. tmp.copy( vectorC );
  15429. tmp.multiplyScalar( c );
  15430. point.add( tmp );
  15431. return point;
  15432. },
  15433. // Get random point in face (triangle / quad)
  15434. // (uniform distribution)
  15435. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15436. var vA, vB, vC, vD;
  15437. if ( face instanceof THREE.Face3 ) {
  15438. vA = geometry.vertices[ face.a ];
  15439. vB = geometry.vertices[ face.b ];
  15440. vC = geometry.vertices[ face.c ];
  15441. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15442. } else if ( face instanceof THREE.Face4 ) {
  15443. vA = geometry.vertices[ face.a ];
  15444. vB = geometry.vertices[ face.b ];
  15445. vC = geometry.vertices[ face.c ];
  15446. vD = geometry.vertices[ face.d ];
  15447. var area1, area2;
  15448. if ( useCachedAreas ) {
  15449. if ( face._area1 && face._area2 ) {
  15450. area1 = face._area1;
  15451. area2 = face._area2;
  15452. } else {
  15453. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15454. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15455. face._area1 = area1;
  15456. face._area2 = area2;
  15457. }
  15458. } else {
  15459. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15460. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15461. }
  15462. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15463. if ( r < area1 ) {
  15464. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15465. } else {
  15466. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15467. }
  15468. }
  15469. },
  15470. // Get uniformly distributed random points in mesh
  15471. // - create array with cumulative sums of face areas
  15472. // - pick random number from 0 to total area
  15473. // - find corresponding place in area array by binary search
  15474. // - get random point in face
  15475. randomPointsInGeometry: function ( geometry, n ) {
  15476. var face, i,
  15477. faces = geometry.faces,
  15478. vertices = geometry.vertices,
  15479. il = faces.length,
  15480. totalArea = 0,
  15481. cumulativeAreas = [],
  15482. vA, vB, vC, vD;
  15483. // precompute face areas
  15484. for ( i = 0; i < il; i ++ ) {
  15485. face = faces[ i ];
  15486. if ( face instanceof THREE.Face3 ) {
  15487. vA = vertices[ face.a ];
  15488. vB = vertices[ face.b ];
  15489. vC = vertices[ face.c ];
  15490. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15491. } else if ( face instanceof THREE.Face4 ) {
  15492. vA = vertices[ face.a ];
  15493. vB = vertices[ face.b ];
  15494. vC = vertices[ face.c ];
  15495. vD = vertices[ face.d ];
  15496. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15497. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15498. face._area = face._area1 + face._area2;
  15499. }
  15500. totalArea += face._area;
  15501. cumulativeAreas[ i ] = totalArea;
  15502. }
  15503. // binary search cumulative areas array
  15504. function binarySearchIndices( value ) {
  15505. function binarySearch( start, end ) {
  15506. // return closest larger index
  15507. // if exact number is not found
  15508. if ( end < start )
  15509. return start;
  15510. var mid = start + Math.floor( ( end - start ) / 2 );
  15511. if ( cumulativeAreas[ mid ] > value ) {
  15512. return binarySearch( start, mid - 1 );
  15513. } else if ( cumulativeAreas[ mid ] < value ) {
  15514. return binarySearch( mid + 1, end );
  15515. } else {
  15516. return mid;
  15517. }
  15518. }
  15519. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15520. return result;
  15521. }
  15522. // pick random face weighted by face area
  15523. var r, index,
  15524. result = [];
  15525. var stats = {};
  15526. for ( i = 0; i < n; i ++ ) {
  15527. r = THREE.GeometryUtils.random() * totalArea;
  15528. index = binarySearchIndices( r );
  15529. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15530. if ( ! stats[ index ] ) {
  15531. stats[ index ] = 1;
  15532. } else {
  15533. stats[ index ] += 1;
  15534. }
  15535. }
  15536. return result;
  15537. },
  15538. // Get triangle area (half of parallelogram)
  15539. // http://mathworld.wolfram.com/TriangleArea.html
  15540. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15541. var tmp1 = THREE.GeometryUtils.__v1,
  15542. tmp2 = THREE.GeometryUtils.__v2;
  15543. tmp1.subVectors( vectorB, vectorA );
  15544. tmp2.subVectors( vectorC, vectorA );
  15545. tmp1.cross( tmp2 );
  15546. return 0.5 * tmp1.length();
  15547. },
  15548. // Center geometry so that 0,0,0 is in center of bounding box
  15549. center: function ( geometry ) {
  15550. geometry.computeBoundingBox();
  15551. var bb = geometry.boundingBox;
  15552. var offset = new THREE.Vector3();
  15553. offset.addVectors( bb.min, bb.max );
  15554. offset.multiplyScalar( -0.5 );
  15555. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15556. geometry.computeBoundingBox();
  15557. return offset;
  15558. },
  15559. // Normalize UVs to be from <0,1>
  15560. // (for now just the first set of UVs)
  15561. normalizeUVs: function ( geometry ) {
  15562. var uvSet = geometry.faceVertexUvs[ 0 ];
  15563. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15564. var uvs = uvSet[ i ];
  15565. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15566. // texture repeat
  15567. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15568. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15569. }
  15570. }
  15571. },
  15572. triangulateQuads: function ( geometry ) {
  15573. var i, il, j, jl;
  15574. var faces = [];
  15575. var faceUvs = [];
  15576. var faceVertexUvs = [];
  15577. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15578. faceUvs[ i ] = [];
  15579. }
  15580. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15581. faceVertexUvs[ i ] = [];
  15582. }
  15583. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15584. var face = geometry.faces[ i ];
  15585. if ( face instanceof THREE.Face4 ) {
  15586. var a = face.a;
  15587. var b = face.b;
  15588. var c = face.c;
  15589. var d = face.d;
  15590. var triA = new THREE.Face3();
  15591. var triB = new THREE.Face3();
  15592. triA.color.copy( face.color );
  15593. triB.color.copy( face.color );
  15594. triA.materialIndex = face.materialIndex;
  15595. triB.materialIndex = face.materialIndex;
  15596. triA.a = a;
  15597. triA.b = b;
  15598. triA.c = d;
  15599. triB.a = b;
  15600. triB.b = c;
  15601. triB.c = d;
  15602. if ( face.vertexColors.length === 4 ) {
  15603. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15604. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15605. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15606. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15607. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15608. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15609. }
  15610. faces.push( triA, triB );
  15611. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15612. if ( geometry.faceVertexUvs[ j ].length ) {
  15613. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15614. var uvA = uvs[ 0 ];
  15615. var uvB = uvs[ 1 ];
  15616. var uvC = uvs[ 2 ];
  15617. var uvD = uvs[ 3 ];
  15618. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15619. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15620. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15621. }
  15622. }
  15623. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15624. if ( geometry.faceUvs[ j ].length ) {
  15625. var faceUv = geometry.faceUvs[ j ][ i ];
  15626. faceUvs[ j ].push( faceUv, faceUv );
  15627. }
  15628. }
  15629. } else {
  15630. faces.push( face );
  15631. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15632. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15633. }
  15634. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15635. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15636. }
  15637. }
  15638. }
  15639. geometry.faces = faces;
  15640. geometry.faceUvs = faceUvs;
  15641. geometry.faceVertexUvs = faceVertexUvs;
  15642. geometry.computeCentroids();
  15643. geometry.computeFaceNormals();
  15644. geometry.computeVertexNormals();
  15645. if ( geometry.hasTangents ) geometry.computeTangents();
  15646. },
  15647. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15648. var faces = geometry.faces;
  15649. var start = startFace || 0;
  15650. var end = endFace || faces.length - 1;
  15651. for ( var i = start; i <= end; i ++ ) {
  15652. faces[i].materialIndex = index;
  15653. }
  15654. }
  15655. };
  15656. THREE.GeometryUtils.random = THREE.Math.random16;
  15657. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15658. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15659. /**
  15660. * @author alteredq / http://alteredqualia.com/
  15661. * @author mrdoob / http://mrdoob.com/
  15662. */
  15663. THREE.ImageUtils = {
  15664. crossOrigin: 'anonymous',
  15665. loadTexture: function ( url, mapping, onLoad, onError ) {
  15666. var image = new Image();
  15667. var texture = new THREE.Texture( image, mapping );
  15668. var loader = new THREE.ImageLoader();
  15669. loader.addEventListener( 'load', function ( event ) {
  15670. texture.image = event.content;
  15671. texture.needsUpdate = true;
  15672. if ( onLoad ) onLoad( texture );
  15673. } );
  15674. loader.addEventListener( 'error', function ( event ) {
  15675. if ( onError ) onError( event.message );
  15676. } );
  15677. loader.crossOrigin = this.crossOrigin;
  15678. loader.load( url, image );
  15679. texture.sourceFile = url;
  15680. return texture;
  15681. },
  15682. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15683. var texture = new THREE.CompressedTexture();
  15684. texture.mapping = mapping;
  15685. var request = new XMLHttpRequest();
  15686. request.onload = function () {
  15687. var buffer = request.response;
  15688. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15689. texture.format = dds.format;
  15690. texture.mipmaps = dds.mipmaps;
  15691. texture.image.width = dds.width;
  15692. texture.image.height = dds.height;
  15693. // gl.generateMipmap fails for compressed textures
  15694. // mipmaps must be embedded in the DDS file
  15695. // or texture filters must not use mipmapping
  15696. texture.generateMipmaps = false;
  15697. texture.needsUpdate = true;
  15698. if ( onLoad ) onLoad( texture );
  15699. }
  15700. request.onerror = onError;
  15701. request.open( 'GET', url, true );
  15702. request.responseType = "arraybuffer";
  15703. request.send( null );
  15704. return texture;
  15705. },
  15706. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15707. var images = [];
  15708. images.loadCount = 0;
  15709. var texture = new THREE.Texture();
  15710. texture.image = images;
  15711. if ( mapping !== undefined ) texture.mapping = mapping;
  15712. // no flipping needed for cube textures
  15713. texture.flipY = false;
  15714. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15715. var cubeImage = new Image();
  15716. images[ i ] = cubeImage;
  15717. cubeImage.onload = function () {
  15718. images.loadCount += 1;
  15719. if ( images.loadCount === 6 ) {
  15720. texture.needsUpdate = true;
  15721. if ( onLoad ) onLoad( texture );
  15722. }
  15723. };
  15724. cubeImage.onerror = onError;
  15725. cubeImage.crossOrigin = this.crossOrigin;
  15726. cubeImage.src = array[ i ];
  15727. }
  15728. return texture;
  15729. },
  15730. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15731. var images = [];
  15732. images.loadCount = 0;
  15733. var texture = new THREE.CompressedTexture();
  15734. texture.image = images;
  15735. if ( mapping !== undefined ) texture.mapping = mapping;
  15736. // no flipping for cube textures
  15737. // (also flipping doesn't work for compressed textures )
  15738. texture.flipY = false;
  15739. // can't generate mipmaps for compressed textures
  15740. // mips must be embedded in DDS files
  15741. texture.generateMipmaps = false;
  15742. var generateCubeFaceCallback = function ( rq, img ) {
  15743. return function () {
  15744. var buffer = rq.response;
  15745. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15746. img.format = dds.format;
  15747. img.mipmaps = dds.mipmaps;
  15748. img.width = dds.width;
  15749. img.height = dds.height;
  15750. images.loadCount += 1;
  15751. if ( images.loadCount === 6 ) {
  15752. texture.format = dds.format;
  15753. texture.needsUpdate = true;
  15754. if ( onLoad ) onLoad( texture );
  15755. }
  15756. }
  15757. }
  15758. // compressed cubemap textures as 6 separate DDS files
  15759. if ( array instanceof Array ) {
  15760. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15761. var cubeImage = {};
  15762. images[ i ] = cubeImage;
  15763. var request = new XMLHttpRequest();
  15764. request.onload = generateCubeFaceCallback( request, cubeImage );
  15765. request.onerror = onError;
  15766. var url = array[ i ];
  15767. request.open( 'GET', url, true );
  15768. request.responseType = "arraybuffer";
  15769. request.send( null );
  15770. }
  15771. // compressed cubemap texture stored in a single DDS file
  15772. } else {
  15773. var url = array;
  15774. var request = new XMLHttpRequest();
  15775. request.onload = function( ) {
  15776. var buffer = request.response;
  15777. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15778. if ( dds.isCubemap ) {
  15779. var faces = dds.mipmaps.length / dds.mipmapCount;
  15780. for ( var f = 0; f < faces; f ++ ) {
  15781. images[ f ] = { mipmaps : [] };
  15782. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15783. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15784. images[ f ].format = dds.format;
  15785. images[ f ].width = dds.width;
  15786. images[ f ].height = dds.height;
  15787. }
  15788. }
  15789. texture.format = dds.format;
  15790. texture.needsUpdate = true;
  15791. if ( onLoad ) onLoad( texture );
  15792. }
  15793. }
  15794. request.onerror = onError;
  15795. request.open( 'GET', url, true );
  15796. request.responseType = "arraybuffer";
  15797. request.send( null );
  15798. }
  15799. return texture;
  15800. },
  15801. parseDDS: function ( buffer, loadMipmaps ) {
  15802. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15803. // Adapted from @toji's DDS utils
  15804. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15805. // All values and structures referenced from:
  15806. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15807. var DDS_MAGIC = 0x20534444;
  15808. var DDSD_CAPS = 0x1,
  15809. DDSD_HEIGHT = 0x2,
  15810. DDSD_WIDTH = 0x4,
  15811. DDSD_PITCH = 0x8,
  15812. DDSD_PIXELFORMAT = 0x1000,
  15813. DDSD_MIPMAPCOUNT = 0x20000,
  15814. DDSD_LINEARSIZE = 0x80000,
  15815. DDSD_DEPTH = 0x800000;
  15816. var DDSCAPS_COMPLEX = 0x8,
  15817. DDSCAPS_MIPMAP = 0x400000,
  15818. DDSCAPS_TEXTURE = 0x1000;
  15819. var DDSCAPS2_CUBEMAP = 0x200,
  15820. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15821. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15822. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15823. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15824. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15825. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15826. DDSCAPS2_VOLUME = 0x200000;
  15827. var DDPF_ALPHAPIXELS = 0x1,
  15828. DDPF_ALPHA = 0x2,
  15829. DDPF_FOURCC = 0x4,
  15830. DDPF_RGB = 0x40,
  15831. DDPF_YUV = 0x200,
  15832. DDPF_LUMINANCE = 0x20000;
  15833. function fourCCToInt32( value ) {
  15834. return value.charCodeAt(0) +
  15835. (value.charCodeAt(1) << 8) +
  15836. (value.charCodeAt(2) << 16) +
  15837. (value.charCodeAt(3) << 24);
  15838. }
  15839. function int32ToFourCC( value ) {
  15840. return String.fromCharCode(
  15841. value & 0xff,
  15842. (value >> 8) & 0xff,
  15843. (value >> 16) & 0xff,
  15844. (value >> 24) & 0xff
  15845. );
  15846. }
  15847. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15848. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15849. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15850. var headerLengthInt = 31; // The header length in 32 bit ints
  15851. // Offsets into the header array
  15852. var off_magic = 0;
  15853. var off_size = 1;
  15854. var off_flags = 2;
  15855. var off_height = 3;
  15856. var off_width = 4;
  15857. var off_mipmapCount = 7;
  15858. var off_pfFlags = 20;
  15859. var off_pfFourCC = 21;
  15860. var off_caps = 27;
  15861. var off_caps2 = 28;
  15862. var off_caps3 = 29;
  15863. var off_caps4 = 30;
  15864. // Parse header
  15865. var header = new Int32Array( buffer, 0, headerLengthInt );
  15866. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15867. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15868. return dds;
  15869. }
  15870. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15871. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15872. return dds;
  15873. }
  15874. var blockBytes;
  15875. var fourCC = header[ off_pfFourCC ];
  15876. switch ( fourCC ) {
  15877. case FOURCC_DXT1:
  15878. blockBytes = 8;
  15879. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15880. break;
  15881. case FOURCC_DXT3:
  15882. blockBytes = 16;
  15883. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15884. break;
  15885. case FOURCC_DXT5:
  15886. blockBytes = 16;
  15887. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15888. break;
  15889. default:
  15890. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15891. return dds;
  15892. }
  15893. dds.mipmapCount = 1;
  15894. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15895. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15896. }
  15897. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15898. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15899. dds.width = header[ off_width ];
  15900. dds.height = header[ off_height ];
  15901. var dataOffset = header[ off_size ] + 4;
  15902. // Extract mipmaps buffers
  15903. var width = dds.width;
  15904. var height = dds.height;
  15905. var faces = dds.isCubemap ? 6 : 1;
  15906. for ( var face = 0; face < faces; face ++ ) {
  15907. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15908. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15909. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15910. var mipmap = { "data": byteArray, "width": width, "height": height };
  15911. dds.mipmaps.push( mipmap );
  15912. dataOffset += dataLength;
  15913. width = Math.max( width * 0.5, 1 );
  15914. height = Math.max( height * 0.5, 1 );
  15915. }
  15916. width = dds.width;
  15917. height = dds.height;
  15918. }
  15919. return dds;
  15920. },
  15921. getNormalMap: function ( image, depth ) {
  15922. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15923. var cross = function ( a, b ) {
  15924. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  15925. }
  15926. var subtract = function ( a, b ) {
  15927. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15928. }
  15929. var normalize = function ( a ) {
  15930. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15931. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15932. }
  15933. depth = depth | 1;
  15934. var width = image.width;
  15935. var height = image.height;
  15936. var canvas = document.createElement( 'canvas' );
  15937. canvas.width = width;
  15938. canvas.height = height;
  15939. var context = canvas.getContext( '2d' );
  15940. context.drawImage( image, 0, 0 );
  15941. var data = context.getImageData( 0, 0, width, height ).data;
  15942. var imageData = context.createImageData( width, height );
  15943. var output = imageData.data;
  15944. for ( var x = 0; x < width; x ++ ) {
  15945. for ( var y = 0; y < height; y ++ ) {
  15946. var ly = y - 1 < 0 ? 0 : y - 1;
  15947. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15948. var lx = x - 1 < 0 ? 0 : x - 1;
  15949. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15950. var points = [];
  15951. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15952. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15953. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15954. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15955. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15956. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15957. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15958. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15959. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15960. var normals = [];
  15961. var num_points = points.length;
  15962. for ( var i = 0; i < num_points; i ++ ) {
  15963. var v1 = points[ i ];
  15964. var v2 = points[ ( i + 1 ) % num_points ];
  15965. v1 = subtract( v1, origin );
  15966. v2 = subtract( v2, origin );
  15967. normals.push( normalize( cross( v1, v2 ) ) );
  15968. }
  15969. var normal = [ 0, 0, 0 ];
  15970. for ( var i = 0; i < normals.length; i ++ ) {
  15971. normal[ 0 ] += normals[ i ][ 0 ];
  15972. normal[ 1 ] += normals[ i ][ 1 ];
  15973. normal[ 2 ] += normals[ i ][ 2 ];
  15974. }
  15975. normal[ 0 ] /= normals.length;
  15976. normal[ 1 ] /= normals.length;
  15977. normal[ 2 ] /= normals.length;
  15978. var idx = ( y * width + x ) * 4;
  15979. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15980. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15981. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15982. output[ idx + 3 ] = 255;
  15983. }
  15984. }
  15985. context.putImageData( imageData, 0, 0 );
  15986. return canvas;
  15987. },
  15988. generateDataTexture: function ( width, height, color ) {
  15989. var size = width * height;
  15990. var data = new Uint8Array( 3 * size );
  15991. var r = Math.floor( color.r * 255 );
  15992. var g = Math.floor( color.g * 255 );
  15993. var b = Math.floor( color.b * 255 );
  15994. for ( var i = 0; i < size; i ++ ) {
  15995. data[ i * 3 ] = r;
  15996. data[ i * 3 + 1 ] = g;
  15997. data[ i * 3 + 2 ] = b;
  15998. }
  15999. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16000. texture.needsUpdate = true;
  16001. return texture;
  16002. }
  16003. };
  16004. /**
  16005. * @author alteredq / http://alteredqualia.com/
  16006. */
  16007. THREE.SceneUtils = {
  16008. createMultiMaterialObject: function ( geometry, materials ) {
  16009. var group = new THREE.Object3D();
  16010. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16011. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16012. }
  16013. return group;
  16014. },
  16015. detach : function ( child, parent, scene ) {
  16016. child.applyMatrix( parent.matrixWorld );
  16017. parent.remove( child );
  16018. scene.add( child );
  16019. },
  16020. attach: function ( child, scene, parent ) {
  16021. var matrixWorldInverse = new THREE.Matrix4();
  16022. matrixWorldInverse.getInverse( parent.matrixWorld );
  16023. child.applyMatrix( matrixWorldInverse );
  16024. scene.remove( child );
  16025. parent.add( child );
  16026. }
  16027. };
  16028. /**
  16029. * @author zz85 / http://www.lab4games.net/zz85/blog
  16030. * @author alteredq / http://alteredqualia.com/
  16031. *
  16032. * For Text operations in three.js (See TextGeometry)
  16033. *
  16034. * It uses techniques used in:
  16035. *
  16036. * typeface.js and canvastext
  16037. * For converting fonts and rendering with javascript
  16038. * http://typeface.neocracy.org
  16039. *
  16040. * Triangulation ported from AS3
  16041. * Simple Polygon Triangulation
  16042. * http://actionsnippet.com/?p=1462
  16043. *
  16044. * A Method to triangulate shapes with holes
  16045. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16046. *
  16047. */
  16048. THREE.FontUtils = {
  16049. faces : {},
  16050. // Just for now. face[weight][style]
  16051. face : "helvetiker",
  16052. weight: "normal",
  16053. style : "normal",
  16054. size : 150,
  16055. divisions : 10,
  16056. getFace : function() {
  16057. return this.faces[ this.face ][ this.weight ][ this.style ];
  16058. },
  16059. loadFace : function( data ) {
  16060. var family = data.familyName.toLowerCase();
  16061. var ThreeFont = this;
  16062. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16063. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16064. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16065. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16066. return data;
  16067. },
  16068. drawText : function( text ) {
  16069. var characterPts = [], allPts = [];
  16070. // RenderText
  16071. var i, p,
  16072. face = this.getFace(),
  16073. scale = this.size / face.resolution,
  16074. offset = 0,
  16075. chars = String( text ).split( '' ),
  16076. length = chars.length;
  16077. var fontPaths = [];
  16078. for ( i = 0; i < length; i ++ ) {
  16079. var path = new THREE.Path();
  16080. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16081. offset += ret.offset;
  16082. fontPaths.push( ret.path );
  16083. }
  16084. // get the width
  16085. var width = offset / 2;
  16086. //
  16087. // for ( p = 0; p < allPts.length; p++ ) {
  16088. //
  16089. // allPts[ p ].x -= width;
  16090. //
  16091. // }
  16092. //var extract = this.extractPoints( allPts, characterPts );
  16093. //extract.contour = allPts;
  16094. //extract.paths = fontPaths;
  16095. //extract.offset = width;
  16096. return { paths : fontPaths, offset : width };
  16097. },
  16098. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16099. var pts = [];
  16100. var i, i2, divisions,
  16101. outline, action, length,
  16102. scaleX, scaleY,
  16103. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16104. laste,
  16105. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16106. if ( !glyph ) return;
  16107. if ( glyph.o ) {
  16108. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16109. length = outline.length;
  16110. scaleX = scale;
  16111. scaleY = scale;
  16112. for ( i = 0; i < length; ) {
  16113. action = outline[ i ++ ];
  16114. //console.log( action );
  16115. switch( action ) {
  16116. case 'm':
  16117. // Move To
  16118. x = outline[ i++ ] * scaleX + offset;
  16119. y = outline[ i++ ] * scaleY;
  16120. path.moveTo( x, y );
  16121. break;
  16122. case 'l':
  16123. // Line To
  16124. x = outline[ i++ ] * scaleX + offset;
  16125. y = outline[ i++ ] * scaleY;
  16126. path.lineTo(x,y);
  16127. break;
  16128. case 'q':
  16129. // QuadraticCurveTo
  16130. cpx = outline[ i++ ] * scaleX + offset;
  16131. cpy = outline[ i++ ] * scaleY;
  16132. cpx1 = outline[ i++ ] * scaleX + offset;
  16133. cpy1 = outline[ i++ ] * scaleY;
  16134. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16135. laste = pts[ pts.length - 1 ];
  16136. if ( laste ) {
  16137. cpx0 = laste.x;
  16138. cpy0 = laste.y;
  16139. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16140. var t = i2 / divisions;
  16141. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16142. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16143. }
  16144. }
  16145. break;
  16146. case 'b':
  16147. // Cubic Bezier Curve
  16148. cpx = outline[ i++ ] * scaleX + offset;
  16149. cpy = outline[ i++ ] * scaleY;
  16150. cpx1 = outline[ i++ ] * scaleX + offset;
  16151. cpy1 = outline[ i++ ] * -scaleY;
  16152. cpx2 = outline[ i++ ] * scaleX + offset;
  16153. cpy2 = outline[ i++ ] * -scaleY;
  16154. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16155. laste = pts[ pts.length - 1 ];
  16156. if ( laste ) {
  16157. cpx0 = laste.x;
  16158. cpy0 = laste.y;
  16159. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16160. var t = i2 / divisions;
  16161. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16162. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16163. }
  16164. }
  16165. break;
  16166. }
  16167. }
  16168. }
  16169. return { offset: glyph.ha*scale, path:path};
  16170. }
  16171. };
  16172. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16173. // Parameters
  16174. parameters = parameters || {};
  16175. var size = parameters.size !== undefined ? parameters.size : 100;
  16176. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16177. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16178. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16179. var style = parameters.style !== undefined ? parameters.style : "normal";
  16180. THREE.FontUtils.size = size;
  16181. THREE.FontUtils.divisions = curveSegments;
  16182. THREE.FontUtils.face = font;
  16183. THREE.FontUtils.weight = weight;
  16184. THREE.FontUtils.style = style;
  16185. // Get a Font data json object
  16186. var data = THREE.FontUtils.drawText( text );
  16187. var paths = data.paths;
  16188. var shapes = [];
  16189. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16190. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16191. }
  16192. return shapes;
  16193. };
  16194. /**
  16195. * This code is a quick port of code written in C++ which was submitted to
  16196. * flipcode.com by John W. Ratcliff // July 22, 2000
  16197. * See original code and more information here:
  16198. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16199. *
  16200. * ported to actionscript by Zevan Rosser
  16201. * www.actionsnippet.com
  16202. *
  16203. * ported to javascript by Joshua Koo
  16204. * http://www.lab4games.net/zz85/blog
  16205. *
  16206. */
  16207. ( function( namespace ) {
  16208. var EPSILON = 0.0000000001;
  16209. // takes in an contour array and returns
  16210. var process = function( contour, indices ) {
  16211. var n = contour.length;
  16212. if ( n < 3 ) return null;
  16213. var result = [],
  16214. verts = [],
  16215. vertIndices = [];
  16216. /* we want a counter-clockwise polygon in verts */
  16217. var u, v, w;
  16218. if ( area( contour ) > 0.0 ) {
  16219. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16220. } else {
  16221. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16222. }
  16223. var nv = n;
  16224. /* remove nv - 2 vertices, creating 1 triangle every time */
  16225. var count = 2 * nv; /* error detection */
  16226. for( v = nv - 1; nv > 2; ) {
  16227. /* if we loop, it is probably a non-simple polygon */
  16228. if ( ( count-- ) <= 0 ) {
  16229. //** Triangulate: ERROR - probable bad polygon!
  16230. //throw ( "Warning, unable to triangulate polygon!" );
  16231. //return null;
  16232. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16233. console.log( "Warning, unable to triangulate polygon!" );
  16234. if ( indices ) return vertIndices;
  16235. return result;
  16236. }
  16237. /* three consecutive vertices in current polygon, <u,v,w> */
  16238. u = v; if ( nv <= u ) u = 0; /* previous */
  16239. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16240. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16241. if ( snip( contour, u, v, w, nv, verts ) ) {
  16242. var a, b, c, s, t;
  16243. /* true names of the vertices */
  16244. a = verts[ u ];
  16245. b = verts[ v ];
  16246. c = verts[ w ];
  16247. /* output Triangle */
  16248. result.push( [ contour[ a ],
  16249. contour[ b ],
  16250. contour[ c ] ] );
  16251. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16252. /* remove v from the remaining polygon */
  16253. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16254. verts[ s ] = verts[ t ];
  16255. }
  16256. nv--;
  16257. /* reset error detection counter */
  16258. count = 2 * nv;
  16259. }
  16260. }
  16261. if ( indices ) return vertIndices;
  16262. return result;
  16263. };
  16264. // calculate area of the contour polygon
  16265. var area = function ( contour ) {
  16266. var n = contour.length;
  16267. var a = 0.0;
  16268. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16269. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16270. }
  16271. return a * 0.5;
  16272. };
  16273. var snip = function ( contour, u, v, w, n, verts ) {
  16274. var p;
  16275. var ax, ay, bx, by;
  16276. var cx, cy, px, py;
  16277. ax = contour[ verts[ u ] ].x;
  16278. ay = contour[ verts[ u ] ].y;
  16279. bx = contour[ verts[ v ] ].x;
  16280. by = contour[ verts[ v ] ].y;
  16281. cx = contour[ verts[ w ] ].x;
  16282. cy = contour[ verts[ w ] ].y;
  16283. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16284. var aX, aY, bX, bY, cX, cY;
  16285. var apx, apy, bpx, bpy, cpx, cpy;
  16286. var cCROSSap, bCROSScp, aCROSSbp;
  16287. aX = cx - bx; aY = cy - by;
  16288. bX = ax - cx; bY = ay - cy;
  16289. cX = bx - ax; cY = by - ay;
  16290. for ( p = 0; p < n; p++ ) {
  16291. if( (p === u) || (p === v) || (p === w) ) continue;
  16292. px = contour[ verts[ p ] ].x
  16293. py = contour[ verts[ p ] ].y
  16294. apx = px - ax; apy = py - ay;
  16295. bpx = px - bx; bpy = py - by;
  16296. cpx = px - cx; cpy = py - cy;
  16297. // see if p is inside triangle abc
  16298. aCROSSbp = aX*bpy - aY*bpx;
  16299. cCROSSap = cX*apy - cY*apx;
  16300. bCROSScp = bX*cpy - bY*cpx;
  16301. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16302. }
  16303. return true;
  16304. };
  16305. namespace.Triangulate = process;
  16306. namespace.Triangulate.area = area;
  16307. return namespace;
  16308. })(THREE.FontUtils);
  16309. // To use the typeface.js face files, hook up the API
  16310. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16311. * @author zz85 / http://www.lab4games.net/zz85/blog
  16312. * Extensible curve object
  16313. *
  16314. * Some common of Curve methods
  16315. * .getPoint(t), getTangent(t)
  16316. * .getPointAt(u), getTagentAt(u)
  16317. * .getPoints(), .getSpacedPoints()
  16318. * .getLength()
  16319. * .updateArcLengths()
  16320. *
  16321. * This file contains following classes:
  16322. *
  16323. * -- 2d classes --
  16324. * THREE.Curve
  16325. * THREE.LineCurve
  16326. * THREE.QuadraticBezierCurve
  16327. * THREE.CubicBezierCurve
  16328. * THREE.SplineCurve
  16329. * THREE.ArcCurve
  16330. * THREE.EllipseCurve
  16331. *
  16332. * -- 3d classes --
  16333. * THREE.LineCurve3
  16334. * THREE.QuadraticBezierCurve3
  16335. * THREE.CubicBezierCurve3
  16336. * THREE.SplineCurve3
  16337. * THREE.ClosedSplineCurve3
  16338. *
  16339. * A series of curves can be represented as a THREE.CurvePath
  16340. *
  16341. **/
  16342. /**************************************************************
  16343. * Abstract Curve base class
  16344. **************************************************************/
  16345. THREE.Curve = function () {
  16346. };
  16347. // Virtual base class method to overwrite and implement in subclasses
  16348. // - t [0 .. 1]
  16349. THREE.Curve.prototype.getPoint = function ( t ) {
  16350. console.log( "Warning, getPoint() not implemented!" );
  16351. return null;
  16352. };
  16353. // Get point at relative position in curve according to arc length
  16354. // - u [0 .. 1]
  16355. THREE.Curve.prototype.getPointAt = function ( u ) {
  16356. var t = this.getUtoTmapping( u );
  16357. return this.getPoint( t );
  16358. };
  16359. // Get sequence of points using getPoint( t )
  16360. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16361. if ( !divisions ) divisions = 5;
  16362. var d, pts = [];
  16363. for ( d = 0; d <= divisions; d ++ ) {
  16364. pts.push( this.getPoint( d / divisions ) );
  16365. }
  16366. return pts;
  16367. };
  16368. // Get sequence of points using getPointAt( u )
  16369. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16370. if ( !divisions ) divisions = 5;
  16371. var d, pts = [];
  16372. for ( d = 0; d <= divisions; d ++ ) {
  16373. pts.push( this.getPointAt( d / divisions ) );
  16374. }
  16375. return pts;
  16376. };
  16377. // Get total curve arc length
  16378. THREE.Curve.prototype.getLength = function () {
  16379. var lengths = this.getLengths();
  16380. return lengths[ lengths.length - 1 ];
  16381. };
  16382. // Get list of cumulative segment lengths
  16383. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16384. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16385. if ( this.cacheArcLengths
  16386. && ( this.cacheArcLengths.length == divisions + 1 )
  16387. && !this.needsUpdate) {
  16388. //console.log( "cached", this.cacheArcLengths );
  16389. return this.cacheArcLengths;
  16390. }
  16391. this.needsUpdate = false;
  16392. var cache = [];
  16393. var current, last = this.getPoint( 0 );
  16394. var p, sum = 0;
  16395. cache.push( 0 );
  16396. for ( p = 1; p <= divisions; p ++ ) {
  16397. current = this.getPoint ( p / divisions );
  16398. sum += current.distanceTo( last );
  16399. cache.push( sum );
  16400. last = current;
  16401. }
  16402. this.cacheArcLengths = cache;
  16403. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16404. };
  16405. THREE.Curve.prototype.updateArcLengths = function() {
  16406. this.needsUpdate = true;
  16407. this.getLengths();
  16408. };
  16409. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16410. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16411. var arcLengths = this.getLengths();
  16412. var i = 0, il = arcLengths.length;
  16413. var targetArcLength; // The targeted u distance value to get
  16414. if ( distance ) {
  16415. targetArcLength = distance;
  16416. } else {
  16417. targetArcLength = u * arcLengths[ il - 1 ];
  16418. }
  16419. //var time = Date.now();
  16420. // binary search for the index with largest value smaller than target u distance
  16421. var low = 0, high = il - 1, comparison;
  16422. while ( low <= high ) {
  16423. 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
  16424. comparison = arcLengths[ i ] - targetArcLength;
  16425. if ( comparison < 0 ) {
  16426. low = i + 1;
  16427. continue;
  16428. } else if ( comparison > 0 ) {
  16429. high = i - 1;
  16430. continue;
  16431. } else {
  16432. high = i;
  16433. break;
  16434. // DONE
  16435. }
  16436. }
  16437. i = high;
  16438. //console.log('b' , i, low, high, Date.now()- time);
  16439. if ( arcLengths[ i ] == targetArcLength ) {
  16440. var t = i / ( il - 1 );
  16441. return t;
  16442. }
  16443. // we could get finer grain at lengths, or use simple interpolatation between two points
  16444. var lengthBefore = arcLengths[ i ];
  16445. var lengthAfter = arcLengths[ i + 1 ];
  16446. var segmentLength = lengthAfter - lengthBefore;
  16447. // determine where we are between the 'before' and 'after' points
  16448. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16449. // add that fractional amount to t
  16450. var t = ( i + segmentFraction ) / ( il -1 );
  16451. return t;
  16452. };
  16453. // Returns a unit vector tangent at t
  16454. // In case any sub curve does not implement its tangent derivation,
  16455. // 2 points a small delta apart will be used to find its gradient
  16456. // which seems to give a reasonable approximation
  16457. THREE.Curve.prototype.getTangent = function( t ) {
  16458. var delta = 0.0001;
  16459. var t1 = t - delta;
  16460. var t2 = t + delta;
  16461. // Capping in case of danger
  16462. if ( t1 < 0 ) t1 = 0;
  16463. if ( t2 > 1 ) t2 = 1;
  16464. var pt1 = this.getPoint( t1 );
  16465. var pt2 = this.getPoint( t2 );
  16466. var vec = pt2.clone().sub(pt1);
  16467. return vec.normalize();
  16468. };
  16469. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16470. var t = this.getUtoTmapping( u );
  16471. return this.getTangent( t );
  16472. };
  16473. /**************************************************************
  16474. * Line
  16475. **************************************************************/
  16476. THREE.LineCurve = function ( v1, v2 ) {
  16477. this.v1 = v1;
  16478. this.v2 = v2;
  16479. };
  16480. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16481. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16482. var point = this.v2.clone().sub(this.v1);
  16483. point.multiplyScalar( t ).add( this.v1 );
  16484. return point;
  16485. };
  16486. // Line curve is linear, so we can overwrite default getPointAt
  16487. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16488. return this.getPoint( u );
  16489. };
  16490. THREE.LineCurve.prototype.getTangent = function( t ) {
  16491. var tangent = this.v2.clone().sub(this.v1);
  16492. return tangent.normalize();
  16493. };
  16494. /**************************************************************
  16495. * Quadratic Bezier curve
  16496. **************************************************************/
  16497. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16498. this.v0 = v0;
  16499. this.v1 = v1;
  16500. this.v2 = v2;
  16501. };
  16502. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16503. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16504. var tx, ty;
  16505. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16506. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16507. return new THREE.Vector2( tx, ty );
  16508. };
  16509. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16510. var tx, ty;
  16511. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16512. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16513. // returns unit vector
  16514. var tangent = new THREE.Vector2( tx, ty );
  16515. tangent.normalize();
  16516. return tangent;
  16517. };
  16518. /**************************************************************
  16519. * Cubic Bezier curve
  16520. **************************************************************/
  16521. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16522. this.v0 = v0;
  16523. this.v1 = v1;
  16524. this.v2 = v2;
  16525. this.v3 = v3;
  16526. };
  16527. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16528. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16529. var tx, ty;
  16530. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16531. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16532. return new THREE.Vector2( tx, ty );
  16533. };
  16534. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16535. var tx, ty;
  16536. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16537. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16538. var tangent = new THREE.Vector2( tx, ty );
  16539. tangent.normalize();
  16540. return tangent;
  16541. };
  16542. /**************************************************************
  16543. * Spline curve
  16544. **************************************************************/
  16545. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16546. this.points = (points == undefined) ? [] : points;
  16547. };
  16548. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16549. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16550. var v = new THREE.Vector2();
  16551. var c = [];
  16552. var points = this.points, point, intPoint, weight;
  16553. point = ( points.length - 1 ) * t;
  16554. intPoint = Math.floor( point );
  16555. weight = point - intPoint;
  16556. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16557. c[ 1 ] = intPoint;
  16558. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16559. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16560. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16561. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16562. return v;
  16563. };
  16564. /**************************************************************
  16565. * Ellipse curve
  16566. **************************************************************/
  16567. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16568. aStartAngle, aEndAngle,
  16569. aClockwise ) {
  16570. this.aX = aX;
  16571. this.aY = aY;
  16572. this.xRadius = xRadius;
  16573. this.yRadius = yRadius;
  16574. this.aStartAngle = aStartAngle;
  16575. this.aEndAngle = aEndAngle;
  16576. this.aClockwise = aClockwise;
  16577. };
  16578. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16579. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16580. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16581. if ( !this.aClockwise ) {
  16582. t = 1 - t;
  16583. }
  16584. var angle = this.aStartAngle + t * deltaAngle;
  16585. var tx = this.aX + this.xRadius * Math.cos( angle );
  16586. var ty = this.aY + this.yRadius * Math.sin( angle );
  16587. return new THREE.Vector2( tx, ty );
  16588. };
  16589. /**************************************************************
  16590. * Arc curve
  16591. **************************************************************/
  16592. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16593. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16594. };
  16595. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16596. /**************************************************************
  16597. * Utils
  16598. **************************************************************/
  16599. THREE.Curve.Utils = {
  16600. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16601. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16602. },
  16603. // Puay Bing, thanks for helping with this derivative!
  16604. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16605. return -3 * p0 * (1 - t) * (1 - t) +
  16606. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16607. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16608. 3 * t * t * p3;
  16609. },
  16610. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16611. // To check if my formulas are correct
  16612. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16613. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16614. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16615. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16616. return h00 + h10 + h01 + h11;
  16617. },
  16618. // Catmull-Rom
  16619. interpolate: function( p0, p1, p2, p3, t ) {
  16620. var v0 = ( p2 - p0 ) * 0.5;
  16621. var v1 = ( p3 - p1 ) * 0.5;
  16622. var t2 = t * t;
  16623. var t3 = t * t2;
  16624. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16625. }
  16626. };
  16627. // TODO: Transformation for Curves?
  16628. /**************************************************************
  16629. * 3D Curves
  16630. **************************************************************/
  16631. // A Factory method for creating new curve subclasses
  16632. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16633. constructor.prototype = Object.create( THREE.Curve.prototype );
  16634. constructor.prototype.getPoint = getPointFunc;
  16635. return constructor;
  16636. };
  16637. /**************************************************************
  16638. * Line3D
  16639. **************************************************************/
  16640. THREE.LineCurve3 = THREE.Curve.create(
  16641. function ( v1, v2 ) {
  16642. this.v1 = v1;
  16643. this.v2 = v2;
  16644. },
  16645. function ( t ) {
  16646. var r = new THREE.Vector3();
  16647. r.subVectors( this.v2, this.v1 ); // diff
  16648. r.multiplyScalar( t );
  16649. r.add( this.v1 );
  16650. return r;
  16651. }
  16652. );
  16653. /**************************************************************
  16654. * Quadratic Bezier 3D curve
  16655. **************************************************************/
  16656. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16657. function ( v0, v1, v2 ) {
  16658. this.v0 = v0;
  16659. this.v1 = v1;
  16660. this.v2 = v2;
  16661. },
  16662. function ( t ) {
  16663. var tx, ty, tz;
  16664. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16665. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16666. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16667. return new THREE.Vector3( tx, ty, tz );
  16668. }
  16669. );
  16670. /**************************************************************
  16671. * Cubic Bezier 3D curve
  16672. **************************************************************/
  16673. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16674. function ( v0, v1, v2, v3 ) {
  16675. this.v0 = v0;
  16676. this.v1 = v1;
  16677. this.v2 = v2;
  16678. this.v3 = v3;
  16679. },
  16680. function ( t ) {
  16681. var tx, ty, tz;
  16682. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16683. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16684. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16685. return new THREE.Vector3( tx, ty, tz );
  16686. }
  16687. );
  16688. /**************************************************************
  16689. * Spline 3D curve
  16690. **************************************************************/
  16691. THREE.SplineCurve3 = THREE.Curve.create(
  16692. function ( points /* array of Vector3 */) {
  16693. this.points = (points == undefined) ? [] : points;
  16694. },
  16695. function ( t ) {
  16696. var v = new THREE.Vector3();
  16697. var c = [];
  16698. var points = this.points, point, intPoint, weight;
  16699. point = ( points.length - 1 ) * t;
  16700. intPoint = Math.floor( point );
  16701. weight = point - intPoint;
  16702. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16703. c[ 1 ] = intPoint;
  16704. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16705. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16706. var pt0 = points[ c[0] ],
  16707. pt1 = points[ c[1] ],
  16708. pt2 = points[ c[2] ],
  16709. pt3 = points[ c[3] ];
  16710. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16711. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16712. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16713. return v;
  16714. }
  16715. );
  16716. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16717. // var v = new THREE.Vector3();
  16718. // var c = [];
  16719. // var points = this.points, point, intPoint, weight;
  16720. // point = ( points.length - 1 ) * t;
  16721. // intPoint = Math.floor( point );
  16722. // weight = point - intPoint;
  16723. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16724. // c[ 1 ] = intPoint;
  16725. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16726. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16727. // var pt0 = points[ c[0] ],
  16728. // pt1 = points[ c[1] ],
  16729. // pt2 = points[ c[2] ],
  16730. // pt3 = points[ c[3] ];
  16731. // // t = weight;
  16732. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16733. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16734. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16735. // return v;
  16736. // }
  16737. /**************************************************************
  16738. * Closed Spline 3D curve
  16739. **************************************************************/
  16740. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16741. function ( points /* array of Vector3 */) {
  16742. this.points = (points == undefined) ? [] : points;
  16743. },
  16744. function ( t ) {
  16745. var v = new THREE.Vector3();
  16746. var c = [];
  16747. var points = this.points, point, intPoint, weight;
  16748. point = ( points.length - 0 ) * t;
  16749. // This needs to be from 0-length +1
  16750. intPoint = Math.floor( point );
  16751. weight = point - intPoint;
  16752. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16753. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16754. c[ 1 ] = ( intPoint ) % points.length;
  16755. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16756. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16757. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16758. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16759. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16760. return v;
  16761. }
  16762. );
  16763. /**
  16764. * @author zz85 / http://www.lab4games.net/zz85/blog
  16765. *
  16766. **/
  16767. /**************************************************************
  16768. * Curved Path - a curve path is simply a array of connected
  16769. * curves, but retains the api of a curve
  16770. **************************************************************/
  16771. THREE.CurvePath = function () {
  16772. this.curves = [];
  16773. this.bends = [];
  16774. this.autoClose = false; // Automatically closes the path
  16775. };
  16776. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16777. THREE.CurvePath.prototype.add = function ( curve ) {
  16778. this.curves.push( curve );
  16779. };
  16780. THREE.CurvePath.prototype.checkConnection = function() {
  16781. // TODO
  16782. // If the ending of curve is not connected to the starting
  16783. // or the next curve, then, this is not a real path
  16784. };
  16785. THREE.CurvePath.prototype.closePath = function() {
  16786. // TODO Test
  16787. // and verify for vector3 (needs to implement equals)
  16788. // Add a line curve if start and end of lines are not connected
  16789. var startPoint = this.curves[0].getPoint(0);
  16790. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16791. if (!startPoint.equals(endPoint)) {
  16792. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16793. }
  16794. };
  16795. // To get accurate point with reference to
  16796. // entire path distance at time t,
  16797. // following has to be done:
  16798. // 1. Length of each sub path have to be known
  16799. // 2. Locate and identify type of curve
  16800. // 3. Get t for the curve
  16801. // 4. Return curve.getPointAt(t')
  16802. THREE.CurvePath.prototype.getPoint = function( t ) {
  16803. var d = t * this.getLength();
  16804. var curveLengths = this.getCurveLengths();
  16805. var i = 0, diff, curve;
  16806. // To think about boundaries points.
  16807. while ( i < curveLengths.length ) {
  16808. if ( curveLengths[ i ] >= d ) {
  16809. diff = curveLengths[ i ] - d;
  16810. curve = this.curves[ i ];
  16811. var u = 1 - diff / curve.getLength();
  16812. return curve.getPointAt( u );
  16813. break;
  16814. }
  16815. i ++;
  16816. }
  16817. return null;
  16818. // loop where sum != 0, sum > d , sum+1 <d
  16819. };
  16820. /*
  16821. THREE.CurvePath.prototype.getTangent = function( t ) {
  16822. };*/
  16823. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16824. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16825. // getPoint() depends on getLength
  16826. THREE.CurvePath.prototype.getLength = function() {
  16827. var lens = this.getCurveLengths();
  16828. return lens[ lens.length - 1 ];
  16829. };
  16830. // Compute lengths and cache them
  16831. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16832. THREE.CurvePath.prototype.getCurveLengths = function() {
  16833. // We use cache values if curves and cache array are same length
  16834. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16835. return this.cacheLengths;
  16836. };
  16837. // Get length of subsurve
  16838. // Push sums into cached array
  16839. var lengths = [], sums = 0;
  16840. var i, il = this.curves.length;
  16841. for ( i = 0; i < il; i ++ ) {
  16842. sums += this.curves[ i ].getLength();
  16843. lengths.push( sums );
  16844. }
  16845. this.cacheLengths = lengths;
  16846. return lengths;
  16847. };
  16848. // Returns min and max coordinates, as well as centroid
  16849. THREE.CurvePath.prototype.getBoundingBox = function () {
  16850. var points = this.getPoints();
  16851. var maxX, maxY, maxZ;
  16852. var minX, minY, minZ;
  16853. maxX = maxY = Number.NEGATIVE_INFINITY;
  16854. minX = minY = Number.POSITIVE_INFINITY;
  16855. var p, i, il, sum;
  16856. var v3 = points[0] instanceof THREE.Vector3;
  16857. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16858. for ( i = 0, il = points.length; i < il; i ++ ) {
  16859. p = points[ i ];
  16860. if ( p.x > maxX ) maxX = p.x;
  16861. else if ( p.x < minX ) minX = p.x;
  16862. if ( p.y > maxY ) maxY = p.y;
  16863. else if ( p.y < minY ) minY = p.y;
  16864. if ( v3 ) {
  16865. if ( p.z > maxZ ) maxZ = p.z;
  16866. else if ( p.z < minZ ) minZ = p.z;
  16867. }
  16868. sum.add( p );
  16869. }
  16870. var ret = {
  16871. minX: minX,
  16872. minY: minY,
  16873. maxX: maxX,
  16874. maxY: maxY,
  16875. centroid: sum.divideScalar( il )
  16876. };
  16877. if ( v3 ) {
  16878. ret.maxZ = maxZ;
  16879. ret.minZ = minZ;
  16880. }
  16881. return ret;
  16882. };
  16883. /**************************************************************
  16884. * Create Geometries Helpers
  16885. **************************************************************/
  16886. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16887. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16888. var pts = this.getPoints( divisions, true );
  16889. return this.createGeometry( pts );
  16890. };
  16891. // Generate geometry from equidistance sampling along the path
  16892. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16893. var pts = this.getSpacedPoints( divisions, true );
  16894. return this.createGeometry( pts );
  16895. };
  16896. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16897. var geometry = new THREE.Geometry();
  16898. for ( var i = 0; i < points.length; i ++ ) {
  16899. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16900. }
  16901. return geometry;
  16902. };
  16903. /**************************************************************
  16904. * Bend / Wrap Helper Methods
  16905. **************************************************************/
  16906. // Wrap path / Bend modifiers?
  16907. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16908. this.bends.push( bendpath );
  16909. };
  16910. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16911. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16912. var i, il;
  16913. if ( !bends ) {
  16914. bends = this.bends;
  16915. }
  16916. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16917. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16918. }
  16919. return oldPts;
  16920. };
  16921. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16922. var oldPts = this.getSpacedPoints( segments );
  16923. var i, il;
  16924. if ( !bends ) {
  16925. bends = this.bends;
  16926. }
  16927. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16928. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16929. }
  16930. return oldPts;
  16931. };
  16932. // This returns getPoints() bend/wrapped around the contour of a path.
  16933. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16934. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16935. var bounds = this.getBoundingBox();
  16936. var i, il, p, oldX, oldY, xNorm;
  16937. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16938. p = oldPts[ i ];
  16939. oldX = p.x;
  16940. oldY = p.y;
  16941. xNorm = oldX / bounds.maxX;
  16942. // If using actual distance, for length > path, requires line extrusions
  16943. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16944. xNorm = path.getUtoTmapping( xNorm, oldX );
  16945. // check for out of bounds?
  16946. var pathPt = path.getPoint( xNorm );
  16947. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16948. p.x = pathPt.x + normal.x;
  16949. p.y = pathPt.y + normal.y;
  16950. }
  16951. return oldPts;
  16952. };
  16953. /**
  16954. * @author alteredq / http://alteredqualia.com/
  16955. */
  16956. THREE.Gyroscope = function () {
  16957. THREE.Object3D.call( this );
  16958. };
  16959. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16960. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16961. this.matrixAutoUpdate && this.updateMatrix();
  16962. // update matrixWorld
  16963. if ( this.matrixWorldNeedsUpdate || force ) {
  16964. if ( this.parent ) {
  16965. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16966. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16967. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16968. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16969. } else {
  16970. this.matrixWorld.copy( this.matrix );
  16971. }
  16972. this.matrixWorldNeedsUpdate = false;
  16973. force = true;
  16974. }
  16975. // update children
  16976. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16977. this.children[ i ].updateMatrixWorld( force );
  16978. }
  16979. };
  16980. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16981. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16982. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16983. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16984. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16985. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16986. /**
  16987. * @author zz85 / http://www.lab4games.net/zz85/blog
  16988. * Creates free form 2d path using series of points, lines or curves.
  16989. *
  16990. **/
  16991. THREE.Path = function ( points ) {
  16992. THREE.CurvePath.call(this);
  16993. this.actions = [];
  16994. if ( points ) {
  16995. this.fromPoints( points );
  16996. }
  16997. };
  16998. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16999. THREE.PathActions = {
  17000. MOVE_TO: 'moveTo',
  17001. LINE_TO: 'lineTo',
  17002. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17003. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17004. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17005. ARC: 'arc', // Circle
  17006. ELLIPSE: 'ellipse'
  17007. };
  17008. // TODO Clean up PATH API
  17009. // Create path using straight lines to connect all points
  17010. // - vectors: array of Vector2
  17011. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17012. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17013. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17014. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17015. };
  17016. };
  17017. // startPath() endPath()?
  17018. THREE.Path.prototype.moveTo = function ( x, y ) {
  17019. var args = Array.prototype.slice.call( arguments );
  17020. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17021. };
  17022. THREE.Path.prototype.lineTo = function ( x, y ) {
  17023. var args = Array.prototype.slice.call( arguments );
  17024. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17025. var x0 = lastargs[ lastargs.length - 2 ];
  17026. var y0 = lastargs[ lastargs.length - 1 ];
  17027. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17028. this.curves.push( curve );
  17029. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17030. };
  17031. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17032. var args = Array.prototype.slice.call( arguments );
  17033. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17034. var x0 = lastargs[ lastargs.length - 2 ];
  17035. var y0 = lastargs[ lastargs.length - 1 ];
  17036. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17037. new THREE.Vector2( aCPx, aCPy ),
  17038. new THREE.Vector2( aX, aY ) );
  17039. this.curves.push( curve );
  17040. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17041. };
  17042. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17043. aCP2x, aCP2y,
  17044. aX, aY ) {
  17045. var args = Array.prototype.slice.call( arguments );
  17046. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17047. var x0 = lastargs[ lastargs.length - 2 ];
  17048. var y0 = lastargs[ lastargs.length - 1 ];
  17049. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17050. new THREE.Vector2( aCP1x, aCP1y ),
  17051. new THREE.Vector2( aCP2x, aCP2y ),
  17052. new THREE.Vector2( aX, aY ) );
  17053. this.curves.push( curve );
  17054. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17055. };
  17056. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17057. var args = Array.prototype.slice.call( arguments );
  17058. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17059. var x0 = lastargs[ lastargs.length - 2 ];
  17060. var y0 = lastargs[ lastargs.length - 1 ];
  17061. //---
  17062. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17063. Array.prototype.push.apply( npts, pts );
  17064. var curve = new THREE.SplineCurve( npts );
  17065. this.curves.push( curve );
  17066. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17067. };
  17068. // FUTURE: Change the API or follow canvas API?
  17069. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17070. aStartAngle, aEndAngle, aClockwise ) {
  17071. var lastargs = this.actions[ this.actions.length - 1].args;
  17072. var x0 = lastargs[ lastargs.length - 2 ];
  17073. var y0 = lastargs[ lastargs.length - 1 ];
  17074. this.absarc(aX + x0, aY + y0, aRadius,
  17075. aStartAngle, aEndAngle, aClockwise );
  17076. };
  17077. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17078. aStartAngle, aEndAngle, aClockwise ) {
  17079. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17080. };
  17081. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17082. aStartAngle, aEndAngle, aClockwise ) {
  17083. var lastargs = this.actions[ this.actions.length - 1].args;
  17084. var x0 = lastargs[ lastargs.length - 2 ];
  17085. var y0 = lastargs[ lastargs.length - 1 ];
  17086. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17087. aStartAngle, aEndAngle, aClockwise );
  17088. };
  17089. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17090. aStartAngle, aEndAngle, aClockwise ) {
  17091. var args = Array.prototype.slice.call( arguments );
  17092. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17093. aStartAngle, aEndAngle, aClockwise );
  17094. this.curves.push( curve );
  17095. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17096. args.push(lastPoint.x);
  17097. args.push(lastPoint.y);
  17098. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17099. };
  17100. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17101. if ( ! divisions ) divisions = 40;
  17102. var points = [];
  17103. for ( var i = 0; i < divisions; i ++ ) {
  17104. points.push( this.getPoint( i / divisions ) );
  17105. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17106. }
  17107. // if ( closedPath ) {
  17108. //
  17109. // points.push( points[ 0 ] );
  17110. //
  17111. // }
  17112. return points;
  17113. };
  17114. /* Return an array of vectors based on contour of the path */
  17115. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17116. if (this.useSpacedPoints) {
  17117. console.log('tata');
  17118. return this.getSpacedPoints( divisions, closedPath );
  17119. }
  17120. divisions = divisions || 12;
  17121. var points = [];
  17122. var i, il, item, action, args;
  17123. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17124. laste, j,
  17125. t, tx, ty;
  17126. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17127. item = this.actions[ i ];
  17128. action = item.action;
  17129. args = item.args;
  17130. switch( action ) {
  17131. case THREE.PathActions.MOVE_TO:
  17132. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17133. break;
  17134. case THREE.PathActions.LINE_TO:
  17135. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17136. break;
  17137. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17138. cpx = args[ 2 ];
  17139. cpy = args[ 3 ];
  17140. cpx1 = args[ 0 ];
  17141. cpy1 = args[ 1 ];
  17142. if ( points.length > 0 ) {
  17143. laste = points[ points.length - 1 ];
  17144. cpx0 = laste.x;
  17145. cpy0 = laste.y;
  17146. } else {
  17147. laste = this.actions[ i - 1 ].args;
  17148. cpx0 = laste[ laste.length - 2 ];
  17149. cpy0 = laste[ laste.length - 1 ];
  17150. }
  17151. for ( j = 1; j <= divisions; j ++ ) {
  17152. t = j / divisions;
  17153. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17154. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17155. points.push( new THREE.Vector2( tx, ty ) );
  17156. }
  17157. break;
  17158. case THREE.PathActions.BEZIER_CURVE_TO:
  17159. cpx = args[ 4 ];
  17160. cpy = args[ 5 ];
  17161. cpx1 = args[ 0 ];
  17162. cpy1 = args[ 1 ];
  17163. cpx2 = args[ 2 ];
  17164. cpy2 = args[ 3 ];
  17165. if ( points.length > 0 ) {
  17166. laste = points[ points.length - 1 ];
  17167. cpx0 = laste.x;
  17168. cpy0 = laste.y;
  17169. } else {
  17170. laste = this.actions[ i - 1 ].args;
  17171. cpx0 = laste[ laste.length - 2 ];
  17172. cpy0 = laste[ laste.length - 1 ];
  17173. }
  17174. for ( j = 1; j <= divisions; j ++ ) {
  17175. t = j / divisions;
  17176. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17177. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17178. points.push( new THREE.Vector2( tx, ty ) );
  17179. }
  17180. break;
  17181. case THREE.PathActions.CSPLINE_THRU:
  17182. laste = this.actions[ i - 1 ].args;
  17183. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17184. var spts = [ last ];
  17185. var n = divisions * args[ 0 ].length;
  17186. spts = spts.concat( args[ 0 ] );
  17187. var spline = new THREE.SplineCurve( spts );
  17188. for ( j = 1; j <= n; j ++ ) {
  17189. points.push( spline.getPointAt( j / n ) ) ;
  17190. }
  17191. break;
  17192. case THREE.PathActions.ARC:
  17193. var aX = args[ 0 ], aY = args[ 1 ],
  17194. aRadius = args[ 2 ],
  17195. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17196. aClockwise = !!args[ 5 ];
  17197. var deltaAngle = aEndAngle - aStartAngle;
  17198. var angle;
  17199. var tdivisions = divisions * 2;
  17200. for ( j = 1; j <= tdivisions; j ++ ) {
  17201. t = j / tdivisions;
  17202. if ( ! aClockwise ) {
  17203. t = 1 - t;
  17204. }
  17205. angle = aStartAngle + t * deltaAngle;
  17206. tx = aX + aRadius * Math.cos( angle );
  17207. ty = aY + aRadius * Math.sin( angle );
  17208. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17209. points.push( new THREE.Vector2( tx, ty ) );
  17210. }
  17211. //console.log(points);
  17212. break;
  17213. case THREE.PathActions.ELLIPSE:
  17214. var aX = args[ 0 ], aY = args[ 1 ],
  17215. xRadius = args[ 2 ],
  17216. yRadius = args[ 3 ],
  17217. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17218. aClockwise = !!args[ 6 ];
  17219. var deltaAngle = aEndAngle - aStartAngle;
  17220. var angle;
  17221. var tdivisions = divisions * 2;
  17222. for ( j = 1; j <= tdivisions; j ++ ) {
  17223. t = j / tdivisions;
  17224. if ( ! aClockwise ) {
  17225. t = 1 - t;
  17226. }
  17227. angle = aStartAngle + t * deltaAngle;
  17228. tx = aX + xRadius * Math.cos( angle );
  17229. ty = aY + yRadius * Math.sin( angle );
  17230. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17231. points.push( new THREE.Vector2( tx, ty ) );
  17232. }
  17233. //console.log(points);
  17234. break;
  17235. } // end switch
  17236. }
  17237. // Normalize to remove the closing point by default.
  17238. var lastPoint = points[ points.length - 1];
  17239. var EPSILON = 0.0000000001;
  17240. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17241. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17242. points.splice( points.length - 1, 1);
  17243. if ( closedPath ) {
  17244. points.push( points[ 0 ] );
  17245. }
  17246. return points;
  17247. };
  17248. // Breaks path into shapes
  17249. THREE.Path.prototype.toShapes = function() {
  17250. var i, il, item, action, args;
  17251. var subPaths = [], lastPath = new THREE.Path();
  17252. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17253. item = this.actions[ i ];
  17254. args = item.args;
  17255. action = item.action;
  17256. if ( action == THREE.PathActions.MOVE_TO ) {
  17257. if ( lastPath.actions.length != 0 ) {
  17258. subPaths.push( lastPath );
  17259. lastPath = new THREE.Path();
  17260. }
  17261. }
  17262. lastPath[ action ].apply( lastPath, args );
  17263. }
  17264. if ( lastPath.actions.length != 0 ) {
  17265. subPaths.push( lastPath );
  17266. }
  17267. // console.log(subPaths);
  17268. if ( subPaths.length == 0 ) return [];
  17269. var tmpPath, tmpShape, shapes = [];
  17270. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17271. // console.log("Holes first", holesFirst);
  17272. if ( subPaths.length == 1) {
  17273. tmpPath = subPaths[0];
  17274. tmpShape = new THREE.Shape();
  17275. tmpShape.actions = tmpPath.actions;
  17276. tmpShape.curves = tmpPath.curves;
  17277. shapes.push( tmpShape );
  17278. return shapes;
  17279. };
  17280. if ( holesFirst ) {
  17281. tmpShape = new THREE.Shape();
  17282. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17283. tmpPath = subPaths[ i ];
  17284. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17285. tmpShape.actions = tmpPath.actions;
  17286. tmpShape.curves = tmpPath.curves;
  17287. shapes.push( tmpShape );
  17288. tmpShape = new THREE.Shape();
  17289. //console.log('cw', i);
  17290. } else {
  17291. tmpShape.holes.push( tmpPath );
  17292. //console.log('ccw', i);
  17293. }
  17294. }
  17295. } else {
  17296. // Shapes first
  17297. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17298. tmpPath = subPaths[ i ];
  17299. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17300. if ( tmpShape ) shapes.push( tmpShape );
  17301. tmpShape = new THREE.Shape();
  17302. tmpShape.actions = tmpPath.actions;
  17303. tmpShape.curves = tmpPath.curves;
  17304. } else {
  17305. tmpShape.holes.push( tmpPath );
  17306. }
  17307. }
  17308. shapes.push( tmpShape );
  17309. }
  17310. //console.log("shape", shapes);
  17311. return shapes;
  17312. };
  17313. /**
  17314. * @author zz85 / http://www.lab4games.net/zz85/blog
  17315. * Defines a 2d shape plane using paths.
  17316. **/
  17317. // STEP 1 Create a path.
  17318. // STEP 2 Turn path into shape.
  17319. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17320. // STEP 3a - Extract points from each shape, turn to vertices
  17321. // STEP 3b - Triangulate each shape, add faces.
  17322. THREE.Shape = function () {
  17323. THREE.Path.apply( this, arguments );
  17324. this.holes = [];
  17325. };
  17326. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17327. // Convenience method to return ExtrudeGeometry
  17328. THREE.Shape.prototype.extrude = function ( options ) {
  17329. var extruded = new THREE.ExtrudeGeometry( this, options );
  17330. return extruded;
  17331. };
  17332. // Convenience method to return ShapeGeometry
  17333. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17334. var geometry = new THREE.ShapeGeometry( this, options );
  17335. return geometry;
  17336. };
  17337. // Get points of holes
  17338. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17339. var i, il = this.holes.length, holesPts = [];
  17340. for ( i = 0; i < il; i ++ ) {
  17341. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17342. }
  17343. return holesPts;
  17344. };
  17345. // Get points of holes (spaced by regular distance)
  17346. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17347. var i, il = this.holes.length, holesPts = [];
  17348. for ( i = 0; i < il; i ++ ) {
  17349. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17350. }
  17351. return holesPts;
  17352. };
  17353. // Get points of shape and holes (keypoints based on segments parameter)
  17354. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17355. return {
  17356. shape: this.getTransformedPoints( divisions ),
  17357. holes: this.getPointsHoles( divisions )
  17358. };
  17359. };
  17360. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17361. if (this.useSpacedPoints) {
  17362. return this.extractAllSpacedPoints(divisions);
  17363. }
  17364. return this.extractAllPoints(divisions);
  17365. };
  17366. //
  17367. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17368. //
  17369. // return {
  17370. //
  17371. // shape: this.transform( bend, divisions ),
  17372. // holes: this.getPointsHoles( divisions, bend )
  17373. //
  17374. // };
  17375. //
  17376. // };
  17377. // Get points of shape and holes (spaced by regular distance)
  17378. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17379. return {
  17380. shape: this.getTransformedSpacedPoints( divisions ),
  17381. holes: this.getSpacedPointsHoles( divisions )
  17382. };
  17383. };
  17384. /**************************************************************
  17385. * Utils
  17386. **************************************************************/
  17387. THREE.Shape.Utils = {
  17388. /*
  17389. contour - array of vector2 for contour
  17390. holes - array of array of vector2
  17391. */
  17392. removeHoles: function ( contour, holes ) {
  17393. var shape = contour.concat(); // work on this shape
  17394. var allpoints = shape.concat();
  17395. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17396. var prevShapeVert, nextShapeVert,
  17397. prevHoleVert, nextHoleVert,
  17398. holeIndex, shapeIndex,
  17399. shapeId, shapeGroup,
  17400. h, h2,
  17401. hole, shortest, d,
  17402. p, pts1, pts2,
  17403. tmpShape1, tmpShape2,
  17404. tmpHole1, tmpHole2,
  17405. verts = [];
  17406. for ( h = 0; h < holes.length; h ++ ) {
  17407. hole = holes[ h ];
  17408. /*
  17409. shapeholes[ h ].concat(); // preserves original
  17410. holes.push( hole );
  17411. */
  17412. Array.prototype.push.apply( allpoints, hole );
  17413. shortest = Number.POSITIVE_INFINITY;
  17414. // Find the shortest pair of pts between shape and hole
  17415. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17416. // Using distanceToSquared() intead of distanceTo() should speed a little
  17417. // since running square roots operations are reduced.
  17418. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17419. pts1 = hole[ h2 ];
  17420. var dist = [];
  17421. for ( p = 0; p < shape.length; p++ ) {
  17422. pts2 = shape[ p ];
  17423. d = pts1.distanceToSquared( pts2 );
  17424. dist.push( d );
  17425. if ( d < shortest ) {
  17426. shortest = d;
  17427. holeIndex = h2;
  17428. shapeIndex = p;
  17429. }
  17430. }
  17431. }
  17432. //console.log("shortest", shortest, dist);
  17433. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17434. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17435. var areaapts = [
  17436. hole[ holeIndex ],
  17437. shape[ shapeIndex ],
  17438. shape[ prevShapeVert ]
  17439. ];
  17440. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17441. var areabpts = [
  17442. hole[ holeIndex ],
  17443. hole[ prevHoleVert ],
  17444. shape[ shapeIndex ]
  17445. ];
  17446. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17447. var shapeOffset = 1;
  17448. var holeOffset = -1;
  17449. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17450. shapeIndex += shapeOffset;
  17451. holeIndex += holeOffset;
  17452. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17453. shapeIndex %= shape.length;
  17454. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17455. holeIndex %= hole.length;
  17456. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17457. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17458. areaapts = [
  17459. hole[ holeIndex ],
  17460. shape[ shapeIndex ],
  17461. shape[ prevShapeVert ]
  17462. ];
  17463. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17464. areabpts = [
  17465. hole[ holeIndex ],
  17466. hole[ prevHoleVert ],
  17467. shape[ shapeIndex ]
  17468. ];
  17469. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17470. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17471. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17472. // In case areas are not correct.
  17473. //console.log("USE THIS");
  17474. shapeIndex = oldShapeIndex;
  17475. holeIndex = oldHoleIndex ;
  17476. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17477. shapeIndex %= shape.length;
  17478. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17479. holeIndex %= hole.length;
  17480. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17481. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17482. } else {
  17483. //console.log("USE THAT ")
  17484. }
  17485. tmpShape1 = shape.slice( 0, shapeIndex );
  17486. tmpShape2 = shape.slice( shapeIndex );
  17487. tmpHole1 = hole.slice( holeIndex );
  17488. tmpHole2 = hole.slice( 0, holeIndex );
  17489. // Should check orders here again?
  17490. var trianglea = [
  17491. hole[ holeIndex ],
  17492. shape[ shapeIndex ],
  17493. shape[ prevShapeVert ]
  17494. ];
  17495. var triangleb = [
  17496. hole[ holeIndex ] ,
  17497. hole[ prevHoleVert ],
  17498. shape[ shapeIndex ]
  17499. ];
  17500. verts.push( trianglea );
  17501. verts.push( triangleb );
  17502. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17503. }
  17504. return {
  17505. shape:shape, /* shape with no holes */
  17506. isolatedPts: verts, /* isolated faces */
  17507. allpoints: allpoints
  17508. }
  17509. },
  17510. triangulateShape: function ( contour, holes ) {
  17511. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17512. var shape = shapeWithoutHoles.shape,
  17513. allpoints = shapeWithoutHoles.allpoints,
  17514. isolatedPts = shapeWithoutHoles.isolatedPts;
  17515. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17516. // 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.
  17517. //console.log( "triangles",triangles, triangles.length );
  17518. //console.log( "allpoints",allpoints, allpoints.length );
  17519. var i, il, f, face,
  17520. key, index,
  17521. allPointsMap = {},
  17522. isolatedPointsMap = {};
  17523. // prepare all points map
  17524. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17525. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17526. if ( allPointsMap[ key ] !== undefined ) {
  17527. console.log( "Duplicate point", key );
  17528. }
  17529. allPointsMap[ key ] = i;
  17530. }
  17531. // check all face vertices against all points map
  17532. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17533. face = triangles[ i ];
  17534. for ( f = 0; f < 3; f ++ ) {
  17535. key = face[ f ].x + ":" + face[ f ].y;
  17536. index = allPointsMap[ key ];
  17537. if ( index !== undefined ) {
  17538. face[ f ] = index;
  17539. }
  17540. }
  17541. }
  17542. // check isolated points vertices against all points map
  17543. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17544. face = isolatedPts[ i ];
  17545. for ( f = 0; f < 3; f ++ ) {
  17546. key = face[ f ].x + ":" + face[ f ].y;
  17547. index = allPointsMap[ key ];
  17548. if ( index !== undefined ) {
  17549. face[ f ] = index;
  17550. }
  17551. }
  17552. }
  17553. return triangles.concat( isolatedPts );
  17554. }, // end triangulate shapes
  17555. /*
  17556. triangulate2 : function( pts, holes ) {
  17557. // For use with Poly2Tri.js
  17558. var allpts = pts.concat();
  17559. var shape = [];
  17560. for (var p in pts) {
  17561. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17562. }
  17563. var swctx = new js.poly2tri.SweepContext(shape);
  17564. for (var h in holes) {
  17565. var aHole = holes[h];
  17566. var newHole = []
  17567. for (i in aHole) {
  17568. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17569. allpts.push(aHole[i]);
  17570. }
  17571. swctx.AddHole(newHole);
  17572. }
  17573. var find;
  17574. var findIndexForPt = function (pt) {
  17575. find = new THREE.Vector2(pt.x, pt.y);
  17576. var p;
  17577. for (p=0, pl = allpts.length; p<pl; p++) {
  17578. if (allpts[p].equals(find)) return p;
  17579. }
  17580. return -1;
  17581. };
  17582. // triangulate
  17583. js.poly2tri.sweep.Triangulate(swctx);
  17584. var triangles = swctx.GetTriangles();
  17585. var tr ;
  17586. var facesPts = [];
  17587. for (var t in triangles) {
  17588. tr = triangles[t];
  17589. facesPts.push([
  17590. findIndexForPt(tr.GetPoint(0)),
  17591. findIndexForPt(tr.GetPoint(1)),
  17592. findIndexForPt(tr.GetPoint(2))
  17593. ]);
  17594. }
  17595. // console.log(facesPts);
  17596. // console.log("triangles", triangles.length, triangles);
  17597. // Returns array of faces with 3 element each
  17598. return facesPts;
  17599. },
  17600. */
  17601. isClockWise: function ( pts ) {
  17602. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17603. },
  17604. // Bezier Curves formulas obtained from
  17605. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17606. // Quad Bezier Functions
  17607. b2p0: function ( t, p ) {
  17608. var k = 1 - t;
  17609. return k * k * p;
  17610. },
  17611. b2p1: function ( t, p ) {
  17612. return 2 * ( 1 - t ) * t * p;
  17613. },
  17614. b2p2: function ( t, p ) {
  17615. return t * t * p;
  17616. },
  17617. b2: function ( t, p0, p1, p2 ) {
  17618. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17619. },
  17620. // Cubic Bezier Functions
  17621. b3p0: function ( t, p ) {
  17622. var k = 1 - t;
  17623. return k * k * k * p;
  17624. },
  17625. b3p1: function ( t, p ) {
  17626. var k = 1 - t;
  17627. return 3 * k * k * t * p;
  17628. },
  17629. b3p2: function ( t, p ) {
  17630. var k = 1 - t;
  17631. return 3 * k * t * t * p;
  17632. },
  17633. b3p3: function ( t, p ) {
  17634. return t * t * t * p;
  17635. },
  17636. b3: function ( t, p0, p1, p2, p3 ) {
  17637. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17638. }
  17639. };
  17640. /**
  17641. * @author mikael emtinger / http://gomo.se/
  17642. */
  17643. THREE.AnimationHandler = (function() {
  17644. var playing = [];
  17645. var library = {};
  17646. var that = {};
  17647. //--- update ---
  17648. that.update = function( deltaTimeMS ) {
  17649. for( var i = 0; i < playing.length; i ++ )
  17650. playing[ i ].update( deltaTimeMS );
  17651. };
  17652. //--- add ---
  17653. that.addToUpdate = function( animation ) {
  17654. if ( playing.indexOf( animation ) === -1 )
  17655. playing.push( animation );
  17656. };
  17657. //--- remove ---
  17658. that.removeFromUpdate = function( animation ) {
  17659. var index = playing.indexOf( animation );
  17660. if( index !== -1 )
  17661. playing.splice( index, 1 );
  17662. };
  17663. //--- add ---
  17664. that.add = function( data ) {
  17665. if ( library[ data.name ] !== undefined )
  17666. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17667. library[ data.name ] = data;
  17668. initData( data );
  17669. };
  17670. //--- get ---
  17671. that.get = function( name ) {
  17672. if ( typeof name === "string" ) {
  17673. if ( library[ name ] ) {
  17674. return library[ name ];
  17675. } else {
  17676. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17677. return null;
  17678. }
  17679. } else {
  17680. // todo: add simple tween library
  17681. }
  17682. };
  17683. //--- parse ---
  17684. that.parse = function( root ) {
  17685. // setup hierarchy
  17686. var hierarchy = [];
  17687. if ( root instanceof THREE.SkinnedMesh ) {
  17688. for( var b = 0; b < root.bones.length; b++ ) {
  17689. hierarchy.push( root.bones[ b ] );
  17690. }
  17691. } else {
  17692. parseRecurseHierarchy( root, hierarchy );
  17693. }
  17694. return hierarchy;
  17695. };
  17696. var parseRecurseHierarchy = function( root, hierarchy ) {
  17697. hierarchy.push( root );
  17698. for( var c = 0; c < root.children.length; c++ )
  17699. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17700. }
  17701. //--- init data ---
  17702. var initData = function( data ) {
  17703. if( data.initialized === true )
  17704. return;
  17705. // loop through all keys
  17706. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17707. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17708. // remove minus times
  17709. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17710. data.hierarchy[ h ].keys[ k ].time = 0;
  17711. // create quaternions
  17712. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17713. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17714. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17715. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17716. }
  17717. }
  17718. // prepare morph target keys
  17719. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17720. // get all used
  17721. var usedMorphTargets = {};
  17722. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17723. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17724. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17725. usedMorphTargets[ morphTargetName ] = -1;
  17726. }
  17727. }
  17728. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17729. // set all used on all frames
  17730. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17731. var influences = {};
  17732. for ( var morphTargetName in usedMorphTargets ) {
  17733. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17734. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17735. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17736. break;
  17737. }
  17738. }
  17739. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17740. influences[ morphTargetName ] = 0;
  17741. }
  17742. }
  17743. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17744. }
  17745. }
  17746. // remove all keys that are on the same time
  17747. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17748. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17749. data.hierarchy[ h ].keys.splice( k, 1 );
  17750. k --;
  17751. }
  17752. }
  17753. // set index
  17754. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17755. data.hierarchy[ h ].keys[ k ].index = k;
  17756. }
  17757. }
  17758. // JIT
  17759. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17760. data.JIT = {};
  17761. data.JIT.hierarchy = [];
  17762. for( var h = 0; h < data.hierarchy.length; h ++ )
  17763. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17764. // done
  17765. data.initialized = true;
  17766. };
  17767. // interpolation types
  17768. that.LINEAR = 0;
  17769. that.CATMULLROM = 1;
  17770. that.CATMULLROM_FORWARD = 2;
  17771. return that;
  17772. }());
  17773. /**
  17774. * @author mikael emtinger / http://gomo.se/
  17775. * @author mrdoob / http://mrdoob.com/
  17776. * @author alteredq / http://alteredqualia.com/
  17777. */
  17778. THREE.Animation = function ( root, name, interpolationType ) {
  17779. this.root = root;
  17780. this.data = THREE.AnimationHandler.get( name );
  17781. this.hierarchy = THREE.AnimationHandler.parse( root );
  17782. this.currentTime = 0;
  17783. this.timeScale = 1;
  17784. this.isPlaying = false;
  17785. this.isPaused = true;
  17786. this.loop = true;
  17787. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17788. this.points = [];
  17789. this.target = new THREE.Vector3();
  17790. };
  17791. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17792. if ( this.isPlaying === false ) {
  17793. this.isPlaying = true;
  17794. this.loop = loop !== undefined ? loop : true;
  17795. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17796. // reset key cache
  17797. var h, hl = this.hierarchy.length,
  17798. object;
  17799. for ( h = 0; h < hl; h ++ ) {
  17800. object = this.hierarchy[ h ];
  17801. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17802. object.useQuaternion = true;
  17803. }
  17804. object.matrixAutoUpdate = true;
  17805. if ( object.animationCache === undefined ) {
  17806. object.animationCache = {};
  17807. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17808. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17809. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17810. }
  17811. var prevKey = object.animationCache.prevKey;
  17812. var nextKey = object.animationCache.nextKey;
  17813. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17814. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17815. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17816. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17817. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17818. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17819. }
  17820. this.update( 0 );
  17821. }
  17822. this.isPaused = false;
  17823. THREE.AnimationHandler.addToUpdate( this );
  17824. };
  17825. THREE.Animation.prototype.pause = function() {
  17826. if ( this.isPaused === true ) {
  17827. THREE.AnimationHandler.addToUpdate( this );
  17828. } else {
  17829. THREE.AnimationHandler.removeFromUpdate( this );
  17830. }
  17831. this.isPaused = !this.isPaused;
  17832. };
  17833. THREE.Animation.prototype.stop = function() {
  17834. this.isPlaying = false;
  17835. this.isPaused = false;
  17836. THREE.AnimationHandler.removeFromUpdate( this );
  17837. };
  17838. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17839. // early out
  17840. if ( this.isPlaying === false ) return;
  17841. // vars
  17842. var types = [ "pos", "rot", "scl" ];
  17843. var type;
  17844. var scale;
  17845. var vector;
  17846. var prevXYZ, nextXYZ;
  17847. var prevKey, nextKey;
  17848. var object;
  17849. var animationCache;
  17850. var frame;
  17851. var JIThierarchy = this.data.JIT.hierarchy;
  17852. var currentTime, unloopedCurrentTime;
  17853. var currentPoint, forwardPoint, angle;
  17854. this.currentTime += deltaTimeMS * this.timeScale;
  17855. unloopedCurrentTime = this.currentTime;
  17856. currentTime = this.currentTime = this.currentTime % this.data.length;
  17857. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17858. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17859. object = this.hierarchy[ h ];
  17860. animationCache = object.animationCache;
  17861. // loop through pos/rot/scl
  17862. for ( var t = 0; t < 3; t ++ ) {
  17863. // get keys
  17864. type = types[ t ];
  17865. prevKey = animationCache.prevKey[ type ];
  17866. nextKey = animationCache.nextKey[ type ];
  17867. // switch keys?
  17868. if ( nextKey.time <= unloopedCurrentTime ) {
  17869. // did we loop?
  17870. if ( currentTime < unloopedCurrentTime ) {
  17871. if ( this.loop ) {
  17872. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17873. nextKey = this.getNextKeyWith( type, h, 1 );
  17874. while( nextKey.time < currentTime ) {
  17875. prevKey = nextKey;
  17876. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17877. }
  17878. } else {
  17879. this.stop();
  17880. return;
  17881. }
  17882. } else {
  17883. do {
  17884. prevKey = nextKey;
  17885. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17886. } while( nextKey.time < currentTime )
  17887. }
  17888. animationCache.prevKey[ type ] = prevKey;
  17889. animationCache.nextKey[ type ] = nextKey;
  17890. }
  17891. object.matrixAutoUpdate = true;
  17892. object.matrixWorldNeedsUpdate = true;
  17893. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17894. prevXYZ = prevKey[ type ];
  17895. nextXYZ = nextKey[ type ];
  17896. // check scale error
  17897. if ( scale < 0 || scale > 1 ) {
  17898. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17899. scale = scale < 0 ? 0 : 1;
  17900. }
  17901. // interpolate
  17902. if ( type === "pos" ) {
  17903. vector = object.position;
  17904. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17905. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17906. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17907. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17908. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17909. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17910. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17911. this.points[ 1 ] = prevXYZ;
  17912. this.points[ 2 ] = nextXYZ;
  17913. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17914. scale = scale * 0.33 + 0.33;
  17915. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17916. vector.x = currentPoint[ 0 ];
  17917. vector.y = currentPoint[ 1 ];
  17918. vector.z = currentPoint[ 2 ];
  17919. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17920. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17921. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17922. this.target.sub( vector );
  17923. this.target.y = 0;
  17924. this.target.normalize();
  17925. angle = Math.atan2( this.target.x, this.target.z );
  17926. object.rotation.set( 0, angle, 0 );
  17927. }
  17928. }
  17929. } else if ( type === "rot" ) {
  17930. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17931. } else if ( type === "scl" ) {
  17932. vector = object.scale;
  17933. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17934. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17935. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17936. }
  17937. }
  17938. }
  17939. };
  17940. // Catmull-Rom spline
  17941. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17942. var c = [], v3 = [],
  17943. point, intPoint, weight, w2, w3,
  17944. pa, pb, pc, pd;
  17945. point = ( points.length - 1 ) * scale;
  17946. intPoint = Math.floor( point );
  17947. weight = point - intPoint;
  17948. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17949. c[ 1 ] = intPoint;
  17950. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17951. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17952. pa = points[ c[ 0 ] ];
  17953. pb = points[ c[ 1 ] ];
  17954. pc = points[ c[ 2 ] ];
  17955. pd = points[ c[ 3 ] ];
  17956. w2 = weight * weight;
  17957. w3 = weight * w2;
  17958. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17959. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17960. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17961. return v3;
  17962. };
  17963. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17964. var v0 = ( p2 - p0 ) * 0.5,
  17965. v1 = ( p3 - p1 ) * 0.5;
  17966. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17967. };
  17968. // Get next key with
  17969. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17970. var keys = this.data.hierarchy[ h ].keys;
  17971. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17972. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17973. key = key < keys.length - 1 ? key : keys.length - 1;
  17974. } else {
  17975. key = key % keys.length;
  17976. }
  17977. for ( ; key < keys.length; key++ ) {
  17978. if ( keys[ key ][ type ] !== undefined ) {
  17979. return keys[ key ];
  17980. }
  17981. }
  17982. return this.data.hierarchy[ h ].keys[ 0 ];
  17983. };
  17984. // Get previous key with
  17985. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17986. var keys = this.data.hierarchy[ h ].keys;
  17987. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17988. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17989. key = key > 0 ? key : 0;
  17990. } else {
  17991. key = key >= 0 ? key : key + keys.length;
  17992. }
  17993. for ( ; key >= 0; key -- ) {
  17994. if ( keys[ key ][ type ] !== undefined ) {
  17995. return keys[ key ];
  17996. }
  17997. }
  17998. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17999. };
  18000. /**
  18001. * @author mikael emtinger / http://gomo.se/
  18002. * @author mrdoob / http://mrdoob.com/
  18003. * @author alteredq / http://alteredqualia.com/
  18004. * @author khang duong
  18005. * @author erik kitson
  18006. */
  18007. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18008. this.root = root;
  18009. this.data = THREE.AnimationHandler.get( data );
  18010. this.hierarchy = THREE.AnimationHandler.parse( root );
  18011. this.currentTime = 0;
  18012. this.timeScale = 0.001;
  18013. this.isPlaying = false;
  18014. this.isPaused = true;
  18015. this.loop = true;
  18016. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18017. // initialize to first keyframes
  18018. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18019. var keys = this.data.hierarchy[h].keys,
  18020. sids = this.data.hierarchy[h].sids,
  18021. obj = this.hierarchy[h];
  18022. if ( keys.length && sids ) {
  18023. for ( var s = 0; s < sids.length; s++ ) {
  18024. var sid = sids[ s ],
  18025. next = this.getNextKeyWith( sid, h, 0 );
  18026. if ( next ) {
  18027. next.apply( sid );
  18028. }
  18029. }
  18030. obj.matrixAutoUpdate = false;
  18031. this.data.hierarchy[h].node.updateMatrix();
  18032. obj.matrixWorldNeedsUpdate = true;
  18033. }
  18034. }
  18035. };
  18036. // Play
  18037. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18038. if( !this.isPlaying ) {
  18039. this.isPlaying = true;
  18040. this.loop = loop !== undefined ? loop : true;
  18041. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18042. this.startTimeMs = startTimeMS;
  18043. this.startTime = 10000000;
  18044. this.endTime = -this.startTime;
  18045. // reset key cache
  18046. var h, hl = this.hierarchy.length,
  18047. object,
  18048. node;
  18049. for ( h = 0; h < hl; h++ ) {
  18050. object = this.hierarchy[ h ];
  18051. node = this.data.hierarchy[ h ];
  18052. object.useQuaternion = true;
  18053. if ( node.animationCache === undefined ) {
  18054. node.animationCache = {};
  18055. node.animationCache.prevKey = null;
  18056. node.animationCache.nextKey = null;
  18057. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18058. }
  18059. var keys = this.data.hierarchy[h].keys;
  18060. if (keys.length) {
  18061. node.animationCache.prevKey = keys[ 0 ];
  18062. node.animationCache.nextKey = keys[ 1 ];
  18063. this.startTime = Math.min( keys[0].time, this.startTime );
  18064. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18065. }
  18066. }
  18067. this.update( 0 );
  18068. }
  18069. this.isPaused = false;
  18070. THREE.AnimationHandler.addToUpdate( this );
  18071. };
  18072. // Pause
  18073. THREE.KeyFrameAnimation.prototype.pause = function() {
  18074. if( this.isPaused ) {
  18075. THREE.AnimationHandler.addToUpdate( this );
  18076. } else {
  18077. THREE.AnimationHandler.removeFromUpdate( this );
  18078. }
  18079. this.isPaused = !this.isPaused;
  18080. };
  18081. // Stop
  18082. THREE.KeyFrameAnimation.prototype.stop = function() {
  18083. this.isPlaying = false;
  18084. this.isPaused = false;
  18085. THREE.AnimationHandler.removeFromUpdate( this );
  18086. // reset JIT matrix and remove cache
  18087. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18088. var obj = this.hierarchy[ h ];
  18089. var node = this.data.hierarchy[ h ];
  18090. if ( node.animationCache !== undefined ) {
  18091. var original = node.animationCache.originalMatrix;
  18092. if( obj instanceof THREE.Bone ) {
  18093. original.copy( obj.skinMatrix );
  18094. obj.skinMatrix = original;
  18095. } else {
  18096. original.copy( obj.matrix );
  18097. obj.matrix = original;
  18098. }
  18099. delete node.animationCache;
  18100. }
  18101. }
  18102. };
  18103. // Update
  18104. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18105. // early out
  18106. if( !this.isPlaying ) return;
  18107. // vars
  18108. var prevKey, nextKey;
  18109. var object;
  18110. var node;
  18111. var frame;
  18112. var JIThierarchy = this.data.JIT.hierarchy;
  18113. var currentTime, unloopedCurrentTime;
  18114. var looped;
  18115. // update
  18116. this.currentTime += deltaTimeMS * this.timeScale;
  18117. unloopedCurrentTime = this.currentTime;
  18118. currentTime = this.currentTime = this.currentTime % this.data.length;
  18119. // if looped around, the current time should be based on the startTime
  18120. if ( currentTime < this.startTimeMs ) {
  18121. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18122. }
  18123. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18124. looped = currentTime < unloopedCurrentTime;
  18125. if ( looped && !this.loop ) {
  18126. // Set the animation to the last keyframes and stop
  18127. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18128. var keys = this.data.hierarchy[h].keys,
  18129. sids = this.data.hierarchy[h].sids,
  18130. end = keys.length-1,
  18131. obj = this.hierarchy[h];
  18132. if ( keys.length ) {
  18133. for ( var s = 0; s < sids.length; s++ ) {
  18134. var sid = sids[ s ],
  18135. prev = this.getPrevKeyWith( sid, h, end );
  18136. if ( prev ) {
  18137. prev.apply( sid );
  18138. }
  18139. }
  18140. this.data.hierarchy[h].node.updateMatrix();
  18141. obj.matrixWorldNeedsUpdate = true;
  18142. }
  18143. }
  18144. this.stop();
  18145. return;
  18146. }
  18147. // check pre-infinity
  18148. if ( currentTime < this.startTime ) {
  18149. return;
  18150. }
  18151. // update
  18152. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18153. object = this.hierarchy[ h ];
  18154. node = this.data.hierarchy[ h ];
  18155. var keys = node.keys,
  18156. animationCache = node.animationCache;
  18157. // use JIT?
  18158. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18159. if( object instanceof THREE.Bone ) {
  18160. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18161. object.matrixWorldNeedsUpdate = false;
  18162. } else {
  18163. object.matrix = JIThierarchy[ h ][ frame ];
  18164. object.matrixWorldNeedsUpdate = true;
  18165. }
  18166. // use interpolation
  18167. } else if ( keys.length ) {
  18168. // make sure so original matrix and not JIT matrix is set
  18169. if ( this.JITCompile && animationCache ) {
  18170. if( object instanceof THREE.Bone ) {
  18171. object.skinMatrix = animationCache.originalMatrix;
  18172. } else {
  18173. object.matrix = animationCache.originalMatrix;
  18174. }
  18175. }
  18176. prevKey = animationCache.prevKey;
  18177. nextKey = animationCache.nextKey;
  18178. if ( prevKey && nextKey ) {
  18179. // switch keys?
  18180. if ( nextKey.time <= unloopedCurrentTime ) {
  18181. // did we loop?
  18182. if ( looped && this.loop ) {
  18183. prevKey = keys[ 0 ];
  18184. nextKey = keys[ 1 ];
  18185. while ( nextKey.time < currentTime ) {
  18186. prevKey = nextKey;
  18187. nextKey = keys[ prevKey.index + 1 ];
  18188. }
  18189. } else if ( !looped ) {
  18190. var lastIndex = keys.length - 1;
  18191. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18192. prevKey = nextKey;
  18193. nextKey = keys[ prevKey.index + 1 ];
  18194. }
  18195. }
  18196. animationCache.prevKey = prevKey;
  18197. animationCache.nextKey = nextKey;
  18198. }
  18199. if(nextKey.time >= currentTime)
  18200. prevKey.interpolate( nextKey, currentTime );
  18201. else
  18202. prevKey.interpolate( nextKey, nextKey.time);
  18203. }
  18204. this.data.hierarchy[h].node.updateMatrix();
  18205. object.matrixWorldNeedsUpdate = true;
  18206. }
  18207. }
  18208. // update JIT?
  18209. if ( this.JITCompile ) {
  18210. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18211. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18212. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18213. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18214. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18215. } else {
  18216. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18217. }
  18218. }
  18219. }
  18220. }
  18221. };
  18222. // Get next key with
  18223. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18224. var keys = this.data.hierarchy[ h ].keys;
  18225. key = key % keys.length;
  18226. for ( ; key < keys.length; key++ ) {
  18227. if ( keys[ key ].hasTarget( sid ) ) {
  18228. return keys[ key ];
  18229. }
  18230. }
  18231. return keys[ 0 ];
  18232. };
  18233. // Get previous key with
  18234. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18235. var keys = this.data.hierarchy[ h ].keys;
  18236. key = key >= 0 ? key : key + keys.length;
  18237. for ( ; key >= 0; key-- ) {
  18238. if ( keys[ key ].hasTarget( sid ) ) {
  18239. return keys[ key ];
  18240. }
  18241. }
  18242. return keys[ keys.length - 1 ];
  18243. };
  18244. /**
  18245. * Camera for rendering cube maps
  18246. * - renders scene into axis-aligned cube
  18247. *
  18248. * @author alteredq / http://alteredqualia.com/
  18249. */
  18250. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18251. THREE.Object3D.call( this );
  18252. var fov = 90, aspect = 1;
  18253. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18254. cameraPX.up.set( 0, -1, 0 );
  18255. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18256. this.add( cameraPX );
  18257. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18258. cameraNX.up.set( 0, -1, 0 );
  18259. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18260. this.add( cameraNX );
  18261. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18262. cameraPY.up.set( 0, 0, 1 );
  18263. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18264. this.add( cameraPY );
  18265. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18266. cameraNY.up.set( 0, 0, -1 );
  18267. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18268. this.add( cameraNY );
  18269. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18270. cameraPZ.up.set( 0, -1, 0 );
  18271. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18272. this.add( cameraPZ );
  18273. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18274. cameraNZ.up.set( 0, -1, 0 );
  18275. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18276. this.add( cameraNZ );
  18277. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18278. this.updateCubeMap = function ( renderer, scene ) {
  18279. var renderTarget = this.renderTarget;
  18280. var generateMipmaps = renderTarget.generateMipmaps;
  18281. renderTarget.generateMipmaps = false;
  18282. renderTarget.activeCubeFace = 0;
  18283. renderer.render( scene, cameraPX, renderTarget );
  18284. renderTarget.activeCubeFace = 1;
  18285. renderer.render( scene, cameraNX, renderTarget );
  18286. renderTarget.activeCubeFace = 2;
  18287. renderer.render( scene, cameraPY, renderTarget );
  18288. renderTarget.activeCubeFace = 3;
  18289. renderer.render( scene, cameraNY, renderTarget );
  18290. renderTarget.activeCubeFace = 4;
  18291. renderer.render( scene, cameraPZ, renderTarget );
  18292. renderTarget.generateMipmaps = generateMipmaps;
  18293. renderTarget.activeCubeFace = 5;
  18294. renderer.render( scene, cameraNZ, renderTarget );
  18295. };
  18296. };
  18297. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18298. /*
  18299. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18300. *
  18301. * A general perpose camera, for setting FOV, Lens Focal Length,
  18302. * and switching between perspective and orthographic views easily.
  18303. * Use this only if you do not wish to manage
  18304. * both a Orthographic and Perspective Camera
  18305. *
  18306. */
  18307. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18308. THREE.Camera.call( this );
  18309. this.fov = fov;
  18310. this.left = -width / 2;
  18311. this.right = width / 2
  18312. this.top = height / 2;
  18313. this.bottom = -height / 2;
  18314. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18315. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18316. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18317. this.zoom = 1;
  18318. this.toPerspective();
  18319. var aspect = width/height;
  18320. };
  18321. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18322. THREE.CombinedCamera.prototype.toPerspective = function () {
  18323. // Switches to the Perspective Camera
  18324. this.near = this.cameraP.near;
  18325. this.far = this.cameraP.far;
  18326. this.cameraP.fov = this.fov / this.zoom ;
  18327. this.cameraP.updateProjectionMatrix();
  18328. this.projectionMatrix = this.cameraP.projectionMatrix;
  18329. this.inPerspectiveMode = true;
  18330. this.inOrthographicMode = false;
  18331. };
  18332. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18333. // Switches to the Orthographic camera estimating viewport from Perspective
  18334. var fov = this.fov;
  18335. var aspect = this.cameraP.aspect;
  18336. var near = this.cameraP.near;
  18337. var far = this.cameraP.far;
  18338. // The size that we set is the mid plane of the viewing frustum
  18339. var hyperfocus = ( near + far ) / 2;
  18340. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18341. var planeHeight = 2 * halfHeight;
  18342. var planeWidth = planeHeight * aspect;
  18343. var halfWidth = planeWidth / 2;
  18344. halfHeight /= this.zoom;
  18345. halfWidth /= this.zoom;
  18346. this.cameraO.left = -halfWidth;
  18347. this.cameraO.right = halfWidth;
  18348. this.cameraO.top = halfHeight;
  18349. this.cameraO.bottom = -halfHeight;
  18350. // this.cameraO.left = -farHalfWidth;
  18351. // this.cameraO.right = farHalfWidth;
  18352. // this.cameraO.top = farHalfHeight;
  18353. // this.cameraO.bottom = -farHalfHeight;
  18354. // this.cameraO.left = this.left / this.zoom;
  18355. // this.cameraO.right = this.right / this.zoom;
  18356. // this.cameraO.top = this.top / this.zoom;
  18357. // this.cameraO.bottom = this.bottom / this.zoom;
  18358. this.cameraO.updateProjectionMatrix();
  18359. this.near = this.cameraO.near;
  18360. this.far = this.cameraO.far;
  18361. this.projectionMatrix = this.cameraO.projectionMatrix;
  18362. this.inPerspectiveMode = false;
  18363. this.inOrthographicMode = true;
  18364. };
  18365. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18366. this.cameraP.aspect = width / height;
  18367. this.left = -width / 2;
  18368. this.right = width / 2
  18369. this.top = height / 2;
  18370. this.bottom = -height / 2;
  18371. };
  18372. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18373. this.fov = fov;
  18374. if ( this.inPerspectiveMode ) {
  18375. this.toPerspective();
  18376. } else {
  18377. this.toOrthographic();
  18378. }
  18379. };
  18380. // For mantaining similar API with PerspectiveCamera
  18381. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18382. if ( this.inPerspectiveMode ) {
  18383. this.toPerspective();
  18384. } else {
  18385. this.toPerspective();
  18386. this.toOrthographic();
  18387. }
  18388. };
  18389. /*
  18390. * Uses Focal Length (in mm) to estimate and set FOV
  18391. * 35mm (fullframe) camera is used if frame size is not specified;
  18392. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18393. */
  18394. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18395. if ( frameHeight === undefined ) frameHeight = 24;
  18396. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18397. this.setFov( fov );
  18398. return fov;
  18399. };
  18400. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18401. this.zoom = zoom;
  18402. if ( this.inPerspectiveMode ) {
  18403. this.toPerspective();
  18404. } else {
  18405. this.toOrthographic();
  18406. }
  18407. };
  18408. THREE.CombinedCamera.prototype.toFrontView = function() {
  18409. this.rotation.x = 0;
  18410. this.rotation.y = 0;
  18411. this.rotation.z = 0;
  18412. // should we be modifing the matrix instead?
  18413. this.rotationAutoUpdate = false;
  18414. };
  18415. THREE.CombinedCamera.prototype.toBackView = function() {
  18416. this.rotation.x = 0;
  18417. this.rotation.y = Math.PI;
  18418. this.rotation.z = 0;
  18419. this.rotationAutoUpdate = false;
  18420. };
  18421. THREE.CombinedCamera.prototype.toLeftView = function() {
  18422. this.rotation.x = 0;
  18423. this.rotation.y = - Math.PI / 2;
  18424. this.rotation.z = 0;
  18425. this.rotationAutoUpdate = false;
  18426. };
  18427. THREE.CombinedCamera.prototype.toRightView = function() {
  18428. this.rotation.x = 0;
  18429. this.rotation.y = Math.PI / 2;
  18430. this.rotation.z = 0;
  18431. this.rotationAutoUpdate = false;
  18432. };
  18433. THREE.CombinedCamera.prototype.toTopView = function() {
  18434. this.rotation.x = - Math.PI / 2;
  18435. this.rotation.y = 0;
  18436. this.rotation.z = 0;
  18437. this.rotationAutoUpdate = false;
  18438. };
  18439. THREE.CombinedCamera.prototype.toBottomView = function() {
  18440. this.rotation.x = Math.PI / 2;
  18441. this.rotation.y = 0;
  18442. this.rotation.z = 0;
  18443. this.rotationAutoUpdate = false;
  18444. };
  18445. /**
  18446. * @author hughes
  18447. */
  18448. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18449. THREE.Geometry.call( this );
  18450. radius = radius || 50;
  18451. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18452. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18453. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18454. var i, uvs = [],
  18455. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18456. this.vertices.push(center);
  18457. uvs.push( centerUV );
  18458. for ( i = 0; i <= segments; i ++ ) {
  18459. var vertex = new THREE.Vector3();
  18460. var segment = thetaStart + i / segments * thetaLength;
  18461. vertex.x = radius * Math.cos( segment );
  18462. vertex.y = radius * Math.sin( segment );
  18463. this.vertices.push( vertex );
  18464. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18465. }
  18466. var n = new THREE.Vector3( 0, 0, -1 );
  18467. for ( i = 1; i <= segments; i ++ ) {
  18468. var v1 = i;
  18469. var v2 = i + 1 ;
  18470. var v3 = 0;
  18471. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18472. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18473. }
  18474. this.computeCentroids();
  18475. this.computeFaceNormals();
  18476. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18477. };
  18478. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18479. /**
  18480. * @author mrdoob / http://mrdoob.com/
  18481. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18482. */
  18483. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18484. THREE.Geometry.call( this );
  18485. var scope = this;
  18486. this.width = width;
  18487. this.height = height;
  18488. this.depth = depth;
  18489. this.widthSegments = widthSegments || 1;
  18490. this.heightSegments = heightSegments || 1;
  18491. this.depthSegments = depthSegments || 1;
  18492. var width_half = this.width / 2;
  18493. var height_half = this.height / 2;
  18494. var depth_half = this.depth / 2;
  18495. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18496. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18497. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18498. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18499. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18500. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18501. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18502. var w, ix, iy,
  18503. gridX = scope.widthSegments,
  18504. gridY = scope.heightSegments,
  18505. width_half = width / 2,
  18506. height_half = height / 2,
  18507. offset = scope.vertices.length;
  18508. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18509. w = 'z';
  18510. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18511. w = 'y';
  18512. gridY = scope.depthSegments;
  18513. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18514. w = 'x';
  18515. gridX = scope.depthSegments;
  18516. }
  18517. var gridX1 = gridX + 1,
  18518. gridY1 = gridY + 1,
  18519. segment_width = width / gridX,
  18520. segment_height = height / gridY,
  18521. normal = new THREE.Vector3();
  18522. normal[ w ] = depth > 0 ? 1 : - 1;
  18523. for ( iy = 0; iy < gridY1; iy ++ ) {
  18524. for ( ix = 0; ix < gridX1; ix ++ ) {
  18525. var vector = new THREE.Vector3();
  18526. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18527. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18528. vector[ w ] = depth;
  18529. scope.vertices.push( vector );
  18530. }
  18531. }
  18532. for ( iy = 0; iy < gridY; iy++ ) {
  18533. for ( ix = 0; ix < gridX; ix++ ) {
  18534. var a = ix + gridX1 * iy;
  18535. var b = ix + gridX1 * ( iy + 1 );
  18536. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18537. var d = ( ix + 1 ) + gridX1 * iy;
  18538. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18539. face.normal.copy( normal );
  18540. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18541. face.materialIndex = materialIndex;
  18542. scope.faces.push( face );
  18543. scope.faceVertexUvs[ 0 ].push( [
  18544. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18545. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18546. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18547. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18548. ] );
  18549. }
  18550. }
  18551. }
  18552. this.computeCentroids();
  18553. this.mergeVertices();
  18554. };
  18555. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18556. /**
  18557. * @author mrdoob / http://mrdoob.com/
  18558. */
  18559. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18560. THREE.Geometry.call( this );
  18561. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18562. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18563. height = height !== undefined ? height : 100;
  18564. var heightHalf = height / 2;
  18565. var segmentsX = radiusSegments || 8;
  18566. var segmentsY = heightSegments || 1;
  18567. var x, y, vertices = [], uvs = [];
  18568. for ( y = 0; y <= segmentsY; y ++ ) {
  18569. var verticesRow = [];
  18570. var uvsRow = [];
  18571. var v = y / segmentsY;
  18572. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18573. for ( x = 0; x <= segmentsX; x ++ ) {
  18574. var u = x / segmentsX;
  18575. var vertex = new THREE.Vector3();
  18576. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18577. vertex.y = - v * height + heightHalf;
  18578. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18579. this.vertices.push( vertex );
  18580. verticesRow.push( this.vertices.length - 1 );
  18581. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18582. }
  18583. vertices.push( verticesRow );
  18584. uvs.push( uvsRow );
  18585. }
  18586. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18587. var na, nb;
  18588. for ( x = 0; x < segmentsX; x ++ ) {
  18589. if ( radiusTop !== 0 ) {
  18590. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18591. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18592. } else {
  18593. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18594. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18595. }
  18596. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18597. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18598. for ( y = 0; y < segmentsY; y ++ ) {
  18599. var v1 = vertices[ y ][ x ];
  18600. var v2 = vertices[ y + 1 ][ x ];
  18601. var v3 = vertices[ y + 1 ][ x + 1 ];
  18602. var v4 = vertices[ y ][ x + 1 ];
  18603. var n1 = na.clone();
  18604. var n2 = na.clone();
  18605. var n3 = nb.clone();
  18606. var n4 = nb.clone();
  18607. var uv1 = uvs[ y ][ x ].clone();
  18608. var uv2 = uvs[ y + 1 ][ x ].clone();
  18609. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18610. var uv4 = uvs[ y ][ x + 1 ].clone();
  18611. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18612. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18613. }
  18614. }
  18615. // top cap
  18616. if ( !openEnded && radiusTop > 0 ) {
  18617. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18618. for ( x = 0; x < segmentsX; x ++ ) {
  18619. var v1 = vertices[ 0 ][ x ];
  18620. var v2 = vertices[ 0 ][ x + 1 ];
  18621. var v3 = this.vertices.length - 1;
  18622. var n1 = new THREE.Vector3( 0, 1, 0 );
  18623. var n2 = new THREE.Vector3( 0, 1, 0 );
  18624. var n3 = new THREE.Vector3( 0, 1, 0 );
  18625. var uv1 = uvs[ 0 ][ x ].clone();
  18626. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18627. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18628. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18629. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18630. }
  18631. }
  18632. // bottom cap
  18633. if ( !openEnded && radiusBottom > 0 ) {
  18634. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18635. for ( x = 0; x < segmentsX; x ++ ) {
  18636. var v1 = vertices[ y ][ x + 1 ];
  18637. var v2 = vertices[ y ][ x ];
  18638. var v3 = this.vertices.length - 1;
  18639. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18640. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18641. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18642. var uv1 = uvs[ y ][ x + 1 ].clone();
  18643. var uv2 = uvs[ y ][ x ].clone();
  18644. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18645. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18646. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18647. }
  18648. }
  18649. this.computeCentroids();
  18650. this.computeFaceNormals();
  18651. }
  18652. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18653. /**
  18654. * @author zz85 / http://www.lab4games.net/zz85/blog
  18655. *
  18656. * Creates extruded geometry from a path shape.
  18657. *
  18658. * parameters = {
  18659. *
  18660. * size: <float>, // size of the text
  18661. * height: <float>, // thickness to extrude text
  18662. * curveSegments: <int>, // number of points on the curves
  18663. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18664. * amount: <int>, // Amount
  18665. *
  18666. * bevelEnabled: <bool>, // turn on bevel
  18667. * bevelThickness: <float>, // how deep into text bevel goes
  18668. * bevelSize: <float>, // how far from text outline is bevel
  18669. * bevelSegments: <int>, // number of bevel layers
  18670. *
  18671. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18672. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18673. *
  18674. * material: <int> // material index for front and back faces
  18675. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18676. * uvGenerator: <Object> // object that provides UV generator functions
  18677. *
  18678. * }
  18679. **/
  18680. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18681. if ( typeof( shapes ) === "undefined" ) {
  18682. shapes = [];
  18683. return;
  18684. }
  18685. THREE.Geometry.call( this );
  18686. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18687. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18688. this.addShapeList( shapes, options );
  18689. this.computeCentroids();
  18690. this.computeFaceNormals();
  18691. // can't really use automatic vertex normals
  18692. // as then front and back sides get smoothed too
  18693. // should do separate smoothing just for sides
  18694. //this.computeVertexNormals();
  18695. //console.log( "took", ( Date.now() - startTime ) );
  18696. };
  18697. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18698. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18699. var sl = shapes.length;
  18700. for ( var s = 0; s < sl; s ++ ) {
  18701. var shape = shapes[ s ];
  18702. this.addShape( shape, options );
  18703. }
  18704. };
  18705. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18706. var amount = options.amount !== undefined ? options.amount : 100;
  18707. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18708. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18709. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18710. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18711. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18712. var steps = options.steps !== undefined ? options.steps : 1;
  18713. var extrudePath = options.extrudePath;
  18714. var extrudePts, extrudeByPath = false;
  18715. var material = options.material;
  18716. var extrudeMaterial = options.extrudeMaterial;
  18717. // Use default WorldUVGenerator if no UV generators are specified.
  18718. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18719. var shapebb = this.shapebb;
  18720. //shapebb = shape.getBoundingBox();
  18721. var splineTube, binormal, normal, position2;
  18722. if ( extrudePath ) {
  18723. extrudePts = extrudePath.getSpacedPoints( steps );
  18724. extrudeByPath = true;
  18725. bevelEnabled = false; // bevels not supported for path extrusion
  18726. // SETUP TNB variables
  18727. // Reuse TNB from TubeGeomtry for now.
  18728. // TODO1 - have a .isClosed in spline?
  18729. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18730. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18731. binormal = new THREE.Vector3();
  18732. normal = new THREE.Vector3();
  18733. position2 = new THREE.Vector3();
  18734. }
  18735. // Safeguards if bevels are not enabled
  18736. if ( ! bevelEnabled ) {
  18737. bevelSegments = 0;
  18738. bevelThickness = 0;
  18739. bevelSize = 0;
  18740. }
  18741. // Variables initalization
  18742. var ahole, h, hl; // looping of holes
  18743. var scope = this;
  18744. var bevelPoints = [];
  18745. var shapesOffset = this.vertices.length;
  18746. var shapePoints = shape.extractPoints( curveSegments );
  18747. var vertices = shapePoints.shape;
  18748. var holes = shapePoints.holes;
  18749. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18750. if ( reverse ) {
  18751. vertices = vertices.reverse();
  18752. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18753. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18754. ahole = holes[ h ];
  18755. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18756. holes[ h ] = ahole.reverse();
  18757. }
  18758. }
  18759. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18760. }
  18761. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18762. /* Vertices */
  18763. var contour = vertices; // vertices has all points but contour has only points of circumference
  18764. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18765. ahole = holes[ h ];
  18766. vertices = vertices.concat( ahole );
  18767. }
  18768. function scalePt2 ( pt, vec, size ) {
  18769. if ( !vec ) console.log( "die" );
  18770. return vec.clone().multiplyScalar( size ).add( pt );
  18771. }
  18772. var b, bs, t, z,
  18773. vert, vlen = vertices.length,
  18774. face, flen = faces.length,
  18775. cont, clen = contour.length;
  18776. // Find directions for point movement
  18777. var RAD_TO_DEGREES = 180 / Math.PI;
  18778. function getBevelVec( pt_i, pt_j, pt_k ) {
  18779. // Algorithm 2
  18780. return getBevelVec2( pt_i, pt_j, pt_k );
  18781. }
  18782. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18783. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18784. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18785. if ( anglea > angleb ) {
  18786. angleb += Math.PI * 2;
  18787. }
  18788. var anglec = ( anglea + angleb ) / 2;
  18789. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18790. var x = - Math.cos( anglec );
  18791. var y = - Math.sin( anglec );
  18792. var vec = new THREE.Vector2( x, y ); //.normalize();
  18793. return vec;
  18794. }
  18795. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18796. var a = THREE.ExtrudeGeometry.__v1,
  18797. b = THREE.ExtrudeGeometry.__v2,
  18798. v_hat = THREE.ExtrudeGeometry.__v3,
  18799. w_hat = THREE.ExtrudeGeometry.__v4,
  18800. p = THREE.ExtrudeGeometry.__v5,
  18801. q = THREE.ExtrudeGeometry.__v6,
  18802. v, w,
  18803. v_dot_w_hat, q_sub_p_dot_w_hat,
  18804. s, intersection;
  18805. // good reading for line-line intersection
  18806. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18807. // define a as vector j->i
  18808. // define b as vectot k->i
  18809. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18810. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18811. // get unit vectors
  18812. v = a.normalize();
  18813. w = b.normalize();
  18814. // normals from pt i
  18815. v_hat.set( -v.y, v.x );
  18816. w_hat.set( w.y, -w.x );
  18817. // pts from i
  18818. p.copy( pt_i ).add( v_hat );
  18819. q.copy( pt_i ).add( w_hat );
  18820. if ( p.equals( q ) ) {
  18821. //console.log("Warning: lines are straight");
  18822. return w_hat.clone();
  18823. }
  18824. // Points from j, k. helps prevents points cross overover most of the time
  18825. p.copy( pt_j ).add( v_hat );
  18826. q.copy( pt_k ).add( w_hat );
  18827. v_dot_w_hat = v.dot( w_hat );
  18828. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18829. // We should not reach these conditions
  18830. if ( v_dot_w_hat === 0 ) {
  18831. console.log( "Either infinite or no solutions!" );
  18832. if ( q_sub_p_dot_w_hat === 0 ) {
  18833. console.log( "Its finite solutions." );
  18834. } else {
  18835. console.log( "Too bad, no solutions." );
  18836. }
  18837. }
  18838. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18839. if ( s < 0 ) {
  18840. // in case of emergecy, revert to algorithm 1.
  18841. return getBevelVec1( pt_i, pt_j, pt_k );
  18842. }
  18843. intersection = v.multiplyScalar( s ).add( p );
  18844. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18845. }
  18846. var contourMovements = [];
  18847. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18848. if ( j === il ) j = 0;
  18849. if ( k === il ) k = 0;
  18850. // (j)---(i)---(k)
  18851. // console.log('i,j,k', i, j , k)
  18852. var pt_i = contour[ i ];
  18853. var pt_j = contour[ j ];
  18854. var pt_k = contour[ k ];
  18855. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18856. }
  18857. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18858. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18859. ahole = holes[ h ];
  18860. oneHoleMovements = [];
  18861. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18862. if ( j === il ) j = 0;
  18863. if ( k === il ) k = 0;
  18864. // (j)---(i)---(k)
  18865. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18866. }
  18867. holesMovements.push( oneHoleMovements );
  18868. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18869. }
  18870. // Loop bevelSegments, 1 for the front, 1 for the back
  18871. for ( b = 0; b < bevelSegments; b ++ ) {
  18872. //for ( b = bevelSegments; b > 0; b -- ) {
  18873. t = b / bevelSegments;
  18874. z = bevelThickness * ( 1 - t );
  18875. //z = bevelThickness * t;
  18876. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18877. //bs = bevelSize * t ; // linear
  18878. // contract shape
  18879. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18880. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18881. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18882. v( vert.x, vert.y, - z );
  18883. }
  18884. // expand holes
  18885. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18886. ahole = holes[ h ];
  18887. oneHoleMovements = holesMovements[ h ];
  18888. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18889. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18890. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18891. v( vert.x, vert.y, -z );
  18892. }
  18893. }
  18894. }
  18895. bs = bevelSize;
  18896. // Back facing vertices
  18897. for ( i = 0; i < vlen; i ++ ) {
  18898. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18899. if ( !extrudeByPath ) {
  18900. v( vert.x, vert.y, 0 );
  18901. } else {
  18902. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18903. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18904. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18905. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18906. v( position2.x, position2.y, position2.z );
  18907. }
  18908. }
  18909. // Add stepped vertices...
  18910. // Including front facing vertices
  18911. var s;
  18912. for ( s = 1; s <= steps; s ++ ) {
  18913. for ( i = 0; i < vlen; i ++ ) {
  18914. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18915. if ( !extrudeByPath ) {
  18916. v( vert.x, vert.y, amount / steps * s );
  18917. } else {
  18918. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18919. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18920. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18921. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18922. v( position2.x, position2.y, position2.z );
  18923. }
  18924. }
  18925. }
  18926. // Add bevel segments planes
  18927. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18928. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18929. t = b / bevelSegments;
  18930. z = bevelThickness * ( 1 - t );
  18931. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18932. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18933. // contract shape
  18934. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18935. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18936. v( vert.x, vert.y, amount + z );
  18937. }
  18938. // expand holes
  18939. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18940. ahole = holes[ h ];
  18941. oneHoleMovements = holesMovements[ h ];
  18942. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18943. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18944. if ( !extrudeByPath ) {
  18945. v( vert.x, vert.y, amount + z );
  18946. } else {
  18947. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18948. }
  18949. }
  18950. }
  18951. }
  18952. /* Faces */
  18953. // Top and bottom faces
  18954. buildLidFaces();
  18955. // Sides faces
  18956. buildSideFaces();
  18957. ///// Internal functions
  18958. function buildLidFaces() {
  18959. if ( bevelEnabled ) {
  18960. var layer = 0 ; // steps + 1
  18961. var offset = vlen * layer;
  18962. // Bottom faces
  18963. for ( i = 0; i < flen; i ++ ) {
  18964. face = faces[ i ];
  18965. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18966. }
  18967. layer = steps + bevelSegments * 2;
  18968. offset = vlen * layer;
  18969. // Top faces
  18970. for ( i = 0; i < flen; i ++ ) {
  18971. face = faces[ i ];
  18972. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18973. }
  18974. } else {
  18975. // Bottom faces
  18976. for ( i = 0; i < flen; i++ ) {
  18977. face = faces[ i ];
  18978. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18979. }
  18980. // Top faces
  18981. for ( i = 0; i < flen; i ++ ) {
  18982. face = faces[ i ];
  18983. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18984. }
  18985. }
  18986. }
  18987. // Create faces for the z-sides of the shape
  18988. function buildSideFaces() {
  18989. var layeroffset = 0;
  18990. sidewalls( contour, layeroffset );
  18991. layeroffset += contour.length;
  18992. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18993. ahole = holes[ h ];
  18994. sidewalls( ahole, layeroffset );
  18995. //, true
  18996. layeroffset += ahole.length;
  18997. }
  18998. }
  18999. function sidewalls( contour, layeroffset ) {
  19000. var j, k;
  19001. i = contour.length;
  19002. while ( --i >= 0 ) {
  19003. j = i;
  19004. k = i - 1;
  19005. if ( k < 0 ) k = contour.length - 1;
  19006. //console.log('b', i,j, i-1, k,vertices.length);
  19007. var s = 0, sl = steps + bevelSegments * 2;
  19008. for ( s = 0; s < sl; s ++ ) {
  19009. var slen1 = vlen * s;
  19010. var slen2 = vlen * ( s + 1 );
  19011. var a = layeroffset + j + slen1,
  19012. b = layeroffset + k + slen1,
  19013. c = layeroffset + k + slen2,
  19014. d = layeroffset + j + slen2;
  19015. f4( a, b, c, d, contour, s, sl, j, k );
  19016. }
  19017. }
  19018. }
  19019. function v( x, y, z ) {
  19020. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19021. }
  19022. function f3( a, b, c, isBottom ) {
  19023. a += shapesOffset;
  19024. b += shapesOffset;
  19025. c += shapesOffset;
  19026. // normal, color, material
  19027. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19028. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19029. scope.faceVertexUvs[ 0 ].push( uvs );
  19030. }
  19031. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19032. a += shapesOffset;
  19033. b += shapesOffset;
  19034. c += shapesOffset;
  19035. d += shapesOffset;
  19036. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19037. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19038. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19039. scope.faceVertexUvs[ 0 ].push( uvs );
  19040. }
  19041. };
  19042. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19043. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19044. var ax = geometry.vertices[ indexA ].x,
  19045. ay = geometry.vertices[ indexA ].y,
  19046. bx = geometry.vertices[ indexB ].x,
  19047. by = geometry.vertices[ indexB ].y,
  19048. cx = geometry.vertices[ indexC ].x,
  19049. cy = geometry.vertices[ indexC ].y;
  19050. return [
  19051. new THREE.Vector2( ax, ay ),
  19052. new THREE.Vector2( bx, by ),
  19053. new THREE.Vector2( cx, cy )
  19054. ];
  19055. },
  19056. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19057. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19058. },
  19059. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19060. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19061. contourIndex1, contourIndex2 ) {
  19062. var ax = geometry.vertices[ indexA ].x,
  19063. ay = geometry.vertices[ indexA ].y,
  19064. az = geometry.vertices[ indexA ].z,
  19065. bx = geometry.vertices[ indexB ].x,
  19066. by = geometry.vertices[ indexB ].y,
  19067. bz = geometry.vertices[ indexB ].z,
  19068. cx = geometry.vertices[ indexC ].x,
  19069. cy = geometry.vertices[ indexC ].y,
  19070. cz = geometry.vertices[ indexC ].z,
  19071. dx = geometry.vertices[ indexD ].x,
  19072. dy = geometry.vertices[ indexD ].y,
  19073. dz = geometry.vertices[ indexD ].z;
  19074. if ( Math.abs( ay - by ) < 0.01 ) {
  19075. return [
  19076. new THREE.Vector2( ax, 1 - az ),
  19077. new THREE.Vector2( bx, 1 - bz ),
  19078. new THREE.Vector2( cx, 1 - cz ),
  19079. new THREE.Vector2( dx, 1 - dz )
  19080. ];
  19081. } else {
  19082. return [
  19083. new THREE.Vector2( ay, 1 - az ),
  19084. new THREE.Vector2( by, 1 - bz ),
  19085. new THREE.Vector2( cy, 1 - cz ),
  19086. new THREE.Vector2( dy, 1 - dz )
  19087. ];
  19088. }
  19089. }
  19090. };
  19091. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19092. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19093. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19094. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19095. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19096. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19097. /**
  19098. * @author jonobr1 / http://jonobr1.com
  19099. *
  19100. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19101. * ExtrudeGeometry.
  19102. *
  19103. * parameters = {
  19104. *
  19105. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19106. *
  19107. * material: <int> // material index for front and back faces
  19108. * uvGenerator: <Object> // object that provides UV generator functions
  19109. *
  19110. * }
  19111. **/
  19112. THREE.ShapeGeometry = function ( shapes, options ) {
  19113. THREE.Geometry.call( this );
  19114. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19115. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19116. this.addShapeList( shapes, options );
  19117. this.computeCentroids();
  19118. this.computeFaceNormals();
  19119. };
  19120. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19121. /**
  19122. * Add an array of shapes to THREE.ShapeGeometry.
  19123. */
  19124. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19125. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19126. this.addShape( shapes[ i ], options );
  19127. }
  19128. return this;
  19129. };
  19130. /**
  19131. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19132. */
  19133. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19134. if ( options === undefined ) options = {};
  19135. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19136. var material = options.material;
  19137. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19138. var shapebb = this.shapebb;
  19139. //
  19140. var i, l, hole, s;
  19141. var shapesOffset = this.vertices.length;
  19142. var shapePoints = shape.extractPoints( curveSegments );
  19143. var vertices = shapePoints.shape;
  19144. var holes = shapePoints.holes;
  19145. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19146. if ( reverse ) {
  19147. vertices = vertices.reverse();
  19148. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19149. for ( i = 0, l = holes.length; i < l; i++ ) {
  19150. hole = holes[ i ];
  19151. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19152. holes[ i ] = hole.reverse();
  19153. }
  19154. }
  19155. reverse = false;
  19156. }
  19157. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19158. // Vertices
  19159. var contour = vertices;
  19160. for ( i = 0, l = holes.length; i < l; i++ ) {
  19161. hole = holes[ i ];
  19162. vertices = vertices.concat( hole );
  19163. }
  19164. //
  19165. var vert, vlen = vertices.length;
  19166. var face, flen = faces.length;
  19167. var cont, clen = contour.length;
  19168. for ( i = 0; i < vlen; i++ ) {
  19169. vert = vertices[ i ];
  19170. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19171. }
  19172. for ( i = 0; i < flen; i++ ) {
  19173. face = faces[ i ];
  19174. var a = face[ 0 ] + shapesOffset;
  19175. var b = face[ 1 ] + shapesOffset;
  19176. var c = face[ 2 ] + shapesOffset;
  19177. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19178. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19179. }
  19180. };
  19181. /**
  19182. * @author astrodud / http://astrodud.isgreat.org/
  19183. * @author zz85 / https://github.com/zz85
  19184. * @author bhouston / http://exocortex.com
  19185. */
  19186. // points - to create a closed torus, one must use a set of points
  19187. // like so: [ a, b, c, d, a ], see first is the same as last.
  19188. // segments - the number of circumference segments to create
  19189. // phiStart - the starting radian
  19190. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19191. // 2*pi is a closed lathe, less than 2PI is a portion.
  19192. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19193. THREE.Geometry.call( this );
  19194. segments = segments || 12;
  19195. phiStart = phiStart || 0;
  19196. phiLength = phiLength || 2 * Math.PI;
  19197. var inversePointLength = 1.0 / ( points.length - 1 );
  19198. var inverseSegments = 1.0 / segments;
  19199. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19200. var phi = phiStart + i * inverseSegments * phiLength;
  19201. var c = Math.cos( phi ),
  19202. s = Math.sin( phi );
  19203. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19204. var pt = points[ j ];
  19205. var vertex = new THREE.Vector3();
  19206. vertex.x = c * pt.x - s * pt.y;
  19207. vertex.y = s * pt.x + c * pt.y;
  19208. vertex.z = pt.z;
  19209. this.vertices.push( vertex );
  19210. }
  19211. }
  19212. var np = points.length;
  19213. for ( var i = 0, il = segments; i < il; i ++ ) {
  19214. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19215. var base = j + np * i;
  19216. var a = base;
  19217. var b = base + np;
  19218. var c = base + 1 + np;
  19219. var d = base + 1;
  19220. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19221. var u0 = i * inverseSegments;
  19222. var v0 = j * inversePointLength;
  19223. var u1 = u0 + inverseSegments;
  19224. var v1 = v0 + inversePointLength;
  19225. this.faceVertexUvs[ 0 ].push( [
  19226. new THREE.Vector2( u0, v0 ),
  19227. new THREE.Vector2( u1, v0 ),
  19228. new THREE.Vector2( u1, v1 ),
  19229. new THREE.Vector2( u0, v1 )
  19230. ] );
  19231. }
  19232. }
  19233. this.mergeVertices();
  19234. this.computeCentroids();
  19235. this.computeFaceNormals();
  19236. this.computeVertexNormals();
  19237. };
  19238. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19239. /**
  19240. * @author mrdoob / http://mrdoob.com/
  19241. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19242. */
  19243. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19244. THREE.Geometry.call( this );
  19245. this.width = width;
  19246. this.height = height;
  19247. this.widthSegments = widthSegments || 1;
  19248. this.heightSegments = heightSegments || 1;
  19249. var ix, iz;
  19250. var width_half = width / 2;
  19251. var height_half = height / 2;
  19252. var gridX = this.widthSegments;
  19253. var gridZ = this.heightSegments;
  19254. var gridX1 = gridX + 1;
  19255. var gridZ1 = gridZ + 1;
  19256. var segment_width = this.width / gridX;
  19257. var segment_height = this.height / gridZ;
  19258. var normal = new THREE.Vector3( 0, 0, 1 );
  19259. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19260. for ( ix = 0; ix < gridX1; ix ++ ) {
  19261. var x = ix * segment_width - width_half;
  19262. var y = iz * segment_height - height_half;
  19263. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19264. }
  19265. }
  19266. for ( iz = 0; iz < gridZ; iz ++ ) {
  19267. for ( ix = 0; ix < gridX; ix ++ ) {
  19268. var a = ix + gridX1 * iz;
  19269. var b = ix + gridX1 * ( iz + 1 );
  19270. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19271. var d = ( ix + 1 ) + gridX1 * iz;
  19272. var face = new THREE.Face4( a, b, c, d );
  19273. face.normal.copy( normal );
  19274. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19275. this.faces.push( face );
  19276. this.faceVertexUvs[ 0 ].push( [
  19277. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19278. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19279. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19280. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19281. ] );
  19282. }
  19283. }
  19284. this.computeCentroids();
  19285. };
  19286. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19287. /**
  19288. * @author Kaleb Murphy
  19289. */
  19290. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19291. THREE.Geometry.call( this );
  19292. innerRadius = innerRadius || 0;
  19293. outerRadius = outerRadius || 50;
  19294. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19295. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19296. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19297. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19298. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19299. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19300. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19301. var vertex = new THREE.Vector3();
  19302. var segment = thetaStart + o / thetaSegments * thetaLength;
  19303. vertex.x = radius * Math.cos( segment );
  19304. vertex.y = radius * Math.sin( segment );
  19305. this.vertices.push( vertex );
  19306. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19307. }
  19308. radius += radiusStep;
  19309. }
  19310. var n = new THREE.Vector3( 0, 0, 1 );
  19311. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19312. var thetaSegment = i * thetaSegments;
  19313. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19314. var segment = o + thetaSegment;
  19315. var v1 = segment + i;
  19316. var v2 = segment + thetaSegments + i;
  19317. var v3 = segment + thetaSegments + 1 + i;
  19318. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19319. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19320. v1 = segment + i;
  19321. v2 = segment + thetaSegments + 1 + i;
  19322. v3 = segment + 1 + i;
  19323. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19324. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19325. }
  19326. }
  19327. this.computeCentroids();
  19328. this.computeFaceNormals();
  19329. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19330. };
  19331. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19332. /**
  19333. * @author mrdoob / http://mrdoob.com/
  19334. */
  19335. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19336. THREE.Geometry.call( this );
  19337. this.radius = radius || 50;
  19338. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19339. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19340. phiStart = phiStart !== undefined ? phiStart : 0;
  19341. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19342. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19343. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19344. var x, y, vertices = [], uvs = [];
  19345. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19346. var verticesRow = [];
  19347. var uvsRow = [];
  19348. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19349. var u = x / this.widthSegments;
  19350. var v = y / this.heightSegments;
  19351. var vertex = new THREE.Vector3();
  19352. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19353. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19354. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19355. this.vertices.push( vertex );
  19356. verticesRow.push( this.vertices.length - 1 );
  19357. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19358. }
  19359. vertices.push( verticesRow );
  19360. uvs.push( uvsRow );
  19361. }
  19362. for ( y = 0; y < this.heightSegments; y ++ ) {
  19363. for ( x = 0; x < this.widthSegments; x ++ ) {
  19364. var v1 = vertices[ y ][ x + 1 ];
  19365. var v2 = vertices[ y ][ x ];
  19366. var v3 = vertices[ y + 1 ][ x ];
  19367. var v4 = vertices[ y + 1 ][ x + 1 ];
  19368. var n1 = this.vertices[ v1 ].clone().normalize();
  19369. var n2 = this.vertices[ v2 ].clone().normalize();
  19370. var n3 = this.vertices[ v3 ].clone().normalize();
  19371. var n4 = this.vertices[ v4 ].clone().normalize();
  19372. var uv1 = uvs[ y ][ x + 1 ].clone();
  19373. var uv2 = uvs[ y ][ x ].clone();
  19374. var uv3 = uvs[ y + 1 ][ x ].clone();
  19375. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19376. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19377. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19378. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19379. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19380. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19381. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19382. } else {
  19383. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19384. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19385. }
  19386. }
  19387. }
  19388. this.computeCentroids();
  19389. this.computeFaceNormals();
  19390. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19391. };
  19392. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19393. /**
  19394. * @author zz85 / http://www.lab4games.net/zz85/blog
  19395. * @author alteredq / http://alteredqualia.com/
  19396. *
  19397. * For creating 3D text geometry in three.js
  19398. *
  19399. * Text = 3D Text
  19400. *
  19401. * parameters = {
  19402. * size: <float>, // size of the text
  19403. * height: <float>, // thickness to extrude text
  19404. * curveSegments: <int>, // number of points on the curves
  19405. *
  19406. * font: <string>, // font name
  19407. * weight: <string>, // font weight (normal, bold)
  19408. * style: <string>, // font style (normal, italics)
  19409. *
  19410. * bevelEnabled: <bool>, // turn on bevel
  19411. * bevelThickness: <float>, // how deep into text bevel goes
  19412. * bevelSize: <float>, // how far from text outline is bevel
  19413. * }
  19414. *
  19415. */
  19416. /* Usage Examples
  19417. // TextGeometry wrapper
  19418. var text3d = new TextGeometry( text, options );
  19419. // Complete manner
  19420. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19421. var text3d = new ExtrudeGeometry( textShapes, options );
  19422. */
  19423. THREE.TextGeometry = function ( text, parameters ) {
  19424. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19425. // translate parameters to ExtrudeGeometry API
  19426. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19427. // defaults
  19428. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19429. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19430. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19431. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19432. };
  19433. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19434. /**
  19435. * @author oosmoxiecode
  19436. * @author mrdoob / http://mrdoob.com/
  19437. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19438. */
  19439. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19440. THREE.Geometry.call( this );
  19441. var scope = this;
  19442. this.radius = radius || 100;
  19443. this.tube = tube || 40;
  19444. this.radialSegments = radialSegments || 8;
  19445. this.tubularSegments = tubularSegments || 6;
  19446. this.arc = arc || Math.PI * 2;
  19447. var center = new THREE.Vector3(), uvs = [], normals = [];
  19448. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19449. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19450. var u = i / this.tubularSegments * this.arc;
  19451. var v = j / this.radialSegments * Math.PI * 2;
  19452. center.x = this.radius * Math.cos( u );
  19453. center.y = this.radius * Math.sin( u );
  19454. var vertex = new THREE.Vector3();
  19455. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19456. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19457. vertex.z = this.tube * Math.sin( v );
  19458. this.vertices.push( vertex );
  19459. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19460. normals.push( vertex.clone().sub( center ).normalize() );
  19461. }
  19462. }
  19463. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19464. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19465. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19466. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19467. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19468. var d = ( this.tubularSegments + 1 ) * j + i;
  19469. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19470. face.normal.add( normals[ a ] );
  19471. face.normal.add( normals[ b ] );
  19472. face.normal.add( normals[ c ] );
  19473. face.normal.add( normals[ d ] );
  19474. face.normal.normalize();
  19475. this.faces.push( face );
  19476. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19477. }
  19478. }
  19479. this.computeCentroids();
  19480. };
  19481. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19482. /**
  19483. * @author oosmoxiecode
  19484. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19485. */
  19486. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19487. THREE.Geometry.call( this );
  19488. var scope = this;
  19489. this.radius = radius || 100;
  19490. this.tube = tube || 40;
  19491. this.radialSegments = radialSegments || 64;
  19492. this.tubularSegments = tubularSegments || 8;
  19493. this.p = p || 2;
  19494. this.q = q || 3;
  19495. this.heightScale = heightScale || 1;
  19496. this.grid = new Array( this.radialSegments );
  19497. var tang = new THREE.Vector3();
  19498. var n = new THREE.Vector3();
  19499. var bitan = new THREE.Vector3();
  19500. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19501. this.grid[ i ] = new Array( this.tubularSegments );
  19502. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19503. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19504. var v = j / this.tubularSegments * 2 * Math.PI;
  19505. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19506. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19507. var cx, cy;
  19508. tang.subVectors( p2, p1 );
  19509. n.addVectors( p2, p1 );
  19510. bitan.crossVectors( tang, n );
  19511. n.crossVectors( bitan, tang );
  19512. bitan.normalize();
  19513. n.normalize();
  19514. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19515. cy = this.tube * Math.sin( v );
  19516. p1.x += cx * n.x + cy * bitan.x;
  19517. p1.y += cx * n.y + cy * bitan.y;
  19518. p1.z += cx * n.z + cy * bitan.z;
  19519. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19520. }
  19521. }
  19522. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19523. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19524. var ip = ( i + 1 ) % this.radialSegments;
  19525. var jp = ( j + 1 ) % this.tubularSegments;
  19526. var a = this.grid[ i ][ j ];
  19527. var b = this.grid[ ip ][ j ];
  19528. var c = this.grid[ ip ][ jp ];
  19529. var d = this.grid[ i ][ jp ];
  19530. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19531. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19532. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19533. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19534. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19535. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19536. }
  19537. }
  19538. this.computeCentroids();
  19539. this.computeFaceNormals();
  19540. this.computeVertexNormals();
  19541. function vert( x, y, z ) {
  19542. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19543. }
  19544. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19545. var cu = Math.cos( u );
  19546. var cv = Math.cos( v );
  19547. var su = Math.sin( u );
  19548. var quOverP = in_q / in_p * u;
  19549. var cs = Math.cos( quOverP );
  19550. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19551. var ty = radius * ( 2 + cs ) * su * 0.5;
  19552. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19553. return new THREE.Vector3( tx, ty, tz );
  19554. }
  19555. };
  19556. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19557. /**
  19558. * @author WestLangley / https://github.com/WestLangley
  19559. * @author zz85 / https://github.com/zz85
  19560. * @author miningold / https://github.com/miningold
  19561. *
  19562. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19563. *
  19564. * Creates a tube which extrudes along a 3d spline
  19565. *
  19566. * Uses parallel transport frames as described in
  19567. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19568. */
  19569. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19570. THREE.Geometry.call( this );
  19571. this.path = path;
  19572. this.segments = segments || 64;
  19573. this.radius = radius || 1;
  19574. this.radiusSegments = radiusSegments || 8;
  19575. this.closed = closed || false;
  19576. if ( debug ) this.debug = new THREE.Object3D();
  19577. this.grid = [];
  19578. var scope = this,
  19579. tangent,
  19580. normal,
  19581. binormal,
  19582. numpoints = this.segments + 1,
  19583. x, y, z,
  19584. tx, ty, tz,
  19585. u, v,
  19586. cx, cy,
  19587. pos, pos2 = new THREE.Vector3(),
  19588. i, j,
  19589. ip, jp,
  19590. a, b, c, d,
  19591. uva, uvb, uvc, uvd;
  19592. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19593. tangents = frames.tangents,
  19594. normals = frames.normals,
  19595. binormals = frames.binormals;
  19596. // proxy internals
  19597. this.tangents = tangents;
  19598. this.normals = normals;
  19599. this.binormals = binormals;
  19600. function vert( x, y, z ) {
  19601. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19602. }
  19603. // consruct the grid
  19604. for ( i = 0; i < numpoints; i++ ) {
  19605. this.grid[ i ] = [];
  19606. u = i / ( numpoints - 1 );
  19607. pos = path.getPointAt( u );
  19608. tangent = tangents[ i ];
  19609. normal = normals[ i ];
  19610. binormal = binormals[ i ];
  19611. if ( this.debug ) {
  19612. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19613. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19614. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19615. }
  19616. for ( j = 0; j < this.radiusSegments; j++ ) {
  19617. v = j / this.radiusSegments * 2 * Math.PI;
  19618. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19619. cy = this.radius * Math.sin( v );
  19620. pos2.copy( pos );
  19621. pos2.x += cx * normal.x + cy * binormal.x;
  19622. pos2.y += cx * normal.y + cy * binormal.y;
  19623. pos2.z += cx * normal.z + cy * binormal.z;
  19624. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19625. }
  19626. }
  19627. // construct the mesh
  19628. for ( i = 0; i < this.segments; i++ ) {
  19629. for ( j = 0; j < this.radiusSegments; j++ ) {
  19630. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19631. jp = (j + 1) % this.radiusSegments;
  19632. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19633. b = this.grid[ ip ][ j ];
  19634. c = this.grid[ ip ][ jp ];
  19635. d = this.grid[ i ][ jp ];
  19636. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19637. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19638. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19639. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19640. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19641. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19642. }
  19643. }
  19644. this.computeCentroids();
  19645. this.computeFaceNormals();
  19646. this.computeVertexNormals();
  19647. };
  19648. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19649. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19650. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19651. var tangent = new THREE.Vector3(),
  19652. normal = new THREE.Vector3(),
  19653. binormal = new THREE.Vector3(),
  19654. tangents = [],
  19655. normals = [],
  19656. binormals = [],
  19657. vec = new THREE.Vector3(),
  19658. mat = new THREE.Matrix4(),
  19659. numpoints = segments + 1,
  19660. theta,
  19661. epsilon = 0.0001,
  19662. smallest,
  19663. tx, ty, tz,
  19664. i, u, v;
  19665. // expose internals
  19666. this.tangents = tangents;
  19667. this.normals = normals;
  19668. this.binormals = binormals;
  19669. // compute the tangent vectors for each segment on the path
  19670. for ( i = 0; i < numpoints; i++ ) {
  19671. u = i / ( numpoints - 1 );
  19672. tangents[ i ] = path.getTangentAt( u );
  19673. tangents[ i ].normalize();
  19674. }
  19675. initialNormal3();
  19676. function initialNormal1(lastBinormal) {
  19677. // fixed start binormal. Has dangers of 0 vectors
  19678. normals[ 0 ] = new THREE.Vector3();
  19679. binormals[ 0 ] = new THREE.Vector3();
  19680. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19681. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19682. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19683. }
  19684. function initialNormal2() {
  19685. // This uses the Frenet-Serret formula for deriving binormal
  19686. var t2 = path.getTangentAt( epsilon );
  19687. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19688. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19689. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19690. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19691. }
  19692. function initialNormal3() {
  19693. // select an initial normal vector perpenicular to the first tangent vector,
  19694. // and in the direction of the smallest tangent xyz component
  19695. normals[ 0 ] = new THREE.Vector3();
  19696. binormals[ 0 ] = new THREE.Vector3();
  19697. smallest = Number.MAX_VALUE;
  19698. tx = Math.abs( tangents[ 0 ].x );
  19699. ty = Math.abs( tangents[ 0 ].y );
  19700. tz = Math.abs( tangents[ 0 ].z );
  19701. if ( tx <= smallest ) {
  19702. smallest = tx;
  19703. normal.set( 1, 0, 0 );
  19704. }
  19705. if ( ty <= smallest ) {
  19706. smallest = ty;
  19707. normal.set( 0, 1, 0 );
  19708. }
  19709. if ( tz <= smallest ) {
  19710. normal.set( 0, 0, 1 );
  19711. }
  19712. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19713. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19714. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19715. }
  19716. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19717. for ( i = 1; i < numpoints; i++ ) {
  19718. normals[ i ] = normals[ i-1 ].clone();
  19719. binormals[ i ] = binormals[ i-1 ].clone();
  19720. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19721. if ( vec.length() > epsilon ) {
  19722. vec.normalize();
  19723. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19724. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19725. }
  19726. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19727. }
  19728. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19729. if ( closed ) {
  19730. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19731. theta /= ( numpoints - 1 );
  19732. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19733. theta = -theta;
  19734. }
  19735. for ( i = 1; i < numpoints; i++ ) {
  19736. // twist a little...
  19737. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19738. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19739. }
  19740. }
  19741. };
  19742. /**
  19743. * @author clockworkgeek / https://github.com/clockworkgeek
  19744. * @author timothypratley / https://github.com/timothypratley
  19745. */
  19746. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19747. THREE.Geometry.call( this );
  19748. radius = radius || 1;
  19749. detail = detail || 0;
  19750. var that = this;
  19751. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19752. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19753. }
  19754. var midpoints = [], p = this.vertices;
  19755. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19756. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19757. }
  19758. this.mergeVertices();
  19759. // Apply radius
  19760. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19761. this.vertices[ i ].multiplyScalar( radius );
  19762. }
  19763. // Project vector onto sphere's surface
  19764. function prepare( vector ) {
  19765. var vertex = vector.normalize().clone();
  19766. vertex.index = that.vertices.push( vertex ) - 1;
  19767. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19768. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19769. var v = inclination( vector ) / Math.PI + 0.5;
  19770. vertex.uv = new THREE.Vector2( u, 1 - v );
  19771. return vertex;
  19772. }
  19773. // Approximate a curved face with recursively sub-divided triangles.
  19774. function make( v1, v2, v3, detail ) {
  19775. if ( detail < 1 ) {
  19776. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19777. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19778. face.normal = face.centroid.clone().normalize();
  19779. that.faces.push( face );
  19780. var azi = azimuth( face.centroid );
  19781. that.faceVertexUvs[ 0 ].push( [
  19782. correctUV( v1.uv, v1, azi ),
  19783. correctUV( v2.uv, v2, azi ),
  19784. correctUV( v3.uv, v3, azi )
  19785. ] );
  19786. } else {
  19787. detail -= 1;
  19788. // split triangle into 4 smaller triangles
  19789. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19790. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19791. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19792. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19793. }
  19794. }
  19795. function midpoint( v1, v2 ) {
  19796. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19797. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19798. var mid = midpoints[ v1.index ][ v2.index ];
  19799. if ( mid === undefined ) {
  19800. // generate mean point and project to surface with prepare()
  19801. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19802. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19803. );
  19804. }
  19805. return mid;
  19806. }
  19807. // Angle around the Y axis, counter-clockwise when looking from above.
  19808. function azimuth( vector ) {
  19809. return Math.atan2( vector.z, -vector.x );
  19810. }
  19811. // Angle above the XZ plane.
  19812. function inclination( vector ) {
  19813. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19814. }
  19815. // Texture fixing helper. Spheres have some odd behaviours.
  19816. function correctUV( uv, vector, azimuth ) {
  19817. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19818. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19819. return uv;
  19820. }
  19821. this.computeCentroids();
  19822. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19823. };
  19824. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19825. /**
  19826. * @author timothypratley / https://github.com/timothypratley
  19827. */
  19828. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19829. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19830. var vertices = [
  19831. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19832. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19833. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19834. ];
  19835. var faces = [
  19836. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19837. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19838. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19839. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19840. ];
  19841. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19842. };
  19843. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19844. /**
  19845. * @author timothypratley / https://github.com/timothypratley
  19846. */
  19847. THREE.OctahedronGeometry = function ( radius, detail ) {
  19848. var vertices = [
  19849. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19850. ];
  19851. var faces = [
  19852. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19853. ];
  19854. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19855. };
  19856. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19857. /**
  19858. * @author timothypratley / https://github.com/timothypratley
  19859. */
  19860. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19861. var vertices = [
  19862. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19863. ];
  19864. var faces = [
  19865. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19866. ];
  19867. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19868. };
  19869. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19870. /**
  19871. * @author zz85 / https://github.com/zz85
  19872. * Parametric Surfaces Geometry
  19873. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19874. *
  19875. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19876. *
  19877. */
  19878. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19879. THREE.Geometry.call( this );
  19880. var verts = this.vertices;
  19881. var faces = this.faces;
  19882. var uvs = this.faceVertexUvs[ 0 ];
  19883. useTris = (useTris === undefined) ? false : useTris;
  19884. var i, il, j, p;
  19885. var u, v;
  19886. var stackCount = stacks + 1;
  19887. var sliceCount = slices + 1;
  19888. for ( i = 0; i <= stacks; i ++ ) {
  19889. v = i / stacks;
  19890. for ( j = 0; j <= slices; j ++ ) {
  19891. u = j / slices;
  19892. p = func( u, v );
  19893. verts.push( p );
  19894. }
  19895. }
  19896. var a, b, c, d;
  19897. var uva, uvb, uvc, uvd;
  19898. for ( i = 0; i < stacks; i ++ ) {
  19899. for ( j = 0; j < slices; j ++ ) {
  19900. a = i * sliceCount + j;
  19901. b = i * sliceCount + j + 1;
  19902. c = (i + 1) * sliceCount + j;
  19903. d = (i + 1) * sliceCount + j + 1;
  19904. uva = new THREE.Vector2( j / slices, i / stacks );
  19905. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19906. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19907. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19908. if ( useTris ) {
  19909. faces.push( new THREE.Face3( a, b, c ) );
  19910. faces.push( new THREE.Face3( b, d, c ) );
  19911. uvs.push( [ uva, uvb, uvc ] );
  19912. uvs.push( [ uvb, uvd, uvc ] );
  19913. } else {
  19914. faces.push( new THREE.Face4( a, b, d, c ) );
  19915. uvs.push( [ uva, uvb, uvd, uvc ] );
  19916. }
  19917. }
  19918. }
  19919. // console.log(this);
  19920. // magic bullet
  19921. // var diff = this.mergeVertices();
  19922. // console.log('removed ', diff, ' vertices by merging');
  19923. this.computeCentroids();
  19924. this.computeFaceNormals();
  19925. this.computeVertexNormals();
  19926. };
  19927. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19928. /**
  19929. * @author qiao / https://github.com/qiao
  19930. * @fileoverview This is a convex hull generator using the incremental method.
  19931. * The complexity is O(n^2) where n is the number of vertices.
  19932. * O(nlogn) algorithms do exist, but they are much more complicated.
  19933. *
  19934. * Benchmark:
  19935. *
  19936. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19937. *
  19938. * Num Vertices Time(ms)
  19939. *
  19940. * 10 1
  19941. * 20 3
  19942. * 30 19
  19943. * 40 48
  19944. * 50 107
  19945. */
  19946. THREE.ConvexGeometry = function( vertices ) {
  19947. THREE.Geometry.call( this );
  19948. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19949. for ( var i = 3; i < vertices.length; i++ ) {
  19950. addPoint( i );
  19951. }
  19952. function addPoint( vertexId ) {
  19953. var vertex = vertices[ vertexId ].clone();
  19954. var mag = vertex.length();
  19955. vertex.x += mag * randomOffset();
  19956. vertex.y += mag * randomOffset();
  19957. vertex.z += mag * randomOffset();
  19958. var hole = [];
  19959. for ( var f = 0; f < faces.length; ) {
  19960. var face = faces[ f ];
  19961. // for each face, if the vertex can see it,
  19962. // then we try to add the face's edges into the hole.
  19963. if ( visible( face, vertex ) ) {
  19964. for ( var e = 0; e < 3; e++ ) {
  19965. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19966. var boundary = true;
  19967. // remove duplicated edges.
  19968. for ( var h = 0; h < hole.length; h++ ) {
  19969. if ( equalEdge( hole[ h ], edge ) ) {
  19970. hole[ h ] = hole[ hole.length - 1 ];
  19971. hole.pop();
  19972. boundary = false;
  19973. break;
  19974. }
  19975. }
  19976. if ( boundary ) {
  19977. hole.push( edge );
  19978. }
  19979. }
  19980. // remove faces[ f ]
  19981. faces[ f ] = faces[ faces.length - 1 ];
  19982. faces.pop();
  19983. } else { // not visible
  19984. f++;
  19985. }
  19986. }
  19987. // construct the new faces formed by the edges of the hole and the vertex
  19988. for ( var h = 0; h < hole.length; h++ ) {
  19989. faces.push( [
  19990. hole[ h ][ 0 ],
  19991. hole[ h ][ 1 ],
  19992. vertexId
  19993. ] );
  19994. }
  19995. }
  19996. /**
  19997. * Whether the face is visible from the vertex
  19998. */
  19999. function visible( face, vertex ) {
  20000. var va = vertices[ face[ 0 ] ];
  20001. var vb = vertices[ face[ 1 ] ];
  20002. var vc = vertices[ face[ 2 ] ];
  20003. var n = normal( va, vb, vc );
  20004. // distance from face to origin
  20005. var dist = n.dot( va );
  20006. return n.dot( vertex ) >= dist;
  20007. }
  20008. /**
  20009. * Face normal
  20010. */
  20011. function normal( va, vb, vc ) {
  20012. var cb = new THREE.Vector3();
  20013. var ab = new THREE.Vector3();
  20014. cb.subVectors( vc, vb );
  20015. ab.subVectors( va, vb );
  20016. cb.cross( ab );
  20017. cb.normalize();
  20018. return cb;
  20019. }
  20020. /**
  20021. * Detect whether two edges are equal.
  20022. * Note that when constructing the convex hull, two same edges can only
  20023. * be of the negative direction.
  20024. */
  20025. function equalEdge( ea, eb ) {
  20026. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20027. }
  20028. /**
  20029. * Create a random offset between -1e-6 and 1e-6.
  20030. */
  20031. function randomOffset() {
  20032. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20033. }
  20034. /**
  20035. * XXX: Not sure if this is the correct approach. Need someone to review.
  20036. */
  20037. function vertexUv( vertex ) {
  20038. var mag = vertex.length();
  20039. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20040. }
  20041. // Push vertices into `this.vertices`, skipping those inside the hull
  20042. var id = 0;
  20043. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20044. for ( var i = 0; i < faces.length; i++ ) {
  20045. var face = faces[ i ];
  20046. for ( var j = 0; j < 3; j++ ) {
  20047. if ( newId[ face[ j ] ] === undefined ) {
  20048. newId[ face[ j ] ] = id++;
  20049. this.vertices.push( vertices[ face[ j ] ] );
  20050. }
  20051. face[ j ] = newId[ face[ j ] ];
  20052. }
  20053. }
  20054. // Convert faces into instances of THREE.Face3
  20055. for ( var i = 0; i < faces.length; i++ ) {
  20056. this.faces.push( new THREE.Face3(
  20057. faces[ i ][ 0 ],
  20058. faces[ i ][ 1 ],
  20059. faces[ i ][ 2 ]
  20060. ) );
  20061. }
  20062. // Compute UVs
  20063. for ( var i = 0; i < this.faces.length; i++ ) {
  20064. var face = this.faces[ i ];
  20065. this.faceVertexUvs[ 0 ].push( [
  20066. vertexUv( this.vertices[ face.a ] ),
  20067. vertexUv( this.vertices[ face.b ] ),
  20068. vertexUv( this.vertices[ face.c ])
  20069. ] );
  20070. }
  20071. this.computeCentroids();
  20072. this.computeFaceNormals();
  20073. this.computeVertexNormals();
  20074. };
  20075. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20076. /**
  20077. * @author sroucheray / http://sroucheray.org/
  20078. * @author mrdoob / http://mrdoob.com/
  20079. */
  20080. THREE.AxisHelper = function ( size ) {
  20081. var geometry = new THREE.Geometry();
  20082. geometry.vertices.push(
  20083. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20084. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20085. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20086. );
  20087. geometry.colors.push(
  20088. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20089. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20090. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20091. );
  20092. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20093. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20094. };
  20095. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20096. /**
  20097. * @author WestLangley / http://github.com/WestLangley
  20098. * @author zz85 / https://github.com/zz85
  20099. * @author bhouston / https://exocortex.com
  20100. *
  20101. * Creates an arrow for visualizing directions
  20102. *
  20103. * Parameters:
  20104. * dir - Vector3
  20105. * origin - Vector3
  20106. * length - Number
  20107. * hex - color in hex value
  20108. */
  20109. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20110. THREE.Object3D.call( this );
  20111. if ( length === undefined ) length = 20;
  20112. if ( hex === undefined ) hex = 0xffff00;
  20113. var lineGeometry = new THREE.Geometry();
  20114. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20115. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20116. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20117. this.add( this.line );
  20118. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20119. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20120. this.cone.position.set( 0, 1, 0 );
  20121. this.add( this.cone );
  20122. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20123. this.setDirection( dir );
  20124. this.setLength( length );
  20125. };
  20126. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20127. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20128. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  20129. if ( d.y > 0.999 ) {
  20130. this.rotation.set( 0, 0, 0 );
  20131. } else if ( d.y < - 0.999 ) {
  20132. this.rotation.set( Math.PI, 0, 0 );
  20133. } else {
  20134. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  20135. var radians = Math.acos( d.y );
  20136. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  20137. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  20138. }
  20139. };
  20140. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20141. this.scale.set( length, length, length );
  20142. };
  20143. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20144. this.line.material.color.setHex( hex );
  20145. this.cone.material.color.setHex( hex );
  20146. };
  20147. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20148. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20149. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20150. /**
  20151. * @author alteredq / http://alteredqualia.com/
  20152. *
  20153. * - shows frustum, line of sight and up of the camera
  20154. * - suitable for fast updates
  20155. * - based on frustum visualization in lightgl.js shadowmap example
  20156. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20157. */
  20158. THREE.CameraHelper = function ( camera ) {
  20159. THREE.Line.call( this );
  20160. var scope = this;
  20161. this.geometry = new THREE.Geometry();
  20162. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20163. this.type = THREE.LinePieces;
  20164. this.matrixWorld = camera.matrixWorld;
  20165. this.matrixAutoUpdate = false;
  20166. this.pointMap = {};
  20167. // colors
  20168. var hexFrustum = 0xffaa00;
  20169. var hexCone = 0xff0000;
  20170. var hexUp = 0x00aaff;
  20171. var hexTarget = 0xffffff;
  20172. var hexCross = 0x333333;
  20173. // near
  20174. addLine( "n1", "n2", hexFrustum );
  20175. addLine( "n2", "n4", hexFrustum );
  20176. addLine( "n4", "n3", hexFrustum );
  20177. addLine( "n3", "n1", hexFrustum );
  20178. // far
  20179. addLine( "f1", "f2", hexFrustum );
  20180. addLine( "f2", "f4", hexFrustum );
  20181. addLine( "f4", "f3", hexFrustum );
  20182. addLine( "f3", "f1", hexFrustum );
  20183. // sides
  20184. addLine( "n1", "f1", hexFrustum );
  20185. addLine( "n2", "f2", hexFrustum );
  20186. addLine( "n3", "f3", hexFrustum );
  20187. addLine( "n4", "f4", hexFrustum );
  20188. // cone
  20189. addLine( "p", "n1", hexCone );
  20190. addLine( "p", "n2", hexCone );
  20191. addLine( "p", "n3", hexCone );
  20192. addLine( "p", "n4", hexCone );
  20193. // up
  20194. addLine( "u1", "u2", hexUp );
  20195. addLine( "u2", "u3", hexUp );
  20196. addLine( "u3", "u1", hexUp );
  20197. // target
  20198. addLine( "c", "t", hexTarget );
  20199. addLine( "p", "c", hexCross );
  20200. // cross
  20201. addLine( "cn1", "cn2", hexCross );
  20202. addLine( "cn3", "cn4", hexCross );
  20203. addLine( "cf1", "cf2", hexCross );
  20204. addLine( "cf3", "cf4", hexCross );
  20205. this.camera = camera;
  20206. function addLine( a, b, hex ) {
  20207. addPoint( a, hex );
  20208. addPoint( b, hex );
  20209. }
  20210. function addPoint( id, hex ) {
  20211. scope.geometry.vertices.push( new THREE.Vector3() );
  20212. scope.geometry.colors.push( new THREE.Color( hex ) );
  20213. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20214. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20215. }
  20216. this.update( camera );
  20217. };
  20218. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20219. THREE.CameraHelper.prototype.update = function () {
  20220. var scope = this;
  20221. var w = 1, h = 1;
  20222. // we need just camera projection matrix
  20223. // world matrix must be identity
  20224. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20225. // center / target
  20226. setPoint( "c", 0, 0, -1 );
  20227. setPoint( "t", 0, 0, 1 );
  20228. // near
  20229. setPoint( "n1", -w, -h, -1 );
  20230. setPoint( "n2", w, -h, -1 );
  20231. setPoint( "n3", -w, h, -1 );
  20232. setPoint( "n4", w, h, -1 );
  20233. // far
  20234. setPoint( "f1", -w, -h, 1 );
  20235. setPoint( "f2", w, -h, 1 );
  20236. setPoint( "f3", -w, h, 1 );
  20237. setPoint( "f4", w, h, 1 );
  20238. // up
  20239. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20240. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20241. setPoint( "u3", 0, h * 2, -1 );
  20242. // cross
  20243. setPoint( "cf1", -w, 0, 1 );
  20244. setPoint( "cf2", w, 0, 1 );
  20245. setPoint( "cf3", 0, -h, 1 );
  20246. setPoint( "cf4", 0, h, 1 );
  20247. setPoint( "cn1", -w, 0, -1 );
  20248. setPoint( "cn2", w, 0, -1 );
  20249. setPoint( "cn3", 0, -h, -1 );
  20250. setPoint( "cn4", 0, h, -1 );
  20251. function setPoint( point, x, y, z ) {
  20252. THREE.CameraHelper.__v.set( x, y, z );
  20253. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20254. var points = scope.pointMap[ point ];
  20255. if ( points !== undefined ) {
  20256. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20257. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20258. }
  20259. }
  20260. }
  20261. this.geometry.verticesNeedUpdate = true;
  20262. };
  20263. THREE.CameraHelper.__projector = new THREE.Projector();
  20264. THREE.CameraHelper.__v = new THREE.Vector3();
  20265. THREE.CameraHelper.__c = new THREE.Camera();
  20266. /**
  20267. * @author alteredq / http://alteredqualia.com/
  20268. *
  20269. * - shows directional light color, intensity, position, orientation and target
  20270. */
  20271. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20272. THREE.Object3D.call( this );
  20273. this.light = light;
  20274. // position
  20275. this.position = light.position;
  20276. // direction
  20277. this.direction = new THREE.Vector3();
  20278. this.direction.subVectors( light.target.position, light.position );
  20279. // color
  20280. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20281. this.color = light.color.clone();
  20282. this.color.multiplyScalar( intensity );
  20283. var hexColor = this.color.getHex();
  20284. // light helper
  20285. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20286. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20287. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20288. this.add( this.lightSphere );
  20289. this.lightSphere.userData.isGizmo = true;
  20290. this.lightSphere.userData.gizmoSubject = light;
  20291. this.lightSphere.userData.gizmoRoot = this;
  20292. // light target helper
  20293. this.targetSphere = null;
  20294. if ( light.target.userData.targetInverse !== undefined ) {
  20295. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20296. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20297. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20298. this.targetSphere.position = light.target.position;
  20299. this.targetSphere.userData.isGizmo = true;
  20300. this.targetSphere.userData.gizmoSubject = light.target;
  20301. this.targetSphere.userData.gizmoRoot = this.targetSphere;
  20302. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20303. var lineGeometry = new THREE.Geometry();
  20304. lineGeometry.vertices.push( this.position.clone() );
  20305. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20306. lineGeometry.computeLineDistances();
  20307. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20308. this.targetLine.userData.isGizmo = true;
  20309. }
  20310. //
  20311. this.userData.isGizmo = true;
  20312. }
  20313. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20314. THREE.DirectionalLightHelper.prototype.update = function () {
  20315. // update arrow orientation
  20316. // pointing from light to target
  20317. this.direction.subVectors( this.light.target.position, this.light.position );
  20318. // update arrow, spheres and line colors to light color * light intensity
  20319. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20320. this.color.copy( this.light.color );
  20321. this.color.multiplyScalar( intensity );
  20322. this.lightSphere.material.color.copy( this.color );
  20323. // Only update targetSphere and targetLine if available
  20324. if ( this.targetSphere !== null ) {
  20325. this.targetSphere.material.color.copy( this.color );
  20326. this.targetLine.material.color.copy( this.color );
  20327. // update target line vertices
  20328. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20329. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20330. this.targetLine.geometry.computeLineDistances();
  20331. this.targetLine.geometry.verticesNeedUpdate = true;
  20332. }
  20333. }
  20334. /**
  20335. * @author alteredq / http://alteredqualia.com/
  20336. *
  20337. * - shows hemisphere light intensity, sky and ground colors and directions
  20338. */
  20339. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20340. THREE.Object3D.call( this );
  20341. this.light = light;
  20342. // position
  20343. this.position = light.position;
  20344. //
  20345. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20346. // sky color
  20347. this.color = light.color.clone();
  20348. this.color.multiplyScalar( intensity );
  20349. var hexColor = this.color.getHex();
  20350. // ground color
  20351. this.groundColor = light.groundColor.clone();
  20352. this.groundColor.multiplyScalar( intensity );
  20353. var hexColorGround = this.groundColor.getHex();
  20354. // double colored light bulb
  20355. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20356. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20357. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20358. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20359. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20360. bulbGeometry.faces[ i ].materialIndex = 0;
  20361. }
  20362. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20363. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20364. }
  20365. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20366. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20367. // arrows for sky and ground light directions
  20368. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20369. this.lightArrow.rotation.x = Math.PI;
  20370. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20371. var joint = new THREE.Object3D();
  20372. joint.rotation.x = -Math.PI * 0.5;
  20373. joint.add( this.lightSphere );
  20374. joint.add( this.lightArrow );
  20375. joint.add( this.lightArrowGround );
  20376. this.add( joint );
  20377. //
  20378. this.lightSphere.userData.isGizmo = true;
  20379. this.lightSphere.userData.gizmoSubject = light;
  20380. this.lightSphere.userData.gizmoRoot = this;
  20381. //
  20382. this.userData.isGizmo = true;
  20383. //
  20384. this.target = new THREE.Vector3();
  20385. this.lookAt( this.target );
  20386. }
  20387. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20388. THREE.HemisphereLightHelper.prototype.update = function () {
  20389. // update sphere sky and ground colors to light color * light intensity
  20390. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20391. this.color.copy( this.light.color );
  20392. this.color.multiplyScalar( intensity );
  20393. this.groundColor.copy( this.light.groundColor );
  20394. this.groundColor.multiplyScalar( intensity );
  20395. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20396. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20397. this.lightArrow.setColor( this.color.getHex() );
  20398. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20399. this.lookAt( this.target );
  20400. }
  20401. /**
  20402. * @author alteredq / http://alteredqualia.com/
  20403. * @author mrdoob / http://mrdoob.com/
  20404. */
  20405. THREE.PointLightHelper = function ( light, sphereSize ) {
  20406. /*
  20407. // light helper
  20408. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20409. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20410. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20411. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20412. var d = light.distance;
  20413. if ( d === 0.0 ) {
  20414. this.lightDistance.visible = false;
  20415. } else {
  20416. this.lightDistance.scale.set( d, d, d );
  20417. }
  20418. this.add( this.lightSphere );
  20419. this.add( this.lightRays );
  20420. this.add( this.lightDistance );
  20421. */
  20422. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20423. var material = new THREE.MeshBasicMaterial( { color: light.color.getHex(), fog: false, wireframe: true } );
  20424. THREE.Mesh.call( this, geometry, material );
  20425. this.light = light;
  20426. this.position = light.position;
  20427. }
  20428. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20429. THREE.PointLightHelper.prototype.update = function () {
  20430. this.material.color.copy( this.light.color );
  20431. this.material.color.multiplyScalar( THREE.Math.clamp( this.light.intensity, 0, 1 ) );
  20432. /*
  20433. this.lightDistance.material.color.copy( this.color );
  20434. var d = this.light.distance;
  20435. if ( d === 0.0 ) {
  20436. this.lightDistance.visible = false;
  20437. } else {
  20438. this.lightDistance.visible = true;
  20439. this.lightDistance.scale.set( d, d, d );
  20440. }
  20441. */
  20442. }
  20443. /**
  20444. * @author alteredq / http://alteredqualia.com/
  20445. *
  20446. * - shows spot light color, intensity, position, orientation, light cone and target
  20447. */
  20448. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20449. THREE.Object3D.call( this );
  20450. this.light = light;
  20451. // position
  20452. this.position = light.position;
  20453. // direction
  20454. this.direction = new THREE.Vector3();
  20455. this.direction.subVectors( light.target.position, light.position );
  20456. // color
  20457. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20458. this.color = light.color.clone();
  20459. this.color.multiplyScalar( intensity );
  20460. var hexColor = this.color.getHex();
  20461. // light helper
  20462. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20463. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20464. var coneMatrix = new THREE.Matrix4();
  20465. coneMatrix.rotateX( -Math.PI/2 );
  20466. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20467. coneGeometry.applyMatrix( coneMatrix );
  20468. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20469. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20470. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20471. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20472. var coneLength = light.distance ? light.distance : 10000;
  20473. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20474. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20475. this.gyroscope = new THREE.Gyroscope();
  20476. this.gyroscope.add( this.lightSphere );
  20477. this.add( this.gyroscope );
  20478. this.add( this.lightCone );
  20479. this.lookAt( light.target.position );
  20480. this.lightSphere.userData.isGizmo = true;
  20481. this.lightSphere.userData.gizmoSubject = light;
  20482. this.lightSphere.userData.gizmoRoot = this;
  20483. // light target helper
  20484. this.targetSphere = null;
  20485. if ( light.target.userData.targetInverse !== undefined ) {
  20486. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20487. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20488. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20489. this.targetSphere.position = light.target.position;
  20490. this.targetSphere.userData.isGizmo = true;
  20491. this.targetSphere.userData.gizmoSubject = light.target;
  20492. this.targetSphere.userData.gizmoRoot = this.targetSphere;
  20493. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20494. var lineGeometry = new THREE.Geometry();
  20495. lineGeometry.vertices.push( this.position.clone() );
  20496. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20497. lineGeometry.computeLineDistances();
  20498. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20499. this.targetLine.userData.isGizmo = true;
  20500. }
  20501. //
  20502. this.userData.isGizmo = true;
  20503. }
  20504. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20505. THREE.SpotLightHelper.prototype.update = function () {
  20506. // update arrow orientation
  20507. // pointing from light to target
  20508. this.direction.subVectors( this.light.target.position, this.light.position );
  20509. // update light cone orientation and size
  20510. this.lookAt( this.light.target.position );
  20511. var coneLength = this.light.distance ? this.light.distance : 10000;
  20512. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20513. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20514. // update arrow, spheres and line colors to light color * light intensity
  20515. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20516. this.color.copy( this.light.color );
  20517. this.color.multiplyScalar( intensity );
  20518. this.lightSphere.material.color.copy( this.color );
  20519. this.lightCone.material.color.copy( this.color );
  20520. // Only update targetSphere and targetLine if available
  20521. if ( this.targetSphere !== null ) {
  20522. this.targetSphere.material.color.copy( this.color );
  20523. this.targetLine.material.color.copy( this.color );
  20524. // update target line vertices
  20525. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20526. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20527. this.targetLine.geometry.computeLineDistances();
  20528. this.targetLine.geometry.verticesNeedUpdate = true;
  20529. }
  20530. };
  20531. /**
  20532. * @author alteredq / http://alteredqualia.com/
  20533. */
  20534. THREE.ImmediateRenderObject = function () {
  20535. THREE.Object3D.call( this );
  20536. this.render = function ( renderCallback ) { };
  20537. };
  20538. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20539. /**
  20540. * @author mikael emtinger / http://gomo.se/
  20541. * @author alteredq / http://alteredqualia.com/
  20542. */
  20543. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20544. THREE.Object3D.call( this );
  20545. this.lensFlares = [];
  20546. this.positionScreen = new THREE.Vector3();
  20547. this.customUpdateCallback = undefined;
  20548. if( texture !== undefined ) {
  20549. this.add( texture, size, distance, blending, color );
  20550. }
  20551. };
  20552. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20553. /*
  20554. * Add: adds another flare
  20555. */
  20556. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20557. if( size === undefined ) size = -1;
  20558. if( distance === undefined ) distance = 0;
  20559. if( opacity === undefined ) opacity = 1;
  20560. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20561. if( blending === undefined ) blending = THREE.NormalBlending;
  20562. distance = Math.min( distance, Math.max( 0, distance ) );
  20563. this.lensFlares.push( { texture: texture, // THREE.Texture
  20564. size: size, // size in pixels (-1 = use texture.width)
  20565. distance: distance, // distance (0-1) from light source (0=at light source)
  20566. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20567. scale: 1, // scale
  20568. rotation: 1, // rotation
  20569. opacity: opacity, // opacity
  20570. color: color, // color
  20571. blending: blending } ); // blending
  20572. };
  20573. /*
  20574. * Update lens flares update positions on all flares based on the screen position
  20575. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20576. */
  20577. THREE.LensFlare.prototype.updateLensFlares = function () {
  20578. var f, fl = this.lensFlares.length;
  20579. var flare;
  20580. var vecX = -this.positionScreen.x * 2;
  20581. var vecY = -this.positionScreen.y * 2;
  20582. for( f = 0; f < fl; f ++ ) {
  20583. flare = this.lensFlares[ f ];
  20584. flare.x = this.positionScreen.x + vecX * flare.distance;
  20585. flare.y = this.positionScreen.y + vecY * flare.distance;
  20586. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20587. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20588. }
  20589. };
  20590. /**
  20591. * @author alteredq / http://alteredqualia.com/
  20592. */
  20593. THREE.MorphBlendMesh = function( geometry, material ) {
  20594. THREE.Mesh.call( this, geometry, material );
  20595. this.animationsMap = {};
  20596. this.animationsList = [];
  20597. // prepare default animation
  20598. // (all frames played together in 1 second)
  20599. var numFrames = this.geometry.morphTargets.length;
  20600. var name = "__default";
  20601. var startFrame = 0;
  20602. var endFrame = numFrames - 1;
  20603. var fps = numFrames / 1;
  20604. this.createAnimation( name, startFrame, endFrame, fps );
  20605. this.setAnimationWeight( name, 1 );
  20606. };
  20607. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20608. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20609. var animation = {
  20610. startFrame: start,
  20611. endFrame: end,
  20612. length: end - start + 1,
  20613. fps: fps,
  20614. duration: ( end - start ) / fps,
  20615. lastFrame: 0,
  20616. currentFrame: 0,
  20617. active: false,
  20618. time: 0,
  20619. direction: 1,
  20620. weight: 1,
  20621. directionBackwards: false,
  20622. mirroredLoop: false
  20623. };
  20624. this.animationsMap[ name ] = animation;
  20625. this.animationsList.push( animation );
  20626. };
  20627. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20628. var pattern = /([a-z]+)(\d+)/;
  20629. var firstAnimation, frameRanges = {};
  20630. var geometry = this.geometry;
  20631. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20632. var morph = geometry.morphTargets[ i ];
  20633. var chunks = morph.name.match( pattern );
  20634. if ( chunks && chunks.length > 1 ) {
  20635. var name = chunks[ 1 ];
  20636. var num = chunks[ 2 ];
  20637. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20638. var range = frameRanges[ name ];
  20639. if ( i < range.start ) range.start = i;
  20640. if ( i > range.end ) range.end = i;
  20641. if ( ! firstAnimation ) firstAnimation = name;
  20642. }
  20643. }
  20644. for ( var name in frameRanges ) {
  20645. var range = frameRanges[ name ];
  20646. this.createAnimation( name, range.start, range.end, fps );
  20647. }
  20648. this.firstAnimation = firstAnimation;
  20649. };
  20650. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20651. var animation = this.animationsMap[ name ];
  20652. if ( animation ) {
  20653. animation.direction = 1;
  20654. animation.directionBackwards = false;
  20655. }
  20656. };
  20657. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20658. var animation = this.animationsMap[ name ];
  20659. if ( animation ) {
  20660. animation.direction = -1;
  20661. animation.directionBackwards = true;
  20662. }
  20663. };
  20664. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20665. var animation = this.animationsMap[ name ];
  20666. if ( animation ) {
  20667. animation.fps = fps;
  20668. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20669. }
  20670. };
  20671. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20672. var animation = this.animationsMap[ name ];
  20673. if ( animation ) {
  20674. animation.duration = duration;
  20675. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20676. }
  20677. };
  20678. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20679. var animation = this.animationsMap[ name ];
  20680. if ( animation ) {
  20681. animation.weight = weight;
  20682. }
  20683. };
  20684. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20685. var animation = this.animationsMap[ name ];
  20686. if ( animation ) {
  20687. animation.time = time;
  20688. }
  20689. };
  20690. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20691. var time = 0;
  20692. var animation = this.animationsMap[ name ];
  20693. if ( animation ) {
  20694. time = animation.time;
  20695. }
  20696. return time;
  20697. };
  20698. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20699. var duration = -1;
  20700. var animation = this.animationsMap[ name ];
  20701. if ( animation ) {
  20702. duration = animation.duration;
  20703. }
  20704. return duration;
  20705. };
  20706. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20707. var animation = this.animationsMap[ name ];
  20708. if ( animation ) {
  20709. animation.time = 0;
  20710. animation.active = true;
  20711. } else {
  20712. console.warn( "animation[" + name + "] undefined" );
  20713. }
  20714. };
  20715. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20716. var animation = this.animationsMap[ name ];
  20717. if ( animation ) {
  20718. animation.active = false;
  20719. }
  20720. };
  20721. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20722. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20723. var animation = this.animationsList[ i ];
  20724. if ( ! animation.active ) continue;
  20725. var frameTime = animation.duration / animation.length;
  20726. animation.time += animation.direction * delta;
  20727. if ( animation.mirroredLoop ) {
  20728. if ( animation.time > animation.duration || animation.time < 0 ) {
  20729. animation.direction *= -1;
  20730. if ( animation.time > animation.duration ) {
  20731. animation.time = animation.duration;
  20732. animation.directionBackwards = true;
  20733. }
  20734. if ( animation.time < 0 ) {
  20735. animation.time = 0;
  20736. animation.directionBackwards = false;
  20737. }
  20738. }
  20739. } else {
  20740. animation.time = animation.time % animation.duration;
  20741. if ( animation.time < 0 ) animation.time += animation.duration;
  20742. }
  20743. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20744. var weight = animation.weight;
  20745. if ( keyframe !== animation.currentFrame ) {
  20746. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20747. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20748. this.morphTargetInfluences[ keyframe ] = 0;
  20749. animation.lastFrame = animation.currentFrame;
  20750. animation.currentFrame = keyframe;
  20751. }
  20752. var mix = ( animation.time % frameTime ) / frameTime;
  20753. if ( animation.directionBackwards ) mix = 1 - mix;
  20754. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20755. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20756. }
  20757. };
  20758. /**
  20759. * @author mikael emtinger / http://gomo.se/
  20760. * @author alteredq / http://alteredqualia.com/
  20761. */
  20762. THREE.LensFlarePlugin = function () {
  20763. var _gl, _renderer, _precision, _lensFlare = {};
  20764. this.init = function ( renderer ) {
  20765. _gl = renderer.context;
  20766. _renderer = renderer;
  20767. _precision = renderer.getPrecision();
  20768. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20769. _lensFlare.faces = new Uint16Array( 6 );
  20770. var i = 0;
  20771. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20772. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20773. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20774. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20775. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20776. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20777. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20778. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20779. i = 0;
  20780. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20781. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20782. // buffers
  20783. _lensFlare.vertexBuffer = _gl.createBuffer();
  20784. _lensFlare.elementBuffer = _gl.createBuffer();
  20785. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20786. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20787. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20788. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20789. // textures
  20790. _lensFlare.tempTexture = _gl.createTexture();
  20791. _lensFlare.occlusionTexture = _gl.createTexture();
  20792. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20793. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20794. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20795. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20796. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20797. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20798. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20799. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20800. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20801. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20802. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20803. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20804. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20805. _lensFlare.hasVertexTexture = false;
  20806. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20807. } else {
  20808. _lensFlare.hasVertexTexture = true;
  20809. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20810. }
  20811. _lensFlare.attributes = {};
  20812. _lensFlare.uniforms = {};
  20813. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20814. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20815. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20816. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20817. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20818. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20819. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20820. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20821. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20822. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20823. };
  20824. /*
  20825. * Render lens flares
  20826. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20827. * reads these back and calculates occlusion.
  20828. * Then _lensFlare.update_lensFlares() is called to re-position and
  20829. * update transparency of flares. Then they are rendered.
  20830. *
  20831. */
  20832. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20833. var flares = scene.__webglFlares,
  20834. nFlares = flares.length;
  20835. if ( ! nFlares ) return;
  20836. var tempPosition = new THREE.Vector3();
  20837. var invAspect = viewportHeight / viewportWidth,
  20838. halfViewportWidth = viewportWidth * 0.5,
  20839. halfViewportHeight = viewportHeight * 0.5;
  20840. var size = 16 / viewportHeight,
  20841. scale = new THREE.Vector2( size * invAspect, size );
  20842. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20843. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20844. var uniforms = _lensFlare.uniforms,
  20845. attributes = _lensFlare.attributes;
  20846. // set _lensFlare program and reset blending
  20847. _gl.useProgram( _lensFlare.program );
  20848. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20849. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20850. // loop through all lens flares to update their occlusion and positions
  20851. // setup gl and common used attribs/unforms
  20852. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20853. _gl.uniform1i( uniforms.map, 1 );
  20854. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20855. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20856. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20857. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20858. _gl.disable( _gl.CULL_FACE );
  20859. _gl.depthMask( false );
  20860. var i, j, jl, flare, sprite;
  20861. for ( i = 0; i < nFlares; i ++ ) {
  20862. size = 16 / viewportHeight;
  20863. scale.set( size * invAspect, size );
  20864. // calc object screen position
  20865. flare = flares[ i ];
  20866. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20867. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20868. tempPosition.applyProjection( camera.projectionMatrix );
  20869. // setup arrays for gl programs
  20870. screenPosition.copy( tempPosition )
  20871. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20872. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20873. // screen cull
  20874. if ( _lensFlare.hasVertexTexture || (
  20875. screenPositionPixels.x > 0 &&
  20876. screenPositionPixels.x < viewportWidth &&
  20877. screenPositionPixels.y > 0 &&
  20878. screenPositionPixels.y < viewportHeight ) ) {
  20879. // save current RGB to temp texture
  20880. _gl.activeTexture( _gl.TEXTURE1 );
  20881. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20882. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20883. // render pink quad
  20884. _gl.uniform1i( uniforms.renderType, 0 );
  20885. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20886. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20887. _gl.disable( _gl.BLEND );
  20888. _gl.enable( _gl.DEPTH_TEST );
  20889. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20890. // copy result to occlusionMap
  20891. _gl.activeTexture( _gl.TEXTURE0 );
  20892. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20893. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20894. // restore graphics
  20895. _gl.uniform1i( uniforms.renderType, 1 );
  20896. _gl.disable( _gl.DEPTH_TEST );
  20897. _gl.activeTexture( _gl.TEXTURE1 );
  20898. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20899. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20900. // update object positions
  20901. flare.positionScreen.copy( screenPosition )
  20902. if ( flare.customUpdateCallback ) {
  20903. flare.customUpdateCallback( flare );
  20904. } else {
  20905. flare.updateLensFlares();
  20906. }
  20907. // render flares
  20908. _gl.uniform1i( uniforms.renderType, 2 );
  20909. _gl.enable( _gl.BLEND );
  20910. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20911. sprite = flare.lensFlares[ j ];
  20912. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20913. screenPosition.x = sprite.x;
  20914. screenPosition.y = sprite.y;
  20915. screenPosition.z = sprite.z;
  20916. size = sprite.size * sprite.scale / viewportHeight;
  20917. scale.x = size * invAspect;
  20918. scale.y = size;
  20919. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20920. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20921. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20922. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20923. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20924. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20925. _renderer.setTexture( sprite.texture, 1 );
  20926. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20927. }
  20928. }
  20929. }
  20930. }
  20931. // restore gl
  20932. _gl.enable( _gl.CULL_FACE );
  20933. _gl.enable( _gl.DEPTH_TEST );
  20934. _gl.depthMask( true );
  20935. };
  20936. function createProgram ( shader, precision ) {
  20937. var program = _gl.createProgram();
  20938. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20939. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20940. var prefix = "precision " + precision + " float;\n";
  20941. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20942. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20943. _gl.compileShader( fragmentShader );
  20944. _gl.compileShader( vertexShader );
  20945. _gl.attachShader( program, fragmentShader );
  20946. _gl.attachShader( program, vertexShader );
  20947. _gl.linkProgram( program );
  20948. return program;
  20949. };
  20950. };
  20951. /**
  20952. * @author alteredq / http://alteredqualia.com/
  20953. */
  20954. THREE.ShadowMapPlugin = function () {
  20955. var _gl,
  20956. _renderer,
  20957. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20958. _frustum = new THREE.Frustum(),
  20959. _projScreenMatrix = new THREE.Matrix4(),
  20960. _min = new THREE.Vector3(),
  20961. _max = new THREE.Vector3(),
  20962. _matrixPosition = new THREE.Vector3();
  20963. this.init = function ( renderer ) {
  20964. _gl = renderer.context;
  20965. _renderer = renderer;
  20966. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20967. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20968. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20969. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20970. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20971. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20972. _depthMaterial._shadowPass = true;
  20973. _depthMaterialMorph._shadowPass = true;
  20974. _depthMaterialSkin._shadowPass = true;
  20975. _depthMaterialMorphSkin._shadowPass = true;
  20976. };
  20977. this.render = function ( scene, camera ) {
  20978. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20979. this.update( scene, camera );
  20980. };
  20981. this.update = function ( scene, camera ) {
  20982. var i, il, j, jl, n,
  20983. shadowMap, shadowMatrix, shadowCamera,
  20984. program, buffer, material,
  20985. webglObject, object, light,
  20986. renderList,
  20987. lights = [],
  20988. k = 0,
  20989. fog = null;
  20990. // set GL state for depth map
  20991. _gl.clearColor( 1, 1, 1, 1 );
  20992. _gl.disable( _gl.BLEND );
  20993. _gl.enable( _gl.CULL_FACE );
  20994. _gl.frontFace( _gl.CCW );
  20995. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20996. _gl.cullFace( _gl.FRONT );
  20997. } else {
  20998. _gl.cullFace( _gl.BACK );
  20999. }
  21000. _renderer.setDepthTest( true );
  21001. // preprocess lights
  21002. // - skip lights that are not casting shadows
  21003. // - create virtual lights for cascaded shadow maps
  21004. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21005. light = scene.__lights[ i ];
  21006. if ( ! light.castShadow ) continue;
  21007. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21008. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21009. var virtualLight;
  21010. if ( ! light.shadowCascadeArray[ n ] ) {
  21011. virtualLight = createVirtualLight( light, n );
  21012. virtualLight.originalCamera = camera;
  21013. var gyro = new THREE.Gyroscope();
  21014. gyro.position = light.shadowCascadeOffset;
  21015. gyro.add( virtualLight );
  21016. gyro.add( virtualLight.target );
  21017. camera.add( gyro );
  21018. light.shadowCascadeArray[ n ] = virtualLight;
  21019. console.log( "Created virtualLight", virtualLight );
  21020. } else {
  21021. virtualLight = light.shadowCascadeArray[ n ];
  21022. }
  21023. updateVirtualLight( light, n );
  21024. lights[ k ] = virtualLight;
  21025. k ++;
  21026. }
  21027. } else {
  21028. lights[ k ] = light;
  21029. k ++;
  21030. }
  21031. }
  21032. // render depth map
  21033. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21034. light = lights[ i ];
  21035. if ( ! light.shadowMap ) {
  21036. var shadowFilter = THREE.LinearFilter;
  21037. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21038. shadowFilter = THREE.NearestFilter;
  21039. }
  21040. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21041. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21042. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21043. light.shadowMatrix = new THREE.Matrix4();
  21044. }
  21045. if ( ! light.shadowCamera ) {
  21046. if ( light instanceof THREE.SpotLight ) {
  21047. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21048. } else if ( light instanceof THREE.DirectionalLight ) {
  21049. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21050. } else {
  21051. console.error( "Unsupported light type for shadow" );
  21052. continue;
  21053. }
  21054. scene.add( light.shadowCamera );
  21055. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21056. }
  21057. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21058. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21059. light.shadowCamera.add( light.cameraHelper );
  21060. }
  21061. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21062. updateShadowCamera( camera, light );
  21063. }
  21064. shadowMap = light.shadowMap;
  21065. shadowMatrix = light.shadowMatrix;
  21066. shadowCamera = light.shadowCamera;
  21067. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21068. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21069. shadowCamera.lookAt( _matrixPosition );
  21070. shadowCamera.updateMatrixWorld();
  21071. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21072. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21073. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21074. // compute shadow matrix
  21075. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21076. 0.0, 0.5, 0.0, 0.5,
  21077. 0.0, 0.0, 0.5, 0.5,
  21078. 0.0, 0.0, 0.0, 1.0 );
  21079. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21080. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21081. // update camera matrices and frustum
  21082. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21083. _frustum.setFromMatrix( _projScreenMatrix );
  21084. // render shadow map
  21085. _renderer.setRenderTarget( shadowMap );
  21086. _renderer.clear();
  21087. // set object matrices & frustum culling
  21088. renderList = scene.__webglObjects;
  21089. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21090. webglObject = renderList[ j ];
  21091. object = webglObject.object;
  21092. webglObject.render = false;
  21093. if ( object.visible && object.castShadow ) {
  21094. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21095. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21096. webglObject.render = true;
  21097. }
  21098. }
  21099. }
  21100. // render regular objects
  21101. var objectMaterial, useMorphing, useSkinning;
  21102. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21103. webglObject = renderList[ j ];
  21104. if ( webglObject.render ) {
  21105. object = webglObject.object;
  21106. buffer = webglObject.buffer;
  21107. // culling is overriden globally for all objects
  21108. // while rendering depth map
  21109. // need to deal with MeshFaceMaterial somehow
  21110. // in that case just use the first of material.materials for now
  21111. // (proper solution would require to break objects by materials
  21112. // similarly to regular rendering and then set corresponding
  21113. // depth materials per each chunk instead of just once per object)
  21114. objectMaterial = getObjectMaterial( object );
  21115. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21116. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21117. if ( object.customDepthMaterial ) {
  21118. material = object.customDepthMaterial;
  21119. } else if ( useSkinning ) {
  21120. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21121. } else if ( useMorphing ) {
  21122. material = _depthMaterialMorph;
  21123. } else {
  21124. material = _depthMaterial;
  21125. }
  21126. if ( buffer instanceof THREE.BufferGeometry ) {
  21127. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21128. } else {
  21129. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21130. }
  21131. }
  21132. }
  21133. // set matrices and render immediate objects
  21134. renderList = scene.__webglObjectsImmediate;
  21135. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21136. webglObject = renderList[ j ];
  21137. object = webglObject.object;
  21138. if ( object.visible && object.castShadow ) {
  21139. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21140. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21141. }
  21142. }
  21143. }
  21144. // restore GL state
  21145. var clearColor = _renderer.getClearColor(),
  21146. clearAlpha = _renderer.getClearAlpha();
  21147. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21148. _gl.enable( _gl.BLEND );
  21149. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21150. _gl.cullFace( _gl.BACK );
  21151. }
  21152. };
  21153. function createVirtualLight( light, cascade ) {
  21154. var virtualLight = new THREE.DirectionalLight();
  21155. virtualLight.isVirtual = true;
  21156. virtualLight.onlyShadow = true;
  21157. virtualLight.castShadow = true;
  21158. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21159. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21160. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21161. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21162. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21163. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21164. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21165. virtualLight.shadowDarkness = light.shadowDarkness;
  21166. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21167. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21168. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21169. virtualLight.pointsWorld = [];
  21170. virtualLight.pointsFrustum = [];
  21171. var pointsWorld = virtualLight.pointsWorld,
  21172. pointsFrustum = virtualLight.pointsFrustum;
  21173. for ( var i = 0; i < 8; i ++ ) {
  21174. pointsWorld[ i ] = new THREE.Vector3();
  21175. pointsFrustum[ i ] = new THREE.Vector3();
  21176. }
  21177. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21178. var farZ = light.shadowCascadeFarZ[ cascade ];
  21179. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21180. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21181. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21182. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21183. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21184. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21185. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21186. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21187. return virtualLight;
  21188. }
  21189. // Synchronize virtual light with the original light
  21190. function updateVirtualLight( light, cascade ) {
  21191. var virtualLight = light.shadowCascadeArray[ cascade ];
  21192. virtualLight.position.copy( light.position );
  21193. virtualLight.target.position.copy( light.target.position );
  21194. virtualLight.lookAt( virtualLight.target );
  21195. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21196. virtualLight.shadowDarkness = light.shadowDarkness;
  21197. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21198. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21199. var farZ = light.shadowCascadeFarZ[ cascade ];
  21200. var pointsFrustum = virtualLight.pointsFrustum;
  21201. pointsFrustum[ 0 ].z = nearZ;
  21202. pointsFrustum[ 1 ].z = nearZ;
  21203. pointsFrustum[ 2 ].z = nearZ;
  21204. pointsFrustum[ 3 ].z = nearZ;
  21205. pointsFrustum[ 4 ].z = farZ;
  21206. pointsFrustum[ 5 ].z = farZ;
  21207. pointsFrustum[ 6 ].z = farZ;
  21208. pointsFrustum[ 7 ].z = farZ;
  21209. }
  21210. // Fit shadow camera's ortho frustum to camera frustum
  21211. function updateShadowCamera( camera, light ) {
  21212. var shadowCamera = light.shadowCamera,
  21213. pointsFrustum = light.pointsFrustum,
  21214. pointsWorld = light.pointsWorld;
  21215. _min.set( Infinity, Infinity, Infinity );
  21216. _max.set( -Infinity, -Infinity, -Infinity );
  21217. for ( var i = 0; i < 8; i ++ ) {
  21218. var p = pointsWorld[ i ];
  21219. p.copy( pointsFrustum[ i ] );
  21220. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21221. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21222. if ( p.x < _min.x ) _min.x = p.x;
  21223. if ( p.x > _max.x ) _max.x = p.x;
  21224. if ( p.y < _min.y ) _min.y = p.y;
  21225. if ( p.y > _max.y ) _max.y = p.y;
  21226. if ( p.z < _min.z ) _min.z = p.z;
  21227. if ( p.z > _max.z ) _max.z = p.z;
  21228. }
  21229. shadowCamera.left = _min.x;
  21230. shadowCamera.right = _max.x;
  21231. shadowCamera.top = _max.y;
  21232. shadowCamera.bottom = _min.y;
  21233. // can't really fit near/far
  21234. //shadowCamera.near = _min.z;
  21235. //shadowCamera.far = _max.z;
  21236. shadowCamera.updateProjectionMatrix();
  21237. }
  21238. // For the moment just ignore objects that have multiple materials with different animation methods
  21239. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21240. function getObjectMaterial( object ) {
  21241. return object.material instanceof THREE.MeshFaceMaterial
  21242. ? object.material.materials[ 0 ]
  21243. : object.material;
  21244. };
  21245. };
  21246. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21247. /**
  21248. * @author mikael emtinger / http://gomo.se/
  21249. * @author alteredq / http://alteredqualia.com/
  21250. */
  21251. THREE.SpritePlugin = function () {
  21252. var _gl, _renderer, _precision, _sprite = {};
  21253. this.init = function ( renderer ) {
  21254. _gl = renderer.context;
  21255. _renderer = renderer;
  21256. _precision = renderer.getPrecision();
  21257. _sprite.vertices = new Float32Array( 8 + 8 );
  21258. _sprite.faces = new Uint16Array( 6 );
  21259. var i = 0;
  21260. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21261. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21262. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21263. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21264. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21265. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21266. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21267. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21268. i = 0;
  21269. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21270. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21271. _sprite.vertexBuffer = _gl.createBuffer();
  21272. _sprite.elementBuffer = _gl.createBuffer();
  21273. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21274. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21275. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21276. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21277. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21278. _sprite.attributes = {};
  21279. _sprite.uniforms = {};
  21280. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21281. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21282. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21283. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21284. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21285. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21286. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21287. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21288. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21289. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21290. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21291. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21292. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21293. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21294. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21295. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21296. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21297. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21298. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21299. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21300. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21301. };
  21302. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21303. var sprites = scene.__webglSprites,
  21304. nSprites = sprites.length;
  21305. if ( ! nSprites ) return;
  21306. var attributes = _sprite.attributes,
  21307. uniforms = _sprite.uniforms;
  21308. var invAspect = viewportHeight / viewportWidth;
  21309. var halfViewportWidth = viewportWidth * 0.5,
  21310. halfViewportHeight = viewportHeight * 0.5;
  21311. // setup gl
  21312. _gl.useProgram( _sprite.program );
  21313. _gl.enableVertexAttribArray( attributes.position );
  21314. _gl.enableVertexAttribArray( attributes.uv );
  21315. _gl.disable( _gl.CULL_FACE );
  21316. _gl.enable( _gl.BLEND );
  21317. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21318. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21319. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21320. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21321. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21322. _gl.activeTexture( _gl.TEXTURE0 );
  21323. _gl.uniform1i( uniforms.map, 0 );
  21324. var oldFogType = 0;
  21325. var sceneFogType = 0;
  21326. var fog = scene.fog;
  21327. if ( fog ) {
  21328. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21329. if ( fog instanceof THREE.Fog ) {
  21330. _gl.uniform1f( uniforms.fogNear, fog.near );
  21331. _gl.uniform1f( uniforms.fogFar, fog.far );
  21332. _gl.uniform1i( uniforms.fogType, 1 );
  21333. oldFogType = 1;
  21334. sceneFogType = 1;
  21335. } else if ( fog instanceof THREE.FogExp2 ) {
  21336. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21337. _gl.uniform1i( uniforms.fogType, 2 );
  21338. oldFogType = 2;
  21339. sceneFogType = 2;
  21340. }
  21341. } else {
  21342. _gl.uniform1i( uniforms.fogType, 0 );
  21343. oldFogType = 0;
  21344. sceneFogType = 0;
  21345. }
  21346. // update positions and sort
  21347. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21348. for( i = 0; i < nSprites; i ++ ) {
  21349. sprite = sprites[ i ];
  21350. material = sprite.material;
  21351. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21352. if ( ! material.useScreenCoordinates ) {
  21353. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21354. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21355. } else {
  21356. sprite.z = - sprite.position.z;
  21357. }
  21358. }
  21359. sprites.sort( painterSortStable );
  21360. // render all sprites
  21361. for( i = 0; i < nSprites; i ++ ) {
  21362. sprite = sprites[ i ];
  21363. material = sprite.material;
  21364. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21365. if ( material.map && material.map.image && material.map.image.width ) {
  21366. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21367. if ( material.useScreenCoordinates === true ) {
  21368. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21369. _gl.uniform3f(
  21370. uniforms.screenPosition,
  21371. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21372. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21373. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21374. );
  21375. scale[ 0 ] = _renderer.devicePixelRatio;
  21376. scale[ 1 ] = _renderer.devicePixelRatio;
  21377. } else {
  21378. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21379. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21380. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21381. scale[ 0 ] = 1;
  21382. scale[ 1 ] = 1;
  21383. }
  21384. if ( scene.fog && material.fog ) {
  21385. fogType = sceneFogType;
  21386. } else {
  21387. fogType = 0;
  21388. }
  21389. if ( oldFogType !== fogType ) {
  21390. _gl.uniform1i( uniforms.fogType, fogType );
  21391. oldFogType = fogType;
  21392. }
  21393. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21394. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21395. scale[ 1 ] *= size * sprite.scale.y;
  21396. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21397. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21398. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21399. _gl.uniform1f( uniforms.opacity, material.opacity );
  21400. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21401. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21402. _gl.uniform2fv( uniforms.scale, scale );
  21403. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21404. _renderer.setDepthTest( material.depthTest );
  21405. _renderer.setDepthWrite( material.depthWrite );
  21406. _renderer.setTexture( material.map, 0 );
  21407. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21408. }
  21409. }
  21410. // restore gl
  21411. _gl.enable( _gl.CULL_FACE );
  21412. };
  21413. function createProgram ( shader, precision ) {
  21414. var program = _gl.createProgram();
  21415. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21416. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21417. var prefix = "precision " + precision + " float;\n";
  21418. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21419. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21420. _gl.compileShader( fragmentShader );
  21421. _gl.compileShader( vertexShader );
  21422. _gl.attachShader( program, fragmentShader );
  21423. _gl.attachShader( program, vertexShader );
  21424. _gl.linkProgram( program );
  21425. return program;
  21426. };
  21427. function painterSortStable ( a, b ) {
  21428. if ( a.z !== b.z ) {
  21429. return b.z - a.z;
  21430. } else {
  21431. return b.id - a.id;
  21432. }
  21433. };
  21434. };
  21435. /**
  21436. * @author alteredq / http://alteredqualia.com/
  21437. */
  21438. THREE.DepthPassPlugin = function () {
  21439. this.enabled = false;
  21440. this.renderTarget = null;
  21441. var _gl,
  21442. _renderer,
  21443. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21444. _frustum = new THREE.Frustum(),
  21445. _projScreenMatrix = new THREE.Matrix4();
  21446. this.init = function ( renderer ) {
  21447. _gl = renderer.context;
  21448. _renderer = renderer;
  21449. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21450. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21451. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21452. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21453. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21454. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21455. _depthMaterial._shadowPass = true;
  21456. _depthMaterialMorph._shadowPass = true;
  21457. _depthMaterialSkin._shadowPass = true;
  21458. _depthMaterialMorphSkin._shadowPass = true;
  21459. };
  21460. this.render = function ( scene, camera ) {
  21461. if ( ! this.enabled ) return;
  21462. this.update( scene, camera );
  21463. };
  21464. this.update = function ( scene, camera ) {
  21465. var i, il, j, jl, n,
  21466. program, buffer, material,
  21467. webglObject, object, light,
  21468. renderList,
  21469. fog = null;
  21470. // set GL state for depth map
  21471. _gl.clearColor( 1, 1, 1, 1 );
  21472. _gl.disable( _gl.BLEND );
  21473. _renderer.setDepthTest( true );
  21474. // update scene
  21475. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21476. // update camera matrices and frustum
  21477. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21478. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21479. _frustum.setFromMatrix( _projScreenMatrix );
  21480. // render depth map
  21481. _renderer.setRenderTarget( this.renderTarget );
  21482. _renderer.clear();
  21483. // set object matrices & frustum culling
  21484. renderList = scene.__webglObjects;
  21485. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21486. webglObject = renderList[ j ];
  21487. object = webglObject.object;
  21488. webglObject.render = false;
  21489. if ( object.visible ) {
  21490. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21491. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21492. webglObject.render = true;
  21493. }
  21494. }
  21495. }
  21496. // render regular objects
  21497. var objectMaterial, useMorphing, useSkinning;
  21498. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21499. webglObject = renderList[ j ];
  21500. if ( webglObject.render ) {
  21501. object = webglObject.object;
  21502. buffer = webglObject.buffer;
  21503. // todo: create proper depth material for particles
  21504. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21505. objectMaterial = getObjectMaterial( object );
  21506. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21507. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21508. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21509. if ( object.customDepthMaterial ) {
  21510. material = object.customDepthMaterial;
  21511. } else if ( useSkinning ) {
  21512. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21513. } else if ( useMorphing ) {
  21514. material = _depthMaterialMorph;
  21515. } else {
  21516. material = _depthMaterial;
  21517. }
  21518. if ( buffer instanceof THREE.BufferGeometry ) {
  21519. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21520. } else {
  21521. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21522. }
  21523. }
  21524. }
  21525. // set matrices and render immediate objects
  21526. renderList = scene.__webglObjectsImmediate;
  21527. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21528. webglObject = renderList[ j ];
  21529. object = webglObject.object;
  21530. if ( object.visible ) {
  21531. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21532. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21533. }
  21534. }
  21535. // restore GL state
  21536. var clearColor = _renderer.getClearColor(),
  21537. clearAlpha = _renderer.getClearAlpha();
  21538. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21539. _gl.enable( _gl.BLEND );
  21540. };
  21541. // For the moment just ignore objects that have multiple materials with different animation methods
  21542. // Only the first material will be taken into account for deciding which depth material to use
  21543. function getObjectMaterial( object ) {
  21544. return object.material instanceof THREE.MeshFaceMaterial
  21545. ? object.material.materials[ 0 ]
  21546. : object.material;
  21547. };
  21548. };
  21549. /**
  21550. * @author mikael emtinger / http://gomo.se/
  21551. *
  21552. */
  21553. THREE.ShaderFlares = {
  21554. 'lensFlareVertexTexture': {
  21555. vertexShader: [
  21556. "uniform lowp int renderType;",
  21557. "uniform vec3 screenPosition;",
  21558. "uniform vec2 scale;",
  21559. "uniform float rotation;",
  21560. "uniform sampler2D occlusionMap;",
  21561. "attribute vec2 position;",
  21562. "attribute vec2 uv;",
  21563. "varying vec2 vUV;",
  21564. "varying float vVisibility;",
  21565. "void main() {",
  21566. "vUV = uv;",
  21567. "vec2 pos = position;",
  21568. "if( renderType == 2 ) {",
  21569. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21570. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21571. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21572. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21573. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21574. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21575. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21576. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21577. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21578. "vVisibility = ( visibility.r / 9.0 ) *",
  21579. "( 1.0 - visibility.g / 9.0 ) *",
  21580. "( visibility.b / 9.0 ) *",
  21581. "( 1.0 - visibility.a / 9.0 );",
  21582. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21583. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21584. "}",
  21585. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21586. "}"
  21587. ].join( "\n" ),
  21588. fragmentShader: [
  21589. "uniform lowp int renderType;",
  21590. "uniform sampler2D map;",
  21591. "uniform float opacity;",
  21592. "uniform vec3 color;",
  21593. "varying vec2 vUV;",
  21594. "varying float vVisibility;",
  21595. "void main() {",
  21596. // pink square
  21597. "if( renderType == 0 ) {",
  21598. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21599. // restore
  21600. "} else if( renderType == 1 ) {",
  21601. "gl_FragColor = texture2D( map, vUV );",
  21602. // flare
  21603. "} else {",
  21604. "vec4 texture = texture2D( map, vUV );",
  21605. "texture.a *= opacity * vVisibility;",
  21606. "gl_FragColor = texture;",
  21607. "gl_FragColor.rgb *= color;",
  21608. "}",
  21609. "}"
  21610. ].join( "\n" )
  21611. },
  21612. 'lensFlare': {
  21613. vertexShader: [
  21614. "uniform lowp int renderType;",
  21615. "uniform vec3 screenPosition;",
  21616. "uniform vec2 scale;",
  21617. "uniform float rotation;",
  21618. "attribute vec2 position;",
  21619. "attribute vec2 uv;",
  21620. "varying vec2 vUV;",
  21621. "void main() {",
  21622. "vUV = uv;",
  21623. "vec2 pos = position;",
  21624. "if( renderType == 2 ) {",
  21625. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21626. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21627. "}",
  21628. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21629. "}"
  21630. ].join( "\n" ),
  21631. fragmentShader: [
  21632. "precision mediump float;",
  21633. "uniform lowp int renderType;",
  21634. "uniform sampler2D map;",
  21635. "uniform sampler2D occlusionMap;",
  21636. "uniform float opacity;",
  21637. "uniform vec3 color;",
  21638. "varying vec2 vUV;",
  21639. "void main() {",
  21640. // pink square
  21641. "if( renderType == 0 ) {",
  21642. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21643. // restore
  21644. "} else if( renderType == 1 ) {",
  21645. "gl_FragColor = texture2D( map, vUV );",
  21646. // flare
  21647. "} else {",
  21648. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21649. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21650. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21651. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21652. "visibility = ( 1.0 - visibility / 4.0 );",
  21653. "vec4 texture = texture2D( map, vUV );",
  21654. "texture.a *= opacity * visibility;",
  21655. "gl_FragColor = texture;",
  21656. "gl_FragColor.rgb *= color;",
  21657. "}",
  21658. "}"
  21659. ].join( "\n" )
  21660. }
  21661. };
  21662. /**
  21663. * @author mikael emtinger / http://gomo.se/
  21664. * @author alteredq / http://alteredqualia.com/
  21665. *
  21666. */
  21667. THREE.ShaderSprite = {
  21668. 'sprite': {
  21669. vertexShader: [
  21670. "uniform int useScreenCoordinates;",
  21671. "uniform int sizeAttenuation;",
  21672. "uniform vec3 screenPosition;",
  21673. "uniform mat4 modelViewMatrix;",
  21674. "uniform mat4 projectionMatrix;",
  21675. "uniform float rotation;",
  21676. "uniform vec2 scale;",
  21677. "uniform vec2 alignment;",
  21678. "uniform vec2 uvOffset;",
  21679. "uniform vec2 uvScale;",
  21680. "attribute vec2 position;",
  21681. "attribute vec2 uv;",
  21682. "varying vec2 vUV;",
  21683. "void main() {",
  21684. "vUV = uvOffset + uv * uvScale;",
  21685. "vec2 alignedPosition = position + alignment;",
  21686. "vec2 rotatedPosition;",
  21687. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21688. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21689. "vec4 finalPosition;",
  21690. "if( useScreenCoordinates != 0 ) {",
  21691. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21692. "} else {",
  21693. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21694. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21695. "}",
  21696. "gl_Position = finalPosition;",
  21697. "}"
  21698. ].join( "\n" ),
  21699. fragmentShader: [
  21700. "uniform vec3 color;",
  21701. "uniform sampler2D map;",
  21702. "uniform float opacity;",
  21703. "uniform int fogType;",
  21704. "uniform vec3 fogColor;",
  21705. "uniform float fogDensity;",
  21706. "uniform float fogNear;",
  21707. "uniform float fogFar;",
  21708. "uniform float alphaTest;",
  21709. "varying vec2 vUV;",
  21710. "void main() {",
  21711. "vec4 texture = texture2D( map, vUV );",
  21712. "if ( texture.a < alphaTest ) discard;",
  21713. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21714. "if ( fogType > 0 ) {",
  21715. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21716. "float fogFactor = 0.0;",
  21717. "if ( fogType == 1 ) {",
  21718. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21719. "} else {",
  21720. "const float LOG2 = 1.442695;",
  21721. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21722. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21723. "}",
  21724. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21725. "}",
  21726. "}"
  21727. ].join( "\n" )
  21728. }
  21729. };
粤ICP备19079148号