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