ebook img

Learn OpenGL: Learn modern OpenGL graphics programming in a step-by-step fashion. PDF

525 Pages·2020·54.684 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Learn OpenGL: Learn modern OpenGL graphics programming in a step-by-step fashion.

Theonlineversionofthistextlivesatlearnopengl.com. Copyright c 2020byJoeydeVries (cid:31) ALLRIGHTSRESERVED Thelayoutandstylingofthisbookisbasedonthepublic’LegrandOrangeBook’LaTeXtemplate byVel. Firstprinting,June2020 ISBN:978-90-90-33256-7 Contents 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 I Getting started 2 OpenGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Creating a window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4 Hello Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 5 Hello Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6 Shaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 7 Textures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 8 Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 9 Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 10 Camera. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 11 Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 II Lighting 12 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110 13 Basic Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115 14 Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 15 Lighting Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132 16 Light Casters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 17 Multiple lights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 18 Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155 III Model Loading 19 Assimp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158 20 Mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 21 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .165 IV Advanced OpenGL 22 Depth Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .175 23 Stencil testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182 24 Blending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .188 25 Face culling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 26 Framebuffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 27 Cubemaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 28 Advanced Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .226 29 Advanced GLSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .229 30 Geometry Shader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .242 31 Instancing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .256 32 Anti Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266 V Advanced Lighting 33 Advanced Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .275 34 Gamma Correction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279 35 Shadow Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285 36 Point Shadows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .302 37 Normal Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 38 Parallax Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 39 HDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .338 40 Bloom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 41 Deferred Shading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .353 42 SSAO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .366 VI PBR 43 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 44 Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .396 45 Diffuse irradiance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405 46 Specular IBL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .420 5 VII In Practice 47 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .440 48 Text Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .452 VIII 2D Game 49 Breakout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .462 50 Setting up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464 51 Rendering Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 52 Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .473 53 Ball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .480 54 Collision detection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483 55 Collision resolution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .489 56 Particles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .495 57 Postprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 58 Powerups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .506 59 Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .513 60 Render text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .515 61 Final thoughts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .523 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .525 Firstofall,awarmthankyouforpurchasingthisbook. Thecontentofthisbookoriginally started outas digital letters onthe online platformat learnopengl.com. LearnOpenGL quickly evolvedfromaseriesoftutorials, toafullonlinebookwithyearsofcontinuousfeedbackand improvementsthatarenowfinallyaggregatedintothephysicalcopyyouholdinyourhands. Theonlineversionatlearnopengl.comisfree,andwillalwaysbefree,andforthemostupto datecontentandquestionsfromreadersitisstilladvisedtosearchuparticlesontheonlineplatform. However,aphysicalcopymakesiteasytoreadduringtravel,writenotes,andweshouldneverforget thatcertaincharmofprintedpaper.Andnottoforget,purchasingaphysicalcopyhelpssupportme asanauthorforwhichIagainthankyoufromthebottomofmyheart. Thebookisstructuredsimilarlytotheonlineplatform,withafewminordifferencestoaccount forthebookbeingoffline.Thinkofalargereductionofhyperlinks,hyperlinksbeingfullywritten out,videosnowshowingstaticimages,andthelackoffunctionhoverpop-ups. Thecontenthas howeverbeenthoroughlyrevised,andreviewedmultipletimes,toensurethebookisafirst-class citizenthat’suptotheprofessionalstandardsyou’dexpect. Ifyou’dliketostartyourjourneyintographicsprogrammingyou’vegotagreatpathahead ofyou. Thisbookwillteachyou,stepbystep,thefoundationandskillsofbecomingagraphics programmer.You’lllearn3Dfundamentals,basicandadvancedlighting,modelloading,blending, post-processing,shadows,debugging,PBR,andsomuchmore;andwe’llevenwalkyouthrough theprocessofcreatingafull2Dgame.Ifyou’reasexcitedasIamIwillnowstoptalkingandsee youinthefirstchapter. //Joey 1. Introduction Sinceyoucamehereyouprobablywanttolearntheinnerworkingsofcomputergraphicsanddoall thestuffthecoolkidsdobyyourself.Doingthingsbyyourselfisextremelyfunandresourcefuland givesyouagreatunderstandingofgraphicsprogramming.However,thereareafewitemsthatneed tobetakenintoconsiderationbeforestartingyourjourney. 1.1 Prerequisites SinceOpenGLisagraphicsAPIandnotaplatformofitsown,itrequiresalanguagetooperate inandthelanguageofchoiceisC++. ThereforeadecentknowledgeoftheC++programming languageisrequiredforthesetutorials. However,Iwilltrytoexplainmostoftheconceptsused, includingadvancedC++topicswhererequiredsoitisnotrequiredtobeanexpertinC++,but youshouldbeabletowritemorethanjusta’Hello World’program.Ifyoudon’thavemuch experiencewithC++Icanrecommendthefreetutorialsatwww.learncpp.com. Also, we will be using some math (linear algebra, geometry, and trigonometry) along the wayandIwilltrytoexplainalltherequiredconceptsofthemathrequired. However,I’mnota mathematicianbyheartsoeventhoughmyexplanationsmaybeeasytounderstand,theywillmost likelybeincomplete.SowherenecessaryIwillprovidepointerstogoodresourcesthatexplainthe materialinamorecompletefashion.Don’tbescaredaboutthemathematicalknowledgerequired beforestartingyourjourneyintoOpenGL;almostalltheconceptscanbeunderstoodwithabasic mathematicalbackgroundandIwilltrytokeepthemathematicstoaminimumwherepossible. Mostofthefunctionalitydoesn’tevenrequireyoutounderstandallthemathaslongasyouknow howtouseit. 1.2 Structure LearnOpenGLisbrokendownintoanumberofgeneralsections. Eachsectioncontainsseveral chaptersthateachexplaindifferentconceptsinlargedetail. Thesubjectsaretaughtinalinear fashion(soitisadvisedtostartfromstarttofinish,unlessotherwiseinstructed)whereeachchapter explainsthebackgroundtheoryandthepracticalaspects. Tomaketheconceptseasiertofollow,andgivethemsomeaddedstructure,thebookcontains boxes,codeblocks,andcolorhints. 1.2.1 Boxes Greenboxesencompassessomenotesorusefulfeatures/hintsaboutOpenGLorthe subjectathand. Redboxeswillcontainwarningsorotherfeaturesyouhavetobeextracarefulwith. 1.2.2 Code Youwillfindplentyofsmallpiecesofcodeinthebookthatarelocatedindark-grayboxeswith syntax-highlightedcodeasyoucanseebelow: // This box contains code Sincetheseprovideonlysnippetsofcode,wherevernecessaryyou’llfindapathtothefullsource codeofthechapterdemo(s). ThesourcecodepathsarerelativetotherootoftheLearnOpenGL repositoryonGitHubwhichyoucanfindat: github.com/JoeyDeVries/learnopengl. Therepositorycontainsfullsourcecodesamplesforeverychapter.It’srecommendedtodownload 8 Chapter1.Introduction the repository and review the full source code samples at the end of each chapter to see how everythingfitstogetherasawhole. 1.2.3 Colorhints Somewordsaredisplayedwithadifferentcolortomakeitextraclearthesewordsportrayaspecial meaning: • Definition: greenwordsspecifyadefinitioni.e. animportantaspect/nameofsomething you’relikelytohearmoreoften. • Program structure:redwordsspecifyfunctionnamesorclassnames. • Variables:bluewordsspecifyvariablesincludingallOpenGLconstants. Nowthatyougotabitofafeelofthestructureofthebook,hopovertotheGettingStarted sectiontostartyourjourneyinOpenGL! I Getting started 2 OpenGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Creating a window . . . . . . . . . . . . . . . . . . . . . 14 4 Hello Window . . . . . . . . . . . . . . . . . . . . . . . . . . 20 5 Hello Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6 Shaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 7 Textures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 8 Transformations . . . . . . . . . . . . . . . . . . . . . . . . 67 9 Coordinate Systems . . . . . . . . . . . . . . . . . . . . 82 10 Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 11 Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 2. OpenGL BeforestartingourjourneyweshouldfirstdefinewhatOpenGLactuallyis. OpenGLismainly consideredanAPI(anApplicationProgrammingInterface)thatprovidesuswithalargesetof functionsthatwecanusetomanipulategraphicsandimages.However,OpenGLbyitselfisnotan API,butmerelyaspecification,developedandmaintainedbythewww.khronos.org/. TheOpenGLspecificationspecifiesexactlywhattheresult/outputofeachfunctionshouldbe andhowitshouldperform.Itisthenuptothedevelopersimplementingthisspecificationtocomeup withasolutionofhowthisfunctionshouldoperate.SincetheOpenGLspecificationdoesnotgive usimplementationdetails,theactualdevelopedversionsofOpenGLareallowedtohavedifferent implementations,aslongastheirresultscomplywiththespecification(andarethusthesametothe user). ThepeopledevelopingtheactualOpenGLlibrariesareusuallythegraphicscardmanufacturers. EachgraphicscardthatyoubuysupportsspecificversionsofOpenGLwhicharetheversionsof OpenGLdevelopedspecificallyforthatcard(series). WhenusinganApplesystemtheOpenGL libraryismaintainedbyApplethemselvesandunderLinuxthereexistsacombinationofgraphic suppliers’versionsandhobbyists’adaptationsoftheselibraries. Thisalsomeansthatwhenever OpenGLisshowingweirdbehaviorthatitshouldn’t,thisismostlikelythefaultofthegraphics cardsmanufacturers(orwhoeverdeveloped/maintainedthelibrary). Sincemostimplementationsarebuiltbygraphicscardmanufacturers.Wheneverthereis abugintheimplementationthisisusuallysolvedbyupdatingyourvideocarddrivers; thosedriversincludethenewestversionsofOpenGLthatyourcardsupports.Thisisone ofthereasonswhyit’salwaysadvisedtooccasionallyupdateyourgraphicdrivers. KhronospubliclyhostsallspecificationdocumentsforalltheOpenGLversions.Theinterested readercanfindtheOpenGLspecification1ofversion3.3(whichiswhatwe’llbeusing),whichis agoodreadifyouwanttodelveintothedetailsofOpenGL(notehowtheymostlyjustdescribe resultsandnotimplementations).Thespecificationsalsoprovideagreatreferenceforfindingthe exactworkingsofitsfunctions. 2.1 Core-profile vs Immediate mode In the old days, using OpenGL meant developing in immediate mode (often referred to as the fixed function pipeline) which was an easy-to-use method for drawing graphics. Most of the functionalityofOpenGLwashiddeninsidethelibraryanddevelopersdidnothavemuchcontrol overhowOpenGLdoesitscalculations.Developerseventuallygothungryformoreflexibilityand overtimethespecificationsbecamemoreflexibleasaresult;developersgainedmorecontrolover theirgraphics. Theimmediatemodeisreallyeasytouseandunderstand,butitisalsoextremely inefficient.Forthatreasonthespecificationstartedtodeprecateimmediatemodefunctionalityfrom version3.2onwardsandstartedmotivatingdeveloperstodevelopinOpenGL’score-profilemode, whichisadivisionofOpenGL’sspecificationthatremovedallolddeprecatedfunctionality. WhenusingOpenGL’score-profile,OpenGLforcesustousemodernpractices.Wheneverwe trytouseoneofOpenGL’sdeprecatedfunctions,OpenGLraisesanerrorandstopsdrawing.The 1www.opengl.org/registry/doc/glspec33.core.20100311.withchanges.pdf

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.