WebGLRenderer.js 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. */
  7. THREE.WebGLRenderer = function ( parameters ) {
  8. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9. parameters = parameters || {};
  10. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11. _context = parameters.context !== undefined ? parameters.context : null,
  12. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  13. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  18. _clearColor = new THREE.Color( 0x000000 ),
  19. _clearAlpha = 0;
  20. // public properties
  21. this.domElement = _canvas;
  22. this.context = null;
  23. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  24. ? parameters.devicePixelRatio
  25. : self.devicePixelRatio !== undefined
  26. ? self.devicePixelRatio
  27. : 1;
  28. // clearing
  29. this.autoClear = true;
  30. this.autoClearColor = true;
  31. this.autoClearDepth = true;
  32. this.autoClearStencil = true;
  33. // scene graph
  34. this.sortObjects = true;
  35. this.autoUpdateObjects = true;
  36. // physically based shading
  37. this.gammaInput = false;
  38. this.gammaOutput = false;
  39. // shadow map
  40. this.shadowMapEnabled = false;
  41. this.shadowMapAutoUpdate = true;
  42. this.shadowMapType = THREE.PCFShadowMap;
  43. this.shadowMapCullFace = THREE.CullFaceFront;
  44. this.shadowMapDebug = false;
  45. this.shadowMapCascade = false;
  46. // morphs
  47. this.maxMorphTargets = 8;
  48. this.maxMorphNormals = 4;
  49. // flags
  50. this.autoScaleCubemaps = true;
  51. // custom render plugins
  52. this.renderPluginsPre = [];
  53. this.renderPluginsPost = [];
  54. // info
  55. this.info = {
  56. memory: {
  57. programs: 0,
  58. geometries: 0,
  59. textures: 0
  60. },
  61. render: {
  62. calls: 0,
  63. vertices: 0,
  64. faces: 0,
  65. points: 0
  66. }
  67. };
  68. // internal properties
  69. var _this = this,
  70. _programs = [],
  71. _programs_counter = 0,
  72. // internal state cache
  73. _currentProgram = null,
  74. _currentFramebuffer = null,
  75. _currentMaterialId = -1,
  76. _currentGeometryGroupHash = null,
  77. _currentCamera = null,
  78. _geometryGroupCounter = 0,
  79. _usedTextureUnits = 0,
  80. // GL state cache
  81. _oldDoubleSided = -1,
  82. _oldFlipSided = -1,
  83. _oldBlending = -1,
  84. _oldBlendEquation = -1,
  85. _oldBlendSrc = -1,
  86. _oldBlendDst = -1,
  87. _oldDepthTest = -1,
  88. _oldDepthWrite = -1,
  89. _oldPolygonOffset = null,
  90. _oldPolygonOffsetFactor = null,
  91. _oldPolygonOffsetUnits = null,
  92. _oldLineWidth = null,
  93. _viewportX = 0,
  94. _viewportY = 0,
  95. _viewportWidth = _canvas.width,
  96. _viewportHeight = _canvas.height,
  97. _currentWidth = 0,
  98. _currentHeight = 0,
  99. _enabledAttributes = {},
  100. // frustum
  101. _frustum = new THREE.Frustum(),
  102. // camera matrices cache
  103. _projScreenMatrix = new THREE.Matrix4(),
  104. _projScreenMatrixPS = new THREE.Matrix4(),
  105. _vector3 = new THREE.Vector3(),
  106. // light arrays cache
  107. _direction = new THREE.Vector3(),
  108. _lightsNeedUpdate = true,
  109. _lights = {
  110. ambient: [ 0, 0, 0 ],
  111. directional: { length: 0, colors: new Array(), positions: new Array() },
  112. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  113. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  114. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  115. };
  116. // initialize
  117. var _gl;
  118. var _glExtensionTextureFloat;
  119. var _glExtensionTextureFloatLinear;
  120. var _glExtensionStandardDerivatives;
  121. var _glExtensionTextureFilterAnisotropic;
  122. var _glExtensionCompressedTextureS3TC;
  123. initGL();
  124. setDefaultGLState();
  125. this.context = _gl;
  126. // GPU capabilities
  127. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  128. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  129. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  130. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  131. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  132. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  133. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  134. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  135. //
  136. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  137. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  138. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  139. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  140. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  141. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  142. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  143. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  144. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  145. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  146. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  147. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  148. // clamp precision to maximum available
  149. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  150. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  151. if ( _precision === "highp" && ! highpAvailable ) {
  152. if ( mediumpAvailable ) {
  153. _precision = "mediump";
  154. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  155. } else {
  156. _precision = "lowp";
  157. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  158. }
  159. }
  160. if ( _precision === "mediump" && ! mediumpAvailable ) {
  161. _precision = "lowp";
  162. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  163. }
  164. // API
  165. this.getContext = function () {
  166. return _gl;
  167. };
  168. this.supportsVertexTextures = function () {
  169. return _supportsVertexTextures;
  170. };
  171. this.supportsFloatTextures = function () {
  172. return _glExtensionTextureFloat;
  173. };
  174. this.supportsStandardDerivatives = function () {
  175. return _glExtensionStandardDerivatives;
  176. };
  177. this.supportsCompressedTextureS3TC = function () {
  178. return _glExtensionCompressedTextureS3TC;
  179. };
  180. this.getMaxAnisotropy = function () {
  181. return _maxAnisotropy;
  182. };
  183. this.getPrecision = function () {
  184. return _precision;
  185. };
  186. this.setSize = function ( width, height, updateStyle ) {
  187. _canvas.width = width * this.devicePixelRatio;
  188. _canvas.height = height * this.devicePixelRatio;
  189. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  190. _canvas.style.width = width + 'px';
  191. _canvas.style.height = height + 'px';
  192. }
  193. this.setViewport( 0, 0, width, height );
  194. };
  195. this.setViewport = function ( x, y, width, height ) {
  196. _viewportX = x * this.devicePixelRatio;
  197. _viewportY = y * this.devicePixelRatio;
  198. _viewportWidth = width * this.devicePixelRatio;
  199. _viewportHeight = height * this.devicePixelRatio;
  200. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  201. };
  202. this.setScissor = function ( x, y, width, height ) {
  203. _gl.scissor(
  204. x * this.devicePixelRatio,
  205. y * this.devicePixelRatio,
  206. width * this.devicePixelRatio,
  207. height * this.devicePixelRatio
  208. );
  209. };
  210. this.enableScissorTest = function ( enable ) {
  211. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  212. };
  213. // Clearing
  214. this.setClearColor = function ( color, alpha ) {
  215. _clearColor.set( color );
  216. _clearAlpha = alpha !== undefined ? alpha : 1;
  217. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  218. };
  219. this.setClearColorHex = function ( hex, alpha ) {
  220. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  221. this.setClearColor( hex, alpha );
  222. };
  223. this.getClearColor = function () {
  224. return _clearColor;
  225. };
  226. this.getClearAlpha = function () {
  227. return _clearAlpha;
  228. };
  229. this.clear = function ( color, depth, stencil ) {
  230. var bits = 0;
  231. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  232. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  233. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  234. _gl.clear( bits );
  235. };
  236. this.clearColor = function () {
  237. _gl.clear( _gl.COLOR_BUFFER_BIT );
  238. };
  239. this.clearDepth = function () {
  240. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  241. };
  242. this.clearStencil = function () {
  243. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  244. };
  245. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  246. this.setRenderTarget( renderTarget );
  247. this.clear( color, depth, stencil );
  248. };
  249. // Plugins
  250. this.addPostPlugin = function ( plugin ) {
  251. plugin.init( this );
  252. this.renderPluginsPost.push( plugin );
  253. };
  254. this.addPrePlugin = function ( plugin ) {
  255. plugin.init( this );
  256. this.renderPluginsPre.push( plugin );
  257. };
  258. // Rendering
  259. this.updateShadowMap = function ( scene, camera ) {
  260. _currentProgram = null;
  261. _oldBlending = -1;
  262. _oldDepthTest = -1;
  263. _oldDepthWrite = -1;
  264. _currentGeometryGroupHash = -1;
  265. _currentMaterialId = -1;
  266. _lightsNeedUpdate = true;
  267. _oldDoubleSided = -1;
  268. _oldFlipSided = -1;
  269. this.shadowMapPlugin.update( scene, camera );
  270. };
  271. // Internal functions
  272. // Buffer allocation
  273. function createParticleBuffers ( geometry ) {
  274. geometry.__webglVertexBuffer = _gl.createBuffer();
  275. geometry.__webglColorBuffer = _gl.createBuffer();
  276. _this.info.memory.geometries ++;
  277. };
  278. function createLineBuffers ( geometry ) {
  279. geometry.__webglVertexBuffer = _gl.createBuffer();
  280. geometry.__webglColorBuffer = _gl.createBuffer();
  281. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  282. _this.info.memory.geometries ++;
  283. };
  284. function createMeshBuffers ( geometryGroup ) {
  285. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  286. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  287. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  288. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  289. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  290. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  291. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  292. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  293. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  294. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  295. var m, ml;
  296. if ( geometryGroup.numMorphTargets ) {
  297. geometryGroup.__webglMorphTargetsBuffers = [];
  298. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  299. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  300. }
  301. }
  302. if ( geometryGroup.numMorphNormals ) {
  303. geometryGroup.__webglMorphNormalsBuffers = [];
  304. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  305. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  306. }
  307. }
  308. _this.info.memory.geometries ++;
  309. };
  310. // Events
  311. var onGeometryDispose = function ( event ) {
  312. var geometry = event.target;
  313. geometry.removeEventListener( 'dispose', onGeometryDispose );
  314. deallocateGeometry( geometry );
  315. };
  316. var onTextureDispose = function ( event ) {
  317. var texture = event.target;
  318. texture.removeEventListener( 'dispose', onTextureDispose );
  319. deallocateTexture( texture );
  320. _this.info.memory.textures --;
  321. };
  322. var onRenderTargetDispose = function ( event ) {
  323. var renderTarget = event.target;
  324. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  325. deallocateRenderTarget( renderTarget );
  326. _this.info.memory.textures --;
  327. };
  328. var onMaterialDispose = function ( event ) {
  329. var material = event.target;
  330. material.removeEventListener( 'dispose', onMaterialDispose );
  331. deallocateMaterial( material );
  332. };
  333. // Buffer deallocation
  334. var deleteBuffers = function ( geometry ) {
  335. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  336. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  337. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  338. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  339. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  340. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  341. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  342. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  343. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  344. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  345. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  346. // custom attributes
  347. if ( geometry.__webglCustomAttributesList !== undefined ) {
  348. for ( var id in geometry.__webglCustomAttributesList ) {
  349. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  350. }
  351. }
  352. _this.info.memory.geometries --;
  353. };
  354. var deallocateGeometry = function ( geometry ) {
  355. geometry.__webglInit = undefined;
  356. if ( geometry instanceof THREE.BufferGeometry ) {
  357. var attributes = geometry.attributes;
  358. for ( var key in attributes ) {
  359. if ( attributes[ key ].buffer !== undefined ) {
  360. _gl.deleteBuffer( attributes[ key ].buffer );
  361. }
  362. }
  363. _this.info.memory.geometries --;
  364. } else {
  365. if ( geometry.geometryGroups !== undefined ) {
  366. for ( var g in geometry.geometryGroups ) {
  367. var geometryGroup = geometry.geometryGroups[ g ];
  368. if ( geometryGroup.numMorphTargets !== undefined ) {
  369. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  370. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  371. }
  372. }
  373. if ( geometryGroup.numMorphNormals !== undefined ) {
  374. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  375. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  376. }
  377. }
  378. deleteBuffers( geometryGroup );
  379. }
  380. } else {
  381. deleteBuffers( geometry );
  382. }
  383. }
  384. };
  385. var deallocateTexture = function ( texture ) {
  386. if ( texture.image && texture.image.__webglTextureCube ) {
  387. // cube texture
  388. _gl.deleteTexture( texture.image.__webglTextureCube );
  389. } else {
  390. // 2D texture
  391. if ( ! texture.__webglInit ) return;
  392. texture.__webglInit = false;
  393. _gl.deleteTexture( texture.__webglTexture );
  394. }
  395. };
  396. var deallocateRenderTarget = function ( renderTarget ) {
  397. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  398. _gl.deleteTexture( renderTarget.__webglTexture );
  399. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  400. for ( var i = 0; i < 6; i ++ ) {
  401. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  402. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  403. }
  404. } else {
  405. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  406. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  407. }
  408. };
  409. var deallocateMaterial = function ( material ) {
  410. var program = material.program;
  411. if ( program === undefined ) return;
  412. material.program = undefined;
  413. // only deallocate GL program if this was the last use of shared program
  414. // assumed there is only single copy of any program in the _programs list
  415. // (that's how it's constructed)
  416. var i, il, programInfo;
  417. var deleteProgram = false;
  418. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  419. programInfo = _programs[ i ];
  420. if ( programInfo.program === program ) {
  421. programInfo.usedTimes --;
  422. if ( programInfo.usedTimes === 0 ) {
  423. deleteProgram = true;
  424. }
  425. break;
  426. }
  427. }
  428. if ( deleteProgram === true ) {
  429. // avoid using array.splice, this is costlier than creating new array from scratch
  430. var newPrograms = [];
  431. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  432. programInfo = _programs[ i ];
  433. if ( programInfo.program !== program ) {
  434. newPrograms.push( programInfo );
  435. }
  436. }
  437. _programs = newPrograms;
  438. _gl.deleteProgram( program );
  439. _this.info.memory.programs --;
  440. }
  441. };
  442. // Buffer initialization
  443. function initCustomAttributes ( geometry, object ) {
  444. var nvertices = geometry.vertices.length;
  445. var material = object.material;
  446. if ( material.attributes ) {
  447. if ( geometry.__webglCustomAttributesList === undefined ) {
  448. geometry.__webglCustomAttributesList = [];
  449. }
  450. for ( var a in material.attributes ) {
  451. var attribute = material.attributes[ a ];
  452. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  453. attribute.__webglInitialized = true;
  454. var size = 1; // "f" and "i"
  455. if ( attribute.type === "v2" ) size = 2;
  456. else if ( attribute.type === "v3" ) size = 3;
  457. else if ( attribute.type === "v4" ) size = 4;
  458. else if ( attribute.type === "c" ) size = 3;
  459. attribute.size = size;
  460. attribute.array = new Float32Array( nvertices * size );
  461. attribute.buffer = _gl.createBuffer();
  462. attribute.buffer.belongsToAttribute = a;
  463. attribute.needsUpdate = true;
  464. }
  465. geometry.__webglCustomAttributesList.push( attribute );
  466. }
  467. }
  468. };
  469. function initParticleBuffers ( geometry, object ) {
  470. var nvertices = geometry.vertices.length;
  471. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  472. geometry.__colorArray = new Float32Array( nvertices * 3 );
  473. geometry.__sortArray = [];
  474. geometry.__webglParticleCount = nvertices;
  475. initCustomAttributes ( geometry, object );
  476. };
  477. function initLineBuffers ( geometry, object ) {
  478. var nvertices = geometry.vertices.length;
  479. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  480. geometry.__colorArray = new Float32Array( nvertices * 3 );
  481. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  482. geometry.__webglLineCount = nvertices;
  483. initCustomAttributes ( geometry, object );
  484. };
  485. function initMeshBuffers ( geometryGroup, object ) {
  486. var geometry = object.geometry,
  487. faces3 = geometryGroup.faces3,
  488. nvertices = faces3.length * 3,
  489. ntris = faces3.length * 1,
  490. nlines = faces3.length * 3,
  491. material = getBufferMaterial( object, geometryGroup ),
  492. uvType = bufferGuessUVType( material ),
  493. normalType = bufferGuessNormalType( material ),
  494. vertexColorType = bufferGuessVertexColorType( material );
  495. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  496. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  497. if ( normalType ) {
  498. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  499. }
  500. if ( geometry.hasTangents ) {
  501. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  502. }
  503. if ( vertexColorType ) {
  504. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  505. }
  506. if ( uvType ) {
  507. if ( geometry.faceVertexUvs.length > 0 ) {
  508. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  509. }
  510. if ( geometry.faceVertexUvs.length > 1 ) {
  511. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  512. }
  513. }
  514. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  515. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  516. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  517. }
  518. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  519. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  520. var m, ml;
  521. if ( geometryGroup.numMorphTargets ) {
  522. geometryGroup.__morphTargetsArrays = [];
  523. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  524. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  525. }
  526. }
  527. if ( geometryGroup.numMorphNormals ) {
  528. geometryGroup.__morphNormalsArrays = [];
  529. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  530. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  531. }
  532. }
  533. geometryGroup.__webglFaceCount = ntris * 3;
  534. geometryGroup.__webglLineCount = nlines * 2;
  535. // custom attributes
  536. if ( material.attributes ) {
  537. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  538. geometryGroup.__webglCustomAttributesList = [];
  539. }
  540. for ( var a in material.attributes ) {
  541. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  542. // attribute buffers which are correctly indexed in the setMeshBuffers function
  543. var originalAttribute = material.attributes[ a ];
  544. var attribute = {};
  545. for ( var property in originalAttribute ) {
  546. attribute[ property ] = originalAttribute[ property ];
  547. }
  548. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  549. attribute.__webglInitialized = true;
  550. var size = 1; // "f" and "i"
  551. if( attribute.type === "v2" ) size = 2;
  552. else if( attribute.type === "v3" ) size = 3;
  553. else if( attribute.type === "v4" ) size = 4;
  554. else if( attribute.type === "c" ) size = 3;
  555. attribute.size = size;
  556. attribute.array = new Float32Array( nvertices * size );
  557. attribute.buffer = _gl.createBuffer();
  558. attribute.buffer.belongsToAttribute = a;
  559. originalAttribute.needsUpdate = true;
  560. attribute.__original = originalAttribute;
  561. }
  562. geometryGroup.__webglCustomAttributesList.push( attribute );
  563. }
  564. }
  565. geometryGroup.__inittedArrays = true;
  566. };
  567. function getBufferMaterial( object, geometryGroup ) {
  568. return object.material instanceof THREE.MeshFaceMaterial
  569. ? object.material.materials[ geometryGroup.materialIndex ]
  570. : object.material;
  571. };
  572. function materialNeedsSmoothNormals ( material ) {
  573. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  574. };
  575. function bufferGuessNormalType ( material ) {
  576. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  577. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  578. return false;
  579. }
  580. if ( materialNeedsSmoothNormals( material ) ) {
  581. return THREE.SmoothShading;
  582. } else {
  583. return THREE.FlatShading;
  584. }
  585. };
  586. function bufferGuessVertexColorType( material ) {
  587. if ( material.vertexColors ) {
  588. return material.vertexColors;
  589. }
  590. return false;
  591. };
  592. function bufferGuessUVType( material ) {
  593. // material must use some texture to require uvs
  594. if ( material.map ||
  595. material.lightMap ||
  596. material.bumpMap ||
  597. material.normalMap ||
  598. material.specularMap ||
  599. material instanceof THREE.ShaderMaterial ) {
  600. return true;
  601. }
  602. return false;
  603. };
  604. //
  605. function initDirectBuffers( geometry ) {
  606. var a, attribute, type;
  607. for ( a in geometry.attributes ) {
  608. if ( a === "index" ) {
  609. type = _gl.ELEMENT_ARRAY_BUFFER;
  610. } else {
  611. type = _gl.ARRAY_BUFFER;
  612. }
  613. attribute = geometry.attributes[ a ];
  614. attribute.buffer = _gl.createBuffer();
  615. _gl.bindBuffer( type, attribute.buffer );
  616. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  617. }
  618. };
  619. // Buffer setting
  620. function setParticleBuffers ( geometry, hint, object ) {
  621. var v, c, vertex, offset, index, color,
  622. vertices = geometry.vertices,
  623. vl = vertices.length,
  624. colors = geometry.colors,
  625. cl = colors.length,
  626. vertexArray = geometry.__vertexArray,
  627. colorArray = geometry.__colorArray,
  628. sortArray = geometry.__sortArray,
  629. dirtyVertices = geometry.verticesNeedUpdate,
  630. dirtyElements = geometry.elementsNeedUpdate,
  631. dirtyColors = geometry.colorsNeedUpdate,
  632. customAttributes = geometry.__webglCustomAttributesList,
  633. i, il,
  634. a, ca, cal, value,
  635. customAttribute;
  636. if ( object.sortParticles ) {
  637. _projScreenMatrixPS.copy( _projScreenMatrix );
  638. _projScreenMatrixPS.multiply( object.matrixWorld );
  639. for ( v = 0; v < vl; v ++ ) {
  640. vertex = vertices[ v ];
  641. _vector3.copy( vertex );
  642. _vector3.applyProjection( _projScreenMatrixPS );
  643. sortArray[ v ] = [ _vector3.z, v ];
  644. }
  645. sortArray.sort( numericalSort );
  646. for ( v = 0; v < vl; v ++ ) {
  647. vertex = vertices[ sortArray[v][1] ];
  648. offset = v * 3;
  649. vertexArray[ offset ] = vertex.x;
  650. vertexArray[ offset + 1 ] = vertex.y;
  651. vertexArray[ offset + 2 ] = vertex.z;
  652. }
  653. for ( c = 0; c < cl; c ++ ) {
  654. offset = c * 3;
  655. color = colors[ sortArray[c][1] ];
  656. colorArray[ offset ] = color.r;
  657. colorArray[ offset + 1 ] = color.g;
  658. colorArray[ offset + 2 ] = color.b;
  659. }
  660. if ( customAttributes ) {
  661. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  662. customAttribute = customAttributes[ i ];
  663. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  664. offset = 0;
  665. cal = customAttribute.value.length;
  666. if ( customAttribute.size === 1 ) {
  667. for ( ca = 0; ca < cal; ca ++ ) {
  668. index = sortArray[ ca ][ 1 ];
  669. customAttribute.array[ ca ] = customAttribute.value[ index ];
  670. }
  671. } else if ( customAttribute.size === 2 ) {
  672. for ( ca = 0; ca < cal; ca ++ ) {
  673. index = sortArray[ ca ][ 1 ];
  674. value = customAttribute.value[ index ];
  675. customAttribute.array[ offset ] = value.x;
  676. customAttribute.array[ offset + 1 ] = value.y;
  677. offset += 2;
  678. }
  679. } else if ( customAttribute.size === 3 ) {
  680. if ( customAttribute.type === "c" ) {
  681. for ( ca = 0; ca < cal; ca ++ ) {
  682. index = sortArray[ ca ][ 1 ];
  683. value = customAttribute.value[ index ];
  684. customAttribute.array[ offset ] = value.r;
  685. customAttribute.array[ offset + 1 ] = value.g;
  686. customAttribute.array[ offset + 2 ] = value.b;
  687. offset += 3;
  688. }
  689. } else {
  690. for ( ca = 0; ca < cal; ca ++ ) {
  691. index = sortArray[ ca ][ 1 ];
  692. value = customAttribute.value[ index ];
  693. customAttribute.array[ offset ] = value.x;
  694. customAttribute.array[ offset + 1 ] = value.y;
  695. customAttribute.array[ offset + 2 ] = value.z;
  696. offset += 3;
  697. }
  698. }
  699. } else if ( customAttribute.size === 4 ) {
  700. for ( ca = 0; ca < cal; ca ++ ) {
  701. index = sortArray[ ca ][ 1 ];
  702. value = customAttribute.value[ index ];
  703. customAttribute.array[ offset ] = value.x;
  704. customAttribute.array[ offset + 1 ] = value.y;
  705. customAttribute.array[ offset + 2 ] = value.z;
  706. customAttribute.array[ offset + 3 ] = value.w;
  707. offset += 4;
  708. }
  709. }
  710. }
  711. }
  712. } else {
  713. if ( dirtyVertices ) {
  714. for ( v = 0; v < vl; v ++ ) {
  715. vertex = vertices[ v ];
  716. offset = v * 3;
  717. vertexArray[ offset ] = vertex.x;
  718. vertexArray[ offset + 1 ] = vertex.y;
  719. vertexArray[ offset + 2 ] = vertex.z;
  720. }
  721. }
  722. if ( dirtyColors ) {
  723. for ( c = 0; c < cl; c ++ ) {
  724. color = colors[ c ];
  725. offset = c * 3;
  726. colorArray[ offset ] = color.r;
  727. colorArray[ offset + 1 ] = color.g;
  728. colorArray[ offset + 2 ] = color.b;
  729. }
  730. }
  731. if ( customAttributes ) {
  732. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  733. customAttribute = customAttributes[ i ];
  734. if ( customAttribute.needsUpdate &&
  735. ( customAttribute.boundTo === undefined ||
  736. customAttribute.boundTo === "vertices") ) {
  737. cal = customAttribute.value.length;
  738. offset = 0;
  739. if ( customAttribute.size === 1 ) {
  740. for ( ca = 0; ca < cal; ca ++ ) {
  741. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  742. }
  743. } else if ( customAttribute.size === 2 ) {
  744. for ( ca = 0; ca < cal; ca ++ ) {
  745. value = customAttribute.value[ ca ];
  746. customAttribute.array[ offset ] = value.x;
  747. customAttribute.array[ offset + 1 ] = value.y;
  748. offset += 2;
  749. }
  750. } else if ( customAttribute.size === 3 ) {
  751. if ( customAttribute.type === "c" ) {
  752. for ( ca = 0; ca < cal; ca ++ ) {
  753. value = customAttribute.value[ ca ];
  754. customAttribute.array[ offset ] = value.r;
  755. customAttribute.array[ offset + 1 ] = value.g;
  756. customAttribute.array[ offset + 2 ] = value.b;
  757. offset += 3;
  758. }
  759. } else {
  760. for ( ca = 0; ca < cal; ca ++ ) {
  761. value = customAttribute.value[ ca ];
  762. customAttribute.array[ offset ] = value.x;
  763. customAttribute.array[ offset + 1 ] = value.y;
  764. customAttribute.array[ offset + 2 ] = value.z;
  765. offset += 3;
  766. }
  767. }
  768. } else if ( customAttribute.size === 4 ) {
  769. for ( ca = 0; ca < cal; ca ++ ) {
  770. value = customAttribute.value[ ca ];
  771. customAttribute.array[ offset ] = value.x;
  772. customAttribute.array[ offset + 1 ] = value.y;
  773. customAttribute.array[ offset + 2 ] = value.z;
  774. customAttribute.array[ offset + 3 ] = value.w;
  775. offset += 4;
  776. }
  777. }
  778. }
  779. }
  780. }
  781. }
  782. if ( dirtyVertices || object.sortParticles ) {
  783. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  784. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  785. }
  786. if ( dirtyColors || object.sortParticles ) {
  787. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  788. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  789. }
  790. if ( customAttributes ) {
  791. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  792. customAttribute = customAttributes[ i ];
  793. if ( customAttribute.needsUpdate || object.sortParticles ) {
  794. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  795. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  796. }
  797. }
  798. }
  799. };
  800. function setLineBuffers ( geometry, hint ) {
  801. var v, c, d, vertex, offset, color,
  802. vertices = geometry.vertices,
  803. colors = geometry.colors,
  804. lineDistances = geometry.lineDistances,
  805. vl = vertices.length,
  806. cl = colors.length,
  807. dl = lineDistances.length,
  808. vertexArray = geometry.__vertexArray,
  809. colorArray = geometry.__colorArray,
  810. lineDistanceArray = geometry.__lineDistanceArray,
  811. dirtyVertices = geometry.verticesNeedUpdate,
  812. dirtyColors = geometry.colorsNeedUpdate,
  813. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  814. customAttributes = geometry.__webglCustomAttributesList,
  815. i, il,
  816. a, ca, cal, value,
  817. customAttribute;
  818. if ( dirtyVertices ) {
  819. for ( v = 0; v < vl; v ++ ) {
  820. vertex = vertices[ v ];
  821. offset = v * 3;
  822. vertexArray[ offset ] = vertex.x;
  823. vertexArray[ offset + 1 ] = vertex.y;
  824. vertexArray[ offset + 2 ] = vertex.z;
  825. }
  826. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  827. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  828. }
  829. if ( dirtyColors ) {
  830. for ( c = 0; c < cl; c ++ ) {
  831. color = colors[ c ];
  832. offset = c * 3;
  833. colorArray[ offset ] = color.r;
  834. colorArray[ offset + 1 ] = color.g;
  835. colorArray[ offset + 2 ] = color.b;
  836. }
  837. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  838. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  839. }
  840. if ( dirtyLineDistances ) {
  841. for ( d = 0; d < dl; d ++ ) {
  842. lineDistanceArray[ d ] = lineDistances[ d ];
  843. }
  844. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  845. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  846. }
  847. if ( customAttributes ) {
  848. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  849. customAttribute = customAttributes[ i ];
  850. if ( customAttribute.needsUpdate &&
  851. ( customAttribute.boundTo === undefined ||
  852. customAttribute.boundTo === "vertices" ) ) {
  853. offset = 0;
  854. cal = customAttribute.value.length;
  855. if ( customAttribute.size === 1 ) {
  856. for ( ca = 0; ca < cal; ca ++ ) {
  857. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  858. }
  859. } else if ( customAttribute.size === 2 ) {
  860. for ( ca = 0; ca < cal; ca ++ ) {
  861. value = customAttribute.value[ ca ];
  862. customAttribute.array[ offset ] = value.x;
  863. customAttribute.array[ offset + 1 ] = value.y;
  864. offset += 2;
  865. }
  866. } else if ( customAttribute.size === 3 ) {
  867. if ( customAttribute.type === "c" ) {
  868. for ( ca = 0; ca < cal; ca ++ ) {
  869. value = customAttribute.value[ ca ];
  870. customAttribute.array[ offset ] = value.r;
  871. customAttribute.array[ offset + 1 ] = value.g;
  872. customAttribute.array[ offset + 2 ] = value.b;
  873. offset += 3;
  874. }
  875. } else {
  876. for ( ca = 0; ca < cal; ca ++ ) {
  877. value = customAttribute.value[ ca ];
  878. customAttribute.array[ offset ] = value.x;
  879. customAttribute.array[ offset + 1 ] = value.y;
  880. customAttribute.array[ offset + 2 ] = value.z;
  881. offset += 3;
  882. }
  883. }
  884. } else if ( customAttribute.size === 4 ) {
  885. for ( ca = 0; ca < cal; ca ++ ) {
  886. value = customAttribute.value[ ca ];
  887. customAttribute.array[ offset ] = value.x;
  888. customAttribute.array[ offset + 1 ] = value.y;
  889. customAttribute.array[ offset + 2 ] = value.z;
  890. customAttribute.array[ offset + 3 ] = value.w;
  891. offset += 4;
  892. }
  893. }
  894. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  895. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  896. }
  897. }
  898. }
  899. };
  900. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  901. if ( ! geometryGroup.__inittedArrays ) {
  902. return;
  903. }
  904. var normalType = bufferGuessNormalType( material ),
  905. vertexColorType = bufferGuessVertexColorType( material ),
  906. uvType = bufferGuessUVType( material ),
  907. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  908. var f, fl, fi, face,
  909. vertexNormals, faceNormal, normal,
  910. vertexColors, faceColor,
  911. vertexTangents,
  912. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  913. c1, c2, c3, c4,
  914. sw1, sw2, sw3, sw4,
  915. si1, si2, si3, si4,
  916. sa1, sa2, sa3, sa4,
  917. sb1, sb2, sb3, sb4,
  918. m, ml, i, il,
  919. vn, uvi, uv2i,
  920. vk, vkl, vka,
  921. nka, chf, faceVertexNormals,
  922. a,
  923. vertexIndex = 0,
  924. offset = 0,
  925. offset_uv = 0,
  926. offset_uv2 = 0,
  927. offset_face = 0,
  928. offset_normal = 0,
  929. offset_tangent = 0,
  930. offset_line = 0,
  931. offset_color = 0,
  932. offset_skin = 0,
  933. offset_morphTarget = 0,
  934. offset_custom = 0,
  935. offset_customSrc = 0,
  936. value,
  937. vertexArray = geometryGroup.__vertexArray,
  938. uvArray = geometryGroup.__uvArray,
  939. uv2Array = geometryGroup.__uv2Array,
  940. normalArray = geometryGroup.__normalArray,
  941. tangentArray = geometryGroup.__tangentArray,
  942. colorArray = geometryGroup.__colorArray,
  943. skinIndexArray = geometryGroup.__skinIndexArray,
  944. skinWeightArray = geometryGroup.__skinWeightArray,
  945. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  946. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  947. customAttributes = geometryGroup.__webglCustomAttributesList,
  948. customAttribute,
  949. faceArray = geometryGroup.__faceArray,
  950. lineArray = geometryGroup.__lineArray,
  951. geometry = object.geometry, // this is shared for all chunks
  952. dirtyVertices = geometry.verticesNeedUpdate,
  953. dirtyElements = geometry.elementsNeedUpdate,
  954. dirtyUvs = geometry.uvsNeedUpdate,
  955. dirtyNormals = geometry.normalsNeedUpdate,
  956. dirtyTangents = geometry.tangentsNeedUpdate,
  957. dirtyColors = geometry.colorsNeedUpdate,
  958. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  959. vertices = geometry.vertices,
  960. chunk_faces3 = geometryGroup.faces3,
  961. obj_faces = geometry.faces,
  962. obj_uvs = geometry.faceVertexUvs[ 0 ],
  963. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  964. obj_colors = geometry.colors,
  965. obj_skinIndices = geometry.skinIndices,
  966. obj_skinWeights = geometry.skinWeights,
  967. morphTargets = geometry.morphTargets,
  968. morphNormals = geometry.morphNormals;
  969. if ( dirtyVertices ) {
  970. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  971. face = obj_faces[ chunk_faces3[ f ] ];
  972. v1 = vertices[ face.a ];
  973. v2 = vertices[ face.b ];
  974. v3 = vertices[ face.c ];
  975. vertexArray[ offset ] = v1.x;
  976. vertexArray[ offset + 1 ] = v1.y;
  977. vertexArray[ offset + 2 ] = v1.z;
  978. vertexArray[ offset + 3 ] = v2.x;
  979. vertexArray[ offset + 4 ] = v2.y;
  980. vertexArray[ offset + 5 ] = v2.z;
  981. vertexArray[ offset + 6 ] = v3.x;
  982. vertexArray[ offset + 7 ] = v3.y;
  983. vertexArray[ offset + 8 ] = v3.z;
  984. offset += 9;
  985. }
  986. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  987. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  988. }
  989. if ( dirtyMorphTargets ) {
  990. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  991. offset_morphTarget = 0;
  992. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  993. chf = chunk_faces3[ f ];
  994. face = obj_faces[ chf ];
  995. // morph positions
  996. v1 = morphTargets[ vk ].vertices[ face.a ];
  997. v2 = morphTargets[ vk ].vertices[ face.b ];
  998. v3 = morphTargets[ vk ].vertices[ face.c ];
  999. vka = morphTargetsArrays[ vk ];
  1000. vka[ offset_morphTarget ] = v1.x;
  1001. vka[ offset_morphTarget + 1 ] = v1.y;
  1002. vka[ offset_morphTarget + 2 ] = v1.z;
  1003. vka[ offset_morphTarget + 3 ] = v2.x;
  1004. vka[ offset_morphTarget + 4 ] = v2.y;
  1005. vka[ offset_morphTarget + 5 ] = v2.z;
  1006. vka[ offset_morphTarget + 6 ] = v3.x;
  1007. vka[ offset_morphTarget + 7 ] = v3.y;
  1008. vka[ offset_morphTarget + 8 ] = v3.z;
  1009. // morph normals
  1010. if ( material.morphNormals ) {
  1011. if ( needsSmoothNormals ) {
  1012. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  1013. n1 = faceVertexNormals.a;
  1014. n2 = faceVertexNormals.b;
  1015. n3 = faceVertexNormals.c;
  1016. } else {
  1017. n1 = morphNormals[ vk ].faceNormals[ chf ];
  1018. n2 = n1;
  1019. n3 = n1;
  1020. }
  1021. nka = morphNormalsArrays[ vk ];
  1022. nka[ offset_morphTarget ] = n1.x;
  1023. nka[ offset_morphTarget + 1 ] = n1.y;
  1024. nka[ offset_morphTarget + 2 ] = n1.z;
  1025. nka[ offset_morphTarget + 3 ] = n2.x;
  1026. nka[ offset_morphTarget + 4 ] = n2.y;
  1027. nka[ offset_morphTarget + 5 ] = n2.z;
  1028. nka[ offset_morphTarget + 6 ] = n3.x;
  1029. nka[ offset_morphTarget + 7 ] = n3.y;
  1030. nka[ offset_morphTarget + 8 ] = n3.z;
  1031. }
  1032. //
  1033. offset_morphTarget += 9;
  1034. }
  1035. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  1036. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  1037. if ( material.morphNormals ) {
  1038. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  1039. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  1040. }
  1041. }
  1042. }
  1043. if ( obj_skinWeights.length ) {
  1044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1045. face = obj_faces[ chunk_faces3[ f ] ];
  1046. // weights
  1047. sw1 = obj_skinWeights[ face.a ];
  1048. sw2 = obj_skinWeights[ face.b ];
  1049. sw3 = obj_skinWeights[ face.c ];
  1050. skinWeightArray[ offset_skin ] = sw1.x;
  1051. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  1052. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  1053. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  1054. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  1055. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  1056. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  1057. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  1058. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  1059. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  1060. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  1061. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  1062. // indices
  1063. si1 = obj_skinIndices[ face.a ];
  1064. si2 = obj_skinIndices[ face.b ];
  1065. si3 = obj_skinIndices[ face.c ];
  1066. skinIndexArray[ offset_skin ] = si1.x;
  1067. skinIndexArray[ offset_skin + 1 ] = si1.y;
  1068. skinIndexArray[ offset_skin + 2 ] = si1.z;
  1069. skinIndexArray[ offset_skin + 3 ] = si1.w;
  1070. skinIndexArray[ offset_skin + 4 ] = si2.x;
  1071. skinIndexArray[ offset_skin + 5 ] = si2.y;
  1072. skinIndexArray[ offset_skin + 6 ] = si2.z;
  1073. skinIndexArray[ offset_skin + 7 ] = si2.w;
  1074. skinIndexArray[ offset_skin + 8 ] = si3.x;
  1075. skinIndexArray[ offset_skin + 9 ] = si3.y;
  1076. skinIndexArray[ offset_skin + 10 ] = si3.z;
  1077. skinIndexArray[ offset_skin + 11 ] = si3.w;
  1078. offset_skin += 12;
  1079. }
  1080. if ( offset_skin > 0 ) {
  1081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1082. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  1083. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1084. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  1085. }
  1086. }
  1087. if ( dirtyColors && vertexColorType ) {
  1088. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1089. face = obj_faces[ chunk_faces3[ f ] ];
  1090. vertexColors = face.vertexColors;
  1091. faceColor = face.color;
  1092. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  1093. c1 = vertexColors[ 0 ];
  1094. c2 = vertexColors[ 1 ];
  1095. c3 = vertexColors[ 2 ];
  1096. } else {
  1097. c1 = faceColor;
  1098. c2 = faceColor;
  1099. c3 = faceColor;
  1100. }
  1101. colorArray[ offset_color ] = c1.r;
  1102. colorArray[ offset_color + 1 ] = c1.g;
  1103. colorArray[ offset_color + 2 ] = c1.b;
  1104. colorArray[ offset_color + 3 ] = c2.r;
  1105. colorArray[ offset_color + 4 ] = c2.g;
  1106. colorArray[ offset_color + 5 ] = c2.b;
  1107. colorArray[ offset_color + 6 ] = c3.r;
  1108. colorArray[ offset_color + 7 ] = c3.g;
  1109. colorArray[ offset_color + 8 ] = c3.b;
  1110. offset_color += 9;
  1111. }
  1112. if ( offset_color > 0 ) {
  1113. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1114. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  1115. }
  1116. }
  1117. if ( dirtyTangents && geometry.hasTangents ) {
  1118. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1119. face = obj_faces[ chunk_faces3[ f ] ];
  1120. vertexTangents = face.vertexTangents;
  1121. t1 = vertexTangents[ 0 ];
  1122. t2 = vertexTangents[ 1 ];
  1123. t3 = vertexTangents[ 2 ];
  1124. tangentArray[ offset_tangent ] = t1.x;
  1125. tangentArray[ offset_tangent + 1 ] = t1.y;
  1126. tangentArray[ offset_tangent + 2 ] = t1.z;
  1127. tangentArray[ offset_tangent + 3 ] = t1.w;
  1128. tangentArray[ offset_tangent + 4 ] = t2.x;
  1129. tangentArray[ offset_tangent + 5 ] = t2.y;
  1130. tangentArray[ offset_tangent + 6 ] = t2.z;
  1131. tangentArray[ offset_tangent + 7 ] = t2.w;
  1132. tangentArray[ offset_tangent + 8 ] = t3.x;
  1133. tangentArray[ offset_tangent + 9 ] = t3.y;
  1134. tangentArray[ offset_tangent + 10 ] = t3.z;
  1135. tangentArray[ offset_tangent + 11 ] = t3.w;
  1136. offset_tangent += 12;
  1137. }
  1138. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1139. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  1140. }
  1141. if ( dirtyNormals && normalType ) {
  1142. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1143. face = obj_faces[ chunk_faces3[ f ] ];
  1144. vertexNormals = face.vertexNormals;
  1145. faceNormal = face.normal;
  1146. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  1147. for ( i = 0; i < 3; i ++ ) {
  1148. vn = vertexNormals[ i ];
  1149. normalArray[ offset_normal ] = vn.x;
  1150. normalArray[ offset_normal + 1 ] = vn.y;
  1151. normalArray[ offset_normal + 2 ] = vn.z;
  1152. offset_normal += 3;
  1153. }
  1154. } else {
  1155. for ( i = 0; i < 3; i ++ ) {
  1156. normalArray[ offset_normal ] = faceNormal.x;
  1157. normalArray[ offset_normal + 1 ] = faceNormal.y;
  1158. normalArray[ offset_normal + 2 ] = faceNormal.z;
  1159. offset_normal += 3;
  1160. }
  1161. }
  1162. }
  1163. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1164. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  1165. }
  1166. if ( dirtyUvs && obj_uvs && uvType ) {
  1167. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1168. fi = chunk_faces3[ f ];
  1169. uv = obj_uvs[ fi ];
  1170. if ( uv === undefined ) continue;
  1171. for ( i = 0; i < 3; i ++ ) {
  1172. uvi = uv[ i ];
  1173. uvArray[ offset_uv ] = uvi.x;
  1174. uvArray[ offset_uv + 1 ] = uvi.y;
  1175. offset_uv += 2;
  1176. }
  1177. }
  1178. if ( offset_uv > 0 ) {
  1179. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1180. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  1181. }
  1182. }
  1183. if ( dirtyUvs && obj_uvs2 && uvType ) {
  1184. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1185. fi = chunk_faces3[ f ];
  1186. uv2 = obj_uvs2[ fi ];
  1187. if ( uv2 === undefined ) continue;
  1188. for ( i = 0; i < 3; i ++ ) {
  1189. uv2i = uv2[ i ];
  1190. uv2Array[ offset_uv2 ] = uv2i.x;
  1191. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  1192. offset_uv2 += 2;
  1193. }
  1194. }
  1195. if ( offset_uv2 > 0 ) {
  1196. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1197. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  1198. }
  1199. }
  1200. if ( dirtyElements ) {
  1201. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1202. faceArray[ offset_face ] = vertexIndex;
  1203. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  1204. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  1205. offset_face += 3;
  1206. lineArray[ offset_line ] = vertexIndex;
  1207. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  1208. lineArray[ offset_line + 2 ] = vertexIndex;
  1209. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  1210. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  1211. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  1212. offset_line += 6;
  1213. vertexIndex += 3;
  1214. }
  1215. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1216. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  1217. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1218. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  1219. }
  1220. if ( customAttributes ) {
  1221. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  1222. customAttribute = customAttributes[ i ];
  1223. if ( ! customAttribute.__original.needsUpdate ) continue;
  1224. offset_custom = 0;
  1225. offset_customSrc = 0;
  1226. if ( customAttribute.size === 1 ) {
  1227. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1228. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1229. face = obj_faces[ chunk_faces3[ f ] ];
  1230. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  1231. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  1232. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  1233. offset_custom += 3;
  1234. }
  1235. } else if ( customAttribute.boundTo === "faces" ) {
  1236. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1237. value = customAttribute.value[ chunk_faces3[ f ] ];
  1238. customAttribute.array[ offset_custom ] = value;
  1239. customAttribute.array[ offset_custom + 1 ] = value;
  1240. customAttribute.array[ offset_custom + 2 ] = value;
  1241. offset_custom += 3;
  1242. }
  1243. }
  1244. } else if ( customAttribute.size === 2 ) {
  1245. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1246. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1247. face = obj_faces[ chunk_faces3[ f ] ];
  1248. v1 = customAttribute.value[ face.a ];
  1249. v2 = customAttribute.value[ face.b ];
  1250. v3 = customAttribute.value[ face.c ];
  1251. customAttribute.array[ offset_custom ] = v1.x;
  1252. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1253. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1254. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1255. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1256. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1257. offset_custom += 6;
  1258. }
  1259. } else if ( customAttribute.boundTo === "faces" ) {
  1260. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1261. value = customAttribute.value[ chunk_faces3[ f ] ];
  1262. v1 = value;
  1263. v2 = value;
  1264. v3 = value;
  1265. customAttribute.array[ offset_custom ] = v1.x;
  1266. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1267. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1268. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1269. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1270. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1271. offset_custom += 6;
  1272. }
  1273. }
  1274. } else if ( customAttribute.size === 3 ) {
  1275. var pp;
  1276. if ( customAttribute.type === "c" ) {
  1277. pp = [ "r", "g", "b" ];
  1278. } else {
  1279. pp = [ "x", "y", "z" ];
  1280. }
  1281. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1282. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1283. face = obj_faces[ chunk_faces3[ f ] ];
  1284. v1 = customAttribute.value[ face.a ];
  1285. v2 = customAttribute.value[ face.b ];
  1286. v3 = customAttribute.value[ face.c ];
  1287. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1288. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1289. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1290. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1291. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1292. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1293. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1294. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1295. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1296. offset_custom += 9;
  1297. }
  1298. } else if ( customAttribute.boundTo === "faces" ) {
  1299. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1300. value = customAttribute.value[ chunk_faces3[ f ] ];
  1301. v1 = value;
  1302. v2 = value;
  1303. v3 = value;
  1304. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1305. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1306. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1307. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1308. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1309. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1310. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1311. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1312. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1313. offset_custom += 9;
  1314. }
  1315. } else if ( customAttribute.boundTo === "faceVertices" ) {
  1316. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1317. value = customAttribute.value[ chunk_faces3[ f ] ];
  1318. v1 = value[ 0 ];
  1319. v2 = value[ 1 ];
  1320. v3 = value[ 2 ];
  1321. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1322. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1323. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1324. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1325. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1326. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1327. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1328. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1329. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1330. offset_custom += 9;
  1331. }
  1332. }
  1333. } else if ( customAttribute.size === 4 ) {
  1334. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1335. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1336. face = obj_faces[ chunk_faces3[ f ] ];
  1337. v1 = customAttribute.value[ face.a ];
  1338. v2 = customAttribute.value[ face.b ];
  1339. v3 = customAttribute.value[ face.c ];
  1340. customAttribute.array[ offset_custom ] = v1.x;
  1341. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1342. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1343. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1344. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1345. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1346. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1347. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1348. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1349. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1350. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1351. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1352. offset_custom += 12;
  1353. }
  1354. } else if ( customAttribute.boundTo === "faces" ) {
  1355. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1356. value = customAttribute.value[ chunk_faces3[ f ] ];
  1357. v1 = value;
  1358. v2 = value;
  1359. v3 = value;
  1360. customAttribute.array[ offset_custom ] = v1.x;
  1361. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1362. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1363. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1364. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1365. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1366. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1367. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1368. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1369. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1370. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1371. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1372. offset_custom += 12;
  1373. }
  1374. } else if ( customAttribute.boundTo === "faceVertices" ) {
  1375. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1376. value = customAttribute.value[ chunk_faces3[ f ] ];
  1377. v1 = value[ 0 ];
  1378. v2 = value[ 1 ];
  1379. v3 = value[ 2 ];
  1380. customAttribute.array[ offset_custom ] = v1.x;
  1381. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1382. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1383. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1384. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1385. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1386. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1387. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1388. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1389. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1390. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1391. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1392. offset_custom += 12;
  1393. }
  1394. }
  1395. }
  1396. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  1397. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  1398. }
  1399. }
  1400. if ( dispose ) {
  1401. delete geometryGroup.__inittedArrays;
  1402. delete geometryGroup.__colorArray;
  1403. delete geometryGroup.__normalArray;
  1404. delete geometryGroup.__tangentArray;
  1405. delete geometryGroup.__uvArray;
  1406. delete geometryGroup.__uv2Array;
  1407. delete geometryGroup.__faceArray;
  1408. delete geometryGroup.__vertexArray;
  1409. delete geometryGroup.__lineArray;
  1410. delete geometryGroup.__skinIndexArray;
  1411. delete geometryGroup.__skinWeightArray;
  1412. }
  1413. };
  1414. // used by renderBufferDirect for THREE.Line
  1415. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  1416. var attributeItem, attributeName, attributePointer, attributeSize;
  1417. for ( attributeName in programAttributes ) {
  1418. attributePointer = programAttributes[ attributeName ];
  1419. attributeItem = geometryAttributes[ attributeName ];
  1420. if ( attributePointer >= 0 ) {
  1421. if ( attributeItem ) {
  1422. attributeSize = attributeItem.itemSize;
  1423. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1424. enableAttribute( attributePointer );
  1425. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  1426. } else if ( material.defaultAttributeValues ) {
  1427. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1428. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1429. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1430. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1431. }
  1432. }
  1433. }
  1434. }
  1435. }
  1436. function setDirectBuffers ( geometry, hint, dispose ) {
  1437. var attributes = geometry.attributes;
  1438. var attributeName, attributeItem;
  1439. for ( attributeName in attributes ) {
  1440. attributeItem = attributes[ attributeName ];
  1441. if ( attributeItem.needsUpdate ) {
  1442. if ( attributeName === 'index' ) {
  1443. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  1444. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  1445. } else {
  1446. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1447. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  1448. }
  1449. attributeItem.needsUpdate = false;
  1450. }
  1451. if ( dispose && ! attributeItem.dynamic ) {
  1452. attributeItem.array = null;
  1453. }
  1454. }
  1455. };
  1456. // Buffer rendering
  1457. this.renderBufferImmediate = function ( object, program, material ) {
  1458. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  1459. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  1460. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  1461. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  1462. if ( object.hasPositions ) {
  1463. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  1464. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  1465. _gl.enableVertexAttribArray( program.attributes.position );
  1466. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1467. }
  1468. if ( object.hasNormals ) {
  1469. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  1470. if ( material.shading === THREE.FlatShading ) {
  1471. var nx, ny, nz,
  1472. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  1473. normalArray,
  1474. i, il = object.count * 3;
  1475. for( i = 0; i < il; i += 9 ) {
  1476. normalArray = object.normalArray;
  1477. nax = normalArray[ i ];
  1478. nay = normalArray[ i + 1 ];
  1479. naz = normalArray[ i + 2 ];
  1480. nbx = normalArray[ i + 3 ];
  1481. nby = normalArray[ i + 4 ];
  1482. nbz = normalArray[ i + 5 ];
  1483. ncx = normalArray[ i + 6 ];
  1484. ncy = normalArray[ i + 7 ];
  1485. ncz = normalArray[ i + 8 ];
  1486. nx = ( nax + nbx + ncx ) / 3;
  1487. ny = ( nay + nby + ncy ) / 3;
  1488. nz = ( naz + nbz + ncz ) / 3;
  1489. normalArray[ i ] = nx;
  1490. normalArray[ i + 1 ] = ny;
  1491. normalArray[ i + 2 ] = nz;
  1492. normalArray[ i + 3 ] = nx;
  1493. normalArray[ i + 4 ] = ny;
  1494. normalArray[ i + 5 ] = nz;
  1495. normalArray[ i + 6 ] = nx;
  1496. normalArray[ i + 7 ] = ny;
  1497. normalArray[ i + 8 ] = nz;
  1498. }
  1499. }
  1500. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  1501. _gl.enableVertexAttribArray( program.attributes.normal );
  1502. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1503. }
  1504. if ( object.hasUvs && material.map ) {
  1505. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  1506. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  1507. _gl.enableVertexAttribArray( program.attributes.uv );
  1508. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1509. }
  1510. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  1511. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  1512. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  1513. _gl.enableVertexAttribArray( program.attributes.color );
  1514. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1515. }
  1516. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  1517. object.count = 0;
  1518. };
  1519. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  1520. if ( material.visible === false ) return;
  1521. var linewidth, a, attribute;
  1522. var attributeItem, attributeName, attributePointer, attributeSize;
  1523. var program = setProgram( camera, lights, fog, material, object );
  1524. var programAttributes = program.attributes;
  1525. var geometryAttributes = geometry.attributes;
  1526. var updateBuffers = false,
  1527. wireframeBit = material.wireframe ? 1 : 0,
  1528. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1529. if ( geometryHash !== _currentGeometryGroupHash ) {
  1530. _currentGeometryGroupHash = geometryHash;
  1531. updateBuffers = true;
  1532. }
  1533. if ( updateBuffers ) {
  1534. disableAttributes();
  1535. }
  1536. // render mesh
  1537. if ( object instanceof THREE.Mesh ) {
  1538. var index = geometryAttributes[ "index" ];
  1539. // indexed triangles
  1540. if ( index ) {
  1541. var offsets = geometry.offsets;
  1542. // if there is more than 1 chunk
  1543. // must set attribute pointers to use new offsets for each chunk
  1544. // even if geometry and materials didn't change
  1545. if ( offsets.length > 1 ) updateBuffers = true;
  1546. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1547. var startIndex = offsets[ i ].index;
  1548. if ( updateBuffers ) {
  1549. for ( attributeName in programAttributes ) {
  1550. attributePointer = programAttributes[ attributeName ];
  1551. attributeItem = geometryAttributes[ attributeName ];
  1552. if ( attributePointer >= 0 ) {
  1553. if ( attributeItem ) {
  1554. attributeSize = attributeItem.itemSize;
  1555. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1556. enableAttribute( attributePointer );
  1557. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  1558. } else if ( material.defaultAttributeValues ) {
  1559. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1560. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1561. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1562. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1563. }
  1564. }
  1565. }
  1566. }
  1567. // indices
  1568. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1569. }
  1570. // render indexed triangles
  1571. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  1572. _this.info.render.calls ++;
  1573. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1574. _this.info.render.faces += offsets[ i ].count / 3;
  1575. }
  1576. // non-indexed triangles
  1577. } else {
  1578. if ( updateBuffers ) {
  1579. for ( attributeName in programAttributes ) {
  1580. if ( attributeName === 'index') continue;
  1581. attributePointer = programAttributes[ attributeName ];
  1582. attributeItem = geometryAttributes[ attributeName ];
  1583. if ( attributePointer >= 0 ) {
  1584. if ( attributeItem ) {
  1585. attributeSize = attributeItem.itemSize;
  1586. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1587. enableAttribute( attributePointer );
  1588. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  1589. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  1590. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1591. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1592. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1593. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. var position = geometry.attributes[ "position" ];
  1600. // render non-indexed triangles
  1601. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  1602. _this.info.render.calls ++;
  1603. _this.info.render.vertices += position.array.length / 3;
  1604. _this.info.render.faces += position.array.length / 3 / 3;
  1605. }
  1606. // render particles
  1607. } else if ( object instanceof THREE.ParticleSystem ) {
  1608. if ( updateBuffers ) {
  1609. for ( attributeName in programAttributes ) {
  1610. attributePointer = programAttributes[ attributeName ];
  1611. attributeItem = geometryAttributes[ attributeName ];
  1612. if ( attributePointer >= 0 ) {
  1613. if ( attributeItem ) {
  1614. attributeSize = attributeItem.itemSize;
  1615. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1616. enableAttribute( attributePointer );
  1617. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  1618. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  1619. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1620. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1621. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1622. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1623. }
  1624. }
  1625. }
  1626. }
  1627. }
  1628. var position = geometryAttributes[ "position" ];
  1629. // render particles
  1630. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  1631. _this.info.render.calls ++;
  1632. _this.info.render.points += position.array.length / 3;
  1633. } else if ( object instanceof THREE.Line ) {
  1634. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1635. setLineWidth( material.linewidth );
  1636. var index = geometryAttributes[ "index" ];
  1637. // indexed lines
  1638. if ( index ) {
  1639. var offsets = geometry.offsets;
  1640. // if there is more than 1 chunk
  1641. // must set attribute pointers to use new offsets for each chunk
  1642. // even if geometry and materials didn't change
  1643. if ( offsets.length > 1 ) updateBuffers = true;
  1644. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1645. var startIndex = offsets[ i ].index;
  1646. if ( updateBuffers ) {
  1647. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  1648. // indices
  1649. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1650. }
  1651. // render indexed lines
  1652. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  1653. _this.info.render.calls ++;
  1654. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1655. }
  1656. }
  1657. // non-indexed lines
  1658. else {
  1659. if ( updateBuffers ) {
  1660. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  1661. }
  1662. var position = geometryAttributes[ "position" ];
  1663. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  1664. _this.info.render.calls ++;
  1665. _this.info.render.points += position.array.length;
  1666. }
  1667. }
  1668. };
  1669. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  1670. if ( material.visible === false ) return;
  1671. var linewidth, a, attribute, i, il;
  1672. var program = setProgram( camera, lights, fog, material, object );
  1673. var attributes = program.attributes;
  1674. var updateBuffers = false,
  1675. wireframeBit = material.wireframe ? 1 : 0,
  1676. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1677. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  1678. _currentGeometryGroupHash = geometryGroupHash;
  1679. updateBuffers = true;
  1680. }
  1681. if ( updateBuffers ) {
  1682. disableAttributes();
  1683. }
  1684. // vertices
  1685. if ( !material.morphTargets && attributes.position >= 0 ) {
  1686. if ( updateBuffers ) {
  1687. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1688. enableAttribute( attributes.position );
  1689. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1690. }
  1691. } else {
  1692. if ( object.morphTargetBase ) {
  1693. setupMorphTargets( material, geometryGroup, object );
  1694. }
  1695. }
  1696. if ( updateBuffers ) {
  1697. // custom attributes
  1698. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  1699. if ( geometryGroup.__webglCustomAttributesList ) {
  1700. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  1701. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  1702. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  1703. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  1704. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  1705. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  1706. }
  1707. }
  1708. }
  1709. // colors
  1710. if ( attributes.color >= 0 ) {
  1711. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  1712. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1713. enableAttribute( attributes.color );
  1714. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1715. } else if ( material.defaultAttributeValues ) {
  1716. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  1717. }
  1718. }
  1719. // normals
  1720. if ( attributes.normal >= 0 ) {
  1721. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1722. enableAttribute( attributes.normal );
  1723. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1724. }
  1725. // tangents
  1726. if ( attributes.tangent >= 0 ) {
  1727. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1728. enableAttribute( attributes.tangent );
  1729. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  1730. }
  1731. // uvs
  1732. if ( attributes.uv >= 0 ) {
  1733. if ( object.geometry.faceVertexUvs[0] ) {
  1734. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1735. enableAttribute( attributes.uv );
  1736. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1737. } else if ( material.defaultAttributeValues ) {
  1738. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  1739. }
  1740. }
  1741. if ( attributes.uv2 >= 0 ) {
  1742. if ( object.geometry.faceVertexUvs[1] ) {
  1743. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1744. enableAttribute( attributes.uv2 );
  1745. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  1746. } else if ( material.defaultAttributeValues ) {
  1747. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  1748. }
  1749. }
  1750. if ( material.skinning &&
  1751. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  1752. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1753. enableAttribute( attributes.skinIndex );
  1754. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  1755. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1756. enableAttribute( attributes.skinWeight );
  1757. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  1758. }
  1759. // line distances
  1760. if ( attributes.lineDistance >= 0 ) {
  1761. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  1762. enableAttribute( attributes.lineDistance );
  1763. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  1764. }
  1765. }
  1766. // render mesh
  1767. if ( object instanceof THREE.Mesh ) {
  1768. // wireframe
  1769. if ( material.wireframe ) {
  1770. setLineWidth( material.wireframeLinewidth );
  1771. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1772. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  1773. // triangles
  1774. } else {
  1775. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1776. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  1777. }
  1778. _this.info.render.calls ++;
  1779. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  1780. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  1781. // render lines
  1782. } else if ( object instanceof THREE.Line ) {
  1783. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1784. setLineWidth( material.linewidth );
  1785. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  1786. _this.info.render.calls ++;
  1787. // render particles
  1788. } else if ( object instanceof THREE.ParticleSystem ) {
  1789. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  1790. _this.info.render.calls ++;
  1791. _this.info.render.points += geometryGroup.__webglParticleCount;
  1792. }
  1793. };
  1794. function enableAttribute( attribute ) {
  1795. if ( ! _enabledAttributes[ attribute ] ) {
  1796. _gl.enableVertexAttribArray( attribute );
  1797. _enabledAttributes[ attribute ] = true;
  1798. }
  1799. };
  1800. function disableAttributes() {
  1801. for ( var attribute in _enabledAttributes ) {
  1802. if ( _enabledAttributes[ attribute ] ) {
  1803. _gl.disableVertexAttribArray( attribute );
  1804. _enabledAttributes[ attribute ] = false;
  1805. }
  1806. }
  1807. };
  1808. function setupMorphTargets ( material, geometryGroup, object ) {
  1809. // set base
  1810. var attributes = material.program.attributes;
  1811. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  1812. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  1813. enableAttribute( attributes.position );
  1814. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1815. } else if ( attributes.position >= 0 ) {
  1816. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1817. enableAttribute( attributes.position );
  1818. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1819. }
  1820. if ( object.morphTargetForcedOrder.length ) {
  1821. // set forced order
  1822. var m = 0;
  1823. var order = object.morphTargetForcedOrder;
  1824. var influences = object.morphTargetInfluences;
  1825. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  1826. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  1827. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  1828. enableAttribute( attributes[ "morphTarget" + m ] );
  1829. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1830. }
  1831. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  1832. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  1833. enableAttribute( attributes[ "morphNormal" + m ] );
  1834. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1835. }
  1836. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  1837. m ++;
  1838. }
  1839. } else {
  1840. // find the most influencing
  1841. var influence, activeInfluenceIndices = [];
  1842. var influences = object.morphTargetInfluences;
  1843. var i, il = influences.length;
  1844. for ( i = 0; i < il; i ++ ) {
  1845. influence = influences[ i ];
  1846. if ( influence > 0 ) {
  1847. activeInfluenceIndices.push( [ influence, i ] );
  1848. }
  1849. }
  1850. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  1851. activeInfluenceIndices.sort( numericalSort );
  1852. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  1853. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  1854. activeInfluenceIndices.sort( numericalSort );
  1855. } else if ( activeInfluenceIndices.length === 0 ) {
  1856. activeInfluenceIndices.push( [ 0, 0 ] );
  1857. };
  1858. var influenceIndex, m = 0;
  1859. while ( m < material.numSupportedMorphTargets ) {
  1860. if ( activeInfluenceIndices[ m ] ) {
  1861. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  1862. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  1863. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  1864. enableAttribute( attributes[ "morphTarget" + m ] );
  1865. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1866. }
  1867. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  1868. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  1869. enableAttribute( attributes[ "morphNormal" + m ] );
  1870. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1871. }
  1872. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  1873. } else {
  1874. /*
  1875. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1876. if ( material.morphNormals ) {
  1877. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1878. }
  1879. */
  1880. object.__webglMorphTargetInfluences[ m ] = 0;
  1881. }
  1882. m ++;
  1883. }
  1884. }
  1885. // load updated influences uniform
  1886. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  1887. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  1888. }
  1889. };
  1890. // Sorting
  1891. function painterSortStable ( a, b ) {
  1892. if ( a.z !== b.z ) {
  1893. return b.z - a.z;
  1894. } else {
  1895. return a.id - b.id;
  1896. }
  1897. };
  1898. function numericalSort ( a, b ) {
  1899. return b[ 0 ] - a[ 0 ];
  1900. };
  1901. // Rendering
  1902. this.render = function ( scene, camera, renderTarget, forceClear ) {
  1903. if ( camera instanceof THREE.Camera === false ) {
  1904. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  1905. return;
  1906. }
  1907. var i, il,
  1908. webglObject, object,
  1909. renderList,
  1910. lights = scene.__lights,
  1911. fog = scene.fog;
  1912. // reset caching for this frame
  1913. _currentMaterialId = -1;
  1914. _lightsNeedUpdate = true;
  1915. // update scene graph
  1916. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  1917. // update camera matrices and frustum
  1918. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  1919. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1920. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  1921. _frustum.setFromMatrix( _projScreenMatrix );
  1922. // update WebGL objects
  1923. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  1924. // custom render plugins (pre pass)
  1925. renderPlugins( this.renderPluginsPre, scene, camera );
  1926. //
  1927. _this.info.render.calls = 0;
  1928. _this.info.render.vertices = 0;
  1929. _this.info.render.faces = 0;
  1930. _this.info.render.points = 0;
  1931. this.setRenderTarget( renderTarget );
  1932. if ( this.autoClear || forceClear ) {
  1933. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  1934. }
  1935. // set matrices for regular objects (frustum culled)
  1936. renderList = scene.__webglObjects;
  1937. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  1938. webglObject = renderList[ i ];
  1939. object = webglObject.object;
  1940. webglObject.id = i;
  1941. webglObject.render = false;
  1942. if ( object.visible ) {
  1943. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  1944. setupMatrices( object, camera );
  1945. unrollBufferMaterial( webglObject );
  1946. webglObject.render = true;
  1947. if ( this.sortObjects === true ) {
  1948. if ( object.renderDepth !== null ) {
  1949. webglObject.z = object.renderDepth;
  1950. } else {
  1951. _vector3.setFromMatrixPosition( object.matrixWorld );
  1952. _vector3.applyProjection( _projScreenMatrix );
  1953. webglObject.z = _vector3.z;
  1954. }
  1955. }
  1956. }
  1957. }
  1958. }
  1959. if ( this.sortObjects ) {
  1960. renderList.sort( painterSortStable );
  1961. }
  1962. // set matrices for immediate objects
  1963. renderList = scene.__webglObjectsImmediate;
  1964. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  1965. webglObject = renderList[ i ];
  1966. object = webglObject.object;
  1967. if ( object.visible ) {
  1968. setupMatrices( object, camera );
  1969. unrollImmediateBufferMaterial( webglObject );
  1970. }
  1971. }
  1972. if ( scene.overrideMaterial ) {
  1973. var material = scene.overrideMaterial;
  1974. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  1975. this.setDepthTest( material.depthTest );
  1976. this.setDepthWrite( material.depthWrite );
  1977. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  1978. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  1979. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  1980. } else {
  1981. var material = null;
  1982. // opaque pass (front-to-back order)
  1983. this.setBlending( THREE.NoBlending );
  1984. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  1985. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  1986. // transparent pass (back-to-front order)
  1987. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  1988. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  1989. }
  1990. // custom render plugins (post pass)
  1991. renderPlugins( this.renderPluginsPost, scene, camera );
  1992. // Generate mipmap if we're using any kind of mipmap filtering
  1993. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  1994. updateRenderTargetMipmap( renderTarget );
  1995. }
  1996. // Ensure depth buffer writing is enabled so it can be cleared on next render
  1997. this.setDepthTest( true );
  1998. this.setDepthWrite( true );
  1999. // _gl.finish();
  2000. };
  2001. function renderPlugins( plugins, scene, camera ) {
  2002. if ( ! plugins.length ) return;
  2003. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  2004. // reset state for plugin (to start from clean slate)
  2005. _currentProgram = null;
  2006. _currentCamera = null;
  2007. _oldBlending = -1;
  2008. _oldDepthTest = -1;
  2009. _oldDepthWrite = -1;
  2010. _oldDoubleSided = -1;
  2011. _oldFlipSided = -1;
  2012. _currentGeometryGroupHash = -1;
  2013. _currentMaterialId = -1;
  2014. _lightsNeedUpdate = true;
  2015. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  2016. // reset state after plugin (anything could have changed)
  2017. _currentProgram = null;
  2018. _currentCamera = null;
  2019. _oldBlending = -1;
  2020. _oldDepthTest = -1;
  2021. _oldDepthWrite = -1;
  2022. _oldDoubleSided = -1;
  2023. _oldFlipSided = -1;
  2024. _currentGeometryGroupHash = -1;
  2025. _currentMaterialId = -1;
  2026. _lightsNeedUpdate = true;
  2027. }
  2028. };
  2029. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2030. var webglObject, object, buffer, material, start, end, delta;
  2031. if ( reverse ) {
  2032. start = renderList.length - 1;
  2033. end = -1;
  2034. delta = -1;
  2035. } else {
  2036. start = 0;
  2037. end = renderList.length;
  2038. delta = 1;
  2039. }
  2040. for ( var i = start; i !== end; i += delta ) {
  2041. webglObject = renderList[ i ];
  2042. if ( webglObject.render ) {
  2043. object = webglObject.object;
  2044. buffer = webglObject.buffer;
  2045. if ( overrideMaterial ) {
  2046. material = overrideMaterial;
  2047. } else {
  2048. material = webglObject[ materialType ];
  2049. if ( ! material ) continue;
  2050. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2051. _this.setDepthTest( material.depthTest );
  2052. _this.setDepthWrite( material.depthWrite );
  2053. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2054. }
  2055. _this.setMaterialFaces( material );
  2056. if ( buffer instanceof THREE.BufferGeometry ) {
  2057. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  2058. } else {
  2059. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  2060. }
  2061. }
  2062. }
  2063. };
  2064. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2065. var webglObject, object, material, program;
  2066. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  2067. webglObject = renderList[ i ];
  2068. object = webglObject.object;
  2069. if ( object.visible ) {
  2070. if ( overrideMaterial ) {
  2071. material = overrideMaterial;
  2072. } else {
  2073. material = webglObject[ materialType ];
  2074. if ( ! material ) continue;
  2075. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2076. _this.setDepthTest( material.depthTest );
  2077. _this.setDepthWrite( material.depthWrite );
  2078. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2079. }
  2080. _this.renderImmediateObject( camera, lights, fog, material, object );
  2081. }
  2082. }
  2083. };
  2084. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  2085. var program = setProgram( camera, lights, fog, material, object );
  2086. _currentGeometryGroupHash = -1;
  2087. _this.setMaterialFaces( material );
  2088. if ( object.immediateRenderCallback ) {
  2089. object.immediateRenderCallback( program, _gl, _frustum );
  2090. } else {
  2091. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  2092. }
  2093. };
  2094. function unrollImmediateBufferMaterial ( globject ) {
  2095. var object = globject.object,
  2096. material = object.material;
  2097. if ( material.transparent ) {
  2098. globject.transparent = material;
  2099. globject.opaque = null;
  2100. } else {
  2101. globject.opaque = material;
  2102. globject.transparent = null;
  2103. }
  2104. };
  2105. function unrollBufferMaterial ( globject ) {
  2106. var object = globject.object,
  2107. buffer = globject.buffer,
  2108. material, materialIndex, meshMaterial;
  2109. meshMaterial = object.material;
  2110. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  2111. materialIndex = buffer.materialIndex;
  2112. material = meshMaterial.materials[ materialIndex ];
  2113. if ( material.transparent ) {
  2114. globject.transparent = material;
  2115. globject.opaque = null;
  2116. } else {
  2117. globject.opaque = material;
  2118. globject.transparent = null;
  2119. }
  2120. } else {
  2121. material = meshMaterial;
  2122. if ( material ) {
  2123. if ( material.transparent ) {
  2124. globject.transparent = material;
  2125. globject.opaque = null;
  2126. } else {
  2127. globject.opaque = material;
  2128. globject.transparent = null;
  2129. }
  2130. }
  2131. }
  2132. };
  2133. // Geometry splitting
  2134. function sortFacesByMaterial ( geometry, material ) {
  2135. var f, fl, face, materialIndex, vertices,
  2136. groupHash, hash_map = {};
  2137. var numMorphTargets = geometry.morphTargets.length;
  2138. var numMorphNormals = geometry.morphNormals.length;
  2139. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  2140. geometry.geometryGroups = {};
  2141. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  2142. face = geometry.faces[ f ];
  2143. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  2144. if ( hash_map[ materialIndex ] === undefined ) {
  2145. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  2146. }
  2147. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2148. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  2149. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  2150. }
  2151. vertices = 3;
  2152. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  2153. hash_map[ materialIndex ].counter += 1;
  2154. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2155. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  2156. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  2157. }
  2158. }
  2159. geometry.geometryGroups[ groupHash ].faces3.push( f );
  2160. geometry.geometryGroups[ groupHash ].vertices += vertices;
  2161. }
  2162. geometry.geometryGroupsList = [];
  2163. for ( var g in geometry.geometryGroups ) {
  2164. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  2165. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  2166. }
  2167. };
  2168. // Objects refresh
  2169. this.initWebGLObjects = function ( scene ) {
  2170. if ( !scene.__webglObjects ) {
  2171. scene.__webglObjects = [];
  2172. scene.__webglObjectsImmediate = [];
  2173. scene.__webglSprites = [];
  2174. scene.__webglFlares = [];
  2175. }
  2176. while ( scene.__objectsAdded.length ) {
  2177. addObject( scene.__objectsAdded[ 0 ], scene );
  2178. scene.__objectsAdded.splice( 0, 1 );
  2179. }
  2180. while ( scene.__objectsRemoved.length ) {
  2181. removeObject( scene.__objectsRemoved[ 0 ], scene );
  2182. scene.__objectsRemoved.splice( 0, 1 );
  2183. }
  2184. // update must be called after objects adding / removal
  2185. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  2186. var object = scene.__webglObjects[ o ].object;
  2187. // TODO: Remove this hack (WebGLRenderer refactoring)
  2188. if ( object.__webglInit === undefined ) {
  2189. if ( object.__webglActive !== undefined ) {
  2190. removeObject( object, scene );
  2191. }
  2192. addObject( object, scene );
  2193. }
  2194. updateObject( object );
  2195. }
  2196. };
  2197. // Objects adding
  2198. function addObject( object, scene ) {
  2199. var g, geometry, material, geometryGroup;
  2200. if ( object.__webglInit === undefined ) {
  2201. object.__webglInit = true;
  2202. object._modelViewMatrix = new THREE.Matrix4();
  2203. object._normalMatrix = new THREE.Matrix3();
  2204. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  2205. object.geometry.__webglInit = true;
  2206. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  2207. }
  2208. geometry = object.geometry;
  2209. if ( geometry === undefined ) {
  2210. // fail silently for now
  2211. } else if ( geometry instanceof THREE.BufferGeometry ) {
  2212. initDirectBuffers( geometry );
  2213. } else if ( object instanceof THREE.Mesh ) {
  2214. material = object.material;
  2215. if ( geometry.geometryGroups === undefined ) {
  2216. sortFacesByMaterial( geometry, material );
  2217. }
  2218. // create separate VBOs per geometry chunk
  2219. for ( g in geometry.geometryGroups ) {
  2220. geometryGroup = geometry.geometryGroups[ g ];
  2221. // initialise VBO on the first access
  2222. if ( ! geometryGroup.__webglVertexBuffer ) {
  2223. createMeshBuffers( geometryGroup );
  2224. initMeshBuffers( geometryGroup, object );
  2225. geometry.verticesNeedUpdate = true;
  2226. geometry.morphTargetsNeedUpdate = true;
  2227. geometry.elementsNeedUpdate = true;
  2228. geometry.uvsNeedUpdate = true;
  2229. geometry.normalsNeedUpdate = true;
  2230. geometry.tangentsNeedUpdate = true;
  2231. geometry.colorsNeedUpdate = true;
  2232. }
  2233. }
  2234. } else if ( object instanceof THREE.Line ) {
  2235. if ( ! geometry.__webglVertexBuffer ) {
  2236. createLineBuffers( geometry );
  2237. initLineBuffers( geometry, object );
  2238. geometry.verticesNeedUpdate = true;
  2239. geometry.colorsNeedUpdate = true;
  2240. geometry.lineDistancesNeedUpdate = true;
  2241. }
  2242. } else if ( object instanceof THREE.ParticleSystem ) {
  2243. if ( ! geometry.__webglVertexBuffer ) {
  2244. createParticleBuffers( geometry );
  2245. initParticleBuffers( geometry, object );
  2246. geometry.verticesNeedUpdate = true;
  2247. geometry.colorsNeedUpdate = true;
  2248. }
  2249. }
  2250. }
  2251. if ( object.__webglActive === undefined ) {
  2252. if ( object instanceof THREE.Mesh ) {
  2253. geometry = object.geometry;
  2254. if ( geometry instanceof THREE.BufferGeometry ) {
  2255. addBuffer( scene.__webglObjects, geometry, object );
  2256. } else if ( geometry instanceof THREE.Geometry ) {
  2257. for ( g in geometry.geometryGroups ) {
  2258. geometryGroup = geometry.geometryGroups[ g ];
  2259. addBuffer( scene.__webglObjects, geometryGroup, object );
  2260. }
  2261. }
  2262. } else if ( object instanceof THREE.Line ||
  2263. object instanceof THREE.ParticleSystem ) {
  2264. geometry = object.geometry;
  2265. addBuffer( scene.__webglObjects, geometry, object );
  2266. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2267. addBufferImmediate( scene.__webglObjectsImmediate, object );
  2268. } else if ( object instanceof THREE.Sprite ) {
  2269. scene.__webglSprites.push( object );
  2270. } else if ( object instanceof THREE.LensFlare ) {
  2271. scene.__webglFlares.push( object );
  2272. }
  2273. object.__webglActive = true;
  2274. }
  2275. };
  2276. function addBuffer( objlist, buffer, object ) {
  2277. objlist.push(
  2278. {
  2279. id: null,
  2280. buffer: buffer,
  2281. object: object,
  2282. opaque: null,
  2283. transparent: null,
  2284. z: 0
  2285. }
  2286. );
  2287. };
  2288. function addBufferImmediate( objlist, object ) {
  2289. objlist.push(
  2290. {
  2291. id: null,
  2292. object: object,
  2293. opaque: null,
  2294. transparent: null,
  2295. z: 0
  2296. }
  2297. );
  2298. };
  2299. // Objects updates
  2300. function updateObject( object ) {
  2301. var geometry = object.geometry,
  2302. geometryGroup, customAttributesDirty, material;
  2303. if ( geometry instanceof THREE.BufferGeometry ) {
  2304. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  2305. } else if ( object instanceof THREE.Mesh ) {
  2306. // check all geometry groups
  2307. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  2308. geometryGroup = geometry.geometryGroupsList[ i ];
  2309. material = getBufferMaterial( object, geometryGroup );
  2310. if ( geometry.buffersNeedUpdate ) {
  2311. initMeshBuffers( geometryGroup, object );
  2312. }
  2313. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2314. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  2315. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  2316. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  2317. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  2318. }
  2319. }
  2320. geometry.verticesNeedUpdate = false;
  2321. geometry.morphTargetsNeedUpdate = false;
  2322. geometry.elementsNeedUpdate = false;
  2323. geometry.uvsNeedUpdate = false;
  2324. geometry.normalsNeedUpdate = false;
  2325. geometry.colorsNeedUpdate = false;
  2326. geometry.tangentsNeedUpdate = false;
  2327. geometry.buffersNeedUpdate = false;
  2328. material.attributes && clearCustomAttributes( material );
  2329. } else if ( object instanceof THREE.Line ) {
  2330. material = getBufferMaterial( object, geometry );
  2331. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2332. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  2333. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  2334. }
  2335. geometry.verticesNeedUpdate = false;
  2336. geometry.colorsNeedUpdate = false;
  2337. geometry.lineDistancesNeedUpdate = false;
  2338. material.attributes && clearCustomAttributes( material );
  2339. } else if ( object instanceof THREE.ParticleSystem ) {
  2340. material = getBufferMaterial( object, geometry );
  2341. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2342. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  2343. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  2344. }
  2345. geometry.verticesNeedUpdate = false;
  2346. geometry.colorsNeedUpdate = false;
  2347. material.attributes && clearCustomAttributes( material );
  2348. }
  2349. };
  2350. // Objects updates - custom attributes check
  2351. function areCustomAttributesDirty( material ) {
  2352. for ( var a in material.attributes ) {
  2353. if ( material.attributes[ a ].needsUpdate ) return true;
  2354. }
  2355. return false;
  2356. };
  2357. function clearCustomAttributes( material ) {
  2358. for ( var a in material.attributes ) {
  2359. material.attributes[ a ].needsUpdate = false;
  2360. }
  2361. };
  2362. // Objects removal
  2363. function removeObject( object, scene ) {
  2364. if ( object instanceof THREE.Mesh ||
  2365. object instanceof THREE.ParticleSystem ||
  2366. object instanceof THREE.Line ) {
  2367. removeInstances( scene.__webglObjects, object );
  2368. } else if ( object instanceof THREE.Sprite ) {
  2369. removeInstancesDirect( scene.__webglSprites, object );
  2370. } else if ( object instanceof THREE.LensFlare ) {
  2371. removeInstancesDirect( scene.__webglFlares, object );
  2372. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2373. removeInstances( scene.__webglObjectsImmediate, object );
  2374. }
  2375. delete object.__webglActive;
  2376. };
  2377. function removeInstances( objlist, object ) {
  2378. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2379. if ( objlist[ o ].object === object ) {
  2380. objlist.splice( o, 1 );
  2381. }
  2382. }
  2383. };
  2384. function removeInstancesDirect( objlist, object ) {
  2385. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2386. if ( objlist[ o ] === object ) {
  2387. objlist.splice( o, 1 );
  2388. }
  2389. }
  2390. };
  2391. // Materials
  2392. this.initMaterial = function ( material, lights, fog, object ) {
  2393. material.addEventListener( 'dispose', onMaterialDispose );
  2394. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  2395. if ( material instanceof THREE.MeshDepthMaterial ) {
  2396. shaderID = 'depth';
  2397. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2398. shaderID = 'normal';
  2399. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  2400. shaderID = 'basic';
  2401. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2402. shaderID = 'lambert';
  2403. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2404. shaderID = 'phong';
  2405. } else if ( material instanceof THREE.LineBasicMaterial ) {
  2406. shaderID = 'basic';
  2407. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2408. shaderID = 'dashed';
  2409. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  2410. shaderID = 'particle_basic';
  2411. }
  2412. if ( shaderID ) {
  2413. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  2414. }
  2415. // heuristics to create shader parameters according to lights in the scene
  2416. // (not to blow over maxLights budget)
  2417. maxLightCount = allocateLights( lights );
  2418. maxShadows = allocateShadows( lights );
  2419. maxBones = allocateBones( object );
  2420. parameters = {
  2421. map: !!material.map,
  2422. envMap: !!material.envMap,
  2423. lightMap: !!material.lightMap,
  2424. bumpMap: !!material.bumpMap,
  2425. normalMap: !!material.normalMap,
  2426. specularMap: !!material.specularMap,
  2427. vertexColors: material.vertexColors,
  2428. fog: fog,
  2429. useFog: material.fog,
  2430. fogExp: fog instanceof THREE.FogExp2,
  2431. sizeAttenuation: material.sizeAttenuation,
  2432. skinning: material.skinning,
  2433. maxBones: maxBones,
  2434. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  2435. morphTargets: material.morphTargets,
  2436. morphNormals: material.morphNormals,
  2437. maxMorphTargets: this.maxMorphTargets,
  2438. maxMorphNormals: this.maxMorphNormals,
  2439. maxDirLights: maxLightCount.directional,
  2440. maxPointLights: maxLightCount.point,
  2441. maxSpotLights: maxLightCount.spot,
  2442. maxHemiLights: maxLightCount.hemi,
  2443. maxShadows: maxShadows,
  2444. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  2445. shadowMapType: this.shadowMapType,
  2446. shadowMapDebug: this.shadowMapDebug,
  2447. shadowMapCascade: this.shadowMapCascade,
  2448. alphaTest: material.alphaTest,
  2449. metal: material.metal,
  2450. perPixel: material.perPixel,
  2451. wrapAround: material.wrapAround,
  2452. doubleSided: material.side === THREE.DoubleSide,
  2453. flipSided: material.side === THREE.BackSide
  2454. };
  2455. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  2456. var attributes = material.program.attributes;
  2457. if ( material.morphTargets ) {
  2458. material.numSupportedMorphTargets = 0;
  2459. var id, base = "morphTarget";
  2460. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  2461. id = base + i;
  2462. if ( attributes[ id ] >= 0 ) {
  2463. material.numSupportedMorphTargets ++;
  2464. }
  2465. }
  2466. }
  2467. if ( material.morphNormals ) {
  2468. material.numSupportedMorphNormals = 0;
  2469. var id, base = "morphNormal";
  2470. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  2471. id = base + i;
  2472. if ( attributes[ id ] >= 0 ) {
  2473. material.numSupportedMorphNormals ++;
  2474. }
  2475. }
  2476. }
  2477. material.uniformsList = [];
  2478. for ( u in material.uniforms ) {
  2479. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  2480. }
  2481. };
  2482. function setMaterialShaders( material, shaders ) {
  2483. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  2484. material.vertexShader = shaders.vertexShader;
  2485. material.fragmentShader = shaders.fragmentShader;
  2486. };
  2487. function setProgram( camera, lights, fog, material, object ) {
  2488. _usedTextureUnits = 0;
  2489. if ( material.needsUpdate ) {
  2490. if ( material.program ) deallocateMaterial( material );
  2491. _this.initMaterial( material, lights, fog, object );
  2492. material.needsUpdate = false;
  2493. }
  2494. if ( material.morphTargets ) {
  2495. if ( ! object.__webglMorphTargetInfluences ) {
  2496. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  2497. }
  2498. }
  2499. var refreshMaterial = false;
  2500. var program = material.program,
  2501. p_uniforms = program.uniforms,
  2502. m_uniforms = material.uniforms;
  2503. if ( program !== _currentProgram ) {
  2504. _gl.useProgram( program );
  2505. _currentProgram = program;
  2506. refreshMaterial = true;
  2507. }
  2508. if ( material.id !== _currentMaterialId ) {
  2509. _currentMaterialId = material.id;
  2510. refreshMaterial = true;
  2511. }
  2512. if ( refreshMaterial || camera !== _currentCamera ) {
  2513. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2514. if ( camera !== _currentCamera ) _currentCamera = camera;
  2515. }
  2516. // skinning uniforms must be set even if material didn't change
  2517. // auto-setting of texture unit for bone texture must go before other textures
  2518. // not sure why, but otherwise weird things happen
  2519. if ( material.skinning ) {
  2520. if ( _supportsBoneTextures && object.useVertexTexture ) {
  2521. if ( p_uniforms.boneTexture !== null ) {
  2522. var textureUnit = getTextureUnit();
  2523. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  2524. _this.setTexture( object.boneTexture, textureUnit );
  2525. }
  2526. if ( p_uniforms.boneTextureWidth !== null ) {
  2527. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  2528. }
  2529. if ( p_uniforms.boneTextureHeight !== null ) {
  2530. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  2531. }
  2532. } else {
  2533. if ( p_uniforms.boneGlobalMatrices !== null ) {
  2534. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  2535. }
  2536. }
  2537. }
  2538. if ( refreshMaterial ) {
  2539. // refresh uniforms common to several materials
  2540. if ( fog && material.fog ) {
  2541. refreshUniformsFog( m_uniforms, fog );
  2542. }
  2543. if ( material instanceof THREE.MeshPhongMaterial ||
  2544. material instanceof THREE.MeshLambertMaterial ||
  2545. material.lights ) {
  2546. if ( _lightsNeedUpdate ) {
  2547. setupLights( program, lights );
  2548. _lightsNeedUpdate = false;
  2549. }
  2550. refreshUniformsLights( m_uniforms, _lights );
  2551. }
  2552. if ( material instanceof THREE.MeshBasicMaterial ||
  2553. material instanceof THREE.MeshLambertMaterial ||
  2554. material instanceof THREE.MeshPhongMaterial ) {
  2555. refreshUniformsCommon( m_uniforms, material );
  2556. }
  2557. // refresh single material specific uniforms
  2558. if ( material instanceof THREE.LineBasicMaterial ) {
  2559. refreshUniformsLine( m_uniforms, material );
  2560. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2561. refreshUniformsLine( m_uniforms, material );
  2562. refreshUniformsDash( m_uniforms, material );
  2563. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  2564. refreshUniformsParticle( m_uniforms, material );
  2565. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2566. refreshUniformsPhong( m_uniforms, material );
  2567. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2568. refreshUniformsLambert( m_uniforms, material );
  2569. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  2570. m_uniforms.mNear.value = camera.near;
  2571. m_uniforms.mFar.value = camera.far;
  2572. m_uniforms.opacity.value = material.opacity;
  2573. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2574. m_uniforms.opacity.value = material.opacity;
  2575. }
  2576. if ( object.receiveShadow && ! material._shadowPass ) {
  2577. refreshUniformsShadow( m_uniforms, lights );
  2578. }
  2579. // load common uniforms
  2580. loadUniformsGeneric( program, material.uniformsList );
  2581. // load material specific uniforms
  2582. // (shader material also gets them for the sake of genericity)
  2583. if ( material instanceof THREE.ShaderMaterial ||
  2584. material instanceof THREE.MeshPhongMaterial ||
  2585. material.envMap ) {
  2586. if ( p_uniforms.cameraPosition !== null ) {
  2587. _vector3.setFromMatrixPosition( camera.matrixWorld );
  2588. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  2589. }
  2590. }
  2591. if ( material instanceof THREE.MeshPhongMaterial ||
  2592. material instanceof THREE.MeshLambertMaterial ||
  2593. material instanceof THREE.ShaderMaterial ||
  2594. material.skinning ) {
  2595. if ( p_uniforms.viewMatrix !== null ) {
  2596. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  2597. }
  2598. }
  2599. }
  2600. loadUniformsMatrices( p_uniforms, object );
  2601. if ( p_uniforms.modelMatrix !== null ) {
  2602. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  2603. }
  2604. return program;
  2605. };
  2606. // Uniforms (refresh uniforms objects)
  2607. function refreshUniformsCommon ( uniforms, material ) {
  2608. uniforms.opacity.value = material.opacity;
  2609. if ( _this.gammaInput ) {
  2610. uniforms.diffuse.value.copyGammaToLinear( material.color );
  2611. } else {
  2612. uniforms.diffuse.value = material.color;
  2613. }
  2614. uniforms.map.value = material.map;
  2615. uniforms.lightMap.value = material.lightMap;
  2616. uniforms.specularMap.value = material.specularMap;
  2617. if ( material.bumpMap ) {
  2618. uniforms.bumpMap.value = material.bumpMap;
  2619. uniforms.bumpScale.value = material.bumpScale;
  2620. }
  2621. if ( material.normalMap ) {
  2622. uniforms.normalMap.value = material.normalMap;
  2623. uniforms.normalScale.value.copy( material.normalScale );
  2624. }
  2625. // uv repeat and offset setting priorities
  2626. // 1. color map
  2627. // 2. specular map
  2628. // 3. normal map
  2629. // 4. bump map
  2630. var uvScaleMap;
  2631. if ( material.map ) {
  2632. uvScaleMap = material.map;
  2633. } else if ( material.specularMap ) {
  2634. uvScaleMap = material.specularMap;
  2635. } else if ( material.normalMap ) {
  2636. uvScaleMap = material.normalMap;
  2637. } else if ( material.bumpMap ) {
  2638. uvScaleMap = material.bumpMap;
  2639. }
  2640. if ( uvScaleMap !== undefined ) {
  2641. var offset = uvScaleMap.offset;
  2642. var repeat = uvScaleMap.repeat;
  2643. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  2644. }
  2645. uniforms.envMap.value = material.envMap;
  2646. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  2647. if ( _this.gammaInput ) {
  2648. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  2649. uniforms.reflectivity.value = material.reflectivity;
  2650. } else {
  2651. uniforms.reflectivity.value = material.reflectivity;
  2652. }
  2653. uniforms.refractionRatio.value = material.refractionRatio;
  2654. uniforms.combine.value = material.combine;
  2655. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  2656. };
  2657. function refreshUniformsLine ( uniforms, material ) {
  2658. uniforms.diffuse.value = material.color;
  2659. uniforms.opacity.value = material.opacity;
  2660. };
  2661. function refreshUniformsDash ( uniforms, material ) {
  2662. uniforms.dashSize.value = material.dashSize;
  2663. uniforms.totalSize.value = material.dashSize + material.gapSize;
  2664. uniforms.scale.value = material.scale;
  2665. };
  2666. function refreshUniformsParticle ( uniforms, material ) {
  2667. uniforms.psColor.value = material.color;
  2668. uniforms.opacity.value = material.opacity;
  2669. uniforms.size.value = material.size;
  2670. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  2671. uniforms.map.value = material.map;
  2672. };
  2673. function refreshUniformsFog ( uniforms, fog ) {
  2674. uniforms.fogColor.value = fog.color;
  2675. if ( fog instanceof THREE.Fog ) {
  2676. uniforms.fogNear.value = fog.near;
  2677. uniforms.fogFar.value = fog.far;
  2678. } else if ( fog instanceof THREE.FogExp2 ) {
  2679. uniforms.fogDensity.value = fog.density;
  2680. }
  2681. };
  2682. function refreshUniformsPhong ( uniforms, material ) {
  2683. uniforms.shininess.value = material.shininess;
  2684. if ( _this.gammaInput ) {
  2685. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2686. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2687. uniforms.specular.value.copyGammaToLinear( material.specular );
  2688. } else {
  2689. uniforms.ambient.value = material.ambient;
  2690. uniforms.emissive.value = material.emissive;
  2691. uniforms.specular.value = material.specular;
  2692. }
  2693. if ( material.wrapAround ) {
  2694. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2695. }
  2696. };
  2697. function refreshUniformsLambert ( uniforms, material ) {
  2698. if ( _this.gammaInput ) {
  2699. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2700. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2701. } else {
  2702. uniforms.ambient.value = material.ambient;
  2703. uniforms.emissive.value = material.emissive;
  2704. }
  2705. if ( material.wrapAround ) {
  2706. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2707. }
  2708. };
  2709. function refreshUniformsLights ( uniforms, lights ) {
  2710. uniforms.ambientLightColor.value = lights.ambient;
  2711. uniforms.directionalLightColor.value = lights.directional.colors;
  2712. uniforms.directionalLightDirection.value = lights.directional.positions;
  2713. uniforms.pointLightColor.value = lights.point.colors;
  2714. uniforms.pointLightPosition.value = lights.point.positions;
  2715. uniforms.pointLightDistance.value = lights.point.distances;
  2716. uniforms.spotLightColor.value = lights.spot.colors;
  2717. uniforms.spotLightPosition.value = lights.spot.positions;
  2718. uniforms.spotLightDistance.value = lights.spot.distances;
  2719. uniforms.spotLightDirection.value = lights.spot.directions;
  2720. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  2721. uniforms.spotLightExponent.value = lights.spot.exponents;
  2722. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  2723. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  2724. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  2725. };
  2726. function refreshUniformsShadow ( uniforms, lights ) {
  2727. if ( uniforms.shadowMatrix ) {
  2728. var j = 0;
  2729. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  2730. var light = lights[ i ];
  2731. if ( ! light.castShadow ) continue;
  2732. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  2733. uniforms.shadowMap.value[ j ] = light.shadowMap;
  2734. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  2735. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  2736. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  2737. uniforms.shadowBias.value[ j ] = light.shadowBias;
  2738. j ++;
  2739. }
  2740. }
  2741. }
  2742. };
  2743. // Uniforms (load to GPU)
  2744. function loadUniformsMatrices ( uniforms, object ) {
  2745. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  2746. if ( uniforms.normalMatrix ) {
  2747. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  2748. }
  2749. };
  2750. function getTextureUnit() {
  2751. var textureUnit = _usedTextureUnits;
  2752. if ( textureUnit >= _maxTextures ) {
  2753. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  2754. }
  2755. _usedTextureUnits += 1;
  2756. return textureUnit;
  2757. };
  2758. function loadUniformsGeneric ( program, uniforms ) {
  2759. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  2760. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  2761. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  2762. if ( !location ) continue;
  2763. uniform = uniforms[ j ][ 0 ];
  2764. type = uniform.type;
  2765. value = uniform.value;
  2766. if ( type === "i" ) { // single integer
  2767. _gl.uniform1i( location, value );
  2768. } else if ( type === "f" ) { // single float
  2769. _gl.uniform1f( location, value );
  2770. } else if ( type === "v2" ) { // single THREE.Vector2
  2771. _gl.uniform2f( location, value.x, value.y );
  2772. } else if ( type === "v3" ) { // single THREE.Vector3
  2773. _gl.uniform3f( location, value.x, value.y, value.z );
  2774. } else if ( type === "v4" ) { // single THREE.Vector4
  2775. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  2776. } else if ( type === "c" ) { // single THREE.Color
  2777. _gl.uniform3f( location, value.r, value.g, value.b );
  2778. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  2779. _gl.uniform1iv( location, value );
  2780. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  2781. _gl.uniform3iv( location, value );
  2782. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  2783. _gl.uniform1fv( location, value );
  2784. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  2785. _gl.uniform3fv( location, value );
  2786. } else if ( type === "v2v" ) { // array of THREE.Vector2
  2787. if ( uniform._array === undefined ) {
  2788. uniform._array = new Float32Array( 2 * value.length );
  2789. }
  2790. for ( i = 0, il = value.length; i < il; i ++ ) {
  2791. offset = i * 2;
  2792. uniform._array[ offset ] = value[ i ].x;
  2793. uniform._array[ offset + 1 ] = value[ i ].y;
  2794. }
  2795. _gl.uniform2fv( location, uniform._array );
  2796. } else if ( type === "v3v" ) { // array of THREE.Vector3
  2797. if ( uniform._array === undefined ) {
  2798. uniform._array = new Float32Array( 3 * value.length );
  2799. }
  2800. for ( i = 0, il = value.length; i < il; i ++ ) {
  2801. offset = i * 3;
  2802. uniform._array[ offset ] = value[ i ].x;
  2803. uniform._array[ offset + 1 ] = value[ i ].y;
  2804. uniform._array[ offset + 2 ] = value[ i ].z;
  2805. }
  2806. _gl.uniform3fv( location, uniform._array );
  2807. } else if ( type === "v4v" ) { // array of THREE.Vector4
  2808. if ( uniform._array === undefined ) {
  2809. uniform._array = new Float32Array( 4 * value.length );
  2810. }
  2811. for ( i = 0, il = value.length; i < il; i ++ ) {
  2812. offset = i * 4;
  2813. uniform._array[ offset ] = value[ i ].x;
  2814. uniform._array[ offset + 1 ] = value[ i ].y;
  2815. uniform._array[ offset + 2 ] = value[ i ].z;
  2816. uniform._array[ offset + 3 ] = value[ i ].w;
  2817. }
  2818. _gl.uniform4fv( location, uniform._array );
  2819. } else if ( type === "m4") { // single THREE.Matrix4
  2820. if ( uniform._array === undefined ) {
  2821. uniform._array = new Float32Array( 16 );
  2822. }
  2823. value.flattenToArray( uniform._array );
  2824. _gl.uniformMatrix4fv( location, false, uniform._array );
  2825. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  2826. if ( uniform._array === undefined ) {
  2827. uniform._array = new Float32Array( 16 * value.length );
  2828. }
  2829. for ( i = 0, il = value.length; i < il; i ++ ) {
  2830. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  2831. }
  2832. _gl.uniformMatrix4fv( location, false, uniform._array );
  2833. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  2834. texture = value;
  2835. textureUnit = getTextureUnit();
  2836. _gl.uniform1i( location, textureUnit );
  2837. if ( !texture ) continue;
  2838. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  2839. setCubeTexture( texture, textureUnit );
  2840. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  2841. setCubeTextureDynamic( texture, textureUnit );
  2842. } else {
  2843. _this.setTexture( texture, textureUnit );
  2844. }
  2845. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  2846. if ( uniform._array === undefined ) {
  2847. uniform._array = [];
  2848. }
  2849. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2850. uniform._array[ i ] = getTextureUnit();
  2851. }
  2852. _gl.uniform1iv( location, uniform._array );
  2853. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2854. texture = uniform.value[ i ];
  2855. textureUnit = uniform._array[ i ];
  2856. if ( !texture ) continue;
  2857. _this.setTexture( texture, textureUnit );
  2858. }
  2859. } else {
  2860. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  2861. }
  2862. }
  2863. };
  2864. function setupMatrices ( object, camera ) {
  2865. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  2866. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  2867. };
  2868. //
  2869. function setColorGamma( array, offset, color, intensitySq ) {
  2870. array[ offset ] = color.r * color.r * intensitySq;
  2871. array[ offset + 1 ] = color.g * color.g * intensitySq;
  2872. array[ offset + 2 ] = color.b * color.b * intensitySq;
  2873. };
  2874. function setColorLinear( array, offset, color, intensity ) {
  2875. array[ offset ] = color.r * intensity;
  2876. array[ offset + 1 ] = color.g * intensity;
  2877. array[ offset + 2 ] = color.b * intensity;
  2878. };
  2879. function setupLights ( program, lights ) {
  2880. var l, ll, light, n,
  2881. r = 0, g = 0, b = 0,
  2882. color, skyColor, groundColor,
  2883. intensity, intensitySq,
  2884. position,
  2885. distance,
  2886. zlights = _lights,
  2887. dirColors = zlights.directional.colors,
  2888. dirPositions = zlights.directional.positions,
  2889. pointColors = zlights.point.colors,
  2890. pointPositions = zlights.point.positions,
  2891. pointDistances = zlights.point.distances,
  2892. spotColors = zlights.spot.colors,
  2893. spotPositions = zlights.spot.positions,
  2894. spotDistances = zlights.spot.distances,
  2895. spotDirections = zlights.spot.directions,
  2896. spotAnglesCos = zlights.spot.anglesCos,
  2897. spotExponents = zlights.spot.exponents,
  2898. hemiSkyColors = zlights.hemi.skyColors,
  2899. hemiGroundColors = zlights.hemi.groundColors,
  2900. hemiPositions = zlights.hemi.positions,
  2901. dirLength = 0,
  2902. pointLength = 0,
  2903. spotLength = 0,
  2904. hemiLength = 0,
  2905. dirCount = 0,
  2906. pointCount = 0,
  2907. spotCount = 0,
  2908. hemiCount = 0,
  2909. dirOffset = 0,
  2910. pointOffset = 0,
  2911. spotOffset = 0,
  2912. hemiOffset = 0;
  2913. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  2914. light = lights[ l ];
  2915. if ( light.onlyShadow ) continue;
  2916. color = light.color;
  2917. intensity = light.intensity;
  2918. distance = light.distance;
  2919. if ( light instanceof THREE.AmbientLight ) {
  2920. if ( ! light.visible ) continue;
  2921. if ( _this.gammaInput ) {
  2922. r += color.r * color.r;
  2923. g += color.g * color.g;
  2924. b += color.b * color.b;
  2925. } else {
  2926. r += color.r;
  2927. g += color.g;
  2928. b += color.b;
  2929. }
  2930. } else if ( light instanceof THREE.DirectionalLight ) {
  2931. dirCount += 1;
  2932. if ( ! light.visible ) continue;
  2933. _direction.setFromMatrixPosition( light.matrixWorld );
  2934. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  2935. _direction.sub( _vector3 );
  2936. _direction.normalize();
  2937. // skip lights with undefined direction
  2938. // these create troubles in OpenGL (making pixel black)
  2939. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  2940. dirOffset = dirLength * 3;
  2941. dirPositions[ dirOffset ] = _direction.x;
  2942. dirPositions[ dirOffset + 1 ] = _direction.y;
  2943. dirPositions[ dirOffset + 2 ] = _direction.z;
  2944. if ( _this.gammaInput ) {
  2945. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  2946. } else {
  2947. setColorLinear( dirColors, dirOffset, color, intensity );
  2948. }
  2949. dirLength += 1;
  2950. } else if ( light instanceof THREE.PointLight ) {
  2951. pointCount += 1;
  2952. if ( ! light.visible ) continue;
  2953. pointOffset = pointLength * 3;
  2954. if ( _this.gammaInput ) {
  2955. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  2956. } else {
  2957. setColorLinear( pointColors, pointOffset, color, intensity );
  2958. }
  2959. _vector3.setFromMatrixPosition( light.matrixWorld );
  2960. pointPositions[ pointOffset ] = _vector3.x;
  2961. pointPositions[ pointOffset + 1 ] = _vector3.y;
  2962. pointPositions[ pointOffset + 2 ] = _vector3.z;
  2963. pointDistances[ pointLength ] = distance;
  2964. pointLength += 1;
  2965. } else if ( light instanceof THREE.SpotLight ) {
  2966. spotCount += 1;
  2967. if ( ! light.visible ) continue;
  2968. spotOffset = spotLength * 3;
  2969. if ( _this.gammaInput ) {
  2970. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  2971. } else {
  2972. setColorLinear( spotColors, spotOffset, color, intensity );
  2973. }
  2974. _vector3.setFromMatrixPosition( light.matrixWorld );
  2975. spotPositions[ spotOffset ] = _vector3.x;
  2976. spotPositions[ spotOffset + 1 ] = _vector3.y;
  2977. spotPositions[ spotOffset + 2 ] = _vector3.z;
  2978. spotDistances[ spotLength ] = distance;
  2979. _direction.copy( _vector3 );
  2980. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  2981. _direction.sub( _vector3 );
  2982. _direction.normalize();
  2983. spotDirections[ spotOffset ] = _direction.x;
  2984. spotDirections[ spotOffset + 1 ] = _direction.y;
  2985. spotDirections[ spotOffset + 2 ] = _direction.z;
  2986. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  2987. spotExponents[ spotLength ] = light.exponent;
  2988. spotLength += 1;
  2989. } else if ( light instanceof THREE.HemisphereLight ) {
  2990. hemiCount += 1;
  2991. if ( ! light.visible ) continue;
  2992. _direction.setFromMatrixPosition( light.matrixWorld );
  2993. _direction.normalize();
  2994. // skip lights with undefined direction
  2995. // these create troubles in OpenGL (making pixel black)
  2996. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  2997. hemiOffset = hemiLength * 3;
  2998. hemiPositions[ hemiOffset ] = _direction.x;
  2999. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  3000. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  3001. skyColor = light.color;
  3002. groundColor = light.groundColor;
  3003. if ( _this.gammaInput ) {
  3004. intensitySq = intensity * intensity;
  3005. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  3006. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  3007. } else {
  3008. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  3009. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  3010. }
  3011. hemiLength += 1;
  3012. }
  3013. }
  3014. // null eventual remains from removed lights
  3015. // (this is to avoid if in shader)
  3016. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  3017. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  3018. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  3019. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  3020. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  3021. zlights.directional.length = dirLength;
  3022. zlights.point.length = pointLength;
  3023. zlights.spot.length = spotLength;
  3024. zlights.hemi.length = hemiLength;
  3025. zlights.ambient[ 0 ] = r;
  3026. zlights.ambient[ 1 ] = g;
  3027. zlights.ambient[ 2 ] = b;
  3028. };
  3029. // GL state setting
  3030. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  3031. if ( cullFace === THREE.CullFaceNone ) {
  3032. _gl.disable( _gl.CULL_FACE );
  3033. } else {
  3034. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  3035. _gl.frontFace( _gl.CW );
  3036. } else {
  3037. _gl.frontFace( _gl.CCW );
  3038. }
  3039. if ( cullFace === THREE.CullFaceBack ) {
  3040. _gl.cullFace( _gl.BACK );
  3041. } else if ( cullFace === THREE.CullFaceFront ) {
  3042. _gl.cullFace( _gl.FRONT );
  3043. } else {
  3044. _gl.cullFace( _gl.FRONT_AND_BACK );
  3045. }
  3046. _gl.enable( _gl.CULL_FACE );
  3047. }
  3048. };
  3049. this.setMaterialFaces = function ( material ) {
  3050. var doubleSided = material.side === THREE.DoubleSide;
  3051. var flipSided = material.side === THREE.BackSide;
  3052. if ( _oldDoubleSided !== doubleSided ) {
  3053. if ( doubleSided ) {
  3054. _gl.disable( _gl.CULL_FACE );
  3055. } else {
  3056. _gl.enable( _gl.CULL_FACE );
  3057. }
  3058. _oldDoubleSided = doubleSided;
  3059. }
  3060. if ( _oldFlipSided !== flipSided ) {
  3061. if ( flipSided ) {
  3062. _gl.frontFace( _gl.CW );
  3063. } else {
  3064. _gl.frontFace( _gl.CCW );
  3065. }
  3066. _oldFlipSided = flipSided;
  3067. }
  3068. };
  3069. this.setDepthTest = function ( depthTest ) {
  3070. if ( _oldDepthTest !== depthTest ) {
  3071. if ( depthTest ) {
  3072. _gl.enable( _gl.DEPTH_TEST );
  3073. } else {
  3074. _gl.disable( _gl.DEPTH_TEST );
  3075. }
  3076. _oldDepthTest = depthTest;
  3077. }
  3078. };
  3079. this.setDepthWrite = function ( depthWrite ) {
  3080. if ( _oldDepthWrite !== depthWrite ) {
  3081. _gl.depthMask( depthWrite );
  3082. _oldDepthWrite = depthWrite;
  3083. }
  3084. };
  3085. function setLineWidth ( width ) {
  3086. if ( width !== _oldLineWidth ) {
  3087. _gl.lineWidth( width );
  3088. _oldLineWidth = width;
  3089. }
  3090. };
  3091. function setPolygonOffset ( polygonoffset, factor, units ) {
  3092. if ( _oldPolygonOffset !== polygonoffset ) {
  3093. if ( polygonoffset ) {
  3094. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  3095. } else {
  3096. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  3097. }
  3098. _oldPolygonOffset = polygonoffset;
  3099. }
  3100. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  3101. _gl.polygonOffset( factor, units );
  3102. _oldPolygonOffsetFactor = factor;
  3103. _oldPolygonOffsetUnits = units;
  3104. }
  3105. };
  3106. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  3107. if ( blending !== _oldBlending ) {
  3108. if ( blending === THREE.NoBlending ) {
  3109. _gl.disable( _gl.BLEND );
  3110. } else if ( blending === THREE.AdditiveBlending ) {
  3111. _gl.enable( _gl.BLEND );
  3112. _gl.blendEquation( _gl.FUNC_ADD );
  3113. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  3114. } else if ( blending === THREE.SubtractiveBlending ) {
  3115. // TODO: Find blendFuncSeparate() combination
  3116. _gl.enable( _gl.BLEND );
  3117. _gl.blendEquation( _gl.FUNC_ADD );
  3118. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  3119. } else if ( blending === THREE.MultiplyBlending ) {
  3120. // TODO: Find blendFuncSeparate() combination
  3121. _gl.enable( _gl.BLEND );
  3122. _gl.blendEquation( _gl.FUNC_ADD );
  3123. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  3124. } else if ( blending === THREE.CustomBlending ) {
  3125. _gl.enable( _gl.BLEND );
  3126. } else {
  3127. _gl.enable( _gl.BLEND );
  3128. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  3129. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  3130. }
  3131. _oldBlending = blending;
  3132. }
  3133. if ( blending === THREE.CustomBlending ) {
  3134. if ( blendEquation !== _oldBlendEquation ) {
  3135. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  3136. _oldBlendEquation = blendEquation;
  3137. }
  3138. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  3139. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  3140. _oldBlendSrc = blendSrc;
  3141. _oldBlendDst = blendDst;
  3142. }
  3143. } else {
  3144. _oldBlendEquation = null;
  3145. _oldBlendSrc = null;
  3146. _oldBlendDst = null;
  3147. }
  3148. };
  3149. // Defines
  3150. function generateDefines ( defines ) {
  3151. var value, chunk, chunks = [];
  3152. for ( var d in defines ) {
  3153. value = defines[ d ];
  3154. if ( value === false ) continue;
  3155. chunk = "#define " + d + " " + value;
  3156. chunks.push( chunk );
  3157. }
  3158. return chunks.join( "\n" );
  3159. };
  3160. // Shaders
  3161. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  3162. var p, pl, d, program, code;
  3163. var chunks = [];
  3164. // Generate code
  3165. if ( shaderID ) {
  3166. chunks.push( shaderID );
  3167. } else {
  3168. chunks.push( fragmentShader );
  3169. chunks.push( vertexShader );
  3170. }
  3171. for ( d in defines ) {
  3172. chunks.push( d );
  3173. chunks.push( defines[ d ] );
  3174. }
  3175. for ( p in parameters ) {
  3176. chunks.push( p );
  3177. chunks.push( parameters[ p ] );
  3178. }
  3179. code = chunks.join();
  3180. // Check if code has been already compiled
  3181. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  3182. var programInfo = _programs[ p ];
  3183. if ( programInfo.code === code ) {
  3184. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  3185. programInfo.usedTimes ++;
  3186. return programInfo.program;
  3187. }
  3188. }
  3189. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  3190. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  3191. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  3192. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  3193. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  3194. }
  3195. // console.log( "building new program " );
  3196. //
  3197. var customDefines = generateDefines( defines );
  3198. //
  3199. program = _gl.createProgram();
  3200. var prefix_vertex = [
  3201. "precision " + _precision + " float;",
  3202. "precision " + _precision + " int;",
  3203. customDefines,
  3204. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  3205. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  3206. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  3207. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  3208. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  3209. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  3210. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  3211. "#define MAX_SHADOWS " + parameters.maxShadows,
  3212. "#define MAX_BONES " + parameters.maxBones,
  3213. parameters.map ? "#define USE_MAP" : "",
  3214. parameters.envMap ? "#define USE_ENVMAP" : "",
  3215. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  3216. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  3217. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  3218. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  3219. parameters.vertexColors ? "#define USE_COLOR" : "",
  3220. parameters.skinning ? "#define USE_SKINNING" : "",
  3221. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  3222. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  3223. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  3224. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  3225. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  3226. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  3227. parameters.flipSided ? "#define FLIP_SIDED" : "",
  3228. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  3229. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  3230. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  3231. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  3232. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  3233. "uniform mat4 modelMatrix;",
  3234. "uniform mat4 modelViewMatrix;",
  3235. "uniform mat4 projectionMatrix;",
  3236. "uniform mat4 viewMatrix;",
  3237. "uniform mat3 normalMatrix;",
  3238. "uniform vec3 cameraPosition;",
  3239. "attribute vec3 position;",
  3240. "attribute vec3 normal;",
  3241. "attribute vec2 uv;",
  3242. "attribute vec2 uv2;",
  3243. "#ifdef USE_COLOR",
  3244. "attribute vec3 color;",
  3245. "#endif",
  3246. "#ifdef USE_MORPHTARGETS",
  3247. "attribute vec3 morphTarget0;",
  3248. "attribute vec3 morphTarget1;",
  3249. "attribute vec3 morphTarget2;",
  3250. "attribute vec3 morphTarget3;",
  3251. "#ifdef USE_MORPHNORMALS",
  3252. "attribute vec3 morphNormal0;",
  3253. "attribute vec3 morphNormal1;",
  3254. "attribute vec3 morphNormal2;",
  3255. "attribute vec3 morphNormal3;",
  3256. "#else",
  3257. "attribute vec3 morphTarget4;",
  3258. "attribute vec3 morphTarget5;",
  3259. "attribute vec3 morphTarget6;",
  3260. "attribute vec3 morphTarget7;",
  3261. "#endif",
  3262. "#endif",
  3263. "#ifdef USE_SKINNING",
  3264. "attribute vec4 skinIndex;",
  3265. "attribute vec4 skinWeight;",
  3266. "#endif",
  3267. ""
  3268. ].join("\n");
  3269. var prefix_fragment = [
  3270. "precision " + _precision + " float;",
  3271. "precision " + _precision + " int;",
  3272. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  3273. customDefines,
  3274. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  3275. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  3276. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  3277. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  3278. "#define MAX_SHADOWS " + parameters.maxShadows,
  3279. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  3280. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  3281. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  3282. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  3283. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  3284. parameters.map ? "#define USE_MAP" : "",
  3285. parameters.envMap ? "#define USE_ENVMAP" : "",
  3286. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  3287. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  3288. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  3289. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  3290. parameters.vertexColors ? "#define USE_COLOR" : "",
  3291. parameters.metal ? "#define METAL" : "",
  3292. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  3293. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  3294. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  3295. parameters.flipSided ? "#define FLIP_SIDED" : "",
  3296. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  3297. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  3298. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  3299. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  3300. "uniform mat4 viewMatrix;",
  3301. "uniform vec3 cameraPosition;",
  3302. ""
  3303. ].join("\n");
  3304. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  3305. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  3306. _gl.attachShader( program, glVertexShader );
  3307. _gl.attachShader( program, glFragmentShader );
  3308. //Force a particular attribute to index 0.
  3309. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  3310. //And, color, for example is often automatically bound to index 0 so disabling it
  3311. if ( index0AttributeName ) {
  3312. _gl.bindAttribLocation( program, 0, index0AttributeName );
  3313. }
  3314. _gl.linkProgram( program );
  3315. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  3316. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  3317. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  3318. }
  3319. // clean up
  3320. _gl.deleteShader( glFragmentShader );
  3321. _gl.deleteShader( glVertexShader );
  3322. // console.log( prefix_fragment + fragmentShader );
  3323. // console.log( prefix_vertex + vertexShader );
  3324. program.uniforms = {};
  3325. program.attributes = {};
  3326. var identifiers, u, a, i;
  3327. // cache uniform locations
  3328. identifiers = [
  3329. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  3330. 'morphTargetInfluences'
  3331. ];
  3332. if ( parameters.useVertexTexture ) {
  3333. identifiers.push( 'boneTexture' );
  3334. identifiers.push( 'boneTextureWidth' );
  3335. identifiers.push( 'boneTextureHeight' );
  3336. } else {
  3337. identifiers.push( 'boneGlobalMatrices' );
  3338. }
  3339. for ( u in uniforms ) {
  3340. identifiers.push( u );
  3341. }
  3342. cacheUniformLocations( program, identifiers );
  3343. // cache attributes locations
  3344. identifiers = [
  3345. "position", "normal", "uv", "uv2", "tangent", "color",
  3346. "skinIndex", "skinWeight", "lineDistance"
  3347. ];
  3348. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  3349. identifiers.push( "morphTarget" + i );
  3350. }
  3351. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  3352. identifiers.push( "morphNormal" + i );
  3353. }
  3354. for ( a in attributes ) {
  3355. identifiers.push( a );
  3356. }
  3357. cacheAttributeLocations( program, identifiers );
  3358. program.id = _programs_counter ++;
  3359. _programs.push( { program: program, code: code, usedTimes: 1 } );
  3360. _this.info.memory.programs = _programs.length;
  3361. return program;
  3362. };
  3363. // Shader parameters cache
  3364. function cacheUniformLocations ( program, identifiers ) {
  3365. var i, l, id;
  3366. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  3367. id = identifiers[ i ];
  3368. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  3369. }
  3370. };
  3371. function cacheAttributeLocations ( program, identifiers ) {
  3372. var i, l, id;
  3373. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  3374. id = identifiers[ i ];
  3375. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  3376. }
  3377. };
  3378. function addLineNumbers ( string ) {
  3379. var chunks = string.split( "\n" );
  3380. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  3381. // Chrome reports shader errors on lines
  3382. // starting counting from 1
  3383. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  3384. }
  3385. return chunks.join( "\n" );
  3386. };
  3387. function getShader ( type, string ) {
  3388. var shader;
  3389. if ( type === "fragment" ) {
  3390. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  3391. } else if ( type === "vertex" ) {
  3392. shader = _gl.createShader( _gl.VERTEX_SHADER );
  3393. }
  3394. _gl.shaderSource( shader, string );
  3395. _gl.compileShader( shader );
  3396. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  3397. console.error( _gl.getShaderInfoLog( shader ) );
  3398. console.error( addLineNumbers( string ) );
  3399. return null;
  3400. }
  3401. return shader;
  3402. };
  3403. // Textures
  3404. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  3405. if ( isImagePowerOfTwo ) {
  3406. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3407. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3408. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3409. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3410. } else {
  3411. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3412. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3413. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3414. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3415. }
  3416. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  3417. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  3418. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  3419. texture.__oldAnisotropy = texture.anisotropy;
  3420. }
  3421. }
  3422. };
  3423. this.setTexture = function ( texture, slot ) {
  3424. if ( texture.needsUpdate ) {
  3425. if ( ! texture.__webglInit ) {
  3426. texture.__webglInit = true;
  3427. texture.addEventListener( 'dispose', onTextureDispose );
  3428. texture.__webglTexture = _gl.createTexture();
  3429. _this.info.memory.textures ++;
  3430. }
  3431. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3432. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3433. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3434. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3435. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3436. var image = texture.image,
  3437. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3438. glFormat = paramThreeToGL( texture.format ),
  3439. glType = paramThreeToGL( texture.type );
  3440. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  3441. var mipmap, mipmaps = texture.mipmaps;
  3442. if ( texture instanceof THREE.DataTexture ) {
  3443. // use manually created mipmaps if available
  3444. // if there are no manual mipmaps
  3445. // set 0 level mipmap and then use GL to generate other mipmap levels
  3446. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3447. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3448. mipmap = mipmaps[ i ];
  3449. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3450. }
  3451. texture.generateMipmaps = false;
  3452. } else {
  3453. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3454. }
  3455. } else if ( texture instanceof THREE.CompressedTexture ) {
  3456. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3457. mipmap = mipmaps[ i ];
  3458. if ( texture.format!==THREE.RGBAFormat ) {
  3459. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3460. } else {
  3461. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3462. }
  3463. }
  3464. } else { // regular Texture (image, video, canvas)
  3465. // use manually created mipmaps if available
  3466. // if there are no manual mipmaps
  3467. // set 0 level mipmap and then use GL to generate other mipmap levels
  3468. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3469. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3470. mipmap = mipmaps[ i ];
  3471. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3472. }
  3473. texture.generateMipmaps = false;
  3474. } else {
  3475. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  3476. }
  3477. }
  3478. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3479. texture.needsUpdate = false;
  3480. if ( texture.onUpdate ) texture.onUpdate();
  3481. } else {
  3482. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3483. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3484. }
  3485. };
  3486. function clampToMaxSize ( image, maxSize ) {
  3487. if ( image.width <= maxSize && image.height <= maxSize ) {
  3488. return image;
  3489. }
  3490. // Warning: Scaling through the canvas will only work with images that use
  3491. // premultiplied alpha.
  3492. var maxDimension = Math.max( image.width, image.height );
  3493. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  3494. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  3495. var canvas = document.createElement( 'canvas' );
  3496. canvas.width = newWidth;
  3497. canvas.height = newHeight;
  3498. var ctx = canvas.getContext( "2d" );
  3499. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  3500. return canvas;
  3501. }
  3502. function setCubeTexture ( texture, slot ) {
  3503. if ( texture.image.length === 6 ) {
  3504. if ( texture.needsUpdate ) {
  3505. if ( ! texture.image.__webglTextureCube ) {
  3506. texture.addEventListener( 'dispose', onTextureDispose );
  3507. texture.image.__webglTextureCube = _gl.createTexture();
  3508. _this.info.memory.textures ++;
  3509. }
  3510. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3511. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3512. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3513. var isCompressed = texture instanceof THREE.CompressedTexture;
  3514. var cubeImage = [];
  3515. for ( var i = 0; i < 6; i ++ ) {
  3516. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  3517. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  3518. } else {
  3519. cubeImage[ i ] = texture.image[ i ];
  3520. }
  3521. }
  3522. var image = cubeImage[ 0 ],
  3523. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  3524. glFormat = paramThreeToGL( texture.format ),
  3525. glType = paramThreeToGL( texture.type );
  3526. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  3527. for ( var i = 0; i < 6; i ++ ) {
  3528. if( !isCompressed ) {
  3529. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3530. } else {
  3531. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3532. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3533. mipmap = mipmaps[ j ];
  3534. if ( texture.format!==THREE.RGBAFormat ) {
  3535. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3536. } else {
  3537. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3538. }
  3539. }
  3540. }
  3541. }
  3542. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  3543. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3544. }
  3545. texture.needsUpdate = false;
  3546. if ( texture.onUpdate ) texture.onUpdate();
  3547. } else {
  3548. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3549. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3550. }
  3551. }
  3552. };
  3553. function setCubeTextureDynamic ( texture, slot ) {
  3554. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3555. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  3556. };
  3557. // Render targets
  3558. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  3559. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3560. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  3561. };
  3562. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  3563. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3564. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3565. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3566. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3567. /* For some reason this is not working. Defaulting to RGBA4.
  3568. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3569. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  3570. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3571. */
  3572. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3573. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3574. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3575. } else {
  3576. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3577. }
  3578. };
  3579. this.setRenderTarget = function ( renderTarget ) {
  3580. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  3581. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  3582. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  3583. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  3584. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3585. renderTarget.__webglTexture = _gl.createTexture();
  3586. _this.info.memory.textures ++;
  3587. // Setup texture, create render and frame buffers
  3588. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  3589. glFormat = paramThreeToGL( renderTarget.format ),
  3590. glType = paramThreeToGL( renderTarget.type );
  3591. if ( isCube ) {
  3592. renderTarget.__webglFramebuffer = [];
  3593. renderTarget.__webglRenderbuffer = [];
  3594. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3595. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  3596. for ( var i = 0; i < 6; i ++ ) {
  3597. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3598. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  3599. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3600. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3601. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  3602. }
  3603. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3604. } else {
  3605. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  3606. if ( renderTarget.shareDepthFrom ) {
  3607. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  3608. } else {
  3609. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  3610. }
  3611. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3612. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  3613. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3614. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  3615. if ( renderTarget.shareDepthFrom ) {
  3616. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3617. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3618. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3619. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3620. }
  3621. } else {
  3622. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  3623. }
  3624. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3625. }
  3626. // Release everything
  3627. if ( isCube ) {
  3628. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3629. } else {
  3630. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3631. }
  3632. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3633. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3634. }
  3635. var framebuffer, width, height, vx, vy;
  3636. if ( renderTarget ) {
  3637. if ( isCube ) {
  3638. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  3639. } else {
  3640. framebuffer = renderTarget.__webglFramebuffer;
  3641. }
  3642. width = renderTarget.width;
  3643. height = renderTarget.height;
  3644. vx = 0;
  3645. vy = 0;
  3646. } else {
  3647. framebuffer = null;
  3648. width = _viewportWidth;
  3649. height = _viewportHeight;
  3650. vx = _viewportX;
  3651. vy = _viewportY;
  3652. }
  3653. if ( framebuffer !== _currentFramebuffer ) {
  3654. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3655. _gl.viewport( vx, vy, width, height );
  3656. _currentFramebuffer = framebuffer;
  3657. }
  3658. _currentWidth = width;
  3659. _currentHeight = height;
  3660. };
  3661. function updateRenderTargetMipmap ( renderTarget ) {
  3662. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  3663. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3664. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3665. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3666. } else {
  3667. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3668. _gl.generateMipmap( _gl.TEXTURE_2D );
  3669. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3670. }
  3671. };
  3672. // Fallback filters for non-power-of-2 textures
  3673. function filterFallback ( f ) {
  3674. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  3675. return _gl.NEAREST;
  3676. }
  3677. return _gl.LINEAR;
  3678. };
  3679. // Map three.js constants to WebGL constants
  3680. function paramThreeToGL ( p ) {
  3681. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  3682. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  3683. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  3684. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  3685. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  3686. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  3687. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  3688. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  3689. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  3690. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  3691. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  3692. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  3693. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  3694. if ( p === THREE.ByteType ) return _gl.BYTE;
  3695. if ( p === THREE.ShortType ) return _gl.SHORT;
  3696. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  3697. if ( p === THREE.IntType ) return _gl.INT;
  3698. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  3699. if ( p === THREE.FloatType ) return _gl.FLOAT;
  3700. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  3701. if ( p === THREE.RGBFormat ) return _gl.RGB;
  3702. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  3703. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  3704. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  3705. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  3706. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  3707. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  3708. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  3709. if ( p === THREE.OneFactor ) return _gl.ONE;
  3710. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  3711. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  3712. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  3713. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  3714. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  3715. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  3716. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  3717. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  3718. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  3719. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  3720. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  3721. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3722. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3723. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3724. }
  3725. return 0;
  3726. };
  3727. // Allocations
  3728. function allocateBones ( object ) {
  3729. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  3730. return 1024;
  3731. } else {
  3732. // default for when object is not specified
  3733. // ( for example when prebuilding shader
  3734. // to be used with multiple objects )
  3735. //
  3736. // - leave some extra space for other uniforms
  3737. // - limit here is ANGLE's 254 max uniform vectors
  3738. // (up to 54 should be safe)
  3739. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  3740. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  3741. var maxBones = nVertexMatrices;
  3742. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  3743. maxBones = Math.min( object.bones.length, maxBones );
  3744. if ( maxBones < object.bones.length ) {
  3745. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  3746. }
  3747. }
  3748. return maxBones;
  3749. }
  3750. };
  3751. function allocateLights( lights ) {
  3752. var dirLights = 0;
  3753. var pointLights = 0;
  3754. var spotLights = 0;
  3755. var hemiLights = 0;
  3756. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3757. var light = lights[ l ];
  3758. if ( light.onlyShadow ) continue;
  3759. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  3760. if ( light instanceof THREE.PointLight ) pointLights ++;
  3761. if ( light instanceof THREE.SpotLight ) spotLights ++;
  3762. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  3763. }
  3764. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  3765. };
  3766. function allocateShadows( lights ) {
  3767. var maxShadows = 0;
  3768. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  3769. var light = lights[ l ];
  3770. if ( ! light.castShadow ) continue;
  3771. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  3772. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  3773. }
  3774. return maxShadows;
  3775. };
  3776. // Initialization
  3777. function initGL() {
  3778. try {
  3779. var attributes = {
  3780. alpha: _alpha,
  3781. premultipliedAlpha: _premultipliedAlpha,
  3782. antialias: _antialias,
  3783. stencil: _stencil,
  3784. preserveDrawingBuffer: _preserveDrawingBuffer
  3785. };
  3786. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  3787. if ( _gl === null ) {
  3788. throw 'Error creating WebGL context.';
  3789. }
  3790. } catch ( error ) {
  3791. console.error( error );
  3792. }
  3793. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  3794. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  3795. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  3796. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  3797. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  3798. if ( ! _glExtensionTextureFloat ) {
  3799. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  3800. }
  3801. if ( ! _glExtensionStandardDerivatives ) {
  3802. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  3803. }
  3804. if ( ! _glExtensionTextureFilterAnisotropic ) {
  3805. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  3806. }
  3807. if ( ! _glExtensionCompressedTextureS3TC ) {
  3808. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  3809. }
  3810. if ( _gl.getShaderPrecisionFormat === undefined ) {
  3811. _gl.getShaderPrecisionFormat = function() {
  3812. return {
  3813. "rangeMin" : 1,
  3814. "rangeMax" : 1,
  3815. "precision" : 1
  3816. };
  3817. }
  3818. }
  3819. };
  3820. function setDefaultGLState () {
  3821. _gl.clearColor( 0, 0, 0, 1 );
  3822. _gl.clearDepth( 1 );
  3823. _gl.clearStencil( 0 );
  3824. _gl.enable( _gl.DEPTH_TEST );
  3825. _gl.depthFunc( _gl.LEQUAL );
  3826. _gl.frontFace( _gl.CCW );
  3827. _gl.cullFace( _gl.BACK );
  3828. _gl.enable( _gl.CULL_FACE );
  3829. _gl.enable( _gl.BLEND );
  3830. _gl.blendEquation( _gl.FUNC_ADD );
  3831. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  3832. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  3833. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  3834. };
  3835. // default plugins (order is important)
  3836. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  3837. this.addPrePlugin( this.shadowMapPlugin );
  3838. this.addPostPlugin( new THREE.SpritePlugin() );
  3839. this.addPostPlugin( new THREE.LensFlarePlugin() );
  3840. };
粤ICP备19079148号