Graphics Programming Principles and Algorithms

Total Page:16

File Type:pdf, Size:1020Kb

Graphics Programming Principles and Algorithms Graphics Programming Principles and Algorithms Zongli Shi May 27, 2017 Abstract This paper is an introduction to graphics programming. This is a computer science field trying to answer questions such as how we can model 2D and 3D objects and have them displayed on screen. Researchers in this field are constantly trying to find more efficient algorithms for these tasks. We are going to look at basic algorithms for modeling and drawing line segments, 2D and 3D polygons. We are also going to explore ways to transform and clip 2D and 3D polygons. For illustration purpose, the algorithms presented in this paper are implemented in C++ and hosted at GitHub. Link to the GitHub repository can be found in the introduction paragraph. 1 Introduction Computer graphics has been playing a vital role in communicating computer-generated information to human users as well as providing a more intuitive way for users to interact with computers. Al- though nowadays, devices such as touch screens are everywhere, the effort of developing graphics system in the first place and beauty of efficient graphics rendering algorithms should not be underes- timated. Future development in graphics hardware will also bring new challenges, which will require us to have a thorough understanding of the fundamentals. This paper will mostly investigate the various problems in graphics programming and the algorithms to solve them. All of the algorithms are also presented in the book Computer Graphics by Steven Harrington [Har87]. This paper will also serve as a tutorial, instructing the readers to build a complete graphics system from scratch. At the end we shall have a program manipulating basic bits and bytes but capable of generating 3-D animation all by itself. To better assist the reader in implementing the algorithms presented in this paper, the writer's implementation in C++ can be found in the following GitHub link: https://github.com/shizongli94/graphics_programming. 2 Basic Problems in Graphics The basic problems in graphics programming are similar to those in any task of approximation. The notion of shapes such as polygons and lines are abstract, and by their definitions, continuous in their nature. A line can extend to both directions forever. A polygon can be made as large as we want. However, most display devices are represented as a rectangle holding finitely many individual displaying units called pixels. The size of the screen limits the size of our shapes and the amount of pixels limit how much detail we can put on screen. Therefore, we are trying to map something continuous and infinite in nature such as lines and polygons to something discrete and finite. In this process, some information has to be lost but we should also try to approximate the best we can. We will first look at how to draw a line on screen to illustrate the process of building a discrete representation and how to recover as much lost information as we can. 1 3 Drawing a Line Segment Since a line is infinite in its nature, we have to restrict ourselves to drawing line segments, which will a be reasonable representation of infinite line when going from one side of a screen to another. The simplest way to represent a line segment is to have the coordinates of its two end points. One way of drawing a line segment will be simply starting with one end point and on the way of approaching the other, turning on pixels. This approach resembles our experience of drawing a line segment on paper, but it poses two questions. First, on what criterion should we select a pixel? And second, if the criterion is set, how do we efficiently select the required pixels? For the first question, let us define X as the pixel on row r and column c, and the lines y = r and x = c running through X and intersecting at its center. We also denote L as the line segment with end points (x1; y1) and (x2; y2) where x1 ≤ x2. We then will have a criterion when jmj < 1=2 (m is the slope) as follows: Pixel X will be turned on if y1 < r < y2, x1 < c < x2 and if the intersecting point of x = c and L is within the boundaries of X. We shall not be concerned with when the line crosses x = c at one of the boundaries of pixel X, because choosing either pixel adjacent to this boundary has no effect on our line representation. Notice that we are using the typical mathematical coordinate system with origin at the lower left corner despite most device manufacturers putting the origin at the upper left corner of a screen. Also we are going to use indices starting from 0 instead of 1. This is the typical approach in computer programming. This is for the case jmj < 1=2. For future reference, we call it the gentle case. For the steeper case when jmj > 1=2, we simply re-label the x-axis as the y-axis and y-axis as the x-axis. When labels are interchanged, those two cases are basically the same. They both have the absolute value of slope smaller than 1=2. But why do we bother to divide into two cases? We will see in a moment that this division into cases dramatically simplifies our problem of selecting pixels. When looking at Figure1, we see that pixel at (1; 1) is selected and turned as well as the pixel at (2; 2). The pixel at (0; 0) is not selected even though the line segment starts within its boundaries. The pixel at (2; 1) is not selected either even though there is a portion of the line segment running through it. 4 The First Algorithm: DDA The first algorithm we are going to introduce is DDA. It stands for Digital Differential Analyzer. Before we start to see how the algorithm works, let's first answer why we need to divide line drawing into two cases and restrict ourselves only to the gentle case. Referring to Figure1 and only considering positive slope, notice that when the line segment starts from the pixel at (0; 0), it faces two choices. If it is gentle enough, it will enter the pixel at (1; 0) and crosses x = 1 before leaving it. Otherwise, it will go into pixel (1; 1) and cross its line x = 1 before leaving it. However, it will never be able to reach the pixel (1; 2), because its slope is no larger than 1=2. Therefore we only need to choose one out of the two possible pixels. Furthermore, we already know where the two pixels are located. If the pixel where the line segment starts is at row y0 and column x0, the two pixels we need to choose from will both be in the next column x0 +1. One of them will be in row x0, same as the original pixel. The other will be in row x0 + 1, only one level above the original pixel. Then our algorithm can be described as starting with one pixel, and scanning each column of pixels from left to right. Every time when we are entering the next column, we either choose the pixel in the same row as the pixel in the previous column, or we choose the pixel in the row one level above the pixel in the previous column. When the slope is negative, we still only have two pixels to choose from. If the pixel we start from is at (x0y0), then the pixels we choose from are (x0 + 1; y0) and (x0 + 1; y0 − 1). For future explanations, we are going to use the grid in Figure2 as representation of a screen. Notice the origin in the grid is the lower left corner of a rectangular screen. The pixels below x-axis and the pixels to the left of y-axis are not shown on screen. For simplicity, the upper and right boundaries of the screen are not shown. 2 y = 2 y = 1 y = 0 x = 0 x = 1 x = 2 Figure 1: Criterion on how to select a pixel y x Figure 2: A Screen of Pixels 3 y P0 B0 x Figure 3: An Example of DDA Algorithm y P1 B1 x Figure 4: The state of the program right after coloring a pixel in the second column To understand an algorithm, it is always helpful to have a sense of the idea behind it. For DDA, when we are scanning the columns one by one, the movement from one column to another is essentially the same as adding 1 each time to the x-coordinate. Since a straight line has a constant rate of change, we can exploit this property by adding m, the value of slope, to the y-coordinate each time we move to a new column. This is the idea behind DDA. To describe the implementation details, we define a crossing point to be the point where the line segment of interest crosses the center line of a column. We obtain the coordinates of first crossing point P0 as (x0; y0) and distance h between P0 and B0, which is the central point of the row boundary right below P0. We use h to determine if we want to color subsequent pixels. When we move to the column x0 + 1, we add m to h. If h < 1, we color the pixel (x0 + 1; y0). If h > 1, we color the pixel (x0 + 1; y0 + 1) and we subtract 1 from h. However, we can not use h to determine the first pixel we want to color because there is not a pixel in the previous color we can refer to.
Recommended publications
  • Using Typography and Iconography to Express Emotion
    Using typography and iconography to express emotion (or meaning) in motion graphics as a learning tool for ESL (English as a second language) in a multi-device platform. A thesis submitted to the School of Visual Communication Design, College of Communication and Information of Kent State University in partial fulfillment of the requirements for the degree of Master of Fine Arts by Anthony J. Ezzo May, 2016 Thesis written by Anthony J. Ezzo B.F.A. University of Akron, 1998 M.F.A., Kent State University, 2016 Approved by Gretchen Caldwell Rinnert, M.G.D., Advisor Jaime Kennedy, M.F.A., Director, School of Visual Communication Design Amy Reynolds, Ph.D., Dean, College of Communication and Information TABLE OF CONTENTS TABLE OF CONTENTS .................................................................................... iii LIST OF FIGURES ............................................................................................ v LIST OF TABLES .............................................................................................. v ACKNOWLEDGEMENTS ................................................................................ vi CHAPTER 1. THE PROBLEM .......................................................................................... 1 Thesis ..................................................................................................... 6 2. BACKGROUND AND CONTEXT ............................................................. 7 Understanding The Ell Process ..............................................................
    [Show full text]
  • 3D Graphics Fundamentals
    11BegGameDev.qxd 9/20/04 5:20 PM Page 211 chapter 11 3D Graphics Fundamentals his chapter covers the basics of 3D graphics. You will learn the basic concepts so that you are at least aware of the key points in 3D programming. However, this Tchapter will not go into great detail on 3D mathematics or graphics theory, which are far too advanced for this book. What you will learn instead is the practical implemen- tation of 3D in order to write simple 3D games. You will get just exactly what you need to 211 11BegGameDev.qxd 9/20/04 5:20 PM Page 212 212 Chapter 11 ■ 3D Graphics Fundamentals write a simple 3D game without getting bogged down in theory. If you have questions about how matrix math works and about how 3D rendering is done, you might want to use this chapter as a starting point and then go on and read a book such as Beginning Direct3D Game Programming,by Wolfgang Engel (Course PTR). The goal of this chapter is to provide you with a set of reusable functions that can be used to develop 3D games. Here is what you will learn in this chapter: ■ How to create and use vertices. ■ How to manipulate polygons. ■ How to create a textured polygon. ■ How to create a cube and rotate it. Introduction to 3D Programming It’s a foregone conclusion today that everyone has a 3D accelerated video card. Even the low-end budget video cards are equipped with a 3D graphics processing unit (GPU) that would be impressive were it not for all the competition in this market pushing out more and more polygons and new features every year.
    [Show full text]
  • Flood Insurance Rate Map (FIRM) Graphics Guidance
    Guidance for Flood Risk Analysis and Mapping Flood Insurance Rate Map (FIRM) Graphics November 2019 Requirements for the Federal Emergency Management Agency (FEMA) Risk Mapping, Assessment, and Planning (Risk MAP) Program are specified separately by statute, regulation, or FEMA policy (primarily the Standards for Flood Risk Analysis and Mapping). This document provides guidance to support the requirements and recommends approaches for effective and efficient implementation. The guidance, context, and other information in this document is not required unless it is codified separately in the aforementioned statute, regulation, or policy. Alternate approaches that comply with all requirements are acceptable. For more information, please visit the FEMA Guidelines and Standards for Flood Risk Analysis and Mapping webpage (www.fema.gov/guidelines-and-standards-flood-risk-analysis-and- mapping). Copies of the Standards for Flood Risk Analysis and Mapping policy, related guidance, technical references, and other information about the guidelines and standards development process are all available here. You can also search directly by document title at www.fema.gov/library. FIRM Graphics November 2019 Guidance Document 6 Page i Document History Affected Section or Date Description Subsection This guidance has been revised to align various November descriptions and specifications to standard operating Sections 4.3 and 5.2 2019 procedures, including labeling of structures and application of floodway and special floodway notes. FIRM Graphics November
    [Show full text]
  • Introduction to Scalable Vector Graphics
    Introduction to Scalable Vector Graphics Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Introduction.............................................................. 2 2. What is SVG?........................................................... 4 3. Basic shapes............................................................ 10 4. Definitions and groups................................................. 16 5. Painting .................................................................. 21 6. Coordinates and transformations.................................... 32 7. Paths ..................................................................... 38 8. Text ....................................................................... 46 9. Animation and interactivity............................................ 51 10. Summary............................................................... 55 Introduction to Scalable Vector Graphics Page 1 of 56 ibm.com/developerWorks Presented by developerWorks, your source for great tutorials Section 1. Introduction Should I take this tutorial? This tutorial assists developers who want to understand the concepts behind Scalable Vector Graphics (SVG) in order to build them, either as static documents, or as dynamically generated content. XML experience is not required, but a familiarity with at least one tagging language (such as HTML) will be useful. For basic XML
    [Show full text]
  • An Online System for Classifying Computer Graphics Images from Natural Photographs
    An Online System for Classifying Computer Graphics Images from Natural Photographs Tian-Tsong Ng and Shih-Fu Chang fttng,[email protected] Department of Electrical Engineering Columbia University New York, USA ABSTRACT We describe an online system for classifying computer generated images and camera-captured photographic images, as part of our effort in building a complete passive-blind system for image tampering detection (project website at http: //www.ee.columbia.edu/trustfoto). Users are able to submit any image from a local or an online source to the system and get classification results with confidence scores. Our system has implemented three different algorithms from the state of the art based on the geometry, the wavelet, and the cartoon features. We describe the important algorithmic issues involved for achieving satisfactory performances in both speed and accuracy as well as the capability to handle diverse types of input images. We studied the effects of image size reduction on classification accuracy and speed, and found different size reduction methods worked best for different classification methods. In addition, we incorporated machine learning techniques, such as fusion and subclass-based bagging, in order to counter the effect of performance degradation caused by image size reduction. With all these improvements, we are able to speed up the classification speed by more than two times while keeping the classification accuracy almost intact at about 82%. Keywords: Computer graphics, photograph, classification, online system, geometry features, classifier fusion 1. INTRODUCTION The level of photorealism capable by today’s computer graphics makes distinguishing photographic and computer graphic images difficult.
    [Show full text]
  • Graphics Formats and Tools
    Graphics formats and tools Images à recevoir Stand DRG The different types of graphics format Graphics formats can be classified broadly in 3 different groups -Vector - Raster (or bitmap) - Page description language (PDL) Graphics formats and tools 2 Vector formats In a vector format (revisable) a line is defined by 2 points, the text can be edited Graphics formats and tools 3 Raster (bitmap) format A raster (bitmap) format is like a photograph; the number of dots/cm defines the quality of the drawing Graphics formats and tools 4 Page description language (PDL) formats A page description language is a programming language that describes the appearance of a printed page at a higher level than an actual output bitmap Adobe’s PostScript (.ps), Encapsulated PostScript (.eps) and Portable Document Format (.pdf) are some of the best known page description languages Encapsulated PostScript (.eps) is commonly used for graphics It can contain both unstructured vector information as well as raster (bitmap) data Since it comprises a mixture of data, its quality and usability are variable Graphics formats and tools 5 Background Since the invention of computing, or more precisely since the creation of computer-assisted drawing (CAD), two main professions have evolved - Desktop publishing (DTP) developed principally on Macintosh - Computer-assisted drawing or design (CAD) developed principally on IBM (International Business Machines) Graphics formats and tools 6 Use of DTP applications Used greatly in the fields of marketing, journalism and industrial design, DTP applications fulfil the needs of various professions - from sketches and mock-ups to fashion design - interior design - coachwork (body work) design - web page design -etc.
    [Show full text]
  • Interactive Topographic Web Mapping Using Scalable Vector Graphics
    University of Nebraska at Omaha DigitalCommons@UNO Student Work 12-1-2003 Interactive topographic web mapping using scalable vector graphics Peter Pavlicko University of Nebraska at Omaha Follow this and additional works at: https://digitalcommons.unomaha.edu/studentwork Recommended Citation Pavlicko, Peter, "Interactive topographic web mapping using scalable vector graphics" (2003). Student Work. 589. https://digitalcommons.unomaha.edu/studentwork/589 This Thesis is brought to you for free and open access by DigitalCommons@UNO. It has been accepted for inclusion in Student Work by an authorized administrator of DigitalCommons@UNO. For more information, please contact [email protected]. INTERACTIVE TOPOGRAPHIC WEB MAPPING USING SCALABLE VECTOR GRAPHICS A Thesis Presented to the Department of Geography-Geology and the Faculty of the Graduate College University of Nebraska in Partial Fulfillment of the Requirements for the Degree Master of Arts University of Nebraska at Omaha by Peter Pavlicko December, 2003 UMI Number: EP73227 All rights reserved INFORMATION TO ALL USERS The quality of this reproduction is dependent upon the quality of the copy submitted. In the unlikely event that the author did not send a complete manuscript and there are missing pages, these will be noted. Also, if material had to be removed, a note will indicate the deletion. Dissertation WWisMng UMI EP73227 Published by ProQuest LLC (2015). Copyright in the Dissertation held by the Author. Microform Edition © ProQuest LLC. All rights reserved. This work is protected against unauthorized copying under Title 17, United States Code ProQuest LLC. 789 East Eisenhower Parkway P.O. Box 1346 Ann Arbor, Ml 48106-1346 THESIS ACCEPTANCE Acceptance for the faculty of the Graduate College, University of Nebraska, in Partial fulfillment of the requirements for the degree Master of Arts University of Nebraska Omaha Committee ----------- Uf.A [JL___ Chairperson.
    [Show full text]
  • Rendering Synthetic Objects Into Real Scenes
    ToappearintheSIGGRAPH98conferenceproceedings RenderingSyntheticObjectsintoRealScenes: BridgingTraditionalandImage-basedGraphicswithGlobalIllumination andHighDynamicRangePhotography PaulDebevec UniversityofCaliforniaatBerkeley 1 ABSTRACT 1Introduction Renderingsyntheticobjectsintoreal-worldscenesisanimportant Wepresentamethodthatusesmeasuredsceneradianceandglobal applicationofcomputergraphics,particularlyinarchitecturaland illuminationinordertoaddnewobjectstolight-basedmodelswith visualeffectsdomains.Oftentimes,apieceoffurniture,aprop,or correctlighting.Themethodusesahighdynamicrangeimage- adigitalcreatureoractorneedstoberenderedseamlesslyintoa basedmodelofthescene,ratherthansyntheticlightsources,toil- realscene.Thisdif®culttaskrequiresthattheobjectsbelitcon- luminatethenewobjects.Tocomputetheillumination,thesceneis sistentlywiththesurfacesintheirvicinity,andthattheinterplayof consideredasthreecomponents:thedistantscene,thelocalscene, lightbetweentheobjectsandtheirsurroundingsbeproperlysimu- andthesyntheticobjects.Thedistantsceneisassumedtobepho- lated.Speci®cally,theobjectsshouldcastshadows,appearinre¯ec- tometricallyunaffectedbytheobjects,obviatingtheneedforre- tions,andrefract,focus,andemitlightjustasrealobjectswould. ¯ectancemodelinformation.Thelocalsceneisendowedwithes- timatedre¯ectancemodelinformationsothatitcancatchshadows andreceivere¯ectedlightfromthenewobjects.Renderingsare createdwithastandardglobalilluminationmethodbysimulating Distant theinteractionoflightamongstthethreecomponents.Adifferen- Scene tialrenderingtechniqueallowsforgoodresultstobeobtainedwhen
    [Show full text]
  • Applied Art and Design (AAD) 1
    Applied Art and Design (AAD) 1 AAD 0053. Publication Design II APPLIED ART AND DESIGN Units: 3 Prerequisite: Completion of AAD 52, 54 or 62 with grade of "C" or better (AAD) Hours: 72 (36 lecture, 36 activity) Page layout for developing and producing high-quality multi-page AAD 0012. Visual Communication documents. Emphasis on publication design, production, typography, Units: 3 graphics, and pre-press. Includes research and application of effective Also known as COMM 12 magazine layout concepts, cover design, grid theory, graphics, text Hours: 54 lecture elements and printing standards and processes. (CSU) Study of visual communication including design principles, aesthetics, AAD 0054. Typography visual perception, non-verbal messages, relationship to verbal Units: 3 communication, audience analysis, mass media and persuasion. Prerequisite: Completion of AAD 52, 53, 61, 62, or 75 with grade of "C" or Historical overview of visual media as well as current trends and better technology. (C-ID JOUR 170) (CSU, UC) Advisory: Completion of AAD 60 with grade of "C" or better AAD 0020. Portfolio Development and Presentation Hours: 72 (36 lecture, 36 activity) Units: 3 A professional and historical approach to understanding typographic Advisory: Completion of AAD 70, 75, or 85 with grade of "C" or better principles and form, effects of type on the style and communication Hours: 72 (36 lecture, 36 activity) in print and screen. Includes study of historical and contemporary Function and use of the portfolio as a marketing device for artists and graphics and typographic design, conceptualizing, developing and designers. Styles, materials, resources in portfolio design. Evaluation of refining typographical forms, methods for analyzing typographic usage, professional goals and image building.
    [Show full text]
  • Graphics and Visualization (GV)
    1 Graphics and Visualization (GV) 2 Computer graphics is the term commonly used to describe the computer generation and 3 manipulation of images. It is the science of enabling visual communication through computation. 4 Its uses include cartoons, film special effects, video games, medical imaging, engineering, as 5 well as scientific, information, and knowledge visualization. Traditionally, graphics at the 6 undergraduate level has focused on rendering, linear algebra, and phenomenological approaches. 7 More recently, the focus has begun to include physics, numerical integration, scalability, and 8 special-purpose hardware, In order for students to become adept at the use and generation of 9 computer graphics, many implementation-specific issues must be addressed, such as file formats, 10 hardware interfaces, and application program interfaces. These issues change rapidly, and the 11 description that follows attempts to avoid being overly prescriptive about them. The area 12 encompassed by Graphics and Visual Computing (GV) is divided into several interrelated fields: 13 • Fundamentals: Computer graphics depends on an understanding of how humans use 14 vision to perceive information and how information can be rendered on a display device. 15 Every computer scientist should have some understanding of where and how graphics can 16 be appropriately applied and the fundamental processes involved in display rendering. 17 • Modeling: Information to be displayed must be encoded in computer memory in some 18 form, often in the form of a mathematical specification of shape and form. 19 • Rendering: Rendering is the process of displaying the information contained in a model. 20 • Animation: Animation is the rendering in a manner that makes images appear to move 21 and the synthesis or acquisition of the time variations of models.
    [Show full text]
  • 3D Computer Graphics Compiled By: H
    animation Charge-coupled device Charts on SO(3) chemistry chirality chromatic aberration chrominance Cinema 4D cinematography CinePaint Circle circumference ClanLib Class of the Titans clean room design Clifford algebra Clip Mapping Clipping (computer graphics) Clipping_(computer_graphics) Cocoa (API) CODE V collinear collision detection color color buffer comic book Comm. ACM Command & Conquer: Tiberian series Commutative operation Compact disc Comparison of Direct3D and OpenGL compiler Compiz complement (set theory) complex analysis complex number complex polygon Component Object Model composite pattern compositing Compression artifacts computationReverse computational Catmull-Clark fluid dynamics computational geometry subdivision Computational_geometry computed surface axial tomography Cel-shaded Computed tomography computer animation Computer Aided Design computerCg andprogramming video games Computer animation computer cluster computer display computer file computer game computer games computer generated image computer graphics Computer hardware Computer History Museum Computer keyboard Computer mouse computer program Computer programming computer science computer software computer storage Computer-aided design Computer-aided design#Capabilities computer-aided manufacturing computer-generated imagery concave cone (solid)language Cone tracing Conjugacy_class#Conjugacy_as_group_action Clipmap COLLADA consortium constraints Comparison Constructive solid geometry of continuous Direct3D function contrast ratioand conversion OpenGL between
    [Show full text]
  • Guidance for Flood Risk Analysis and Mapping
    Guidance for Flood Risk Analysis and Mapping Flood Insurance Rate Map (FIRM) Graphics December 2020 Requirements for the Federal Emergency Management Agency (FEMA) Risk Mapping, Assessment, and Planning (Risk MAP) Program are specified separately by statute, regulation, or FEMA policy (primarily the Standards for Flood Risk Analysis and Mapping). This document provides guidance to support the requirements and recommends approaches for effective and efficient implementation. The guidance, context, and other information in this document is not required unless it is codified separately in the aforementioned statute, regulation, or policy. Alternate approaches that comply with all requirements are acceptable. For more information, please visit the FEMA Guidelines and Standards for Flood Risk Analysis and Mapping webpage (www.fema.gov/flood-maps/guidance-partners/guidelines-standards). Copies of the Standards for Flood Risk Analysis and Mapping policy, related guidance, technical references, and other information about the guidelines and standards development process are all available here. You can also search directly by document title at www.fema.gov/multimedia-library. FIRM Graphics December 2020 Guidance Document 6 Page i Table of Revisions The following summary of changes details revisions to this document subsequent to its most recent version in November 2019. Affected Section or Date Description Subsection December Section 1 Added section for Automated Map Production 2020 December Sections 6.7 and 6.8 Added evaluation lines for 2D modeling
    [Show full text]