-
Notifications
You must be signed in to change notification settings - Fork 1
/
05_shader.py
109 lines (82 loc) · 2.68 KB
/
05_shader.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import glfw
import numpy as np
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
def window_resize(window, width, height):
glViewport(0, 0, width, height)
# ==========================================
# Vertex and fragment shader
# ==========================================
vertex_src = """
# version 330
in vec3 position_in;
in vec3 color_in;
out vec3 color_out;
void main()
{
gl_Position = vec4(position_in, 1.0);
color_out = color_in;
}
"""
fragment_src = """
# version 330
in vec3 color_out;
out vec4 color;
void main()
{
color = vec4(color_out, 1.0);
}
"""
# ==========================================
# Initialize window & context
# ==========================================
if not glfw.init():
raise Exception('glfw can\'t be initialized')
# creating the window
window = glfw.create_window(640, 480, "Kelompok 5 - Sushi", None, None)
# check if window was created
if not window:
glfw.terminate()
raise Exception('glfw window can\'t be created')
# set window's position
glfw.set_window_pos(window, 100, 100)
# Get callback and windows resize
glfw.set_window_size_callback(window, window_resize)
# make the context current
glfw.make_context_current(window)
# ==========================================
# Define vertices and color
# ==========================================
vertices = [0, 0.5, 0, 1, 0, 0,
- 0.5, -0.5, 0, 0, 1, 0,
0.5, -0.5, 0, 0, 0, 1]
vertices = np.array(vertices, dtype=np.float32)
# Make Shader Program
shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
compileShader(fragment_src, GL_FRAGMENT_SHADER))
# Make Vertex Buffer Object
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
# Define Vertex location
position = glGetAttribLocation(shader, "position_in")
glEnableVertexAttribArray(position)
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))
# Define color
color = glGetAttribLocation(shader, "color_in")
glEnableVertexAttribArray(color)
glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))
# Using program shader
glUseProgram(shader)
glClearColor(0, 0, 0.1, 0)
# ==========================================
# Loop until the user closes the window
# ==========================================
while not glfw.window_should_close(window):
# Clear buffer and Poll process events
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)
# Draw the object
glDrawArrays(GL_TRIANGLES, 0, 3)
glfw.swap_buffers(window)
glfw.terminate()