Creating an OpenGL context — pyglet v1.5.26
文章推薦指數: 80 %
Note that you cannot create a context directly from a template (any Config you constructed yourself). The Window constructor performs a similar process to the ... pyglet latest ProgrammingGuide Installation Writingapygletapplication Windowing Workingwiththekeyboard Workingwiththemouse Workingwithotherinputdevices Graphics Shapes Displayingtext Images Soundandvideo Applicationresources Thepygleteventframework Keepingtrackoftime CreatinganOpenGLcontext Displays,screens,configsandcontexts Contextsandconfigs Displays Screens OpenGLconfigurationoptions Thedefaultconfiguration Simplecontextconfiguration Selectingthebestconfiguration Sharingobjectsbetweencontexts TheOpenGLinterface Theapplicationeventloop pygletoptions Debuggingtools Advancedtopics In-depthgameexample APIReference pyglet pyglet.app pyglet.canvas pyglet.clock pyglet.event pyglet.font pyglet.gl pyglet.graphics pyglet.gui pyglet.image pyglet.info pyglet.input pyglet.media pyglet.resource pyglet.sprite pyglet.shapes pyglet.text pyglet.window ExternalResources RelatedDocumentation Thirdpartylibraries Projectsusingpyglet DevelopmentGuide Contributing Developmentenvironment Testingpyglet Documentation Makingapygletrelease OpenGLInterfaceImplementation ctypesWrapperGeneration wraptypes Mediamanual Medialoggingmanual pyglet Docs» CreatinganOpenGLcontext EditonGitHub CreatinganOpenGLcontext¶ ThissectiondescribeshowtoconfigureanOpenGLcontext.Formost applicationstheinformationdescribedhereisfartoolow-leveltobeofany concern,howevermoreadvancedapplicationscantakeadvantageofthecomplete controlpygletprovides. Displays,screens,configsandcontexts¶ Flowofconstruction,fromtheabstractCanvastoanewly createdWindowwithitsContext. Contextsandconfigs¶ Whenyoudrawonawindowinpyglet,youaredrawingtoanOpenGLcontext. Everywindowhasitsowncontext,whichiscreatedwhenthewindowiscreated. Youcanaccessthewindow’scontextviaits contextattribute. ThecontextiscreatedfromanOpenGLconfiguration(or“config”),which describesvariouspropertiesofthecontextsuchaswhatcolorformattouse, howmanybuffersareavailable,andsoon.Youcanaccesstheconfig thatwasusedtocreateacontextviathecontext’s configattribute. Forexample,herewecreateawindowusingthedefaultconfigandexaminesome ofitsproperties: >>>importpyglet >>>window=pyglet.window.Window() >>>context=window.context >>>config=context.config >>>config.double_buffer c_int(1) >>>config.stereo c_int(0) >>>config.sample_buffers c_int(0) Notethatthevaluesoftheconfig’sattributesareallctypesinstances. Thisisbecausetheconfigwasnotspecifiedbypyglet.Rather,ithasbeen selectedbypygletfromalistofconfigssupportedbythesystem.Youcan makenoguaranteethatagivenconfigisvalidonasystemunlessitwas providedtoyoubythesystem. pygletsimplifiestheprocessofselectingoneofthesystem’sconfigsby allowingyoutocreatea“template”configwhichspecifiesonlythevaluesyou areinterestedin.SeeSimplecontextconfigurationfordetails. Displays¶ Thesystemmayactuallysupportseveraldifferentsetsofconfigs,dependingon whichdisplaydeviceisbeingused.Forexample,acomputerwithtwovideo cardsmaynotsupportthesameconfigsoneachcard.Anotherexampleisusing X11remotely:thedisplaydevicewillsupportdifferentconfigurationsthanthe localdriver.Evenasinglevideocardonthelocalcomputermaysupport differentconfigsfortwomonitorspluggedin. Inpyglet,aDisplayisacollectionof“screens” attachedtoasingledisplaydevice.OnLinux,thedisplaydevicecorresponds totheX11displaybeingused.OnWindowsandMacOSX,thereisonlyone display(astheseoperatingsystemspresentmultiplevideocardsasasingle virtualdevice). Thepyglet.canvasmoduleprovidesaccesstothedisplay(s).Usethe get_display()functiontogetthedefaultdisplay: >>>display=pyglet.canvas.get_display() Note OnX11,youcanusetheDisplayclassdirectlyto specifythedisplaystringtouse,forexampletousearemotelyconnected display.ThenamestringisinthesameformatasusedbytheDISPLAY environmentvariable: >>>display=pyglet.canvas.Display(name=':1') Ifyouhavemultiplephysicalscreensandyou’reusingXinerama,see ScreenstoselectthedesiredscreenasyouwouldforWindows andMacOSX.Otherwise,youcanspecifythescreennumberviathe x_screenargument: >>>display=pyglet.canvas.Display(name=':1',x_screen=1) Screens¶ Onceyouhaveobtainedadisplay,youcanenumeratethescreensthatare connected.Ascreenisthephysicaldisplaymediumconnectedtothedisplay device;forexampleacomputermonitor,TVorprojector.Mostcomputerswill haveasinglescreen,howeverdual-headworkstationsandlaptopsconnectedto aprojectorarecommoncaseswheremorethanonescreenwillbepresent. Inthefollowingexamplethescreensofadual-headworkstationarelisted: >>>forscreenindisplay.get_screens(): ...print(screen) ... XlibScreen(screen=0,x=1280,y=0,width=1280,height=1024,xinerama=1) XlibScreen(screen=0,x=0,y=0,width=1280,height=1024,xinerama=1) BecausethisworkstationisrunningLinux,thereturnedscreensare XlibScreen,asubclassofScreen.The screenandxineramaattributesarespecifictoLinux,butthe x,y, widthand heightattributesarepresentonallscreens, anddescribethescreen’sgeometry,asshownbelow. Examplearrangementofscreensandtheirreportedgeometry.Notethatthe primarydisplay(marked“1”)ispositionedontheright,accordingtothis particularuser’spreference. Thereisalwaysa“default”screen,whichisthefirstscreenreturnedby get_screens().Dependingontheoperatingsystem, thedefaultscreenisusuallytheonethatcontainsthetaskbar(onWindows)or menubar(onOSX). Youcanaccessthisscreendirectlyusing get_default_screen(). OpenGLconfigurationoptions¶ WhenconfiguringorselectingaConfig,youdosobased onthepropertiesofthatconfig.pygletsupportsafixedsubsetofthe optionsprovidedbyAGL,GLX,WGLandtheirextensions.Inparticular,these constraintsareplacedonallOpenGLconfigs: Buffersarealwayscomponent(RGBorRGBA)color,neverpaletteindexed. The“level”ofabufferisalways0(thisparameterislargelyunsupported bymodernOpenGLdriversanyway). Thereisnowaytosetthetransparentcolorofabuffer(again,this GLX-specificoptionisnotwellsupported). Thereisnosupportforpbuffers(equivalentfunctionalitycanbeachieved muchmoresimplyandefficientlyusingframebufferobjects). Thevisibleportionofthebuffer,sometimescalledthecolorbuffer,is configuredwiththefollowingattributes: buffer_size Numberofbitspersample.Commonvaluesare24and32,whicheach dedicate8bitspercolorcomponent.Abuffersizeof16isalso possible,whichusuallycorrespondsto5,6,and5bitsofred,green andblue,respectively. Usuallythereisnoneedtosetthisproperty,asthedevicedriver willselectabuffersizecompatiblewiththecurrentdisplaymode bydefault. red_size,blue_size,green_size,alpha_size Theseeachgivethenumberofbitsdedicatedtotheirrespectivecolor component.Youshouldavoidsettinganyofthered,greenorblue sizes,asthesearedeterminedbythedriverbasedonthe buffer_sizeproperty. Ifyourequireanalphachannelinyourcolorbuffer(forexample,if youarecompositinginmultiplepasses)youshouldspecify alpha_size=8toensurethatthischanneliscreated. sample_buffersandsamples Configuresthebufferformultisampling(MSAA),inwhichmorethan onecolorsampleisusedtodeterminethecolorofeachpixel, leadingtoahigherquality,antialiasedimage. Enablemultisampling(MSAA)bysettingsample_buffers=1,then givethenumberofsamplesperpixeltouseinsamples. Forexample,samples=2isthefastest,lowest-qualitymultisample configuration.samples=4isstillwidelysupported andfairlyperformantevenonIntelHDandAMDVega. MostmodernGPUssupport2×,4×,8×,and16×MSAAsamples withfairlyhighperformance. stereo Createsseparateleftandrightbuffers,forusewithstereohardware. Onlyspecialisedvideohardwaresuchasstereoscopicglasseswill supportthisoption.Whenused,youwillneedtomanuallyrenderto eachbuffer,forexampleusingglDrawBuffers. double_buffer Createseparatefrontandbackbuffers.Withoutdouble-buffering, drawingcommandsareimmediatelyvisibleonthescreen,andtheuser willnoticeavisibleflickerastheimageisredrawninfrontof them. Itisrecommendedtosetdouble_buffer=True,whichcreatesa separatehiddenbuffertowhichdrawingisperformed.Whenthe Window.flipiscalled,thebuffersareswapped, makingthenewdrawingvisiblevirtuallyinstantaneously. Inadditiontothecolorbuffer,severalotherbufferscanoptionallybe createdbasedonthevaluesoftheseproperties: depth_size Adepthbufferisusuallyrequiredfor3Drendering.Thetypical depthsizeis24bits.Specify0ifyoudonotrequireadepth buffer. stencil_size Thestencilbufferisrequiredformaskingtheotherbuffersand implementingcertainvolumetricshadowingalgorithms.Thetypical stencilsizeis8bits;orspecify0ifyoudonotrequireit. accum_red_size,accum_blue_size,accum_green_size,accum_alpha_size Theaccumulationbuffercanbeusedforsimpleantialiasing, depth-of-field,motionblurandothercompositingoperations.Itsuse nowadaysisbeingsupercededbytheuseoffloating-pointtextures, howeveritisstillapracticalsolutionforimplementingthese effectsonolderhardware. Ifyourequireanaccumulationbuffer,specify8foreach oftheseattributes(thealphacomponentisoptional,ofcourse). aux_buffers Eachauxiliarybufferisconfiguredthesameasthecolourbuffer. Uptofourauxiliarybufferscantypicallybecreated.Specify0 ifyoudonotrequireanyauxiliarybuffers. Liketheaccumulationbuffer,auxiliarybuffersareusedlessoften nowadaysasmoreefficienttechniquessuchasrender-to-textureare available.Theyarealmostuniversallyavailableonolderhardware, though,wherethenewertechniquesarenotpossible. IfyouwishtoworkwithOpenGLdirectly,youcanrequestahigherlevel context.ThisisrequiredifyouwishtoworkwiththemodernOpenGL programmablepipeline.Pleasenote,however,thatpygletcurrentlyuses legacyOpenGLfunctionalityformanyofit’sinternalmodules(suchas thetext,graphics,andspritemodules).Requestingahigherversion contextwillcurrentlypreventusageofthesemodules. major_version Thiswillbeeither3or4,foranOpenGL3.xor4.xcontext. minor_version Therequestedminorversionofthecontext.Insomecases,theOpenGL drivermayreturnahigherversionthanrequested. forward_compatible SettingthistoTruewillaskthedrivertoexcludelegacyOpenGL featuresfromthecontext.Khronosdoesnotrecommendthisoption. Note TorequestahigherhigherversionOpenGLcontextonMacOSX,itisnecessary todisablethepygletshadowcontext.Todothis,setthepygletoption pyglet.options['shadow_window']toFalsebeforecreatingaWindow, orimportingpyglet.window. Thedefaultconfiguration¶ IfyoucreateaWindowwithoutspecifyingthecontext orconfig,pygletwilluseatemplateconfigwiththefollowingproperties: double_buffer True depth_size 24 Simplecontextconfiguration¶ Acontextcanonlybecreatedfromaconfigthatwasprovidedbythesystem. Enumeratingandcomparingtheattributesofallthepossibleconfigsis acomplicatedprocess,sopygletprovidesasimplerinterfacebasedon “template”configs. Togettheconfigwiththeattributesyouneed,constructa Configandsetonlytheattributesyouareinterestedin. YoucanthensupplythisconfigtotheWindow constructortocreatethecontext. Forexample,tocreateawindowwithanalphachannel: config=pyglet.gl.Config(alpha_size=8) window=pyglet.window.Window(config=config) Itissometimesnecessarytocreatethecontextyourself,ratherthanletting theWindowconstructordothisforyou.Inthiscase useget_best_config()toobtaina“complete” config,whichyoucanthenusetocreatethecontext: display=pyglet.canvas.get_display() screen=display.get_default_screen() template=pyglet.gl.Config(alpha_size=8) config=screen.get_best_config(template) context=config.create_context(None) window=pyglet.window.Window(context=context) Notethatyoucannotcreateacontextdirectlyfromatemplate(any Configyouconstructedyourself).The Windowconstructorperformsasimilarprocesstothe abovetocreatethecontextifatemplateconfigisgiven. Notallconfigswillbepossibleonallmachines.Thecallto get_best_config()willraise NoSuchConfigExceptionifthehardwaredoesnot supporttherequestedattributes.Itwillneverreturnaconfigthatdoesnot meetorexceedtheattributesyouspecifyinthetemplate. Youcanusethistosupportnewerhardwarefeatureswhereavailable,butalso acceptalesserconfigifnecessary.Forexample,thefollowingcodecreates awindowwithmultisamplingifpossible,otherwiseleavesmultisamplingoff: template=pyglet.gl.Config(sample_buffers=1,samples=4) try: config=screen.get_best_config(template) exceptpyglet.window.NoSuchConfigException: template=gl.Config() config=screen.get_best_config(template) window=pyglet.window.Window(config=config) Selectingthebestconfiguration¶ Allowingpyglettoselectthebestconfigurationbasedonatemplateis sufficientformostapplications,howeversomecomplexprogramsmaywantto specifytheirownalgorithmforselectingasetofOpenGLattributes. Youcanenumerateascreen’sconfigsusingthe get_matching_configs()method.Youmustsupplya templateasaminimumspecification,butyoucansupplyan“empty”template (onewithnoattributesset)togetalistofallconfigurationssupportedby thescreen. Inthefollowingexample,allconfigurationswitheitheranauxiliarybuffer oranaccumulationbufferareprinted: display=pyglet.canvas.get_display() screen=display.get_default_screen() forconfiginscreen.get_matching_configs(gl.Config()): ifconfig.aux_buffersorconfig.accum_red_size: print(config) Aswellassupportingmorecomplexconfigurationselectionalgorithms, enumerationallowsyoutoefficientlyfindthemaximumvalueofanattribute (forexample,themaximumsamplesperpixel),orpresentalistofpossible configurationstotheuser. Sharingobjectsbetweencontexts¶ EverywindowinpyglethasitsownOpenGLcontext.Eachcontexthasitsown OpenGLstate,includingthematrixstacksandcurrentflags.However, contextscanoptionallysharetheirobjectswithoneormoreothercontexts. Shareableobjectsinclude: Textures Displaylists Shaderprograms Vertexandpixelbufferobjects Framebufferobjects Therearetworeasonsforsharingobjects.Thefirstistoallowobjectsto bestoredonthevideocardonlyonce,evenifusedbymorethanonewindow. Forexample,youcouldhaveonewindowshowingtheactualgame,withother “debug”windowsshowingthevariousobjectsastheyaremanipulated.Or,a setofwidgettexturesrequiredforaGUIcouldbesharedbetweenallthe windowsinanapplication. Thesecondreasonistoavoidhavingtorecreatetheobjectswhenacontext needstoberecreated.Forexample,iftheuserwishestoturnon multisampling,itisnecessarytorecreatethecontext.Ratherthandestroy theoldoneandlosealltheobjectsalreadycreated,youcan Createthenewcontext,sharingobjectspacewiththeoldcontext,then Destroytheoldcontext.Thenewcontextretainsalltheoldobjects. pygletdefinesanObjectSpace:arepresentationofa collectionofobjectsusedbyoneormorecontexts.Eachcontexthasasingle objectspace,accessibleviaits object_spaceattribute. Bydefault,allcontextssharethesameobjectspaceaslongasatleastone contextusingitis“alive”.Ifallthecontextssharinganobjectspaceare lostordestroyed,theobjectspacewillbedestroyedalso.Thisiswhyitis necessarytofollowthestepsoutlinedaboveforretainingobjectswhena contextisrecreated. pygletcreatesahidden“shadow”contextassoonaspyglet.glis imported.Bydefault,allwindowswillshareobjectspacewiththisshadow context,sotheabovestepsaregenerallynotneeded.Theshadowcontextalso allowsobjectssuchastexturestobeloadedbeforeawindowiscreated(see shadow_windowinpyglet.optionsforfurtherdetails). WhenyoucreateaContext,youtellpygletwhichother contextitwillobtainanobjectspacefrom.Bydefault(whenusingthe Windowconstructor tocreatethecontext)themostrecentlycreatedcontextwillbeused.You canspecifyanothercontext,orspecifynocontext(tocreateanewobject space)intheContextconstructor. Itcanbeusefultokeeptrackofwhichobjectspaceanobjectwascreatedin. Forexample,whenyouloadafont,pygletcachesthetexturesusedandreuses them;butonlyifthefontisbeingloadedonthesameobjectspace.The easiestwaytodothisistosetyourownattributesonthe ObjectSpaceobject. Inthefollowingexample,anattributeissetontheobjectspaceindicating thatgameobjectshavebeenloaded.Thisway,ifthecontextisrecreated, youcancheckforthisattributetodetermineifyouneedtoloadthemagain: context=pyglet.gl.current_context object_space=context.object_space object_space.my_game_objects_loaded=True AvoidusingattributenamesonObjectSpacethatbeginwith "pyglet",astheymayconflictwithaninternalmodule. ReadtheDocs v:latest Versions master latest Downloads html epub OnReadtheDocs ProjectHome Builds FreedocumenthostingprovidedbyReadtheDocs.
延伸文章資訊
- 1pyglet.gl.ContextException: Unable to share contexts
So when trying to create the window, we have more than one OpenGL context and it throws an except...
- 2pyrender错误修复_lyyiangang的博客
... line 230, in __init__ raise gl.ContextException('Could not create GL context') pyglet.gl.Cont...
- 3Creating an OpenGL context — pyglet v1.5.26
Note that you cannot create a context directly from a template (any Config you constructed yourse...
- 4pyglet.gl.ContextException: Could not create GL context issue
pyglet.gl.ContextException: Could not create GL context. I try installing manima as follows : # I...
- 5about issue #51 pyglet.gl.ContextException: Could not create ...
ContextException: Could not create GL context ... I ask these questions as I am thinking of using...