-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cpp
94 lines (71 loc) · 2.85 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// File : main.cpp
// Compile : emcc main.cpp -std=c++11 -s WASM=1 -s USE_GLFW=3 -O3 -o index.js
#include <functional>
#include <emscripten.h>
#include <emscripten/html5.h>
#define GLFW_INCLUDE_ES2
#include <GLFW/glfw3.h>
// Shader sources
const GLchar* vertexSource =
"attribute vec3 position; \n"
"void main() \n"
"{ \n"
" gl_Position = vec4(position, 1.0); \n"
"} \n";
const GLchar* fragmentSource =
"precision mediump float;\n"
"void main() \n"
"{ \n"
" gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); \n"
"} \n";
std::function<void()> loop;
void main_loop() { loop(); }
int main()
{
int w, h;
emscripten_get_canvas_element_size("#canvas", &w, &h);
if (!glfwInit()) {
emscripten_force_exit(EXIT_FAILURE);
}
GLFWwindow *window;
window = glfwCreateWindow(w, h, "Hello, WASM World!", NULL, NULL);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
// Create a Vertex Buffer Object and copy the vertex data to it
GLuint vbo;
glGenBuffers(1, &vbo);
GLfloat vertices[] = {0.0f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f};
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Create and compile the vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, nullptr);
glCompileShader(vertexShader);
// Create and compile the fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, nullptr);
glCompileShader(fragmentShader);
// Link the vertex and fragment shader into a shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
loop = [&]
{
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
// Draw a triangle from the 3 vertices
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
};
emscripten_set_main_loop(main_loop, 0, true);
return EXIT_SUCCESS;
}