def render(c, resolution, objects, lights, ambient_intensity, anti_aliasing=False): # image plane coordinates x2 = Vector3(1, resolution[1]/resolution[0], 0) x1 = Vector3(-1, resolution[1]/resolution[0], 0) x4 = Vector3(1, -resolution[1]/resolution[0], 0) x3 = Vector3(-1, -resolution[1]/resolution[0], 0) # Pool is used for conducting multiple raycasts simultaneously # adjust the '12' according to how much processing power you are willing to devote to the render p = Pool(12) # generate list of commands to execute in parallel arglist = [] for y in range(0, resolution[1]): for x in range(0, resolution[0]): arglist.append([x, y, x1, x2, x3, x4, c, resolution, objects, lights, ambient_intensity, anti_aliasing]) results = [] for a in arglist: results.append(p.apply_async(single_ray, args=a,)) # actually execute commands p.close() p.join() results = [r.get() for r in results] #write resultant pixel data to image image = [] i = 0 for y in range(0, resolution[1]): image.append([]) for x in range(0, resolution[0]): image[y].append(results[i]) i += 1 Image.fromarray(np.uint8(np.array(image))).save('test.png')
def __init__(self, ni=5, nj=10, chordRoot=1.0, chordTip=1.0, twistRoot=0.0, twistTip=0.0, span=5.0, sweep=30.0, Sref=1.0, referencePoint=[0.0, 0.0, 0.0], wingType=1, alphaRange=[0.0]): self.size = ni * nj self.A = np.zeros((self.size, self.size)) self.rhs = np.zeros(self.size) self.inducedDownwash = [ np.zeros((self.size, self.size)), np.zeros((self.size, self.size)), np.zeros((self.size, self.size)) ] self.nw = 1 self.panels = [] self.wakePanels = [] self.ni = ni self.nj = nj self.gamma = np.zeros(self.size) self.gammaij = np.zeros(self.size) self.liftAxis = Vector3(0.0, 0.0, 1.0) self.Sref = Sref self.chordRoot = chordRoot self.chordTip = chordTip self.cavg = 0.5 * (chordRoot + chordTip) self.twistRoot = twistRoot self.twistTip = twistTip self.span = span self.sweep = sweep * pi / 180.0 self.referencePoint = Vector3(referencePoint[0], referencePoint[1], referencePoint[2]) self.wingType = wingType self.CL = [] self.CD = [] self.CM = [] self.spanLoad = [] self.alphaRange = alphaRange self.Ufree = Vector3(1.0, 0.0, 0.0) self.rho = 1.0
def __init__(self, name, filename, position=Vector3(0, 0, 0), rotation=Vector3(0, 0, 0), scale=1): self.name = name self.vertices = self.loadOBJ(filename, "vertices") self.normals = self.loadOBJ(filename, "normals") self.faces = self.loadOBJ(filename, "faces") self.rotation = rotation self.position = position self.scaleVertices(scale)
def getVerticalAngle(self, vertexPosition): verticalLookDirection = Vector3(self.topLeftDirection.x, 0, self.topLeftDirection.z) verticalVertexDirection = Vector3(vertexPosition.x - self.position.x, 0, vertexPosition.z - self.position.z) #.normalise() dotProduct = verticalLookDirection.dot(verticalVertexDirection) magnitude = verticalLookDirection.getLength( ) * verticalVertexDirection.getLength() verticalAngle = math.acos(dotProduct / magnitude) return verticalAngle
def getHorizontalAngle(self, vertexPosition): horizontalLookDirection = Vector3(self.topLeftDirection.x, self.topLeftDirection.y, 0) horizontalVertexDirection = Vector3(vertexPosition.x - self.position.x, vertexPosition.y - self.position.y, 0) #.normalise() dotProduct = horizontalLookDirection.dot(horizontalVertexDirection) magnitude = horizontalLookDirection.getLength( ) * horizontalVertexDirection.getLength() horizontalAngle = math.acos(dotProduct / magnitude) return horizontalAngle
def rotateY(self, y): for i, vertex in enumerate(self.vertexList): newVertex = Vector3(0, 0, 0) newVertex.x = vertex.x * cos(y) + vertex.z * sin(y) newVertex.y = vertex.y newVertex.z = -vertex.x * sin(y) + vertex.z * cos(y) self.vertexList[i] = newVertex
def rotateZ(self, z): for i, vertex in enumerate(self.vertexList): newVertex = Vector3(0, 0, 0) newVertex.x = vertex.x newVertex.y = vertex.y * cos(z) - vertex.z * sin(z) newVertex.z = vertex.y * sin(z) + vertex.z * cos(z) self.vertexList[i] = newVertex
def __init__(self, game_object): super(MeshComponent, self).__init__(game_object) self.points = [] self.triangles = {} self.color = Vector3(random() * 255, random() * 255, random() * 255)
def computeForcesAndMoment(self): self.CL.append(0.0) self.CM.append(0.0) self.CD.append(0.0) inducedDownwashX = np.dot(self.inducedDownwash[0], self.gamma) inducedDownwashY = np.dot(self.inducedDownwash[1], self.gamma) inducedDownwashZ = np.dot(self.inducedDownwash[2], self.gamma) for index, panel in enumerate(self.panels): force = self.Ufree.crossProduct( panel.dl()) * self.rho * self.gammaij[index] distToRefrence = self.referencePoint - panel.forceActingPoint() moment = force.crossProduct(distToRefrence) downWash = Vector3(inducedDownwashX[index], inducedDownwashY[index], inducedDownwashZ[index]) self.CL[-1] += force.dot(self.liftAxis) self.CM[-1] += moment[1] self.CD[-1] -= self.rho * downWash.dot( self.liftAxis) * self.gammaij[index] * panel.dy() self.CL[-1] /= (0.5 * self.rho * self.Ufree.Magnitude()**2 * self.Sref) self.CD[-1] /= (0.5 * self.rho * self.Ufree.Magnitude()**2 * self.Sref) self.CM[-1] /= (0.5 * self.rho * self.Ufree.Magnitude()**2 * self.Sref * self.cavg)
def translate_vertexes(vertexes, translation): new_vertexes = [] for v in vertexes: new_vertexes.append( Vector3(v[0] + translation[0], v[1] + translation[1], v[2] + translation[2])) return new_vertexes
def rotateX(self, x): for i, vertex in enumerate(self.vertexList): newVertex = Vector3(0, 0, 0) newVertex.x = vertex.x * cos(x) - vertex.y * sin(x) newVertex.y = vertex.x * sin(x) + vertex.y * cos(x) newVertex.z = vertex.z self.vertexList[i] = newVertex
def drawBline(self, point0, point1, color): x0 = int(point0.x) y0 = int(point0.y) x1 = int(point1.x) y1 = int(point1.y) dx = abs(x1 - x0) dy = abs(y1 - y0) if (x0 < x1): sx = 1 else: sx = -1 if y0 < y1: sy = 1 else: sy = -1 err = dx - dy while x0 != x1 or y0 != y1: self.putPixel(Vector3(x0, y0, 0), color) e2 = 2 * err if e2 > -dy: err -= dy x0 += sx elif e2 < dx: err += dx y0 += sy
def scale_vertexes(vertexes, scale_factor): print(vertexes[0]) new_vertexes = [] for v in vertexes: new_vertexes.append( Vector3(v[0] * scale_factor[0], v[1] * scale_factor[1], v[2] * scale_factor[2])) return new_vertexes
def rotate(self, x): newVertex = Vector3(0, 0, 0) newVertex.x = self.lookDirection.x * cos( x) - self.lookDirection.y * sin(x) newVertex.y = self.lookDirection.x * sin( x) + self.lookDirection.y * cos(x) newVertex.z = self.lookDirection.z self.lookDirection.copyFrom(newVertex)
def generateVertices(self): self.vertexList = list() positionalModifiers = (Vector3(1, 1, 1), Vector3(1, 1, -1), Vector3(1, -1, 1), Vector3(1, -1, -1), Vector3(-1, 1, 1), Vector3(-1, 1, -1), Vector3(-1, -1, 1), Vector3(-1, -1, -1)) for positionalModifier in positionalModifiers: newVertex = self.position + (positionalModifier * (self.sideLength / 2.0)) self.vertexList.append(newVertex)
def transpose_points(self): result = [] for point in self.points: new_point = Vector3.rotate_y(point, self.game_object.transform.rotation.y) new_point = (new_point * self.game_object.transform.scale) + self.game_object.transform.position result.append(new_point) return result
def __init__(self, position): self.position = position self.lookDirection = Vector3(1, 0, 0) self.aspectRatio = 16 / 9 self.horizontalFOV = math.pi #0.5 * math.pi self.verticalFOV = self.horizontalFOV / self.aspectRatio self.objectList = list() self.projectedVertexList = list()
def createCube(cubeList, cam, colours, rotSpeeds): x = uniform(-3, 3) y = uniform(-3, 3) z = uniform(-5, 0) sideLength = uniform(0.5, 2) cube = Cube(Vector3(x, y, z), sideLength) rotSpeeds.append([uniform(-0.05, 0.05), uniform(-0.05, 0.05), uniform(-0.05, 0.05)]) colours.append([randint(100, 255), randint(100, 255), randint(100, 255)]) cubeList.append(cube) cam.addObject(cube)
def initializeWingCosine(self): theta_i = np.linspace(0.5 * np.pi, np.pi, self.nj + 1) y_i = -self.span * np.cos(theta_i) dy = self.span / float(self.nj) for j in range(self.nj): y = y_i[j] yNext = y_i[j + 1] eta = y / self.span etaNext = yNext / self.span twist = (1.0 - eta) * self.twistRoot + eta * self.twistTip twistNext = (1.0 - etaNext) * self.twistRoot + etaNext * self.twistTip chord = Vector3((1.0 - eta) * self.chordRoot + eta * self.chordTip, 0.0, 0.0).rotate(0.0, twist, 0.0) chordNext = Vector3( (1.0 - etaNext) * self.chordRoot + etaNext * self.chordTip, 0.0, 0.0).rotate(0.0, twistNext, 0.0) pt = Vector3(tan(self.sweep) * y, y, 0.0) ptNext = Vector3(tan(self.sweep) * yNext, yNext, 0.0) ds = chord / float(self.ni) dsNext = chordNext / float(self.ni) for i in range(self.ni): p1 = pt p4 = ptNext pt = pt + ds ptNext += dsNext p2 = pt p3 = ptNext self.panels.append(panel(p1, p2, p3, p4))
def preformCollision(self, ray, distance): normal = (ray.rot * distance) - self.pos pos = ray.rot * distance theta = 2 * math.pi * random.uniform(0, 1) u = math.cos(math.acos(w * random.uniform(0, 1) - 1)) x = math.sqrt(1 - u ** 2) * math.cos(theta) y = math.sqrt(1 - u ** 2) * math.sin(theta) tmpDir = Vector3(x, y, u) if tmpDir.dotProduct(normal) < 0: tmpDir *= -1 #return a tuple of the new ray plus a color? Or integrate color with the ray? tmpDir.normalize() return Ray(pos, tmpDir, ray.color + material.color)
def initializeWing(self): dy = self.span / float(self.nj) y = 0.0 yNext = y + dy for j in range(self.nj): eta = y / self.span etaNext = yNext / self.span twist = (1.0 - eta) * self.twistRoot + eta * self.twistTip twistNext = (1.0 - etaNext) * self.twistRoot + etaNext * self.twistTip chord = Vector3((1.0 - eta) * self.chordRoot + eta * self.chordTip, 0.0, 0.0).rotate(0.0, twist, 0.0) chordNext = Vector3( (1.0 - etaNext) * self.chordRoot + etaNext * self.chordTip, 0.0, 0.0).rotate(0.0, twistNext, 0.0) pt = Vector3(tan(self.sweep) * y, y, 0.0) ptNext = Vector3(tan(self.sweep) * yNext, yNext, 0.0) ds = chord / float(self.ni) dsNext = chordNext / float(self.ni) for i in range(self.ni): p1 = pt p4 = ptNext pt = pt + ds ptNext += dsNext p2 = pt p3 = ptNext self.panels.append(panel(p1, p2, p3, p4)) y += dy yNext += dy
def rotate_vertexes(vertexes, angles): angles = Vector3(angles[0] * 2 * math.pi / 360, angles[1] * 2 * math.pi / 360, angles[2] * 2 * math.pi / 360) new_vertexes = [] for v in vertexes: xtheta = angles[0] newv = Vector3(v[0], (v[1] * math.cos(xtheta) - v[2] * math.sin(xtheta)), ((v[1] * math.sin(xtheta)) + (v[2] * math.cos(xtheta)))) ytheta = angles[1] newv = Vector3( (newv[0] * math.cos(ytheta) + newv[2] * math.sin(ytheta)), newv[1], ((-newv[0] * math.sin(ytheta)) + (newv[2] * math.cos(ytheta)))) ztheta = angles[2] newv = Vector3( (newv[0] * math.cos(ztheta) - newv[1] * math.sin(ztheta)), ((newv[0] * math.sin(ztheta)) + (newv[1] * math.cos(ztheta))), newv[2]) new_vertexes.append(newv) return new_vertexes
def loadOBJ(self, filename, option=True): if option == "vertices": verts = [] elif option == "normals": norms = [] else: facesOut = [] # normsOut = [] for line in open(filename, "r"): vals = line.split() if vals[0] == "v" and option != "faces" and option != "normals": v = map(float, vals[1:4]) vector = Vector3(v[0], v[1], v[2]) verts.append(vector) elif vals[0] == "vn" and option != "vertices" and option != "faces": n = map(float, vals[1:4]) normal = Vector3(n[0], n[1], n[2]) norms.append(normal) elif vals[ 0] == "f" and option != "vertices" and option != "normals": face = [] norm = [] for f in vals[1:]: w = f.split("/") face.append(int(w[0]) - 1) norm.append(int(w[2]) - 1) facesOut.append([[face[0], face[1], face[2]], [norm[0], norm[1], norm[2]]]) # return vertsOut, normsOut if option == "vertices": return verts elif option == "normals": return norms else: return facesOut
def render(self, scene): # Render the mesh points. cam = scene.get_camera() points = self.transpose_points() # Cast every point to a cameras' screen. for point in points: point_vector = point - cam.transform.position point_rad = Vector3.dot_relative(point_vector.normalize(), cam.direction) # Assume projection 1:1 ratio. cam_rad = cam.fov_rad point_x = (point_rad.y + cam_rad / 2.0) / cam_rad point_y = (point_rad.x + cam_rad / 2.0) / cam_rad scene.render_point(point_x, point_y) pass
def project(self, vector, aspectRatio, zNear, zFar, fov_degree): if (aspectRatio > 1): sX = 1/aspectRatio else: sX = 1 if (aspectRatio > 1): sY = 1 else: sY = aspectRatio fov = 1/math.tan(math.radians(fov_degree/2)) scaleX = fov * sX scaleY = fov * sY projectionMatrix = self.matrix.get_projection_matrix(zNear, zFar, scaleX, scaleY) projectedVector = Vector4(vector.x, vector.y, vector.z, 1).dot_product_with_matrix(projectionMatrix) return Vector3(projectedVector[0] + self.width/2, projectedVector[1]+ self.height/2, projectedVector[2])
def main(x, y, z, a, b, c): rospy.init_node('init1', anonymous=True) now = rospy.get_rostime() rospy.loginfo("Current time %i %i", now.secs, now.nsecs) pub1 = rospy.Publisher('/firefly/command/trajectory', MultiDOFJointTrajectory, queue_size=100) # initial position of the first pelican trajectory1 = MultiDOFJointTrajectory() trajectory1_point = MultiDOFJointTrajectoryPoint() trajectory1.header.frame_id = 'firefly/base_link' transform1 = Transform() #transform1.translation.x = 0 #transform1.translation.y = 0 #transform1.translation.z = 4 transform1.translation = Vector3(x, y, z) q_rot = quaternion_from_euler(a, b, c) transform1.rotation.x = q_rot[0] transform1.rotation.y = q_rot[1] transform1.rotation.z = q_rot[2] transform1.rotation.w = q_rot[3] velocity1 = Twist() accelerate1 = Twist() t = rospy.Time.now() trajectory1.header.stamp.secs = t.secs trajectory1.header.stamp.nsecs = t.nsecs trajectory1_point.transforms.append(transform1) trajectory1_point.velocities.append(velocity1) trajectory1_point.accelerations.append(accelerate1) trajectory1.points.append(trajectory1_point) # publish the related messages rate = rospy.Rate(100) while not rospy.is_shutdown(): pub1.publish(trajectory1) rate.sleep()
def render(): # spheres.append(Sphere(Vector3( 7, 5, -18), 4, Vector3(80, 120, 60))) # lights.append(Light(Vector3(-20, 20, 20), 50)) # for j in range(height): # for i in range(width): # for k in range(len(spheres)): # x, y, z = buildRay(i, j) # if(intersect(cam.location, Vector3(x, y, z).Normal(), spheres[k])): #i,j,-1.0 # frameBuffer.append(spheres[k].material) # else: # frameBuffer.append(Vector3(51, 178, 204)) for j in range(height): for i in range(width): x, y, z = buildRay(i, j) frameBuffer.append( intersect(cam.location, Vector3(x, y, z).Normal(), spheres)) #i,j,-1. body = bodyFormat(frameBuffer, width) createFile(header, body)
def drawScanLine(self, pointA, pointB, y, sz, ez, sShade, eShade, color): if pointA > pointB: temp = pointA pointA = pointB pointB = temp z_slope = (ez - sz)/(pointB - pointA) shadingGradient = (eShade - sShade)/(pointB - pointA) for x in range(int(pointA), int(pointB)): if x > self.width: return if y > self.height: return color *= sShade color = self.clamp(color, 0, 255) self.putPixel(Vector3(x, y, sz), (color, color, color)) sz += z_slope sShade += shadingGradient
p.join() results = [r.get() for r in results] #write resultant pixel data to image image = [] i = 0 for y in range(0, resolution[1]): image.append([]) for x in range(0, resolution[0]): image[y].append(results[i]) i += 1 Image.fromarray(np.uint8(np.array(image))).save('test.png') if __name__ == '__main__': t= time.time() # camera location c = Vector3(0, 0, -1) # CHANGE THINGS AFTER THIS POINT # setup code which is used for renders # all of this is adjustable depending on what you want to render # blue and red test materials, with different shininesses m = Material(Color(0.6, 0.1, 0.1), Color(0.6, 0.1, 0.1), Color(0.3, 0.3, 0.3), 2, Color(0.3, 0.3, 0.3)) m2 = Material(Color(0.1, 0.1, 0.6), Color(0.1, 0.1, 0.6), Color(0.3, 0.3, 0.3), 2, Color(0.3, 0.3, 0.3)) # mirror material, high reflectivity, low diffuse constant m3 = Material(Color(0.1, 0.1,0.1), Color(0.1,0.1,0.1), Color(0.2, 0.2, 0.2), 2, Color(0.7, 0.7, 0.7)) # glass material, refracts, index of refraction is 1.5 m4 = Material(Color(0.6, 0.1, 0.1), Color(0.6, 0.1, 0.1), Color(0.3, 0.3, 0.3), 2, Color(0.3, 0.3, 0.3), True, 1.5) # objects in the scene #objects = [Sphere(Vector3(0, 0, 8), 3, m)]
#!/usr/bin/env python3 # Test of Vector3 class from Vector3 import Vector3 v = Vector3() v[0] = 1.0 v[1] = 2.0 v[2] = 3.0 print(v[0], v[1], v[2]) print(v) v1 = Vector3(1.1, 2.2, 3.3) print(v1) v2 = Vector3(1, 2) print(v2) v2 = Vector3(1) print(v2)
def __init__(self, rad, xh, yh, zh): """ Constructor """ Vector3.__init__(self, xh, yh, zh) self.radius = rad
def __init__(self, new_x, new_y, new_z): ''' Constructor ''' Vector3.__init__(self, new_x, new_y, new_z)