def generate_twig_from_file(self, filepath): f = open(filepath, 'r') for line in f: if line.startswith("sphere"): arr = line.split(" ") if len(arr) > 10: self.needle_num += 1 zenith_rotation_angle = degree_to_rad(float(arr[13])) azimuth_rotation_angle = degree_to_rad(float(arr[18])) translate_vector = Vector3([float(arr[20]), float(arr[21]), float(arr[22])]) matrix = Matrix44.from_y_rotation(zenith_rotation_angle) matrix = matrix * Matrix44.from_z_rotation(azimuth_rotation_angle) matrix = matrix * Matrix44.from_translation(translate_vector) # applying rotation newNeedle_vertexes = list(map(lambda x: matrix * Vector3(x), self.prim_needle.vertexes)) self.vertexes += newNeedle_vertexes f.close() # generate twig r = math.pi * self.twig_diameter / 6.0 lower_plane, upper_plane = [], [] for i in range(0, 360, 60): angle_rad = degree_to_rad(i) x = r * math.cos(angle_rad) y = r * math.sin(angle_rad) lower_plane.append([x, y, 0]) upper_plane.append([x, y, self.twig_length]) self.twig_vertexes = lower_plane + upper_plane
def rotate_relative(self, rotation): pos = self.get_position() rotate_matrix = Matrix44.from_x_rotation(rotation.x) * \ Matrix44.from_y_rotation(rotation.y) * \ Matrix44.from_z_rotation(rotation.z) self.matrix = rotate_matrix * self.matrix self.set_position(pos)
def render(self): if self.current_pointcloud < len(self.pointclouds): self.handle_mouse() self.handle_keys() self.ctx.viewport = self.wnd.viewport self.ctx.clear(0.0, 0.0, 0.0) self.ctx.enable(mgl.BLEND) vertices = np.load(file=self.pointclouds[self.current_pointcloud]) self.vbo.write(vertices.astype('f4').tobytes()) model = Matrix44.from_scale((self.zoom, self.zoom, self.zoom)) model *= Matrix44.from_x_rotation(-self.theta[1]) model *= Matrix44.from_y_rotation(-self.theta[0]) view = Matrix44.look_at((0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)) projection = Matrix44.perspective_projection( 45.0, self.wnd.ratio, 0.1, 100.0) self.mvp.write((projection * view * model).astype('f4').tobytes()) self.vao.render(mode=mgl.POINTS) self.sleep_to_target_fps(60) self.current_pointcloud += 1 else: if self.out_dir is None: self.current_pointcloud = 0 else: QtCore.QCoreApplication.instance().quit()
def get_rotation(x, y, z): logger.debug('Create rotation matrix with (x:{}, y:{}, z:{})'.format( x, y, z)) x_rotation = Matrix44.from_x_rotation(x) y_rotation = Matrix44.from_y_rotation(y) z_rotation = Matrix44.from_z_rotation(z) return z_rotation * y_rotation * x_rotation
def rotate(self): ct = time.clock() rot_y = Matrix44.from_y_rotation(ct).flatten().astype("float32") c_rotate = numpy.ctypeslib.as_ctypes(rot_y) glUniformMatrix4fv(self.rotate_loc, 1, GL_FALSE, c_rotate) glUniformMatrix4fv(self.light_loc, 1, GL_FALSE, c_rotate)
def __init__(self, target=[363], true=[504, 968], batch_size=1, **kwargs): super().__init__(**kwargs) self.target = target self.true = true self.batch_size = batch_size self.ann = InceptionV3() self.input_width, self.input_height = self.ann.get_input_shape() self.buf_shape = (batch_size, self.input_height, self.input_width) self.tf_rgb = tf.placeholder(tf.float32, [None, None, 3], name='rgbs') dnn_input = tf.expand_dims(self.tf_rgb, 0) self.t_logits, self.t_preds = self.ann.get_logits_prob(dnn_input) self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) self.ann.init_session(self.sess) self.true_label = \ [(self.ann.get_label_from_index(i)) for i in self.true] self.target_label = \ [(self.ann.get_label_from_index(i)) for i in self.target] # ModernGL Context self.ctx = moderngl.create_context(require=330) self.ctx.viewport = (0, 0, self.input_width, self.input_height) self.scene = TestMugScene3D(self.ctx) self.fbo = Fbo(self.ctx, self.ctx.viewport) self.cam_curr_position = self.scene.camera.get_view_position() self.model = Matrix44.from_y_rotation(np.pi) # CHANGE HERE!!! # Here you can define the boundaries for the digital evaluation # and step. This is not the evaluation process that was used in the # paper. Additionally, the values are just an example. self.cam_z_start_position = 10 self.cam_y_start_position = 0 self.cam_x_start_position = -4 self.cam_z_end_position = 30 self.cam_y_end_position = 5 self.cam_x_end_position = 7 self.cam_z_step_size = 1 self.cam_y_step_size = 1 self.cam_x_step_size = 1 # End self.cam_z_position = self.cam_z_start_position self.cam_y_position = self.cam_y_start_position self.cam_x_position = self.cam_x_start_position self.total_images = 0 self.classified_true = 0 self.classified_target = 0 self.classified_other = 0
def buildTransMatrix(pos=[0, 0, 0], rot=[0, 0, 0], scale=[1, 1, 1]): trans = Matrix44.from_translation(pos) rotX = Matrix44.from_x_rotation(np.radians(rot[0])) rotY = Matrix44.from_y_rotation(np.radians(rot[1])) rotZ = Matrix44.from_z_rotation(np.radians(rot[2])) scale = Matrix44.from_scale(scale) tMatrix = trans * scale * rotX * rotY * rotZ return tMatrix
def rotate(self): ct = time.clock() rot_y = Matrix44.from_y_rotation(ct) transform = matrix44.multiply( rot_y, self.translation).flatten().astype("float32") c_transform = numpy.ctypeslib.as_ctypes(transform) glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, c_transform)
def applyTransforms(vector, projectionMat): r = time.clock() + vector[0] * 10 # rotation offset based on vector's 1st component rotX = Matrix44.from_x_rotation(r) rotY = Matrix44.from_y_rotation(r) rotZ = Matrix44.from_z_rotation(r) trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1,1,-5]) # move view back by -5 scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5 tMatrix = projectionMat * trans * scale * rotX * rotY * rotZ prog['transform'].write(tMatrix.astype('f4').tobytes())
def scatterCubes(vector, projectionMat): view = window.getViewMatrix() r = vector[0] * 10.0 # cube rotation offset based on vector's 1st component rotX = Matrix44.from_x_rotation(r*time.clock()/10.0) # rotate cubes over time rotY = Matrix44.from_y_rotation(r) rotZ = Matrix44.from_z_rotation(r) trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1.0,1.0,-5.0]) scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5 tMatrix = projectionMat * view * trans * scale * rotX * rotY * rotZ prog['transform'].write(tMatrix.astype('f4').tobytes())
def render_single_frame(self, r, theta, phi, to_lookat_center=True): self.scene.render_rgb_to_fbo_polar_degrees( r, theta, phi, self.fbo, model=Matrix44.from_y_rotation(np.pi), lookat_center=to_lookat_center) buffer = self.fbo.fbo.read(components=3, dtype='f4') return np.frombuffer(buffer, dtype=np.float32).reshape( (self.fbo.viewport[1], self.fbo.viewport[0], 3))[::-1]
def refresh_position(self): center = self.camera.scene.bounding_box.center dummy_cam = Camera() dummy_cam.matrix = self.default_matrix z_shift = dummy_cam.distance_to_point(center) self.camera.matrix = Matrix44.from_translation([self._shift_x, self._shift_y, self._distance]) * \ Matrix44.from_translation([0, 0, -z_shift]) * \ Matrix44.from_x_rotation(-self._angle_y) * \ Matrix44.from_y_rotation(-self._angle_x) * \ Matrix44.from_translation([0, 0, z_shift]) * \ self.default_matrix post_redisplay()
def render(self): # creating a rotation matrix for the monkey ct = time.clock() rot_y = Matrix44.from_y_rotation(ct*0.5) rot_y = matrix44.multiply(rot_y, InitShader.monkey_model).flatten().astype("float32") c_rotate = numpy.ctypeslib.as_ctypes(rot_y) # to draw the monkey, we need to rebind the monkey's vao glBindVertexArray(self.vao_monkey) glBindTexture(GL_TEXTURE_2D, self.texture) glUniformMatrix4fv(InitShader.model_loc, 1, GL_FALSE, c_rotate) glDrawArrays(GL_TRIANGLES, 0, self.num_verts) glBindVertexArray(0)
def OnDraw(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if self.rotate: ct = time.perf_counter() * 0.1 self.rotate_y = Matrix44.from_y_rotation(ct) glUniformMatrix4fv(self.model_location, 1,GL_FALSE, self.rotate_y) self.Refresh() else: glUniformMatrix4fv(self.model_location, 1,GL_FALSE, self.rotate_y) self.mesh.BindAndDraw() self.SwapBuffers()
def update(dt): proj = Matrix44.perspective_projection(50, width / height, 0.1, 1000.0) rotX = Matrix44.from_x_rotation(0) rotY = Matrix44.from_y_rotation(time.clock() * 1.5) rotZ = Matrix44.from_z_rotation( 180 * np.pi / 180) # rotate 180 degrees. Convert degrees to radians trans = Matrix44.from_translation( [np.sin(time.clock()) / 4, np.sin(time.clock()) / 4, -1.3]) # bounce diagonally from corner to corner, move back by -1.3 scale = Matrix44.from_scale([.5, .5, .5]) # uniformly scale by 0.5 tMatrix = proj * trans * scale * rotX * rotY * rotZ prog['transform'].write(tMatrix.astype('f4').tobytes()) ctx.clear(.1, .1, .1) vao.render()
def build_matrix(self): """Builds and stores the transformation matrix internally""" m = Matrix44.identity() if isinstance(self.scale, list) or isinstance(self.scale, tuple): m.m11 = self.scale[0] m.m22 = self.scale[1] m.m33 = self.scale[2] else: m *= self.scale m.m44 = 1 m = Matrix44.from_x_rotation(math.radians(self.pitch)) * m m = Matrix44.from_y_rotation(math.radians(self.yaw)) * m m = Matrix44.from_z_rotation(math.radians(self.roll)) * m m = Matrix44.from_translation(Vector3(self.position)) * m self.m = numpy.array(m).astype("f4")
def getModelMatrix(self): scale = mat4.from_scale([0.2, 0.2, 0.2]) roty = mat4.from_y_rotation(-self.hAngle) vdiff = self.vAngle - self.oldvAngle rotx = mat4.from_x_rotation(self.getxRot(vdiff)) zdiff = self.hAngle - self.oldhAngle rotz = mat4.from_z_rotation(-self.getzRot(zdiff)) trans = mat4.from_translation(self.position, dtype='f') self.oldhAngle = self.hAngle self.oldvAngle = self.vAngle return scale * rotz * rotx * roty * trans
def build_matrix(self): """Builds and stores the viewport matrix internally Automatically builds the MVP matrix as well""" # Note that by nature, a camera perspective inverts everything # So we negate everything and also do it in reverse # Overrides PositionMatrix, reverse everything, ignore scale m = Matrix44.identity() m = Matrix44.from_translation(-1 * Vector3(self.position)) * m m = Matrix44.from_z_rotation(-math.radians(self.roll)) * m m = Matrix44.from_y_rotation(-math.radians(self.yaw)) * m m = Matrix44.from_x_rotation(-math.radians(self.pitch)) * m if self.tp: # Third person enabled m = Matrix44.from_translation([0, 0, -self.tp_distance]) * m self.m = m self.mvp = numpy.array(self.p * self.m).astype("f4")
def __init__(self, **kwargs): super().__init__(**kwargs) self.scene = MugScene3D(self.ctx) self.init_dnn() self.fbo = Fbo(self.ctx, self.ctx.viewport) self.model = Matrix44.from_y_rotation(np.pi) self.actions = [ # list of keys and the function to call while they are pressed (self.wnd.keys.W, self.scene.camera.dolly_in), (self.wnd.keys.S, self.scene.camera.dolly_out), (self.wnd.keys.A, self.scene.camera.truck_right), (self.wnd.keys.D, self.scene.camera.truck_left), (self.wnd.keys.SPACE, self.scene.camera.pedestal_up), (self.wnd.keys.E, self.scene.camera.pedestal_down), (self.wnd.keys.C, self.classify_frame) ]
def OnDraw(self): if self.bg_color: glClearColor(0.0, 0.0, 0.0, 1.0) else: glClearColor(0.1, 0.15, 0.1, 1.0) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) else: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.translate = matrix44.create_from_translation( Vector3([self.trans_x, self.trans_y, self.trans_z])) self.combined_matrix = matrix44.multiply(self.rot_y, self.translate) if self.rotate: ct = time.clock() self.rot_y = Matrix44.from_y_rotation(ct) glUniformMatrix4fv(self.rot_loc, 1, GL_FALSE, self.rot_y) glUniformMatrix4fv(self.trans_loc, 1, GL_FALSE, self.translate) self.Refresh() else: glUniformMatrix4fv(self.rot_loc, 1, GL_FALSE, self.rot_y) glUniformMatrix4fv(self.trans_loc, 1, GL_FALSE, self.translate) if self.show_triangle: self.mesh.bind_triangle() glDrawArrays(GL_TRIANGLES, 0, self.mesh.tv_count) elif self.show_quad: self.mesh.bind_quad() glDrawArrays(GL_TRIANGLE_STRIP, 0, self.mesh.qv_count) elif self.show_cube: self.mesh.bind_cube() glDrawElements(GL_TRIANGLES, self.mesh.ci_count, GL_UNSIGNED_INT, None) self.SwapBuffers()
def frames(): with create_context() as ctx: renderer = Renderer(ctx, (w, h), mesh, projection=projection) for _ in count(): t = time.time() - beginning theta = t * angular_velocity rotation = Matrix44.from_z_rotation( theta[2]) * Matrix44.from_y_rotation( theta[1]) * Matrix44.from_x_rotation(theta[0]) camera = Matrix44.from_translation(np.array([0, 0, -d ])) * rotation renderer.render(camera, light1) buffer = np.mean(renderer.snapshot2(), axis=-1) lines = ascii.shade(buffer) text = "resolution: {w}x{h}, fov: {fov:.2f}, fps: {fps:.2f}, d: {d:.2f}, by: vidstige 2020".format( w=w, h=h, fov=fov, fps=fps, d=d) lines[-2] = scroller(lines[-2], text, t, w=-12) yield b"\033[2J\033[1;1H" + b'\n'.join(lines) + b"\n" duration = (time.time() - beginning) - t if dt - duration > 0: time.sleep(dt - duration)
def render(self, app, currentTime): glBindVertexArray(self._vao.identifier) try: glUseProgram(self._program.identifier) bg_color = ( math.sin(currentTime) * 0.5 + 0.5, math.cos(currentTime) * 0.5 + 0.5, 0.0, 1.0 ) glClearBufferfv(GL_COLOR, 0, bg_color) glClearBufferfv(GL_DEPTH, 0, [1]) f = currentTime * 0.3 mv_matrix = Matrix44.identity(dtype='f4') mv_matrix *= Matrix44.from_x_rotation( currentTime * math.radians(81)) mv_matrix *= Matrix44.from_y_rotation( currentTime * math.radians(45)) mv_matrix *= Matrix44.from_translation([ math.sin(2.1 * f) * 0.5, math.cos(1.7 * f) * 0.5, math.sin(1.3 * f) * math.cos(1.5 * f) * 2.0]) mv_matrix *= Matrix44.from_translation([0.0, 0.0, -4.0]) self._uniform_block.mv_matrix[:] = mv_matrix.reshape(16) glBufferSubData( GL_UNIFORM_BUFFER, 0, ctypes.sizeof(self._uniform_block), ctypes.byref(self._uniform_block)) self._torus_obj.render() finally: glBindVertexArray(NULL_GL_OBJECT)
def render(self, clr_color=(1.0, 1.0, 1.0)): fbo = self.fbo fbo.clear(*clr_color) cam_ratio = self.fbo.size[0] / self.fbo.size[1] p = Matrix44.perspective_projection(self.cam_angle, cam_ratio, 0.00001, 1000000.0) v = Matrix44.look_at( self.cam_pos, (0, 0, 0), self.cam_up, ) rx = Matrix44.from_x_rotation(self.rotate_x) ry = Matrix44.from_y_rotation(self.rotate_y) rz = Matrix44.from_z_rotation(self.rotate_z) m = rx * ry * rz self._projection.write(p.astype('f4').tobytes()) mv = v * m self._modelview.write(mv.astype('f4').tobytes()) n = mv.inverse.transpose() self._normalMat.write(n.astype('f4').tobytes()) self._mode.value = 2 # Phong #lightPos.value = tuple(tuple(n*Vector4.from_vector3(light_pos))[:3]) self._lightPos.value = tuple(self.light_pos) self._lightColor.value = tuple(self.light_color) self._lightPower.value = self.light_power self._ambientColor.value = tuple(self.ambien_color) self._diffuseColor.value = tuple(self.diffuse_color) self._specColor.value = tuple(self.spec_color) self._shininess.value = self.shininess self._mainColor.value = tuple(self.main_color) self.vao.render() return fbo.read()
fbo.use() # set perspective for all "shaders" prog['projection'].write( Matrix44.perspective_projection(95, 16 / 9, 1, 200, dtype='f4')) prog2['projection'].write( Matrix44.perspective_projection(95, 16 / 9, 1, 200, dtype='f4')) prog3['projection'].write( Matrix44.perspective_projection(95, 16 / 9, 1, 200, dtype='f4')) prog4['projection'].write( Matrix44.perspective_projection(95, 16 / 9, 1, 200, dtype='f4')) mydriver = driver.DummyDriverReceiver(57) modelRotOffz = Matrix44.from_y_rotation(np.pi, dtype='f4') viewPosOffz = Matrix44.from_translation([0, 0, -3], dtype='f4') # viewPosOffz *= Matrix44.from_y_rotation(np.pi/4, dtype='f4') prog4['transformMat'].write( Matrix44.from_translation([0, 1.2, 0], dtype='f4') * viewPosOffz) with mydriver: mydriver.send('hello') while 1: fbo.clear(0.0, 0.0, 0.0, 0.0) data = mydriver.get_pose() hmd = data[:13] cntl1 = data[13:13 + 22] cntl2 = data[13 + 22:13 + 22 + 22]
aspect = float(window_size[0]) / float(window_size[1]) projection = Matrix44.perspective_projection(90., aspect, 1., 100., np.float32) model_view = Matrix44.from_translation([0., 0., -8.], np.float32) GL.glClearColor(0.2, 0.2, 0.2, 1.0) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDisable(GL.GL_CULL_FACE) last = time.clock() glfw.MakeContextCurrent(window) while not glfw.WindowShouldClose(window): current = time.clock() delta = current - last GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) rotation = Matrix44.from_y_rotation(math.pi * delta, np.float32) model_view = rotation * model_view sm.render(in_projection=projection, in_model_view=model_view) glfw.SwapBuffers(window) glfw.PollEvents() last = current glfw.DestroyWindow(window) glfw.Terminate() exit()
def getModelMatrix(self): # TODO: maybe spin planet around another axis and add scaling rot = mat4.from_y_rotation(self.rot, dtype='f') trans = mat4.from_translation(self.position, dtype='f') return rot * trans
def main(): if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) w_width, w_height = 1440, 900 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_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) monkey_obj = ObjLoader() monkey_obj.load_model('monkey.obj') monkey_tex = TextureLoader.load_texture("res/monkey.png") monkey_tex_offset = len(monkey_obj.vertex_index) * 12 monkey_norm_offset = (monkey_tex_offset + len(monkey_obj.texture_index) * 8) sphere_obj = ObjLoader() sphere_obj.load_model('sphere2.obj') sphere_tex = TextureLoader.load_texture("res/yellow.png") sphere_tex_offset = len(sphere_obj.vertex_index) * 12 sphere_norm_offset = (sphere_tex_offset + len(sphere_obj.texture_index) * 8) shader = ShaderLoader.compile_shader("Shaders/vert.vs", "Shaders/frag.fs") sphere_vao = glGenVertexArrays(1) glBindVertexArray(sphere_vao) sphere_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, sphere_VBO) glBufferData(GL_ARRAY_BUFFER, sphere_obj.model.itemsize * len(sphere_obj.model), sphere_obj.model, GL_STATIC_DRAW) #Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #TextureCoords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 2, ctypes.c_void_p(sphere_tex_offset)) glEnableVertexAttribArray(1) #Normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 3, ctypes.c_void_p(sphere_norm_offset)) glEnableVertexAttribArray(2) glBindVertexArray(0) monkey_vao = glGenVertexArrays(1) glBindVertexArray(monkey_vao) monkey_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monkey_VBO) glBufferData(GL_ARRAY_BUFFER, monkey_obj.model.itemsize * len(monkey_obj.model), monkey_obj.model, GL_STATIC_DRAW) #Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #TextureCoords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 2, ctypes.c_void_p(monkey_tex_offset)) glEnableVertexAttribArray(1) #Normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 3, ctypes.c_void_p(monkey_norm_offset)) glEnableVertexAttribArray(2) glBindVertexArray(0) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) projection = pyrr.matrix44.create_perspective_projection_matrix( 60.0, w_width / w_height, 0.1, 100.0) sphere_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])) glUseProgram(shader) model_loc = glGetUniformLocation(shader, "model") view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "proj") light_loc = glGetUniformLocation(shader, "light") 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) light_y = Matrix44.from_y_rotation(0.5) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5) glUniformMatrix4fv(light_loc, 1, GL_FALSE, light_y) glBindVertexArray(sphere_vao) glBindTexture(GL_TEXTURE_2D, sphere_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, Matrix44(sphere_model) * rot_y) glDrawArrays(GL_TRIANGLES, 0, len(sphere_obj.vertex_index)) glBindVertexArray(0) glBindVertexArray(monkey_vao) glBindTexture(GL_TEXTURE_2D, monkey_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_model) glDrawArrays(GL_TRIANGLES, 0, len(monkey_obj.vertex_index)) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return 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("resources/cubeFiles/cube.obj") cube_tex = TextureLoader.load_texture( "resources/cubeFiles/cube_texture.jpg") cube_texture_offset = len(cube.vertex_index) * 12 monkey = ObjLoader() monkey.load_model("resources/monkey/monkey.obj") monkey_tex = TextureLoader.load_texture("resources/monkey/monkey.jpg") monkey_texture_offset = len(monkey.vertex_index) * 12 monster = ObjLoader() monster.load_model("resources/monster/monster.obj") monster_tex = TextureLoader.load_texture("resources/monster/monster.jpg") monster_texture_offset = len(monster.vertex_index) * 12 generic_shader = ShaderLoader.compile_shader("resources/shaders/gen.vs", "resources/shaders/gen.fs") 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(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) 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) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5) glBindVertexArray(cube_vao) glBindTexture(GL_TEXTURE_2D, cube_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * cube_model) glDrawArrays(GL_TRIANGLES, 0, len(cube.vertex_index)) glBindVertexArray(0) glBindVertexArray(monkey_vao) glBindTexture(GL_TEXTURE_2D, monkey_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_model) glDrawArrays(GL_TRIANGLES, 0, len(monkey.vertex_index)) glBindVertexArray(0) 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) glfw.swap_buffers(window) glfw.terminate()
def rotate_y(self, angle): self._rotation *= Matrix44.from_y_rotation(angle) self._update_uniforms()
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()
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(): # 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(): # 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 getModelMatrix(self): rot = mat4.from_y_rotation(self.rot, dtype='f') trans = mat4.from_translation(self.position, dtype='f') return rot * trans