2.First Polygon

Posted clairvoyant

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.First Polygon相关的知识,希望对你有一定的参考价值。

  1 #include <windows.h>
  2 #include <gl/glew.h>
  3 #include <gl/glut.h>
  4 
  5 /*
  6  *  Every OpenGL program is linked to a Rendering Context.
  7  *  A Rendering Context is what links OpenGL calls to the Device Context.
  8  *  In order for your program to draw to a Window you need to create a Device Context.
  9  *  The DC connects the Window to the GDI (Graphics Device Interface).
 10  */
 11 
 12 HGLRC     hRC = NULL;         // Permanent rendering context
 13 HDC       hDC = NULL;         // Private GDI device context
 14 HWND      hWnd = NULL;        // Holds our window handle
 15 HINSTANCE hInstance;          // Holds the instance of the application
 16 
 17 /*
 18  *  It‘s important to make this global so that each procedure knows if 
 19  *  the program is running in fullscreen mode or not.
 20  */
 21 
 22 bool keys[256];         // Array used for the keyboard routine
 23 bool active = TRUE;     // Window active flag set to TRUE by default
 24 bool fullscreen = TRUE; // Fullscreen flag set to fullscreen mode by default
 25 
 26 /*
 27  *  CreateGLWindow() has a reference to WndProc() but WndProc() comes after CreateGLWindow().
 28  */
 29 
 30 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration for WndProc
 31 
 32 /*
 33  *  The job of the next section of code is to resize the OpenGL scene 
 34  *  whenever the window (assuming you are using a Window rather than fullscreen mode) has been resized.
 35  */
 36 
 37 GLvoid ReSizeGLScene(GLsizei width, GLsizei height)   // Resize and initialize the GL window
 38 {
 39     if (height == 0) {                                // Prevent a divide by zero by
 40         height = 1;                                   // Making height equal one
 41     }
 42     
 43     glViewport(0, 0, width, height);                  // Reset the current viewport
 44 
 45     /*
 46      *  The following lines set the screen up for a perspective view. 
 47      *  Meaning things in the distance get smaller. This creates a realistic looking scene. 
 48      *  The perspective is calculated with a 45 degree viewing angle based on 
 49      *  the windows width and height. The 0.1f, 100.0f is the starting point and 
 50      *  ending point for how deep we can draw into the screen.
 51      *
 52      *  The projection matrix is responsible for adding perspective to our scene.
 53      *  glLoadIdentity() restores the selected matrix to it‘s original state.
 54      *  The modelview matrix is where our object information is stored.
 55      *   Lastly we reset the modelview matrix.
 56      */
 57 
 58     glMatrixMode(GL_PROJECTION);                      // Select the projection matrix
 59     glLoadIdentity();                                 // Reset the projection matrix
 60     
 61                                                       // Calculate the aspect ratio of the window
 62     gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
 63 
 64     glMatrixMode(GL_MODELVIEW);                       // Seclet the modelview matrix
 65     glLoadIdentity();                                 // Reset the modelview matrix
 66 }
 67 
 68 int InitGL(GLvoid)                                    // All setup for OpenGL goes here
 69 {
 70     /*
 71      *  Smooth shading blends colors nicely across a polygon, and smoothes out lighting.
 72      */
 73     
 74     glShadeModel(GL_SMOOTH);                          // Enables smooth shading
 75 
 76     glClearColor(0.0f, 0.0f, 0.0f, 0.0f);             // Black background
 77 
 78     /*
 79      *  Think of the depth buffer as layers into the screen. 
 80      *  The depth buffer keeps track of how deep objects are into the screen.
 81      */
 82 
 83     glClearDepth(1.0f);                               // Depth buffer setup
 84     glEnable(GL_DEPTH_TEST);                          // Enable depth testing
 85     glDepthFunc(GL_LEQUAL);                           // The typr of depth test to do
 86 
 87     /*
 88      *  Next we tell OpenGL we want the best perspective correction to be done. 
 89      *  This causes a very tiny performance hit, but makes the perspective view look a bit better.
 90      */
 91 
 92     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);   // Really nice perspective calculations
 93 
 94     return TRUE;
 95 }
 96 
 97 /*
 98  *  For now all we will do is clear the screen to the color we previously decided on, 
 99  *  clear the depth buffer and reset the scene. We wont draw anything yet.
100  */
101 /******************************************************************************************************************************************/
102 /******************************************************************************************************************************************/
103 int DrawGLScene(GLvoid)                                  // Here‘s where we do all the drawing
104 {
105     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clear the screen and the depth buffer
106     glLoadIdentity();                                    // Reset the current modelview matrix
107     
108     /*
109      *  When you do a glLoadIdentity() what you are doing is moving back to 
110      *  the center of the screen with the X axis(轴) running left to right, 
111      *  the Y axis moving up and down, and the Z axis moving into, and out of the screen.
112      */
113     /*
114      *  glTranslatef(x, y, z) moves along the X, Y and Z axis, in that order.
115      *  When you translate, you are not moving a set amount(数量) from the center of the screen, 
116      *  you are moving a set amount from wherever you currently were on the screen.
117      */
118     glTranslatef(-1.5f, 0.0f, -6.0f);                    // Move left 1.5 units and into the screen 6.0
119     glBegin(GL_TRIANGLES);                               // Drawing using traingles
120         glVertex3f(0.0f, 1.0f, 0.0f);                    // Top
121         glVertex3f(-1.0f, -1.0f, 0.0f);                  // Bottom left
122         glVertex3f(1.0f, -1.0f, 0.0f);                   // Bottom right
123     glEnd();                                             // Finished drawing the traingles
124 
125     glTranslatef(3.0f, 0.0f, 0.0f);                      // Move left 3 units
126     
127     /*
128      *  By drawing in a clockwise order, the square will be drawn as a back face. 
129      *  Meaning the side of the quad we see is actually the back. 
130      *  Objects drawn in a counter clockwise order will be facing us.
131      */
132 
133     glBegin(GL_QUADS);                                   // Draw a quad
134         glVertex3f(-1.0f, 1.0f, 0.0f);                   // Top left
135         glVertex3f(1.0f, 1.0f, 0.0f);                    // Top right
136         glVertex3f(1.0f, -1.0f, 0.0f);                   // Bottom right
137         glVertex3f(-1.0f, -1.0f, 0.0f);                  // Bottom left
138     glEnd();                                             // Done drawing the quad
139     return TRUE;                                         // everthing went OK
140 }
141 /******************************************************************************************************************************************/
142 /******************************************************************************************************************************************/
143 /*
144  *  The job of KillGLWindow() is to release the Rendering Context, 
145  *  the Device Context and finally the Window Handle. 
146  */
147 
148 GLvoid KillGLWindow(GLvoid)                              // Properly kill the window
149 {
150     if (fullscreen) {                                    // Are we in fullscreen mode
151         
152         /*
153          *  We use ChangeDisplaySettings(NULL,0) to return us to our original desktop.
154          *  After we‘ve switched back to the desktop we make the cursor visible again.
155          */
156 
157         ChangeDisplaySettings(NULL, 0);                  // if so switch back to the desktop
158         ShowCursor(TRUE);                                // Show mouse pointer
159     }
160 
161     if (hRC) {                                           // Do we have a rendering context
162         if (!wglMakeCurrent(NULL, NULL)) {                // Are we able to release the DC and RC contexts
163             MessageBox(NULL, "Release of DC and RC failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
164         }
165 
166         if (!wglDeleteContext(hRC)) {                     // Are we able to delete the RC
167             MessageBox(NULL, "Release rendering context failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
168             hRC = NULL;                                  // Set RC to NULL
169         }
170 
171         if (hDC && !ReleaseDC(hWnd, hDC)) {              // Are we able to release the DC
172             MessageBox(NULL, "Release device context failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
173             hDC = NULL;                                  // Set DC to NULL
174         }
175         if (hWnd && !DestroyWindow(hWnd)) {              // Are we able to destroy the window
176             MessageBox(NULL, "Could not release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
177             hWnd = NULL;                                 // Set hWnd to NULL
178         }
179 
180         if (!UnregisterClass("OpenGL", hInstance)) {     // Are we able to unregister class
181             MessageBox(NULL, "Could not register class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
182             hInstance = NULL;                            // Set hInstance to NULL
183         }
184     }
185 }
186 
187 /*
188  * The next section of code creates our OpenGL Window.
189  */
190 
191 BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
192 {
193     /*
194      * Find  a pixel format that matches the one we want
195      */
196     GLuint PixelFormat;                                  // Holds the result after serching for a match
197     
198     /*
199      * Before you create a window, you MUST register a Class for the window
200      */
201     WNDCLASS wc;                                         // Windows class structure
202 
203     /*
204      *  dwExStyle and dwStyle will store the Extended and normal Window Style Information.
205     */
206     DWORD dwExStyle;                                     // Window extend style
207     DWORD dwStyle;                                       // Window style
208 
209     RECT WindowRect;                                     // Grabs rectangle upper left/lower right values
210     WindowRect.left = (long)0;                           // Set left value to 0
211     WindowRect.right = (long)width;                      // Set right value to requested width
212     WindowRect.top = (long)0;                            // Set top value to 0
213     WindowRect.bottom = (long)height;                    // Set bottom value to requested height
214 
215     fullscreen = fullscreenflag;                         // Set the global fullscreen flag
216 
217     /*
218      *  The style CS_HREDRAW and CS_VREDRAW force the Window to redraw whenever it is resized. 
219      *  CS_OWNDC creates a private DC for the Window. Meaning the DC is not shared across applications. 
220      *  WndProc is the procedure that watches for messages in our program. 
221      *  No extra Window data is used so we zero the two fields. Then we set the instance. 
222      *  Next we set hIcon to NULL meaning we don‘t want an ICON in the Window, 
223      *  and for a mouse pointer we use the standard arrow. The background color doesn‘t matter 
224      *  (we set that in GL). We don‘t want a menu in this Window so we set it to NULL, 
225      *  and the class name can be any name you want. I‘ll use "OpenGL" for simplicity.
226      */
227     hInstance = GetModuleHandle(NULL);                   // Grab an instance for our window
228     wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;       // Redraw on move, and own DC for window
229     wc.lpfnWndProc = (WNDPROC)WndProc;                   // WndProc handles message
230     wc.cbClsExtra = 0;                                   // No extra window date
231     wc.cbWndExtra = 0;                                   // No extra window date
232     wc.hInstance = hInstance;                            // set the instance
233     wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);              // Load the default icon
234     wc.hCursor = LoadCursor(NULL, IDC_ARROW);            // Load the arrow pointer
235     wc.hbrBackground = NULL;                             // No background requried for GL
236     wc.lpszMenuName = NULL;                              // We don‘t want a menu
237     wc.lpszClassName = "OpenGL";                         // set the class name
238 
239     if (!RegisterClass(&wc)) {                           // Attempt to register the window class
240         MessageBox(NULL, "Failed to register the window class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
241         return FALSE;                                    // Exit and return false
242     }
243 
244     if (fullscreen) {                                    // attempt fullsreen model
245         
246         /*
247         T*  here are a few very important things you should keep in mind when switching to full screen mode.
248          *  Make sure the width and height that you use in fullscreen mode is the same as 
249          *  the width and height you plan to use for your window, and most importantly,
250          *  set fullscreen mode BEFORE you create your window.
251          */
252         DEVMODE dmScreenSettings;                        // Device mode
253         memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Make sure memory‘s cleared
254         dmScreenSettings.dmSize = sizeof(dmScreenSettings);     // Size of devmode structure
255         dmScreenSettings.dmPelsWidth = width;            // Select window width
256         dmScreenSettings.dmPelsHeight = height;          // Select window height
257         dmScreenSettings.dmBitsPerPel = bits;            // Select bits per pixel
258         dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
259         
260         /*
261          *  In the line below ChangeDisplaySettings tries to switch to a mode that matches 
262          *  what we stored in dmScreenSettings. I use the parameter CDS_FULLSCREEN when switching modes, 
263          *  because it‘s supposed to remove the start bar at the bottom of the screen, 
264          *  plus it doesn‘t move or resize the windows on your desktop when you switch to 
265          *  fullscreen mode and back.
266          */
267         //Try to set selected mode and get results. Note: CDS_FULLSCREEN gets rid of start bar
268         if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
269             //If the mode fails, offer two options. Quit or run in a window
270             if (MessageBox(NULL, "The requested fullscreen mode is not supported by\n your video card. Use"
271                 "windowed mode instead?", "GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
272             {
273                 fullscreen = FALSE;                       // Select windowed mode (fullscreen=FLASE)
274             }
275             else {
276                 // Pop up a message box letting user know the programe is closing.
277                 MessageBox(NULL, "Program will now close.", "ERROR", MB_OK | MB_ICONSTOP);
278                 return FALSE;                             // Exit and return FALSE
279             }
280         }
281     }
282 
283     if (fullscreen) {                                     // Are we still in fullscreen mode
284         
285         /*
286          *  If we are still in fullscreen mode we‘ll set the extended style to WS_EX_APPWINDOW, 
287          *  which force a top level window down to the taskbar once our window is visible. 
288          *  For the window style we‘ll create a WS_POPUP window. 
289          *  This type of window has no border around it, making it perfect for fullscreen mode.
290 
291          *  Finally, we disable the mouse pointer. If your program is not interactive, 
292          *  it‘s usually nice to disable the mouse pointer when in fullscreen mode. It‘s up to you though.
293          */
294         dwExStyle = WS_EX_APPWINDOW;                      // Window extended style
295         dwStyle = WS_POPUP;                               // Window style
296         ShowCursor(FALSE);                                // Hide mosue pointer 
297     }
298     else {
299 
300         /*
301          *  If we‘re using a window instead of fullscreen mode, 
302          *  we‘ll add WS_EX_WINDOWEDGE to the extended style. This gives the window a more 3D look. 
303          *  For style we‘ll use WS_OVERLAPPEDWINDOW instead of WS_POPUP. 
304          *  WS_OVERLAPPEDWINDOW creates a window with a title bar, sizing border, 
305          *  window menu, and minimize / maximize buttons.
306          */
307         dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;   // Window extended style
308         dwStyle = WS_OVERLAPPEDWINDOW;                    // Window style
309     }
310 
311     /*
312      *  By using the AdjustWindowRectEx command none of our OpenGL scene will be covered up by the borders, 
313      *  instead, the window will be made larger to account for the pixels needed to draw the window border. 
314      *  In fullscreen mode, this command has no effect.
315      */
316     AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);  // Adjust window to true resqusted
317     
318     /*
319      *  WS_CLIPSIBLINGS and WS_CLIPCHILDREN are both REQUIRED for OpenGL to work properly. 
320      *  These styles prevent other windows from drawing over or into our OpenGL Window.
321      */
322     if (!(hWnd = CreateWindowEx(dwExStyle,                // Extended style for the window
323         "OpenGL",                                         // Class name
324         title,                                            // Window title
325         WS_CLIPSIBLINGS |                                 // Requried window style
326         WS_CLIPCHILDREN |                                 // Requried window style
327         dwStyle,                                          // Select window style
328         0, 0,                                             // Window position
329         WindowRect.right - WindowRect.left,               // Calculate adjusted window width
330         WindowRect.bottom - WindowRect.top,               // Calculate adjusted window height
331         NULL,                                             // No parent window
332         NULL,                                             // No menu
333         hInstance,                                        // Instance
334         NULL)))                                           // Don‘t pass anything to WM_CREATE
335     {
336         KillGLWindow();                                   //Reset the display
337         MessageBox(NULL, "Window creation error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
338         return FALSE;                                     // Retrurn FALSE;
339     }
340 
341     /*
342      *  aside from the stencil buffer and the (slow) accumulation buffer
343      */
344     static PIXELFORMATDESCRIPTOR pfd =                    // pfd tells windows how we want things to be 
345     {
346         sizeof(PIXELFORMATDESCRIPTOR),                    // Size of this pixel format descriptor
347         1,                                                // Version number
348         PFD_DRAW_TO_WINDOW |                              // Format must support window
349         PFD_SUPPORT_OPENGL |                              // Format must support OpenGL
350         PFD_DOUBLEBUFFER,                                 // Must support double buffer
351         PFD_TYPE_RGBA,                                    // Request an RGBA format
352         bits,                                             // Select our color depth
353         0, 0, 0, 0, 0, 0,                                 // Color bits ignored
354         0,                                                // No alpha buffer
355         0,                                                // shift bit ignored
356         0,                                                // No accumulation buffer
357         0, 0, 0, 0,                                       // Accumulation bits ignored
358         16,                                               // 16Bits Z_Buffer (depth buffer)
359         0,                                                // No stencil buffer
360         0,                                                // No auxiliary buffer
361         PFD_MAIN_PLANE,                                   // Main drawing layer
362         0,                                                // Reserved
363         0, 0, 0                                           // Layer makes ignored
364     };
365 
366     if (!(hDC = GetDC(hWnd))) {                           // Did we get a device context
367         KillGLWindow();                                   // Reset the display
368         MessageBox(NULL, "Can‘t create a GL device context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
369         return FALSE;                                     // Return FALSE
370     }
371 
372     if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) {  // Did window find a matching pixel format
373         KillGLWindow();                                   // Reset the display
374         MessageBox(NULL, "Can‘t find a suitable pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
375         return FALSE;                                     // Return FALSE;
376     }
377 
378     if (!SetPixelFormat(hDC, PixelFormat, &pfd)) {        // Are we able to set the pixel format
379         KillGLWindow();                                   // Reset the display
380         MessageBox(NULL, "Can‘t set the pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
381         return FALSE;                                     // Return FALSE;
382     }
383 
384     if (!(hRC = wglCreateContext(hDC))) {                 // Are we able to rendering context
385         KillGLWindow();                                   // Reset the display
386         MessageBox(NULL, "Can‘t create a GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
387         return FALSE;                                     // Return FASLE;
388     }
389 
390     if (!wglMakeCurrent(hDC, hRC)) {                      // Try to activate the rendering context
391         KillGLWindow();                                   // Reset the display
392         MessageBox(NULL, "Can‘t activate the GL rendering context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
393         return FALSE;                                     // Return FALSE    
394     }
395 
396     /*
397      *  ReSizeGLScene passing the screen width and height to set up our perspective OpenGL screen.
398      */
399     ShowWindow(hWnd, SW_SHOW);                            // Show the window
400     SetForegroundWindow(hWnd);                            // slightly higher priority
401     SetFocus(hWnd);                                       // Sets keyboard focus to the window
402     ReSizeGLScene(width, height);                         // Set up our perspective GL screen
403 
404     /*
405      *  we can set up lighting, textures, and anything else that needs to be setup in InitGL().
406      */
407     if (!InitGL()) {   

以上是关于2.First Polygon的主要内容,如果未能解决你的问题,请参考以下文章

Polygon zkEVM节点代码解析

Polygon zkEVM zkROM代码解析

Polygon zkEVM zkROM代码解析

Polygon zkEVM zkROM代码解析

使用 GL_POLYGON 绘制圆,半径超出比例

Cesium 添加 Polygon与multiPolygon