def look_at(self, position, target, world_up): # 1.Position = known # 2.Calculate cameraDirection zaxis = vector.normalise(position - target) # 3.Get positive right axis vector xaxis = vector.normalise( vector3.cross(vector.normalise(world_up), zaxis)) # 4.Calculate the camera up vector yaxis = vector3.cross(zaxis, xaxis) # create translation and rotation matrix translation = Matrix44.identity() translation[3][0] = -position.x translation[3][1] = -position.y translation[3][2] = -position.z rotation = Matrix44.identity() rotation[0][0] = xaxis[0] rotation[1][0] = xaxis[1] rotation[2][0] = xaxis[2] rotation[0][1] = yaxis[0] rotation[1][1] = yaxis[1] rotation[2][1] = yaxis[2] rotation[0][2] = zaxis[0] rotation[1][2] = zaxis[1] rotation[2][2] = zaxis[2] return translation * rotation
def __init__(self, cam_intrinsic_settings = CameraIntrinsicSettings(), scene_object = None): super(Camera, self).__init__(scene_object) self.camera_matrix = Matrix44.identity() self.projection_matrix = Matrix44.identity() self.set_instrinsic_settings(cam_intrinsic_settings)
def __init__(self): self.color = Color(0.0, 0.0, 0.0) self.aabb = aabb.create_from_bounds([0.0, 0.0, 0.0], [0.5, 0.5, 0.5]) self.translation_matrix = Matrix44.identity() self.scale_matrix = Matrix44.identity() self.rotation_matrix = Matrix44.identity() self.selected = False
def _gl_look_at(self, pos, target, up) -> numpy.ndarray: """The standard lookAt method. Args: pos: current position target: target position to look at up: direction up Returns: numpy.ndarray: The matrix """ z = vector.normalise(pos - target) x = vector.normalise(vector3.cross(vector.normalise(up), z)) y = vector3.cross(z, x) translate = Matrix44.identity(dtype="f4") translate[3][0] = -pos.x translate[3][1] = -pos.y translate[3][2] = -pos.z rotate = Matrix44.identity(dtype="f4") rotate[0][0] = x[0] # -- X rotate[1][0] = x[1] rotate[2][0] = x[2] rotate[0][1] = y[0] # -- Y rotate[1][1] = y[1] rotate[2][1] = y[2] rotate[0][2] = z[0] # -- Z rotate[1][2] = z[1] rotate[2][2] = z[2] return rotate * translate
def init(self, width, height, render_samples=16): if not self._initialized: self.ctx = ContextManager.get_offscreen_context() self._scene = Scene(self.ctx) self._scene.init() # A fullscreen quad just for rendering one pass to offscreen textures self.quad_fs = QuadFS(self.ctx) self.quad_fs.m_model.write( Matrix44.identity().astype('f4').tobytes()) self.quad_fs.m_view.write( Matrix44.identity().astype('f4').tobytes()) self.quad_fs.m_proj.write( Matrix44.orthogonal_projection(-1, 1, 1, -1, 1, 10).astype('f4').tobytes()) self.quad_fs.flip_v.value = 0 # aa sampler self.setRenderSamples(render_samples) self._initialized = True print("Workbench initialized") if (self._width, self._height) != (width, height): self.resize(width, height)
def __init__(self, ctx, width, height, Type, id): self.ctx = ctx self.type = Type self.ParentCube = id self.color = self.fromTypeToColor(self.type) self.width = width self.height = height self.x_rot = 0 self.y_rot = 0 self.x_last = 0 self.y_last = 0 self.x_cur = 0 self.y_cur = 0 self.isRotating = False self.orientation = pyrr.quaternion.create(0.0, 0.0, 0.0, 1.0) self.proj = Matrix44.perspective_projection(45.0, self.width / self.height, 0.1, 100.0) self.camera_pos = [0, 3, -8.0] self.vertexes = VERTICES[self.fromTypeTOIndex(Type)] self.rotation = Matrix44.identity() self.rotationLayer = Matrix44.identity() self.degree = 0 self.translation = Matrix44.identity() self.view = Matrix44.look_at( self.camera_pos, # position of camera in world coordinate (0.0, 0.0, 0.0), # target (0.0, 1.0, 0.0), ) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_color; out vec3 v_color; out vec4 Position; void main() { gl_Position = Mvp*vec4(in_vert, 1.0); v_color = in_color; Position=vec4(in_vert,1.0); } ''', fragment_shader=''' #version 330 in vec3 v_color; in vec4 Position; out vec4 f_color; void main() { f_color=vec4(v_color,1); } ''', )
def __init__(self, ctx, width, height, id): self.ctx = ctx self.faces = [Face(ctx, width, height, i, id) for i in range(6)] self.ID = id for i in CUBEFACE[id]: self.faces[i].setImportance() for i in self.faces: i.setUp() self.translation = Matrix44.identity() self.rotation = Matrix44.identity()
def __init__(self): self.location = Vector3() self.scale = Vector3([1, 1, 1]) self.rotation = Rotator([0.0, 0.0, 0.0]) self.quaternion = Quaternion([0, 0, 0, 1]) self.initial_matrix = Matrix44.identity() self.transform_matrix = Matrix44.identity() # Flag indicate whether the transformation is modified or not self.is_changed = False
def set_identity(self, event): self.canvas.combined_matrix = Matrix44.identity() self.canvas.rotate = False self.canvas.trans_x, self.canvas.trans_y, self.canvas.trans_z = 0, 0, 0 self.canvas.rot_y = Matrix44.identity() self.x_slider.SetValue(0) self.y_slider.SetValue(0) self.z_slider.SetValue(0) self.log_matrix() self.canvas.Refresh()
def __init__(self, wcg: mglw.WindowConfig): self.wcg = wcg self.program = wcg.load_program('programs/candlestick.glsl') self.program['m_view'].write(Matrix44.identity(dtype='f4')) self.program['m_model'].write(Matrix44.identity(dtype='f4')) self.vertices = np.array([0, 20, 0, 1000, 20, 0]) self.vbo = wcg.ctx.buffer(self.vertices.astype('f4').tobytes()) self.vao = wcg.ctx.vertex_array(self.program, [(self.vbo, '3f', 'in_position')])
def __init__(self, ctx, width, height, id): self.ctx = ctx self.faces = [ FaceType2(ctx, width, height, i, id) for i in CUBEFACE[id] ] self.ID = id for i in self.faces: #print("setting up") i.setUp() self.translation = Matrix44.identity() self.rotation = Matrix44.identity()
def __init__(self, position, pitch, yaw, roll, width, height, fov, near_plane, far_plane, tp, tp_distance): """Initiates a ViewportMatrix View matrix arguments: - position: tuple length 3, location of camrea - pitch/yaw/roll: floats, rotations along xyz axis Perspective matrix arguments: - width/height: ints, frame width and height - fov: int, field of view in y direction - near_plane: float, clipping for plane closest to camera (recommended=0.1) - far_plane: float, clipping for plane farthest from camera - tp: boolean, whether third person camera should be used - tp_distance: float, distance from camera location to actual viewport location Automatically builds the MVP matrix as well """ self.position = position self.pitch = pitch self.yaw = yaw self.roll = roll self.width = width self.height = height self.near_plane = near_plane self.far_plane = far_plane self.fov = fov self.tp = tp self.tp_distance = tp_distance # Set p to identity so these method auto build the MVP self.p = Matrix44.identity() self.build_view_matrix() self.build_proj_matrix()
def __init__(self, app): # box model self.model = geometry.quad_2d((1, 1), (0.5, 0.5), False, False) # shader self.prog = app.load_program('programs/candlestick.glsl') self.prog['m_view'].write(Matrix44.identity(dtype='f4')) self.upper_cut = -1
def create_transformation_matrix(translation, rx, ry, rz, scale) -> Matrix44: matrix = Matrix44.identity() matrix = matrix.from_translation([translation]) matrix = matrix * matrix.from_x_rotation(np.radians(rx)) * matrix.from_y_rotation(np.radians(ry)) * \ matrix.from_z_rotation(np.radians(rz)) * matrix.from_scale([scale, scale, scale]) return matrix
def __init__(self, scene=None, camera=Camera()): QtCore.QObject.__init__(self) self.ctx = None self._initialized = False self._is_running_ipr = False self._progressive_update = False self._frame_buffer = None # final composited frame self._render_buffer = None self._width = None self._height = None self._camera = camera self._image_data = None # helpers self.m_identity = Matrix44.identity() # just a helper # signals self.signals = Signals() logger.debug("Workbench Renderer created")
def CylinderGeometryTwoPoints(P1, P2, R1=1, R2=1, color=(1,0,0), nz=2, yRes=12, rotateOutput=True): """ Generate a cylinder using two points P1, P2 yRes: number of points along a circle (4: triangle (minimum), 5: square, 6: pentagones, etc) nz: number of points along the z direction (3: pyramid (minimum) return vertices, faces, normals and colors """ DP= np.asarray(P2)[:3]-np.asarray(P1)[:3] L = np.linalg.norm(DP) #print('L',L) # Create a cylinder oriented around z and at origin 0,0,0 vertices, faces, normals, colors = CylinderGeometry(R1=R1, R2=R2, height=L, color=color, nz=nz, yRes=yRes) # print(vertices) # Get the transformation matrix from thes vertices to the points tmat= matrix44_2points(P1, P2, up=(0,0,1), origin=(0,0,0)) #print(tmat) # tmat=Matrix44.identity() # print(tmat) if rotateOutput: if vertices.shape[1]==3: vertices=np.column_stack((vertices,np.ones((vertices.shape[0],1),dtype=np.float32))) if normals.shape[1]==3: normals=np.column_stack((normals,np.zeros((normals.shape[0],1),dtype=np.float32))) vertices = tmat.dot(vertices.T).T normals = tmat.dot(normals.T).T tmat=Matrix44.identity() return vertices, faces, normals, colors, tmat
def __init__(self, **kwargs): super().__init__(**kwargs) self.wnd.mouse_exclusivity = True self.camera.projection.update(near=1, far=1000) self.cube = geometry.cube(size=(2, 2, 2)) self.prog = self.load_program('programs/cube_simple_instanced.glsl') self.prog['m_proj'].write(self.camera.projection.matrix) self.prog['m_model'].write(Matrix44.identity(dtype='f4')) # Generate per instance data represeting a grid of cubes N = 100 self.instances = N * N def gen_data(x_res, z_res, spacing=2.5): """Generates a grid of N * N poistions and random colors on the xz plane""" for y in range(z_res): for x in range(x_res): yield -N * spacing / 2 + spacing * x yield 0 yield -N * spacing / 2 + spacing * y yield numpy.random.uniform(0, 1) yield numpy.random.uniform(0, 1) yield numpy.random.uniform(0, 1) self.instance_data = self.ctx.buffer(numpy.fromiter(gen_data(N, N), 'f4', count=self.instances * 6)) self.cube.buffer(self.instance_data, '3f 3f/i', ['in_offset', 'in_color'])
def __init__(self, data): self.name = data.get("name") self.children = data.get("children") self.matrix = data.get("matrix") self.mesh = data.get("mesh") self.camera = data.get("camera") self.translation = data.get("translation") self.rotation = data.get("rotation") self.scale = data.get("scale") if self.matrix: self.matrix = Matrix44(self.matrix) else: self.matrix = Matrix44.identity() if self.translation is not None: self.matrix = self.matrix * Matrix44.from_translation( self.translation) if self.rotation is not None: quat = quaternion.create( x=self.rotation[0], y=self.rotation[1], z=self.rotation[2], w=self.rotation[3], ) self.matrix = self.matrix * Matrix44.from_quaternion( quat).transpose() if self.scale is not None: self.matrix = self.matrix * Matrix44.from_scale(self.scale)
def __init__(self, data): self.name = data.get('name') self.children = data.get('children') self.matrix = data.get('matrix') self.mesh = data.get('mesh') self.camera = data.get('camera') self.translation = data.get('translation') self.rotation = data.get('rotation') self.scale = data.get('scale') if self.matrix: self.matrix = Matrix44(self.matrix) else: self.matrix = Matrix44.identity() if self.translation is not None: self.matrix = self.matrix * Matrix44.from_translation(self.translation) if self.rotation is not None: quat = quaternion.create( x=self.rotation[0], y=self.rotation[1], z=self.rotation[2], w=self.rotation[3], ) self.matrix = self.matrix * Matrix44.from_quaternion(quat).transpose() if self.scale is not None: self.matrix = self.matrix * Matrix44.from_scale(self.scale)
def calculate_node_bounds(node, transform=Matrix44.identity()): minimum = [100, 100, 100] maximum = [-100, -100, -100] transform = transform * node.transform if isinstance(node.transform, Matrix44) else transform def calculate_mesh_bounds(mesh, transform): arrays = mesh.arrays pos_vertices = arrays["POSITION"]["data"] pos_indices = arrays["POSITION"]["indices"] pos_multi = np.array(np.split(pos_vertices, len(pos_vertices)//3)) pos = pos_multi[pos_indices] pos = np.array([np.array([*x, 1.0]) for x in pos]) trans_pos = np.dot(transform.T, pos.T).T trans_pos = np.array([x[0:3] for x in trans_pos]) maxi = trans_pos.max(axis=0) mini = trans_pos.min(axis=0) return ( mini, maxi ) for child in node.children: child_min, child_max = calculate_node_bounds(child, transform) minimum = np.minimum(child_min, minimum) maximum = np.maximum(child_max, maximum) for mesh in node.meshes: mesh_min, mesh_max = calculate_mesh_bounds(mesh, transform) minimum = np.minimum(mesh_min, minimum) maximum = np.maximum(mesh_max, maximum) return minimum, maximum
def render(self): #print("GeometryViewport render") self.makeCurrent() start_time = time.time() m_view = self.activeCamera.getTransform() m_proj = self.activeCamera.getProjection() # Render the scene to offscreen buffer self.offscreen.use() self.offscreen.clear(0.0) self.ctx.multisample = True self.ctx.disable(moderngl.DEPTH_TEST) # Render guides self.ctx.enable(moderngl.DEPTH_TEST) # TODO: we might also want to pass model matrix so we can get different grid orientations instead of rebuilding grid self.scene_manager.grid.view.write(m_view.astype('f4').tobytes()) self.scene_manager.grid.projection.write(m_proj.astype('f4').tobytes()) self.scene_manager.grid.draw() self.scene_manager.origin.model.write( Matrix44.identity().astype('f4').tobytes()) self.scene_manager.origin.view.write(m_view.astype('f4').tobytes()) self.scene_manager.origin.projection.write( m_proj.astype('f4').tobytes()) self.scene_manager.origin.draw() # draw guides self.drawSceneObjects(m_view, m_proj) # Activate the window screen as the render target self.ctx.disable(moderngl.DEPTH_TEST) self.screen.clear(0.0) self.screen.use() # Image from renderer self.offscreen2_diffuse.use(location=0) self.quad_fs.render() # Render offscreen guides buffer over of screen self.ctx.enable(moderngl.BLEND) self.ctx.blend_equation = moderngl.FUNC_ADD self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA self.offscreen_diffuse.use(location=0) self.quad_fs.render() self.ctx.disable(moderngl.BLEND) self.ctx.finish() time_now = time.time() self.hud_info.fps = 1.0 / (time_now - start_time) # render hud surface self.renderHUD(0)
def __init__(self, ctx, **kwargs): self.ctx = ctx #self.ctx = ContextManager.get_offscreen_context()#moderngl.create_context() self._visible = True self._xform = Matrix4() self._name = None self.m_identity = Matrix44.identity()
def __init__(self, boundlesspath, basedir, ctx, args): # Path to a boundless installation self.boundlesspath = boundlesspath self.basedir = basedir self.args = args with open(self.boundlesspath + '/assets/archetypes/compiledcolorpalettelists.msgpack', 'rb') as palettefile: self.palette_json = utils.convert_msgpackfile(palettefile) self.lookat = Matrix44.look_at((10, 10, 0.0), (10, 10, -5), (0, 1, 0)) self.perspective = Matrix44.perspective_projection(FOV, 1.0, 0.01, 1000.0) self.projection_mat = self.perspective * self.lookat self.model_mat = Matrix44.identity() # Parsed shaders self.shaders = parse_shaders.get_shaders() with open(self.boundlesspath + "/assets/archetypes/compiledspecialmaterials.msgpack", 'rb') as specialsfile: self.specials_json = utils.convert_msgpackfile(specialsfile) self.specials_names = list(map(lambda a: a["name"], self.specials_json)) # A map of all the textures we use which are constant # Key is the uniform name, value is the texture object self.local_tex_path = os.path.join(self.basedir, 'assets/textures') self.const_tex = {} # Dynamic textures self.dyn_tex = {} self.ctx = ctx # Necessary to stop memory leaks self.ctx.gc_mode = "auto" # Note: this is the dimensions of the image. Certain items/blocks/props won't fill # this canvas. self.target_size = (int(args["resolution"]), int(args["resolution"])) self.render_size = ( int(self.target_size[0] // 0.9), int(self.target_size[1] // 0.9) ) if args["anti_alias"] else self.target_size # Initialise properly later, just allocating the field self.prog = {} self.cbo = self.ctx.renderbuffer(self.render_size) self.dbo = self.ctx.depth_texture(self.render_size, alignment=1) self.fbo = self.ctx.framebuffer(color_attachments=(self.cbo), depth_attachment=self.dbo) self.fbo.use() # Initialise all of the constant textures self.init_constant_tex2ds() self.init_constant_texcubes() self.buffer_cache = [] # Grab uniforms with open(os.path.join(self.basedir, 'assets/shader_dump.json')) as uniformsfile: self.uniforms_json = json.load(uniformsfile)
def create_view_matrix(camera): view_matrix = Matrix44.identity() view_matrix = view_matrix.from_x_rotation(np.radians(camera.pitch)) * \ view_matrix.from_y_rotation(np.radians(camera.yaw)) negative_camera_position = [ -camera.position[0], -camera.position[1], -camera.position[2] ] view_matrix = view_matrix * view_matrix.from_translation( negative_camera_position) return view_matrix
def __init__(self): # Два главных аттрибута камеры self.viewMatrix: Matrix44 = Matrix44.identity(dtype=np.float32) self.projectionMatrix: Matrix44 = matrix44.create_perspective_projection( FOV, 1, NEAR_PLANE, FAR_PLANE, dtype=np.float32) # X, Y self.pitch: float = 0 self.yaw: float = 0 # Переменные с плавным переходом self.angleAroundPlayer = SmoothFloat(0, 10) self.distanceFromPlayer = SmoothFloat(20, 5)
def __init__(self, scene_viewer, **kwargs): self._scene_viewer = scene_viewer self.ctx = ContextManager.get_default_context() #self.ctx = moderngl.create_context() self._visible = True self._xform = Matrix4() self._name = None self.m_identity = Matrix44.identity()
def __init__(self, name: str = "New Node"): """ Node element of scene graph (tree structure). Args: name: Name for string representation. """ self.children = list() self._parent = None self.name = name self._local_position = Vector3() self._world_position = Vector3() self._scale = Vector3([1., 1., 1.]) self._local_quaternion = Quaternion() self._world_quaternion = Quaternion() self._world_matrix = Matrix44.identity() self._local_matrix = Matrix44.identity() self.__matrix_needs_update = True
def __init__(self, **kwargs): super().__init__(**kwargs) imgui.create_context() self.wnd.ctx.error self.imgui = ModernglWindowRenderer(self.wnd) self.cube = geometry.cube(size=(2, 2, 2)) self.prog = self.load_program('programs/cube_simple.glsl') self.prog['color'].value = (1.0, 1.0, 1.0, 1.0) self.prog['m_camera'].write(Matrix44.identity(dtype='f4')) self.prog['m_proj'].write(Matrix44.perspective_projection(75, self.wnd.aspect_ratio, 1, 100, dtype='f4')) self.slider_value = 88
def __init__(self, scene=None, color=RGBColor(0, 0, 0), observable=False): if scene is None: scene = Scene() self.raycaster = Raycaster() self.box_select = BoxSelect(self.raycaster, self) self.poly_select = PolySelect(self.raycaster, self) self.scene = scene self.color = color self._matrix_stack = [] self.matrix = Matrix44.identity(dtype=numpy.float32) self.saved_matrix_state = None self.wireframe = False self.selection_view = False self.proj_matrix = Matrix44.identity(dtype=numpy.float32) self.set_up_vector(Vector3([0, 1, 0])) self.set_position(Vector3()) self.set_point_of_interest(Vector3([0, 0, -10])) if observable: CameraObservable.get().add_observer(self)
def render(self, time=0, frametime=0, projection=None, modelview=None, target=None): self.ctx.enable(self.ctx.DEPTH_TEST | self.ctx.CULL_FACE) self.ctx.wireframe = True try: self.program['time'] = time except KeyError: pass self.program['m_proj'].write(projection) self.program['m_cam'].write(modelview) self.program['m_model'].write(Matrix44.identity(dtype="f4")) self.sphere.render(self.program) self.ctx.wireframe = False
def __init__(self, name=None, position=None, texImg=None, specTexImg=None, normalMap=None, shininess=None, ka=None, kd=None, ks=None, program=None): self.model = mat4.identity(dtype='f') self.name = name self.position = position self.texImg = texImg self.specTexImg = specTexImg self.normalMap = normalMap self.shininess = shininess self.ka = ka self.kd = kd self.ks = ks self.program = program self.initTextures()
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 getModelMatrix(self): return mat4.identity(dtype='f')
def __init__(self): self.renderBatches = {} self.view = Matrix44.identity() self.AdjustView((0.0, 0.0, -30), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)) self.perspectiveMatrix = Matrix44.identity()