Merge pull request #8942 from zwsu:master
[platform/upstream/opencv.git] / samples / gpu / opengl.cpp
1 #include <iostream>
2
3 #ifdef WIN32
4     #define WIN32_LEAN_AND_MEAN 1
5     #define NOMINMAX 1
6     #include <windows.h>
7 #endif
8 #if defined(_WIN64)
9     #include <windows.h>
10 #endif
11
12 #if defined(__APPLE__)
13     #include <OpenGL/gl.h>
14     #include <OpenGL/glu.h>
15 #else
16     #include <GL/gl.h>
17     #include <GL/glu.h>
18 #endif
19
20 #include "opencv2/core.hpp"
21 #include "opencv2/core/opengl.hpp"
22 #include "opencv2/core/cuda.hpp"
23 #include "opencv2/highgui.hpp"
24
25 using namespace std;
26 using namespace cv;
27 using namespace cv::cuda;
28
29 const int win_width = 800;
30 const int win_height = 640;
31
32 struct DrawData
33 {
34     ogl::Arrays arr;
35     ogl::Texture2D tex;
36     ogl::Buffer indices;
37 };
38
39 void draw(void* userdata);
40
41 void draw(void* userdata)
42 {
43     DrawData* data = static_cast<DrawData*>(userdata);
44
45     glRotated(0.6, 0, 1, 0);
46
47     ogl::render(data->arr, data->indices, ogl::TRIANGLES);
48 }
49
50 int main(int argc, char* argv[])
51 {
52     string filename;
53     if (argc < 2)
54     {
55         cout << "Usage: " << argv[0] << " image" << endl;
56         filename = "../data/lena.jpg";
57     }
58     else
59         filename = argv[1];
60
61     Mat img = imread(filename);
62     if (img.empty())
63     {
64         cerr << "Can't open image " << filename << endl;
65         return -1;
66     }
67
68     namedWindow("OpenGL", WINDOW_OPENGL);
69     resizeWindow("OpenGL", win_width, win_height);
70
71     Mat_<Vec2f> vertex(1, 4);
72     vertex << Vec2f(-1, 1), Vec2f(-1, -1), Vec2f(1, -1), Vec2f(1, 1);
73
74     Mat_<Vec2f> texCoords(1, 4);
75     texCoords << Vec2f(0, 0), Vec2f(0, 1), Vec2f(1, 1), Vec2f(1, 0);
76
77     Mat_<int> indices(1, 6);
78     indices << 0, 1, 2, 2, 3, 0;
79
80     DrawData data;
81
82     data.arr.setVertexArray(vertex);
83     data.arr.setTexCoordArray(texCoords);
84     data.indices.copyFrom(indices);
85     data.tex.copyFrom(img);
86
87     glMatrixMode(GL_PROJECTION);
88     glLoadIdentity();
89     gluPerspective(45.0, (double)win_width / win_height, 0.1, 100.0);
90
91     glMatrixMode(GL_MODELVIEW);
92     glLoadIdentity();
93     gluLookAt(0, 0, 3, 0, 0, 0, 0, 1, 0);
94
95     glEnable(GL_TEXTURE_2D);
96     data.tex.bind();
97
98     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
99     glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
100
101     glDisable(GL_CULL_FACE);
102
103     setOpenGlDrawCallback("OpenGL", draw, &data);
104
105     for (;;)
106     {
107         updateWindow("OpenGL");
108         char key = (char)waitKey(40);
109         if (key == 27)
110             break;
111     }
112
113     setOpenGlDrawCallback("OpenGL", 0, 0);
114     destroyAllWindows();
115
116     return 0;
117 }