Az előadás letöltése folymat van. Kérjük, várjon

Az előadás letöltése folymat van. Kérjük, várjon

2D grafikus rendszerek Szirmay-Kalos László.

Hasonló előadás


Az előadások a következő témára: "2D grafikus rendszerek Szirmay-Kalos László."— Előadás másolata:

1 2D grafikus rendszerek Szirmay-Kalos László

2 Interaktív programok felépítése
input csővezeték modellezés Esemény kezelés Pozíció Gyorsulás Wiimote Kamera Kinect Virtuális világ modell output csővezeték From system point of view, a graphics application handles the user input, changes the internal state, called the virtual world by modeling it, and then immediately renders the update model presenting the image to the user. This way, the user immerses into the virtual world, i.e. he feels that he is promptly informed about its current state. The process from the input to the virtual world is called the input pipeline. Similarly, the process mapping the virtual world to the screen is the output pipeline. képszintézis Grafikus hardver

3 Funkcionális modell TV-1 TM-1 Bemeneti csővezeték Eszköz koord.
képtér Képtér- világ Világ- lokális mod. Eszköz koord. (xe, ye) kamera Virtuális világ Kép frissités Kurzor (xp, yp) vektorizáció Pixel op Raszteri- záció Nézet transzf Vágás Kép proj rasztertár Modellezési transzf. TM Kimeneti csővezeték TV

4 Szoftver GLUT Operációs és ablakozó rendszer (Windows) MouseLD()
MouseLU() MouseMov() GLUT Alkalmazás (CPU) Alkalmazás Rasztertár Grafikus könyvtár: OpenGL Rajzolás (GPU) rajzolás Our graphics application runs under the control of an operating system together with other applications. The operating system handles shared resources like input devices and the frame buffer as well, so a pixel data in the frame buffer can be changed only via the operating system. As said, this would be too slow, so a new hardware element shows up that is responsible for many time consuming steps of rendering. The GPU is also a shared device that can be accessed via the operating system. Such accesses are calls to a library for the application program. We shall control the GPU through a C graphics library called OpenGL. On the other hand, to catch input events handled by the operating system, we need another library. We shall utilize the GLUT for this purpose, due to its simplicity and the portability (it runs over MsWindows, Xwindow, etc.) PutPixel()

5 Kimeneti csővezeték: OpenGL
Képszintézis könyvtár, API 3D geometria (2D speciális eset) rajzolási állapot (state) grafikus kártya szolgáltatásai Op. rendszer, ablakozó rendszer független MVC: csak view, nem controller, nem model nem ablakoz nem kezel bemeneti eszközöket nem kezel fájlokat (pl. képformátumok) OpenGL is a C library (it has the same age as C++).

6 OpenGL szintaxis (C könyvtár)
gl könyvtár része glVertex3dv( … ) Paraméterszám 2 - (x, y) 3 - (x, y, z), (R, G, B) 4 - (x, y, z, h) (R, G, B, A) Adattípus b - byte ub - unsigned byte s - short i - int f - float d - double Vektor vagy skalár v - vektor - skalár An OpenGL function name starts with gl indicating that it belongs to the OpenGL library, the second part of the name expresses the meaning or the purpose of this function, and the final part of the name defines the number and type of parameters (note that there is no function overloading in C unlike in C++). For example, glVertex3d is an OpenGL function that sends a vertex down the rendering pipeline, and the vertex is passed as 3 double parameters. If the name includes letter v at the end, the function has a “vector” parameter, i.e. it passes the parameters via a pointer addressing a structure that contains the values.

7 Ablakozó – OpenGL – alkalmazás elhelyezkedése
applikáció glX, wgl GLUT gl glu X v. MS-Win hw Ablak-kezelés widgetek Ablakozó- gl híd Window menedzsment Utility-k, tesszellátorok

8 OpenGL transzformációk (2D-s utánérzés)
Normalizált képernyő x y z=0 h=1 Modelview mátrix Projection mátrix Homogén osztás Viewport transzf. képernyő raszterizáció vágás TM 1,1 -1,-1 TV

9 OpenGL transzformációk
(wr,wt) (wl,wb) 1,1 x y z=0 h=1 Modelview mátrix Projection mátrix -1,-1 TM glMatrixMode(GL_MODELVIEW); glLoadIdentity( ); glTranslatef(px, py, 0); glRotatef(phi, 0, 0, 1); glScalef(sx, sy, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(wl, wr, wb, wt);

10 OpenGL mátrix OpenGL specifikáció: Mi:

11 Mátrix konkatenáció x,y,z,1 MODELVIEW sx sy sz 1 cos f sin f
-sin f cos f 1 1 px py pz 1 1 x,y,z,1 glMatrixMode(GL_MODELVIEW); glLoadIdentity( ); glTranslatef(px, py, pz); glRotatef(phi, 0, 0, 1); glScalef(sx, sy, sz); . . . glVertex2f(x,y);

12 Input/Output kezelés Ablak létrehozás callback main regisztráció
Operációs és ablakozó rendszer (Windows) DisplayFunc GLUT KeyboadFunc KeyboadUpFunc SpecialFunc Reshape callback-ek MouseFunc OpenGL The graphics output is implemented by OpenGL. The application window management and the input are the responsibilities of GLUT. Our application consists of a main function and a set of event handlers (we use event driven programming paradigm in interactive systems). In main, our application program interacts with GLUT and specifies the properties of the application window (e.g. initial resolution and what a single pixel should should store), and also the event handlers. An event handler is a C function that should be programmed by us. This function is connected to a specific event of GLUT, and having established this connection we expect GLUT to call our function when the specific event occurs. A partial list of possible events are: Display event that occurs when the application window becomes invalid and thus GLUT asks us to redraw the window to restore its original content. Keyboard event occurs when the user presses a key having ASCII code. Special event is like Keyboard event but is triggered by a key press having no ASCII code (e.g. arrows and function keys). Reshape handler is called when the dimensions of the application window are changed by the user. Mouse event means the pressing or releasing the button of the mouse. Idle event indicates the time elapsed and our virtual world model should be updated to reflect the new time. Event handler registration is optional with the exception of the Display event. If we do not register a handler function, nothing special happens when this event occurs. grafikus hardver MotionFunc IdleFunc applikáció

13 OpenGL alkalmazás (GLUT) main függvény
Ablak megnyitás Rajzolási állapot inicializálás Display callback: képernyő törlés, állapotváltás, rajzolás, buffercsere Reshape callback: Nézet (viewport), kamera transzformácó átállítása Input callback (mouse, keyboard) Idle callback (animáció) Üzenethurok

14 OpenGL/ GLUT inicializálás
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> // download!!! main( int argc, char *argv[] ) { glutInitWindowSize(200, 200); glutInitWindowPosition(100, 100); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE ); glutCreateWindow("Sample Window"); // callback függvények glutKeyboardFunc( Keyboard ); glutDisplayFunc( ReDraw ); // transzformáció glViewport(0, 0, 200, 200); glMatrixMode(GL_MODELVIEW); glLoadIdentity( ); glMatrixMode(GL_PROJECTION); // fő hurok glutMainLoop(); } (100,100) OpenGL/ GLUT inicializálás 200 200 (1,1) Our first GLUT/OpenGL program will draw a green triangle in the application window. - glutInit initializes the GLUT system. - glutInitWindowSize speficies the resolution of the application window when it is first created and shown (of course, this can be changed later by the user). glutInitWindowPosition sets the initial position of the application window. glutInitDisplayMode( GLUT_RGB ) tells the windowing system that a single pixel will store 8 bit red, green, blue components (true color mode). glutCreateWindow creates the application window and shows it to the user with the specified caption bar text. Keyboard is our function (implemented on the next slide). glutKeyboardFunc connects our Keyboard function to the event of pressing ASCII code keys of the keyboard. ReDraw is also our function, which is connected to the event that the application window gets invalid. The viewport is set to cover the entire application window (parameters are the left-bottom corner, width and height). Both the ModelView and the Projection transformations are set to unit transformation, which means that vertices arrive without any modification at the normalized device space. That is, we should define our scene directly in normalized device space where x,y,z are in [-1,1]. glutMainLoop is the message loop, an infinite loop that checks whether events occur and if we registered a handler for that event type, it calls the registered handler. (-1,-1)

15 Eseménykezelés és rajzolás
(1,1) void ReDraw( ) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glutSwapBuffers( ); } void Keyboard(unsigned char key, int x, int y) { if (key == ‘d’) { glColor3d( 0.0, 1.0, 0.0 ); glBegin(GL_TRIANGLES); glVertex2d(-0.8,-0.8); glVertex2d(-0.6, 1.0); glVertex2d( 0.8,-0.2); glEnd( ); (-1,-1) viewport (200,200) Here are the two event handlers. ReDraw has been associated with the Display event (meaning that the application window got invalid), and Keyboard with the Keyboard event meaning that a key of ASCII code was pressed. In ReDraw, first the clear color is specified as black, then the frame buffer is cleared in this application window. In Keyboard, we check whether key ‘d’ is pressed (without Shift) and if yes, it sets the drawing color to green with glColor, then sends a triangle to the rendering pipeline. All types of geometry are sent by first specifying the type as a parameter of the glBegin function (now a sequence of triangles, where each triangle is defined by three consecutive vertices), the vertices are given until the pass initiated with glBegin is closed with glEnd. OpenGL is a state machine, thus attributes (for example, the draw color) remain the same until it is altered. Should the three vertices have different colors, the color could be modified between glVertex calls. glFlush empties the buffer to make even the last bit be processed by the GPU (this is very similar to the flush used in file management).

16 A háromszög újrarajzoláskor megmarad
bool haromszog = false; void ReDraw( ) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); if ( haromszog ) { glColor3d( 0.0, 1.0, 0.0 ); glBegin(GL_TRIANGLES); glVertex2d(-0.8, -0.8); glVertex2d(-0.6, 1.0); glVertex2d(0.8, -0.2); glEnd( ); } glutSwapBuffers(); void Keyboard(unsigned char key, int x, int y) { if (key == 'd') { haromszog = true; ReDraw( ); A háromszög újrarajzoláskor megmarad The triangle does not disappear when the application window is validated if we redraw it in the ReDraw function. Thus, the drawing part is moved to here, which also means that in Keyboard, the Display event handler should be invoked.

17 Nem rajzol feleslegesen sokszor
bool haromszog = false; void ReDraw( ) { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); if ( haromszog ) { glColor3d( 0.0, 1.0, 0.0 ); glBegin(GL_TRIANGLES); glVertex2d(-0.8, -0.8); glVertex2d(-0.6, 1.0); glVertex2d(0.8, -0.2); glEnd( ); } glutSwapBuffers( ); void Keyboard(unsigned char key, int x, int y) { if (key == 'd') { haromszog = true; glutPostRedisplay(); Nem rajzol feleslegesen sokszor We can save redundant redraws if instead of explicitly redrawing the application window, it is just invalidated. Now matter how many times the application window is invalidated, validation requires just a single Redraw.

18 OpenGL: primitívek glBegin(primitív típus); Csúcspont tulajdonságok …
glVertex3f(x, y, z); glEnd( ); OpenGL: primitívek GL_LINES GL_LINE_STRIP GL_POINTS GL_POLYGON GL_LINE_LOOP OpenGL processes points, line segments and triangles, which can be given in many different ways that reduce glVertex calls. POLYGON and QUAD are not recommended since in these cases OpenGL will substitute them by triangles and we cannot control the triangulation process (it may be different on different systems). On the other hand, OpenGL uses a very simple POLYGON to triangle conversion, which works for convex polygons but there is no guarantee for non-convex ones (the utility package has correct polygon triangulation methods, but we can also implement one, for example, with the ear cutting algorithm). GL_QUADS GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_FAN GL_TRIANGLE_STRIP

19 Házi //=========================================================================================== // Szamitogepes grafika hazi feladat keret. Ervenyes 2013-tol. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni. // A program csak ebben a fajlban lehet, a fajl 1 byte-os ASCII karaktereket tartalmazhat. // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni (printf is fajlmuvelet!) // - new operatort hivni az onInitialization-t kivéve, a lefoglalt adat felszabadítása nélkül // - felesleges programsorokat a beadott programban hagyni // - tovabbi kommenteket a beadott programba irni a forrasmegjelolest kommentjeit kiveve // // A feladatot ANSI C++ … , // // A feladatmegoldasokban csak olyan gl/glu/glut fuggvenyek hasznalhatok, amelyek // 1. Az oran a feladatkiadasig elhangzottak ES (logikai AND muvelet) // 2. Az alabbi listaban szerepelnek: … // ... // NYILATKOZAT // Nev : <VEZETEKNEV(EK)> <KERESZTNEV(EK)> // Neptun : <NEPTUN KOD> // ezennel kijelentem, hogy a feladatot magam keszitettem, es ha barmilyen segitseget // igenybe vettem …, akkor a forrast es az atvett reszt kommentekben egyertelmuen jeloltem ... //============================================================================================ #include <math.h> #include <stdlib.h> #if defined(__APPLE__) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h>

20 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Innentol modosithatod...
class Vector { … }; class Color { … }; Color image[screenWidth*screenHeight];// kép void onInitialization( ) {// Inicializacio, glViewport(0, 0, screenWidth, screenHeight); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f);// torlesi szin beallitasa glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // kepernyo torles glDrawPixels(screenWidth, screenHeight, GL_RGB, GL_FLOAT, image); glColor3f(0,0,1); glBegin(GL_TRIANGLES); glVertex2f(-0.2f, -0.2f); … glEnd(); glutSwapBuffers(); void onKeyboard(unsigned char key, int x, int y) { // Billentyuzet esemeny if (key == 'd') glutPostRedisplay( ); // d beture rajzold ujra a kepet void onKeyboardUp(unsigned char key, int x, int y) { } void onMouse(int button, int state, int x, int y) {// Eger esemeny if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN); void onMouseMotion(int x, int y) { } void onIdle( ) {// `Idle' esemenykezelo, jelzi, hogy az ido telik long time = glutGet(GLUT_ELAPSED_TIME); // program inditasa ota eltelt ido // ...Idaig modosithatod~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Házi

21 Még mindig házi // A C++ program belepesi pontja, nem bántani!
int main(int argc, char **argv) { glutInit(&argc, argv); // GLUT inicializalasa glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); // 8 bites R,G,B,A + dupla buffer + melyseg buffer glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); // A MODELVIEW egysegmatrix glLoadIdentity(); glMatrixMode(GL_PROJECTION); // A PROJECTION egysegmatrix onInitialization(); // Az altalad irt inicializalas glutDisplayFunc(onDisplay); // Esemenykezelok regisztralasa glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutKeyboardUpFunc(onKeyboardUp); glutMotionFunc(onMouseMotion); glutMainLoop();// Esemenykezelo hurok return 0; }

22 1. házi: Джугашвили spline
Készítsen Джугашвили-spline-t alkalmazó rajzolóprogramot! A Джугашвили-spline-ban minden két kontrollpont között egy görbeszegmens található, amit a két interpolálandó pont, az azokban felvett sebesség és a kezdeti gyorsulásvektor határoz meg. A felhasználó az egér balgomb egyszeri lenyomással/elengedéssel (B1CLK) veszi fel a kontrollpontokat (max 100-at), amelyek paramétere az aktuális idő lesz sec egységben, majd balgomb dupla klikkel (B2CLK) kijelölt pont és az első pont közötti vektort rendeli a legelső kontrollponthoz, tripla klikkel (B3CLK) pedig ugyanígy tesz a gyorsulásvektorral. A többi belső kontrollpontban a sebességvektor az előző kontrollpont és a jelenlegi kontrollpont közötti egyenesvonalú egyenletes mozgás sebességének és a jelenlegi és rákövetkező pont közötti egyenesvonalú mozgás sebességének az átlaga. A legutolsó kontrollpontban a sebesség zérus. A legelső szegmenst kivéve, a kezdeti gyorsulás az előző szegmens végpontjában kiadódó gyorsulással egyezik meg. A B[1|2|3]CLK műveletek alatt az egér nem mozdul meg, B2CLK esetén két lenyomásnak 0.3 sec-on belül, B3CLK esetén három lenyomásnak kell jönnie úgy, hogy kettő között max 0.3 sec idő telik el. Kezdetben a képernyőn a (x= m; y= m) része látszik a virtuális világnak. A kameraablakot ipad-esen lehet mozgatni, azaz a bal egérgombot lenyomva elrántjuk az egeret egy irányba (BMOV), és az indításhoz képest 0.5 sec múlva mért elmozdulásvektor ellentettjének harmadát tekintjük az ablak kezdeti sebességének. A súrlódási együtthatót úgy kell beállítani, hogy a legnagyobb rántás esetén is a kép mozgása 50%-t elmozdulás után megáll. A space lenyomásával egy kört indítunk el a görbén, amely a paramétert időnek tekintve végiganimál rajta.


Letölteni ppt "2D grafikus rendszerek Szirmay-Kalos László."

Hasonló előadás


Google Hirdetések