OpenGL with PyOpenGL tutorial Python and PyGame p.1
文章推薦指數: 80 %
OpenGL with PyOpenGL introduction and creation of Rotating Cube ... to your perspective, not in relation to your actual location within the 3D environment. search Home +=1 SupporttheContent Community Login Signup Home +=1 SupporttheContent Community Login Signup OpenGLwithPyOpenGLintroductionandcreationofRotatingCube WhenIfirstbeganlookingintoOpenGLwithPython,mymaingoalwastofigureouthowtomakearotatingcube.Idon'tthinkIamalone,sincethisseemstobethepinnacleofunderstandingthebasicsofOpenGL.Assuch,IhavecompiledthisfirstvideotoincludeeverythingfromacquiringPython,PyOpenGL,andPyGame,tocreatingthenecessarycodetomakearotatingcube.Thisfirsttutorialisquitelong,butIwantedtogoaheadandputeverythingintothisvideo.IhadaveryhardtimefiguringoutOpenGL,mainlybecausemostoftheOpenGLwithPyOpenGLtutorialsthatIcouldfindwereclearlywrittenforsomeonewhoalreadyknewOpenGL.Ididnot,sothiswasamassivehurdleforme.HopefullyIcanhelpyoualllearnitmuchfasterthanIdid. Firstoff,PyOpenGLisjustsomePythonbindings(somePythoncodethatactslikeasortofwrapperaroundnativecode),soyoucanmanipulateOpenGLwithinthecontextofPython.OpenGLisacross-languageAPI,soyoucantakeyourknowledgeofOpenGLtootherlanguages. So,thewayOpenGLworksisyoujustspecifytheobjectswithinspace.Foracube,forexample,youspecifythe"corners."Cornersarereferredtoasvertices(plural)orasavertex(singular).Youmayalsoseethemreferredtoasanode(singular)ornodes(plural). Onceyoudefinethevertices,youcanthendothingswiththem.Inthisexample,wewanttodrawlinesbetweenthem.DefiningtheverticesisdonewithasimplelistortupleinPython.Youcanthenpre-definesomeruleslikewhatverticesmakeupa"surface"andbetweenwhatverticesarethe"edges,"orlinesthatwewanttohavedrawnbetweenthevertices. Onceyoudothat,thenyou'rereadytowritetheOpenGLcode.Todothis,youhaveglBeginandglEndstatementsthatyoucall,andbetweentheseiswheretheOpenGL-specificcodegoes.IntheglBeginstatement,youspecifythe"type"ofcodethatyouareabouttopass.Theseareconstants,andcontainthingslikeGL_QUADSorGL_LINES.ThisbasicallynotifiesOpenGLhowyouwantittohandleyourstatements. Sothat'stheabstractconceptofhowOpenGLworks,let'sgoaheadanddoit! First,youwillneedtohavethefollowing: Python PyOpenGL PyGame IfyouareaWindowsuser,thenIhighlyrecommenddownloadingPyGameandPyOpenGLfromthissourceofWindowsbinariesforPythonModules.Justsavethatlinktoyourbookmarks.Superusefulwebsite. Onceyouhaveeverything,goaheadandopenupIDLEandtypein: importpygame importOpenGL Ifyoucantypethosestatementsandrunthemwithoutanyerrors,thenyouarereadytoproceed.Ifyouaregettingerrors,somethingwentwrong.Mostofthetime,theerroriseitheryou'vedownloadedthewrongPythonversionofPyGameorOpenGL,orthewrongbitversion.So,ifyouareusing32bitPython,youneedtouse32bitmodules,andsoon.Evenifyouroperatingsystemisa64bitOS,youmaystillfindyou'rerunninga32bitversionofPython.Ihighlyrecommendusing64bitPythonifyoucan,32bitislimitedto2GBofram,whichisquitethelimitation.Ifyouhavea32bitOS,thenyoucannotuse64bit. Alright,nowlet'sgetintothecode!IfyoustillhavetheimportpygameandimportOpenGLcode,erasethatandstartcompletelyblank. First,we'regoingtodosomeimports: importpygame frompygame.localsimport* fromOpenGL.GLimport* fromOpenGL.GLUimport* We'reimportingallofPyGamehere,andthenallofthePyGame.locals.ThisissometypicalPyGamecode.IfyouwanttolearnabunchmoreaboutPyGame,checkoutthePyGamePythonprogrammingseriesIofferhere. Next,weimportOpenGL.GLandOpenGL.GLU.OpenGL.GLisjustyourtypicalOpenGLfunctions,thenOpenGL.GLUissomeofthemore"fancy"OpenGLfunctions. Forthefirstfewvideos,Igoaheadandmiss-spellvertices.Oops. vertices=( (1,-1,-1), (1,1,-1), (-1,1,-1), (-1,-1,-1), (1,-1,1), (1,1,1), (-1,-1,1), (-1,1,1) ) Here,we'vedefinedthelocation(x,y,z)ofeachvertex.Ithinkitisbesttoenvisionthisin"units."Trytothinkoftheselocations"spatially."Withacube,thereare8"nodes"orvertices. Next,we'rereadytodefinetheedges: edges=( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7) ) Eachoftheabovetuplescontainstwonumbers.Thosenumberscorrespondtoavertex,andthe"edge"isgoingtobedrawnbetweenthosetwovertices.Westartwith0,sincethat'showPythonandmostprogramminglanguageswork(thefirstelementis0).So,0correspondstothefirstvertexwedefined(1,-1,-1)...andsoon. Nowthatwe'vegotthat,let'sworkontherequiredcodetoworkwithOpenGLtoactuallygenerateacube: defCube(): glBegin(GL_LINES) foredgeinedges: forvertexinedge: glVertex3fv(vertices[vertex]) glEnd() First,westartoffourfunctionaswewouldanyotherfunction. Next,sincethisisjustafunctioncontainingOpenGLcode,wegoaheadandopenwithaglBegin(GL_LINES),thisnotifiesOpenGLthatwe'reabouttothrowsomecodeatit,andthentheGL_LINEStellsOpenGLhowtohandlethatcode,which,inthiscase,meansitwilltreatthecodeasline-drawingcode. Fromthere,wesayforedgeinedges,whichcorrespondstoeachpairofverticesinouredgeslist.Sinceeachedgecontains2vertices,wethensayforvertexinedge,doglVertex3fv(vertices[vertex]),whichperformstheglVertex3fvOpenGLfunctiononthe[vertex]elementoftheverticestuple. Assuch,whatendsupbeingpassedthroughOpenGLwiththeconstantofGL_LINESis: glVertex3fv((1,-1,-1)) glVertex3fv((1,1,-1)) ...andsoon.OpenGL,knowingthatwe'redrawinglinesherewilldrawlinesbetweenthosepoints. Afterrunningthroughalledges,we'redone,sowecallglEnd()tonotifyOpenGLthatwe'redonetellingitwhattodo.Foreach"type"ofOpenGLcodethatyouplantouse,youwillneedopeningandclosingGLcommandslikethis. That'sitforourcubefunction.Thisfunctionwillcreatethecube,butnowwewanttodisplaythecubeandspecifyourperspectiveintheenvironment: defmain(): pygame.init() display=(800,600) pygame.display.set_mode(display,DOUBLEBUF|OPENGL) ThisismostlytypicalPyGamecode.Ifyouwanttounderstanditmore,checkoutthePyGamePythonprogrammingseries. Theonlymajordifferencehereiswe'readdinganother"parameter"lookingthingafter"display"inthepygame.display.set_mode.Theseareactuallyconstants,notifyingPyGamethatwe'regoingtobefeedingitOpenGLcode,aswellasDOUBLEBUF,whichstandsfordoublebuffer,andisatypeofbufferingwheretherearetwobufferstocomplywithmonitorrefreshrates.Takenotethatpipe("|")thatisusedtoseparateconstants.Itwillbeusedagainlatertoseparateconstants. Next,withinthismain()function: gluPerspective(45,(display[0]/display[1]),0.1,50.0) gluPerspectiveiscodethatdeterminestheperspective,asitsounds.Thefirstvalueisthedegreevalueofthefieldofview(fov).Thesecondvalueistheaspectratio,whichisthedisplaywidthdividedbythedisplayheight.Thenexttwovaluesherearetheznearandzfar,whicharethenearandfarclippingplanes. Whatintheheckisaclippingplane?Ifyou'relikeme,thatmeansnothingtoyouatthispoint.Basically,aclippingplaneisatwhatdistancedoestheobjectappear/disappear.Sotheobjectwillonlybevisiblebetweenthesetwovalues,andbothvaluesaresupposedtobepositive,becausetheyareinrelationtoyourperspective,notinrelationtoyouractuallocationwithinthe3Denvironment. So,we'rehavingthecloseclippinghappeningat0.1unitsandthefarclippingplaneas50.0unitsaway.Thiswillmakemoresenselater,oncewe'vedisplayedthecubeandwecancontrolwhereweareinthe3Denvironment,thenyouwillseetheclippingplanesinaction. Nextup,wehave: glTranslatef(0.0,0.0,-5) glTranslatef,officially"multipliesthecurrentmatrixbyatranslationmatrix."OKcool,againthatmeansnothingtome.So,inlayman'sterms,thisbasicallymovesyou,andtheparametersarex,yandz.Soabove,we'removingback5unites.Thisissowecanactuallyseethecubewhenwebringitup.Otherwise,we'dbeabittooclose. Nowlet'swriteourtypicaleventloopforPyGame.Again,ifyouwanttolearnmore,checkouttheaforementionedtutorial. whileTrue: foreventinpygame.event.get(): ifevent.type==pygame.QUIT: pygame.quit() quit() ThisisasimplePyGameeventloopthatisonlycheckingforanyexit,whichisonlylookingfortheliteral"x"out.Continuingunderthis"while"statement: glRotatef(1,3,1,1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) glRotatefmultipliesthecurrentmatrixbyarotationmatrix.Theparametershereareangle,x,yandz. ThenwehaveglClear,whichislikeanyotherclearingfunction.Wespecifyacoupleofconstantshere,whichistellingOpenGLwhatexactlywe'reclearing. Oncewehaveaclean"canvas"ifyouwill,wethencallourCube()function. Afterthat,wecallpygame.display.flip(),whichupdatesourdisplay. Finallywethrowinashortwaitwithpygame.time.wait(10). That'sitforourmainfunction,andnowwejustcallamain()attheendtomakeitallwork.Justincaseyougotlostsomewhere,here'stheentirescriptputtogether: importpygame frompygame.localsimport* fromOpenGL.GLimport* fromOpenGL.GLUimport* verticies=( (1,-1,-1), (1,1,-1), (-1,1,-1), (-1,-1,-1), (1,-1,1), (1,1,1), (-1,-1,1), (-1,1,1) ) edges=( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7) ) defCube(): glBegin(GL_LINES) foredgeinedges: forvertexinedge: glVertex3fv(verticies[vertex]) glEnd() defmain(): pygame.init() display=(800,600) pygame.display.set_mode(display,DOUBLEBUF|OPENGL) gluPerspective(45,(display[0]/display[1]),0.1,50.0) glTranslatef(0.0,0.0,-5) whileTrue: foreventinpygame.event.get(): ifevent.type==pygame.QUIT: pygame.quit() quit() glRotatef(1,3,1,1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) main() Theendresultshouldbe: AwesomeandcongratulationsonyourPyOpenGLcube!Thereisobviouslyalotmoretolearn,andsomeofthesefunctionsmaynotmaketoomuchsensejustyet.I'llbegoingoverthoseabitmoreindepthsoon. Thenexttutorial:ColoringSurfacesaswellasunderstandsomeofthebasicOpenGLcode OpenGLwithPyOpenGLintroductionandcreationofRotatingCube ColoringSurfacesaswellasunderstandsomeofthebasicOpenGLcode Go Understandingnavigationwithinthe3DenvironmentviaOpenGL Go Movingtheplayerautomaticallytowardsthecube Go RandomCubePosition Go AddingManyCubestoourGame Go AddingagroundinOpenGL Go Infiniteflyingcubes Go Optimizingtheprocessingforinfinitecubes Go
延伸文章資訊
- 1A Loading and Rendering 3D Models with OpenGL and ...
Beyond chapter 3, when we start writing programs that transform and animate graphics, I begin to ...
- 2用PyOpenGL叩開3D的心扉——OpenGL全解析(3) - 程式人生
對Python來說可能不是很重要,不過還是要說明一下,OpenGL函式有d(double)的版本,C/C++語言一般預設浮點數就是double,使用d版本函式可能會顯得比較 ...
- 3OpenGL with PyOpenGL tutorial Python and PyGame p.1
OpenGL with PyOpenGL introduction and creation of Rotating Cube ... to your perspective, not in r...
- 4PyOpenGL:是一個調用OpenGL的2D/3D的python圖形庫
1 說明1.1 PyOpenGL:是一個調用OpenGL的2D/3D的python圖形庫。1.2 OpenGL:1.2.1 Open Graphics Library,開放圖形庫或者。1.2.2...
- 53d opengl python - CSDN
适用于Python的OpenGL 3D游戏引擎。 版本0.7 MIT许可证。 工作正在进行中。 渲染示例视频要求: 2.7或3.4+ pip install pysdl2 pip install...