def test_create_perspective_projection_matrix_dtype(self): m1 = matrix44.create_perspective_projection_matrix(90, 1024. / 768., 1., 10., dtype='float32') m2 = matrix44.create_perspective_projection_matrix(90, 1024. / 768., 1., 10., dtype='float64') self.assertEqual(m1.dtype, np.float32) self.assertEqual(m2.dtype, np.float64)
def InitGL(self): # triangle = np.array([-0.5, -0.5, 0.0, 1.0, 0.0, 0.0, # 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, # 0.0, 0.5, 0.0, 0.0, 0.0, 1.0], dtype=np.float32) self.mesh = Cube() shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(self.vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(self.fragment_shader, GL_FRAGMENT_SHADER)) glClearColor(0.0, 0.0, 0.0, 0.0) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0])) projection = matrix44.create_perspective_projection_matrix(45.0, self.aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) glUseProgram(shader) glEnable(GL_DEPTH_TEST) vp_loc = glGetUniformLocation(shader, "vp") glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) self.model_location = glGetUniformLocation(shader, "model") self.Refresh()
def create_perspective_projection(): view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0])) projection = matrix44.create_perspective_projection_matrix(45.0, 1280.0 / 720.0, 0.1, 100.0) vp = matrix44.multiply(view, projection).flatten().astype("float32") c_vp = numpy.ctypeslib.as_ctypes(vp) vp_loc = glGetUniformLocation(InitShader.shader, b"vp") glUniformMatrix4fv(vp_loc, 1, GL_FALSE, c_vp)
def change_projection_matrix(self, fov, aspect_ratio, near, far): """Changes mesh projection matrix.""" self.projection_matrix = matrix44.create_perspective_projection_matrix(fov,aspect_ratio,near,far) glUseProgram(self.shader) glUniformMatrix4fv(self.proj_loc,1,GL_FALSE,self.projection_matrix) glUseProgram(0)
def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None): """ Create a projection matrix with the following parameters. When ``aspect_ratio`` is not provided the configured aspect ratio for the window will be used. Args: fov (float): Field of view (float) near (float): Camera near value far (float): Camrea far value Keyword Args: aspect_ratio (float): Aspect ratio of the viewport Returns: The projection matrix as a float32 :py:class:`numpy.array` """ return matrix44.create_perspective_projection_matrix( fov, aspect_ratio or self.window.aspect_ratio, near, far, dtype='f4', )
def __init__(self): mesh = ObjLoader() mesh.load_model("../models/monkey.obj") num_verts = len(mesh.model_vertices) // 3 self.batch = pyglet.graphics.Batch() self.verts = self.batch.add(num_verts, GL_TRIANGLES, None, ('v3f', mesh.model_vertices), ('t2f', mesh.model_textures)) shader = ShaderLoader.compile_shader("shaders/video_13_vert.glsl", "shaders/video_13_frag.glsl") glUseProgram(shader) # vertices glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, self.verts.vertices) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, self.verts.tex_coords) glEnableVertexAttribArray(1) projection = matrix44.create_perspective_projection_matrix( 45.0, 1280 / 720, 0.1, 100.0).flatten().astype("float32") view = matrix44.create_from_translation(Vector3( [0.0, 0.0, -2.0])).flatten().astype("float32") self.translation = matrix44.create_from_translation( Vector3([0.0, 0.0, -2.0])) c_projection = numpy.ctypeslib.as_ctypes(projection) c_view = numpy.ctypeslib.as_ctypes(view) view_loc = glGetUniformLocation(shader, b"view") proj_loc = glGetUniformLocation(shader, b"projection") self.model_loc = glGetUniformLocation(shader, b"model") glUniformMatrix4fv(view_loc, 1, GL_FALSE, c_view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, c_projection) # region texture settings and loading texture = GLuint(0) glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) # set the texture wrapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # set the texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # endregion image = pyglet.image.load('../models/monkey.jpg') image_data = image.get_data('RGB', image.pitch) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
def update_projection_matrix(self, aspect_ratio): if self._aspect_ratio == aspect_ratio: return self._aspect_ratio = aspect_ratio # TODO pmat = create_perspective_projection_matrix(self._field_of_view_y, aspect_ratio, self._near, self._far) self._projection_matrix = numpy.array(pmat).reshape((4, 4))
def projection_matrix(self, ptype=ProjectionType.perspective): if (ptype == ProjectionType.perspective): # Return the current perspective projection Matrix return matrix44.create_perspective_projection_matrix( self._fov, self._aspect, self._zNear, self._zFar) else: # Return the current orthogonal projection Matrix return matrix44.create_orthogonal_projection_matrix( self._rect[0], self._rect[1], self._rect[2], self._rect[3], self._zNear, self._zFar)
def __init__(self): self.camera_pos = Vector3([0.0, 4.0, 3.0]) self.camera_front = Vector3([0.0, 0.0, -1.0]) self.camera_up = Vector3([0.0, 1.0, 0.0]) self.camera_right = Vector3([1.0, 0.0, 0.0]) self.mouse_sensitivity = 0.25 self.jaw = -90 self.pitch = 0 self.projectionMatrix = matrix44.create_perspective_projection_matrix(65, Config.WINDOW_WIDTH / Config.WINDOW_HEIGHT, 0.1, 100.0)
def update_projection_matrix(self, aspect_ratio): if self._aspect_ratio == aspect_ratio: return self._aspect_ratio = aspect_ratio # TODO pmat = create_perspective_projection_matrix( self._field_of_view_y, aspect_ratio, self._near, self._far) self._projection_matrix = numpy.array(pmat).reshape((4, 4))
def calc_projection(self): self.ortho = matrix44.create_orthogonal_projection( -self.hw / self._zoom, self.hw / self._zoom, -self.hh / self._zoom, self.hh / self._zoom, -100.0, 100.0) self.persp = matrix44.create_perspective_projection_matrix( 50.0, self.width / self.height, 0.1, 200.0) if self.is_ortho: self.projection = self.ortho else: self.projection = self.persp self.default_proj = matrix44.create_orthogonal_projection( 0, self.width, 0, self.height, -1, 1) self.view = matrix44.create_look_at((self.x, self.y, 10.0), (self.x, self.y, 0.0), (self.up_x, self.up_y, 0.0))
def test_perspective_projection_works_fine( self ): p = matrix44.create_perspective_projection_matrix( 90, 4.0/3, 0.01, 1000 ) for point, is_inside in ( ( (0, 0, 1), False ), ( (0, 0, 0), False ), ( (0, 0, -0.02), True ), ( (0, 0, -1000), True ), ( (0, 1.50, -1), False ), ( (0, 0, -1001), False ), ( (50, 0, -0.02), False ), ( (0, 50, -0.02), False ), ): self.check_projection_classifies_point_correctly( p, numpy.array( point + ( 1, ) ), is_inside)
def create_projection(self, fov=75.0, near=1.0, far=100.0, ratio=None): """ Create a projection matrix with the following parameters. :param fov: Field of view (float) :param near: Camera near value :param far: Camrea far value :param ratio: Aspect ratio of the window :return: The projection matrix """ return matrix44.create_perspective_projection_matrix( fov, ratio or self.window_aspect, near, far, )
def test_create_perspective_projection_matrix_vector3(self): def apply_test(m, point, inside): p = matrix44.apply_to_vector(m, point) # the values are now in clip space from (-1.,-1.,-1.) -> (1.,1.,1.) # to be inside = all(-1. < value < 1.) self.assertTrue(inside == (np.amax(np.absolute(p)) <= 1.), (inside, point, p)) m = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10.) apply_test(m, np.array((0.,0.,0.)), False) apply_test(m, np.array((0.,0.,-.5)), False) apply_test(m, np.array((0.,0.,-1.)), True) apply_test(m, np.array((0.,0.,-2.)), True) apply_test(m, np.array((0.,0.,-9.)), True) apply_test(m, np.array((0.,0.,-11.)), False) apply_test(m, np.array((1.,1.,-5.)), True)
def test_create_perspective_projection_matrix_vector3(self): def apply_test(m, point, inside): p = matrix44.apply_to_vector(m, point) # the values are now in clip space from (-1.,-1.,-1.) -> (1.,1.,1.) # to be inside = all(-1. < value < 1.) self.assertTrue(inside == (np.amax(np.absolute(p)) <= 1.), (inside, point, p)) m = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10.) apply_test(m, np.array((0.,0.,0.)), False) apply_test(m, np.array((0.,0.,-.5)), False) apply_test(m, np.array((0.,0.,-1.)), True) apply_test(m, np.array((0.,0.,-2.)), True) apply_test(m, np.array((0.,0.,-9.)), True) apply_test(m, np.array((0.,0.,-11.)), False) apply_test(m, np.array((1.,1.,-5.)), True)
def update(self, aspect_ratio=None, fov=None, near=None, far=None): """ Update the internal projection matrix based on current values or values passed in if specified. :param aspect_ratio: New aspect ratio :param fov: New field of view :param near: New near value :param far: New far value """ self.aspect_ratio = aspect_ratio or self.aspect_ratio self.fov = fov or self.fov self.near = near or self.near self.far = far or self.far self.matrix = matrix44.create_perspective_projection_matrix( self.fov, self.aspect_ratio, self.near, self.far)
def set_projection(self, fov=None, aspect=None, near=None, far=None): """ Update projection parameters and return the new version :param fov: Field of view :param aspect: Aspect ratio :param near: Near plane :param far: Far plane :return: Projection matrix """ self.fov = fov or self.fov self.near = near or self.near self.far = far or self.far self.aspect = aspect or self.aspect self.projection = matrix44.create_perspective_projection_matrix( self.fov, self.aspect, self.near, self.far) return self.projection
def prep(self, shader, aspect_ratio, scale_val=None, angle=90.0): self.shader = shader self.shader.use() if scale_val: self.scale = scale_val view = matrix44.create_from_translation(Vector3(DEFAULT_VIEW)) self.shader.set_mat4('view', view) projection = matrix44.create_perspective_projection_matrix( angle, aspect_ratio, PROJECTION_NEAR, PROJECTION_FAR) self.shader.set_mat4('projection', projection) scale = matrix33.create_from_scale( Vector3([self.scale, self.scale, self.scale])) scale = matrix44.create_from_matrix33(scale) self.shader.set_mat4('scale', scale)
def init(): shader = ShaderLoader.compile_shader("shaders/video_13_vert.glsl", "shaders/video_13_frag.glsl") glUseProgram(shader) view = matrix44.create_from_translation(Vector3( [0.0, 0.0, -2.0])).flatten().astype("float32") projection = matrix44.create_perspective_projection_matrix( 45.0, 1280 / 720, 0.1, 100.0).flatten().astype("float32") c_view = numpy.ctypeslib.as_ctypes(view) c_projection = numpy.ctypeslib.as_ctypes(projection) view_loc = glGetUniformLocation(shader, b"view") proj_loc = glGetUniformLocation(shader, b"projection") Shader.model_loc = glGetUniformLocation(shader, b"model") glUniformMatrix4fv(view_loc, 1, GL_FALSE, c_view) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, c_projection)
def test_create_perspective_projection_matrix_vector4_inside(self): def apply_test(m, point, inside): p = matrix44.apply_to_vector(m, point) if np.allclose(p[3], 0.): self.assertFalse(inside) # the values are now in clip space from (-1.,-1.,-1.) -> (1.,1.,1.) # to be inside = all(-1. < value < 1.) if np.allclose(p[3],0.): p[:] = [np.inf,np.inf,np.inf,np.inf] else: p[:3] /= p[3] self.assertTrue(inside == (np.amax(np.absolute(p[:3])) <= 1.), (inside, point, p)) m = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10.) apply_test(m, np.array((0.,0.,0.,1.)), False) apply_test(m, np.array((0.,0.,-.5,1.)), False) apply_test(m, np.array((0.,0.,-1.,1.)), True) apply_test(m, np.array((0.,0.,-2.,1.)), True) apply_test(m, np.array((0.,0.,-9.,1.)), True) apply_test(m, np.array((0.,0.,-11.,1.)), False) apply_test(m, np.array((1.,1.,-5.,1.)), True)
def test_create_perspective_projection_matrix_vector4_inside(self): def apply_test(m, point, inside): p = matrix44.apply_to_vector(m, point) if np.allclose(p[3], 0.): self.assertFalse(inside) # the values are now in clip space from (-1.,-1.,-1.) -> (1.,1.,1.) # to be inside = all(-1. < value < 1.) if np.allclose(p[3],0.): p[:] = [np.inf,np.inf,np.inf,np.inf] else: p[:3] /= p[3] self.assertTrue(inside == (np.amax(np.absolute(p[:3])) <= 1.), (inside, point, p)) m = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10.) apply_test(m, np.array((0.,0.,0.,1.)), False) apply_test(m, np.array((0.,0.,-.5,1.)), False) apply_test(m, np.array((0.,0.,-1.,1.)), True) apply_test(m, np.array((0.,0.,-2.,1.)), True) apply_test(m, np.array((0.,0.,-9.,1.)), True) apply_test(m, np.array((0.,0.,-11.,1.)), False) apply_test(m, np.array((1.,1.,-5.,1.)), True)
def InitGL(self): self.mesh = Geometries() shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0])) projection = matrix44.create_perspective_projection_matrix( 45.0, self.aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) glUseProgram(shader) glEnable(GL_DEPTH_TEST) vp_loc = glGetUniformLocation(shader, "vp") glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) self.rot_loc = glGetUniformLocation(shader, "rotate") self.trans_loc = glGetUniformLocation(shader, "translate")
def render(self): t = clock() self.time_parameter.set_value(t) data = ( ((-0.5, -0.5, 0), (0.0, 0.0)), ((0.5, -0.5, 0), (1.0, 0.0)), ((0, 0.5, 0), (0.5, 1.0)), ) proj = matrix44.create_perspective_projection_matrix( 90, 4.0 / 3.0, 0.01, 100.0) mv = matrix44.multiply( matrix44.create_from_translation((sin(t * 10), 0.0, -3.0 * abs(sin(t * 30)))), matrix44.create_from_z_rotation(t * 50), ) mvp = matrix44.multiply(mv, proj) self.model_view_proj.set_value(mvp) for pass_ in self.technique.passes: pass_.begin() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glBegin(gl.GL_TRIANGLES) for position, texcoord in data: gl.glMultiTexCoord2fv(gl.GL_TEXTURE0, texcoord) gl.glVertex3fv(position) gl.glEnd() pass_.end()
def test_create_perspective_projection_matrix_dtype(self): m1 = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10., dtype='float32') m2 = matrix44.create_perspective_projection_matrix(90, 1024./768., 1., 10., dtype='float64') self.assertEqual(m1.dtype, np.float32) self.assertEqual(m2.dtype, np.float64)
def regenProjectionMatrix(self): self.projectionMatrix = array(mat4.create_perspective_projection_matrix( self.fov, self.aspect, 0.1, 1000.0 ), dtype=float32)
def main(): if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) cube = [ -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) cube_indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] cube_indices = numpy.array(cube_indices, dtype=numpy.uint32) monkey = ObjLoader() monkey.load_model("resources/monkey/monkey.obj") monkey_texture_offset = len(monkey.vertex_index) * 12 vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 textCoords; uniform mat4 vp; uniform mat4 model; out vec2 outText; void main() { gl_Position = vp * model * vec4(position, 1.0f); outText = textCoords; } """ fragment_shader = """ #version 330 in vec2 outText; out vec4 outColor; uniform sampler2D renderedTexture; void main() { outColor = texture(renderedTexture, outText); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) # cube VAO cube_vao = glGenVertexArrays(1) glBindVertexArray(cube_vao) cube_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, cube_VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) cube_EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube_EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.itemsize * len(cube_indices), cube_indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glBindVertexArray(0) # monkey VAO monkey_vao = glGenVertexArrays(1) glBindVertexArray(monkey_vao) monkey_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monkey_VBO) glBufferData(GL_ARRAY_BUFFER, monkey.model.itemsize * len(monkey.model), monkey.model, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 2, ctypes.c_void_p(monkey_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) ########################################################################################### cube_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, cube_texture) # texture wrapping params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # texture filtering params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w_width, w_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) depth_buff = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, depth_buff) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w_width, w_height) FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cube_texture, 0) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buff) glBindFramebuffer(GL_FRAMEBUFFER, 0) ########################################################################################### monkey_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, monkey_texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open("resources/monkey/monkey.jpg") flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) img_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glBindTexture(GL_TEXTURE_2D, 0) ########################################################################################### glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0])) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) cube_position = matrix44.create_from_translation(Vector3([0.0, 0.0, 0.0])) monkey_position = matrix44.create_from_translation( Vector3([0.0, 0.0, -1.0])) vp = matrix44.multiply(view, projection) glUseProgram(shader) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClearColor(0.2, 0.25, 0.27, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) cube_rot_y = pyrr.Matrix44.from_y_rotation(glfw.get_time() * 0.1) cube_rot_x = pyrr.Matrix44.from_x_rotation(glfw.get_time() * 0.1) cube_rot_all = pyrr.matrix44.multiply(cube_rot_y, cube_rot_x) monkey_rot_y = pyrr.Matrix44.from_y_rotation(glfw.get_time()) # draw to the custom frame buffer glBindFramebuffer(GL_FRAMEBUFFER, FBO) glViewport(0, 0, w_width, w_height) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glBindVertexArray(monkey_vao) glBindTexture(GL_TEXTURE_2D, monkey_texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_rot_y * monkey_position) glDrawArrays(GL_TRIANGLES, 0, len(monkey.vertex_index)) glBindVertexArray(0) glBindFramebuffer(GL_FRAMEBUFFER, 0) # draw to the default frame buffer glBindVertexArray(cube_vao) glViewport(0, 0, new_width, new_height) glBindTexture(GL_TEXTURE_2D, cube_texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, cube_rot_all * cube_position) glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) # positions texture_coords cube = [-0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0] cube = numpy.array(cube, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; uniform mat4 vp; uniform mat4 model; out vec2 textures; void main() { gl_Position = vp * model * vec4(position, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 in vec2 textures; out vec4 color; uniform sampler2D tex_sampler; void main() { color = texture(tex_sampler, textures); } """ shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) crate = TextureLoader.load_texture("resources/images/planks_brown_10_diff_1k.jpg") metal = TextureLoader.load_texture("resources/images/green_metal_rust_diff_1k.jpg") brick = TextureLoader.load_texture("resources/images/castle_brick_07_diff_1k.jpg") glUseProgram(shader) glClearColor(0.5, 0.1, 0.2, 1.0) glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0])) projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") # cube_positions = [(1.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -1.2, -2.5), (-8.8, -2.0, -12.3)] cube_positions = [(1.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -1.2, -2.5), (-8.8, -2.0, -12.3), (-2.0, 2.0, -5.5), (-4.0, 2.0, -3.0)] # cube_positions = [(-1.5, 1.0, -0.5), (0.0, 1.0, -0.5), (1.5, 1.0, -0.5), (-1.5, -1.0, -0.5), (0.0, -1.0, -0.5), (1.5, -1.0, -0.5)] glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) time = glfw.get_time() rot_x = matrix44.create_from_x_rotation(sin(time) * 2) rot_y = matrix44.create_from_y_rotation(time * 0.5) rot_z = matrix44.create_from_z_rotation(time) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) if i < 2: glBindTexture(GL_TEXTURE_2D, crate) rotX = matrix44.multiply(rot_x, model) glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotX) elif i == 2 or i == 3: glBindTexture(GL_TEXTURE_2D, metal) rotY = matrix44.multiply(rot_y, model) glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotY) else: glBindTexture(GL_TEXTURE_2D, brick) rotZ = matrix44.multiply(rot_z, model) glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotZ) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def __init__(self, x, y, width, height, position): self.plane = [ -0.5 * x, -0.5 * y, 0.0, 0.0, 0.0, 0.5 * x, -0.5 * y, 0.0, 1.0, 0.0, 0.5 * x, 0.5 * y, 0.0, 1.0, 1.0, -0.5 * x, 0.5 * y, 0.0, 0.0, 1.0 ] self.plane = np.array(self.plane, dtype=np.float32) self.plane_indices = [0, 1, 2, 2, 3, 0] self.plane_indices = np.array(self.plane_indices, dtype=np.uint32) self.external_aspect_ratio = x / y aspect_ratio = float(width / height) self.shader = compile_shader("shaders/blank.vs", "shaders/blank.fs") self.model_loc = glGetUniformLocation(self.shader, "model") self.proj_loc = glGetUniformLocation(self.shader, "proj") self.projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) # plane VAO self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) self.VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.VBO) glBufferData(GL_ARRAY_BUFFER, self.plane.itemsize * len(self.plane), self.plane, GL_STATIC_DRAW) self.EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.plane_indices.itemsize * len(self.plane_indices), self.plane_indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, self.plane.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, self.plane.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glBindVertexArray(0) self.texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.texture) # texture wrapping params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # texture filtering params glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) self.depth_buff = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, self.depth_buff) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height) self.FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, self.FBO) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.texture, 0) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, self.depth_buff) glBindFramebuffer(GL_FRAMEBUFFER, 0) position_matrix = create_from_translation(position) glUseProgram(self.shader) glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, position_matrix) glUniformMatrix4fv(self.proj_loc, 1, GL_FALSE, self.projection) glUseProgram(0)
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1920, 1080 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) cube = ObjLoader() cube.load_model("res/cube/cube.obj") cube_shader = ShaderLoader.compile_shader("shaders/video_09_cube.vs", "shaders/video_09_cube.fs") cube_tex = TextureLoader.load_texture("res/cube/cube_texture.jpg") cube_texture_offset = len(cube.vertex_index) * 12 monkey = ObjLoader() monkey.load_model("res/monkey/monkey.obj") monkey_shader = ShaderLoader.compile_shader("shaders/video_09_monkey.vs", "shaders/video_09_monkey.fs") monkey_tex = TextureLoader.load_texture("res/monkey/monkey.jpg") monkey_texture_offset = len(monkey.vertex_index) * 12 monster = ObjLoader() monster.load_model("res/monster/monster.obj") monster_shader = ShaderLoader.compile_shader( "shaders/video_09_monster.vs", "shaders/video_09_monster.fs") monster_tex = TextureLoader.load_texture("res/monster/monster.jpg") monster_texture_offset = len(monster.vertex_index) * 12 cube_vao = glGenVertexArrays(1) glBindVertexArray(cube_vao) cube_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, cube_vbo) glBufferData(GL_ARRAY_BUFFER, cube.model.itemsize * len(cube.model), cube.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.model.itemsize * 2, ctypes.c_void_p(cube_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) monkey_vao = glGenVertexArrays(1) glBindVertexArray(monkey_vao) monkey_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monkey_vbo) glBufferData(GL_ARRAY_BUFFER, monkey.model.itemsize * len(monkey.model), monkey.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey.model.itemsize * 2, ctypes.c_void_p(monkey_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) monster_vao = glGenVertexArrays(1) glBindVertexArray(monster_vao) monster_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monster_vbo) glBufferData(GL_ARRAY_BUFFER, monster.model.itemsize * len(monster.model), monster.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monster.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monster.model.itemsize * 2, ctypes.c_void_p(monster_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) glClearColor(0.13, 0.2, 0.15, 1.0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) cube_model = matrix44.create_from_translation(Vector3([-4.0, 0.0, -3.0])) monkey_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -3.0])) monster_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -10.0])) glUseProgram(cube_shader) cube_model_loc = glGetUniformLocation(cube_shader, "model") cube_view_loc = glGetUniformLocation(cube_shader, "view") cube_proj_loc = glGetUniformLocation(cube_shader, "proj") glUniformMatrix4fv(cube_model_loc, 1, GL_FALSE, cube_model) glUniformMatrix4fv(cube_proj_loc, 1, GL_FALSE, projection) glUseProgram(0) glUseProgram(monkey_shader) monkey_model_loc = glGetUniformLocation(monkey_shader, "model") monkey_view_loc = glGetUniformLocation(monkey_shader, "view") monkey_proj_loc = glGetUniformLocation(monkey_shader, "proj") glUniformMatrix4fv(monkey_model_loc, 1, GL_FALSE, monkey_model) glUniformMatrix4fv(monkey_proj_loc, 1, GL_FALSE, projection) glUseProgram(0) glUseProgram(monster_shader) monster_model_loc = glGetUniformLocation(monster_shader, "model") monster_view_loc = glGetUniformLocation(monster_shader, "view") monster_proj_loc = glGetUniformLocation(monster_shader, "proj") glUniformMatrix4fv(monster_model_loc, 1, GL_FALSE, monster_model) glUniformMatrix4fv(monster_proj_loc, 1, GL_FALSE, projection) glUseProgram(0) while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glBindVertexArray(cube_vao) glUseProgram(cube_shader) glBindTexture(GL_TEXTURE_2D, cube_tex) glUniformMatrix4fv(cube_view_loc, 1, GL_FALSE, view) glDrawArrays(GL_TRIANGLES, 0, len(cube.vertex_index)) glUseProgram(0) glBindVertexArray(0) glBindVertexArray(monkey_vao) glBindTexture(GL_TEXTURE_2D, monkey_tex) glUseProgram(monkey_shader) glUniformMatrix4fv(monkey_view_loc, 1, GL_FALSE, view) glDrawArrays(GL_TRIANGLES, 0, len(monkey.vertex_index)) glUseProgram(0) glBindVertexArray(0) glBindVertexArray(monster_vao) glBindTexture(GL_TEXTURE_2D, monster_tex) glUseProgram(monster_shader) glUniformMatrix4fv(monster_view_loc, 1, GL_FALSE, view) glDrawArrays(GL_TRIANGLES, 0, len(monster.vertex_index)) glUseProgram(0) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def view_gltf(gltf, uri_path, scene_name=None, openvr=False, window_size=None): if scene_name is None: scene_name = gltf['scene'] if window_size is None: window_size = [800, 600] window = setup_glfw(width=window_size[0], height=window_size[1], double_buffered=not openvr) def on_resize(window, width, height): window_size[0], window_size[1] = width, height glfw.SetWindowSizeCallback(window, on_resize) if openvr and OpenVRRenderer is not None: vr_renderer = OpenVRRenderer() # text_drawer = TextDrawer() gl.glClearColor(0.01, 0.01, 0.17, 1.0); shader_ids = gltfu.setup_shaders(gltf, uri_path) gltfu.setup_programs(gltf, shader_ids) gltfu.setup_textures(gltf, uri_path) gltfu.setup_buffers(gltf, uri_path) scene = gltf.scenes[scene_name] nodes = [gltf.nodes[n] for n in scene.nodes] for node in nodes: gltfu.update_world_matrices(node, gltf) camera_world_matrix = np.eye(4, dtype=np.float32) projection_matrix = np.array(matrix44.create_perspective_projection_matrix(np.rad2deg(55), window_size[0]/window_size[1], 0.1, 1000), dtype=np.float32) for node in nodes: if 'camera' in node: camera = gltf['cameras'][node['camera']] if 'perspective' in camera: perspective = camera['perspective'] projection_matrix = np.array(matrix44.create_perspective_projection_matrix(np.rad2deg(perspective['yfov']), perspective['aspectRatio'], perspective['znear'], perspective['zfar']), dtype=np.float32) elif 'orthographic' in camera: raise Exception('TODO') camera_world_matrix = node['world_matrix'] break camera_position = camera_world_matrix[3, :3] camera_rotation = camera_world_matrix[:3, :3] dposition = np.zeros(3, dtype=np.float32) rotation = np.eye(3, dtype=np.float32) key_state = defaultdict(bool) def on_keydown(window, key, scancode, action, mods): if key == glfw.KEY_ESCAPE and action == glfw.PRESS: glfw.SetWindowShouldClose(window, gl.GL_TRUE) elif action == glfw.PRESS: key_state[key] = True elif action == glfw.RELEASE: key_state[key] = False glfw.SetKeyCallback(window, on_keydown) def on_mousedown(window, button, action, mods): pass glfw.SetMouseButtonCallback(window, on_mousedown) move_speed = 2.0 turn_speed = 0.5 def process_input(dt): glfw.PollEvents() dposition[:] = 0.0 if key_state[glfw.KEY_W]: dposition[2] -= dt * move_speed if key_state[glfw.KEY_S]: dposition[2] += dt * move_speed if key_state[glfw.KEY_A]: dposition[0] -= dt * move_speed if key_state[glfw.KEY_D]: dposition[0] += dt * move_speed if key_state[glfw.KEY_Q]: dposition[1] += dt * move_speed if key_state[glfw.KEY_Z]: dposition[1] -= dt * move_speed theta = 0.0 if key_state[glfw.KEY_LEFT]: theta -= dt * turn_speed if key_state[glfw.KEY_RIGHT]: theta += dt * turn_speed rotation[0,0] = np.cos(theta) rotation[2,2] = rotation[0,0] rotation[0,2] = np.sin(theta) rotation[2,0] = -rotation[0,2] camera_rotation[...] = rotation.dot(camera_world_matrix[:3,:3]) camera_position[:] += camera_rotation.T.dot(dposition) # sort nodes from front to back to avoid overdraw (assuming opaque objects): nodes = sorted(nodes, key=lambda node: np.linalg.norm(camera_position - node['world_matrix'][3, :3])) _logger.info('starting render loop...') sys.stdout.flush() gltfu.num_draw_calls = 0 nframes = 0 lt = glfw.GetTime() dt_max = 0.0 while not glfw.WindowShouldClose(window): t = glfw.GetTime() dt = t - lt dt_max = max(dt, dt_max) lt = t process_input(dt) if openvr: vr_renderer.process_input() vr_renderer.render(gltf, nodes, window_size) else: gl.glViewport(0, 0, window_size[0], window_size[1]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) view_matrix = np.linalg.inv(camera_world_matrix) gltfu.set_material_state.current_material = None gltfu.set_technique_state.current_technique = None for node in nodes: gltfu.draw_node(node, gltf, projection_matrix=projection_matrix, view_matrix=view_matrix) # text_drawer.draw_text("%f" % dt, color=(1.0, 1.0, 0.0, 0.0), # view_matrix=view_matrix, # projection_matrix=projection_matrix) if nframes == 0: _logger.info("num draw calls per frame: %d", gltfu.num_draw_calls) sys.stdout.flush() gltfu.num_draw_calls = 0 st = glfw.GetTime() nframes += 1 glfw.SwapBuffers(window) _logger.info('FPS (avg): %f', ((nframes - 1) / (t - st))) _logger.info('MAX FRAME RENDER TIME: %f', dt_max) sys.stdout.flush() if openvr: vr_renderer.shutdown() glfw.DestroyWindow(window) glfw.Terminate()
def main(): # Inicializamos la libreria de glfw if not glfw.init(): return ventana = glfw.create_window(1080, 720, "Main window", None, None) # Funciones principales de glfw para en la ventana glfw.make_context_current(ventana) # Funcion para habilitar las teclas de la ventana glfw.set_key_callback(ventana, habilitacion) # Da la posicion del mouse tanto en x e y glfw.set_cursor_pos_callback(ventana, uso_mouse) glfw.set_input_mode(ventana, glfw.CURSOR, glfw.CURSOR_DISABLED) # Leemos el objeto, se utilizo como alternativa a pyassimp objeto = Obj() objeto.load("./objetos/wembley.obj") # Leemos la textura, se utilizo como alternativa objeto_texture = tex.texture("./objetos/wembley.jpg") objeto_texture_offset = len(objeto.vertexIndex) * 12 # Creamos cada uno de los shaders generic_vertex = ''' #version 440 in layout(location = 0) vec3 position; in layout(location = 1) vec2 textureCoords; uniform mat4 model; uniform mat4 view; uniform mat4 projection; uniform vec4 color; uniform vec4 light; out vec4 vertexColor; out vec2 nTexture; void main() { gl_Position = projection * view * model * vec4(position, 1.0f); nTexture = vec2(textureCoords.x, 1 - textureCoords.y); } ''' generic_fragment = ''' #version 440 in vec2 nTexture; out vec4 outColor; uniform sampler2D samplerTexture; void main() { outColor = texture(samplerTexture, nTexture); } ''' shader = shaders.compileProgram( shaders.compileShader(generic_vertex, GL_VERTEX_SHADER), shaders.compileShader(generic_fragment, GL_FRAGMENT_SHADER), ) # Lectura de Textura objetoVertex = glGenVertexArrays(1) glBindVertexArray(objetoVertex) objetoBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, objetoBuffer) glBufferData(GL_ARRAY_BUFFER, objeto.model.itemsize * len(objeto.model), objeto.model, GL_STATIC_DRAW) # Posicion del objeto glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, objeto.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # Textura del objeto glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, objeto.model.itemsize * 2, ctypes.c_void_p(objeto_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) glClearColor(0.18, 0.18, 0.18, 1.0) glEnable(GL_DEPTH_TEST) # Utilizamos la libreria de pyrr para la creacion de la matrix projectionMatrix = matrix44.create_perspective_projection_matrix( 45.0, (1080 / 720), 0.1, 100.0) # Model matrix MM = Vector3([0.0, 0.0, -10.0]) modelMatrix = matrix44.create_from_translation(MM) # Utilizamos shader para la compilacion glUseProgram(shader) # Matrix de projection glUniformMatrix4fv(glGetUniformLocation(shader, "projection"), 1, GL_FALSE, projectionMatrix) # Ciclo para evitar que se trabe la libreria glfw while not glfw.window_should_close(ventana): # Obtenemos cada uno de los eventos glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = camara.viewMatriz() # Matrix de view glUniformMatrix4fv(glGetUniformLocation(shader, "view"), 1, GL_FALSE, view) if rotation == False: do_movement() rotationY = Matrix44.from_y_rotation(glfw.get_time() * 0.5) glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, rotation * modelMatrix) # Utilizamos las libreris de OpenGL para obtener las texturas glBindVertexArray(objetoVertex) glBindTexture(GL_TEXTURE_2D, objeto_texture) # Creamos la matrix del modelo glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, modelMatrix) # Dibujamos cada uno de los triangulos glDrawArrays(GL_TRIANGLES, 0, len(objeto.vertexIndex)) glBindVertexArray(0) # Mandamos cada uno de los buffers glfw.swap_buffers(ventana) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1920, 1080 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "3D HOUSE", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) obj = ObjLoader() obj.load_model("resources/houseobj.obj") obj_shader = ShaderLoader.compile_shader("shaders/video_09_vert.vs", "shaders/video_09_monster.fs") obj_tex = textureloader.load_texture("resources/Lightmap.jpg") obj_texture_offset = len(obj.vertex_index) * 12 obj_vao = glGenVertexArrays(1) glBindVertexArray(obj_vao) obj_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, obj_vbo) glBufferData(GL_ARRAY_BUFFER, obj.model.itemsize * len(obj.model), obj.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, obj.model.itemsize * 2, ctypes.c_void_p(obj_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix( 90.0, aspect_ratio, 1.0, 100.0) obj_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -5.0])) glUseProgram(obj_shader) obj_model_loc = glGetUniformLocation(obj_shader, "model") obj_view_loc = glGetUniformLocation(obj_shader, "view") obj_proj_loc = glGetUniformLocation(obj_shader, "proj") glUniformMatrix4fv(obj_model_loc, 1, GL_FALSE, obj_model) glUniformMatrix4fv(obj_proj_loc, 1, GL_FALSE, projection) glUseProgram(0) while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glBindVertexArray(obj_vao) glBindTexture(GL_TEXTURE_2D, obj_tex) glUseProgram(obj_shader) glUniformMatrix4fv(obj_view_loc, 1, GL_FALSE, view) glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index)) glUseProgram(0) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1920, 1080 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) #window = glfw.create_window(w_width, w_height, "My OpenGL window", glfw.get_primary_monitor(), None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # positions texture_coords cube = [ -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; in layout(location = 2) vec3 offset; uniform mat4 model; uniform mat4 view; uniform mat4 proj; out vec2 textures; void main() { vec3 final_pos = vec3(position.x + offset.x, position.y + offset.y, position.z + offset.z); gl_Position = proj * view * model * vec4(final_pos, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 in vec2 textures; out vec4 color; uniform sampler2D tex_sampler; void main() { color = texture(tex_sampler, textures); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) # instances instance_array = [] offset = 1 for z in range(0, 100, 2): for y in range(0, 100, 2): for x in range(0, 100, 2): translation = Vector3([0.0, 0.0, 0.0]) translation.x = x + offset translation.y = y + offset translation.z = z + offset instance_array.append(translation) instance_array = numpy.array(instance_array, numpy.float32).flatten() instanceVBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, instanceVBO) glBufferData(GL_ARRAY_BUFFER, instance_array.itemsize * len(instance_array), instance_array, GL_STATIC_DRAW) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(2) glVertexAttribDivisor(2, 1) crate = TextureLoader.load_texture( "resources/images/planks_brown_10_diff_1k.jpg") glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) model = matrix44.create_from_translation(Vector3([-14.0, -8.0, 0.0])) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) model_loc = glGetUniformLocation(shader, "model") view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "proj") glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) glDrawElementsInstanced(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None, 125000) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_pos_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) # positions cube = [ -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; uniform mat4 vp; uniform mat4 model; void main() { gl_Position = vp * model * vec4(position, 1.0f); } """ fragment_shader = """ #version 330 out vec4 outColor; uniform vec3 color; void main() { outColor = vec4(color, 1.0); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0])) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") color_loc = glGetUniformLocation(shader, "color") cube_positions = [(-2.0, 0.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)] cube_colors = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 2) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) glUniform3fv(color_loc, 1, cube_colors[i]) if i == 0: if red_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) elif i == 1: if green_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) else: if blue_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) # positions texture_coords cube = [-0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0] cube = numpy.array(cube, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; uniform mat4 model; uniform mat4 view; uniform mat4 proj; out vec2 textures; void main() { gl_Position = proj * view * model * vec4(position, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 in vec2 textures; out vec4 color; uniform sampler2D tex_sampler; void main() { color = texture(tex_sampler, textures); } """ shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) crate = TextureLoader.load_texture("res/crate.jpg") metal = TextureLoader.load_texture("res/metal.jpg") brick = TextureLoader.load_texture("res/brick.jpg") glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0) model_loc = glGetUniformLocation(shader, "model") view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "proj") cube_positions = [(0.0, 0.0, 0.0), (2.0, 2.0, -5.0), (1.5, -1.2, -2.5), (8.8, -2.0, -12.3), (-2.0, 2.0, -5.5), (-4.0, 2.0, -3.0)] glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) if i < 2: glBindTexture(GL_TEXTURE_2D, crate) elif i == 2 or i == 3: glBindTexture(GL_TEXTURE_2D, metal) else: glBindTexture(GL_TEXTURE_2D, brick) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def __init__(self, filename, vertexshadername, fragmentshadername, texturename, width, height): self.vert_coords = [] self.text_coords = [] self.norm_coords = [] self.vert_index = [] self.text_index = [] self.norm_index = [] self.model = [] self.projection_matrix = matrix44.create_perspective_projection_matrix( 60.0, width / height, 0.1, 10000) self.position = [0., 0., 0.] self.orientation = [0., 0., 0., 1.] for line in open(filename, 'r'): if line.startswith('#'): continue values = line.split() if not values: continue if values[0] == 'v': self.vert_coords.append(values[1:4]) if values[0] == 'vt': self.text_coords.append(values[1:3]) if values[0] == 'vn': self.norm_coords.append(values[1:4]) if values[0] == 'f': vi = [] ti = [] ni = [] for v in values[1:4]: w = v.split('/') vi.append(int(w[0]) - 1) ti.append(int(w[1]) - 1) ni.append(int(w[2]) - 1) self.vert_index.append(vi) self.text_index.append(ti) self.norm_index.append(ni) self.vert_index = [y for x in self.vert_index for y in x] self.text_index = [y for x in self.text_index for y in x] self.norm_index = [y for x in self.norm_index for y in x] for i in self.vert_index: self.model.extend(self.vert_coords[i]) for i in self.text_index: self.model.extend(self.text_coords[i]) for i in self.norm_index: self.model.extend(self.norm_coords[i]) self.model = np.array(self.model, dtype='float32') self.texture_offset = len(self.vert_index) * 12 self.normal_offset = (self.texture_offset + len(self.text_index) * 8) self.shader = compile_shader(vertexshadername, fragmentshadername) self.model_loc = glGetUniformLocation(self.shader, "model") self.view_loc = glGetUniformLocation(self.shader, "view") self.proj_loc = glGetUniformLocation(self.shader, "proj") self.orientation_loc = glGetUniformLocation(self.shader, "orientation") glUseProgram(self.shader) glUniformMatrix4fv(self.proj_loc, 1, GL_FALSE, self.projection_matrix) glUseProgram(0) self.texture = load_texture(texturename) self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) self.vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vbo) glBufferData(GL_ARRAY_BUFFER, self.model.itemsize * len(self.model), self.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, self.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #texture glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, self.model.itemsize * 2, ctypes.c_void_p(self.texture_offset)) glEnableVertexAttribArray(1) #normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, self.model.itemsize * 3, ctypes.c_void_p(self.normal_offset)) glEnableVertexAttribArray(2) glBindVertexArray(0) self.set_position(self.position) self.set_orientation(self.orientation)
def main(): # comenzar glfw if not glfw.init(): return aspect_ratio = wwidth / wheight #creamos la ventana window = glfw.create_window(wwidth, wheight, "ProyectoGraficas", None, None) #terminar ventana if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) #carbamos el primer ObjLoader casa = ObjLoader() #buscamos el objeto en nuestras carpetas casa.load_model("obj/casa2.obj") #buscamos la textura en nuestras carpetas casa_tex = TextureLoader.load_texture("obj/pared.jpg") #calculamos casa_texture_offset = len(casa.vertex_index) * 12 #cargamos el segundo objeto monster = ObjLoader() #buscamos el obj en nuestras carpetas monster.load_model("obj/monster.obj") #buscamos la textura en nuestras carpetas monster_tex = TextureLoader.load_texture("obj/monster.jpg") #calculamos monster_texture_offset = len(monster.vertex_index) * 12 #obtenemos los shaders de nuestras carpetas. generic_shader = ShaderLoader.compile_shader( "shaders/generic_vertex_shader.vs", "shaders/generic_fragment_shader.fs") #------------------------------------casa--------------------------------------------------------------------------# #generamos nestras variaml casavao = glGenVertexArrays(1) glBindVertexArray(casavao) casavbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, casavbo) glBufferData(GL_ARRAY_BUFFER, casa.model.itemsize * len(casa.model), casa.model, GL_STATIC_DRAW) #posicion glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, casa.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #Texturas glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, casa.model.itemsize * 2, ctypes.c_void_p(casa_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) #-------------------------------------------------------------------------------------------------------------------- #-------------------------------------------------------monstruo------------------------------------------------------# monster_vao = glGenVertexArrays(1) glBindVertexArray(monster_vao) monster_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monster_vbo) glBufferData(GL_ARRAY_BUFFER, monster.model.itemsize * len(monster.model), monster.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monster.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monster.model.itemsize * 2, ctypes.c_void_p(monster_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) #-----------------------------------------------------------------------------------------------------------------------# #colocamos el color negro glClearColor(0, 0, 0, 0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) #traslacion del vector a la casa2 #colocar en el lugar casaModelo = matrix44.create_from_translation(Vector3([0.0, 0.0, -3.0])) #traslacion en el vectro3 al monstruo #colocar en el lugar monster_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -10.0])) #shaders glUseProgram(generic_shader) model_loc = glGetUniformLocation(generic_shader, "model") view_loc = glGetUniformLocation(generic_shader, "view") proj_loc = glGetUniformLocation(generic_shader, "proj") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) #mientras la ventana while not glfw.window_should_close(window): glfw.poll_events() do_movement() #colocar la ventada de un color especifico glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) #rotaciones rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5) #--------------------------------------casa--------------------------------------# glBindVertexArray(casavao) glBindTexture(GL_TEXTURE_2D, casa_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, casaModelo) glDrawArrays(GL_TRIANGLES, 0, len(casa.vertex_index)) glBindVertexArray(0) #--------------------------------------------------------------------------------# #---------------------------------------monstruo----------------------------------# glBindVertexArray(monster_vao) glBindTexture(GL_TEXTURE_2D, monster_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monster_model) glDrawArrays(GL_TRIANGLES, 0, len(monster.vertex_index)) glBindVertexArray(0) #-------------------------------------------------------------------------------------- #buffer de la ventana glfw.swap_buffers(window) #finalizamos glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_pos_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) # positions texture coordinates cube = [-0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; uniform mat4 vp; uniform mat4 model; out vec2 textures; void main() { gl_Position = vp * model * vec4(position, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 out vec4 outColor; in vec2 textures; uniform sampler2D tex_sampler; uniform ivec3 icolor; uniform int switcher; void main() { if(switcher == 0){ outColor = texture(tex_sampler, textures); }else{ outColor = vec4(icolor.r/255.0, icolor.g/255.0, icolor.b/255.0, 1.0); } } """ shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) # vertex buffer object and element buffer object VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) crate = TextureLoader.load_texture("resources/images/planks_brown_10_diff_1k.jpg") metal = TextureLoader.load_texture("resources/images/green_metal_rust_diff_1k.jpg") brick = TextureLoader.load_texture("resources/images/castle_brick_07_diff_1k.jpg") ###################################################################################### # picking texture and a frame buffer object pick_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, pick_texture) FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1280, 720, 0, GL_RGB, GL_FLOAT, None) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pick_texture, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) ###################################################################################### glUseProgram(shader) glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0])) projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") icolor_loc = glGetUniformLocation(shader, "icolor") switcher_loc = glGetUniformLocation(shader, "switcher") cube_positions = [(-2.0, 0.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)] pick_colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClearColor(0.2, 0.3, 0.2, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 2) # draw to the default frame buffer glUniform1i(switcher_loc, 0) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) if i == 0: glBindTexture(GL_TEXTURE_2D, crate) if red_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) elif i == 1: glBindTexture(GL_TEXTURE_2D, metal) if green_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) else: glBindTexture(GL_TEXTURE_2D, brick) if blue_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) # draw to the custom frame buffer object glUniform1i(switcher_loc, 1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for i in range(len(cube_positions)): pick_model = matrix44.create_from_translation(cube_positions[i]) glUniform3iv(icolor_loc, 1, pick_colors[i]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, pick_model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) if pick: picker() glBindFramebuffer(GL_FRAMEBUFFER, 0) glfw.swap_buffers(window) glfw.terminate()