build_cmd_buffer_lib.py 256 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527
  1. # Copyright (c) 2018 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Common code generator for command buffers."""
  5. import errno
  6. import itertools
  7. import os
  8. import os.path
  9. import re
  10. import platform
  11. from subprocess import call
  12. _SIZE_OF_UINT32 = 4
  13. _SIZE_OF_COMMAND_HEADER = 4
  14. _FIRST_SPECIFIC_COMMAND_ID = 256
  15. _LICENSE = """// Copyright %s The Chromium Authors. All rights reserved.
  16. // Use of this source code is governed by a BSD-style license that can be
  17. // found in the LICENSE file.
  18. """
  19. _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
  20. // gpu/command_buffer/build_%s_cmd_buffer.py
  21. // It's formatted by clang-format using chromium coding style:
  22. // clang-format -i -style=chromium filename
  23. // DO NOT EDIT!
  24. """
  25. # This string is copied directly out of the gl2.h file from GLES2.0
  26. #
  27. # Edits:
  28. #
  29. # *) Any argument that is a resourceID has been changed to GLid<Type>.
  30. # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
  31. # If it's allowed to not exist it's GLidBind<Type>
  32. #
  33. # *) All GLenums have been changed to GLenumTypeOfEnum
  34. #
  35. _GL_TYPES = {
  36. 'GLenum': 'unsigned int',
  37. 'GLboolean': 'unsigned char',
  38. 'GLbitfield': 'unsigned int',
  39. 'GLbyte': 'signed char',
  40. 'GLshort': 'short',
  41. 'GLint': 'int',
  42. 'GLsizei': 'int',
  43. 'GLubyte': 'unsigned char',
  44. 'GLushort': 'unsigned short',
  45. 'GLuint': 'unsigned int',
  46. 'GLfloat': 'float',
  47. 'GLclampf': 'float',
  48. 'GLvoid': 'void',
  49. 'GLfixed': 'int',
  50. 'GLclampx': 'int'
  51. }
  52. _GL_TYPES_32 = {
  53. 'GLintptr': 'long int',
  54. 'GLsizeiptr': 'long int'
  55. }
  56. _GL_TYPES_64 = {
  57. 'GLintptr': 'long long int',
  58. 'GLsizeiptr': 'long long int'
  59. }
  60. _ETC_COMPRESSED_TEXTURE_FORMATS = [
  61. 'GL_COMPRESSED_R11_EAC',
  62. 'GL_COMPRESSED_SIGNED_R11_EAC',
  63. 'GL_COMPRESSED_RG11_EAC',
  64. 'GL_COMPRESSED_SIGNED_RG11_EAC',
  65. 'GL_COMPRESSED_RGB8_ETC2',
  66. 'GL_COMPRESSED_SRGB8_ETC2',
  67. 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
  68. 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
  69. 'GL_COMPRESSED_RGBA8_ETC2_EAC',
  70. 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
  71. ]
  72. # This table specifies the different pepper interfaces that are supported for
  73. # GL commands. 'dev' is true if it's a dev interface.
  74. _PEPPER_INTERFACES = [
  75. {'name': '', 'dev': False},
  76. {'name': 'InstancedArrays', 'dev': False},
  77. {'name': 'FramebufferBlit', 'dev': False},
  78. {'name': 'FramebufferMultisample', 'dev': False},
  79. {'name': 'ChromiumEnableFeature', 'dev': False},
  80. {'name': 'ChromiumMapSub', 'dev': False},
  81. {'name': 'Query', 'dev': False},
  82. {'name': 'VertexArrayObject', 'dev': False},
  83. {'name': 'DrawBuffers', 'dev': True},
  84. ]
  85. # Capabilities selected with glEnable
  86. # on_change: string of C++ code that is executed when the state is changed.
  87. _CAPABILITY_FLAGS = [
  88. {'name': 'blend'},
  89. {'name': 'cull_face'},
  90. {'name': 'depth_test',
  91. 'on_change': 'framebuffer_state_.clear_state_dirty = true;'},
  92. {'name': 'dither', 'default': True},
  93. {'name': 'framebuffer_srgb_ext', 'default': True, 'no_init': True,
  94. 'extension_flag': 'ext_srgb_write_control'},
  95. {'name': 'polygon_offset_fill'},
  96. {'name': 'sample_alpha_to_coverage'},
  97. {'name': 'sample_coverage'},
  98. {'name': 'scissor_test'},
  99. {'name': 'stencil_test',
  100. 'on_change': '''state_.stencil_state_changed_since_validation = true;
  101. framebuffer_state_.clear_state_dirty = true;'''},
  102. {'name': 'rasterizer_discard', 'es3': True},
  103. {'name': 'primitive_restart_fixed_index', 'es3': True},
  104. {'name': 'multisample_ext', 'default': True,
  105. 'extension_flag': 'ext_multisample_compatibility'},
  106. {'name': 'sample_alpha_to_one_ext',
  107. 'extension_flag': 'ext_multisample_compatibility'},
  108. ]
  109. _STATE_INFO = {
  110. 'ClearColor': {
  111. 'type': 'Normal',
  112. 'func': 'ClearColor',
  113. 'enum': 'GL_COLOR_CLEAR_VALUE',
  114. 'states': [
  115. {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
  116. {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
  117. {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
  118. {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
  119. ],
  120. },
  121. 'ClearDepthf': {
  122. 'type': 'Normal',
  123. 'func': 'ClearDepth',
  124. 'enum': 'GL_DEPTH_CLEAR_VALUE',
  125. 'states': [
  126. {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
  127. ],
  128. },
  129. 'ColorMask': {
  130. 'type': 'Normal',
  131. 'func': 'ColorMask',
  132. 'enum': 'GL_COLOR_WRITEMASK',
  133. 'states': [
  134. {
  135. 'name': 'color_mask_red',
  136. 'type': 'GLboolean',
  137. 'default': 'true',
  138. 'cached': True
  139. },
  140. {
  141. 'name': 'color_mask_green',
  142. 'type': 'GLboolean',
  143. 'default': 'true',
  144. 'cached': True
  145. },
  146. {
  147. 'name': 'color_mask_blue',
  148. 'type': 'GLboolean',
  149. 'default': 'true',
  150. 'cached': True
  151. },
  152. {
  153. 'name': 'color_mask_alpha',
  154. 'type': 'GLboolean',
  155. 'default': 'true',
  156. 'cached': True
  157. },
  158. ],
  159. 'on_change': 'framebuffer_state_.clear_state_dirty = true;',
  160. },
  161. 'ClearStencil': {
  162. 'type': 'Normal',
  163. 'func': 'ClearStencil',
  164. 'enum': 'GL_STENCIL_CLEAR_VALUE',
  165. 'states': [
  166. {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
  167. ],
  168. },
  169. 'CoverageModulationCHROMIUM': {
  170. 'type': 'Normal',
  171. 'func': 'CoverageModulationNV',
  172. 'extension_flag': 'chromium_framebuffer_mixed_samples',
  173. 'states': [
  174. { 'enum': 'GL_COVERAGE_MODULATION_CHROMIUM',
  175. 'name': 'coverage_modulation',
  176. 'type': 'GLenum',
  177. 'default': 'GL_NONE',
  178. },
  179. ]
  180. },
  181. 'BlendColor': {
  182. 'type': 'Normal',
  183. 'func': 'BlendColor',
  184. 'enum': 'GL_BLEND_COLOR',
  185. 'states': [
  186. {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
  187. {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
  188. {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
  189. {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
  190. ],
  191. },
  192. 'BlendEquation': {
  193. 'type': 'SrcDst',
  194. 'func': 'BlendEquationSeparate',
  195. 'states': [
  196. {
  197. 'name': 'blend_equation_rgb',
  198. 'type': 'GLenum',
  199. 'enum': 'GL_BLEND_EQUATION_RGB',
  200. 'default': 'GL_FUNC_ADD',
  201. },
  202. {
  203. 'name': 'blend_equation_alpha',
  204. 'type': 'GLenum',
  205. 'enum': 'GL_BLEND_EQUATION_ALPHA',
  206. 'default': 'GL_FUNC_ADD',
  207. },
  208. ],
  209. },
  210. 'BlendFunc': {
  211. 'type': 'SrcDst',
  212. 'func': 'BlendFuncSeparate',
  213. 'states': [
  214. {
  215. 'name': 'blend_source_rgb',
  216. 'type': 'GLenum',
  217. 'enum': 'GL_BLEND_SRC_RGB',
  218. 'default': 'GL_ONE',
  219. },
  220. {
  221. 'name': 'blend_dest_rgb',
  222. 'type': 'GLenum',
  223. 'enum': 'GL_BLEND_DST_RGB',
  224. 'default': 'GL_ZERO',
  225. },
  226. {
  227. 'name': 'blend_source_alpha',
  228. 'type': 'GLenum',
  229. 'enum': 'GL_BLEND_SRC_ALPHA',
  230. 'default': 'GL_ONE',
  231. },
  232. {
  233. 'name': 'blend_dest_alpha',
  234. 'type': 'GLenum',
  235. 'enum': 'GL_BLEND_DST_ALPHA',
  236. 'default': 'GL_ZERO',
  237. },
  238. ],
  239. },
  240. 'PolygonOffset': {
  241. 'type': 'Normal',
  242. 'func': 'PolygonOffset',
  243. 'states': [
  244. {
  245. 'name': 'polygon_offset_factor',
  246. 'type': 'GLfloat',
  247. 'enum': 'GL_POLYGON_OFFSET_FACTOR',
  248. 'default': '0.0f',
  249. },
  250. {
  251. 'name': 'polygon_offset_units',
  252. 'type': 'GLfloat',
  253. 'enum': 'GL_POLYGON_OFFSET_UNITS',
  254. 'default': '0.0f',
  255. },
  256. ],
  257. },
  258. 'CullFace': {
  259. 'type': 'Normal',
  260. 'func': 'CullFace',
  261. 'enum': 'GL_CULL_FACE_MODE',
  262. 'states': [
  263. {
  264. 'name': 'cull_mode',
  265. 'type': 'GLenum',
  266. 'default': 'GL_BACK',
  267. },
  268. ],
  269. },
  270. 'FrontFace': {
  271. 'type': 'Normal',
  272. 'func': 'FrontFace',
  273. 'enum': 'GL_FRONT_FACE',
  274. 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
  275. },
  276. 'DepthFunc': {
  277. 'type': 'Normal',
  278. 'func': 'DepthFunc',
  279. 'enum': 'GL_DEPTH_FUNC',
  280. 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
  281. },
  282. 'DepthRange': {
  283. 'type': 'Normal',
  284. 'func': 'DepthRange',
  285. 'enum': 'GL_DEPTH_RANGE',
  286. 'states': [
  287. {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
  288. {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
  289. ],
  290. },
  291. 'SampleCoverage': {
  292. 'type': 'Normal',
  293. 'func': 'SampleCoverage',
  294. 'states': [
  295. {
  296. 'name': 'sample_coverage_value',
  297. 'type': 'GLclampf',
  298. 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
  299. 'default': '1.0f',
  300. },
  301. {
  302. 'name': 'sample_coverage_invert',
  303. 'type': 'GLboolean',
  304. 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
  305. 'default': 'false',
  306. },
  307. ],
  308. },
  309. 'StencilMask': {
  310. 'type': 'FrontBack',
  311. 'func': 'StencilMaskSeparate',
  312. 'states': [
  313. {
  314. 'name': 'stencil_front_writemask',
  315. 'type': 'GLuint',
  316. 'enum': 'GL_STENCIL_WRITEMASK',
  317. 'default': '0xFFFFFFFFU',
  318. 'cached': True,
  319. },
  320. {
  321. 'name': 'stencil_back_writemask',
  322. 'type': 'GLuint',
  323. 'enum': 'GL_STENCIL_BACK_WRITEMASK',
  324. 'default': '0xFFFFFFFFU',
  325. 'cached': True,
  326. },
  327. ],
  328. 'on_change': '''framebuffer_state_.clear_state_dirty = true;
  329. state_.stencil_state_changed_since_validation = true;''',
  330. },
  331. 'StencilOp': {
  332. 'type': 'FrontBack',
  333. 'func': 'StencilOpSeparate',
  334. 'states': [
  335. {
  336. 'name': 'stencil_front_fail_op',
  337. 'type': 'GLenum',
  338. 'enum': 'GL_STENCIL_FAIL',
  339. 'default': 'GL_KEEP',
  340. },
  341. {
  342. 'name': 'stencil_front_z_fail_op',
  343. 'type': 'GLenum',
  344. 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
  345. 'default': 'GL_KEEP',
  346. },
  347. {
  348. 'name': 'stencil_front_z_pass_op',
  349. 'type': 'GLenum',
  350. 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
  351. 'default': 'GL_KEEP',
  352. },
  353. {
  354. 'name': 'stencil_back_fail_op',
  355. 'type': 'GLenum',
  356. 'enum': 'GL_STENCIL_BACK_FAIL',
  357. 'default': 'GL_KEEP',
  358. },
  359. {
  360. 'name': 'stencil_back_z_fail_op',
  361. 'type': 'GLenum',
  362. 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
  363. 'default': 'GL_KEEP',
  364. },
  365. {
  366. 'name': 'stencil_back_z_pass_op',
  367. 'type': 'GLenum',
  368. 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
  369. 'default': 'GL_KEEP',
  370. },
  371. ],
  372. },
  373. 'StencilFunc': {
  374. 'type': 'FrontBack',
  375. 'func': 'StencilFuncSeparate',
  376. 'states': [
  377. {
  378. 'name': 'stencil_front_func',
  379. 'type': 'GLenum',
  380. 'enum': 'GL_STENCIL_FUNC',
  381. 'default': 'GL_ALWAYS',
  382. },
  383. {
  384. 'name': 'stencil_front_ref',
  385. 'type': 'GLint',
  386. 'enum': 'GL_STENCIL_REF',
  387. 'default': '0',
  388. },
  389. {
  390. 'name': 'stencil_front_mask',
  391. 'type': 'GLuint',
  392. 'enum': 'GL_STENCIL_VALUE_MASK',
  393. 'default': '0xFFFFFFFFU',
  394. },
  395. {
  396. 'name': 'stencil_back_func',
  397. 'type': 'GLenum',
  398. 'enum': 'GL_STENCIL_BACK_FUNC',
  399. 'default': 'GL_ALWAYS',
  400. },
  401. {
  402. 'name': 'stencil_back_ref',
  403. 'type': 'GLint',
  404. 'enum': 'GL_STENCIL_BACK_REF',
  405. 'default': '0',
  406. },
  407. {
  408. 'name': 'stencil_back_mask',
  409. 'type': 'GLuint',
  410. 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
  411. 'default': '0xFFFFFFFFU',
  412. },
  413. ],
  414. 'on_change': 'state_.stencil_state_changed_since_validation = true;',
  415. },
  416. 'Hint': {
  417. 'type': 'NamedParameter',
  418. 'func': 'Hint',
  419. 'states': [
  420. {
  421. 'name': 'hint_generate_mipmap',
  422. 'type': 'GLenum',
  423. 'enum': 'GL_GENERATE_MIPMAP_HINT',
  424. 'default': 'GL_DONT_CARE',
  425. 'gl_version_flag': '!is_desktop_core_profile'
  426. },
  427. {
  428. 'name': 'hint_fragment_shader_derivative',
  429. 'type': 'GLenum',
  430. 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
  431. 'default': 'GL_DONT_CARE',
  432. 'extension_flag': 'oes_standard_derivatives'
  433. },
  434. {
  435. 'name': 'hint_texture_filtering',
  436. 'type': 'GLenum',
  437. 'enum': 'GL_TEXTURE_FILTERING_HINT_CHROMIUM',
  438. 'default': 'GL_NICEST',
  439. 'extension_flag': 'chromium_texture_filtering_hint'
  440. }
  441. ],
  442. },
  443. 'PixelStore': {
  444. 'type': 'NamedParameter',
  445. 'func': 'PixelStorei',
  446. 'states': [
  447. {
  448. 'name': 'pack_alignment',
  449. 'type': 'GLint',
  450. 'enum': 'GL_PACK_ALIGNMENT',
  451. 'default': '4'
  452. },
  453. {
  454. 'name': 'unpack_alignment',
  455. 'type': 'GLint',
  456. 'enum': 'GL_UNPACK_ALIGNMENT',
  457. 'default': '4'
  458. },
  459. {
  460. 'name': 'pack_row_length',
  461. 'type': 'GLint',
  462. 'enum': 'GL_PACK_ROW_LENGTH',
  463. 'default': '0',
  464. 'es3': True,
  465. 'manual': True,
  466. },
  467. {
  468. 'name': 'pack_skip_pixels',
  469. 'type': 'GLint',
  470. 'enum': 'GL_PACK_SKIP_PIXELS',
  471. 'default': '0',
  472. 'es3': True,
  473. 'manual': True,
  474. },
  475. {
  476. 'name': 'pack_skip_rows',
  477. 'type': 'GLint',
  478. 'enum': 'GL_PACK_SKIP_ROWS',
  479. 'default': '0',
  480. 'es3': True,
  481. 'manual': True,
  482. },
  483. {
  484. 'name': 'unpack_row_length',
  485. 'type': 'GLint',
  486. 'enum': 'GL_UNPACK_ROW_LENGTH',
  487. 'default': '0',
  488. 'es3': True,
  489. 'manual': True,
  490. },
  491. {
  492. 'name': 'unpack_image_height',
  493. 'type': 'GLint',
  494. 'enum': 'GL_UNPACK_IMAGE_HEIGHT',
  495. 'default': '0',
  496. 'es3': True,
  497. 'manual': True,
  498. },
  499. {
  500. 'name': 'unpack_skip_pixels',
  501. 'type': 'GLint',
  502. 'enum': 'GL_UNPACK_SKIP_PIXELS',
  503. 'default': '0',
  504. 'es3': True,
  505. 'manual': True,
  506. },
  507. {
  508. 'name': 'unpack_skip_rows',
  509. 'type': 'GLint',
  510. 'enum': 'GL_UNPACK_SKIP_ROWS',
  511. 'default': '0',
  512. 'es3': True,
  513. 'manual': True,
  514. },
  515. {
  516. 'name': 'unpack_skip_images',
  517. 'type': 'GLint',
  518. 'enum': 'GL_UNPACK_SKIP_IMAGES',
  519. 'default': '0',
  520. 'es3': True,
  521. 'manual': True,
  522. }
  523. ],
  524. },
  525. # TODO: Consider implemenenting these states
  526. # GL_ACTIVE_TEXTURE
  527. 'LineWidth': {
  528. 'type': 'Normal',
  529. 'custom_function' : True,
  530. 'func': 'DoLineWidth',
  531. 'enum': 'GL_LINE_WIDTH',
  532. 'states': [
  533. {
  534. 'name': 'line_width',
  535. 'type': 'GLfloat',
  536. 'default': '1.0f',
  537. 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
  538. 'nan_check': True,
  539. }],
  540. },
  541. 'DepthMask': {
  542. 'type': 'Normal',
  543. 'func': 'DepthMask',
  544. 'enum': 'GL_DEPTH_WRITEMASK',
  545. 'states': [
  546. {
  547. 'name': 'depth_mask',
  548. 'type': 'GLboolean',
  549. 'default': 'true',
  550. 'cached': True
  551. },
  552. ],
  553. 'on_change': 'framebuffer_state_.clear_state_dirty = true;',
  554. },
  555. 'Scissor': {
  556. 'type': 'Normal',
  557. 'func': 'Scissor',
  558. 'enum': 'GL_SCISSOR_BOX',
  559. 'states': [
  560. # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
  561. {
  562. 'name': 'scissor_x',
  563. 'type': 'GLint',
  564. 'default': '0',
  565. },
  566. {
  567. 'name': 'scissor_y',
  568. 'type': 'GLint',
  569. 'default': '0',
  570. },
  571. {
  572. 'name': 'scissor_width',
  573. 'type': 'GLsizei',
  574. 'default': '1',
  575. 'expected': 'initial_size.width()',
  576. },
  577. {
  578. 'name': 'scissor_height',
  579. 'type': 'GLsizei',
  580. 'default': '1',
  581. 'expected': 'initial_size.height()',
  582. },
  583. ],
  584. },
  585. 'Viewport': {
  586. 'type': 'Normal',
  587. 'func': 'Viewport',
  588. 'enum': 'GL_VIEWPORT',
  589. 'states': [
  590. # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
  591. {
  592. 'name': 'viewport_x',
  593. 'type': 'GLint',
  594. 'default': '0',
  595. },
  596. {
  597. 'name': 'viewport_y',
  598. 'type': 'GLint',
  599. 'default': '0',
  600. },
  601. {
  602. 'name': 'viewport_width',
  603. 'type': 'GLsizei',
  604. 'default': '1',
  605. 'expected': 'initial_size.width()',
  606. },
  607. {
  608. 'name': 'viewport_height',
  609. 'type': 'GLsizei',
  610. 'default': '1',
  611. 'expected': 'initial_size.height()',
  612. },
  613. ],
  614. },
  615. 'WindowRectanglesEXT': {
  616. 'type': 'Normal',
  617. 'func': 'WindowRectanglesEXT',
  618. 'custom_function': True,
  619. 'extension_flag': 'ext_window_rectangles',
  620. 'no_init': True,
  621. 'states': [
  622. {
  623. 'name': 'window_rectangles_mode',
  624. 'type': 'GLenum',
  625. 'enum': 'GL_WINDOW_RECTANGLE_MODE_EXT',
  626. 'default': 'GL_EXCLUSIVE_EXT',
  627. },
  628. {
  629. 'name': 'num_window_rectangles',
  630. 'type': 'GLint',
  631. 'enum': 'GL_NUM_WINDOW_RECTANGLES_EXT',
  632. 'default': '0',
  633. },
  634. ],
  635. },
  636. }
  637. _prefix = None
  638. _upper_prefix = None
  639. _lower_prefix = None
  640. def InitializePrefix(mixed_case_prefix):
  641. """Initialize prefix used for autogenerated code.
  642. Must be called before autogenerating code. Prefixes are used by autogenerated
  643. code in many places: class names, filenames, namespaces, constants,
  644. defines. Given a single mixed case prefix suitable for a class name, we also
  645. initialize lower and upper case prefixes for other uses (e.g. filenames and
  646. #defines).
  647. """
  648. global _prefix
  649. if _prefix:
  650. raise AssertionError
  651. _prefix = mixed_case_prefix
  652. global _upper_prefix
  653. _upper_prefix = mixed_case_prefix.upper()
  654. global _lower_prefix
  655. _lower_prefix = mixed_case_prefix.lower()
  656. def _Namespace():
  657. if _lower_prefix != 'gles2':
  658. return 'gles2::'
  659. return ''
  660. def Grouper(n, iterable, fillvalue=None):
  661. """Collect data into fixed-length chunks or blocks"""
  662. args = [iter(iterable)] * n
  663. return itertools.zip_longest(fillvalue=fillvalue, *args)
  664. def SplitWords(input_string):
  665. """Split by '_' if found, otherwise split at uppercase/numeric chars.
  666. Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
  667. "Case"], and "Vector3" into ["Vector", "3"].
  668. """
  669. if input_string.find('_') > -1:
  670. # 'some_TEXT_' -> 'some TEXT'
  671. return input_string.replace('_', ' ').strip().split()
  672. input_string = input_string.replace('::', ' ')
  673. if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
  674. # mixed case.
  675. # look for capitalization to cut input_strings
  676. # 'SomeText' -> 'Some Text'
  677. input_string = re.sub('([A-Z])', r' \1', input_string).strip()
  678. # 'Vector3' -> 'Vector 3'
  679. input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
  680. return input_string.split()
  681. def ToUnderscore(input_string):
  682. """converts CamelCase to camel_case."""
  683. words = SplitWords(input_string)
  684. return '_'.join([word.lower() for word in words])
  685. def ValidatorClassName(type_name):
  686. """Converts some::namespace::TypeName to SomeNamespaceTypeNameValidator."""
  687. words = SplitWords(type_name)
  688. prefix = ''.join([word.title() for word in words])
  689. return '%sValidator' % prefix
  690. def CachedStateName(item):
  691. if item.get('cached', False):
  692. return 'cached_' + item['name']
  693. return item['name']
  694. def GuardState(state, operation, feature_info):
  695. if 'manual' in state:
  696. assert state['manual']
  697. return ""
  698. result = []
  699. result_end = []
  700. if 'es3' in state:
  701. assert state['es3']
  702. result.append(" if (%s->IsES3Capable()) {\n" % feature_info);
  703. result_end.append(" }\n")
  704. if 'extension_flag' in state:
  705. result.append(" if (%s->feature_flags().%s) {\n " %
  706. (feature_info, state['extension_flag']))
  707. result_end.append(" }\n")
  708. if 'gl_version_flag' in state:
  709. name = state['gl_version_flag']
  710. inverted = ''
  711. if name[0] == '!':
  712. inverted = '!'
  713. name = name[1:]
  714. result.append(" if (%s%s->gl_version_info().%s) {\n" %
  715. (inverted, feature_info, name))
  716. result_end.append(" }\n")
  717. result.append(operation)
  718. return ''.join(result + result_end)
  719. def ToGLExtensionString(extension_flag):
  720. """Returns GL-type extension string of a extension flag."""
  721. if extension_flag == "oes_compressed_etc1_rgb8_texture":
  722. return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
  723. # unfortunate.
  724. uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
  725. 'egl', 'atc', 'etc1', 'angle']
  726. parts = extension_flag.split('_')
  727. return "_".join(
  728. [part.upper() if part in uppercase_words else part for part in parts])
  729. def ToCamelCase(input_string):
  730. """converts ABC_underscore_case to ABCUnderscoreCase."""
  731. return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
  732. def EnumsConflict(a, b):
  733. """Returns true if the enums have different names (ignoring suffixes) and one
  734. of them is a Chromium enum."""
  735. if a == b:
  736. return False
  737. if b.endswith('_CHROMIUM'):
  738. a, b = b, a
  739. if not a.endswith('_CHROMIUM'):
  740. return False
  741. def removesuffix(string, suffix):
  742. if not string.endswith(suffix):
  743. return string
  744. return string[:-len(suffix)]
  745. b = removesuffix(b, "_NV")
  746. b = removesuffix(b, "_EXT")
  747. b = removesuffix(b, "_OES")
  748. return removesuffix(a, "_CHROMIUM") != b
  749. def GetGLGetTypeConversion(result_type, value_type, value):
  750. """Makes a gl compatible type conversion string for accessing state variables.
  751. Useful when accessing state variables through glGetXXX calls.
  752. glGet documetation (for example, the manual pages):
  753. [...] If glGetIntegerv is called, [...] most floating-point values are
  754. rounded to the nearest integer value. [...]
  755. Args:
  756. result_type: the gl type to be obtained
  757. value_type: the GL type of the state variable
  758. value: the name of the state variable
  759. Returns:
  760. String that converts the state variable to desired GL type according to GL
  761. rules.
  762. """
  763. if result_type == 'GLint':
  764. if value_type == 'GLfloat':
  765. return 'static_cast<GLint>(round(%s))' % value
  766. return 'static_cast<%s>(%s)' % (result_type, value)
  767. class CWriter():
  768. """Context manager that creates a C source file.
  769. To be used with the `with` statement. Returns a normal `file` type, open only
  770. for writing - any existing files with that name will be overwritten. It will
  771. automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
  772. at the beginning.
  773. Example:
  774. with CWriter("file.cpp") as myfile:
  775. myfile.write("hello")
  776. # type(myfile) == file
  777. """
  778. def __init__(self, filename, year):
  779. self.filename = filename
  780. self._ENTER_MSG = _LICENSE % year + _DO_NOT_EDIT_WARNING % _lower_prefix
  781. self._EXIT_MSG = ""
  782. try:
  783. os.makedirs(os.path.dirname(filename))
  784. except OSError as e:
  785. if e.errno == errno.EEXIST:
  786. pass
  787. self._file = open(filename, 'w', newline='')
  788. def __enter__(self):
  789. self._file.write(self._ENTER_MSG)
  790. return self._file
  791. def __exit__(self, exc_type, exc_value, traceback):
  792. self._file.write(self._EXIT_MSG)
  793. self._file.close()
  794. class CHeaderWriter(CWriter):
  795. """Context manager that creates a C header file.
  796. Works the same way as CWriter, except it will also add the #ifdef guard
  797. around it. If `file_comment` is set, it will write that before the #ifdef
  798. guard.
  799. """
  800. def __init__(self, filename, year, file_comment=None):
  801. super().__init__(filename, year)
  802. guard = self._get_guard()
  803. if file_comment is None:
  804. file_comment = ""
  805. self._ENTER_MSG = self._ENTER_MSG + file_comment \
  806. + "#ifndef %s\n#define %s\n\n" % (guard, guard)
  807. self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
  808. def _get_guard(self):
  809. non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
  810. assert self.filename.startswith("gpu/")
  811. return non_alnum_re.sub('_', self.filename).upper() + '_'
  812. class TypeHandler():
  813. """This class emits code for a particular type of function."""
  814. _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
  815. def InitFunction(self, func):
  816. """Add or adjust anything type specific for this function."""
  817. if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
  818. func.AddCmdArg(DataSizeArgument('data_size'))
  819. def NeedsDataTransferFunction(self, func):
  820. """Overriden from TypeHandler."""
  821. return func.num_pointer_args >= 1
  822. def WriteStruct(self, func, f):
  823. """Writes a structure that matches the arguments to a function."""
  824. comment = func.GetInfo('cmd_comment')
  825. if not comment == None:
  826. f.write(comment)
  827. f.write("struct %s {\n" % func.name)
  828. f.write(" typedef %s ValueType;\n" % func.name)
  829. f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
  830. func.WriteCmdArgFlag(f)
  831. func.WriteCmdFlag(f)
  832. f.write("\n")
  833. result = func.GetInfo('result')
  834. if not result == None:
  835. if len(result) == 1:
  836. f.write(" typedef %s Result;\n\n" % result[0])
  837. else:
  838. f.write(" struct Result {\n")
  839. for line in result:
  840. f.write(" %s;\n" % line)
  841. f.write(" };\n\n")
  842. func.WriteCmdComputeSize(f)
  843. func.WriteCmdSetHeader(f)
  844. func.WriteCmdInit(f)
  845. func.WriteCmdSet(f)
  846. func.WriteArgAccessors(f)
  847. f.write(" gpu::CommandHeader header;\n")
  848. total_args = 0
  849. args = func.GetCmdArgs()
  850. for arg in args:
  851. for cmd_type, name in arg.GetArgDecls():
  852. f.write(" %s %s;\n" % (cmd_type, name))
  853. total_args += 1
  854. trace_queue = func.GetInfo('trace_queueing_flow', False)
  855. if trace_queue:
  856. f.write(" uint32_t trace_id;\n")
  857. total_args += 1
  858. consts = func.GetCmdConstants()
  859. for const in consts:
  860. const_decls = const.GetArgDecls()
  861. assert(len(const_decls) == 1)
  862. const_cmd_type, const_name = const_decls[0]
  863. f.write(" static const %s %s = %s;\n" %
  864. (const_cmd_type, const_name, const.GetConstantValue()))
  865. f.write("};\n")
  866. f.write("\n")
  867. size = total_args * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
  868. f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
  869. f.write(" \"size of %s should be %d\");\n" %
  870. (func.name, size))
  871. f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
  872. f.write(" \"offset of %s header should be 0\");\n" %
  873. func.name)
  874. offset = _SIZE_OF_COMMAND_HEADER
  875. for arg in args:
  876. for _, name in arg.GetArgDecls():
  877. f.write("static_assert(offsetof(%s, %s) == %d,\n" %
  878. (func.name, name, offset))
  879. f.write(" \"offset of %s %s should be %d\");\n" %
  880. (func.name, name, offset))
  881. offset += _SIZE_OF_UINT32
  882. if not result == None and len(result) > 1:
  883. offset = 0;
  884. for line in result:
  885. parts = line.split()
  886. name = parts[-1]
  887. check = """
  888. static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
  889. "offset of %(cmd_name)s Result %(field_name)s should be "
  890. "%(offset)d");
  891. """
  892. f.write((check.strip() + "\n") % {
  893. 'cmd_name': func.name,
  894. 'field_name': name,
  895. 'offset': offset,
  896. })
  897. offset += _SIZE_OF_UINT32
  898. f.write("\n")
  899. def WriteHandlerImplementation(self, func, f):
  900. """Writes the handler implementation for this command."""
  901. args = []
  902. for arg in func.GetOriginalArgs():
  903. if arg.name.endswith("size") and arg.type == "GLsizei":
  904. args.append("num_%s" % func.GetLastOriginalArg().name)
  905. elif arg.name == "length":
  906. args.append("nullptr")
  907. else:
  908. args.append(arg.name)
  909. if func.GetInfo('type') == 'GETn' and func.name != 'GetSynciv':
  910. args.append('num_values')
  911. f.write(" %s(%s);\n" %
  912. (func.GetGLFunctionName(), ", ".join(args)))
  913. def WriteCmdSizeTest(self, _func, f):
  914. """Writes the size test for a command."""
  915. f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
  916. def WriteFormatTest(self, func, f):
  917. """Writes a format test for a command."""
  918. f.write("TEST_F(%sFormatTest, %s) {\n" % (_prefix, func.name))
  919. f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
  920. (func.name, func.name))
  921. f.write(" void* next_cmd = cmd.Set(\n")
  922. f.write(" &cmd")
  923. args = func.GetCmdArgs()
  924. for value, arg in enumerate(args):
  925. f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
  926. f.write(");\n")
  927. f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
  928. func.name)
  929. f.write(" cmd.header.command);\n")
  930. func.type_handler.WriteCmdSizeTest(func, f)
  931. for value, arg in enumerate(args):
  932. f.write(" EXPECT_EQ(static_cast<%s>(%d), %s);\n" %
  933. (arg.type, value + 11, arg.GetArgAccessor('cmd')))
  934. f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
  935. f.write(" next_cmd, sizeof(cmd));\n")
  936. f.write("}\n")
  937. f.write("\n")
  938. def WriteImmediateFormatTest(self, func, f):
  939. """Writes a format test for an immediate version of a command."""
  940. def WriteGetDataSizeCode(self, func, arg, f):
  941. """Writes the code to set data_size used in validation"""
  942. def WriteImmediateHandlerImplementation (self, func, f):
  943. """Writes the handler impl for the immediate version of a command."""
  944. f.write(" %s(%s);\n" %
  945. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  946. def WriteBucketHandlerImplementation (self, func, f):
  947. """Writes the handler impl for the bucket version of a command."""
  948. f.write(" %s(%s);\n" %
  949. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  950. def WriteServiceHandlerFunctionHeader(self, func, f):
  951. """Writes function header for service implementation handlers."""
  952. f.write("""error::Error %(prefix)sDecoderImpl::Handle%(name)s(
  953. uint32_t immediate_data_size, const volatile void* cmd_data) {
  954. """ % {'name': func.name, 'prefix' : _prefix})
  955. if func.IsES3():
  956. f.write("""if (!feature_info_->IsWebGL2OrES3OrHigherContext())
  957. return error::kUnknownCommand;
  958. """)
  959. if func.IsES31():
  960. f.write("""return error::kUnknownCommand;
  961. }
  962. """)
  963. return
  964. if func.GetCmdArgs():
  965. f.write("""const volatile %(prefix)s::cmds::%(name)s& c =
  966. *static_cast<const volatile %(prefix)s::cmds::%(name)s*>(cmd_data);
  967. """ % {'name': func.name, 'prefix': _lower_prefix})
  968. def WriteServiceHandlerArgGetCode(self, func, f):
  969. """Writes the argument unpack code for service handlers."""
  970. if len(func.GetOriginalArgs()) > 0:
  971. for arg in func.GetOriginalArgs():
  972. if not arg.IsPointer():
  973. arg.WriteGetCode(f)
  974. # Write pointer arguments second. Sizes may be dependent on other args
  975. for arg in func.GetOriginalArgs():
  976. if arg.IsPointer():
  977. self.WriteGetDataSizeCode(func, arg, f)
  978. arg.WriteGetCode(f)
  979. def WriteImmediateServiceHandlerArgGetCode(self, func, f):
  980. """Writes the argument unpack code for immediate service handlers."""
  981. for arg in func.GetOriginalArgs():
  982. if arg.IsPointer():
  983. self.WriteGetDataSizeCode(func, arg, f)
  984. arg.WriteGetCode(f)
  985. def WriteBucketServiceHandlerArgGetCode(self, func, f):
  986. """Writes the argument unpack code for bucket service handlers."""
  987. for arg in func.GetCmdArgs():
  988. arg.WriteGetCode(f)
  989. for arg in func.GetOriginalArgs():
  990. if arg.IsConstant():
  991. arg.WriteGetCode(f)
  992. self.WriteGetDataSizeCode(func, arg, f)
  993. def WriteServiceImplementation(self, func, f):
  994. """Writes the service implementation for a command."""
  995. self.WriteServiceHandlerFunctionHeader(func, f)
  996. if func.IsES31():
  997. return
  998. self.WriteHandlerExtensionCheck(func, f)
  999. self.WriteHandlerDeferReadWrite(func, f);
  1000. self.WriteServiceHandlerArgGetCode(func, f)
  1001. func.WriteHandlerValidation(f)
  1002. func.WriteQueueTraceEvent(f)
  1003. func.WriteHandlerImplementation(f)
  1004. f.write(" return error::kNoError;\n")
  1005. f.write("}\n")
  1006. f.write("\n")
  1007. def WriteImmediateServiceImplementation(self, func, f):
  1008. """Writes the service implementation for an immediate version of command."""
  1009. self.WriteServiceHandlerFunctionHeader(func, f)
  1010. if func.IsES31():
  1011. return
  1012. self.WriteHandlerExtensionCheck(func, f)
  1013. self.WriteHandlerDeferReadWrite(func, f);
  1014. self.WriteImmediateServiceHandlerArgGetCode(func, f)
  1015. func.WriteHandlerValidation(f)
  1016. func.WriteQueueTraceEvent(f)
  1017. func.WriteHandlerImplementation(f)
  1018. f.write(" return error::kNoError;\n")
  1019. f.write("}\n")
  1020. f.write("\n")
  1021. def WriteBucketServiceImplementation(self, func, f):
  1022. """Writes the service implementation for a bucket version of command."""
  1023. self.WriteServiceHandlerFunctionHeader(func, f)
  1024. if func.IsES31():
  1025. return
  1026. self.WriteHandlerExtensionCheck(func, f)
  1027. self.WriteHandlerDeferReadWrite(func, f);
  1028. self.WriteBucketServiceHandlerArgGetCode(func, f)
  1029. func.WriteHandlerValidation(f)
  1030. func.WriteQueueTraceEvent(f)
  1031. func.WriteHandlerImplementation(f)
  1032. f.write(" return error::kNoError;\n")
  1033. f.write("}\n")
  1034. f.write("\n")
  1035. def WritePassthroughServiceFunctionHeader(self, func, f):
  1036. """Writes function header for service passthrough handlers."""
  1037. f.write("""error::Error GLES2DecoderPassthroughImpl::Handle%(name)s(
  1038. uint32_t immediate_data_size, const volatile void* cmd_data) {
  1039. """ % {'name': func.name})
  1040. if func.IsES3():
  1041. f.write("""if (!feature_info_->IsWebGL2OrES3OrHigherContext())
  1042. return error::kUnknownCommand;
  1043. """)
  1044. if func.IsES31():
  1045. f.write("""if (!feature_info_->IsES31ForTestingContext())
  1046. return error::kUnknownCommand;
  1047. """)
  1048. if func.GetCmdArgs():
  1049. f.write("""const volatile gles2::cmds::%(name)s& c =
  1050. *static_cast<const volatile gles2::cmds::%(name)s*>(cmd_data);
  1051. """ % {'name': func.name})
  1052. def WritePassthroughServiceFunctionDoerCall(self, func, f):
  1053. """Writes the function call to the passthrough service doer."""
  1054. f.write(""" error::Error error = Do%(name)s(%(args)s);
  1055. if (error != error::kNoError) {
  1056. return error;
  1057. }""" % {'name': func.original_name,
  1058. 'args': func.MakePassthroughServiceDoerArgString("")})
  1059. def WritePassthroughServiceImplementation(self, func, f):
  1060. """Writes the service implementation for a command."""
  1061. self.WritePassthroughServiceFunctionHeader(func, f)
  1062. self.WriteHandlerExtensionCheck(func, f)
  1063. self.WriteServiceHandlerArgGetCode(func, f)
  1064. func.WritePassthroughHandlerValidation(f)
  1065. self.WritePassthroughServiceFunctionDoerCall(func, f)
  1066. f.write(" return error::kNoError;\n")
  1067. f.write("}\n")
  1068. f.write("\n")
  1069. def WritePassthroughImmediateServiceImplementation(self, func, f):
  1070. """Writes the service implementation for a command."""
  1071. self.WritePassthroughServiceFunctionHeader(func, f)
  1072. self.WriteHandlerExtensionCheck(func, f)
  1073. self.WriteImmediateServiceHandlerArgGetCode(func, f)
  1074. func.WritePassthroughHandlerValidation(f)
  1075. self.WritePassthroughServiceFunctionDoerCall(func, f)
  1076. f.write(" return error::kNoError;\n")
  1077. f.write("}\n")
  1078. f.write("\n")
  1079. def WritePassthroughBucketServiceImplementation(self, func, f):
  1080. """Writes the service implementation for a command."""
  1081. self.WritePassthroughServiceFunctionHeader(func, f)
  1082. self.WriteHandlerExtensionCheck(func, f)
  1083. self.WriteBucketServiceHandlerArgGetCode(func, f)
  1084. func.WritePassthroughHandlerValidation(f)
  1085. self.WritePassthroughServiceFunctionDoerCall(func, f)
  1086. f.write(" return error::kNoError;\n")
  1087. f.write("}\n")
  1088. f.write("\n")
  1089. def WriteHandlerExtensionCheck(self, func, f):
  1090. if func.GetInfo('extension_flag'):
  1091. f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
  1092. f.write(" return error::kUnknownCommand;")
  1093. f.write(" }\n\n")
  1094. def WriteHandlerDeferReadWrite(self, func, f):
  1095. """Writes the code to handle deferring reads or writes."""
  1096. defer_draws = func.GetInfo('defer_draws')
  1097. defer_reads = func.GetInfo('defer_reads')
  1098. if defer_draws or defer_reads:
  1099. f.write(" error::Error error;\n")
  1100. if defer_draws:
  1101. f.write(" error = WillAccessBoundFramebufferForDraw();\n")
  1102. f.write(" if (error != error::kNoError)\n")
  1103. f.write(" return error;\n")
  1104. if defer_reads:
  1105. f.write(" error = WillAccessBoundFramebufferForRead();\n")
  1106. f.write(" if (error != error::kNoError)\n")
  1107. f.write(" return error;\n")
  1108. def WriteValidUnitTest(self, func, f, test, *extras):
  1109. """Writes a valid unit test for the service implementation."""
  1110. if not func.GetInfo('expectation', True):
  1111. test = self._remove_expected_call_re.sub('', test)
  1112. name = func.name
  1113. arg_strings = [
  1114. arg.GetValidArg(func) \
  1115. for arg in func.GetOriginalArgs() if not arg.IsConstant()
  1116. ]
  1117. gl_arg_strings = [
  1118. arg.GetValidGLArg(func) \
  1119. for arg in func.GetOriginalArgs()
  1120. ]
  1121. gl_func_name = func.GetGLTestFunctionName()
  1122. varz = {
  1123. 'name': name,
  1124. 'gl_func_name': gl_func_name,
  1125. 'args': ", ".join(arg_strings),
  1126. 'gl_args': ", ".join(gl_arg_strings),
  1127. }
  1128. for extra in extras:
  1129. varz.update(extra)
  1130. old_test = ""
  1131. while (old_test != test):
  1132. old_test = test
  1133. test = test % varz
  1134. f.write(test % varz)
  1135. def WriteInvalidUnitTest(self, func, f, test, *extras):
  1136. """Writes an invalid unit test for the service implementation."""
  1137. if func.IsES3():
  1138. return
  1139. for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
  1140. # Service implementation does not test constants, as they are not part of
  1141. # the call in the service side.
  1142. if invalid_arg.IsConstant():
  1143. continue
  1144. num_invalid_values = invalid_arg.GetNumInvalidValues(func)
  1145. for value_index in range(0, num_invalid_values):
  1146. arg_strings = []
  1147. parse_result = "kNoError"
  1148. gl_error = None
  1149. for arg in func.GetOriginalArgs():
  1150. if arg.IsConstant():
  1151. continue
  1152. if invalid_arg is arg:
  1153. (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
  1154. value_index)
  1155. else:
  1156. arg_string = arg.GetValidArg(func)
  1157. arg_strings.append(arg_string)
  1158. gl_arg_strings = []
  1159. for arg in func.GetOriginalArgs():
  1160. gl_arg_strings.append("_")
  1161. gl_func_name = func.GetGLTestFunctionName()
  1162. gl_error_test = ''
  1163. if not gl_error == None:
  1164. gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
  1165. varz = {
  1166. 'name': func.name,
  1167. 'arg_index': invalid_arg_index,
  1168. 'value_index': value_index,
  1169. 'gl_func_name': gl_func_name,
  1170. 'args': ", ".join(arg_strings),
  1171. 'all_but_last_args': ", ".join(arg_strings[:-1]),
  1172. 'gl_args': ", ".join(gl_arg_strings),
  1173. 'parse_result': parse_result,
  1174. 'gl_error_test': gl_error_test,
  1175. }
  1176. for extra in extras:
  1177. varz.update(extra)
  1178. f.write(test % varz)
  1179. def WriteServiceUnitTest(self, func, f, *extras):
  1180. """Writes the service unit test for a command."""
  1181. if func.name == 'Enable':
  1182. valid_test = """
  1183. TEST_P(%(test_name)s, %(name)sValidArgs) {
  1184. SetupExpectationsForEnableDisable(%(gl_args)s, true);
  1185. SpecializedSetup<cmds::%(name)s, 0>(true);
  1186. cmds::%(name)s cmd;
  1187. cmd.Init(%(args)s);"""
  1188. elif func.name == 'Disable':
  1189. valid_test = """
  1190. TEST_P(%(test_name)s, %(name)sValidArgs) {
  1191. SetupExpectationsForEnableDisable(%(gl_args)s, false);
  1192. SpecializedSetup<cmds::%(name)s, 0>(true);
  1193. cmds::%(name)s cmd;
  1194. cmd.Init(%(args)s);"""
  1195. else:
  1196. valid_test = """
  1197. TEST_P(%(test_name)s, %(name)sValidArgs) {
  1198. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  1199. SpecializedSetup<cmds::%(name)s, 0>(true);
  1200. cmds::%(name)s cmd;
  1201. cmd.Init(%(args)s);"""
  1202. valid_test += """
  1203. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1204. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  1205. }
  1206. """
  1207. self.WriteValidUnitTest(func, f, valid_test, *extras)
  1208. if not func.IsES3():
  1209. invalid_test = """
  1210. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  1211. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  1212. SpecializedSetup<cmds::%(name)s, 0>(false);
  1213. cmds::%(name)s cmd;
  1214. cmd.Init(%(args)s);
  1215. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
  1216. }
  1217. """
  1218. self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
  1219. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  1220. """Writes the service unit test for an immediate command."""
  1221. def WriteImmediateValidationCode(self, func, f):
  1222. """Writes the validation code for an immediate version of a command."""
  1223. def WriteBucketServiceUnitTest(self, func, f, *extras):
  1224. """Writes the service unit test for a bucket command."""
  1225. def WriteGLES2ImplementationDeclaration(self, func, f):
  1226. """Writes the GLES2 Implemention declaration."""
  1227. f.write("%s %s(%s) override;\n" %
  1228. (func.return_type, func.original_name,
  1229. func.MakeTypedOriginalArgString("", add_default = True)))
  1230. f.write("\n")
  1231. def WriteGLES2CLibImplementation(self, func, f):
  1232. f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
  1233. (func.return_type, func.name,
  1234. func.MakeTypedOriginalArgString("")))
  1235. result_string = "return "
  1236. if func.return_type == "void":
  1237. result_string = ""
  1238. f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
  1239. (result_string, func.original_name,
  1240. func.MakeOriginalArgString("")))
  1241. f.write("}\n")
  1242. def WriteGLES2Header(self, func, f):
  1243. """Writes a re-write macro for GLES"""
  1244. f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
  1245. def WriteClientGLCallLog(self, func, f):
  1246. """Writes a logging macro for the client side code."""
  1247. comma = ""
  1248. if len(func.GetOriginalArgs()):
  1249. comma = " << "
  1250. f.write(
  1251. ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] %s("%s%s << ")");\n' %
  1252. (func.prefixed_name, comma, func.MakeLogArgString()))
  1253. def WriteClientGLReturnLog(self, func, f):
  1254. """Writes the return value logging code."""
  1255. if func.return_type != "void":
  1256. f.write(' GPU_CLIENT_LOG("return:" << result)\n')
  1257. def WriteGLES2ImplementationHeader(self, func, f):
  1258. """Writes the GLES2 Implemention."""
  1259. self.WriteGLES2ImplementationDeclaration(func, f)
  1260. def WriteGLES2TraceImplementationHeader(self, func, f):
  1261. """Writes the GLES2 Trace Implemention header."""
  1262. f.write("%s %s(%s) override;\n" %
  1263. (func.return_type, func.original_name,
  1264. func.MakeTypedOriginalArgString("")))
  1265. def WriteGLES2TraceImplementation(self, func, f):
  1266. """Writes the GLES2 Trace Implemention."""
  1267. f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
  1268. (func.return_type, func.original_name,
  1269. func.MakeTypedOriginalArgString("")))
  1270. result_string = "return "
  1271. if func.return_type == "void":
  1272. result_string = ""
  1273. f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
  1274. func.name)
  1275. f.write(" %sgl_->%s(%s);\n" %
  1276. (result_string, func.name, func.MakeOriginalArgString("")))
  1277. f.write("}\n")
  1278. f.write("\n")
  1279. def WriteGLES2Implementation(self, func, f):
  1280. """Writes the GLES2 Implemention."""
  1281. impl_func = func.GetInfo('impl_func', True)
  1282. if func.can_auto_generate and impl_func:
  1283. f.write("%s %sImplementation::%s(%s) {\n" %
  1284. (func.return_type, _prefix, func.original_name,
  1285. func.MakeTypedOriginalArgString("")))
  1286. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  1287. self.WriteClientGLCallLog(func, f)
  1288. func.WriteDestinationInitalizationValidation(f)
  1289. for arg in func.GetOriginalArgs():
  1290. arg.WriteClientSideValidationCode(f, func)
  1291. f.write(" helper_->%s(%s);\n" %
  1292. (func.name, func.MakeHelperArgString("")))
  1293. if _prefix != 'WebGPU':
  1294. f.write(" CheckGLError();\n")
  1295. self.WriteClientGLReturnLog(func, f)
  1296. f.write("}\n")
  1297. f.write("\n")
  1298. def WriteGLES2InterfaceHeader(self, func, f):
  1299. """Writes the GLES2 Interface."""
  1300. f.write("virtual %s %s(%s) = 0;\n" %
  1301. (func.return_type, func.original_name,
  1302. func.MakeTypedOriginalArgString("", add_default = True)))
  1303. def WriteGLES2InterfaceStub(self, func, f):
  1304. """Writes the GLES2 Interface stub declaration."""
  1305. f.write("%s %s(%s) override;\n" %
  1306. (func.return_type, func.original_name,
  1307. func.MakeTypedOriginalArgString("")))
  1308. def WriteGLES2InterfaceStubImpl(self, func, f):
  1309. """Writes the GLES2 Interface stub declaration."""
  1310. args = func.GetOriginalArgs()
  1311. arg_string = ", ".join(
  1312. ["%s /* %s */" % (arg.type, arg.name) for arg in args])
  1313. f.write("%s %sInterfaceStub::%s(%s) {\n" %
  1314. (func.return_type, _prefix, func.original_name, arg_string))
  1315. if func.return_type != "void":
  1316. f.write(" return 0;\n")
  1317. f.write("}\n")
  1318. def WriteGLES2ImplementationUnitTest(self, func, f):
  1319. """Writes the GLES2 Implemention unit test."""
  1320. client_test = func.GetInfo('client_test', True)
  1321. if func.can_auto_generate and client_test:
  1322. code = """
  1323. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  1324. struct Cmds {
  1325. cmds::%(name)s cmd;
  1326. };
  1327. Cmds expected;
  1328. expected.cmd.Init(%(cmd_args)s);
  1329. gl_->%(name)s(%(args)s);
  1330. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  1331. }
  1332. """
  1333. cmd_arg_strings = [
  1334. arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
  1335. ]
  1336. gl_arg_strings = [
  1337. arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
  1338. ]
  1339. f.write(code % {
  1340. 'prefix' : _prefix,
  1341. 'name': func.name,
  1342. 'args': ", ".join(gl_arg_strings),
  1343. 'cmd_args': ", ".join(cmd_arg_strings),
  1344. })
  1345. # Test constants for invalid values, as they are not tested by the
  1346. # service.
  1347. constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
  1348. if constants:
  1349. code = """
  1350. TEST_F(%(prefix)sImplementationTest,
  1351. %(name)sInvalidConstantArg%(invalid_index)d) {
  1352. gl_->%(name)s(%(args)s);
  1353. EXPECT_TRUE(NoCommandsWritten());
  1354. EXPECT_EQ(%(gl_error)s, CheckError());
  1355. }
  1356. """
  1357. for invalid_arg in constants:
  1358. gl_arg_strings = []
  1359. invalid = invalid_arg.GetInvalidArg(0)
  1360. for arg in func.GetOriginalArgs():
  1361. if arg is invalid_arg:
  1362. gl_arg_strings.append(invalid[0])
  1363. else:
  1364. gl_arg_strings.append(arg.GetValidClientSideArg(func))
  1365. f.write(code % {
  1366. 'prefix' : _prefix,
  1367. 'name': func.name,
  1368. 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
  1369. 'args': ", ".join(gl_arg_strings),
  1370. 'gl_error': invalid[2],
  1371. })
  1372. def WriteDestinationInitalizationValidation(self, func, f):
  1373. """Writes the client side destintion initialization validation."""
  1374. for arg in func.GetOriginalArgs():
  1375. arg.WriteDestinationInitalizationValidation(f, func)
  1376. def WriteTraceEvent(self, func, f):
  1377. f.write(' TRACE_EVENT0("gpu", "%sImplementation::%s");\n' %
  1378. (_prefix, func.original_name))
  1379. def WriteImmediateCmdComputeSize(self, _func, f):
  1380. """Writes the size computation code for the immediate version of a cmd."""
  1381. f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
  1382. f.write(" return static_cast<uint32_t>(\n")
  1383. f.write(" sizeof(ValueType) + // NOLINT\n")
  1384. f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
  1385. f.write(" }\n")
  1386. f.write("\n")
  1387. def WriteImmediateCmdSetHeader(self, _func, f):
  1388. """Writes the SetHeader function for the immediate version of a cmd."""
  1389. f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
  1390. f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
  1391. f.write(" }\n")
  1392. f.write("\n")
  1393. def WriteImmediateCmdInit(self, func, f):
  1394. """Writes the Init function for the immediate version of a command."""
  1395. raise NotImplementedError(func.name)
  1396. def WriteImmediateCmdSet(self, func, f):
  1397. """Writes the Set function for the immediate version of a command."""
  1398. raise NotImplementedError(func.name)
  1399. def WriteCmdHelper(self, func, f):
  1400. """Writes the cmd helper definition for a cmd."""
  1401. code = """ void %(name)s(%(typed_args)s) {
  1402. %(lp)s::cmds::%(name)s* c = GetCmdSpace<%(lp)s::cmds::%(name)s>();
  1403. if (c) {
  1404. c->Init(%(args)s);
  1405. }
  1406. }
  1407. """
  1408. f.write(code % {
  1409. "lp" : _lower_prefix,
  1410. "name": func.name,
  1411. "typed_args": func.MakeTypedCmdArgString(""),
  1412. "args": func.MakeCmdArgString(""),
  1413. })
  1414. def WriteImmediateCmdHelper(self, func, f):
  1415. """Writes the cmd helper definition for the immediate version of a cmd."""
  1416. code = """ void %(name)s(%(typed_args)s) {
  1417. const uint32_t s = 0;
  1418. %(lp)s::cmds::%(name)s* c =
  1419. GetImmediateCmdSpaceTotalSize<%(lp)s::cmds::%(name)s>(s);
  1420. if (c) {
  1421. c->Init(%(args)s);
  1422. }
  1423. }
  1424. """
  1425. f.write(code % {
  1426. "lp" : _lower_prefix,
  1427. "name": func.name,
  1428. "typed_args": func.MakeTypedCmdArgString(""),
  1429. "args": func.MakeCmdArgString(""),
  1430. })
  1431. class StateSetHandler(TypeHandler):
  1432. """Handler for commands that simply set state."""
  1433. def WriteHandlerImplementation(self, func, f):
  1434. """Overrriden from TypeHandler."""
  1435. state_name = func.GetInfo('state')
  1436. state = _STATE_INFO[state_name]
  1437. states = state['states']
  1438. args = func.GetOriginalArgs()
  1439. for ndx,item in enumerate(states):
  1440. code = []
  1441. if 'range_checks' in item:
  1442. for range_check in item['range_checks']:
  1443. code.append("%s %s" % (args[ndx].name, range_check['check']))
  1444. if 'nan_check' in item:
  1445. # Drivers might generate an INVALID_VALUE error when a value is set
  1446. # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
  1447. # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
  1448. # Make this behavior consistent within Chromium, and avoid leaking GL
  1449. # errors by generating the error in the command buffer instead of
  1450. # letting the GL driver generate it.
  1451. code.append("std::isnan(%s)" % args[ndx].name)
  1452. if code:
  1453. f.write(" if (%s) {\n" % " ||\n ".join(code))
  1454. f.write(
  1455. ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
  1456. ' "%s", "%s out of range");\n' %
  1457. (func.name, args[ndx].name))
  1458. f.write(" return error::kNoError;\n")
  1459. f.write(" }\n")
  1460. code = []
  1461. for ndx,item in enumerate(states):
  1462. code.append("state_.%s != %s" % (item['name'], args[ndx].name))
  1463. f.write(" if (%s) {\n" % " ||\n ".join(code))
  1464. for ndx,item in enumerate(states):
  1465. f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
  1466. if 'on_change' in state:
  1467. f.write(" %s\n" % state['on_change'])
  1468. if not func.GetInfo("no_gl"):
  1469. for ndx,item in enumerate(states):
  1470. if item.get('cached', False):
  1471. f.write(" state_.%s = %s;\n" %
  1472. (CachedStateName(item), args[ndx].name))
  1473. f.write(" %s(%s);\n" %
  1474. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  1475. f.write(" }\n")
  1476. def WriteServiceUnitTest(self, func, f, *extras):
  1477. """Overrriden from TypeHandler."""
  1478. TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
  1479. state_name = func.GetInfo('state')
  1480. state = _STATE_INFO[state_name]
  1481. states = state['states']
  1482. for ndx,item in enumerate(states):
  1483. if 'range_checks' in item:
  1484. for check_ndx, range_check in enumerate(item['range_checks']):
  1485. valid_test = """
  1486. TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
  1487. SpecializedSetup<cmds::%(name)s, 0>(false);
  1488. cmds::%(name)s cmd;
  1489. cmd.Init(%(args)s);
  1490. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1491. EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
  1492. }
  1493. """
  1494. name = func.name
  1495. arg_strings = [
  1496. arg.GetValidArg(func) \
  1497. for arg in func.GetOriginalArgs() if not arg.IsConstant()
  1498. ]
  1499. arg_strings[ndx] = range_check['test_value']
  1500. varz = {
  1501. 'name': name,
  1502. 'ndx': ndx,
  1503. 'check_ndx': check_ndx,
  1504. 'args': ", ".join(arg_strings),
  1505. }
  1506. for extra in extras:
  1507. varz.update(extra)
  1508. f.write(valid_test % varz)
  1509. if 'nan_check' in item:
  1510. valid_test = """
  1511. TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
  1512. SpecializedSetup<cmds::%(name)s, 0>(false);
  1513. cmds::%(name)s cmd;
  1514. cmd.Init(%(args)s);
  1515. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1516. EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
  1517. }
  1518. """
  1519. name = func.name
  1520. arg_strings = [
  1521. arg.GetValidArg(func) \
  1522. for arg in func.GetOriginalArgs() if not arg.IsConstant()
  1523. ]
  1524. arg_strings[ndx] = 'nanf("")'
  1525. varz = {
  1526. 'name': name,
  1527. 'ndx': ndx,
  1528. 'args': ", ".join(arg_strings),
  1529. }
  1530. for extra in extras:
  1531. varz.update(extra)
  1532. f.write(valid_test % varz)
  1533. def WriteImmediateCmdInit(self, func, f):
  1534. """Overrriden from TypeHandler."""
  1535. def WriteImmediateCmdSet(self, func, f):
  1536. """Overrriden from TypeHandler."""
  1537. class StateSetRGBAlphaHandler(TypeHandler):
  1538. """Handler for commands that simply set state that have rgb/alpha."""
  1539. def WriteHandlerImplementation(self, func, f):
  1540. """Overrriden from TypeHandler."""
  1541. state_name = func.GetInfo('state')
  1542. state = _STATE_INFO[state_name]
  1543. states = state['states']
  1544. args = func.GetOriginalArgs()
  1545. num_args = len(args)
  1546. code = []
  1547. for ndx,item in enumerate(states):
  1548. code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
  1549. f.write(" if (%s) {\n" % " ||\n ".join(code))
  1550. for ndx, item in enumerate(states):
  1551. f.write(" state_.%s = %s;\n" %
  1552. (item['name'], args[ndx % num_args].name))
  1553. if 'on_change' in state:
  1554. f.write(" %s\n" % state['on_change'])
  1555. if not func.GetInfo("no_gl"):
  1556. f.write(" %s(%s);\n" %
  1557. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  1558. f.write(" }\n")
  1559. def WriteImmediateCmdInit(self, func, f):
  1560. """Overrriden from TypeHandler."""
  1561. def WriteImmediateCmdSet(self, func, f):
  1562. """Overrriden from TypeHandler."""
  1563. class StateSetFrontBackSeparateHandler(TypeHandler):
  1564. """Handler for commands that simply set state that have front/back."""
  1565. def WriteHandlerImplementation(self, func, f):
  1566. """Overrriden from TypeHandler."""
  1567. state_name = func.GetInfo('state')
  1568. state = _STATE_INFO[state_name]
  1569. states = state['states']
  1570. args = func.GetOriginalArgs()
  1571. face = args[0].name
  1572. num_args = len(args)
  1573. f.write(" bool changed = false;\n")
  1574. for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
  1575. f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
  1576. (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
  1577. code = []
  1578. for ndx, item in enumerate(group):
  1579. code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
  1580. f.write(" changed |= %s;\n" % " ||\n ".join(code))
  1581. f.write(" }\n")
  1582. f.write(" if (changed) {\n")
  1583. for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
  1584. f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
  1585. (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
  1586. for ndx, item in enumerate(group):
  1587. f.write(" state_.%s = %s;\n" %
  1588. (item['name'], args[ndx + 1].name))
  1589. f.write(" }\n")
  1590. if 'on_change' in state:
  1591. f.write(" %s\n" % state['on_change'])
  1592. if not func.GetInfo("no_gl"):
  1593. f.write(" %s(%s);\n" %
  1594. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  1595. f.write(" }\n")
  1596. def WriteImmediateCmdInit(self, func, f):
  1597. """Overrriden from TypeHandler."""
  1598. def WriteImmediateCmdSet(self, func, f):
  1599. """Overrriden from TypeHandler."""
  1600. class StateSetFrontBackHandler(TypeHandler):
  1601. """Handler for commands that simply set state that set both front/back."""
  1602. def WriteHandlerImplementation(self, func, f):
  1603. """Overrriden from TypeHandler."""
  1604. state_name = func.GetInfo('state')
  1605. state = _STATE_INFO[state_name]
  1606. states = state['states']
  1607. args = func.GetOriginalArgs()
  1608. num_args = len(args)
  1609. code = []
  1610. for group in Grouper(num_args, states):
  1611. for ndx, item in enumerate(group):
  1612. code.append("state_.%s != %s" % (item['name'], args[ndx].name))
  1613. f.write(" if (%s) {\n" % " ||\n ".join(code))
  1614. for group in Grouper(num_args, states):
  1615. for ndx, item in enumerate(group):
  1616. f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
  1617. if 'on_change' in state:
  1618. f.write(" %s\n" % state['on_change'])
  1619. if not func.GetInfo("no_gl"):
  1620. f.write(" %s(%s);\n" %
  1621. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  1622. f.write(" }\n")
  1623. def WriteImmediateCmdInit(self, func, f):
  1624. """Overrriden from TypeHandler."""
  1625. def WriteImmediateCmdSet(self, func, f):
  1626. """Overrriden from TypeHandler."""
  1627. class StateSetNamedParameter(TypeHandler):
  1628. """Handler for commands that set a state chosen with an enum parameter."""
  1629. def WriteHandlerImplementation(self, func, f):
  1630. """Overridden from TypeHandler."""
  1631. state_name = func.GetInfo('state')
  1632. state = _STATE_INFO[state_name]
  1633. states = state['states']
  1634. args = func.GetOriginalArgs()
  1635. num_args = len(args)
  1636. assert num_args == 2
  1637. f.write(" switch (%s) {\n" % args[0].name)
  1638. for state in states:
  1639. f.write(" case %s:\n" % state['enum'])
  1640. f.write(" if (state_.%s != %s) {\n" %
  1641. (state['name'], args[1].name))
  1642. f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
  1643. if not func.GetInfo("no_gl"):
  1644. operation = " %s(%s);\n" % \
  1645. (func.GetGLFunctionName(), func.MakeOriginalArgString(""))
  1646. f.write(GuardState(state, operation, "feature_info_"))
  1647. f.write(" }\n")
  1648. f.write(" break;\n")
  1649. f.write(" default:\n")
  1650. f.write(" NOTREACHED();\n")
  1651. f.write(" }\n")
  1652. def WriteImmediateCmdInit(self, func, f):
  1653. """Overrriden from TypeHandler."""
  1654. def WriteImmediateCmdSet(self, func, f):
  1655. """Overrriden from TypeHandler."""
  1656. class CustomHandler(TypeHandler):
  1657. """Handler for commands that are auto-generated but require minor tweaks."""
  1658. def InitFunction(self, func):
  1659. """Overrriden from TypeHandler."""
  1660. if (func.name.startswith('CompressedTex') and func.name.endswith('Bucket')):
  1661. # Remove imageSize argument, take the size from the bucket instead.
  1662. func.cmd_args = [arg for arg in func.cmd_args if arg.name != 'imageSize']
  1663. func.AddCmdArg(Argument('bucket_id', 'GLuint'))
  1664. else:
  1665. TypeHandler.InitFunction(self, func)
  1666. def WriteServiceImplementation(self, func, f):
  1667. """Overrriden from TypeHandler."""
  1668. if func.IsES31():
  1669. TypeHandler.WriteServiceImplementation(self, func, f)
  1670. def WriteImmediateServiceImplementation(self, func, f):
  1671. """Overrriden from TypeHandler."""
  1672. if func.IsES31():
  1673. TypeHandler.WriteImmediateServiceImplementation(self, func, f)
  1674. def WriteBucketServiceImplementation(self, func, f):
  1675. """Overrriden from TypeHandler."""
  1676. if func.IsES31():
  1677. TypeHandler.WriteBucketServiceImplementation(self, func, f)
  1678. def WritePassthroughServiceImplementation(self, func, f):
  1679. """Overrriden from TypeHandler."""
  1680. def WritePassthroughImmediateServiceImplementation(self, func, f):
  1681. """Overrriden from TypeHandler."""
  1682. def WritePassthroughBucketServiceImplementation(self, func, f):
  1683. """Overrriden from TypeHandler."""
  1684. def WriteServiceUnitTest(self, func, f, *extras):
  1685. """Overrriden from TypeHandler."""
  1686. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  1687. """Overrriden from TypeHandler."""
  1688. def WriteImmediateCmdGetTotalSize(self, _func, f):
  1689. """Overrriden from TypeHandler."""
  1690. f.write(
  1691. " uint32_t total_size = 0; // WARNING: compute correct size.\n")
  1692. def WriteImmediateCmdInit(self, func, f):
  1693. """Overrriden from TypeHandler."""
  1694. f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
  1695. self.WriteImmediateCmdGetTotalSize(func, f)
  1696. f.write(" SetHeader(total_size);\n")
  1697. args = func.GetCmdArgs()
  1698. for arg in args:
  1699. arg.WriteSetCode(f, 4, '_%s' % arg.name)
  1700. f.write(" }\n")
  1701. f.write("\n")
  1702. def WriteImmediateCmdSet(self, func, f):
  1703. """Overrriden from TypeHandler."""
  1704. copy_args = func.MakeCmdArgString("_", False)
  1705. f.write(" void* Set(void* cmd%s) {\n" %
  1706. func.MakeTypedCmdArgString("_", True))
  1707. self.WriteImmediateCmdGetTotalSize(func, f)
  1708. f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
  1709. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  1710. "cmd, total_size);\n")
  1711. f.write(" }\n")
  1712. f.write("\n")
  1713. class NoCommandHandler(CustomHandler):
  1714. """Handler for functions that don't use commands"""
  1715. def WriteGLES2Implementation(self, func, f):
  1716. pass
  1717. def WriteGLES2ImplementationUnitTest(self, func, f):
  1718. pass
  1719. class DataHandler(TypeHandler):
  1720. """
  1721. Handler for glBufferData, glBufferSubData, glTex{Sub}Image*D.
  1722. """
  1723. def WriteGetDataSizeCode(self, func, arg, f):
  1724. """Overrriden from TypeHandler."""
  1725. # TODO: Move this data to _FUNCTION_INFO?
  1726. name = func.name
  1727. if name.endswith("Immediate"):
  1728. name = name[0:-9]
  1729. if arg.name in func.size_args:
  1730. size = func.size_args[arg.name]
  1731. f.write(" uint32_t %s = %s;\n" % (arg.GetReservedSizeId(), size))
  1732. else:
  1733. f.write("// uint32_t %s = 0; // WARNING: compute correct size.\n" % (
  1734. arg.GetReservedSizeId()))
  1735. def WriteImmediateCmdGetTotalSize(self, func, f):
  1736. """Overrriden from TypeHandler."""
  1737. def WriteImmediateCmdInit(self, func, f):
  1738. """Overrriden from TypeHandler."""
  1739. f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
  1740. self.WriteImmediateCmdGetTotalSize(func, f)
  1741. f.write(" SetHeader(total_size);\n")
  1742. args = func.GetCmdArgs()
  1743. for arg in args:
  1744. f.write(" %s = _%s;\n" % (arg.name, arg.name))
  1745. f.write(" }\n")
  1746. f.write("\n")
  1747. def WriteImmediateCmdSet(self, func, f):
  1748. """Overrriden from TypeHandler."""
  1749. copy_args = func.MakeCmdArgString("_", False)
  1750. f.write(" void* Set(void* cmd%s) {\n" %
  1751. func.MakeTypedCmdArgString("_", True))
  1752. self.WriteImmediateCmdGetTotalSize(func, f)
  1753. f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
  1754. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  1755. "cmd, total_size);\n")
  1756. f.write(" }\n")
  1757. f.write("\n")
  1758. def WriteImmediateFormatTest(self, func, f):
  1759. """Overrriden from TypeHandler."""
  1760. # TODO: Remove this exception.
  1761. return
  1762. def WriteServiceUnitTest(self, func, f, *extras):
  1763. """Overrriden from TypeHandler."""
  1764. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  1765. """Overrriden from TypeHandler."""
  1766. def WriteImmediateCmdInit(self, func, f):
  1767. """Overrriden from TypeHandler."""
  1768. def WriteImmediateCmdSet(self, func, f):
  1769. """Overrriden from TypeHandler."""
  1770. class BindHandler(TypeHandler):
  1771. """Handler for glBind___ type functions."""
  1772. def WriteServiceUnitTest(self, func, f, *extras):
  1773. """Overrriden from TypeHandler."""
  1774. if len(func.GetOriginalArgs()) == 1:
  1775. valid_test = """
  1776. TEST_P(%(test_name)s, %(name)sValidArgs) {
  1777. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  1778. SpecializedSetup<cmds::%(name)s, 0>(true);
  1779. cmds::%(name)s cmd;
  1780. cmd.Init(%(args)s);
  1781. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1782. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  1783. }
  1784. """
  1785. if func.GetInfo("gen_func"):
  1786. valid_test += """
  1787. TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
  1788. EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
  1789. EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
  1790. .WillOnce(SetArgPointee<1>(kNewServiceId));
  1791. SpecializedSetup<cmds::%(name)s, 0>(true);
  1792. cmds::%(name)s cmd;
  1793. cmd.Init(kNewClientId);
  1794. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1795. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  1796. EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != nullptr);
  1797. }
  1798. """
  1799. self.WriteValidUnitTest(func, f, valid_test, {
  1800. 'resource_type': func.GetOriginalArgs()[0].resource_type,
  1801. 'gl_gen_func_name': func.GetInfo("gen_func"),
  1802. }, *extras)
  1803. else:
  1804. valid_test = """
  1805. TEST_P(%(test_name)s, %(name)sValidArgs) {
  1806. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  1807. SpecializedSetup<cmds::%(name)s, 0>(true);
  1808. cmds::%(name)s cmd;
  1809. cmd.Init(%(args)s);
  1810. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1811. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  1812. }
  1813. """
  1814. if func.GetInfo("gen_func"):
  1815. valid_test += """
  1816. TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
  1817. EXPECT_CALL(*gl_,
  1818. %(gl_func_name)s(%(gl_args_with_new_id)s));
  1819. EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
  1820. .WillOnce(SetArgPointee<1>(kNewServiceId));
  1821. SpecializedSetup<cmds::%(name)s, 0>(true);
  1822. cmds::%(name)s cmd;
  1823. cmd.Init(%(args_with_new_id)s);
  1824. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  1825. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  1826. EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != nullptr);
  1827. }
  1828. """
  1829. gl_args_with_new_id = []
  1830. args_with_new_id = []
  1831. for arg in func.GetOriginalArgs():
  1832. if hasattr(arg, 'resource_type'):
  1833. gl_args_with_new_id.append('kNewServiceId')
  1834. args_with_new_id.append('kNewClientId')
  1835. else:
  1836. gl_args_with_new_id.append(arg.GetValidGLArg(func))
  1837. args_with_new_id.append(arg.GetValidArg(func))
  1838. self.WriteValidUnitTest(func, f, valid_test, {
  1839. 'args_with_new_id': ", ".join(args_with_new_id),
  1840. 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
  1841. 'resource_type': func.GetResourceIdArg().resource_type,
  1842. 'gl_gen_func_name': func.GetInfo("gen_func"),
  1843. }, *extras)
  1844. invalid_test = """
  1845. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  1846. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  1847. SpecializedSetup<cmds::%(name)s, 0>(false);
  1848. cmds::%(name)s cmd;
  1849. cmd.Init(%(args)s);
  1850. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
  1851. }
  1852. """
  1853. self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
  1854. def WriteGLES2Implementation(self, func, f):
  1855. """Writes the GLES2 Implemention."""
  1856. impl_func = func.GetInfo('impl_func', True)
  1857. if func.can_auto_generate and impl_func:
  1858. f.write("%s %sImplementation::%s(%s) {\n" %
  1859. (func.return_type, _prefix, func.original_name,
  1860. func.MakeTypedOriginalArgString("")))
  1861. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  1862. func.WriteDestinationInitalizationValidation(f)
  1863. self.WriteClientGLCallLog(func, f)
  1864. for arg in func.GetOriginalArgs():
  1865. arg.WriteClientSideValidationCode(f, func)
  1866. code = """ if (Is%(type)sReservedId(%(id)s)) {
  1867. SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
  1868. return;
  1869. }
  1870. %(name)sHelper(%(arg_string)s);
  1871. CheckGLError();
  1872. }
  1873. """
  1874. name_arg = func.GetResourceIdArg()
  1875. f.write(code % {
  1876. 'name': func.name,
  1877. 'arg_string': func.MakeOriginalArgString(""),
  1878. 'id': name_arg.name,
  1879. 'type': name_arg.resource_type,
  1880. 'lc_type': name_arg.resource_type.lower(),
  1881. })
  1882. def WriteGLES2ImplementationUnitTest(self, func, f):
  1883. """Overrriden from TypeHandler."""
  1884. client_test = func.GetInfo('client_test', True)
  1885. if not client_test:
  1886. return
  1887. code = """
  1888. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  1889. struct Cmds {
  1890. cmds::%(name)s cmd;
  1891. };
  1892. Cmds expected;
  1893. expected.cmd.Init(%(cmd_args)s);
  1894. gl_->%(name)s(%(args)s);
  1895. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
  1896. if not func.IsES3():
  1897. code += """
  1898. ClearCommands();
  1899. gl_->%(name)s(%(args)s);
  1900. EXPECT_TRUE(NoCommandsWritten());"""
  1901. code += """
  1902. }
  1903. """
  1904. cmd_arg_strings = [
  1905. arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
  1906. ]
  1907. gl_arg_strings = [
  1908. arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
  1909. ]
  1910. f.write(code % {
  1911. 'prefix' : _prefix,
  1912. 'name': func.name,
  1913. 'args': ", ".join(gl_arg_strings),
  1914. 'cmd_args': ", ".join(cmd_arg_strings),
  1915. })
  1916. def WriteImmediateCmdInit(self, func, f):
  1917. """Overrriden from TypeHandler."""
  1918. def WriteImmediateCmdSet(self, func, f):
  1919. """Overrriden from TypeHandler."""
  1920. class GENnHandler(TypeHandler):
  1921. """Handler for glGen___ type functions."""
  1922. def InitFunction(self, func):
  1923. """Overrriden from TypeHandler."""
  1924. def WriteGetDataSizeCode(self, func, arg, f):
  1925. """Overrriden from TypeHandler."""
  1926. code = """ uint32_t %(data_size)s;
  1927. if (!base::CheckMul(n, sizeof(GLuint)).AssignIfValid(&%(data_size)s)) {
  1928. return error::kOutOfBounds;
  1929. }
  1930. """ % {'data_size': arg.GetReservedSizeId()}
  1931. f.write(code)
  1932. def WriteHandlerImplementation (self, func, f):
  1933. """Overrriden from TypeHandler."""
  1934. raise NotImplementedError("GENn functions are immediate")
  1935. def WriteImmediateHandlerImplementation(self, func, f):
  1936. """Overrriden from TypeHandler."""
  1937. param_name = func.GetLastOriginalArg().name
  1938. f.write(" auto %(name)s_copy = std::make_unique<GLuint[]>(n);\n"
  1939. " GLuint* %(name)s_safe = %(name)s_copy.get();\n"
  1940. " std::copy(%(name)s, %(name)s + n, %(name)s_safe);\n"
  1941. " if (!%(ns)sCheckUniqueAndNonNullIds(n, %(name)s_safe) ||\n"
  1942. " !%(func)sHelper(n, %(name)s_safe)) {\n"
  1943. " return error::kInvalidArguments;\n"
  1944. " }\n" % {'name': param_name,
  1945. 'func': func.original_name,
  1946. 'ns': _Namespace()})
  1947. def WriteGLES2Implementation(self, func, f):
  1948. """Overrriden from TypeHandler."""
  1949. log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
  1950. for (GLsizei i = 0; i < n; ++i) {
  1951. GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
  1952. }
  1953. });""" % func.GetOriginalArgs()[1].name)
  1954. args = {
  1955. 'log_code': log_code,
  1956. 'return_type': func.return_type,
  1957. 'prefix' : _prefix,
  1958. 'name': func.original_name,
  1959. 'typed_args': func.MakeTypedOriginalArgString(""),
  1960. 'args': func.MakeOriginalArgString(""),
  1961. 'resource_types': func.GetInfo('resource_types'),
  1962. 'count_name': func.GetOriginalArgs()[0].name,
  1963. }
  1964. f.write(
  1965. "%(return_type)s %(prefix)sImplementation::"
  1966. "%(name)s(%(typed_args)s) {\n" %
  1967. args)
  1968. func.WriteDestinationInitalizationValidation(f)
  1969. self.WriteClientGLCallLog(func, f)
  1970. for arg in func.GetOriginalArgs():
  1971. arg.WriteClientSideValidationCode(f, func)
  1972. not_shared = func.GetInfo('not_shared')
  1973. if not_shared:
  1974. alloc_code = ("""\
  1975. IdAllocator* id_allocator = GetIdAllocator(IdNamespaces::k%s);
  1976. for (GLsizei ii = 0; ii < n; ++ii)
  1977. %s[ii] = id_allocator->AllocateID();""" %
  1978. (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
  1979. else:
  1980. alloc_code = ("""\
  1981. GetIdHandler(SharedIdNamespaces::k%(resource_types)s)->
  1982. MakeIds(this, 0, %(args)s);""" % args)
  1983. args['alloc_code'] = alloc_code
  1984. code = """\
  1985. GPU_CLIENT_SINGLE_THREAD_CHECK();
  1986. %(alloc_code)s
  1987. %(name)sHelper(%(args)s);
  1988. helper_->%(name)sImmediate(%(args)s);
  1989. """
  1990. if not not_shared:
  1991. code += """\
  1992. if (share_group_->bind_generates_resource())
  1993. helper_->CommandBufferHelper::Flush();
  1994. """
  1995. code += """\
  1996. %(log_code)s
  1997. CheckGLError();
  1998. }
  1999. """
  2000. f.write(code % args)
  2001. def WriteGLES2ImplementationUnitTest(self, func, f):
  2002. """Overrriden from TypeHandler."""
  2003. code = """
  2004. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  2005. GLuint ids[2] = { 0, };
  2006. struct Cmds {
  2007. cmds::%(name)sImmediate gen;
  2008. GLuint data[2];
  2009. };
  2010. Cmds expected;
  2011. expected.gen.Init(std::size(ids), &ids[0]);
  2012. expected.data[0] = k%(types)sStartId;
  2013. expected.data[1] = k%(types)sStartId + 1;
  2014. gl_->%(name)s(std::size(ids), &ids[0]);
  2015. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  2016. EXPECT_EQ(k%(types)sStartId, ids[0]);
  2017. EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
  2018. }
  2019. """
  2020. f.write(code % {
  2021. 'prefix' : _prefix,
  2022. 'name': func.name,
  2023. 'types': func.GetInfo('resource_types'),
  2024. })
  2025. def WriteServiceUnitTest(self, func, f, *extras):
  2026. """Overrriden from TypeHandler."""
  2027. raise NotImplementedError("GENn functions are immediate")
  2028. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  2029. """Overrriden from TypeHandler."""
  2030. valid_test = """
  2031. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2032. EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
  2033. .WillOnce(SetArgPointee<1>(kNewServiceId));
  2034. cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
  2035. GLuint temp = kNewClientId;
  2036. SpecializedSetup<cmds::%(name)s, 0>(true);
  2037. cmd->Init(1, &temp);
  2038. EXPECT_EQ(error::kNoError,
  2039. ExecuteImmediateCmd(*cmd, sizeof(temp)));
  2040. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2041. EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != nullptr);
  2042. }
  2043. """
  2044. self.WriteValidUnitTest(func, f, valid_test, {
  2045. 'resource_name': func.GetInfo('resource_type'),
  2046. }, *extras)
  2047. duplicate_id_test = """
  2048. TEST_P(%(test_name)s, %(name)sDuplicateOrNullIds) {
  2049. EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
  2050. cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
  2051. GLuint temp[3] = {kNewClientId, kNewClientId + 1, kNewClientId};
  2052. SpecializedSetup<cmds::%(name)s, 1>(true);
  2053. cmd->Init(3, temp);
  2054. EXPECT_EQ(error::kInvalidArguments,
  2055. ExecuteImmediateCmd(*cmd, sizeof(temp)));
  2056. EXPECT_TRUE(Get%(resource_name)s(kNewClientId) == nullptr);
  2057. EXPECT_TRUE(Get%(resource_name)s(kNewClientId + 1) == nullptr);
  2058. GLuint null_id[2] = {kNewClientId, 0};
  2059. cmd->Init(2, null_id);
  2060. EXPECT_EQ(error::kInvalidArguments,
  2061. ExecuteImmediateCmd(*cmd, sizeof(temp)));
  2062. EXPECT_TRUE(Get%(resource_name)s(kNewClientId) == nullptr);
  2063. }
  2064. """
  2065. self.WriteValidUnitTest(func, f, duplicate_id_test, {
  2066. 'resource_name': func.GetInfo('resource_type'),
  2067. }, *extras)
  2068. invalid_test = """
  2069. TEST_P(%(test_name)s, %(name)sInvalidArgs) {
  2070. EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
  2071. cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
  2072. SpecializedSetup<cmds::%(name)s, 0>(false);
  2073. cmd->Init(1, &client_%(resource_name)s_id_);
  2074. EXPECT_EQ(error::kInvalidArguments,
  2075. ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
  2076. }
  2077. """
  2078. self.WriteValidUnitTest(func, f, invalid_test, {
  2079. 'resource_name': func.GetInfo('resource_type').lower(),
  2080. }, *extras)
  2081. def WriteImmediateCmdComputeSize(self, _func, f):
  2082. """Overrriden from TypeHandler."""
  2083. f.write(" static uint32_t ComputeDataSize(GLsizei _n) {\n")
  2084. f.write(
  2085. " return static_cast<uint32_t>(sizeof(GLuint) * _n); // NOLINT\n")
  2086. f.write(" }\n")
  2087. f.write("\n")
  2088. f.write(" static uint32_t ComputeSize(GLsizei _n) {\n")
  2089. f.write(" return static_cast<uint32_t>(\n")
  2090. f.write(" sizeof(ValueType) + ComputeDataSize(_n)); // NOLINT\n")
  2091. f.write(" }\n")
  2092. f.write("\n")
  2093. def WriteImmediateCmdSetHeader(self, _func, f):
  2094. """Overrriden from TypeHandler."""
  2095. f.write(" void SetHeader(GLsizei _n) {\n")
  2096. f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(_n));\n")
  2097. f.write(" }\n")
  2098. f.write("\n")
  2099. def WriteImmediateCmdInit(self, func, f):
  2100. """Overrriden from TypeHandler."""
  2101. last_arg = func.GetLastOriginalArg()
  2102. f.write(" void Init(%s, %s _%s) {\n" %
  2103. (func.MakeTypedCmdArgString("_"),
  2104. last_arg.type, last_arg.name))
  2105. f.write(" SetHeader(_n);\n")
  2106. args = func.GetCmdArgs()
  2107. for arg in args:
  2108. f.write(" %s = _%s;\n" % (arg.name, arg.name))
  2109. f.write(" memcpy(ImmediateDataAddress(this),\n")
  2110. f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
  2111. f.write(" }\n")
  2112. f.write("\n")
  2113. def WriteImmediateCmdSet(self, func, f):
  2114. """Overrriden from TypeHandler."""
  2115. last_arg = func.GetLastOriginalArg()
  2116. copy_args = func.MakeCmdArgString("_", False)
  2117. f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
  2118. (func.MakeTypedCmdArgString("_", True),
  2119. last_arg.type, last_arg.name))
  2120. f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
  2121. (copy_args, last_arg.name))
  2122. f.write(" const uint32_t size = ComputeSize(_n);\n")
  2123. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  2124. "cmd, size);\n")
  2125. f.write(" }\n")
  2126. f.write("\n")
  2127. def WriteImmediateCmdHelper(self, func, f):
  2128. """Overrriden from TypeHandler."""
  2129. code = """ void %(name)s(%(typed_args)s) {
  2130. const uint32_t size = %(lp)s::cmds::%(name)s::ComputeSize(n);
  2131. %(lp)s::cmds::%(name)s* c =
  2132. GetImmediateCmdSpaceTotalSize<%(lp)s::cmds::%(name)s>(size);
  2133. if (c) {
  2134. c->Init(%(args)s);
  2135. }
  2136. }
  2137. """
  2138. f.write(code % {
  2139. "lp" : _lower_prefix,
  2140. "name": func.name,
  2141. "typed_args": func.MakeTypedOriginalArgString(""),
  2142. "args": func.MakeOriginalArgString(""),
  2143. })
  2144. def WriteImmediateFormatTest(self, func, f):
  2145. """Overrriden from TypeHandler."""
  2146. f.write("TEST_F(%sFormatTest, %s) {\n" % (_prefix, func.name))
  2147. f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
  2148. f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
  2149. (func.name, func.name))
  2150. f.write(" void* next_cmd = cmd.Set(\n")
  2151. f.write(" &cmd, static_cast<GLsizei>(std::size(ids)), ids);\n")
  2152. f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
  2153. func.name)
  2154. f.write(" cmd.header.command);\n")
  2155. f.write(" EXPECT_EQ(sizeof(cmd) +\n")
  2156. f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
  2157. f.write(" cmd.header.size * 4u);\n")
  2158. f.write(" EXPECT_EQ(static_cast<GLsizei>(std::size(ids)), cmd.n);\n");
  2159. f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
  2160. f.write(" next_cmd, sizeof(cmd) +\n")
  2161. f.write(" RoundSizeToMultipleOfEntries(std::size(ids) * 4u));\n")
  2162. f.write(" EXPECT_EQ(0, memcmp(ids, ImmediateDataAddress(&cmd),\n")
  2163. f.write(" sizeof(ids)));\n")
  2164. f.write("}\n")
  2165. f.write("\n")
  2166. class CreateHandler(TypeHandler):
  2167. """Handler for glCreate___ type functions."""
  2168. def InitFunction(self, func):
  2169. """Overrriden from TypeHandler."""
  2170. func.AddCmdArg(Argument("client_id", 'uint32_t'))
  2171. def __GetResourceType(self, func):
  2172. if func.return_type == "GLsync":
  2173. return "Sync"
  2174. return func.name[6:] # Create*
  2175. def WriteServiceUnitTest(self, func, f, *extras):
  2176. """Overrriden from TypeHandler."""
  2177. valid_test = """
  2178. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2179. %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
  2180. .WillOnce(Return(%(const_service_id)s));
  2181. SpecializedSetup<cmds::%(name)s, 0>(true);
  2182. cmds::%(name)s cmd;
  2183. cmd.Init(%(args)s%(comma)skNewClientId);
  2184. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  2185. EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
  2186. if func.IsES3():
  2187. valid_test += """
  2188. %(return_type)s service_id = 0;
  2189. EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
  2190. EXPECT_EQ(%(const_service_id)s, service_id);
  2191. }
  2192. """
  2193. else:
  2194. valid_test += """
  2195. EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
  2196. }
  2197. """
  2198. comma = ""
  2199. cmd_arg_count = 0
  2200. for arg in func.GetOriginalArgs():
  2201. if not arg.IsConstant():
  2202. cmd_arg_count += 1
  2203. if cmd_arg_count:
  2204. comma = ", "
  2205. if func.return_type == 'GLsync':
  2206. id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
  2207. "<GLsync>(kNewServiceId);\n ")
  2208. const_service_id = "kNewServiceIdGLuint"
  2209. else:
  2210. id_type_cast = ""
  2211. const_service_id = "kNewServiceId"
  2212. self.WriteValidUnitTest(func, f, valid_test, {
  2213. 'comma': comma,
  2214. 'resource_type': self.__GetResourceType(func),
  2215. 'return_type': func.return_type,
  2216. 'id_type_cast': id_type_cast,
  2217. 'const_service_id': const_service_id,
  2218. }, *extras)
  2219. invalid_test = """
  2220. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  2221. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  2222. SpecializedSetup<cmds::%(name)s, 0>(false);
  2223. cmds::%(name)s cmd;
  2224. cmd.Init(%(args)s%(comma)skNewClientId);
  2225. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
  2226. }
  2227. """
  2228. self.WriteInvalidUnitTest(func, f, invalid_test, {
  2229. 'comma': comma,
  2230. }, *extras)
  2231. def WriteHandlerImplementation (self, func, f):
  2232. """Overrriden from TypeHandler."""
  2233. if func.IsES3():
  2234. code = """ uint32_t client_id = c.client_id;
  2235. %(return_type)s service_id = 0;
  2236. if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
  2237. return error::kInvalidArguments;
  2238. }
  2239. service_id = %(gl_func_name)s(%(gl_args)s);
  2240. if (service_id) {
  2241. group_->Add%(resource_name)sId(client_id, service_id);
  2242. }
  2243. """
  2244. else:
  2245. code = """ uint32_t client_id = c.client_id;
  2246. if (Get%(resource_name)s(client_id)) {
  2247. return error::kInvalidArguments;
  2248. }
  2249. %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
  2250. if (service_id) {
  2251. Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
  2252. }
  2253. """
  2254. f.write(code % {
  2255. 'resource_name': self.__GetResourceType(func),
  2256. 'return_type': func.return_type,
  2257. 'gl_func_name': func.GetGLFunctionName(),
  2258. 'gl_args': func.MakeOriginalArgString(""),
  2259. 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
  2260. def WriteGLES2Implementation(self, func, f):
  2261. """Overrriden from TypeHandler."""
  2262. f.write("%s %sImplementation::%s(%s) {\n" %
  2263. (func.return_type, _prefix, func.original_name,
  2264. func.MakeTypedOriginalArgString("")))
  2265. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  2266. func.WriteDestinationInitalizationValidation(f)
  2267. self.WriteClientGLCallLog(func, f)
  2268. for arg in func.GetOriginalArgs():
  2269. arg.WriteClientSideValidationCode(f, func)
  2270. f.write(" GLuint client_id;\n")
  2271. not_shared = func.GetInfo('not_shared')
  2272. if not_shared:
  2273. f.write('IdAllocator* id_allocator = GetIdAllocator(IdNamespaces::k%s);' %
  2274. func.GetInfo('resource_types'))
  2275. f.write('client_id = id_allocator->AllocateID();')
  2276. else:
  2277. if func.return_type == "GLsync":
  2278. f.write(
  2279. " GetIdHandler(SharedIdNamespaces::kSyncs)->\n")
  2280. else:
  2281. f.write(
  2282. " GetIdHandler(SharedIdNamespaces::kProgramsAndShaders)->\n")
  2283. f.write(" MakeIds(this, 0, 1, &client_id);\n")
  2284. f.write(" helper_->%s(%s);\n" %
  2285. (func.name, func.MakeCmdArgString("")))
  2286. f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
  2287. f.write(" CheckGLError();\n")
  2288. if func.return_type == "GLsync":
  2289. f.write(" return reinterpret_cast<GLsync>(client_id);\n")
  2290. else:
  2291. f.write(" return client_id;\n")
  2292. f.write("}\n")
  2293. f.write("\n")
  2294. def WritePassthroughServiceImplementation(self, func, f):
  2295. """Overrriden from TypeHandler."""
  2296. def WriteImmediateCmdInit(self, func, f):
  2297. """Overrriden from TypeHandler."""
  2298. def WriteImmediateCmdSet(self, func, f):
  2299. """Overrriden from TypeHandler."""
  2300. class DeleteHandler(TypeHandler):
  2301. """Handler for glDelete___ single resource type functions."""
  2302. def WriteServiceImplementation(self, func, f):
  2303. """Overrriden from TypeHandler."""
  2304. if func.IsES3() or func.IsES31():
  2305. TypeHandler.WriteServiceImplementation(self, func, f)
  2306. # HandleDeleteShader and HandleDeleteProgram are manually written.
  2307. def WriteGLES2Implementation(self, func, f):
  2308. """Overrriden from TypeHandler."""
  2309. f.write("%s %sImplementation::%s(%s) {\n" %
  2310. (func.return_type, _prefix, func.original_name,
  2311. func.MakeTypedOriginalArgString("")))
  2312. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  2313. func.WriteDestinationInitalizationValidation(f)
  2314. self.WriteClientGLCallLog(func, f)
  2315. for arg in func.GetOriginalArgs():
  2316. arg.WriteClientSideValidationCode(f, func)
  2317. f.write(
  2318. " if (%s == 0)\n return;" % func.GetOriginalArgs()[-1].name);
  2319. f.write(" %sHelper(%s);\n" %
  2320. (func.original_name, func.GetOriginalArgs()[-1].name))
  2321. f.write(" CheckGLError();\n")
  2322. f.write("}\n")
  2323. f.write("\n")
  2324. def WriteHandlerImplementation (self, func, f):
  2325. """Overrriden from TypeHandler."""
  2326. assert len(func.GetOriginalArgs()) == 1
  2327. arg = func.GetOriginalArgs()[0]
  2328. f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
  2329. def WriteImmediateCmdInit(self, func, f):
  2330. """Overrriden from TypeHandler."""
  2331. def WriteImmediateCmdSet(self, func, f):
  2332. """Overrriden from TypeHandler."""
  2333. class DELnHandler(TypeHandler):
  2334. """Handler for glDelete___ type functions."""
  2335. def WriteGetDataSizeCode(self, func, arg, f):
  2336. """Overrriden from TypeHandler."""
  2337. code = """ uint32_t %(data_size)s;
  2338. if (!base::CheckMul(n, sizeof(GLuint)).AssignIfValid(&%(data_size)s)) {
  2339. return error::kOutOfBounds;
  2340. }
  2341. """ % {'data_size': arg.GetReservedSizeId()}
  2342. f.write(code)
  2343. def WriteGLES2ImplementationUnitTest(self, func, f):
  2344. """Overrriden from TypeHandler."""
  2345. code = """
  2346. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  2347. GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
  2348. struct Cmds {
  2349. cmds::%(name)sImmediate del;
  2350. GLuint data[2];
  2351. };
  2352. Cmds expected;
  2353. expected.del.Init(std::size(ids), &ids[0]);
  2354. expected.data[0] = k%(types)sStartId;
  2355. expected.data[1] = k%(types)sStartId + 1;
  2356. gl_->%(name)s(std::size(ids), &ids[0]);
  2357. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  2358. }
  2359. """
  2360. f.write(code % {
  2361. 'prefix' : _prefix,
  2362. 'name': func.name,
  2363. 'types': func.GetInfo('resource_types'),
  2364. })
  2365. def WriteServiceUnitTest(self, func, f, *extras):
  2366. """Overrriden from TypeHandler."""
  2367. valid_test = """
  2368. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2369. EXPECT_CALL(
  2370. *gl_,
  2371. %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
  2372. .Times(1);
  2373. GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
  2374. SpecializedSetup<cmds::%(name)s, 0>(true);
  2375. cmds::%(name)s cmd;
  2376. cmd.Init(%(args)s);
  2377. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  2378. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2379. EXPECT_TRUE(
  2380. Get%(upper_resource_name)s(client_%(resource_name)s_id_) == nullptr);
  2381. }
  2382. """
  2383. self.WriteValidUnitTest(func, f, valid_test, {
  2384. 'resource_name': func.GetInfo('resource_type').lower(),
  2385. 'upper_resource_name': func.GetInfo('resource_type'),
  2386. }, *extras)
  2387. invalid_test = """
  2388. TEST_P(%(test_name)s, %(name)sInvalidArgs) {
  2389. GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
  2390. SpecializedSetup<cmds::%(name)s, 0>(false);
  2391. cmds::%(name)s cmd;
  2392. cmd.Init(%(args)s);
  2393. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  2394. }
  2395. """
  2396. self.WriteValidUnitTest(func, f, invalid_test, *extras)
  2397. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  2398. """Overrriden from TypeHandler."""
  2399. valid_test = """
  2400. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2401. EXPECT_CALL(
  2402. *gl_,
  2403. %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
  2404. .Times(1);
  2405. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
  2406. SpecializedSetup<cmds::%(name)s, 0>(true);
  2407. cmd.Init(1, &client_%(resource_name)s_id_);
  2408. EXPECT_EQ(error::kNoError,
  2409. ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
  2410. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2411. EXPECT_TRUE(
  2412. Get%(upper_resource_name)s(client_%(resource_name)s_id_) == nullptr);
  2413. }
  2414. """
  2415. self.WriteValidUnitTest(func, f, valid_test, {
  2416. 'resource_name': func.GetInfo('resource_type').lower(),
  2417. 'upper_resource_name': func.GetInfo('resource_type'),
  2418. }, *extras)
  2419. invalid_test = """
  2420. TEST_P(%(test_name)s, %(name)sInvalidArgs) {
  2421. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
  2422. SpecializedSetup<cmds::%(name)s, 0>(false);
  2423. GLuint temp = kInvalidClientId;
  2424. cmd.Init(1, &temp);
  2425. EXPECT_EQ(error::kNoError,
  2426. ExecuteImmediateCmd(cmd, sizeof(temp)));
  2427. }
  2428. """
  2429. self.WriteValidUnitTest(func, f, invalid_test, *extras)
  2430. def WriteHandlerImplementation (self, func, f):
  2431. """Overrriden from TypeHandler."""
  2432. f.write(" %sHelper(n, %s);\n" %
  2433. (func.name, func.GetLastOriginalArg().name))
  2434. def WriteImmediateHandlerImplementation (self, func, f):
  2435. """Overrriden from TypeHandler."""
  2436. f.write(" %sHelper(n, %s);\n" %
  2437. (func.original_name, func.GetLastOriginalArg().name))
  2438. def WriteGLES2Implementation(self, func, f):
  2439. """Overrriden from TypeHandler."""
  2440. impl_func = func.GetInfo('impl_func', True)
  2441. if impl_func:
  2442. args = {
  2443. 'return_type': func.return_type,
  2444. 'prefix' : _prefix,
  2445. 'name': func.original_name,
  2446. 'typed_args': func.MakeTypedOriginalArgString(""),
  2447. 'args': func.MakeOriginalArgString(""),
  2448. 'resource_type': func.GetInfo('resource_type').lower(),
  2449. 'count_name': func.GetOriginalArgs()[0].name,
  2450. }
  2451. f.write(
  2452. "%(return_type)s %(prefix)sImplementation::"
  2453. "%(name)s(%(typed_args)s) {\n" %
  2454. args)
  2455. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  2456. func.WriteDestinationInitalizationValidation(f)
  2457. self.WriteClientGLCallLog(func, f)
  2458. f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
  2459. for (GLsizei i = 0; i < n; ++i) {
  2460. GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
  2461. }
  2462. });
  2463. """ % func.GetOriginalArgs()[1].name)
  2464. f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
  2465. for (GLsizei i = 0; i < n; ++i) {
  2466. DCHECK(%s[i] != 0);
  2467. }
  2468. });
  2469. """ % func.GetOriginalArgs()[1].name)
  2470. for arg in func.GetOriginalArgs():
  2471. arg.WriteClientSideValidationCode(f, func)
  2472. code = """ %(name)sHelper(%(args)s);
  2473. CheckGLError();
  2474. }
  2475. """
  2476. f.write(code % args)
  2477. def WriteImmediateCmdComputeSize(self, _func, f):
  2478. """Overrriden from TypeHandler."""
  2479. f.write(" static uint32_t ComputeDataSize(GLsizei _n) {\n")
  2480. f.write(
  2481. " return static_cast<uint32_t>(sizeof(GLuint) * _n); // NOLINT\n")
  2482. f.write(" }\n")
  2483. f.write("\n")
  2484. f.write(" static uint32_t ComputeSize(GLsizei _n) {\n")
  2485. f.write(" return static_cast<uint32_t>(\n")
  2486. f.write(" sizeof(ValueType) + ComputeDataSize(_n)); // NOLINT\n")
  2487. f.write(" }\n")
  2488. f.write("\n")
  2489. def WriteImmediateCmdSetHeader(self, _func, f):
  2490. """Overrriden from TypeHandler."""
  2491. f.write(" void SetHeader(GLsizei _n) {\n")
  2492. f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(_n));\n")
  2493. f.write(" }\n")
  2494. f.write("\n")
  2495. def WriteImmediateCmdInit(self, func, f):
  2496. """Overrriden from TypeHandler."""
  2497. last_arg = func.GetLastOriginalArg()
  2498. f.write(" void Init(%s, %s _%s) {\n" %
  2499. (func.MakeTypedCmdArgString("_"),
  2500. last_arg.type, last_arg.name))
  2501. f.write(" SetHeader(_n);\n")
  2502. args = func.GetCmdArgs()
  2503. for arg in args:
  2504. f.write(" %s = _%s;\n" % (arg.name, arg.name))
  2505. f.write(" memcpy(ImmediateDataAddress(this),\n")
  2506. f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
  2507. f.write(" }\n")
  2508. f.write("\n")
  2509. def WriteImmediateCmdSet(self, func, f):
  2510. """Overrriden from TypeHandler."""
  2511. last_arg = func.GetLastOriginalArg()
  2512. copy_args = func.MakeCmdArgString("_", False)
  2513. f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
  2514. (func.MakeTypedCmdArgString("_", True),
  2515. last_arg.type, last_arg.name))
  2516. f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
  2517. (copy_args, last_arg.name))
  2518. f.write(" const uint32_t size = ComputeSize(_n);\n")
  2519. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  2520. "cmd, size);\n")
  2521. f.write(" }\n")
  2522. f.write("\n")
  2523. def WriteImmediateCmdHelper(self, func, f):
  2524. """Overrriden from TypeHandler."""
  2525. code = """ void %(name)s(%(typed_args)s) {
  2526. const uint32_t size = %(lp)s::cmds::%(name)s::ComputeSize(n);
  2527. %(lp)s::cmds::%(name)s* c =
  2528. GetImmediateCmdSpaceTotalSize<%(lp)s::cmds::%(name)s>(size);
  2529. if (c) {
  2530. c->Init(%(args)s);
  2531. }
  2532. }
  2533. """
  2534. f.write(code % {
  2535. "lp" : _lower_prefix,
  2536. "name": func.name,
  2537. "typed_args": func.MakeTypedOriginalArgString(""),
  2538. "args": func.MakeOriginalArgString(""),
  2539. })
  2540. def WriteImmediateFormatTest(self, func, f):
  2541. """Overrriden from TypeHandler."""
  2542. f.write("TEST_F(%sFormatTest, %s) {\n" % (_prefix, func.name))
  2543. f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
  2544. f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
  2545. (func.name, func.name))
  2546. f.write(" void* next_cmd = cmd.Set(\n")
  2547. f.write(" &cmd, static_cast<GLsizei>(std::size(ids)), ids);\n")
  2548. f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
  2549. func.name)
  2550. f.write(" cmd.header.command);\n")
  2551. f.write(" EXPECT_EQ(sizeof(cmd) +\n")
  2552. f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
  2553. f.write(" cmd.header.size * 4u);\n")
  2554. f.write(" EXPECT_EQ(static_cast<GLsizei>(std::size(ids)), cmd.n);\n");
  2555. f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
  2556. f.write(" next_cmd, sizeof(cmd) +\n")
  2557. f.write(" RoundSizeToMultipleOfEntries(std::size(ids) * 4u));\n")
  2558. f.write(" EXPECT_EQ(0, memcmp(ids, ImmediateDataAddress(&cmd),\n")
  2559. f.write(" sizeof(ids)));\n")
  2560. f.write("}\n")
  2561. f.write("\n")
  2562. class GETnHandler(TypeHandler):
  2563. """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
  2564. def InitFunction(self, func):
  2565. """Overrriden from TypeHandler."""
  2566. TypeHandler.InitFunction(self, func)
  2567. if func.name == 'GetSynciv':
  2568. return
  2569. arg_insert_point = len(func.passthrough_service_doer_args) - 1;
  2570. func.passthrough_service_doer_args.insert(
  2571. arg_insert_point, Argument('length', 'GLsizei*'))
  2572. func.passthrough_service_doer_args.insert(
  2573. arg_insert_point, Argument('bufsize', 'GLsizei'))
  2574. def NeedsDataTransferFunction(self, func):
  2575. """Overriden from TypeHandler."""
  2576. return False
  2577. def WriteServiceImplementation(self, func, f):
  2578. """Overrriden from TypeHandler."""
  2579. self.WriteServiceHandlerFunctionHeader(func, f)
  2580. if func.IsES31():
  2581. return
  2582. last_arg = func.GetLastOriginalArg()
  2583. # All except shm_id and shm_offset.
  2584. all_but_last_args = func.GetCmdArgs()[:-2]
  2585. for arg in all_but_last_args:
  2586. arg.WriteGetCode(f)
  2587. code = """ typedef cmds::%(func_name)s::Result Result;
  2588. GLsizei num_values = 0;
  2589. if (!GetNumValuesReturnedForGLGet(pname, &num_values)) {
  2590. LOCAL_SET_GL_ERROR_INVALID_ENUM(":%(func_name)s", pname, "pname");
  2591. return error::kNoError;
  2592. }
  2593. uint32_t checked_size = 0;
  2594. if (!Result::ComputeSize(num_values).AssignIfValid(&checked_size)) {
  2595. return error::kOutOfBounds;
  2596. }
  2597. Result* result = GetSharedMemoryAs<Result*>(
  2598. c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
  2599. checked_size);
  2600. %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : nullptr;
  2601. """
  2602. f.write(code % {
  2603. 'last_arg_type': last_arg.type,
  2604. 'last_arg_name': last_arg.name,
  2605. 'func_name': func.name,
  2606. })
  2607. func.WriteHandlerValidation(f)
  2608. code = """ // Check that the client initialized the result.
  2609. if (result->size != 0) {
  2610. return error::kInvalidArguments;
  2611. }
  2612. """
  2613. shadowed = func.GetInfo('shadowed')
  2614. if not shadowed:
  2615. f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
  2616. f.write(code)
  2617. func.WriteHandlerImplementation(f)
  2618. if shadowed:
  2619. code = """ result->SetNumResults(num_values);
  2620. return error::kNoError;
  2621. }
  2622. """
  2623. else:
  2624. code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
  2625. if (error == GL_NO_ERROR) {
  2626. result->SetNumResults(num_values);
  2627. }
  2628. return error::kNoError;
  2629. }
  2630. """
  2631. f.write(code % {'func_name': func.name})
  2632. def WritePassthroughServiceImplementation(self, func, f):
  2633. """Overrriden from TypeHandler."""
  2634. self.WritePassthroughServiceFunctionHeader(func, f)
  2635. last_arg = func.GetLastOriginalArg()
  2636. # All except shm_id and shm_offset.
  2637. all_but_last_args = func.GetCmdArgs()[:-2]
  2638. for arg in all_but_last_args:
  2639. arg.WriteGetCode(f)
  2640. code = """ unsigned int buffer_size = 0;
  2641. typedef cmds::%(func_name)s::Result Result;
  2642. Result* result = GetSharedMemoryAndSizeAs<Result*>(
  2643. c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
  2644. sizeof(Result), &buffer_size);
  2645. %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : nullptr;
  2646. if (%(last_arg_name)s == nullptr) {
  2647. return error::kOutOfBounds;
  2648. }
  2649. GLsizei bufsize = Result::ComputeMaxResults(buffer_size);
  2650. GLsizei written_values = 0;
  2651. GLsizei* length = &written_values;
  2652. """
  2653. f.write(code % {
  2654. 'last_arg_type': last_arg.type,
  2655. 'last_arg_name': last_arg.name,
  2656. 'func_name': func.name,
  2657. })
  2658. self.WritePassthroughServiceFunctionDoerCall(func, f)
  2659. code = """ if (written_values > bufsize) {
  2660. return error::kOutOfBounds;
  2661. }
  2662. result->SetNumResults(written_values);
  2663. return error::kNoError;
  2664. }
  2665. """
  2666. f.write(code % {'func_name': func.name})
  2667. def WriteGLES2Implementation(self, func, f):
  2668. """Overrriden from TypeHandler."""
  2669. impl_func = func.GetInfo('impl_func', True)
  2670. if impl_func:
  2671. f.write("%s %sImplementation::%s(%s) {\n" %
  2672. (func.return_type, _prefix, func.original_name,
  2673. func.MakeTypedOriginalArgString("")))
  2674. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  2675. func.WriteDestinationInitalizationValidation(f)
  2676. self.WriteClientGLCallLog(func, f)
  2677. for arg in func.GetOriginalArgs():
  2678. arg.WriteClientSideValidationCode(f, func)
  2679. all_but_last_args = func.GetOriginalArgs()[:-1]
  2680. args = []
  2681. has_length_arg = False
  2682. for arg in all_but_last_args:
  2683. if arg.type == 'GLsync':
  2684. args.append('ToGLuint(%s)' % arg.name)
  2685. elif arg.name.endswith('size') and arg.type == 'GLsizei':
  2686. continue
  2687. elif arg.name == 'length':
  2688. has_length_arg = True
  2689. continue
  2690. else:
  2691. args.append(arg.name)
  2692. arg_string = ", ".join(args)
  2693. all_arg_string = (
  2694. ", ".join([
  2695. "%s" % arg.name
  2696. for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
  2697. self.WriteTraceEvent(func, f)
  2698. code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
  2699. return;
  2700. }
  2701. typedef cmds::%(func_name)s::Result Result;
  2702. ScopedResultPtr<Result> result = GetResultAs<Result>();
  2703. if (!result) {
  2704. return;
  2705. }
  2706. result->SetNumResults(0);
  2707. helper_->%(func_name)s(%(arg_string)s,
  2708. GetResultShmId(), result.offset());
  2709. WaitForCmd();
  2710. result->CopyResult(%(last_arg_name)s);
  2711. GPU_CLIENT_LOG_CODE_BLOCK({
  2712. for (int32_t i = 0; i < result->GetNumResults(); ++i) {
  2713. GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
  2714. }
  2715. });"""
  2716. if has_length_arg:
  2717. code += """
  2718. if (length) {
  2719. *length = result->GetNumResults();
  2720. }"""
  2721. code += """
  2722. CheckGLError();
  2723. }
  2724. """
  2725. f.write(code % {
  2726. 'func_name': func.name,
  2727. 'arg_string': arg_string,
  2728. 'all_arg_string': all_arg_string,
  2729. 'last_arg_name': func.GetLastOriginalArg().name,
  2730. })
  2731. def WriteGLES2ImplementationUnitTest(self, func, f):
  2732. """Writes the GLES2 Implemention unit test."""
  2733. code = """
  2734. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  2735. struct Cmds {
  2736. cmds::%(name)s cmd;
  2737. };
  2738. typedef cmds::%(name)s::Result::Type ResultType;
  2739. ResultType result = 0;
  2740. Cmds expected;
  2741. ExpectedMemoryInfo result1 = GetExpectedResultMemory(
  2742. sizeof(uint32_t) + sizeof(ResultType));
  2743. expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
  2744. EXPECT_CALL(*command_buffer(), OnFlush())
  2745. .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
  2746. .RetiresOnSaturation();
  2747. gl_->%(name)s(%(args)s, &result);
  2748. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  2749. EXPECT_EQ(static_cast<ResultType>(1), result);
  2750. }
  2751. """
  2752. first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
  2753. if not first_cmd_arg:
  2754. return
  2755. first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
  2756. func)
  2757. cmd_arg_strings = [first_cmd_arg]
  2758. for arg in func.GetCmdArgs()[1:-2]:
  2759. cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
  2760. gl_arg_strings = [first_gl_arg]
  2761. for arg in func.GetOriginalArgs()[1:-1]:
  2762. gl_arg_strings.append(arg.GetValidClientSideArg(func))
  2763. f.write(code % {
  2764. 'prefix' : _prefix,
  2765. 'name': func.name,
  2766. 'args': ", ".join(gl_arg_strings),
  2767. 'cmd_args': ", ".join(cmd_arg_strings),
  2768. })
  2769. def WriteServiceUnitTest(self, func, f, *extras):
  2770. """Overrriden from TypeHandler."""
  2771. valid_test = """
  2772. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2773. EXPECT_CALL(*gl_, GetError())
  2774. .WillRepeatedly(Return(GL_NO_ERROR));
  2775. SpecializedSetup<cmds::%(name)s, 0>(true);
  2776. typedef cmds::%(name)s::Result Result;
  2777. Result* result = static_cast<Result*>(shared_memory_address_);
  2778. EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
  2779. result->size = 0;
  2780. cmds::%(name)s cmd;
  2781. cmd.Init(%(cmd_args)s);
  2782. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  2783. EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
  2784. %(valid_pname)s),
  2785. result->GetNumResults());
  2786. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2787. }
  2788. """
  2789. gl_arg_strings = []
  2790. cmd_arg_strings = []
  2791. valid_pname = ''
  2792. for arg in func.GetOriginalArgs()[:-1]:
  2793. if arg.name == 'length':
  2794. gl_arg_value = 'nullptr'
  2795. elif arg.name.endswith('size'):
  2796. gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
  2797. valid_pname)
  2798. elif arg.type == 'GLsync':
  2799. gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
  2800. else:
  2801. gl_arg_value = arg.GetValidGLArg(func)
  2802. gl_arg_strings.append(gl_arg_value)
  2803. if arg.name == 'pname':
  2804. valid_pname = gl_arg_value
  2805. if arg.name.endswith('size') or arg.name == 'length':
  2806. continue
  2807. if arg.type == 'GLsync':
  2808. arg_value = 'client_sync_id_'
  2809. else:
  2810. arg_value = arg.GetValidArg(func)
  2811. cmd_arg_strings.append(arg_value)
  2812. if func.GetInfo('gl_test_func') == 'glGetIntegerv':
  2813. gl_arg_strings.append("_")
  2814. else:
  2815. gl_arg_strings.append("result->GetData()")
  2816. cmd_arg_strings.append("shared_memory_id_")
  2817. cmd_arg_strings.append("shared_memory_offset_")
  2818. self.WriteValidUnitTest(func, f, valid_test, {
  2819. 'local_gl_args': ", ".join(gl_arg_strings),
  2820. 'cmd_args': ", ".join(cmd_arg_strings),
  2821. 'valid_pname': valid_pname,
  2822. }, *extras)
  2823. if not func.IsES3():
  2824. invalid_test = """
  2825. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  2826. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  2827. SpecializedSetup<cmds::%(name)s, 0>(false);
  2828. cmds::%(name)s::Result* result =
  2829. static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
  2830. result->size = 0;
  2831. cmds::%(name)s cmd;
  2832. cmd.Init(%(args)s);
  2833. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
  2834. EXPECT_EQ(0u, result->size);%(gl_error_test)s
  2835. }
  2836. """
  2837. self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
  2838. def WriteImmediateCmdInit(self, func, f):
  2839. """Overrriden from TypeHandler."""
  2840. def WriteImmediateCmdSet(self, func, f):
  2841. """Overrriden from TypeHandler."""
  2842. class ArrayArgTypeHandler(TypeHandler):
  2843. """Base class for type handlers that handle args that are arrays"""
  2844. def GetArrayType(self, func):
  2845. """Returns the type of the element in the element array being PUT to."""
  2846. for arg in func.GetOriginalArgs():
  2847. if arg.IsPointer():
  2848. element_type = arg.GetPointedType()
  2849. return element_type
  2850. # Special case: array type handler is used for a function that is forwarded
  2851. # to the actual array type implementation
  2852. element_type = func.GetOriginalArgs()[-1].type
  2853. assert all(arg.type == element_type \
  2854. for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
  2855. return element_type
  2856. def GetArrayCount(self, func):
  2857. """Returns the count of the elements in the array being PUT to."""
  2858. return func.GetInfo('count')
  2859. def WriteImmediateCmdInit(self, func, f):
  2860. """Overrriden from TypeHandler."""
  2861. def WriteImmediateCmdSet(self, func, f):
  2862. """Overrriden from TypeHandler."""
  2863. class PUTHandler(ArrayArgTypeHandler):
  2864. """Handler for glTexParameter_v, glVertexAttrib_v functions."""
  2865. def WriteServiceUnitTest(self, func, f, *extras):
  2866. """Writes the service unit test for a command."""
  2867. expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
  2868. if func.GetInfo("first_element_only"):
  2869. gl_arg_strings = [
  2870. arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
  2871. ]
  2872. gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
  2873. expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
  2874. ", ".join(gl_arg_strings))
  2875. valid_test = """
  2876. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2877. SpecializedSetup<cmds::%(name)s, 0>(true);
  2878. cmds::%(name)s cmd;
  2879. cmd.Init(%(args)s);
  2880. GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
  2881. %(expected_call)s
  2882. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  2883. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2884. }
  2885. """
  2886. extra = {
  2887. 'data_type': self.GetArrayType(func),
  2888. 'data_value': func.GetInfo('data_value') or '0',
  2889. 'expected_call': expected_call,
  2890. }
  2891. self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
  2892. invalid_test = """
  2893. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  2894. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  2895. SpecializedSetup<cmds::%(name)s, 0>(false);
  2896. cmds::%(name)s cmd;
  2897. cmd.Init(%(args)s);
  2898. GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
  2899. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
  2900. }
  2901. """
  2902. self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
  2903. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  2904. """Writes the service unit test for a command."""
  2905. valid_test = """
  2906. TEST_P(%(test_name)s, %(name)sValidArgs) {
  2907. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
  2908. SpecializedSetup<cmds::%(name)s, 0>(true);
  2909. %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
  2910. cmd.Init(%(gl_client_args)s, &temp[0]);
  2911. EXPECT_CALL(
  2912. *gl_,
  2913. %(gl_func_name)s(%(gl_args)s, %(expectation)s));
  2914. EXPECT_EQ(error::kNoError,
  2915. ExecuteImmediateCmd(cmd, sizeof(temp)));
  2916. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  2917. }
  2918. """
  2919. gl_client_arg_strings = [
  2920. arg.GetValidArg(func) for arg in func.GetOriginalArgs()[0:-1]
  2921. ]
  2922. gl_arg_strings = [
  2923. arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
  2924. ]
  2925. gl_any_strings = ["_"] * len(gl_arg_strings)
  2926. data_count = self.GetArrayCount(func)
  2927. if func.GetInfo('first_element_only'):
  2928. expectation = "temp[0]"
  2929. else:
  2930. expectation = "PointsToArray(temp, %s)" % data_count
  2931. extra = {
  2932. 'expectation': expectation,
  2933. 'data_type': self.GetArrayType(func),
  2934. 'data_count': data_count,
  2935. 'data_value': func.GetInfo('data_value') or '0',
  2936. 'gl_client_args': ", ".join(gl_client_arg_strings),
  2937. 'gl_args': ", ".join(gl_arg_strings),
  2938. 'gl_any_args': ", ".join(gl_any_strings),
  2939. }
  2940. self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
  2941. invalid_test = """
  2942. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  2943. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
  2944. if func.IsES3():
  2945. invalid_test += """
  2946. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
  2947. """
  2948. else:
  2949. invalid_test += """
  2950. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
  2951. """
  2952. invalid_test += """
  2953. SpecializedSetup<cmds::%(name)s, 0>(false);
  2954. %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
  2955. cmd.Init(%(all_but_last_args)s, &temp[0]);
  2956. EXPECT_EQ(error::%(parse_result)s,
  2957. ExecuteImmediateCmd(cmd, sizeof(temp)));
  2958. %(gl_error_test)s
  2959. }
  2960. """
  2961. self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
  2962. def WriteGetDataSizeCode(self, func, arg, f):
  2963. """Overrriden from TypeHandler."""
  2964. code = (""" uint32_t %(data_size)s;
  2965. if (!%(namespace)sGLES2Util::""" +
  2966. """ComputeDataSize<%(arrayType)s, %(arrayCount)d>(1, &%(data_size)s)) {
  2967. return error::kOutOfBounds;
  2968. }
  2969. """)
  2970. f.write(code % {'data_size': arg.GetReservedSizeId(),
  2971. 'namespace': _Namespace(),
  2972. 'arrayType': self.GetArrayType(func),
  2973. 'arrayCount': self.GetArrayCount(func)})
  2974. if func.IsImmediate():
  2975. f.write(" if (%s > immediate_data_size) {\n" % arg.GetReservedSizeId())
  2976. f.write(" return error::kOutOfBounds;\n")
  2977. f.write(" }\n")
  2978. def __NeedsToCalcDataCount(self, func):
  2979. use_count_func = func.GetInfo('use_count_func')
  2980. return use_count_func not in (None, False)
  2981. def WriteGLES2Implementation(self, func, f):
  2982. """Overrriden from TypeHandler."""
  2983. impl_func = func.GetInfo('impl_func')
  2984. if impl_func not in (None, True):
  2985. return;
  2986. f.write("%s %sImplementation::%s(%s) {\n" %
  2987. (func.return_type, _prefix, func.original_name,
  2988. func.MakeTypedOriginalArgString("")))
  2989. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  2990. func.WriteDestinationInitalizationValidation(f)
  2991. self.WriteClientGLCallLog(func, f)
  2992. if self.__NeedsToCalcDataCount(func):
  2993. f.write(" uint32_t count = %sGLES2Util::Calc%sDataCount(%s);\n" %
  2994. (_Namespace(), func.name, func.GetOriginalArgs()[0].name))
  2995. f.write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
  2996. f.write(" if (count == 0) {\n")
  2997. f.write(" SetGLErrorInvalidEnum(\"%s\", %s, \"%s\");\n" %
  2998. (func.prefixed_name, func.GetOriginalArgs()[0].name,
  2999. func.GetOriginalArgs()[0].name))
  3000. f.write(" return;\n")
  3001. f.write(" }\n")
  3002. else:
  3003. f.write(" uint32_t count = %d;" % self.GetArrayCount(func))
  3004. f.write(" for (uint32_t ii = 0; ii < count; ++ii)\n")
  3005. f.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
  3006. func.GetLastOriginalArg().name)
  3007. for arg in func.GetOriginalArgs():
  3008. arg.WriteClientSideValidationCode(f, func)
  3009. f.write(" helper_->%sImmediate(%s);\n" %
  3010. (func.name, func.MakeOriginalArgString("")))
  3011. f.write(" CheckGLError();\n")
  3012. f.write("}\n")
  3013. f.write("\n")
  3014. def WriteGLES2ImplementationUnitTest(self, func, f):
  3015. """Writes the GLES2 Implemention unit test."""
  3016. client_test = func.GetInfo('client_test', True)
  3017. if not client_test:
  3018. return;
  3019. code = """
  3020. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  3021. %(type)s data[%(count)d] = {0};
  3022. struct Cmds {
  3023. cmds::%(name)sImmediate cmd;
  3024. %(type)s data[%(count)d];
  3025. };
  3026. for (int jj = 0; jj < %(count)d; ++jj) {
  3027. data[jj] = static_cast<%(type)s>(jj);
  3028. }
  3029. Cmds expected;
  3030. expected.cmd.Init(%(cmd_args)s, &data[0]);
  3031. gl_->%(name)s(%(args)s, &data[0]);
  3032. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  3033. }
  3034. """
  3035. cmd_arg_strings = [
  3036. arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
  3037. ]
  3038. gl_arg_strings = [
  3039. arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
  3040. ]
  3041. f.write(code % {
  3042. 'prefix' : _prefix,
  3043. 'name': func.name,
  3044. 'type': self.GetArrayType(func),
  3045. 'count': self.GetArrayCount(func),
  3046. 'args': ", ".join(gl_arg_strings),
  3047. 'cmd_args': ", ".join(cmd_arg_strings),
  3048. })
  3049. def WriteImmediateCmdComputeSize(self, func, f):
  3050. """Overrriden from TypeHandler."""
  3051. f.write(" static uint32_t ComputeDataSize() {\n")
  3052. f.write(" return static_cast<uint32_t>(\n")
  3053. f.write(" sizeof(%s) * %d);\n" %
  3054. (self.GetArrayType(func), self.GetArrayCount(func)))
  3055. f.write(" }\n")
  3056. f.write("\n")
  3057. if self.__NeedsToCalcDataCount(func):
  3058. f.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
  3059. (func.GetOriginalArgs()[0].type,
  3060. func.GetOriginalArgs()[0].name))
  3061. f.write(" return static_cast<uint32_t>(\n")
  3062. f.write(" sizeof(%s) * %sGLES2Util::Calc%sDataCount(%s));\n" %
  3063. (self.GetArrayType(func), _Namespace(), func.original_name,
  3064. func.GetOriginalArgs()[0].name))
  3065. f.write(" }\n")
  3066. f.write("\n")
  3067. f.write(" static uint32_t ComputeSize() {\n")
  3068. f.write(" return static_cast<uint32_t>(\n")
  3069. f.write(
  3070. " sizeof(ValueType) + ComputeDataSize());\n")
  3071. f.write(" }\n")
  3072. f.write("\n")
  3073. def WriteImmediateCmdSetHeader(self, _func, f):
  3074. """Overrriden from TypeHandler."""
  3075. f.write(" void SetHeader() {\n")
  3076. f.write(
  3077. " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
  3078. f.write(" }\n")
  3079. f.write("\n")
  3080. def WriteImmediateCmdInit(self, func, f):
  3081. """Overrriden from TypeHandler."""
  3082. last_arg = func.GetLastOriginalArg()
  3083. f.write(" void Init(%s, %s _%s) {\n" %
  3084. (func.MakeTypedCmdArgString("_"),
  3085. last_arg.type, last_arg.name))
  3086. f.write(" SetHeader();\n")
  3087. args = func.GetCmdArgs()
  3088. for arg in args:
  3089. arg.WriteSetCode(f, 4, "_%s" % arg.name)
  3090. f.write(" memcpy(ImmediateDataAddress(this),\n")
  3091. if self.__NeedsToCalcDataCount(func):
  3092. f.write(" _%s, ComputeEffectiveDataSize(%s));" %
  3093. (last_arg.name, func.GetOriginalArgs()[0].name))
  3094. f.write("""
  3095. DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
  3096. char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
  3097. ComputeEffectiveDataSize(%(arg)s);
  3098. memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
  3099. """ % { 'arg': func.GetOriginalArgs()[0].name, })
  3100. else:
  3101. f.write(" _%s, ComputeDataSize());\n" % last_arg.name)
  3102. f.write(" }\n")
  3103. f.write("\n")
  3104. def WriteImmediateCmdSet(self, func, f):
  3105. """Overrriden from TypeHandler."""
  3106. last_arg = func.GetLastOriginalArg()
  3107. copy_args = func.MakeCmdArgString("_", False)
  3108. f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
  3109. (func.MakeTypedCmdArgString("_", True),
  3110. last_arg.type, last_arg.name))
  3111. f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
  3112. (copy_args, last_arg.name))
  3113. f.write(" const uint32_t size = ComputeSize();\n")
  3114. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  3115. "cmd, size);\n")
  3116. f.write(" }\n")
  3117. f.write("\n")
  3118. def WriteImmediateCmdHelper(self, func, f):
  3119. """Overrriden from TypeHandler."""
  3120. code = """ void %(name)s(%(typed_args)s) {
  3121. const uint32_t size = %(lp)s::cmds::%(name)s::ComputeSize();
  3122. %(lp)s::cmds::%(name)s* c =
  3123. GetImmediateCmdSpaceTotalSize<%(lp)s::cmds::%(name)s>(size);
  3124. if (c) {
  3125. c->Init(%(args)s);
  3126. }
  3127. }
  3128. """
  3129. f.write(code % {
  3130. "lp" : _lower_prefix,
  3131. "name": func.name,
  3132. "typed_args": func.MakeTypedOriginalArgString(""),
  3133. "args": func.MakeOriginalArgString(""),
  3134. })
  3135. def WriteImmediateFormatTest(self, func, f):
  3136. """Overrriden from TypeHandler."""
  3137. f.write("TEST_F(%sFormatTest, %s) {\n" % (_prefix, func.name))
  3138. f.write(" const int kSomeBaseValueToTestWith = 51;\n")
  3139. f.write(" static %s data[] = {\n" % self.GetArrayType(func))
  3140. for v in range(0, self.GetArrayCount(func)):
  3141. f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
  3142. (self.GetArrayType(func), v))
  3143. f.write(" };\n")
  3144. f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
  3145. (func.name, func.name))
  3146. f.write(" void* next_cmd = cmd.Set(\n")
  3147. f.write(" &cmd")
  3148. args = func.GetCmdArgs()
  3149. for value, arg in enumerate(args):
  3150. f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
  3151. f.write(",\n data);\n")
  3152. args = func.GetCmdArgs()
  3153. f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
  3154. % func.name)
  3155. f.write(" cmd.header.command);\n")
  3156. f.write(" EXPECT_EQ(sizeof(cmd) +\n")
  3157. f.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
  3158. f.write(" cmd.header.size * 4u);\n")
  3159. for value, arg in enumerate(args):
  3160. f.write(" EXPECT_EQ(static_cast<%s>(%d), %s);\n" %
  3161. (arg.type, value + 11, arg.GetArgAccessor('cmd')))
  3162. f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
  3163. f.write(" next_cmd, sizeof(cmd) +\n")
  3164. f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
  3165. # TODO: Check that data was inserted
  3166. f.write("}\n")
  3167. f.write("\n")
  3168. class PUTnHandler(ArrayArgTypeHandler):
  3169. """Handler for PUTn 'glUniform__v' type functions."""
  3170. def WriteServiceUnitTest(self, func, f, *extras):
  3171. """Overridden from TypeHandler."""
  3172. ArrayArgTypeHandler.WriteServiceUnitTest(self, func, f, *extras)
  3173. valid_test = """
  3174. TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
  3175. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  3176. SpecializedSetup<cmds::%(name)s, 0>(true);
  3177. cmds::%(name)s cmd;
  3178. cmd.Init(%(args)s);
  3179. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  3180. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  3181. }
  3182. """
  3183. gl_arg_strings = []
  3184. arg_strings = []
  3185. for count, arg in enumerate(func.GetOriginalArgs()):
  3186. # hardcoded to match unit tests.
  3187. if count == 0:
  3188. # the location of the second element of the 2nd uniform.
  3189. # defined in GLES2DecoderBase::SetupShaderForUniform
  3190. gl_arg_strings.append("3")
  3191. arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
  3192. elif count == 1:
  3193. # the number of elements that gl will be called with.
  3194. gl_arg_strings.append("3")
  3195. # the number of elements requested in the command.
  3196. arg_strings.append("5")
  3197. else:
  3198. gl_arg_strings.append(arg.GetValidGLArg(func))
  3199. if not arg.IsConstant():
  3200. arg_strings.append(arg.GetValidArg(func))
  3201. extra = {
  3202. 'gl_args': ", ".join(gl_arg_strings),
  3203. 'args': ", ".join(arg_strings),
  3204. }
  3205. self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
  3206. def WriteImmediateServiceUnitTest(self, func, f, *extras):
  3207. """Overridden from TypeHandler."""
  3208. valid_test = """
  3209. TEST_P(%(test_name)s, %(name)sValidArgs) {
  3210. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
  3211. SpecializedSetup<cmds::%(name)s, 0>(true);
  3212. %(data_type)s temp[%(data_count)s * 2] = { 0, };
  3213. EXPECT_CALL(
  3214. *gl_,
  3215. %(gl_func_name)s(%(gl_args)s,
  3216. PointsToArray(temp, %(data_count)s)));
  3217. cmd.Init(%(args)s, &temp[0]);
  3218. EXPECT_EQ(error::kNoError,
  3219. ExecuteImmediateCmd(cmd, sizeof(temp)));
  3220. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  3221. }
  3222. """
  3223. gl_arg_strings = []
  3224. gl_any_strings = []
  3225. arg_strings = []
  3226. for arg in func.GetOriginalArgs()[0:-1]:
  3227. gl_arg_strings.append(arg.GetValidGLArg(func))
  3228. gl_any_strings.append("_")
  3229. if not arg.IsConstant():
  3230. arg_strings.append(arg.GetValidArg(func))
  3231. extra = {
  3232. 'data_type': self.GetArrayType(func),
  3233. 'data_count': self.GetArrayCount(func),
  3234. 'args': ", ".join(arg_strings),
  3235. 'gl_args': ", ".join(gl_arg_strings),
  3236. 'gl_any_args': ", ".join(gl_any_strings),
  3237. }
  3238. self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
  3239. invalid_test = """
  3240. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  3241. cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
  3242. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
  3243. SpecializedSetup<cmds::%(name)s, 0>(false);
  3244. %(data_type)s temp[%(data_count)s * 2] = { 0, };
  3245. cmd.Init(%(all_but_last_args)s, &temp[0]);
  3246. EXPECT_EQ(error::%(parse_result)s,
  3247. ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
  3248. }
  3249. """
  3250. self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
  3251. def WriteGetDataSizeCode(self, func, arg, f):
  3252. """Overrriden from TypeHandler."""
  3253. code = (""" uint32_t %(data_size)s = 0;
  3254. if (count >= 0 && !%(namespace)sGLES2Util::""" +
  3255. """ComputeDataSize<%(arrayType)s, %(arrayCount)d>(count, &%(data_size)s)) {
  3256. return error::kOutOfBounds;
  3257. }
  3258. """)
  3259. f.write(code % {'data_size': arg.GetReservedSizeId(),
  3260. 'namespace': _Namespace(),
  3261. 'arrayType': self.GetArrayType(func),
  3262. 'arrayCount': self.GetArrayCount(func)})
  3263. if func.IsImmediate():
  3264. f.write(" if (%s > immediate_data_size) {\n" % arg.GetReservedSizeId())
  3265. f.write(" return error::kOutOfBounds;\n")
  3266. f.write(" }\n")
  3267. def WriteGLES2Implementation(self, func, f):
  3268. """Overrriden from TypeHandler."""
  3269. impl_func = func.GetInfo('impl_func')
  3270. if impl_func not in (None, True):
  3271. return;
  3272. f.write("%s %sImplementation::%s(%s) {\n" %
  3273. (func.return_type, _prefix, func.original_name,
  3274. func.MakeTypedOriginalArgString("")))
  3275. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  3276. func.WriteDestinationInitalizationValidation(f)
  3277. self.WriteClientGLCallLog(func, f)
  3278. last_pointer_name = func.GetLastOriginalPointerArg().name
  3279. f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
  3280. for (GLsizei i = 0; i < count; ++i) {
  3281. """)
  3282. values_str = ' << ", " << '.join(
  3283. ["%s[%d + i * %d]" % (
  3284. last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
  3285. 0, self.GetArrayCount(func))])
  3286. f.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
  3287. f.write(" }\n });\n")
  3288. for arg in func.GetOriginalArgs():
  3289. arg.WriteClientSideValidationCode(f, func)
  3290. f.write(" helper_->%sImmediate(%s);\n" %
  3291. (func.name, func.MakeInitString("")))
  3292. f.write(" CheckGLError();\n")
  3293. f.write("}\n")
  3294. f.write("\n")
  3295. def WriteGLES2ImplementationUnitTest(self, func, f):
  3296. """Writes the GLES2 Implemention unit test."""
  3297. client_test = func.GetInfo('client_test', True)
  3298. if not client_test:
  3299. return;
  3300. code = """
  3301. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  3302. %(type)s data[%(count_param)d][%(count)d] = {{0}};
  3303. struct Cmds {
  3304. cmds::%(name)sImmediate cmd;
  3305. %(type)s data[%(count_param)d][%(count)d];
  3306. };
  3307. Cmds expected;
  3308. for (int ii = 0; ii < %(count_param)d; ++ii) {
  3309. for (int jj = 0; jj < %(count)d; ++jj) {
  3310. data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
  3311. }
  3312. }
  3313. expected.cmd.Init(%(cmd_args)s);
  3314. gl_->%(name)s(%(args)s);
  3315. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  3316. }
  3317. """
  3318. cmd_arg_strings = []
  3319. for arg in func.GetCmdArgs():
  3320. if arg.name.endswith("_shm_id"):
  3321. cmd_arg_strings.append("&data[0][0]")
  3322. elif arg.name.endswith("_shm_offset"):
  3323. continue
  3324. else:
  3325. cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
  3326. gl_arg_strings = []
  3327. count_param = 0
  3328. for arg in func.GetOriginalArgs():
  3329. if arg.IsPointer():
  3330. valid_value = "&data[0][0]"
  3331. else:
  3332. valid_value = arg.GetValidClientSideArg(func)
  3333. gl_arg_strings.append(valid_value)
  3334. if arg.name == "count":
  3335. count_param = int(valid_value)
  3336. f.write(code % {
  3337. 'prefix' : _prefix,
  3338. 'name': func.name,
  3339. 'type': self.GetArrayType(func),
  3340. 'count': self.GetArrayCount(func),
  3341. 'args': ", ".join(gl_arg_strings),
  3342. 'cmd_args': ", ".join(cmd_arg_strings),
  3343. 'count_param': count_param,
  3344. })
  3345. # Test constants for invalid values, as they are not tested by the
  3346. # service.
  3347. constants = [
  3348. arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
  3349. ]
  3350. if not constants:
  3351. return
  3352. code = """
  3353. TEST_F(%(prefix)sImplementationTest,
  3354. %(name)sInvalidConstantArg%(invalid_index)d) {
  3355. %(type)s data[%(count_param)d][%(count)d] = {{0}};
  3356. for (int ii = 0; ii < %(count_param)d; ++ii) {
  3357. for (int jj = 0; jj < %(count)d; ++jj) {
  3358. data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
  3359. }
  3360. }
  3361. gl_->%(name)s(%(args)s);
  3362. EXPECT_TRUE(NoCommandsWritten());
  3363. EXPECT_EQ(%(gl_error)s, CheckError());
  3364. }
  3365. """
  3366. for invalid_arg in constants:
  3367. gl_arg_strings = []
  3368. invalid = invalid_arg.GetInvalidArg(func)
  3369. for arg in func.GetOriginalArgs():
  3370. if arg is invalid_arg:
  3371. gl_arg_strings.append(invalid[0])
  3372. elif arg.IsPointer():
  3373. gl_arg_strings.append("&data[0][0]")
  3374. else:
  3375. valid_value = arg.GetValidClientSideArg(func)
  3376. gl_arg_strings.append(valid_value)
  3377. if arg.name == "count":
  3378. count_param = int(valid_value)
  3379. f.write(code % {
  3380. 'prefix' : _prefix,
  3381. 'name': func.name,
  3382. 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
  3383. 'type': self.GetArrayType(func),
  3384. 'count': self.GetArrayCount(func),
  3385. 'args': ", ".join(gl_arg_strings),
  3386. 'gl_error': invalid[2],
  3387. 'count_param': count_param,
  3388. })
  3389. def WriteImmediateCmdComputeSize(self, func, f):
  3390. """Overrriden from TypeHandler."""
  3391. f.write(" static uint32_t ComputeDataSize(GLsizei _n) {\n")
  3392. f.write(" return static_cast<uint32_t>(\n")
  3393. f.write(" sizeof(%s) * %d * _n); // NOLINT\n" %
  3394. (self.GetArrayType(func), self.GetArrayCount(func)))
  3395. f.write(" }\n")
  3396. f.write("\n")
  3397. f.write(" static uint32_t ComputeSize(GLsizei _n) {\n")
  3398. f.write(" return static_cast<uint32_t>(\n")
  3399. f.write(
  3400. " sizeof(ValueType) + ComputeDataSize(_n)); // NOLINT\n")
  3401. f.write(" }\n")
  3402. f.write("\n")
  3403. def WriteImmediateCmdSetHeader(self, _func, f):
  3404. """Overrriden from TypeHandler."""
  3405. f.write(" void SetHeader(GLsizei _n) {\n")
  3406. f.write(
  3407. " header.SetCmdByTotalSize<ValueType>(ComputeSize(_n));\n")
  3408. f.write(" }\n")
  3409. f.write("\n")
  3410. def WriteImmediateCmdInit(self, func, f):
  3411. """Overrriden from TypeHandler."""
  3412. f.write(" void Init(%s) {\n" %
  3413. func.MakeTypedInitString("_"))
  3414. f.write(" SetHeader(_count);\n")
  3415. args = func.GetCmdArgs()
  3416. for arg in args:
  3417. arg.WriteSetCode(f, 4, "_%s" % arg.name)
  3418. f.write(" memcpy(ImmediateDataAddress(this),\n")
  3419. pointer_arg = func.GetLastOriginalPointerArg()
  3420. f.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
  3421. f.write(" }\n")
  3422. f.write("\n")
  3423. def WriteImmediateCmdSet(self, func, f):
  3424. """Overrriden from TypeHandler."""
  3425. f.write(" void* Set(void* cmd%s) {\n" %
  3426. func.MakeTypedInitString("_", True))
  3427. f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
  3428. func.MakeInitString("_"))
  3429. f.write(" const uint32_t size = ComputeSize(_count);\n")
  3430. f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
  3431. "cmd, size);\n")
  3432. f.write(" }\n")
  3433. f.write("\n")
  3434. def WriteImmediateCmdHelper(self, func, f):
  3435. """Overrriden from TypeHandler."""
  3436. code = """ void %(name)s(%(typed_args)s) {
  3437. const uint32_t size = %(lp)s::cmds::%(name)s::ComputeSize(count);
  3438. %(lp)s::cmds::%(name)s* c =
  3439. GetImmediateCmdSpaceTotalSize<%(lp)s::cmds::%(name)s>(size);
  3440. if (c) {
  3441. c->Init(%(args)s);
  3442. }
  3443. }
  3444. """
  3445. f.write(code % {
  3446. "lp" : _lower_prefix,
  3447. "name": func.name,
  3448. "typed_args": func.MakeTypedInitString(""),
  3449. "args": func.MakeInitString("")
  3450. })
  3451. def WriteImmediateFormatTest(self, func, f):
  3452. """Overrriden from TypeHandler."""
  3453. args = func.GetOriginalArgs()
  3454. count_param = 0
  3455. for arg in args:
  3456. if arg.name == "count":
  3457. count_param = int(arg.GetValidClientSideCmdArg(func))
  3458. f.write("TEST_F(%sFormatTest, %s) {\n" % (_prefix, func.name))
  3459. f.write(" const int kSomeBaseValueToTestWith = 51;\n")
  3460. f.write(" static %s data[] = {\n" % self.GetArrayType(func))
  3461. for v in range(0, self.GetArrayCount(func) * count_param):
  3462. f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
  3463. (self.GetArrayType(func), v))
  3464. f.write(" };\n")
  3465. f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
  3466. (func.name, func.name))
  3467. f.write(" const GLsizei kNumElements = %d;\n" % count_param)
  3468. f.write(" const size_t kExpectedCmdSize =\n")
  3469. f.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
  3470. (self.GetArrayType(func), self.GetArrayCount(func)))
  3471. f.write(" void* next_cmd = cmd.Set(\n")
  3472. f.write(" &cmd")
  3473. for value, arg in enumerate(args):
  3474. if arg.IsPointer():
  3475. f.write(",\n data")
  3476. elif arg.IsConstant():
  3477. continue
  3478. else:
  3479. f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
  3480. f.write(");\n")
  3481. f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
  3482. func.name)
  3483. f.write(" cmd.header.command);\n")
  3484. f.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
  3485. for value, arg in enumerate(args):
  3486. if arg.IsPointer() or arg.IsConstant():
  3487. continue
  3488. f.write(" EXPECT_EQ(static_cast<%s>(%d), %s);\n" %
  3489. (arg.type, value + 1, arg.GetArgAccessor('cmd')))
  3490. f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
  3491. f.write(" next_cmd, sizeof(cmd) +\n")
  3492. f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
  3493. # TODO: Check that data was inserted
  3494. f.write("}\n")
  3495. f.write("\n")
  3496. class PUTSTRHandler(ArrayArgTypeHandler):
  3497. """Handler for functions that pass a string array."""
  3498. def __GetDataArg(self, func):
  3499. """Return the argument that points to the 2D char arrays"""
  3500. for arg in func.GetOriginalArgs():
  3501. if arg.IsPointer2D():
  3502. return arg
  3503. return None
  3504. def __GetLengthArg(self, func):
  3505. """Return the argument that holds length for each char array"""
  3506. for arg in func.GetOriginalArgs():
  3507. if arg.IsPointer() and not arg.IsPointer2D():
  3508. return arg
  3509. return None
  3510. def WriteGLES2Implementation(self, func, f):
  3511. """Overrriden from TypeHandler."""
  3512. f.write("%s %sImplementation::%s(%s) {\n" %
  3513. (func.return_type, _prefix, func.original_name,
  3514. func.MakeTypedOriginalArgString("")))
  3515. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  3516. func.WriteDestinationInitalizationValidation(f)
  3517. self.WriteClientGLCallLog(func, f)
  3518. data_arg = self.__GetDataArg(func)
  3519. length_arg = self.__GetLengthArg(func)
  3520. log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
  3521. for (GLsizei ii = 0; ii < count; ++ii) {
  3522. if (%(data)s[ii]) {"""
  3523. if length_arg == None:
  3524. log_code_block += """
  3525. GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
  3526. else:
  3527. log_code_block += """
  3528. if (%(length)s && %(length)s[ii] >= 0) {
  3529. const std::string my_str(%(data)s[ii], %(length)s[ii]);
  3530. GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
  3531. } else {
  3532. GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
  3533. }"""
  3534. log_code_block += """
  3535. } else {
  3536. GPU_CLIENT_LOG(" " << ii << ": NULL");
  3537. }
  3538. }
  3539. });
  3540. """
  3541. f.write(log_code_block % {
  3542. 'data': data_arg.name,
  3543. 'length': length_arg.name if not length_arg == None else ''
  3544. })
  3545. for arg in func.GetOriginalArgs():
  3546. arg.WriteClientSideValidationCode(f, func)
  3547. bucket_args = []
  3548. for arg in func.GetOriginalArgs():
  3549. if arg.name == 'count' or arg == self.__GetLengthArg(func):
  3550. continue
  3551. if arg == self.__GetDataArg(func):
  3552. bucket_args.append('kResultBucketId')
  3553. else:
  3554. bucket_args.append(arg.name)
  3555. code_block = """
  3556. if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
  3557. return;
  3558. }
  3559. helper_->%(func_name)sBucket(%(bucket_args)s);
  3560. helper_->SetBucketSize(kResultBucketId, 0);
  3561. CheckGLError();
  3562. }
  3563. """
  3564. f.write(code_block % {
  3565. 'data': data_arg.name,
  3566. 'length': length_arg.name if not length_arg == None else 'nullptr',
  3567. 'func_name': func.name,
  3568. 'bucket_args': ', '.join(bucket_args),
  3569. })
  3570. def WriteGLES2ImplementationUnitTest(self, func, f):
  3571. """Overrriden from TypeHandler."""
  3572. code = """
  3573. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  3574. const uint32_t kBucketId = %(prefix)sImplementation::kResultBucketId;
  3575. const char* kString1 = "happy";
  3576. const char* kString2 = "ending";
  3577. const size_t kString1Size = ::strlen(kString1) + 1;
  3578. const size_t kString2Size = ::strlen(kString2) + 1;
  3579. const size_t kHeaderSize = sizeof(GLint) * 3;
  3580. const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
  3581. const size_t kPaddedHeaderSize =
  3582. transfer_buffer_->RoundToAlignment(kHeaderSize);
  3583. const size_t kPaddedString1Size =
  3584. transfer_buffer_->RoundToAlignment(kString1Size);
  3585. const size_t kPaddedString2Size =
  3586. transfer_buffer_->RoundToAlignment(kString2Size);
  3587. struct Cmds {
  3588. cmd::SetBucketSize set_bucket_size;
  3589. cmd::SetBucketData set_bucket_header;
  3590. cmd::SetToken set_token1;
  3591. cmd::SetBucketData set_bucket_data1;
  3592. cmd::SetToken set_token2;
  3593. cmd::SetBucketData set_bucket_data2;
  3594. cmd::SetToken set_token3;
  3595. cmds::%(name)sBucket cmd_bucket;
  3596. cmd::SetBucketSize clear_bucket_size;
  3597. };
  3598. ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
  3599. ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
  3600. ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
  3601. Cmds expected;
  3602. expected.set_bucket_size.Init(kBucketId, kSourceSize);
  3603. expected.set_bucket_header.Init(
  3604. kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
  3605. expected.set_token1.Init(GetNextToken());
  3606. expected.set_bucket_data1.Init(
  3607. kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
  3608. expected.set_token2.Init(GetNextToken());
  3609. expected.set_bucket_data2.Init(
  3610. kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
  3611. mem2.offset);
  3612. expected.set_token3.Init(GetNextToken());
  3613. expected.cmd_bucket.Init(%(bucket_args)s);
  3614. expected.clear_bucket_size.Init(kBucketId, 0);
  3615. const char* kStrings[] = { kString1, kString2 };
  3616. gl_->%(name)s(%(gl_args)s);
  3617. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  3618. }
  3619. """
  3620. gl_args = []
  3621. bucket_args = []
  3622. for arg in func.GetOriginalArgs():
  3623. if arg == self.__GetDataArg(func):
  3624. gl_args.append('kStrings')
  3625. bucket_args.append('kBucketId')
  3626. elif arg == self.__GetLengthArg(func):
  3627. gl_args.append('nullptr')
  3628. elif arg.name == 'count':
  3629. gl_args.append('2')
  3630. else:
  3631. gl_args.append(arg.GetValidClientSideArg(func))
  3632. bucket_args.append(arg.GetValidClientSideArg(func))
  3633. f.write(code % {
  3634. 'prefix' : _prefix,
  3635. 'name': func.name,
  3636. 'gl_args': ", ".join(gl_args),
  3637. 'bucket_args': ", ".join(bucket_args),
  3638. })
  3639. if self.__GetLengthArg(func) == None:
  3640. return
  3641. code = """
  3642. TEST_F(%(prefix)sImplementationTest, %(name)sWithLength) {
  3643. const uint32_t kBucketId = %(prefix)sImplementation::kResultBucketId;
  3644. const char* kString = "foobar******";
  3645. const size_t kStringSize = 6; // We only need "foobar".
  3646. const size_t kHeaderSize = sizeof(GLint) * 2;
  3647. const size_t kSourceSize = kHeaderSize + kStringSize + 1;
  3648. const size_t kPaddedHeaderSize =
  3649. transfer_buffer_->RoundToAlignment(kHeaderSize);
  3650. const size_t kPaddedStringSize =
  3651. transfer_buffer_->RoundToAlignment(kStringSize + 1);
  3652. struct Cmds {
  3653. cmd::SetBucketSize set_bucket_size;
  3654. cmd::SetBucketData set_bucket_header;
  3655. cmd::SetToken set_token1;
  3656. cmd::SetBucketData set_bucket_data;
  3657. cmd::SetToken set_token2;
  3658. cmds::ShaderSourceBucket shader_source_bucket;
  3659. cmd::SetBucketSize clear_bucket_size;
  3660. };
  3661. ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
  3662. ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
  3663. Cmds expected;
  3664. expected.set_bucket_size.Init(kBucketId, kSourceSize);
  3665. expected.set_bucket_header.Init(
  3666. kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
  3667. expected.set_token1.Init(GetNextToken());
  3668. expected.set_bucket_data.Init(
  3669. kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
  3670. expected.set_token2.Init(GetNextToken());
  3671. expected.shader_source_bucket.Init(%(bucket_args)s);
  3672. expected.clear_bucket_size.Init(kBucketId, 0);
  3673. const char* kStrings[] = { kString };
  3674. const GLint kLength[] = { kStringSize };
  3675. gl_->%(name)s(%(gl_args)s);
  3676. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  3677. }
  3678. """
  3679. gl_args = []
  3680. for arg in func.GetOriginalArgs():
  3681. if arg == self.__GetDataArg(func):
  3682. gl_args.append('kStrings')
  3683. elif arg == self.__GetLengthArg(func):
  3684. gl_args.append('kLength')
  3685. elif arg.name == 'count':
  3686. gl_args.append('1')
  3687. else:
  3688. gl_args.append(arg.GetValidClientSideArg(func))
  3689. f.write(code % {
  3690. 'prefix' : _prefix,
  3691. 'name': func.name,
  3692. 'gl_args': ", ".join(gl_args),
  3693. 'bucket_args': ", ".join(bucket_args),
  3694. })
  3695. def WriteBucketServiceUnitTest(self, func, f, *extras):
  3696. """Overrriden from TypeHandler."""
  3697. cmd_args = []
  3698. cmd_args_with_invalid_id = []
  3699. gl_args = []
  3700. for index, arg in enumerate(func.GetOriginalArgs()):
  3701. if arg == self.__GetLengthArg(func):
  3702. gl_args.append('_')
  3703. elif arg.name == 'count':
  3704. gl_args.append('1')
  3705. elif arg == self.__GetDataArg(func):
  3706. cmd_args.append('kBucketId')
  3707. cmd_args_with_invalid_id.append('kBucketId')
  3708. gl_args.append('_')
  3709. elif index == 0: # Resource ID arg
  3710. cmd_args.append(arg.GetValidArg(func))
  3711. cmd_args_with_invalid_id.append('kInvalidClientId')
  3712. gl_args.append(arg.GetValidGLArg(func))
  3713. else:
  3714. cmd_args.append(arg.GetValidArg(func))
  3715. cmd_args_with_invalid_id.append(arg.GetValidArg(func))
  3716. gl_args.append(arg.GetValidGLArg(func))
  3717. test = """
  3718. TEST_P(%(test_name)s, %(name)sValidArgs) {
  3719. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  3720. const uint32_t kBucketId = 123;
  3721. const char kSource0[] = "hello";
  3722. const char* kSource[] = { kSource0 };
  3723. const char kValidStrEnd = 0;
  3724. SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
  3725. cmds::%(name)s cmd;
  3726. cmd.Init(%(cmd_args)s);
  3727. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
  3728. test += """
  3729. }
  3730. """
  3731. self.WriteValidUnitTest(func, f, test, {
  3732. 'cmd_args': ", ".join(cmd_args),
  3733. 'gl_args': ", ".join(gl_args),
  3734. }, *extras)
  3735. test = """
  3736. TEST_P(%(test_name)s, %(name)sInvalidArgs) {
  3737. const uint32_t kBucketId = 123;
  3738. const char kSource0[] = "hello";
  3739. const char* kSource[] = { kSource0 };
  3740. const char kValidStrEnd = 0;
  3741. cmds::%(name)s cmd;
  3742. // Test no bucket.
  3743. cmd.Init(%(cmd_args)s);
  3744. EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
  3745. // Test invalid client.
  3746. SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
  3747. cmd.Init(%(cmd_args_with_invalid_id)s);
  3748. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  3749. EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
  3750. }
  3751. """
  3752. self.WriteValidUnitTest(func, f, test, {
  3753. 'cmd_args': ", ".join(cmd_args),
  3754. 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
  3755. }, *extras)
  3756. test = """
  3757. TEST_P(%(test_name)s, %(name)sInvalidHeader) {
  3758. const uint32_t kBucketId = 123;
  3759. const char kSource0[] = "hello";
  3760. const char* kSource[] = { kSource0 };
  3761. const char kValidStrEnd = 0;
  3762. const GLsizei kCount = static_cast<GLsizei>(std::size(kSource));
  3763. const GLsizei kTests[] = {
  3764. kCount + 1,
  3765. 0,
  3766. std::numeric_limits<GLsizei>::max(),
  3767. -1,
  3768. };
  3769. for (size_t ii = 0; ii < std::size(kTests); ++ii) {
  3770. SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
  3771. cmds::%(name)s cmd;
  3772. cmd.Init(%(cmd_args)s);
  3773. EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
  3774. }
  3775. }
  3776. """
  3777. self.WriteValidUnitTest(func, f, test, {
  3778. 'cmd_args': ", ".join(cmd_args),
  3779. }, *extras)
  3780. test = """
  3781. TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
  3782. const uint32_t kBucketId = 123;
  3783. const char kSource0[] = "hello";
  3784. const char* kSource[] = { kSource0 };
  3785. const char kInvalidStrEnd = '*';
  3786. SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
  3787. cmds::%(name)s cmd;
  3788. cmd.Init(%(cmd_args)s);
  3789. EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
  3790. }
  3791. """
  3792. self.WriteValidUnitTest(func, f, test, {
  3793. 'cmd_args': ", ".join(cmd_args),
  3794. }, *extras)
  3795. class PUTXnHandler(ArrayArgTypeHandler):
  3796. """Handler for glUniform?f functions."""
  3797. def WriteHandlerImplementation(self, func, f):
  3798. """Overrriden from TypeHandler."""
  3799. code = """ %(type)s temp[%(count)s] = { %(values)s};
  3800. Do%(name)sv(%(location)s, 1, &temp[0]);
  3801. """
  3802. values = ""
  3803. args = func.GetOriginalArgs()
  3804. count = int(self.GetArrayCount(func))
  3805. for ii in range(count):
  3806. values += "%s, " % args[len(args) - count + ii].name
  3807. f.write(code % {
  3808. 'name': func.name,
  3809. 'count': self.GetArrayCount(func),
  3810. 'type': self.GetArrayType(func),
  3811. 'location': args[0].name,
  3812. 'args': func.MakeOriginalArgString(""),
  3813. 'values': values,
  3814. })
  3815. def WriteServiceUnitTest(self, func, f, *extras):
  3816. """Overrriden from TypeHandler."""
  3817. valid_test = """
  3818. TEST_P(%(test_name)s, %(name)sValidArgs) {
  3819. EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
  3820. SpecializedSetup<cmds::%(name)s, 0>(true);
  3821. cmds::%(name)s cmd;
  3822. cmd.Init(%(args)s);
  3823. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  3824. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  3825. }
  3826. """
  3827. args = func.GetOriginalArgs()
  3828. local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
  3829. self.WriteValidUnitTest(func, f, valid_test, {
  3830. 'name': func.name,
  3831. 'count': self.GetArrayCount(func),
  3832. 'local_args': local_args,
  3833. }, *extras)
  3834. invalid_test = """
  3835. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  3836. EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
  3837. SpecializedSetup<cmds::%(name)s, 0>(false);
  3838. cmds::%(name)s cmd;
  3839. cmd.Init(%(args)s);
  3840. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
  3841. }
  3842. """
  3843. self.WriteInvalidUnitTest(func, f, invalid_test, {
  3844. 'name': func.GetInfo('name'),
  3845. 'count': self.GetArrayCount(func),
  3846. })
  3847. class GLcharHandler(CustomHandler):
  3848. """Handler for functions that pass a single string ."""
  3849. def WriteImmediateCmdComputeSize(self, _func, f):
  3850. """Overrriden from TypeHandler."""
  3851. f.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
  3852. f.write(" return static_cast<uint32_t>(\n")
  3853. f.write(" sizeof(ValueType) + data_size); // NOLINT\n")
  3854. f.write(" }\n")
  3855. def WriteImmediateCmdSetHeader(self, _func, f):
  3856. """Overrriden from TypeHandler."""
  3857. code = """
  3858. void SetHeader(uint32_t data_size) {
  3859. header.SetCmdBySize<ValueType>(data_size);
  3860. }
  3861. """
  3862. f.write(code)
  3863. def WriteImmediateCmdInit(self, func, f):
  3864. """Overrriden from TypeHandler."""
  3865. last_arg = func.GetLastOriginalArg()
  3866. args = func.GetCmdArgs()
  3867. code = """
  3868. void Init(%s, uint32_t _data_size) {
  3869. SetHeader(_data_size);
  3870. """
  3871. f.write(code % func.MakeTypedArgString("_"))
  3872. for arg in args:
  3873. arg.WriteSetCode(f, 4, "_%s" % arg.name)
  3874. code = """
  3875. memcpy(ImmediateDataAddress(this), _%s, _data_size);
  3876. }
  3877. """
  3878. f.write(code % last_arg.name)
  3879. def WriteImmediateCmdSet(self, func, f):
  3880. """Overrriden from TypeHandler."""
  3881. f.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
  3882. func.MakeTypedCmdArgString("_", True))
  3883. f.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
  3884. func.MakeCmdArgString("_"))
  3885. f.write(" return NextImmediateCmdAddress<ValueType>("
  3886. "cmd, _data_size);\n")
  3887. f.write(" }\n")
  3888. f.write("\n")
  3889. def WriteImmediateCmdHelper(self, func, f):
  3890. """Overrriden from TypeHandler."""
  3891. code = """ void %(name)s(%(typed_args)s) {
  3892. const uint32_t data_size = strlen(name);
  3893. %(lp)s::cmds::%(name)s* c =
  3894. GetImmediateCmdSpace<%(lp)s::cmds::%(name)s>(data_size);
  3895. if (c) {
  3896. c->Init(%(args)s, data_size);
  3897. }
  3898. }
  3899. """
  3900. f.write(code % {
  3901. "lp" : _lower_prefix,
  3902. "name": func.name,
  3903. "typed_args": func.MakeTypedOriginalArgString(""),
  3904. "args": func.MakeOriginalArgString(""),
  3905. })
  3906. def WriteImmediateFormatTest(self, func, f):
  3907. """Overrriden from TypeHandler."""
  3908. init_code = []
  3909. check_code = []
  3910. all_but_last_arg = func.GetCmdArgs()[:-1]
  3911. for value, arg in enumerate(all_but_last_arg):
  3912. init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
  3913. for value, arg in enumerate(all_but_last_arg):
  3914. check_code.append(" EXPECT_EQ(static_cast<%s>(%d), %s);" %
  3915. (arg.type, value + 11, arg.GetArgAccessor('cmd')))
  3916. code = """
  3917. TEST_F(%(prefix)sFormatTest, %(func_name)s) {
  3918. cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
  3919. static const char* const test_str = \"test string\";
  3920. void* next_cmd = cmd.Set(
  3921. &cmd,
  3922. %(init_code)s
  3923. test_str,
  3924. strlen(test_str));
  3925. EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
  3926. cmd.header.command);
  3927. EXPECT_EQ(sizeof(cmd) +
  3928. RoundSizeToMultipleOfEntries(strlen(test_str)),
  3929. cmd.header.size * 4u);
  3930. EXPECT_EQ(static_cast<char*>(next_cmd),
  3931. reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
  3932. RoundSizeToMultipleOfEntries(strlen(test_str)));
  3933. %(check_code)s
  3934. EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
  3935. EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
  3936. CheckBytesWritten(
  3937. next_cmd,
  3938. sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
  3939. sizeof(cmd) + strlen(test_str));
  3940. }
  3941. """
  3942. f.write(code % {
  3943. 'prefix': _prefix,
  3944. 'func_name': func.name,
  3945. 'init_code': "\n".join(init_code),
  3946. 'check_code': "\n".join(check_code),
  3947. })
  3948. class GLcharNHandler(CustomHandler):
  3949. """Handler for functions that pass a single string with an optional len."""
  3950. def InitFunction(self, func):
  3951. """Overrriden from TypeHandler."""
  3952. func.cmd_args = []
  3953. func.AddCmdArg(Argument('bucket_id', 'GLuint'))
  3954. def NeedsDataTransferFunction(self, func):
  3955. """Overriden from TypeHandler."""
  3956. return False
  3957. def WriteServiceImplementation(self, func, f):
  3958. """Overrriden from TypeHandler."""
  3959. self.WriteServiceHandlerFunctionHeader(func, f)
  3960. if func.IsES31():
  3961. return
  3962. f.write("""
  3963. GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
  3964. Bucket* bucket = GetBucket(bucket_id);
  3965. if (!bucket || bucket->size() == 0) {
  3966. return error::kInvalidArguments;
  3967. }
  3968. std::string str;
  3969. if (!bucket->GetAsString(&str)) {
  3970. return error::kInvalidArguments;
  3971. }
  3972. %(gl_func_name)s(0, str.c_str());
  3973. return error::kNoError;
  3974. }
  3975. """ % {
  3976. 'gl_func_name': func.GetGLFunctionName(),
  3977. 'bucket_id': func.cmd_args[0].name,
  3978. })
  3979. class IsHandler(TypeHandler):
  3980. """Handler for glIs____ type and glGetError functions."""
  3981. def InitFunction(self, func):
  3982. """Overrriden from TypeHandler."""
  3983. func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
  3984. func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
  3985. if func.GetInfo('result') == None:
  3986. func.AddInfo('result', ['uint32_t'])
  3987. func.passthrough_service_doer_args.append(Argument('result', 'uint32_t*'))
  3988. def WriteServiceUnitTest(self, func, f, *extras):
  3989. """Overrriden from TypeHandler."""
  3990. valid_test = """
  3991. TEST_P(%(test_name)s, %(name)sValidArgs) {
  3992. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
  3993. SpecializedSetup<cmds::%(name)s, 0>(true);
  3994. cmds::%(name)s cmd;
  3995. cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
  3996. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  3997. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  3998. }
  3999. """
  4000. comma = ""
  4001. if len(func.GetOriginalArgs()):
  4002. comma =", "
  4003. self.WriteValidUnitTest(func, f, valid_test, {
  4004. 'comma': comma,
  4005. }, *extras)
  4006. invalid_test = """
  4007. TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
  4008. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  4009. SpecializedSetup<cmds::%(name)s, 0>(false);
  4010. cmds::%(name)s cmd;
  4011. cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
  4012. EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
  4013. }
  4014. """
  4015. self.WriteInvalidUnitTest(func, f, invalid_test, {
  4016. 'comma': comma,
  4017. }, *extras)
  4018. invalid_test = """
  4019. TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
  4020. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
  4021. SpecializedSetup<cmds::%(name)s, 0>(false);
  4022. cmds::%(name)s cmd;
  4023. cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
  4024. EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
  4025. cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
  4026. EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
  4027. }
  4028. """
  4029. self.WriteValidUnitTest(func, f, invalid_test, {
  4030. 'comma': comma,
  4031. }, *extras)
  4032. def WriteServiceImplementation(self, func, f):
  4033. """Overrriden from TypeHandler."""
  4034. self.WriteServiceHandlerFunctionHeader(func, f)
  4035. if func.IsES31():
  4036. return
  4037. self.WriteHandlerExtensionCheck(func, f)
  4038. args = func.GetOriginalArgs()
  4039. for arg in args:
  4040. arg.WriteGetCode(f)
  4041. code = """ typedef cmds::%(func_name)s::Result Result;
  4042. Result* result_dst = GetSharedMemoryAs<Result*>(
  4043. c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
  4044. if (!result_dst) {
  4045. return error::kOutOfBounds;
  4046. }
  4047. """
  4048. f.write(code % {'func_name': func.name})
  4049. func.WriteHandlerValidation(f)
  4050. f.write(" *result_dst = %s(%s);\n" %
  4051. (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
  4052. f.write(" return error::kNoError;\n")
  4053. f.write("}\n")
  4054. f.write("\n")
  4055. def WritePassthroughServiceImplementation(self, func, f):
  4056. """Overrriden from TypeHandler."""
  4057. self.WritePassthroughServiceFunctionHeader(func, f)
  4058. self.WriteHandlerExtensionCheck(func, f)
  4059. self.WriteServiceHandlerArgGetCode(func, f)
  4060. code = """ typedef cmds::%(func_name)s::Result Result;
  4061. Result* result = GetSharedMemoryAs<Result*>(
  4062. c.result_shm_id, c.result_shm_offset, sizeof(*result));
  4063. if (!result) {
  4064. return error::kOutOfBounds;
  4065. }
  4066. """
  4067. f.write(code % {'func_name': func.name})
  4068. self.WritePassthroughServiceFunctionDoerCall(func, f)
  4069. f.write(" return error::kNoError;\n")
  4070. f.write("}\n")
  4071. f.write("\n")
  4072. def WriteGLES2Implementation(self, func, f):
  4073. """Overrriden from TypeHandler."""
  4074. impl_func = func.GetInfo('impl_func', True)
  4075. if impl_func:
  4076. error_value = func.GetInfo("error_value") or "GL_FALSE"
  4077. f.write("%s %sImplementation::%s(%s) {\n" %
  4078. (func.return_type, _prefix, func.original_name,
  4079. func.MakeTypedOriginalArgString("")))
  4080. f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
  4081. self.WriteTraceEvent(func, f)
  4082. func.WriteDestinationInitalizationValidation(f)
  4083. self.WriteClientGLCallLog(func, f)
  4084. f.write(" typedef cmds::%s::Result Result;\n" % func.name)
  4085. f.write(" ScopedResultPtr<Result> result = GetResultAs<Result>();\n")
  4086. f.write(" if (!result) {\n")
  4087. f.write(" return %s;\n" % error_value)
  4088. f.write(" }\n")
  4089. f.write(" *result = 0;\n")
  4090. assert len(func.GetOriginalArgs()) == 1
  4091. id_arg = func.GetOriginalArgs()[0]
  4092. if id_arg.type == 'GLsync':
  4093. arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
  4094. else:
  4095. arg_string = func.MakeOriginalArgString("")
  4096. f.write(
  4097. " helper_->%s(%s, GetResultShmId(), result.offset());\n" %
  4098. (func.name, arg_string))
  4099. f.write(" WaitForCmd();\n")
  4100. f.write(" %s result_value = *result" % func.return_type)
  4101. if func.return_type == "GLboolean":
  4102. f.write(" != 0")
  4103. f.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
  4104. f.write(" CheckGLError();\n")
  4105. f.write(" return result_value;\n")
  4106. f.write("}\n")
  4107. f.write("\n")
  4108. def WriteGLES2ImplementationUnitTest(self, func, f):
  4109. """Overrriden from TypeHandler."""
  4110. client_test = func.GetInfo('client_test', True)
  4111. if client_test:
  4112. code = """
  4113. TEST_F(%(prefix)sImplementationTest, %(name)s) {
  4114. struct Cmds {
  4115. cmds::%(name)s cmd;
  4116. };
  4117. Cmds expected;
  4118. ExpectedMemoryInfo result1 =
  4119. GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
  4120. expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
  4121. EXPECT_CALL(*command_buffer(), OnFlush())
  4122. .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
  4123. .RetiresOnSaturation();
  4124. GLboolean result = gl_->%(name)s(%(gl_id_value)s);
  4125. EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  4126. EXPECT_TRUE(result);
  4127. }
  4128. """
  4129. args = func.GetOriginalArgs()
  4130. assert len(args) == 1
  4131. f.write(code % {
  4132. 'prefix' : _prefix,
  4133. 'name': func.name,
  4134. 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
  4135. 'gl_id_value': args[0].GetValidClientSideArg(func) })
  4136. def WriteImmediateCmdInit(self, func, f):
  4137. """Overrriden from TypeHandler."""
  4138. def WriteImmediateCmdSet(self, func, f):
  4139. """Overrriden from TypeHandler."""
  4140. class STRnHandler(TypeHandler):
  4141. """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
  4142. GetTranslatedShaderSourceANGLE."""
  4143. def InitFunction(self, func):
  4144. """Overrriden from TypeHandler."""
  4145. # remove all but the first cmd args.
  4146. cmd_args = func.GetCmdArgs()
  4147. func.ClearCmdArgs()
  4148. func.AddCmdArg(cmd_args[0])
  4149. # add on a bucket id.
  4150. func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
  4151. def WriteGLES2Implementation(self, func, f):
  4152. """Overrriden from TypeHandler."""
  4153. code_1 = """%(return_type)s %(prefix)sImplementation::%(func_name)s(
  4154. %(args)s) {
  4155. GPU_CLIENT_SINGLE_THREAD_CHECK();
  4156. """
  4157. code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
  4158. << "] gl%(func_name)s" << "("
  4159. << %(arg0)s << ", "
  4160. << %(arg1)s << ", "
  4161. << static_cast<void*>(%(arg2)s) << ", "
  4162. << static_cast<void*>(%(arg3)s) << ")");
  4163. helper_->SetBucketSize(kResultBucketId, 0);
  4164. helper_->%(func_name)s(%(id_name)s, kResultBucketId);
  4165. std::string str;
  4166. GLsizei max_size = 0;
  4167. if (GetBucketAsString(kResultBucketId, &str)) {
  4168. if (bufsize > 0) {
  4169. max_size =
  4170. std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
  4171. memcpy(%(dest_name)s, str.c_str(), max_size);
  4172. %(dest_name)s[max_size] = '\\0';
  4173. GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
  4174. }
  4175. }
  4176. if (%(length_name)s != nullptr) {
  4177. *%(length_name)s = max_size;
  4178. }
  4179. CheckGLError();
  4180. }
  4181. """
  4182. args = func.GetOriginalArgs()
  4183. str_args = {
  4184. 'prefix' : _prefix,
  4185. 'return_type': func.return_type,
  4186. 'func_name': func.original_name,
  4187. 'args': func.MakeTypedOriginalArgString(""),
  4188. 'id_name': args[0].name,
  4189. 'bufsize_name': args[1].name,
  4190. 'length_name': args[2].name,
  4191. 'dest_name': args[3].name,
  4192. 'arg0': args[0].name,
  4193. 'arg1': args[1].name,
  4194. 'arg2': args[2].name,
  4195. 'arg3': args[3].name,
  4196. }
  4197. f.write(code_1 % str_args)
  4198. func.WriteDestinationInitalizationValidation(f)
  4199. f.write(code_2 % str_args)
  4200. def WriteServiceUnitTest(self, func, f, *extras):
  4201. """Overrriden from TypeHandler."""
  4202. valid_test = """
  4203. TEST_P(%(test_name)s, %(name)sValidArgs) {
  4204. const char* kInfo = "hello";
  4205. const uint32_t kBucketId = 123;
  4206. SpecializedSetup<cmds::%(name)s, 0>(true);
  4207. %(expect_len_code)s
  4208. EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
  4209. .WillOnce(DoAll(SetArgPointee<2>(strlen(kInfo)),
  4210. SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
  4211. cmds::%(name)s cmd;
  4212. cmd.Init(%(args)s);
  4213. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  4214. CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
  4215. ASSERT_TRUE(bucket != nullptr);
  4216. EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
  4217. EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
  4218. bucket->size()));
  4219. EXPECT_EQ(GL_NO_ERROR, GetGLError());
  4220. }
  4221. """
  4222. args = func.GetOriginalArgs()
  4223. id_name = args[0].GetValidGLArg(func)
  4224. get_len_func = func.GetInfo('get_len_func')
  4225. get_len_enum = func.GetInfo('get_len_enum')
  4226. sub = {
  4227. 'id_name': id_name,
  4228. 'get_len_func': get_len_func,
  4229. 'get_len_enum': get_len_enum,
  4230. 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
  4231. args[0].GetValidGLArg(func),
  4232. 'args': '%s, kBucketId' % args[0].GetValidArg(func),
  4233. 'expect_len_code': '',
  4234. }
  4235. if get_len_func and get_len_func[0:2] == 'gl':
  4236. sub['expect_len_code'] = (
  4237. " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
  4238. " .WillOnce(SetArgPointee<2>(strlen(kInfo) + 1));") % (
  4239. get_len_func[2:], id_name, get_len_enum)
  4240. self.WriteValidUnitTest(func, f, valid_test, sub, *extras)
  4241. invalid_test = """
  4242. TEST_P(%(test_name)s, %(name)sInvalidArgs) {
  4243. const uint32_t kBucketId = 123;
  4244. EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
  4245. .Times(0);
  4246. cmds::%(name)s cmd;
  4247. cmd.Init(kInvalidClientId, kBucketId);
  4248. EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
  4249. EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
  4250. }
  4251. """
  4252. self.WriteValidUnitTest(func, f, invalid_test, *extras)
  4253. def WriteServiceImplementation(self, func, f):
  4254. """Overrriden from TypeHandler."""
  4255. if func.IsES31():
  4256. TypeHandler.WriteServiceImplementation(self, func, f)
  4257. def WritePassthroughServiceImplementation(self, func, f):
  4258. """Overrriden from TypeHandler."""
  4259. def WriteImmediateCmdInit(self, func, f):
  4260. """Overrriden from TypeHandler."""
  4261. def WriteImmediateCmdSet(self, func, f):
  4262. """Overrriden from TypeHandler."""
  4263. class NamedType():
  4264. """A class that represents a type of an argument in a client function.
  4265. A type of an argument that is to be passed through in the command buffer
  4266. command. Currently used only for the arguments that are specificly named in
  4267. the 'cmd_buffer_functions.txt' f, mostly enums.
  4268. """
  4269. def __init__(self, info):
  4270. assert not 'is_complete' in info or info['is_complete'] == True
  4271. self.info = info
  4272. self.valid = info['valid']
  4273. if 'invalid' in info:
  4274. self.invalid = info['invalid']
  4275. else:
  4276. self.invalid = []
  4277. if 'valid_es3' in info:
  4278. self.valid_es3 = info['valid_es3']
  4279. else:
  4280. self.valid_es3 = []
  4281. if 'deprecated_es3' in info:
  4282. self.deprecated_es3 = info['deprecated_es3']
  4283. else:
  4284. self.deprecated_es3 = []
  4285. self.create_validator = info.get('validator', True)
  4286. self.is_complete = info.get('is_complete', False)
  4287. def GetType(self):
  4288. return self.info['type']
  4289. def GetInvalidValues(self):
  4290. return self.invalid
  4291. def GetValidValues(self):
  4292. return self.valid
  4293. def GetValidValuesES3(self):
  4294. return self.valid_es3
  4295. def GetDeprecatedValuesES3(self):
  4296. return self.deprecated_es3
  4297. def HasES3Values(self):
  4298. return self.valid_es3 or self.deprecated_es3
  4299. def IsConstant(self):
  4300. return self.is_complete and len(self.GetValidValues()) == 1
  4301. def IsComplete(self):
  4302. return self.is_complete
  4303. def CreateValidator(self):
  4304. return self.create_validator and not self.IsConstant()
  4305. def GetConstantValue(self):
  4306. return self.GetValidValues()[0]
  4307. class Argument():
  4308. """A class that represents a function argument."""
  4309. cmd_type_map_ = {
  4310. 'GLenum': ['uint32_t'],
  4311. 'GLint': ['int32_t'],
  4312. 'GLintptr': ['int32_t'],
  4313. 'GLsizei': ['int32_t'],
  4314. 'GLsizeiptr': ['int32_t'],
  4315. 'GLfloat': ['float'],
  4316. 'GLclampf': ['float'],
  4317. 'GLuint64': ['uint32_t', 'uint32_t'],
  4318. }
  4319. need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
  4320. def __init__(self, name, arg_type, arg_default = None):
  4321. self.name = name
  4322. self.optional = arg_type.endswith("Optional*")
  4323. if self.optional:
  4324. arg_type = arg_type[:-len("Optional*")] + "*"
  4325. self.type = arg_type
  4326. self.default = arg_default
  4327. if arg_type in self.cmd_type_map_:
  4328. self.cmd_type = self.cmd_type_map_[arg_type]
  4329. else:
  4330. self.cmd_type = ['uint32_t']
  4331. def IsPointer(self):
  4332. """Returns true if argument is a pointer."""
  4333. return False
  4334. def IsPointer2D(self):
  4335. """Returns true if argument is a 2D pointer."""
  4336. return False
  4337. def IsConstant(self):
  4338. """Returns true if the argument has only one valid value."""
  4339. return False
  4340. def AddCmdArgs(self, args):
  4341. """Adds command arguments for this argument to the given list."""
  4342. if not self.IsConstant():
  4343. args.append(self)
  4344. def AddInitArgs(self, args):
  4345. """Adds init arguments for this argument to the given list."""
  4346. if not self.IsConstant():
  4347. args.append(self)
  4348. def GetValidArg(self, func):
  4349. """Gets a valid value for this argument."""
  4350. valid_arg = func.GetValidArg(self)
  4351. if valid_arg != None:
  4352. return valid_arg
  4353. index = func.GetOriginalArgs().index(self)
  4354. return str(index + 1)
  4355. def GetArgDecls(self):
  4356. if len(self.cmd_type) == 1:
  4357. return [(self.cmd_type[0], self.name)]
  4358. return [(cmd_type, self.name + '_%d' % i)
  4359. for i, cmd_type
  4360. in enumerate(self.cmd_type)]
  4361. def GetReservedSizeId(self):
  4362. """Gets a special identifier name for the data size of this argument"""
  4363. return "%s_size" % self.name
  4364. def GetValidClientSideArg(self, func):
  4365. """Gets a valid value for this argument."""
  4366. valid_arg = func.GetValidArg(self)
  4367. if valid_arg != None:
  4368. return valid_arg
  4369. if self.IsPointer():
  4370. return 'nullptr'
  4371. index = func.GetOriginalArgs().index(self)
  4372. if self.type == 'GLsync':
  4373. return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
  4374. return str(index + 1)
  4375. def GetValidClientSideCmdArg(self, func):
  4376. """Gets a valid value for this argument."""
  4377. valid_arg = func.GetValidArg(self)
  4378. if valid_arg != None:
  4379. return valid_arg
  4380. try:
  4381. index = func.GetOriginalArgs().index(self)
  4382. return str(index + 1)
  4383. except ValueError:
  4384. pass
  4385. index = func.GetCmdArgs().index(self)
  4386. return str(index + 1)
  4387. def GetValidGLArg(self, func):
  4388. """Gets a valid GL value for this argument."""
  4389. value = self.GetValidArg(func)
  4390. if self.type == 'GLsync':
  4391. return ("reinterpret_cast<GLsync>(%s)" % value)
  4392. return value
  4393. def GetValidNonCachedClientSideArg(self, _func):
  4394. """Returns a valid value for this argument in a GL call.
  4395. Using the value will produce a command buffer service invocation.
  4396. Returns None if there is no such value."""
  4397. value = '123'
  4398. if self.type == 'GLsync':
  4399. return ("reinterpret_cast<GLsync>(%s)" % value)
  4400. return value
  4401. def GetValidNonCachedClientSideCmdArg(self, _func):
  4402. """Returns a valid value for this argument in a command buffer command.
  4403. Calling the GL function with the value returned by
  4404. GetValidNonCachedClientSideArg will result in a command buffer command
  4405. that contains the value returned by this function. """
  4406. return '123'
  4407. def GetNumInvalidValues(self, _func):
  4408. """returns the number of invalid values to be tested."""
  4409. return 0
  4410. def GetInvalidArg(self, _index):
  4411. """returns an invalid value and expected parse result by index."""
  4412. return ("---ERROR0---", "---ERROR2---", None)
  4413. def GetArgAccessor(self, cmd_struct_name):
  4414. """Returns the name of the accessor for the argument within the struct."""
  4415. return '%s.%s' % (cmd_struct_name, self.name)
  4416. def GetLogArg(self):
  4417. """Get argument appropriate for LOG macro."""
  4418. if self.type == 'GLboolean':
  4419. return '%sGLES2Util::GetStringBool(%s)' % (_Namespace(), self.name)
  4420. if self.type == 'GLenum':
  4421. return '%sGLES2Util::GetStringEnum(%s)' % (_Namespace(), self.name)
  4422. return self.name
  4423. def WriteGetCode(self, f):
  4424. """Writes the code to get an argument from a command structure."""
  4425. if self.type == 'GLsync':
  4426. my_type = 'GLuint'
  4427. else:
  4428. my_type = self.type
  4429. f.write(" %s %s = static_cast<%s>(c.%s);\n" %
  4430. (my_type, self.name, my_type, self.name))
  4431. def WriteSetCode(self, f, indent, var):
  4432. f.write("%s%s = %s;\n" % (' ' * indent, self.name, var))
  4433. def WriteArgAccessor(self, f):
  4434. """Writes specialized accessor for argument."""
  4435. def WriteValidationCode(self, f, func):
  4436. """Writes the validation code for an argument."""
  4437. def WritePassthroughValidationCode(self, f, func):
  4438. """Writes the passthrough validation code for an argument."""
  4439. def WriteClientSideValidationCode(self, f, func):
  4440. """Writes the validation code for an argument."""
  4441. def WriteDestinationInitalizationValidation(self, f, func):
  4442. """Writes the client side destintion initialization validation."""
  4443. def WriteDestinationInitalizationValidatationIfNeeded(self, f, _func):
  4444. """Writes the client side destintion initialization validation if needed."""
  4445. parts = self.type.split(" ")
  4446. if len(parts) > 1:
  4447. return
  4448. if parts[0] in self.need_validation_:
  4449. f.write(
  4450. " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
  4451. ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
  4452. def GetImmediateVersion(self):
  4453. """Gets the immediate version of this argument."""
  4454. return self
  4455. def GetBucketVersion(self):
  4456. """Gets the bucket version of this argument."""
  4457. return self
  4458. class BoolArgument(Argument):
  4459. """class for C++ bool"""
  4460. def __init__(self, name, _type, arg_default):
  4461. Argument.__init__(self, name, _type, arg_default)
  4462. def GetValidArg(self, func):
  4463. """Gets a valid value for this argument."""
  4464. return 'true'
  4465. def GetValidClientSideArg(self, func):
  4466. """Gets a valid value for this argument."""
  4467. return 'true'
  4468. def GetValidClientSideCmdArg(self, func):
  4469. """Gets a valid value for this argument."""
  4470. return 'true'
  4471. def GetValidGLArg(self, func):
  4472. """Gets a valid GL value for this argument."""
  4473. return 'true'
  4474. def GetArgAccessor(self, cmd_struct_name):
  4475. """Returns the name of the accessor for the argument within the struct."""
  4476. return 'static_cast<bool>(%s.%s)' % (struct_name, self.name)
  4477. class GLBooleanArgument(Argument):
  4478. """class for GLboolean"""
  4479. def __init__(self, name, _type, arg_default):
  4480. Argument.__init__(self, name, 'GLboolean', arg_default)
  4481. def GetValidArg(self, func):
  4482. """Gets a valid value for this argument."""
  4483. return 'true'
  4484. def GetValidClientSideArg(self, func):
  4485. """Gets a valid value for this argument."""
  4486. return 'true'
  4487. def GetValidClientSideCmdArg(self, func):
  4488. """Gets a valid value for this argument."""
  4489. return 'true'
  4490. def GetValidGLArg(self, func):
  4491. """Gets a valid GL value for this argument."""
  4492. return 'true'
  4493. class UniformLocationArgument(Argument):
  4494. """class for uniform locations."""
  4495. def __init__(self, name, arg_default):
  4496. Argument.__init__(self, name, "GLint", arg_default)
  4497. def WriteGetCode(self, f):
  4498. """Writes the code to get an argument from a command structure."""
  4499. code = """ %s %s = static_cast<%s>(c.%s);
  4500. """
  4501. f.write(code % (self.type, self.name, self.type, self.name))
  4502. class DataSizeArgument(Argument):
  4503. """class for data_size which Bucket commands do not need."""
  4504. def __init__(self, name):
  4505. Argument.__init__(self, name, "uint32_t")
  4506. def GetBucketVersion(self):
  4507. return None
  4508. class SizeArgument(Argument):
  4509. """class for GLsizei and GLsizeiptr."""
  4510. def GetNumInvalidValues(self, func):
  4511. """overridden from Argument."""
  4512. if func.IsImmediate():
  4513. return 0
  4514. return 1
  4515. def GetInvalidArg(self, _index):
  4516. """overridden from Argument."""
  4517. return ("-1", "kNoError", "GL_INVALID_VALUE")
  4518. def WriteValidationCode(self, f, func):
  4519. """overridden from Argument."""
  4520. code = """ if (%(var_name)s < 0) {
  4521. LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
  4522. return error::kNoError;
  4523. }
  4524. """
  4525. f.write(code % {
  4526. "var_name": self.name,
  4527. "func_name": func.original_name,
  4528. })
  4529. def WriteClientSideValidationCode(self, f, func):
  4530. """overridden from Argument."""
  4531. code = """ if (%(var_name)s < 0) {
  4532. SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
  4533. return;
  4534. }
  4535. """
  4536. f.write(code % {
  4537. "var_name": self.name,
  4538. "func_name": func.original_name,
  4539. })
  4540. class SizeNotNegativeArgument(SizeArgument):
  4541. """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
  4542. def GetInvalidArg(self, _index):
  4543. """overridden from SizeArgument."""
  4544. return ("-1", "kOutOfBounds", "GL_NO_ERROR")
  4545. def WriteValidationCode(self, f, func):
  4546. """overridden from SizeArgument."""
  4547. class EnumBaseArgument(Argument):
  4548. """Base class for EnumArgument, IntArgument, and BitfieldArgument."""
  4549. def __init__(self, name, gl_type, type_name, arg_type, gl_error,
  4550. named_type_info, arg_default):
  4551. Argument.__init__(self, name, gl_type, arg_default)
  4552. self.gl_error = gl_error
  4553. self.type_name = type_name
  4554. self.named_type = NamedType(named_type_info[type_name])
  4555. def IsConstant(self):
  4556. return self.named_type.IsConstant()
  4557. def GetConstantValue(self):
  4558. return self.named_type.GetConstantValue()
  4559. def WriteValidationCode(self, f, func):
  4560. if self.named_type.IsConstant():
  4561. return
  4562. f.write(" if (!validators_->%s.IsValid(%s)) {\n" %
  4563. (ToUnderscore(self.type_name), self.name))
  4564. if self.gl_error == "GL_INVALID_ENUM":
  4565. f.write(
  4566. " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
  4567. (func.original_name, self.name, self.name))
  4568. else:
  4569. f.write(
  4570. " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
  4571. (self.gl_error, func.original_name, self.name, self.gl_error))
  4572. f.write(" return error::kNoError;\n")
  4573. f.write(" }\n")
  4574. def WriteClientSideValidationCode(self, f, func):
  4575. if not self.named_type.IsConstant():
  4576. return
  4577. f.write(" if (%s != %s) {" % (self.name,
  4578. self.GetConstantValue()))
  4579. f.write(
  4580. " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
  4581. (self.gl_error, func.original_name, self.name, self.gl_error))
  4582. if func.return_type == "void":
  4583. f.write(" return;\n")
  4584. else:
  4585. f.write(" return %s;\n" % func.GetErrorReturnString())
  4586. f.write(" }\n")
  4587. def GetValidArg(self, func):
  4588. valid_arg = func.GetValidArg(self)
  4589. if valid_arg != None:
  4590. return valid_arg
  4591. valid = self.named_type.GetValidValues()
  4592. if valid:
  4593. return valid[0]
  4594. index = func.GetOriginalArgs().index(self)
  4595. return str(index + 1)
  4596. def GetValidClientSideArg(self, func):
  4597. """Gets a valid value for this argument."""
  4598. return self.GetValidArg(func)
  4599. def GetValidClientSideCmdArg(self, func):
  4600. """Gets a valid value for this argument."""
  4601. valid_arg = func.GetValidArg(self)
  4602. if valid_arg != None:
  4603. return valid_arg
  4604. valid = self.named_type.GetValidValues()
  4605. if valid:
  4606. return valid[0]
  4607. try:
  4608. index = func.GetOriginalArgs().index(self)
  4609. return str(index + 1)
  4610. except ValueError:
  4611. pass
  4612. index = func.GetCmdArgs().index(self)
  4613. return str(index + 1)
  4614. def GetValidGLArg(self, func):
  4615. """Gets a valid value for this argument."""
  4616. return self.GetValidArg(func)
  4617. def GetNumInvalidValues(self, _func):
  4618. """returns the number of invalid values to be tested."""
  4619. return len(self.named_type.GetInvalidValues())
  4620. def GetInvalidArg(self, index):
  4621. """returns an invalid value by index."""
  4622. invalid = self.named_type.GetInvalidValues()
  4623. if invalid:
  4624. num_invalid = len(invalid)
  4625. if index >= num_invalid:
  4626. index = num_invalid - 1
  4627. return (invalid[index], "kNoError", self.gl_error)
  4628. return ("---ERROR1---", "kNoError", self.gl_error)
  4629. class EnumArgument(EnumBaseArgument):
  4630. """A class that represents a GLenum argument"""
  4631. def __init__(self, name, arg_type, named_type_info, arg_default):
  4632. EnumBaseArgument.__init__(self, name, "GLenum", arg_type[len("GLenum"):],
  4633. arg_type, "GL_INVALID_ENUM", named_type_info,
  4634. arg_default)
  4635. def GetLogArg(self):
  4636. """Overridden from Argument."""
  4637. return ("GLES2Util::GetString%s(%s)" %
  4638. (self.type_name, self.name))
  4639. class EnumClassArgument(EnumBaseArgument):
  4640. """A class that represents a C++ enum argument encoded as uint32_t"""
  4641. def __init__(self, name, arg_type, named_type_info, arg_default):
  4642. type_name = arg_type[len("EnumClass"):]
  4643. EnumBaseArgument.__init__(self, name, type_name, type_name, arg_type,
  4644. "GL_INVALID_ENUM", named_type_info, arg_default)
  4645. def GetArgAccessor(self, cmd_struct_name):
  4646. """Returns the name of the accessor for the argument within the struct."""
  4647. return 'static_cast<%s>(%s.%s)' % (self.type_name, struct_name, self.name)
  4648. def WriteSetCode(self, f, indent, var):
  4649. f.write("%s%s = static_cast<uint32_t>(%s);\n" %
  4650. (' ' * indent, self.name, var))
  4651. def GetLogArg(self):
  4652. return 'static_cast<uint32_t>(%s)' % self.name
  4653. class IntArgument(EnumBaseArgument):
  4654. """A class for a GLint argument that can only accept specific values.
  4655. For example glTexImage2D takes a GLint for its internalformat
  4656. argument instead of a GLenum.
  4657. """
  4658. def __init__(self, name, arg_type, named_type_info, arg_default):
  4659. EnumBaseArgument.__init__(self, name, "GLint", arg_type[len("GLint"):],
  4660. arg_type, "GL_INVALID_VALUE", named_type_info,
  4661. arg_default)
  4662. class BitFieldArgument(EnumBaseArgument):
  4663. """A class for a GLbitfield argument that can only accept specific values.
  4664. For example glFenceSync takes a GLbitfield for its flags argument bit it
  4665. must be 0.
  4666. """
  4667. def __init__(self, name, arg_type, named_type_info, arg_default):
  4668. EnumBaseArgument.__init__(self, name, "GLbitfield",
  4669. arg_type[len("GLbitfield"):], arg_type,
  4670. "GL_INVALID_VALUE", named_type_info, arg_default)
  4671. class ImmediatePointerArgument(Argument):
  4672. """A class that represents an immediate argument to a function.
  4673. An immediate argument is one where the data follows the command.
  4674. """
  4675. def IsPointer(self):
  4676. return True
  4677. def GetPointedType(self):
  4678. match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
  4679. assert match
  4680. return match.groupdict()['element_type']
  4681. def AddCmdArgs(self, args):
  4682. """Overridden from Argument."""
  4683. def WriteGetCode(self, f):
  4684. """Overridden from Argument."""
  4685. f.write(" volatile %s %s = %sGetImmediateDataAs<volatile %s>(\n" %
  4686. (self.type, self.name, _Namespace(), self.type))
  4687. f.write(" c, %s, immediate_data_size);\n" %
  4688. self.GetReservedSizeId())
  4689. def WriteValidationCode(self, f, func):
  4690. """Overridden from Argument."""
  4691. if self.optional:
  4692. return
  4693. f.write(" if (%s == nullptr) {\n" % self.name)
  4694. f.write(" return error::kOutOfBounds;\n")
  4695. f.write(" }\n")
  4696. def WritePassthroughValidationCode(self, f, func):
  4697. """Overridden from Argument."""
  4698. if self.optional:
  4699. return
  4700. f.write(" if (%s == nullptr) {\n" % self.name)
  4701. f.write(" return error::kOutOfBounds;\n")
  4702. f.write(" }\n")
  4703. def GetImmediateVersion(self):
  4704. """Overridden from Argument."""
  4705. return None
  4706. def WriteDestinationInitalizationValidation(self, f, func):
  4707. """Overridden from Argument."""
  4708. self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
  4709. def GetLogArg(self):
  4710. """Overridden from Argument."""
  4711. return "static_cast<const void*>(%s)" % self.name
  4712. class PointerArgument(Argument):
  4713. """A class that represents a pointer argument to a function."""
  4714. def IsPointer(self):
  4715. """Overridden from Argument."""
  4716. return True
  4717. def IsPointer2D(self):
  4718. """Overridden from Argument."""
  4719. return self.type.count('*') == 2
  4720. def GetPointedType(self):
  4721. match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
  4722. assert match
  4723. return match.groupdict()['element_type']
  4724. def GetValidArg(self, func):
  4725. """Overridden from Argument."""
  4726. return "shared_memory_id_, shared_memory_offset_"
  4727. def GetValidGLArg(self, func):
  4728. """Overridden from Argument."""
  4729. return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
  4730. def GetNumInvalidValues(self, _func):
  4731. """Overridden from Argument."""
  4732. return 2
  4733. def GetInvalidArg(self, index):
  4734. """Overridden from Argument."""
  4735. if index == 0:
  4736. return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
  4737. return ("shared_memory_id_, kInvalidSharedMemoryOffset",
  4738. "kOutOfBounds", None)
  4739. def GetLogArg(self):
  4740. """Overridden from Argument."""
  4741. return "static_cast<const void*>(%s)" % self.name
  4742. def AddCmdArgs(self, args):
  4743. """Overridden from Argument."""
  4744. args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
  4745. args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
  4746. def WriteGetCode(self, f):
  4747. """Overridden from Argument."""
  4748. f.write(
  4749. " %s %s = GetSharedMemoryAs<%s>(\n" %
  4750. (self.type, self.name, self.type))
  4751. f.write(
  4752. " c.%s_shm_id, c.%s_shm_offset, %s);\n" %
  4753. (self.name, self.name, self.GetReservedSizeId()))
  4754. def WriteValidationCode(self, f, func):
  4755. """Overridden from Argument."""
  4756. if self.optional:
  4757. return
  4758. f.write(" if (%s == nullptr) {\n" % self.name)
  4759. f.write(" return error::kOutOfBounds;\n")
  4760. f.write(" }\n")
  4761. def GetImmediateVersion(self):
  4762. """Overridden from Argument."""
  4763. return ImmediatePointerArgument(self.name, self.type)
  4764. def GetBucketVersion(self):
  4765. """Overridden from Argument."""
  4766. if self.type.find('char') >= 0:
  4767. if self.IsPointer2D():
  4768. return InputStringArrayBucketArgument(self.name, self.type)
  4769. return InputStringBucketArgument(self.name, self.type)
  4770. return BucketPointerArgument(self.name, self.type)
  4771. def WriteDestinationInitalizationValidation(self, f, func):
  4772. """Overridden from Argument."""
  4773. self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
  4774. class BucketPointerArgument(PointerArgument):
  4775. """A class that represents an bucket argument to a function."""
  4776. def AddCmdArgs(self, args):
  4777. """Overridden from Argument."""
  4778. def WriteGetCode(self, f):
  4779. """Overridden from Argument."""
  4780. f.write(
  4781. " %s %s = bucket->GetData(0, %s);\n" %
  4782. (self.type, self.name, self.GetReservedSizeId()))
  4783. def WriteValidationCode(self, f, func):
  4784. """Overridden from Argument."""
  4785. def GetImmediateVersion(self):
  4786. """Overridden from Argument."""
  4787. return None
  4788. def WriteDestinationInitalizationValidation(self, f, func):
  4789. """Overridden from Argument."""
  4790. self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
  4791. def GetLogArg(self):
  4792. """Overridden from Argument."""
  4793. return "static_cast<const void*>(%s)" % self.name
  4794. class InputStringBucketArgument(Argument):
  4795. """A string input argument where the string is passed in a bucket."""
  4796. def __init__(self, name, _type):
  4797. Argument.__init__(self, name + "_bucket_id", "uint32_t")
  4798. def IsPointer(self):
  4799. """Overridden from Argument."""
  4800. return True
  4801. def IsPointer2D(self):
  4802. """Overridden from Argument."""
  4803. return False
  4804. class InputStringArrayBucketArgument(Argument):
  4805. """A string array input argument where the strings are passed in a bucket."""
  4806. def __init__(self, name, _type):
  4807. Argument.__init__(self, name + "_bucket_id", "uint32_t")
  4808. self._original_name = name
  4809. def WriteGetCode(self, f):
  4810. """Overridden from Argument."""
  4811. code = """
  4812. Bucket* bucket = GetBucket(c.%(name)s);
  4813. if (!bucket) {
  4814. return error::kInvalidArguments;
  4815. }
  4816. GLsizei count = 0;
  4817. std::vector<char*> strs;
  4818. std::vector<GLint> len;
  4819. if (!bucket->GetAsStrings(&count, &strs, &len)) {
  4820. return error::kInvalidArguments;
  4821. }
  4822. const char** %(original_name)s =
  4823. strs.size() > 0 ? const_cast<const char**>(&strs[0]) : nullptr;
  4824. const GLint* length =
  4825. len.size() > 0 ? const_cast<const GLint*>(&len[0]) : nullptr;
  4826. (void)length;
  4827. """
  4828. f.write(code % {
  4829. 'name': self.name,
  4830. 'original_name': self._original_name,
  4831. })
  4832. def GetValidArg(self, func):
  4833. return "kNameBucketId"
  4834. def GetValidGLArg(self, func):
  4835. return "_"
  4836. def IsPointer(self):
  4837. """Overridden from Argument."""
  4838. return True
  4839. def IsPointer2D(self):
  4840. """Overridden from Argument."""
  4841. return True
  4842. class ResourceIdArgument(Argument):
  4843. """A class that represents a resource id argument to a function."""
  4844. def __init__(self, name, arg_type, arg_default):
  4845. match = re.match("(GLid\w+)", arg_type)
  4846. self.resource_type = match.group(1)[4:]
  4847. if self.resource_type == "Sync":
  4848. arg_type = arg_type.replace(match.group(1), "GLsync")
  4849. else:
  4850. arg_type = arg_type.replace(match.group(1), "GLuint")
  4851. Argument.__init__(self, name, arg_type, arg_default)
  4852. def WriteGetCode(self, f):
  4853. """Overridden from Argument."""
  4854. if self.type == "GLsync":
  4855. my_type = "GLuint"
  4856. else:
  4857. my_type = self.type
  4858. f.write(" %s %s = %s;\n" % (my_type, self.name, self.GetArgAccessor('c')))
  4859. def GetValidArg(self, func):
  4860. return "client_%s_id_" % self.resource_type.lower()
  4861. def GetValidGLArg(self, func):
  4862. if self.resource_type == "Sync":
  4863. return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
  4864. return "kService%sId" % self.resource_type
  4865. class ResourceIdBindArgument(Argument):
  4866. """Represents a resource id argument to a bind function."""
  4867. def __init__(self, name, arg_type, arg_default):
  4868. match = re.match("(GLidBind\w+)", arg_type)
  4869. self.resource_type = match.group(1)[8:]
  4870. arg_type = arg_type.replace(match.group(1), "GLuint")
  4871. Argument.__init__(self, name, arg_type, arg_default)
  4872. def WriteGetCode(self, f):
  4873. """Overridden from Argument."""
  4874. code = """ %(type)s %(name)s = c.%(name)s;
  4875. """
  4876. f.write(code % {'type': self.type, 'name': self.name})
  4877. def GetValidArg(self, func):
  4878. return "client_%s_id_" % self.resource_type.lower()
  4879. def GetValidGLArg(self, func):
  4880. return "kService%sId" % self.resource_type
  4881. class ResourceIdZeroArgument(Argument):
  4882. """Represents a resource id argument to a function that can be zero."""
  4883. def __init__(self, name, arg_type, arg_default):
  4884. match = re.match("(GLidZero\w+)", arg_type)
  4885. self.resource_type = match.group(1)[8:]
  4886. arg_type = arg_type.replace(match.group(1), "GLuint")
  4887. Argument.__init__(self, name, arg_type, arg_default)
  4888. def WriteGetCode(self, f):
  4889. """Overridden from Argument."""
  4890. f.write(" %s %s = %s;\n" % (self.type, self.name,
  4891. self.GetArgAccessor('c')))
  4892. def GetValidArg(self, func):
  4893. return "client_%s_id_" % self.resource_type.lower()
  4894. def GetValidGLArg(self, func):
  4895. return "kService%sId" % self.resource_type
  4896. def GetNumInvalidValues(self, _func):
  4897. """returns the number of invalid values to be tested."""
  4898. return 1
  4899. def GetInvalidArg(self, _index):
  4900. """returns an invalid value by index."""
  4901. return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
  4902. class Int64Argument(Argument):
  4903. """Represents a GLuint64 argument which splits up into 2 uint32_t items."""
  4904. def __init__(self, name, arg_type, arg_default):
  4905. Argument.__init__(self, name, arg_type, arg_default)
  4906. def GetArgAccessor(self, cmd_struct_name):
  4907. return "%s.%s()" % (cmd_struct_name, self.name)
  4908. def WriteArgAccessor(self, f):
  4909. """Writes specialized accessor for compound members."""
  4910. f.write(" %s %s() const volatile {\n" % (self.type, self.name))
  4911. f.write(" return static_cast<%s>(\n" % self.type)
  4912. f.write(" %sGLES2Util::MapTwoUint32ToUint64(\n" % _Namespace())
  4913. f.write(" %s_0,\n" % self.name)
  4914. f.write(" %s_1));\n" % self.name)
  4915. f.write(" }\n")
  4916. f.write("\n")
  4917. def WriteGetCode(self, f):
  4918. """Writes the code to get an argument from a command structure."""
  4919. f.write(" %s %s = c.%s();\n" % (self.type, self.name, self.name))
  4920. def WriteSetCode(self, f, indent, var):
  4921. indent_str = ' ' * indent
  4922. f.write("%s%sGLES2Util::MapUint64ToTwoUint32(static_cast<uint64_t>(%s),\n" %
  4923. (indent_str, _Namespace(), var))
  4924. f.write("%s &%s_0,\n" %
  4925. (indent_str, self.name))
  4926. f.write("%s &%s_1);\n" %
  4927. (indent_str, self.name))
  4928. class Function():
  4929. """A class that represents a function."""
  4930. def __init__(self, name, info, named_type_info, type_handlers):
  4931. self.name = name
  4932. self.named_type_info = named_type_info
  4933. self.prefixed_name = info['prefixed_name']
  4934. self.original_name = info['original_name']
  4935. self.original_args = self.ParseArgs(info['original_args'])
  4936. if 'cmd_args' in info:
  4937. self.args_for_cmds = self.ParseArgs(info['cmd_args'])
  4938. else:
  4939. self.args_for_cmds = self.original_args[:]
  4940. self.passthrough_service_doer_args = self.original_args[:]
  4941. if 'size_args' in info:
  4942. self.size_args = info['size_args']
  4943. else:
  4944. self.size_args = {}
  4945. self.return_type = info['return_type']
  4946. if self.return_type != 'void':
  4947. self.return_arg = CreateArg(info['return_type'] + " result",
  4948. named_type_info)
  4949. else:
  4950. self.return_arg = None
  4951. self.num_pointer_args = sum(
  4952. [1 for arg in self.args_for_cmds if arg.IsPointer()])
  4953. if self.num_pointer_args > 0:
  4954. for arg in reversed(self.original_args):
  4955. if arg.IsPointer():
  4956. self.last_original_pointer_arg = arg
  4957. break
  4958. else:
  4959. self.last_original_pointer_arg = None
  4960. self.info = info
  4961. self.type_handler = type_handlers[info['type']]
  4962. self.can_auto_generate = (self.num_pointer_args == 0 and
  4963. info['return_type'] == "void")
  4964. # Satisfy pylint warning attribute-defined-outside-init.
  4965. #
  4966. # self.cmd_args is typically set in InitFunction, but that method may be
  4967. # overriden.
  4968. self.cmd_args = []
  4969. self.InitFunction()
  4970. def ParseArgs(self, arg_string):
  4971. """Parses a function arg string."""
  4972. args = []
  4973. parts = arg_string.split(',')
  4974. for p in parts:
  4975. arg = CreateArg(p, self.named_type_info)
  4976. if arg:
  4977. args.append(arg)
  4978. return args
  4979. def IsType(self, type_name):
  4980. """Returns true if function is a certain type."""
  4981. return self.info['type'] == type_name
  4982. def InitFunction(self):
  4983. """Creates command args and calls the init function for the type handler.
  4984. Creates argument lists for command buffer commands, eg. self.cmd_args and
  4985. self.init_args.
  4986. Calls the type function initialization.
  4987. Override to create different kind of command buffer command argument lists.
  4988. """
  4989. self.cmd_args = []
  4990. for arg in self.args_for_cmds:
  4991. arg.AddCmdArgs(self.cmd_args)
  4992. self.init_args = []
  4993. for arg in self.args_for_cmds:
  4994. arg.AddInitArgs(self.init_args)
  4995. if self.return_arg:
  4996. self.init_args.append(self.return_arg)
  4997. self.type_handler.InitFunction(self)
  4998. def IsImmediate(self):
  4999. """Returns whether the function is immediate data function or not."""
  5000. return False
  5001. def IsES3(self):
  5002. """Returns whether the function requires an ES3 context or not."""
  5003. return self.GetInfo('es3', False)
  5004. def IsES31(self):
  5005. """Returns whether the function requires an ES31 context or not."""
  5006. return self.GetInfo('es31', False)
  5007. def GetInfo(self, name, default = None):
  5008. """Returns a value from the function info for this function."""
  5009. if name in self.info:
  5010. return self.info[name]
  5011. return default
  5012. def GetValidArg(self, arg):
  5013. """Gets a valid argument value for the parameter arg from the function info
  5014. if one exists."""
  5015. try:
  5016. index = self.GetOriginalArgs().index(arg)
  5017. except ValueError:
  5018. return None
  5019. valid_args = self.GetInfo('valid_args')
  5020. if valid_args and str(index) in valid_args:
  5021. return valid_args[str(index)]
  5022. return None
  5023. def AddInfo(self, name, value):
  5024. """Adds an info."""
  5025. self.info[name] = value
  5026. def IsExtension(self):
  5027. return self.GetInfo('extension') or self.GetInfo('extension_flag')
  5028. def IsCoreGLFunction(self):
  5029. return (not self.IsExtension() and
  5030. not self.GetInfo('pepper_interface') and
  5031. not self.IsES3() and
  5032. not self.IsES31())
  5033. def InPepperInterface(self, interface):
  5034. ext = self.GetInfo('pepper_interface')
  5035. if not interface.GetName():
  5036. return self.IsCoreGLFunction()
  5037. return ext == interface.GetName()
  5038. def InAnyPepperExtension(self):
  5039. return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
  5040. def GetErrorReturnString(self):
  5041. if self.GetInfo("error_return"):
  5042. return self.GetInfo("error_return")
  5043. if self.return_type == "GLboolean":
  5044. return "GL_FALSE"
  5045. if "*" in self.return_type:
  5046. return "nullptr"
  5047. return "0"
  5048. def GetGLFunctionName(self):
  5049. """Gets the function to call to execute GL for this command."""
  5050. if self.GetInfo('decoder_func'):
  5051. return self.GetInfo('decoder_func')
  5052. return "api()->gl%sFn" % self.original_name
  5053. def GetGLTestFunctionName(self):
  5054. gl_func_name = self.GetInfo('gl_test_func')
  5055. if gl_func_name == None:
  5056. gl_func_name = self.GetGLFunctionName()
  5057. if gl_func_name.startswith("gl"):
  5058. gl_func_name = gl_func_name[2:]
  5059. else:
  5060. gl_func_name = self.original_name
  5061. return gl_func_name
  5062. def GetDataTransferMethods(self):
  5063. return self.GetInfo('data_transfer_methods',
  5064. ['immediate' if self.num_pointer_args == 1 else 'shm'])
  5065. def AddCmdArg(self, arg):
  5066. """Adds a cmd argument to this function."""
  5067. self.cmd_args.append(arg)
  5068. def GetCmdArgs(self):
  5069. """Gets the command args for this function."""
  5070. return self.cmd_args
  5071. def ClearCmdArgs(self):
  5072. """Clears the command args for this function."""
  5073. self.cmd_args = []
  5074. def GetCmdConstants(self):
  5075. """Gets the constants for this function."""
  5076. return [arg for arg in self.args_for_cmds if arg.IsConstant()]
  5077. def GetInitArgs(self):
  5078. """Gets the init args for this function."""
  5079. return self.init_args
  5080. def GetOriginalArgs(self):
  5081. """Gets the original arguments to this function."""
  5082. return self.original_args
  5083. def GetPassthroughServiceDoerArgs(self):
  5084. """Gets the original arguments to this function."""
  5085. return self.passthrough_service_doer_args
  5086. def GetLastOriginalArg(self):
  5087. """Gets the last original argument to this function."""
  5088. return self.original_args[len(self.original_args) - 1]
  5089. def GetLastOriginalPointerArg(self):
  5090. return self.last_original_pointer_arg
  5091. def GetResourceIdArg(self):
  5092. for arg in self.original_args:
  5093. if hasattr(arg, 'resource_type'):
  5094. return arg
  5095. return None
  5096. def _MaybePrependComma(self, arg_string, add_comma):
  5097. """Adds a comma if arg_string is not empty and add_comma is true."""
  5098. comma = ""
  5099. if add_comma and len(arg_string):
  5100. comma = ", "
  5101. return "%s%s" % (comma, arg_string)
  5102. def MakeTypedOriginalArgString(self, prefix, add_comma = False,
  5103. add_default = False):
  5104. """Gets a list of arguments as they are in GL."""
  5105. args = self.GetOriginalArgs()
  5106. def ArgToString(arg):
  5107. tmp = [arg.type, prefix + arg.name]
  5108. if add_default and arg.default:
  5109. tmp.append("=")
  5110. tmp.append(arg.default)
  5111. return " ".join(tmp)
  5112. arg_string = ", ".join([ArgToString(arg) for arg in args])
  5113. return self._MaybePrependComma(arg_string, add_comma)
  5114. def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
  5115. """Gets the list of arguments as they are in GL."""
  5116. args = self.GetOriginalArgs()
  5117. arg_string = separator.join(
  5118. ["%s%s" % (prefix, arg.name) for arg in args])
  5119. return self._MaybePrependComma(arg_string, add_comma)
  5120. def MakePassthroughServiceDoerArgString(self, prefix, add_comma = False,
  5121. separator = ", "):
  5122. """Gets the list of arguments as they are in used by the passthrough
  5123. service doer function."""
  5124. args = self.GetPassthroughServiceDoerArgs()
  5125. arg_string = separator.join(
  5126. ["%s%s" % (prefix, arg.name) for arg in args])
  5127. return self._MaybePrependComma(arg_string, add_comma)
  5128. def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
  5129. """Gets a list of GL arguments after removing unneeded arguments."""
  5130. args = self.GetOriginalArgs()
  5131. arg_string = separator.join(
  5132. ["%s%s" % (prefix, arg.name)
  5133. for arg in args if not arg.IsConstant()])
  5134. return self._MaybePrependComma(arg_string, add_comma)
  5135. def MakeTypedPepperArgString(self, prefix):
  5136. """Gets a list of arguments as they need to be for Pepper."""
  5137. if self.GetInfo("pepper_args"):
  5138. return self.GetInfo("pepper_args")
  5139. return self.MakeTypedOriginalArgString(prefix, False)
  5140. def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
  5141. """Converts a C type name to the corresponding Pepper IDL type."""
  5142. idltype = {
  5143. 'char*': '[out] str_t',
  5144. 'const GLchar* const*': '[out] cstr_t',
  5145. 'const char*': 'cstr_t',
  5146. 'const void*': 'mem_t',
  5147. 'void*': '[out] mem_t',
  5148. 'void**': '[out] mem_ptr_t',
  5149. }.get(ctype, ctype)
  5150. # We use "GLxxx_ptr_t" for "GLxxx*".
  5151. matched = re.match(r'(const )?(GL\w+)\*$', ctype)
  5152. if matched:
  5153. idltype = matched.group(2) + '_ptr_t'
  5154. if not matched.group(1):
  5155. idltype = '[out] ' + idltype
  5156. # If an in/out specifier is not specified yet, prepend [in].
  5157. if idltype[0] != '[':
  5158. idltype = '[in] ' + idltype
  5159. # Strip the in/out specifier for a return type.
  5160. if is_for_return_type:
  5161. idltype = re.sub(r'\[\w+\] ', '', idltype)
  5162. return idltype
  5163. def MakeTypedPepperIdlArgStrings(self):
  5164. """Gets a list of arguments as they need to be for Pepper IDL."""
  5165. args = self.GetOriginalArgs()
  5166. return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
  5167. for arg in args]
  5168. def GetPepperName(self):
  5169. if self.GetInfo("pepper_name"):
  5170. return self.GetInfo("pepper_name")
  5171. return self.name
  5172. def MakeTypedCmdArgString(self, prefix, add_comma = False):
  5173. """Gets a typed list of arguments as they need to be for command buffers."""
  5174. args = self.GetCmdArgs()
  5175. arg_string = ", ".join(
  5176. ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
  5177. return self._MaybePrependComma(arg_string, add_comma)
  5178. def MakeCmdArgString(self, prefix, add_comma = False):
  5179. """Gets the list of arguments as they need to be for command buffers."""
  5180. args = self.GetCmdArgs()
  5181. arg_string = ", ".join(
  5182. ["%s%s" % (prefix, arg.name) for arg in args])
  5183. return self._MaybePrependComma(arg_string, add_comma)
  5184. def MakeTypedInitString(self, prefix, add_comma = False):
  5185. """Gets a typed list of arguments as they need to be for cmd Init/Set."""
  5186. args = self.GetInitArgs()
  5187. arg_string = ", ".join(
  5188. ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
  5189. return self._MaybePrependComma(arg_string, add_comma)
  5190. def MakeInitString(self, prefix, add_comma = False):
  5191. """Gets the list of arguments as they need to be for cmd Init/Set."""
  5192. args = self.GetInitArgs()
  5193. arg_string = ", ".join(
  5194. ["%s%s" % (prefix, arg.name) for arg in args])
  5195. return self._MaybePrependComma(arg_string, add_comma)
  5196. def MakeLogArgString(self):
  5197. """Makes a string of the arguments for the LOG macros"""
  5198. args = self.GetOriginalArgs()
  5199. return ' << ", " << '.join([arg.GetLogArg() for arg in args])
  5200. def WriteHandlerValidation(self, f):
  5201. """Writes validation code for the function."""
  5202. for arg in self.GetOriginalArgs():
  5203. arg.WriteValidationCode(f, self)
  5204. self.WriteValidationCode(f)
  5205. def WriteQueueTraceEvent(self, f):
  5206. if self.GetInfo("trace_queueing_flow", False):
  5207. trace = 'TRACE_DISABLED_BY_DEFAULT("gpu_cmd_queue")'
  5208. f.write("""if (c.trace_id) {
  5209. TRACE_EVENT_WITH_FLOW0(%s, "CommandBufferQueue",
  5210. c.trace_id, TRACE_EVENT_FLAG_FLOW_IN);\n}""" % trace)
  5211. def WritePassthroughHandlerValidation(self, f):
  5212. """Writes validation code for the function."""
  5213. for arg in self.GetOriginalArgs():
  5214. arg.WritePassthroughValidationCode(f, self)
  5215. def WriteHandlerImplementation(self, f):
  5216. """Writes the handler implementation for this command."""
  5217. self.type_handler.WriteHandlerImplementation(self, f)
  5218. def WriteValidationCode(self, f):
  5219. """Writes the validation code for a command."""
  5220. def WriteCmdFlag(self, f):
  5221. """Writes the cmd cmd_flags constant."""
  5222. # By default trace only at the highest level 3.
  5223. trace_level = int(self.GetInfo('trace_level', default = 3))
  5224. if trace_level not in range(0, 4):
  5225. raise KeyError("Unhandled trace_level: %d" % trace_level)
  5226. cmd_flags = ('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
  5227. f.write(" static const uint8_t cmd_flags = %s;\n" % cmd_flags)
  5228. def WriteCmdArgFlag(self, f):
  5229. """Writes the cmd kArgFlags constant."""
  5230. f.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
  5231. def WriteCmdComputeSize(self, f):
  5232. """Writes the ComputeSize function for the command."""
  5233. f.write(" static uint32_t ComputeSize() {\n")
  5234. f.write(
  5235. " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
  5236. f.write(" }\n")
  5237. f.write("\n")
  5238. def WriteCmdSetHeader(self, f):
  5239. """Writes the cmd's SetHeader function."""
  5240. f.write(" void SetHeader() {\n")
  5241. f.write(" header.SetCmd<ValueType>();\n")
  5242. f.write(" }\n")
  5243. f.write("\n")
  5244. def WriteCmdInit(self, f):
  5245. """Writes the cmd's Init function."""
  5246. f.write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
  5247. f.write(" SetHeader();\n")
  5248. args = self.GetCmdArgs()
  5249. for arg in args:
  5250. arg.WriteSetCode(f, 4, '_%s' % arg.name)
  5251. if self.GetInfo("trace_queueing_flow", False):
  5252. trace = 'TRACE_DISABLED_BY_DEFAULT("gpu_cmd_queue")'
  5253. f.write('bool is_tracing = false;')
  5254. f.write('TRACE_EVENT_CATEGORY_GROUP_ENABLED(%s, &is_tracing);' % trace)
  5255. f.write('if (is_tracing) {')
  5256. f.write(' trace_id = base::RandUint64();')
  5257. f.write('TRACE_EVENT_WITH_FLOW1(%s, "CommandBufferQueue",' % trace)
  5258. f.write('trace_id, TRACE_EVENT_FLAG_FLOW_OUT,')
  5259. f.write('"command", "%s");' % self.name)
  5260. f.write('} else {\n trace_id = 0;\n}\n');
  5261. f.write("}\n")
  5262. f.write("\n")
  5263. def WriteCmdSet(self, f):
  5264. """Writes the cmd's Set function."""
  5265. copy_args = self.MakeCmdArgString("_", False)
  5266. f.write(" void* Set(void* cmd%s) {\n" %
  5267. self.MakeTypedCmdArgString("_", True))
  5268. f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
  5269. f.write(" return NextCmdAddress<ValueType>(cmd);\n")
  5270. f.write(" }\n")
  5271. f.write("\n")
  5272. def WriteArgAccessors(self, f):
  5273. """Writes the cmd's accessor functions."""
  5274. for arg in self.GetCmdArgs():
  5275. arg.WriteArgAccessor(f)
  5276. def WriteStruct(self, f):
  5277. self.type_handler.WriteStruct(self, f)
  5278. def WriteDocs(self, f):
  5279. self.type_handler.WriteDocs(self, f)
  5280. def WriteCmdHelper(self, f):
  5281. """Writes the cmd's helper."""
  5282. self.type_handler.WriteCmdHelper(self, f)
  5283. def WriteServiceImplementation(self, f):
  5284. """Writes the service implementation for a command."""
  5285. self.type_handler.WriteServiceImplementation(self, f)
  5286. def WritePassthroughServiceImplementation(self, f):
  5287. """Writes the service implementation for a command."""
  5288. self.type_handler.WritePassthroughServiceImplementation(self, f)
  5289. def WriteServiceUnitTest(self, f, *extras):
  5290. """Writes the service implementation for a command."""
  5291. self.type_handler.WriteServiceUnitTest(self, f, *extras)
  5292. def WriteGLES2CLibImplementation(self, f):
  5293. """Writes the GLES2 C Lib Implemention."""
  5294. self.type_handler.WriteGLES2CLibImplementation(self, f)
  5295. def WriteGLES2InterfaceHeader(self, f):
  5296. """Writes the GLES2 Interface declaration."""
  5297. self.type_handler.WriteGLES2InterfaceHeader(self, f)
  5298. def WriteGLES2InterfaceStub(self, f):
  5299. """Writes the GLES2 Interface Stub declaration."""
  5300. self.type_handler.WriteGLES2InterfaceStub(self, f)
  5301. def WriteGLES2InterfaceStubImpl(self, f):
  5302. """Writes the GLES2 Interface Stub declaration."""
  5303. self.type_handler.WriteGLES2InterfaceStubImpl(self, f)
  5304. def WriteGLES2ImplementationHeader(self, f):
  5305. """Writes the GLES2 Implemention declaration."""
  5306. self.type_handler.WriteGLES2ImplementationHeader(self, f)
  5307. def WriteGLES2Implementation(self, f):
  5308. """Writes the GLES2 Implemention definition."""
  5309. self.type_handler.WriteGLES2Implementation(self, f)
  5310. def WriteGLES2TraceImplementationHeader(self, f):
  5311. """Writes the GLES2 Trace Implemention declaration."""
  5312. self.type_handler.WriteGLES2TraceImplementationHeader(self, f)
  5313. def WriteGLES2TraceImplementation(self, f):
  5314. """Writes the GLES2 Trace Implemention definition."""
  5315. self.type_handler.WriteGLES2TraceImplementation(self, f)
  5316. def WriteGLES2Header(self, f):
  5317. """Writes the GLES2 Implemention unit test."""
  5318. self.type_handler.WriteGLES2Header(self, f)
  5319. def WriteGLES2ImplementationUnitTest(self, f):
  5320. """Writes the GLES2 Implemention unit test."""
  5321. self.type_handler.WriteGLES2ImplementationUnitTest(self, f)
  5322. def WriteDestinationInitalizationValidation(self, f):
  5323. """Writes the client side destintion initialization validation."""
  5324. self.type_handler.WriteDestinationInitalizationValidation(self, f)
  5325. def WriteFormatTest(self, f):
  5326. """Writes the cmd's format test."""
  5327. self.type_handler.WriteFormatTest(self, f)
  5328. class PepperInterface():
  5329. """A class that represents a function."""
  5330. def __init__(self, info):
  5331. self.name = info["name"]
  5332. self.dev = info["dev"]
  5333. def GetName(self):
  5334. return self.name
  5335. def GetInterfaceName(self):
  5336. upperint = ""
  5337. dev = ""
  5338. if self.name:
  5339. upperint = "_" + self.name.upper()
  5340. if self.dev:
  5341. dev = "_DEV"
  5342. return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
  5343. def GetStructName(self):
  5344. dev = ""
  5345. if self.dev:
  5346. dev = "_Dev"
  5347. return "PPB_OpenGLES2%s%s" % (self.name, dev)
  5348. class ImmediateFunction(Function):
  5349. """A class that represents an immediate function command."""
  5350. def __init__(self, func, type_handlers):
  5351. Function.__init__(
  5352. self,
  5353. "%sImmediate" % func.name,
  5354. func.info,
  5355. func.named_type_info,
  5356. type_handlers)
  5357. def InitFunction(self):
  5358. # Override args in original_args and args_for_cmds with immediate versions
  5359. # of the args.
  5360. new_original_args = []
  5361. for arg in self.original_args:
  5362. new_arg = arg.GetImmediateVersion()
  5363. if new_arg:
  5364. new_original_args.append(new_arg)
  5365. self.original_args = new_original_args
  5366. new_args_for_cmds = []
  5367. for arg in self.args_for_cmds:
  5368. new_arg = arg.GetImmediateVersion()
  5369. if new_arg:
  5370. new_args_for_cmds.append(new_arg)
  5371. self.args_for_cmds = new_args_for_cmds
  5372. Function.InitFunction(self)
  5373. def IsImmediate(self):
  5374. return True
  5375. def WriteServiceImplementation(self, f):
  5376. """Overridden from Function"""
  5377. self.type_handler.WriteImmediateServiceImplementation(self, f)
  5378. def WritePassthroughServiceImplementation(self, f):
  5379. """Overridden from Function"""
  5380. self.type_handler.WritePassthroughImmediateServiceImplementation(self, f)
  5381. def WriteHandlerImplementation(self, f):
  5382. """Overridden from Function"""
  5383. self.type_handler.WriteImmediateHandlerImplementation(self, f)
  5384. def WriteServiceUnitTest(self, f, *extras):
  5385. """Writes the service implementation for a command."""
  5386. self.type_handler.WriteImmediateServiceUnitTest(self, f, *extras)
  5387. def WriteValidationCode(self, f):
  5388. """Overridden from Function"""
  5389. self.type_handler.WriteImmediateValidationCode(self, f)
  5390. def WriteCmdArgFlag(self, f):
  5391. """Overridden from Function"""
  5392. f.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
  5393. def WriteCmdComputeSize(self, f):
  5394. """Overridden from Function"""
  5395. self.type_handler.WriteImmediateCmdComputeSize(self, f)
  5396. def WriteCmdSetHeader(self, f):
  5397. """Overridden from Function"""
  5398. self.type_handler.WriteImmediateCmdSetHeader(self, f)
  5399. def WriteCmdInit(self, f):
  5400. """Overridden from Function"""
  5401. self.type_handler.WriteImmediateCmdInit(self, f)
  5402. def WriteCmdSet(self, f):
  5403. """Overridden from Function"""
  5404. self.type_handler.WriteImmediateCmdSet(self, f)
  5405. def WriteCmdHelper(self, f):
  5406. """Overridden from Function"""
  5407. self.type_handler.WriteImmediateCmdHelper(self, f)
  5408. def WriteFormatTest(self, f):
  5409. """Overridden from Function"""
  5410. self.type_handler.WriteImmediateFormatTest(self, f)
  5411. class BucketFunction(Function):
  5412. """A class that represnets a bucket version of a function command."""
  5413. def __init__(self, func, type_handlers):
  5414. Function.__init__(
  5415. self,
  5416. "%sBucket" % func.name,
  5417. func.info,
  5418. func.named_type_info,
  5419. type_handlers)
  5420. def InitFunction(self):
  5421. # Override args in original_args and args_for_cmds with bucket versions
  5422. # of the args.
  5423. new_original_args = []
  5424. for arg in self.original_args:
  5425. new_arg = arg.GetBucketVersion()
  5426. if new_arg:
  5427. new_original_args.append(new_arg)
  5428. self.original_args = new_original_args
  5429. new_args_for_cmds = []
  5430. for arg in self.args_for_cmds:
  5431. new_arg = arg.GetBucketVersion()
  5432. if new_arg:
  5433. new_args_for_cmds.append(new_arg)
  5434. self.args_for_cmds = new_args_for_cmds
  5435. Function.InitFunction(self)
  5436. def WriteServiceImplementation(self, f):
  5437. """Overridden from Function"""
  5438. self.type_handler.WriteBucketServiceImplementation(self, f)
  5439. def WritePassthroughServiceImplementation(self, f):
  5440. """Overridden from Function"""
  5441. self.type_handler.WritePassthroughBucketServiceImplementation(self, f)
  5442. def WriteHandlerImplementation(self, f):
  5443. """Overridden from Function"""
  5444. self.type_handler.WriteBucketHandlerImplementation(self, f)
  5445. def WriteServiceUnitTest(self, f, *extras):
  5446. """Overridden from Function"""
  5447. self.type_handler.WriteBucketServiceUnitTest(self, f, *extras)
  5448. def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
  5449. """Overridden from Function"""
  5450. args = self.GetOriginalArgs()
  5451. arg_string = separator.join(
  5452. ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
  5453. else arg.name) for arg in args])
  5454. return super()._MaybePrependComma(arg_string, add_comma)
  5455. def CreateArg(arg_string, named_type_info):
  5456. """Convert string argument to an Argument class that represents it.
  5457. The parameter 'arg_string' can be a single argument to a GL function,
  5458. something like 'GLsizei width' or 'const GLenum* bufs'. Returns an instance of
  5459. the Argument class, or None if 'arg_string' is 'void'.
  5460. """
  5461. if arg_string == 'void':
  5462. return None
  5463. arg_string = arg_string.strip()
  5464. arg_default = None
  5465. if '=' in arg_string:
  5466. arg_string, arg_default = arg_string.split('=')
  5467. arg_default = arg_default.strip()
  5468. arg_parts = arg_string.split()
  5469. assert len(arg_parts) > 1
  5470. arg_name = arg_parts[-1]
  5471. arg_type = " ".join(arg_parts[0:-1])
  5472. t = arg_parts[0] # only the first part of arg_type
  5473. # Is this a pointer argument?
  5474. if arg_string.find('*') >= 0:
  5475. return PointerArgument(arg_name, arg_type, arg_default)
  5476. if t.startswith('EnumClass'):
  5477. return EnumClassArgument(arg_name, arg_type, named_type_info, arg_default)
  5478. # Is this a resource argument? Must come after pointer check.
  5479. if t.startswith('GLidBind'):
  5480. return ResourceIdBindArgument(arg_name, arg_type, arg_default)
  5481. if t.startswith('GLidZero'):
  5482. return ResourceIdZeroArgument(arg_name, arg_type, arg_default)
  5483. if t.startswith('GLid'):
  5484. return ResourceIdArgument(arg_name, arg_type, arg_default)
  5485. if t.startswith('GLenum') and t !='GLenum':
  5486. return EnumArgument(arg_name, arg_type, named_type_info, arg_default)
  5487. if t.startswith('GLbitfield') and t != 'GLbitfield':
  5488. return BitFieldArgument(arg_name, arg_type, named_type_info, arg_default)
  5489. if t.startswith('GLboolean'):
  5490. return GLBooleanArgument(arg_name, arg_type, arg_default)
  5491. if t.startswith('GLintUniformLocation'):
  5492. return UniformLocationArgument(arg_name, arg_default)
  5493. if (t.startswith('GLint') and t != 'GLint' and
  5494. not t.startswith('GLintptr')):
  5495. return IntArgument(arg_name, arg_type, named_type_info, arg_default)
  5496. if t == 'bool':
  5497. return BoolArgument(arg_name, arg_type, arg_default)
  5498. if t in ('GLsizeiNotNegative', 'GLintptrNotNegative'):
  5499. return SizeNotNegativeArgument(arg_name, t.replace('NotNegative', ''),
  5500. arg_default)
  5501. if t.startswith('GLsize'):
  5502. return SizeArgument(arg_name, arg_type, arg_default)
  5503. if t in ('GLuint64', 'GLint64'):
  5504. return Int64Argument(arg_name, arg_type, arg_default)
  5505. return Argument(arg_name, arg_type, arg_default)
  5506. class GLGenerator():
  5507. """A class to generate GL command buffers."""
  5508. _whitespace_re = re.compile(r'^\w*$')
  5509. _comment_re = re.compile(r'^//.*$')
  5510. _function_re = re.compile(r'^GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);$')
  5511. def __init__(self, verbose, year, function_info, named_type_info,
  5512. chromium_root_dir):
  5513. self.original_functions = []
  5514. self.functions = []
  5515. self.chromium_root_dir = chromium_root_dir
  5516. self.verbose = verbose
  5517. self.year = year
  5518. self.errors = 0
  5519. self.pepper_interfaces = []
  5520. self.interface_info = {}
  5521. self.generated_cpp_filenames = []
  5522. self.function_info = function_info
  5523. self.named_type_info = named_type_info
  5524. self.capability_flags = _CAPABILITY_FLAGS
  5525. self.type_handlers = {
  5526. '': TypeHandler(),
  5527. 'Bind': BindHandler(),
  5528. 'Create': CreateHandler(),
  5529. 'Custom': CustomHandler(),
  5530. 'Data': DataHandler(),
  5531. 'Delete': DeleteHandler(),
  5532. 'DELn': DELnHandler(),
  5533. 'GENn': GENnHandler(),
  5534. 'GETn': GETnHandler(),
  5535. 'GLchar': GLcharHandler(),
  5536. 'GLcharN': GLcharNHandler(),
  5537. 'Is': IsHandler(),
  5538. 'NoCommand': NoCommandHandler(),
  5539. 'PUT': PUTHandler(),
  5540. 'PUTn': PUTnHandler(),
  5541. 'PUTSTR': PUTSTRHandler(),
  5542. 'PUTXn': PUTXnHandler(),
  5543. 'StateSet': StateSetHandler(),
  5544. 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
  5545. 'StateSetFrontBack': StateSetFrontBackHandler(),
  5546. 'StateSetFrontBackSeparate':
  5547. StateSetFrontBackSeparateHandler(),
  5548. 'StateSetNamedParameter': StateSetNamedParameter(),
  5549. 'STRn': STRnHandler(),
  5550. }
  5551. for interface in _PEPPER_INTERFACES:
  5552. interface = PepperInterface(interface)
  5553. self.pepper_interfaces.append(interface)
  5554. self.interface_info[interface.GetName()] = interface
  5555. def AddFunction(self, func):
  5556. """Adds a function."""
  5557. self.functions.append(func)
  5558. def GetFunctionInfo(self, name):
  5559. """Gets a type info for the given function name."""
  5560. if name in self.function_info:
  5561. func_info = self.function_info[name].copy()
  5562. else:
  5563. func_info = {}
  5564. if not 'type' in func_info:
  5565. func_info['type'] = ''
  5566. return func_info
  5567. def Log(self, msg):
  5568. """Prints something if verbose is true."""
  5569. if self.verbose:
  5570. print(msg)
  5571. def Error(self, msg):
  5572. """Prints an error."""
  5573. print("Error: %s" % msg)
  5574. self.errors += 1
  5575. def ParseGLH(self, filename):
  5576. """Parses the cmd_buffer_functions.txt file and extracts the functions"""
  5577. filename = os.path.join(self.chromium_root_dir, filename)
  5578. with open(filename, "r") as f:
  5579. functions = f.read()
  5580. for line in functions.splitlines():
  5581. if self._whitespace_re.match(line) or self._comment_re.match(line):
  5582. continue
  5583. match = self._function_re.match(line)
  5584. if match:
  5585. prefixed_name = match.group(2)
  5586. func_name = prefixed_name[2:]
  5587. func_info = self.GetFunctionInfo(func_name)
  5588. if func_info['type'] == 'Noop':
  5589. continue
  5590. parsed_func_info = {
  5591. 'prefixed_name': prefixed_name,
  5592. 'original_name': func_name,
  5593. 'original_args': match.group(3),
  5594. 'return_type': match.group(1).strip(),
  5595. }
  5596. for k in parsed_func_info:
  5597. if not k in func_info:
  5598. func_info[k] = parsed_func_info[k]
  5599. f = Function(func_name, func_info, self.named_type_info,
  5600. self.type_handlers)
  5601. if not f.GetInfo('internal'):
  5602. self.original_functions.append(f)
  5603. #for arg in f.GetOriginalArgs():
  5604. # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
  5605. # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
  5606. func_type = f.GetInfo('type')
  5607. if func_type != 'NoCommand':
  5608. if f.type_handler.NeedsDataTransferFunction(f):
  5609. methods = f.GetDataTransferMethods()
  5610. if 'immediate' in methods:
  5611. self.AddFunction(ImmediateFunction(f, self.type_handlers))
  5612. if 'bucket' in methods:
  5613. self.AddFunction(BucketFunction(f, self.type_handlers))
  5614. if 'shm' in methods:
  5615. self.AddFunction(f)
  5616. else:
  5617. self.AddFunction(f)
  5618. else:
  5619. self.Error("Could not parse function: %s using regex: %s" %
  5620. (line, self._function_re.pattern))
  5621. self.Log("Auto Generated Functions : %d" %
  5622. len([f for f in self.functions if f.can_auto_generate or
  5623. (not f.IsType('') and not f.IsType('Custom') and
  5624. not f.IsType('Todo'))]))
  5625. funcs = [f for f in self.functions if not f.can_auto_generate and
  5626. (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
  5627. self.Log("Non Auto Generated Functions: %d" % len(funcs))
  5628. for f in funcs:
  5629. self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
  5630. def WriteCommandIds(self, filename):
  5631. """Writes the command buffer format"""
  5632. with CHeaderWriter(filename, self.year) as f:
  5633. f.write("#define %s_COMMAND_LIST(OP) \\\n" % _upper_prefix)
  5634. cmd_id = 256
  5635. for func in self.functions:
  5636. f.write(" %-60s /* %d */ \\\n" %
  5637. ("OP(%s)" % func.name, cmd_id))
  5638. cmd_id += 1
  5639. f.write("\n")
  5640. f.write("enum CommandId {\n")
  5641. f.write(" kOneBeforeStartPoint = cmd::kLastCommonId, "
  5642. "// All %s commands start after this.\n" % _prefix)
  5643. f.write("#define %s_CMD_OP(name) k ## name,\n" % _upper_prefix)
  5644. f.write(" %s_COMMAND_LIST(%s_CMD_OP)\n" %
  5645. (_upper_prefix, _upper_prefix))
  5646. f.write("#undef %s_CMD_OP\n" % _upper_prefix)
  5647. f.write(" kNumCommands,\n")
  5648. f.write(" kFirst%sCommand = kOneBeforeStartPoint + 1\n" % _prefix)
  5649. f.write("};\n")
  5650. f.write("\n")
  5651. self.generated_cpp_filenames.append(filename)
  5652. def WriteFormat(self, filename):
  5653. """Writes the command buffer format"""
  5654. with CHeaderWriter(filename, self.year) as f:
  5655. # Forward declaration of a few enums used in constant argument
  5656. # to avoid including GL header files.
  5657. enum_defines = {}
  5658. if 'FenceSync' in self.function_info:
  5659. enum_defines['GL_SYNC_GPU_COMMANDS_COMPLETE'] = '0x9117'
  5660. if 'ClientWaitSync' in self.function_info:
  5661. enum_defines['GL_SYNC_FLUSH_COMMANDS_BIT'] = '0x00000001'
  5662. f.write('\n')
  5663. for enum in enum_defines:
  5664. f.write("#define %s %s\n" % (enum, enum_defines[enum]))
  5665. f.write('\n')
  5666. for func in self.functions:
  5667. func.WriteStruct(f)
  5668. f.write("\n")
  5669. self.generated_cpp_filenames.append(filename)
  5670. def WriteDocs(self, filename):
  5671. """Writes the command buffer doc version of the commands"""
  5672. with CHeaderWriter(filename, self.year) as f:
  5673. for func in self.functions:
  5674. func.WriteDocs(f)
  5675. f.write("\n")
  5676. self.generated_cpp_filenames.append(filename)
  5677. def WriteFormatTest(self, filename):
  5678. """Writes the command buffer format test."""
  5679. comment = ("// This file contains unit tests for %s commands\n"
  5680. "// It is included by %s_cmd_format_test.cc\n\n" %
  5681. (_lower_prefix, _lower_prefix))
  5682. with CHeaderWriter(filename, self.year, comment) as f:
  5683. for func in self.functions:
  5684. func.WriteFormatTest(f)
  5685. self.generated_cpp_filenames.append(filename)
  5686. def WriteCmdHelperHeader(self, filename):
  5687. """Writes the gles2 command helper."""
  5688. with CHeaderWriter(filename, self.year) as f:
  5689. for func in self.functions:
  5690. func.WriteCmdHelper(f)
  5691. self.generated_cpp_filenames.append(filename)
  5692. def WriteServiceContextStateHeader(self, filename):
  5693. """Writes the service context state header."""
  5694. comment = "// It is included by context_state.h\n"
  5695. with CHeaderWriter(filename, self.year, comment) as f:
  5696. f.write("struct EnableFlags {\n")
  5697. f.write(" EnableFlags();\n")
  5698. for capability in self.capability_flags:
  5699. f.write(" bool %s;\n" % capability['name'])
  5700. f.write(" bool cached_%s;\n" % capability['name'])
  5701. f.write("};\n\n")
  5702. for state_name in sorted(_STATE_INFO.keys()):
  5703. state = _STATE_INFO[state_name]
  5704. for item in state['states']:
  5705. if isinstance(item['default'], list):
  5706. f.write("%s %s[%d];\n" % (item['type'], item['name'],
  5707. len(item['default'])))
  5708. else:
  5709. f.write("%s %s;\n" % (item['type'], item['name']))
  5710. if item.get('cached', False):
  5711. if isinstance(item['default'], list):
  5712. f.write("%s cached_%s[%d];\n" % (item['type'], item['name'],
  5713. len(item['default'])))
  5714. else:
  5715. f.write("%s cached_%s;\n" % (item['type'], item['name']))
  5716. f.write("\n")
  5717. f.write("""
  5718. inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
  5719. switch (cap) {
  5720. """)
  5721. for capability in self.capability_flags:
  5722. f.write("""\
  5723. case GL_%s:
  5724. """ % capability['name'].upper())
  5725. f.write("""\
  5726. if (enable_flags.cached_%(name)s == enable &&
  5727. !ignore_cached_state)
  5728. return;
  5729. enable_flags.cached_%(name)s = enable;
  5730. break;
  5731. """ % capability)
  5732. f.write("""\
  5733. default:
  5734. NOTREACHED();
  5735. return;
  5736. }
  5737. if (enable)
  5738. api()->glEnableFn(cap);
  5739. else
  5740. api()->glDisableFn(cap);
  5741. }
  5742. """)
  5743. self.generated_cpp_filenames.append(filename)
  5744. def WriteClientContextStateHeader(self, filename):
  5745. """Writes the client context state header."""
  5746. comment = "// It is included by client_context_state.h\n"
  5747. with CHeaderWriter(filename, self.year, comment) as f:
  5748. f.write("struct EnableFlags {\n")
  5749. f.write(" EnableFlags();\n")
  5750. for capability in self.capability_flags:
  5751. if 'extension_flag' in capability:
  5752. continue
  5753. f.write(" bool %s;\n" % capability['name'])
  5754. f.write("};\n\n")
  5755. self.generated_cpp_filenames.append(filename)
  5756. def WriteContextStateGetters(self, f, class_name):
  5757. """Writes the state getters."""
  5758. for gl_type in ["GLint", "GLfloat"]:
  5759. f.write("""
  5760. bool %s::GetStateAs%s(
  5761. GLenum pname, %s* params, GLsizei* num_written) const {
  5762. switch (pname) {
  5763. """ % (class_name, gl_type, gl_type))
  5764. for state_name in sorted(_STATE_INFO.keys()):
  5765. state = _STATE_INFO[state_name]
  5766. if 'enum' in state:
  5767. f.write(" case %s:\n" % state['enum'])
  5768. f.write(" *num_written = %d;\n" % len(state['states']))
  5769. f.write(" if (params) {\n")
  5770. for ndx,item in enumerate(state['states']):
  5771. f.write(" params[%d] = static_cast<%s>(%s);\n" %
  5772. (ndx, gl_type, item['name']))
  5773. f.write(" }\n")
  5774. f.write(" return true;\n")
  5775. else:
  5776. for item in state['states']:
  5777. f.write(" case %s:\n" % item['enum'])
  5778. if isinstance(item['default'], list):
  5779. item_len = len(item['default'])
  5780. f.write(" *num_written = %d;\n" % item_len)
  5781. f.write(" if (params) {\n")
  5782. if item['type'] == gl_type:
  5783. f.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
  5784. (item['name'], item['type'], item_len))
  5785. else:
  5786. f.write(" for (size_t i = 0; i < %s; ++i) {\n" %
  5787. item_len)
  5788. f.write(" params[i] = %s;\n" %
  5789. (GetGLGetTypeConversion(gl_type, item['type'],
  5790. "%s[i]" % item['name'])))
  5791. f.write(" }\n");
  5792. else:
  5793. f.write(" *num_written = 1;\n")
  5794. f.write(" if (params) {\n")
  5795. f.write(" params[0] = %s;\n" %
  5796. (GetGLGetTypeConversion(gl_type, item['type'],
  5797. item['name'])))
  5798. f.write(" }\n")
  5799. f.write(" return true;\n")
  5800. for capability in self.capability_flags:
  5801. f.write(" case GL_%s:\n" % capability['name'].upper())
  5802. f.write(" *num_written = 1;\n")
  5803. f.write(" if (params) {\n")
  5804. f.write(
  5805. " params[0] = static_cast<%s>(enable_flags.%s);\n" %
  5806. (gl_type, capability['name']))
  5807. f.write(" }\n")
  5808. f.write(" return true;\n")
  5809. f.write(""" default:
  5810. return false;
  5811. }
  5812. }
  5813. """)
  5814. def WriteServiceContextStateImpl(self, filename):
  5815. """Writes the context state service implementation."""
  5816. comment = "// It is included by context_state.cc\n"
  5817. with CHeaderWriter(filename, self.year, comment) as f:
  5818. code = []
  5819. for capability in self.capability_flags:
  5820. code.append("%s(%s)" %
  5821. (capability['name'],
  5822. ('false', 'true')['default' in capability]))
  5823. code.append("cached_%s(%s)" %
  5824. (capability['name'],
  5825. ('false', 'true')['default' in capability]))
  5826. f.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
  5827. ",\n ".join(code))
  5828. f.write("\n")
  5829. f.write("void ContextState::Initialize() {\n")
  5830. for state_name in sorted(_STATE_INFO.keys()):
  5831. state = _STATE_INFO[state_name]
  5832. for item in state['states']:
  5833. if isinstance(item['default'], list):
  5834. for ndx, value in enumerate(item['default']):
  5835. f.write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
  5836. else:
  5837. f.write(" %s = %s;\n" % (item['name'], item['default']))
  5838. if item.get('cached', False):
  5839. if isinstance(item['default'], list):
  5840. for ndx, value in enumerate(item['default']):
  5841. f.write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
  5842. else:
  5843. f.write(" cached_%s = %s;\n" % (item['name'], item['default']))
  5844. f.write("}\n")
  5845. f.write("""
  5846. void ContextState::InitCapabilities(const ContextState* prev_state) const {
  5847. """)
  5848. def WriteCapabilities(test_prev, es3_caps):
  5849. for capability in self.capability_flags:
  5850. capability_name = capability['name']
  5851. capability_no_init = 'no_init' in capability and \
  5852. capability['no_init'] == True
  5853. if capability_no_init:
  5854. continue
  5855. capability_es3 = 'es3' in capability and capability['es3'] == True
  5856. if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
  5857. continue
  5858. if 'extension_flag' in capability:
  5859. f.write(" if (feature_info_->feature_flags().%s) {\n " %
  5860. capability['extension_flag'])
  5861. if test_prev:
  5862. f.write(""" if (prev_state->enable_flags.cached_%s !=
  5863. enable_flags.cached_%s) {\n""" %
  5864. (capability_name, capability_name))
  5865. f.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
  5866. (capability_name.upper(), capability_name))
  5867. if test_prev:
  5868. f.write(" }")
  5869. if 'extension_flag' in capability:
  5870. f.write(" }")
  5871. f.write(" if (prev_state) {")
  5872. WriteCapabilities(True, False)
  5873. f.write(" if (feature_info_->IsES3Capable()) {\n")
  5874. WriteCapabilities(True, True)
  5875. f.write(" }\n")
  5876. f.write(" } else {")
  5877. WriteCapabilities(False, False)
  5878. f.write(" if (feature_info_->IsES3Capable()) {\n")
  5879. WriteCapabilities(False, True)
  5880. f.write(" }\n")
  5881. f.write(" }")
  5882. f.write("""}
  5883. void ContextState::InitState(const ContextState *prev_state) const {
  5884. """)
  5885. def WriteStates(test_prev):
  5886. # We need to sort the keys so the expectations match
  5887. for state_name in sorted(_STATE_INFO.keys()):
  5888. state = _STATE_INFO[state_name]
  5889. if 'no_init' in state and state['no_init']:
  5890. continue
  5891. if state['type'] == 'FrontBack':
  5892. num_states = len(state['states'])
  5893. for ndx, group in enumerate(Grouper(num_states // 2,
  5894. state['states'])):
  5895. if test_prev:
  5896. f.write(" if (")
  5897. args = []
  5898. for place, item in enumerate(group):
  5899. item_name = CachedStateName(item)
  5900. args.append('%s' % item_name)
  5901. if test_prev:
  5902. if place > 0:
  5903. f.write(' ||\n')
  5904. f.write("(%s != prev_state->%s)" % (item_name, item_name))
  5905. if test_prev:
  5906. f.write(")\n")
  5907. f.write(
  5908. " api()->gl%sFn(%s, %s);\n" %
  5909. (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
  5910. ", ".join(args)))
  5911. elif state['type'] == 'NamedParameter':
  5912. for item in state['states']:
  5913. item_name = CachedStateName(item)
  5914. operation = []
  5915. if test_prev:
  5916. if isinstance(item['default'], list):
  5917. operation.append(" if (memcmp(prev_state->%s, %s, "
  5918. "sizeof(%s) * %d)) {\n" %
  5919. (item_name, item_name, item['type'],
  5920. len(item['default'])))
  5921. else:
  5922. operation.append(" if (prev_state->%s != %s) {\n " %
  5923. (item_name, item_name))
  5924. operation.append(" api()->gl%sFn(%s, %s);\n" %
  5925. (state['func'],
  5926. (item['enum_set']
  5927. if 'enum_set' in item else item['enum']),
  5928. item['name']))
  5929. if test_prev:
  5930. operation.append(" }")
  5931. guarded_operation = GuardState(item, ''.join(operation),
  5932. "feature_info_")
  5933. f.write(guarded_operation)
  5934. else:
  5935. if 'extension_flag' in state:
  5936. f.write(" if (feature_info_->feature_flags().%s)\n " %
  5937. state['extension_flag'])
  5938. if test_prev:
  5939. f.write(" if (")
  5940. args = []
  5941. for place, item in enumerate(state['states']):
  5942. item_name = CachedStateName(item)
  5943. args.append('%s' % item_name)
  5944. if test_prev:
  5945. if place > 0:
  5946. f.write(' ||\n')
  5947. f.write("(%s != prev_state->%s)" %
  5948. (item_name, item_name))
  5949. if test_prev:
  5950. f.write(" )\n")
  5951. if 'custom_function' in state:
  5952. f.write(" %s(%s);\n" % (state['func'], ", ".join(args)))
  5953. else:
  5954. f.write(" api()->gl%sFn(%s);\n" % (state['func'],
  5955. ", ".join(args)))
  5956. f.write(" if (prev_state) {")
  5957. WriteStates(True)
  5958. f.write(" } else {")
  5959. WriteStates(False)
  5960. f.write(" }")
  5961. f.write(" InitStateManual(prev_state);")
  5962. f.write("}\n")
  5963. f.write("""bool ContextState::GetEnabled(GLenum cap) const {
  5964. switch (cap) {
  5965. """)
  5966. for capability in self.capability_flags:
  5967. f.write(" case GL_%s:\n" % capability['name'].upper())
  5968. f.write(" return enable_flags.%s;\n" % capability['name'])
  5969. f.write(""" default:
  5970. NOTREACHED();
  5971. return false;
  5972. }
  5973. }
  5974. """)
  5975. self.WriteContextStateGetters(f, "ContextState")
  5976. self.generated_cpp_filenames.append(filename)
  5977. def WriteClientContextStateImpl(self, filename):
  5978. """Writes the context state client side implementation."""
  5979. comment = "// It is included by client_context_state.cc\n"
  5980. with CHeaderWriter(filename, self.year, comment) as f:
  5981. code = []
  5982. for capability in self.capability_flags:
  5983. if 'extension_flag' in capability:
  5984. continue
  5985. code.append("%s(%s)" %
  5986. (capability['name'],
  5987. ('false', 'true')['default' in capability]))
  5988. f.write(
  5989. "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
  5990. ",\n ".join(code))
  5991. f.write("\n")
  5992. f.write("""
  5993. bool ClientContextState::SetCapabilityState(
  5994. GLenum cap, bool enabled, bool* changed) {
  5995. *changed = false;
  5996. switch (cap) {
  5997. """)
  5998. for capability in self.capability_flags:
  5999. if 'extension_flag' in capability:
  6000. continue
  6001. f.write(" case GL_%s:\n" % capability['name'].upper())
  6002. f.write(""" if (enable_flags.%(name)s != enabled) {
  6003. *changed = true;
  6004. enable_flags.%(name)s = enabled;
  6005. }
  6006. return true;
  6007. """ % capability)
  6008. f.write(""" default:
  6009. return false;
  6010. }
  6011. }
  6012. """)
  6013. f.write("""bool ClientContextState::GetEnabled(
  6014. GLenum cap, bool* enabled) const {
  6015. switch (cap) {
  6016. """)
  6017. for capability in self.capability_flags:
  6018. if 'extension_flag' in capability:
  6019. continue
  6020. f.write(" case GL_%s:\n" % capability['name'].upper())
  6021. f.write(" *enabled = enable_flags.%s;\n" % capability['name'])
  6022. f.write(" return true;\n")
  6023. f.write(""" default:
  6024. return false;
  6025. }
  6026. }
  6027. """)
  6028. self.generated_cpp_filenames.append(filename)
  6029. def WriteServiceImplementation(self, filename):
  6030. """Writes the service decoder implementation."""
  6031. comment = "// It is included by %s_cmd_decoder.cc\n" % _lower_prefix
  6032. with CHeaderWriter(filename, self.year, comment) as f:
  6033. for func in self.functions:
  6034. func.WriteServiceImplementation(f)
  6035. if self.capability_flags and _prefix == 'GLES2':
  6036. f.write("""
  6037. bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
  6038. switch (cap) {
  6039. """)
  6040. for capability in self.capability_flags:
  6041. f.write(" case GL_%s:\n" % capability['name'].upper())
  6042. if 'on_change' in capability:
  6043. f.write("""\
  6044. state_.enable_flags.%(name)s = enabled;
  6045. if (state_.enable_flags.cached_%(name)s != enabled
  6046. || state_.ignore_cached_state) {
  6047. %(on_change)s
  6048. }
  6049. return false;
  6050. """ % capability)
  6051. else:
  6052. f.write("""\
  6053. state_.enable_flags.%(name)s = enabled;
  6054. if (state_.enable_flags.cached_%(name)s != enabled
  6055. || state_.ignore_cached_state) {
  6056. state_.enable_flags.cached_%(name)s = enabled;
  6057. return true;
  6058. }
  6059. return false;
  6060. """ % capability)
  6061. f.write(""" default:
  6062. NOTREACHED();
  6063. return false;
  6064. }
  6065. }
  6066. """)
  6067. self.generated_cpp_filenames.append(filename)
  6068. def WritePassthroughServiceImplementation(self, filename):
  6069. """Writes the passthrough service decoder implementation."""
  6070. with CWriter(filename, self.year) as f:
  6071. header = """
  6072. #include \"gpu/command_buffer/service/gles2_cmd_decoder_passthrough.h\"
  6073. namespace gpu {
  6074. namespace gles2 {
  6075. """;
  6076. f.write(header);
  6077. for func in self.functions:
  6078. func.WritePassthroughServiceImplementation(f)
  6079. footer = """
  6080. } // namespace gles2
  6081. } // namespace gpu
  6082. """;
  6083. f.write(footer);
  6084. self.generated_cpp_filenames.append(filename)
  6085. def WriteServiceUnitTests(self, filename_pattern):
  6086. """Writes the service decoder unit tests."""
  6087. num_tests = len(self.functions)
  6088. FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
  6089. count = 0
  6090. for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
  6091. count += 1
  6092. filename = filename_pattern % count
  6093. comment = "// It is included by %s_cmd_decoder_unittest_%d.cc\n" \
  6094. % (_lower_prefix, count)
  6095. with CHeaderWriter(filename, self.year, comment) as f:
  6096. end = test_num + FUNCTIONS_PER_FILE
  6097. if end > num_tests:
  6098. end = num_tests
  6099. for idx in range(test_num, end):
  6100. func = self.functions[idx]
  6101. test_name = '%sDecoderTest%d' % (_prefix, count)
  6102. if func.IsES3():
  6103. test_name = 'GLES3DecoderTest%d' % count
  6104. # Do any filtering of the functions here, so that the functions
  6105. # will not move between the numbered files if filtering properties
  6106. # are changed.
  6107. if func.GetInfo('extension_flag'):
  6108. continue
  6109. if func.GetInfo('unit_test') != False:
  6110. func.WriteServiceUnitTest(f, {
  6111. 'test_name': test_name
  6112. })
  6113. self.generated_cpp_filenames.append(filename)
  6114. def WriteServiceContextStateTestHelpers(self, filename):
  6115. comment = "// It is included by context_state_test_helpers.cc\n"
  6116. with CHeaderWriter(filename, self.year, comment) as f:
  6117. if self.capability_flags:
  6118. f.write(
  6119. """void ContextStateTestHelpers::SetupInitCapabilitiesExpectations(
  6120. MockGL* gl,
  6121. gles2::FeatureInfo* feature_info) {
  6122. """)
  6123. for capability in self.capability_flags:
  6124. capability_no_init = 'no_init' in capability and \
  6125. capability['no_init'] == True
  6126. if capability_no_init:
  6127. continue
  6128. capability_es3 = 'es3' in capability and capability['es3'] == True
  6129. if capability_es3:
  6130. continue
  6131. if 'extension_flag' in capability:
  6132. f.write(" if (feature_info->feature_flags().%s) {\n" %
  6133. capability['extension_flag'])
  6134. f.write(" ")
  6135. f.write(" ExpectEnableDisable(gl, GL_%s, %s);\n" %
  6136. (capability['name'].upper(),
  6137. ('false', 'true')['default' in capability]))
  6138. if 'extension_flag' in capability:
  6139. f.write(" }")
  6140. f.write(" if (feature_info->IsES3Capable()) {")
  6141. for capability in self.capability_flags:
  6142. capability_es3 = 'es3' in capability and capability['es3'] == True
  6143. if capability_es3:
  6144. f.write(" ExpectEnableDisable(gl, GL_%s, %s);\n" %
  6145. (capability['name'].upper(),
  6146. ('false', 'true')['default' in capability]))
  6147. f.write(""" }
  6148. }
  6149. """)
  6150. f.write("""
  6151. void ContextStateTestHelpers::SetupInitStateExpectations(
  6152. MockGL* gl,
  6153. gles2::FeatureInfo* feature_info,
  6154. const gfx::Size& initial_size) {
  6155. """)
  6156. # We need to sort the keys so the expectations match
  6157. for state_name in sorted(_STATE_INFO.keys()):
  6158. state = _STATE_INFO[state_name]
  6159. if state['type'] == 'FrontBack':
  6160. num_states = len(state['states'])
  6161. for ndx, group in enumerate(Grouper(num_states // 2,
  6162. state['states'])):
  6163. args = []
  6164. for item in group:
  6165. if 'expected' in item:
  6166. args.append(item['expected'])
  6167. else:
  6168. args.append(item['default'])
  6169. f.write(
  6170. " EXPECT_CALL(*gl, %s(%s, %s))\n" %
  6171. (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
  6172. ", ".join(args)))
  6173. f.write(" .Times(1)\n")
  6174. f.write(" .RetiresOnSaturation();\n")
  6175. elif state['type'] == 'NamedParameter':
  6176. for item in state['states']:
  6177. expect_value = item['default']
  6178. if isinstance(expect_value, list):
  6179. # TODO: Currently we do not check array values.
  6180. expect_value = "_"
  6181. operation = []
  6182. operation.append(
  6183. " EXPECT_CALL(*gl, %s(%s, %s))\n" %
  6184. (state['func'],
  6185. (item['enum_set']
  6186. if 'enum_set' in item else item['enum']),
  6187. expect_value))
  6188. operation.append(" .Times(1)\n")
  6189. operation.append(" .RetiresOnSaturation();\n")
  6190. guarded_operation = GuardState(item, ''.join(operation),
  6191. "feature_info")
  6192. f.write(guarded_operation)
  6193. elif 'no_init' not in state:
  6194. if 'extension_flag' in state:
  6195. f.write(" if (feature_info->feature_flags().%s) {\n" %
  6196. state['extension_flag'])
  6197. f.write(" ")
  6198. args = []
  6199. for item in state['states']:
  6200. if 'expected' in item:
  6201. args.append(item['expected'])
  6202. else:
  6203. args.append(item['default'])
  6204. # TODO: Currently we do not check array values.
  6205. args = ["_" if isinstance(arg, list) else arg for arg in args]
  6206. if 'custom_function' in state:
  6207. f.write(" SetupInitStateManualExpectationsFor%s(gl, %s);\n" %
  6208. (state['func'], ", ".join(args)))
  6209. else:
  6210. f.write(" EXPECT_CALL(*gl, %s(%s))\n" %
  6211. (state['func'], ", ".join(args)))
  6212. f.write(" .Times(1)\n")
  6213. f.write(" .RetiresOnSaturation();\n")
  6214. if 'extension_flag' in state:
  6215. f.write(" }\n")
  6216. f.write(" SetupInitStateManualExpectations(gl, feature_info);\n")
  6217. f.write("}\n")
  6218. self.generated_cpp_filenames.append(filename)
  6219. def WriteServiceUnitTestsForExtensions(self, filename):
  6220. """Writes the service decoder unit tests for functions with extension_flag.
  6221. The functions are special in that they need a specific unit test
  6222. baseclass to turn on the extension.
  6223. """
  6224. functions = [f for f in self.functions if f.GetInfo('extension_flag')]
  6225. comment = "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
  6226. with CHeaderWriter(filename, self.year, comment) as f:
  6227. for func in functions:
  6228. if True:
  6229. if func.GetInfo('unit_test') != False:
  6230. extension = ToCamelCase(
  6231. ToGLExtensionString(func.GetInfo('extension_flag')))
  6232. test_name = 'GLES2DecoderTestWith%s' % extension
  6233. if func.IsES3():
  6234. test_name = 'GLES3DecoderTestWith%s' % extension
  6235. func.WriteServiceUnitTest(f, {
  6236. 'test_name': test_name
  6237. })
  6238. self.generated_cpp_filenames.append(filename)
  6239. def WriteGLES2Header(self, filename):
  6240. """Writes the GLES2 header."""
  6241. comment = "// This file contains Chromium-specific GLES2 declarations.\n\n"
  6242. with CHeaderWriter(filename, self.year, comment) as f:
  6243. for func in self.original_functions:
  6244. func.WriteGLES2Header(f)
  6245. f.write("\n")
  6246. self.generated_cpp_filenames.append(filename)
  6247. def WriteGLES2CLibImplementation(self, filename):
  6248. """Writes the GLES2 c lib implementation."""
  6249. comment = "// These functions emulate GLES2 over command buffers.\n"
  6250. with CHeaderWriter(filename, self.year, comment) as f:
  6251. for func in self.original_functions:
  6252. func.WriteGLES2CLibImplementation(f)
  6253. f.write("""
  6254. namespace gles2 {
  6255. extern const NameToFunc g_gles2_function_table[] = {
  6256. """)
  6257. for func in self.original_functions:
  6258. f.write(
  6259. ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
  6260. (func.name, func.name))
  6261. f.write(""" { nullptr, nullptr, },
  6262. };
  6263. } // namespace gles2
  6264. """)
  6265. self.generated_cpp_filenames.append(filename)
  6266. def WriteGLES2InterfaceHeader(self, filename):
  6267. """Writes the GLES2 interface header."""
  6268. comment = ("// This file is included by %s_interface.h to declare the\n"
  6269. "// GL api functions.\n" % _lower_prefix)
  6270. with CHeaderWriter(filename, self.year, comment) as f:
  6271. for func in self.original_functions:
  6272. func.WriteGLES2InterfaceHeader(f)
  6273. self.generated_cpp_filenames.append(filename)
  6274. def WriteGLES2InterfaceStub(self, filename):
  6275. """Writes the GLES2 interface stub header."""
  6276. comment = "// This file is included by gles2_interface_stub.h.\n"
  6277. with CHeaderWriter(filename, self.year, comment) as f:
  6278. for func in self.original_functions:
  6279. func.WriteGLES2InterfaceStub(f)
  6280. self.generated_cpp_filenames.append(filename)
  6281. def WriteGLES2InterfaceStubImpl(self, filename):
  6282. """Writes the GLES2 interface header."""
  6283. comment = "// This file is included by gles2_interface_stub.cc.\n"
  6284. with CHeaderWriter(filename, self.year, comment) as f:
  6285. for func in self.original_functions:
  6286. func.WriteGLES2InterfaceStubImpl(f)
  6287. self.generated_cpp_filenames.append(filename)
  6288. def WriteGLES2ImplementationHeader(self, filename):
  6289. """Writes the GLES2 Implementation header."""
  6290. comment = \
  6291. ("// This file is included by %s_implementation.h to declare the\n"
  6292. "// GL api functions.\n" % _lower_prefix)
  6293. with CHeaderWriter(filename, self.year, comment) as f:
  6294. for func in self.original_functions:
  6295. func.WriteGLES2ImplementationHeader(f)
  6296. self.generated_cpp_filenames.append(filename)
  6297. def WriteGLES2Implementation(self, filename):
  6298. """Writes the GLES2 Implementation."""
  6299. comment = \
  6300. ("// This file is included by %s_implementation.cc to define the\n"
  6301. "// GL api functions.\n" % _lower_prefix)
  6302. with CHeaderWriter(filename, self.year, comment) as f:
  6303. for func in self.original_functions:
  6304. func.WriteGLES2Implementation(f)
  6305. self.generated_cpp_filenames.append(filename)
  6306. def WriteGLES2TraceImplementationHeader(self, filename):
  6307. """Writes the GLES2 Trace Implementation header."""
  6308. comment = "// This file is included by gles2_trace_implementation.h\n"
  6309. with CHeaderWriter(filename, self.year, comment) as f:
  6310. for func in self.original_functions:
  6311. func.WriteGLES2TraceImplementationHeader(f)
  6312. self.generated_cpp_filenames.append(filename)
  6313. def WriteGLES2TraceImplementation(self, filename):
  6314. """Writes the GLES2 Trace Implementation."""
  6315. comment = "// This file is included by gles2_trace_implementation.cc\n"
  6316. with CHeaderWriter(filename, self.year, comment) as f:
  6317. for func in self.original_functions:
  6318. func.WriteGLES2TraceImplementation(f)
  6319. self.generated_cpp_filenames.append(filename)
  6320. def WriteGLES2ImplementationUnitTests(self, filename):
  6321. """Writes the GLES2 helper header."""
  6322. comment = \
  6323. ("// This file is included by %s_implementation.h to declare the\n"
  6324. "// GL api functions.\n" % _lower_prefix)
  6325. with CHeaderWriter(filename, self.year, comment) as f:
  6326. for func in self.original_functions:
  6327. func.WriteGLES2ImplementationUnitTest(f)
  6328. self.generated_cpp_filenames.append(filename)
  6329. def WriteServiceUtilsHeader(self, filename):
  6330. """Writes the gles2 auto generated utility header."""
  6331. with CHeaderWriter(filename, self.year) as f:
  6332. for name in sorted(self.named_type_info.keys()):
  6333. named_type = NamedType(self.named_type_info[name])
  6334. if not named_type.CreateValidator():
  6335. continue
  6336. class_name = ValidatorClassName(name)
  6337. if named_type.IsComplete():
  6338. f.write("""class %(class_name)s {
  6339. public:
  6340. bool IsValid(const %(type)s value) const;"""% {
  6341. 'class_name': class_name,
  6342. 'type': named_type.GetType()
  6343. })
  6344. if named_type.HasES3Values():
  6345. f.write("""%s();
  6346. void SetIsES3(bool is_es3) { is_es3_ = is_es3; }
  6347. private:
  6348. bool is_es3_;""" % class_name)
  6349. f.write("};\n")
  6350. f.write("%s %s;\n\n" %
  6351. (class_name, ToUnderscore(name)))
  6352. else:
  6353. f.write("ValueValidator<%s> %s;\n" %
  6354. (named_type.GetType(), ToUnderscore(name)))
  6355. f.write("\n")
  6356. self.generated_cpp_filenames.append(filename)
  6357. def WriteServiceUtilsImplementation(self, filename):
  6358. """Writes the gles2 auto generated utility implementation."""
  6359. with CHeaderWriter(filename, self.year) as f:
  6360. names = sorted(self.named_type_info.keys())
  6361. for name in names:
  6362. named_type = NamedType(self.named_type_info[name])
  6363. class_name = ValidatorClassName(name)
  6364. if not named_type.CreateValidator():
  6365. continue
  6366. if named_type.IsComplete():
  6367. if named_type.HasES3Values():
  6368. f.write("""Validators::%(class_name)s::%(class_name)s()
  6369. : is_es3_(false) {}""" % { 'class_name': class_name })
  6370. f.write("""bool Validators::%(class_name)s::IsValid(
  6371. const %(type)s value) const {
  6372. switch(value) {\n""" % {
  6373. 'class_name': class_name,
  6374. 'type': named_type.GetType()
  6375. })
  6376. if named_type.GetValidValues():
  6377. for value in named_type.GetValidValues():
  6378. f.write("case %s:\n" % value)
  6379. f.write("return true;\n")
  6380. if named_type.GetValidValuesES3():
  6381. for value in named_type.GetValidValuesES3():
  6382. f.write("case %s:\n" % value)
  6383. f.write("return is_es3_;\n")
  6384. if named_type.GetDeprecatedValuesES3():
  6385. for value in named_type.GetDeprecatedValuesES3():
  6386. f.write("case %s:\n" % value)
  6387. f.write("return !is_es3_;\n")
  6388. f.write("}\nreturn false;\n}\n")
  6389. f.write("\n")
  6390. else:
  6391. if named_type.GetValidValues():
  6392. f.write("static const %s valid_%s_table[] = {\n" %
  6393. (named_type.GetType(), ToUnderscore(name)))
  6394. for value in named_type.GetValidValues():
  6395. f.write(" %s,\n" % value)
  6396. f.write("};\n")
  6397. f.write("\n")
  6398. if named_type.GetValidValuesES3():
  6399. f.write("static const %s valid_%s_table_es3[] = {\n" %
  6400. (named_type.GetType(), ToUnderscore(name)))
  6401. for value in named_type.GetValidValuesES3():
  6402. f.write(" %s,\n" % value)
  6403. f.write("};\n")
  6404. f.write("\n")
  6405. if named_type.GetDeprecatedValuesES3():
  6406. f.write("static const %s deprecated_%s_table_es3[] = {\n" %
  6407. (named_type.GetType(), ToUnderscore(name)))
  6408. for value in named_type.GetDeprecatedValuesES3():
  6409. f.write(" %s,\n" % value)
  6410. f.write("};\n")
  6411. f.write("\n")
  6412. f.write("Validators::Validators()")
  6413. pre = ' : '
  6414. for name in names:
  6415. named_type = NamedType(self.named_type_info[name])
  6416. if not named_type.CreateValidator() or named_type.IsComplete():
  6417. continue
  6418. if named_type.GetValidValues():
  6419. code = """%(pre)s%(name)s(
  6420. valid_%(name)s_table, std::size(valid_%(name)s_table))"""
  6421. else:
  6422. code = "%(pre)s%(name)s()"
  6423. f.write(code % {
  6424. 'name': ToUnderscore(name),
  6425. 'pre': pre,
  6426. })
  6427. pre = ',\n '
  6428. f.write(" {\n");
  6429. f.write("}\n\n");
  6430. if _prefix == 'GLES2':
  6431. f.write("void Validators::UpdateValuesES3() {\n")
  6432. for name in names:
  6433. named_type = NamedType(self.named_type_info[name])
  6434. if not named_type.IsConstant() and named_type.IsComplete():
  6435. if named_type.HasES3Values():
  6436. f.write(" %(name)s.SetIsES3(true);" % {
  6437. 'name': ToUnderscore(name),
  6438. })
  6439. continue
  6440. if named_type.GetDeprecatedValuesES3():
  6441. code = """ %(name)s.RemoveValues(
  6442. deprecated_%(name)s_table_es3, std::size(deprecated_%(name)s_table_es3));
  6443. """
  6444. f.write(code % {
  6445. 'name': ToUnderscore(name),
  6446. })
  6447. if named_type.GetValidValuesES3():
  6448. code = """ %(name)s.AddValues(
  6449. valid_%(name)s_table_es3, std::size(valid_%(name)s_table_es3));
  6450. """
  6451. f.write(code % {
  6452. 'name': ToUnderscore(name),
  6453. })
  6454. f.write("}\n\n");
  6455. f.write("void Validators::UpdateETCCompressedTextureFormats() {\n")
  6456. for name in ['CompressedTextureFormat', 'TextureInternalFormatStorage']:
  6457. for fmt in _ETC_COMPRESSED_TEXTURE_FORMATS:
  6458. code = """ %(name)s.AddValue(%(format)s);
  6459. """
  6460. f.write(code % {
  6461. 'name': ToUnderscore(name),
  6462. 'format': fmt,
  6463. })
  6464. f.write("}\n\n");
  6465. self.generated_cpp_filenames.append(filename)
  6466. def WriteCommonUtilsHeader(self, filename):
  6467. """Writes the gles2 common utility header."""
  6468. with CHeaderWriter(filename, self.year) as f:
  6469. type_infos = sorted(self.named_type_info.keys())
  6470. for type_info in type_infos:
  6471. if self.named_type_info[type_info]['type'] == 'GLenum':
  6472. f.write("static std::string GetString%s(uint32_t value);\n" %
  6473. type_info)
  6474. f.write("\n")
  6475. self.generated_cpp_filenames.append(filename)
  6476. def WriteCommonUtilsImpl(self, filename):
  6477. """Writes the gles2 common utility header."""
  6478. enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
  6479. define_dict = {}
  6480. for fname in ['third_party/khronos/GLES2/gl2.h',
  6481. 'third_party/khronos/GLES2/gl2ext.h',
  6482. 'third_party/khronos/GLES3/gl3.h',
  6483. 'third_party/khronos/GLES3/gl31.h',
  6484. 'gpu/GLES2/gl2chromium.h',
  6485. 'gpu/GLES2/gl2extchromium.h']:
  6486. fname = os.path.join(self.chromium_root_dir, fname)
  6487. lines = open(fname).readlines()
  6488. for line in lines:
  6489. m = enum_re.match(line)
  6490. if m:
  6491. name = m.group(1)
  6492. value = m.group(2)
  6493. if len(value) <= 10 and value.startswith('0x'):
  6494. if not value in define_dict:
  6495. define_dict[value] = name
  6496. # check our own _CHROMIUM macro conflicts with khronos GL headers.
  6497. elif EnumsConflict(define_dict[value], name):
  6498. self.Error("code collision: %s and %s have the same code %s" %
  6499. (define_dict[value], name, value))
  6500. with CHeaderWriter(filename, self.year) as f:
  6501. f.write("static const %sUtil::EnumToString "
  6502. "enum_to_string_table[] = {\n" % _prefix)
  6503. for value in sorted(define_dict):
  6504. f.write(' { %s, "%s", },\n' % (value, define_dict[value]))
  6505. f.write("""};
  6506. const %(p)sUtil::EnumToString* const %(p)sUtil::enum_to_string_table_ =
  6507. enum_to_string_table;
  6508. const size_t %(p)sUtil::enum_to_string_table_len_ =
  6509. sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
  6510. """ % { 'p' : _prefix})
  6511. enums = sorted(self.named_type_info.keys())
  6512. for enum in enums:
  6513. if self.named_type_info[enum]['type'] == 'GLenum':
  6514. f.write("std::string %sUtil::GetString%s(uint32_t value) {\n" %
  6515. (_prefix, enum))
  6516. valid_list = self.named_type_info[enum]['valid']
  6517. if 'valid_es3' in self.named_type_info[enum]:
  6518. for es3_enum in self.named_type_info[enum]['valid_es3']:
  6519. if not es3_enum in valid_list:
  6520. valid_list.append(es3_enum)
  6521. assert len(valid_list) == len(set(valid_list))
  6522. if len(valid_list) > 0:
  6523. f.write(" static const EnumToString string_table[] = {\n")
  6524. for value in valid_list:
  6525. f.write(' { %s, "%s" },\n' % (value, value))
  6526. f.write(""" };
  6527. return %sUtil::GetQualifiedEnumString(
  6528. string_table, std::size(string_table), value);
  6529. }
  6530. """ % _prefix)
  6531. else:
  6532. f.write(""" return %sUtil::GetQualifiedEnumString(
  6533. nullptr, 0, value);
  6534. }
  6535. """ % _prefix)
  6536. self.generated_cpp_filenames.append(filename)
  6537. def WritePepperGLES2Interface(self, filename, dev):
  6538. """Writes the Pepper OpenGLES interface definition."""
  6539. with CWriter(filename, self.year) as f:
  6540. f.write("label Chrome {\n")
  6541. f.write(" M39 = 1.0\n")
  6542. f.write("};\n\n")
  6543. if not dev:
  6544. # Declare GL types.
  6545. f.write("[version=1.0]\n")
  6546. f.write("describe {\n")
  6547. for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
  6548. 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
  6549. 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
  6550. 'GLubyte', 'GLuint', 'GLushort']:
  6551. f.write(" %s;\n" % gltype)
  6552. f.write(" %s_ptr_t;\n" % gltype)
  6553. f.write("};\n\n")
  6554. # C level typedefs.
  6555. f.write("#inline c\n")
  6556. f.write("#include \"ppapi/c/pp_resource.h\"\n")
  6557. if dev:
  6558. f.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
  6559. else:
  6560. f.write("\n#ifndef __gl2_h_\n")
  6561. for (k, v) in _GL_TYPES.items():
  6562. f.write("typedef %s %s;\n" % (v, k))
  6563. f.write("#ifdef _WIN64\n")
  6564. for (k, v) in _GL_TYPES_64.items():
  6565. f.write("typedef %s %s;\n" % (v, k))
  6566. f.write("#else\n")
  6567. for (k, v) in _GL_TYPES_32.items():
  6568. f.write("typedef %s %s;\n" % (v, k))
  6569. f.write("#endif // _WIN64\n")
  6570. f.write("#endif // __gl2_h_\n\n")
  6571. f.write("#endinl\n")
  6572. for interface in self.pepper_interfaces:
  6573. if interface.dev != dev:
  6574. continue
  6575. # Historically, we provide OpenGLES2 interfaces with struct
  6576. # namespace. Not to break code which uses the interface as
  6577. # "struct OpenGLES2", we put it in struct namespace.
  6578. f.write('\n[macro="%s", force_struct_namespace]\n' %
  6579. interface.GetInterfaceName())
  6580. f.write("interface %s {\n" % interface.GetStructName())
  6581. for func in self.original_functions:
  6582. if not func.InPepperInterface(interface):
  6583. continue
  6584. ret_type = func.MapCTypeToPepperIdlType(func.return_type,
  6585. is_for_return_type=True)
  6586. func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
  6587. f.write(func_prefix)
  6588. f.write("[in] PP_Resource context")
  6589. for arg in func.MakeTypedPepperIdlArgStrings():
  6590. f.write(",\n" + " " * len(func_prefix) + arg)
  6591. f.write(");\n")
  6592. f.write("};\n\n")
  6593. def WritePepperGLES2Implementation(self, filename):
  6594. """Writes the Pepper OpenGLES interface implementation."""
  6595. with CWriter(filename, self.year) as f:
  6596. f.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
  6597. f.write("#include \"base/logging.h\"\n")
  6598. f.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
  6599. f.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
  6600. f.write("#include \"ppapi/thunk/enter.h\"\n\n")
  6601. f.write("namespace ppapi {\n\n")
  6602. f.write("namespace {\n\n")
  6603. f.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
  6604. " Enter3D;\n\n")
  6605. f.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
  6606. " enter) {\n")
  6607. f.write(" DCHECK(enter);\n")
  6608. f.write(" DCHECK(enter->succeeded());\n")
  6609. f.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
  6610. "gles2_impl();\n");
  6611. f.write("}\n\n");
  6612. for func in self.original_functions:
  6613. if not func.InAnyPepperExtension():
  6614. continue
  6615. original_arg = func.MakeTypedPepperArgString("")
  6616. context_arg = "PP_Resource context_id"
  6617. if len(original_arg):
  6618. arg = context_arg + ", " + original_arg
  6619. else:
  6620. arg = context_arg
  6621. f.write("%s %s(%s) {\n" %
  6622. (func.return_type, func.GetPepperName(), arg))
  6623. f.write(" Enter3D enter(context_id, true);\n")
  6624. f.write(" if (enter.succeeded()) {\n")
  6625. return_str = "" if func.return_type == "void" else "return "
  6626. f.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
  6627. (return_str, func.original_name,
  6628. func.MakeOriginalArgString("")))
  6629. f.write(" }")
  6630. if func.return_type == "void":
  6631. f.write("\n")
  6632. else:
  6633. f.write(" else {\n")
  6634. f.write(" return %s;\n" % func.GetErrorReturnString())
  6635. f.write(" }\n")
  6636. f.write("}\n\n")
  6637. f.write("} // namespace\n")
  6638. for interface in self.pepper_interfaces:
  6639. f.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
  6640. (interface.GetStructName(), interface.GetName()))
  6641. f.write(" static const struct %s "
  6642. "ppb_opengles2 = {\n" % interface.GetStructName())
  6643. f.write(" &")
  6644. f.write(",\n &".join(
  6645. f.GetPepperName() for f in self.original_functions
  6646. if f.InPepperInterface(interface)))
  6647. f.write("\n")
  6648. f.write(" };\n")
  6649. f.write(" return &ppb_opengles2;\n")
  6650. f.write("}\n")
  6651. f.write("} // namespace ppapi\n")
  6652. self.generated_cpp_filenames.append(filename)
  6653. def WriteGLES2ToPPAPIBridge(self, filename):
  6654. """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
  6655. with CWriter(filename, self.year) as f:
  6656. f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
  6657. f.write("#define GL_GLEXT_PROTOTYPES\n")
  6658. f.write("#endif\n")
  6659. f.write("#include <GLES2/gl2.h>\n")
  6660. f.write("#include <GLES2/gl2ext.h>\n")
  6661. f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
  6662. for func in self.original_functions:
  6663. if not func.InAnyPepperExtension():
  6664. continue
  6665. interface = self.interface_info[func.GetInfo('pepper_interface') or '']
  6666. f.write("%s GL_APIENTRY gl%s(%s) {\n" %
  6667. (func.return_type, func.GetPepperName(),
  6668. func.MakeTypedPepperArgString("")))
  6669. return_str = "" if func.return_type == "void" else "return "
  6670. interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
  6671. original_arg = func.MakeOriginalArgString("")
  6672. context_arg = "glGetCurrentContextPPAPI()"
  6673. if len(original_arg):
  6674. arg = context_arg + ", " + original_arg
  6675. else:
  6676. arg = context_arg
  6677. if interface.GetName():
  6678. f.write(" const struct %s* ext = %s;\n" %
  6679. (interface.GetStructName(), interface_str))
  6680. f.write(" if (ext)\n")
  6681. f.write(" %sext->%s(%s);\n" %
  6682. (return_str, func.GetPepperName(), arg))
  6683. if return_str:
  6684. f.write(" %s0;\n" % return_str)
  6685. else:
  6686. f.write(" %s%s->%s(%s);\n" %
  6687. (return_str, interface_str, func.GetPepperName(), arg))
  6688. f.write("}\n\n")
  6689. self.generated_cpp_filenames.append(filename)
  6690. def Format(generated_files, output_dir, chromium_root_dir):
  6691. """Format generated_files relative to output_dir using clang-format."""
  6692. formatter = "third_party/depot_tools/clang-format"
  6693. if platform.system() == "Windows":
  6694. formatter = "third_party\\depot_tools\\clang-format.bat"
  6695. formatter = os.path.join(chromium_root_dir, formatter)
  6696. generated_files = map(lambda filename: os.path.join(output_dir, filename),
  6697. generated_files)
  6698. for filename in generated_files:
  6699. call([formatter, "-i", "-style=chromium", filename], cwd=chromium_root_dir)