def generateTerrain(self, loader, heightMap): image = Image.open(heightMap) rgb_image = image.convert('RGB') VERTEX_COUNT = image.height image.close() self.heights = np.empty(shape=[VERTEX_COUNT, VERTEX_COUNT]) vertices = [] normals = [] textureCoords = [] for i in range(VERTEX_COUNT): for j in range(VERTEX_COUNT): height = self.__getHeight(j, i, rgb_image) self.heights[j][i] = height vertices.append( Vector3([ j / (VERTEX_COUNT - 1) * self.__SIZE, height, i / (VERTEX_COUNT - 1) * self.__SIZE ])) normal = self.__calculateNormal(j, i, rgb_image) normals.append(normal) textureCoords.append( Vector3( [j / (VERTEX_COUNT - 1), i / (VERTEX_COUNT - 1), 0.0])) indices = [] for gz in range(VERTEX_COUNT - 1): for gx in range(VERTEX_COUNT - 1): topLeft = (gz * VERTEX_COUNT) + gx topRight = topLeft + 1 bottomLeft = ((gz + 1) * VERTEX_COUNT) + gx bottomRight = bottomLeft + 1 indices.append(topLeft) indices.append(bottomLeft) indices.append(topRight) indices.append(topRight) indices.append(bottomLeft) indices.append(bottomRight) finalVertexList = [] finalNormalList = [] finalTextCoordsList = [] for num in range(len(indices)): vertexNumber = indices[num] finalVertexList.append(Vector3(vertices[vertexNumber])) finalNormalList.append(Vector3(normals[vertexNumber])) finalTextCoordsList.append(Vector3(textureCoords[vertexNumber])) finalVertexList = np.array(finalVertexList) finalNormalList = np.array(finalNormalList) finalTextCoordsList = np.array(finalTextCoordsList) return loader.loadToVAO(finalVertexList, finalTextCoordsList, finalNormalList)
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 create_nodes_with_importance(layer_nodes: List[int], center_position: Vector3, x_range: Tuple[float, float], y_range: Tuple[float, float], z_range: Tuple[float, float], node_importance_data: List[np.array], node_size: float = None) -> List[List[Node]]: nodes: List[List[Node]] = [] num_classes: int = layer_nodes[len(layer_nodes) - 1] padding: int = get_buffer_padding(num_classes, ADDITIONAL_NODE_BUFFER_DATA) for layer, node_count in enumerate(layer_nodes): input_edges: int = 0 output_edges: int = 0 if 0 < layer: input_edges = layer_nodes[layer - 1] if layer < len(layer_nodes) - 1: output_edges = layer_nodes[layer + 1] nodes_sqrt = math.ceil(math.sqrt(node_count)) current_layer_nodes: List[Node] = [] if node_count <= 1: position: Vector3 = Vector3([ center_position.x, center_position.y, z_range[0] * (1 - layer / (len(layer_nodes) - 1)) + z_range[1] * layer / (len(layer_nodes) - 1) ]) current_layer_nodes.append( Node(len(current_layer_nodes), input_edges, output_edges).importance_init( num_classes, padding, position, node_importance_data[layer][0])) else: node_size_x: float = node_size node_size_y: float = node_size if node_size is None: node_size_x = abs(x_range[1] - x_range[0]) / nodes_sqrt node_size_y = abs(y_range[1] - y_range[0]) / nodes_sqrt for i in range(node_count): pos_x: float = (i % nodes_sqrt) - (nodes_sqrt - 1.0) / 2.0 pos_y: float = (math.floor( i / nodes_sqrt)) - (nodes_sqrt - 1.0) / 2.0 position: Vector3 = Vector3([ pos_x * node_size_x + center_position.x, pos_y * node_size_y + center_position.y, z_range[0] * (1 - layer / (len(layer_nodes) - 1)) + z_range[1] * layer / (len(layer_nodes) - 1) ]) current_layer_nodes.append( Node(len(current_layer_nodes), input_edges, output_edges).importance_init( num_classes, padding, position, node_importance_data[layer][i])) nodes.append(current_layer_nodes) return nodes
def set_position(self, camera_position_index: CameraPose): self.move_vector = Vector3([0, 0, 0]) self.camera_up = Vector3([0.0, 1.0, 0.0]) self.camera_pos = CAMERA_POSE_POSITION[camera_position_index] self.camera_pos = self.base + self.camera_pos self.camera_front = Vector3( vector.normalise(self.base - self.camera_pos)) self.set_yaw_pitch_from_front(not camera_position_index == 0) self.camera_right = Vector3( vector.normalise(np.cross(self.camera_up, self.camera_front))) self.yaw_offset = 0.0
def refract(v: vec3, n: vec3, ni_over_nt: float, refracted: vec3) -> bool: uv = v.normalized dt = uv.dot(n) discriminant = 1.0 - ni_over_nt**2 * (1.0 - dt**2) if discriminant > 0: new_refracted = ni_over_nt * (uv - n * dt) - n * sqrt(discriminant) refracted.x = new_refracted.x refracted.y = new_refracted.y refracted.z = new_refracted.z return True return False
def __init__(self, radius: float, **kwargs): self._radius: float = radius self._pos: Vector3 = Vector3([0.0, 0.0, 0.0]) self._center: Vector3 = Vector3(kwargs.get("center", [0.0, 0.0, 0.0])) self._axes_lengths: Vector3 = Vector3( kwargs.get("axes_lengths", [0.0, 0.0, 0.0])) self._velocities: Vector3 = Vector3( kwargs.get("velocities", [0.0, 0.0, 0.0])) self._phase: Vector3 = Vector3(kwargs.get("phase", [0.0, 0.0, 0.0])) self._color: (float, float, float) = tuple(kwargs.get("color", (1.0, 1.0, 1.0)))
def pTov(self, x, y, radius): x = (2.0 * x) / self.windowWidth - 1.0 y = 1.0 - (2.0 * y) / self.windowHeight d = math.sqrt(x * x + y * y) z = 0 if d < radius: z = math.sqrt(radius * radius - d * d) return Vector3([x, y, z]) else: z = 0 return Vector3([x / d * radius, y / d * radius, z])
def __init__(self): self.camera_pos = Vector3([0.0, 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.pitch_constraint = 60 self.move_disabled = False
def update_camera_vectors(self): front = Vector3([0.0, 0.0, 0.0]) front.x = cos(radians(self.yaw)) * cos(radians(self.pitch)) front.y = sin(radians(self.pitch)) front.z = sin(radians(self.yaw)) * cos(radians(self.pitch)) self.camera_front = vector.normalise(front) self.camera_right = vector.normalise( vector3.cross(self.camera_front, Vector3([0.0, 1.0, 0.0]))) self.camera_up = vector.normalise( vector3.cross(self.camera_right, self.camera_front))
def __init__(self): self.camera_pos = Vector3([0.0, 0.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.yaw = -90.0 self.pitch = 0.0 self.last_camera_y = 0
def __compute_view_matrix(self, drone_pose): # Camera view matrix return Matrix44.look_at( # eye: position of the camera in world coordinates drone_pose.translation, # target: position in world coordinates that the camera is looking at drone_pose.translation + (drone_pose.orientation * Vector3([1.0, 0.0, 0.0])), # up: up vector of the camera. drone_pose.orientation * Vector3([0.0, 0.0, 1.0]), )
def calculateMouseRay(self, projectionMatrix, viewMAtrix, screenX, screenY, mouse_x, mouse_y): x = (2.0 * mouse_x) / screenX - 1.0 y = 1.0 - (2.0 * mouse_y) / screenY z = -1.0 D_view = Vector4.from_vector3(Vector3([x, y, z]), w=1.0) ray_eye = projectionMatrix.inverse * D_view ray_eye = Vector4([ray_eye.x, ray_eye.y, -1.0, 0.0]) ray_wor = ((viewMAtrix.inverse) * ray_eye).xyz return Vector3(ray_wor)
def __init__(self, width, height, view): self.camera_position = Vector3([0., 0., 3.]) self.camera_front = Vector3([0., 0., -1.]) self.view_loc = view self.sensitivity = .4 self.last_frame = 0 self.last_x = width / 2 self.last_y = height / 2 self.pitch = 0 self.yaw = 0 self.last_cam_y = 0
def Axis_from_jaw_pitch(jaw, pitch): front = Vector3([0.0, 0.0, 0.0]) # jaw, pitch are spherical coordinates that define a unit vector front.x = cos(radians(jaw)) * cos(radians(pitch)) front.z = sin(radians(pitch)) front.y = sin(radians(jaw)) * cos(radians(pitch)) right = vector3.cross(front, Vector3([0.0, 0.0, 1.0])) up = vector3.cross(right, front) return (front, right, up)
def __init__(self, x, y, radius): # self.windowWidth = x self.windowHeight = y self.radius = radius self.startX = 0 self.startY = 0 self.trackballMove = False self.curPos = Vector3([0, 0, 0]) self.lastPos = Vector3([0, 0, 0]) self.angle = 0 self.axis = Vector3([1, 0, 1]) self.doingAnything = True
def barryCentric(p1, p2, p3, pos): # pos is a Vector2 p1 = Vector3(p1) p2 = Vector3(p2) p3 = Vector3(p3) det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z) l1 = ((p2.z - p3.z) * (pos[0] - p3.x) + (p3.x - p2.x) * (pos[1] - p3.z)) / det l2 = ((p3.z - p1.z) * (pos[0] - p3.x) + (p1.x - p3.x) * (pos[1] - p3.z)) / det l3 = 1.0 - l1 - l2 return l1 * p1.y + l2 * p2.y + l3 * p3.y
def rotate(data, xs=1, ys=1, zs=1): out = [] if xs != 1 or ys != 1 or zs != 1: scale = Vector3([xs, ys, zs]) else: scale = None for i in xrange(0, len(data), 3): vec = rotation * Vector3(data[i:i + 3]) if scale is not None: vec *= scale out += list(vec) return out
def __init__(self, ratio): self._field_of_view_degrees = 60.0 self._z_near = 0.1 self._z_far = 1000 self._ratio = ratio self.build_projection() self._camera_position = Vector3([-20.0, 100.0, -20.0]) self._camera_front = Vector3([50.0, -50.0, 50.0]) self._camera_up = Vector3([0.0, 1.0, 0.0]) self._cameras_target = (self._camera_position + self._camera_front) self.build_look_at()
def __init__(self): self.camera_pos = Vector3([0.0, 0.0, 0.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.5 self.velocity = 0.05 self.yaw = 0.0 self.pitch = 0.0 self.lastX = 64 self.lastY = 64
def OnDragValue(self, event): pos = Vector3([ self.position_x.value, self.position_y.value, self.position_z.value ]) up = Vector3([self.up_x.value, self.up_y.value, self.up_z.value]) direction = Vector3([ self.direction_x.value, self.direction_y.value, self.direction_z.value ]) self.flythrough.camera.look_at(pos, pos + direction, up) self.gl_canvas.camera_interactor.reset_position(False) self.gl_canvas.Refresh() self.UpdateTimeline()
def get_position(self) -> Vector3: """ Get camera position in world coordinate system. """ mat = self.matrix relative_pos = Vector3([mat[3, 0], mat[3, 1], mat[3, 2]]) relative_pos *= -1 actual_pos = Vector3() for i in range(3): actual_pos[i] = mat[i, 0] * relative_pos.x + mat[ i, 1] * relative_pos.y + mat[i, 2] * relative_pos.z return actual_pos
def parse_input(input_file: TextIO) -> list[Scanner]: scanners = [] for line in input_file: line = line.strip() if line.startswith("---"): res = parse("--- scanner {idx:d} ---", line) scanner = Scanner(res.named["idx"], [], Vector3(), Matrix33.identity()) scanners.append(scanner) elif line: scanner.beacons.append( Vector3([int(p) for p in line.split(",")], dtype=np.int_)) return scanners
def __init__(self, ctx, vao): """ Construct the Fresnel helper class. :param ctx: The OpenGL context to render in. :param vao: The model to render. """ self.ctx = ctx self.vao = vao self.light_pos = Vector3([0.0, 0.0, 2.0], dtype='f4') self.light_color = Vector3([1.0, 1.0, 1.0], dtype='f4') self.object_color = Vector3([1.0, 0.5, 0.31], dtype='f4')
def test_intersects_bbox(): bbox = BoundingBox(0, 0, 0, 100, 100, 20) origin = Vector3(numpy.array([105, 105, 25], dtype=numpy.float32)) world_origin = Vector3(numpy.array([0, 0, 0], dtype=numpy.float32)) up = Vector3([0, 0, 1], numpy.float32) c = Camera() c.look_at(origin, world_origin, up) direction = c.get_direction() ray = Ray(origin, direction) assert ray.intersects_bbox(bbox) ray.origin = -origin # Move ray past bbox assert not ray.intersects_bbox(bbox) ray.direction = -direction # Now look at it from opposite side assert ray.intersects_bbox(bbox)
def spawn_initial_planets(self): # create sun self.sun = Circle( position=Vector3([PsauxConfig.width / 2.0, PsauxConfig.height / 2.0, 0.0]), mass=1e6, velocity=Vector3([0.0, 0.0, 0.0]), color=RED, batch=self.drawing_batch, ) self.entities.append(self.sun) # create starting planets self.spawn_planet( position=Vector3([200.0, 700.0, 0.0]), velocity=Vector3([3e-4, 4e-5, 0.0]), mass=1e4, color=GREEN, ) self.spawn_planet(Vector3([213.3, 700.0, 0.0]), Vector3([-3e-4, 4e-5, 0.0])) self.spawn_planet( position=Vector3([400.0, 480.0, 0.0]), velocity=Vector3([5e-4, 2e-4, 0.0]), mass=1e4, color=GREEN, )
def create_transformation(self, rotation=None, translation=None): """Convenient transformation method doing rotations and translation""" mat = None if rotation is not None: mat = Matrix44.from_eulers(Vector3(rotation)) if translation is not None: trans = matrix44.create_from_translation(Vector3(translation)) if mat is None: mat = trans else: mat = matrix44.multiply(mat, trans) return mat
def __compute_bbox_coords(self, mesh, view): upright = Quaternion.from_y_rotation(np.pi / 2) rotation = Quaternion(mesh['rotation']) center = mesh['translation'] world_corners = { 'top_left': Vector3([center[0], center[1], center[2]]) + (rotation * upright * Vector3([0, mesh['width'] / 2, mesh['height'] / 2])), 'top_right': Vector3([center[0], center[1], center[2]]) + (rotation * upright * Vector3([0, -mesh['width'] / 2, mesh['height'] / 2])), 'bottom_right': Vector3([center[0], center[1], center[2]]) + (rotation * upright * Vector3([0, -mesh['width'] / 2, -mesh['height'] / 2])), 'bottom_left': Vector3([center[0], center[1], center[2]]) + (rotation * upright * Vector3([0, mesh['width'] / 2, -mesh['height'] / 2])) } hidden_corners = 0 left = right = top = bottom = None for key, value in world_corners.items(): img_coords = self.__project_to_img_frame(value, view) if (img_coords[0] < 10 or img_coords[0] > (self.width - 10) or img_coords[1] < 10 or img_coords[1] > (self.height - 10)): hidden_corners += 1 if left is None or (img_coords[0] < left['x']): left = {'x': img_coords[0], 'y': img_coords[1]} if top is None or (img_coords[1] < top['y']): top = {'x': img_coords[0], 'y': img_coords[1]} if bottom is None or (img_coords[1] > bottom['y']): bottom = {'x': img_coords[0], 'y': img_coords[1]} if right is None or (img_coords[0] > right['x']): right = {'x': img_coords[0], 'y': img_coords[1]} image_corners = { 'min': [int(left['x']), int(top['y'])], 'max': [int(right['x']), int(bottom['y'])] } if hidden_corners > 3: return {} elif hidden_corners > 0: for key, img_coords in image_corners.items(): for i in range(0, 2): if img_coords[i] < 0: img_coords[i] = 0 elif img_coords[i] > (self.width if i == 0 else self.height): img_coords[i] = self.width if i == 0 else self.height image_corners[key] = img_coords return image_corners
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): if self.drag and modifiers ^ pyglet.window.key.MOD_SHIFT: start_x, start_y = self.click_coord movement_vector = Vector3([x - start_x, y - start_y, 0]) delta_x, delta_y, _ = movement_vector * self.world.settings.drag_sensitivity self.world.spawn_planet( position=Vector3([start_x, start_y, 0.0]), velocity=Vector3([delta_x, delta_y, 0.0]), ) self.click_coord = None self.drag = False self.mouse_line.visible = False
def render(self, time: float, frametime: float): self.ctx.enable_only(moderngl.CULL_FACE | moderngl.DEPTH_TEST) m_rot = Matrix44.from_eulers(Vector3((time, time, time))) m_trans = matrix44.create_from_translation(Vector3((0.0, 0.0, -3.0))) m_mv = matrix44.multiply(m_rot, m_trans) self.prog['m_proj'].write(self.camera.projection.tobytes()) self.prog['m_model'].write(m_mv.astype('f4').tobytes()) self.prog['m_camera'].write(self.camera.matrix.astype('f4').tobytes()) self.prog['layer'].value = math.fmod(time, 10) self.prog['texture0'].value = 0 self.texture.use(location=0) self.cube.render(self.prog)
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 test_conversions(self): from pyrr import Quaternion, Matrix33, Matrix44, Vector3, Vector4 v3 = Vector3([1.,0.,0.]) v4 = Vector4.from_vector3(v3, w=1.0) v3, w = Vector3.from_vector4(v4) m44 = Matrix44() q = Quaternion(m44) m33 = Matrix33(q) m33 = Matrix44().matrix33 m44 = Matrix33().matrix44 q = Matrix44().quaternion q = Matrix33().quaternion m33 = Quaternion().matrix33 m44 = Quaternion().matrix44