def init_particles(num, sphp, domain, surface): particles = [] p1 = Vec([.5, 2.]) * sphp.sim_scale particles += [ Particle(p1, sphp, [0,0,255], surface) ] pmin = Vec([.5, .5]) pmax = Vec([2., 3.]) ps = addRect_old(num, pmin, pmax, sphp) for p in ps: particles += [ Particle(p, sphp, [255,0,0], surface) ] """ p2 = Vec([400., 400.]) * sphp.sim_scale p3 = Vec([415., 400.]) * sphp.sim_scale p4 = Vec([400., 415.]) * sphp.sim_scale p5 = Vec([415., 415.]) * sphp.sim_scale p6 = Vec([430., 430.]) * sphp.sim_scale particles += [ Particle(p1, sphp, [255,0,0], surface) ] particles += [ Particle(p2, sphp, [0,0,255], surface) ] particles += [ Particle(p3, sphp, [0,205,0], surface) ] particles += [ Particle(p4, sphp, [0,205,205], surface) ] particles += [ Particle(p5, sphp, [0,205,205], surface) ] particles += [ Particle(p6, sphp, [0,205,205], surface) ] """ return particles
def subdivide(self): self.subdivision = [] center = self.direction # vector defining the plane plane1 = Vec(-self.direction.y / self.direction.x, 1, 0) plane2 = Vec(-self.direction.z / self.direction.x, 0, -1) plane1 /= plane1.length() plane2 /= plane2.length() r = range(-self.SUB_COUNT/2, self.SUB_COUNT/2) size = float(self.SUB_COUNT) for x in r: if x % 10 == 0: print "\r%s%%" % int((x + size/2) / size * 100), sys.stdout.flush() for y in r: # the position on the plane pos = ((plane1 * x) + (plane2 * y)) / size # the vector pointing to the point on the grid res = center + pos # normalize res /= res.length() self.subdivision.append(self.trace(res))
def __init__(self, pos, np, system, color, surface): #physics stuff #position self.pos = pos #north pole (vector with origin at position) #self.np = np #south pole (vector with origin at position) #self.sp = -1 * np #self.r = system.radius self.h = system.smoothing_radius self.scale = system.sim_scale self.mass = system.mass self.dens = system.rho0 self.force = Vec([0., 0.]) self.vel = Vec([0., 0.]) self.veleval = Vec([0., 0.]) #lock a particle in place (force updates don't affect it) self.lock = False #pygame stuff self.col = color self.surface = surface self.screen_scale = self.surface.get_width() / system.domain.width
def get_input(): global mouse_down, mouse_old, translate, rotate key = pygame.key.get_pressed() #print key trans = 2.0 for event in pygame.event.get(): if event.type == QUIT or key[K_ESCAPE] or key[K_q]: print "quit!" pygame.quit(); sys.exit() elif event.type == MOUSEBUTTONDOWN: print "MOUSE DOWN" mouse_down = True mouse_old = Vec([event.pos[0]*1., event.pos[1]*1.]) elif event.type == MOUSEMOTION: if(mouse_down): print "MOUSE MOTION" m = Vec([event.pos[0]*1., event.pos[1]*1.]) dx = m.x - mouse_old.x dy = m.y - mouse_old.y button1, button2, button3 = pygame.mouse.get_pressed() if button1: rotate.x += dy * .2 rotate.y += dx * .2 elif button3: translate .z -= dy * .01 mouse_old = m print "rotate", rotate, "translate", translate elif event.type == MOUSEBUTTONUP: print "MOUSE UP" mouse_down = False elif key[K_w]: translate.z += .1*trans #y is z and z is y elif key[K_s]: translate.z -= .1*trans elif key[K_a]: translate.x += .1*trans elif key[K_d]: translate.x -= .1*trans glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(initrans.x, initrans.y, initrans.z) #glTranslatef(-10, -10, -30) #glRotatef(-90, 1, 0, 0) glRotatef(rotate.x, 1, 0, 0) glRotatef(rotate.y, 0, 1, 0) #we switched around the axis so make this rotate_z glTranslatef(translate.x, translate.y, translate.z)
def targetPrey(predator, boids): if predator.currHunger <= PredatorBehavior.maxKillTimeout: return Vec() closestBoid = None closestBoidDistance = None preyVec = Vec() for boid in boids: distance = predator.position.distanceTo(boid.position) if distance < closestBoidDistance or closestBoidDistance is None: closestBoidDistance = distance closestBoid = boid if closestBoid is not None: preyVec = closestBoid.position.subVec(predator.position) preyVec = preyVec.setMag(PredatorBehavior.maxVelocity) preyVec = preyVec.subVec(predator.velocity) preyVec = preyVec.limit(PredatorBehavior.maxForce) return preyVec
def calc_cell(self, v): """Calculate the grid cell from a vertex""" vv = (v - self.min)*self.delta ii = Vec([0,0,0]) ii.x = int(vv.x) ii.y = int(vv.y) ii.z = int(vv.z) return ii
def calc_cell(self, v): """Calculate the grid cell from a vertex""" vv = (v - self.min) * self.delta ii = Vec([0, 0, 0]) ii.x = int(vv.x) ii.y = int(vv.y) ii.z = int(vv.z) return ii
def __init__(self, queue, *args, **kwargs): self.queue = queue #for communication from other threads #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([-85., 0., 80.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -2.]) self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Chaotic Artist") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) #this will poll for new events in the multiprocessing queue glutIdleFunc(self.poll) #setup OpenGL scene self.glinit() #set up initial conditions (pos_vbo, col_vbo, time, props) = initialize.ca(ntracers) #create our OpenCL instance #self.cle = part2.Part2(num, dt, "part2.cl") self.cle = cartist.ChaoticArtist(ntracers, dt=dt, dlife=dlife, A=.1, B=.3, F=220, oomph=.001) self.cle.loadData(pos_vbo, col_vbo, time, props) self.t = t self.x = x self.y = y self.z = z #newp = numpy.array([.25, .25, 0., 1.], dtype=numpy.float32) #print "newp", newp #self.cle.execute(newp, self.t) glutMainLoop()
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) #self.initrans = Vec([0., 0., -2.]) self.init_persp_trans = Vec([-.5, 0., -1.5]) self.init_ortho_trans = Vec([0., 0., 0.]) self.init_persp_rotate = Vec([0., 0., 0.]) self.init_ortho_rotate = Vec([90., -90., 0.]) self.ortho = False self.choice = 2 #self.stable = True self.stable = False #self.type = "square" self.wtype = "sin" #self.wtype = "sawtooth" #self.wtype = "sweep_poly" self.dt = dt self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Part 2: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) glViewport(0, 0, self.width, self.height) #setup OpenGL scene self.glprojection() #set up initial conditions self.init_wave(self.dt, dx, ntracers, True) #create our OpenCL instance #self.cle = part2.Part2(num, dt, "part2.cl") self.cle = wave.Wave(self.dt, dx, ntracers, self.params) self.cle.loadData(self.pos_vbo, self.col_vbo) self.cle.execute(subintervals) glutMainLoop()
def orthovec(u): """return arbitrary orthogonal vectors to u""" v = Vec([1., -u.x/u.y, 0.]) b = 1. a = b*u.x/u.y c = -b*(u.x**2 + u.y**2)/(u.y*u.z) w = Vec([a, b, c]) print "u dot v", numpy.dot(u, v) print "w dot v", numpy.dot(v, w) print "w dot u", numpy.dot(u, w) return normalize(v), normalize(w)
def __init__(self, cle, *args, **kwargs): window.Window.__init__(self, *args, **kwargs) #glutil.init(self.width, self.height) self.cle = cle self.num = num #mouse handling for transforming scene self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -2.])
def __init__(self, pos): # Seriously less complicated self.position = pos self.velocity = Vec() self.deltaVel = Vec() # If hunger reaches a threshold the predator will go on # a hunt. self.currHunger = 0 PredatorBoid.color = (255, 0, 0)
def __init__(self, pos, sphp, color, surface): #physics stuff self.pos = pos self.h = sphp.smoothing_radius self.scale = sphp.sim_scale self.mass = sphp.mass self.vel = Vec([0.,0.]) self.veleval = Vec([0.,0.]) #pygame stuff self.col = color self.surface = surface self.screen_scale = self.surface.get_width() / sphp.domain.width
def __init__(self, pos, chr_1, chr_2): self.ID = None # Spatial vars # Position defines the Boid's position in the habitat self.position = pos # Same, for velocity self.velocity = Vec() # deltaVel is used for velocity change (acceleration) # when moving the boid self.deltaVel = Vec() # Genetic vars # Chromosome one and two. self.chromosome_1 = chr_1 self.chromosome_2 = chr_2 # Gene expression: the phenotypes controlled by the genes manifest # themselves as the mean value of the two alleles. self.phenotypes = {} for key, val in self.chromosome_1.genes.iteritems(): self.phenotypes[key] = ( self.chromosome_1.getExpressedWeight(key) + self.chromosome_2.getExpressedWeight(key)) / 2.0 self.color = [] for col in ['red', 'green', 'blue']: colval = int(self.phenotypes[col]) * 50 # A color value outside 0-255 would break the program: if colval > 255: colval = 255 elif colval < 0: colval = 0 self.color.append(colval) # Nbr of collissions the boid is guilty of and # confusion timer self.collisions = 0 self.dazedTimer = 0
def draw(): glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) #glLoadIdentity() #glTranslatef(-10.0, -10.0, -36.0) #glTranslatef(0.,0.,-6.) gl.draw_axes() glColor3f(1,1,1) glPointSize(5) #glBegin(GL_POINTS) #glVertex3f(0,0,0) #glVertex3f(1,1,1) #glVertex3f(0, 1, 0) #glEnd() #origin o = Vec([0.,0.,0.]) #direction u = normalize(Vec([1., 1., 1.])) #orthogonal vec v,w = orthovec(u) #w = rotateaxis(u, v, 90) #print u #print v #print w glColor3f(.5, 1, 0) gl.draw_line(o, u) glColor3f(0, 1, .5) gl.draw_line(o, v) glColor3f(.5, 0, .5) gl.draw_line(o, w) particles = distribute_disc(u, v, w, 1, 300, .1) print len(particles) glBegin(GL_POINTS) glColor3f(1, 1, 1) glVertex3f(u.x, u.y, u.z) glColor3f(.5, .5, .5) for p in particles: glVertex3f(p.x, p.y, p.z) glEnd() pygame.display.flip()
def generate(self): self.fields = [] seed = id(self) gen_size = Size(self.size, self.size) map = NoiseMap(gen_size, seed) map.generate_noise(map.sinussinus_noise) for i in range(10): map2 = NoiseMap(gen_size, seed * i) map2.generate_noise(map2.sinussinus_noise) if i % 2: map2.reverse() map = map + map2 map.for_every(abs) map.soft_focus() map.normalize() map.equalize_range(7, 10, 9) map.equalize_range(0, 6, 0) map.equalize_range(6, 8, 9) map.dualize() for y, line in enumerate(map.map): for x, value in enumerate(line): ground_type = GROUNDS['DIRT'] if value: ground_type = GROUNDS['WATER'] self.fields.append(Field(ground_type, Vec((x, y))))
def generatePoint(radius=200, mu=0, sigma=25): r = np.random.rand() * (2 * math.pi * 2 / 4) - ( 2 * math.pi * 1 / 4) # Rotation somewhere between -.5pi and .5pi p = Vec(0, -radius).rotate(r) + sampleFromNormal2D( sigma=sigma ) # Rotate vector, add random offset sampled from normal distribution return p
def lineLineIntersection(a1, b1, c1, a2, b2, c2): determinant = a1 * b2 - a2 * b1 if determinant == 0: print("[lineLineIntersection] Lines not intersecting!") return None return Vec((b2 * c1 - b1 * c2) / determinant, (a1 * c2 - a2 * c1) / determinant)
def addRect_old(num, pmin, pmax, sphp): #Create a rectangle with at most num particles in it. The size of the return #vector will be the actual number of particles used to fill the rectangle print "**** addRect ****" print "rest dist:", sphp.rest_distance print "sim_scale:", sphp.sim_scale spacing = 1.0 * sphp.rest_distance / sphp.sim_scale; print "spacing", spacing xmin = pmin.x# * scale xmax = pmax.x# * scale ymin = pmin.y# * scale ymax = pmax.y# * scale print "min, max", xmin, xmax, ymin, ymax rvec = []; i=0; for y in np.arange(ymin, ymax, spacing): for x in np.arange(xmin, xmax, spacing): if i >= num: break print "x, y", x, y rvec += [ Vec([x,y]) * sphp.sim_scale]; #rvec += [[x, y, 0., 1.]] i+=1; print "%d particles added" % i #rvecnp = np.array(rvec, dtype=np.float32) #return rvecnp; return rvec
def separatePredator(predator, predators): sepV = Vec() for otherPredator in predators: if predator is otherPredator: continue difference = predator.position.subVec(otherPredator.position) distance = difference.getMag() if distance < PredatorBehavior.minDistance: difference = difference.normalized() difference = difference.divScalar(distance) sepV = sepV.addVec(difference) if sepV.getMag() > 0: sepV = sepV.setMag(PredatorBehavior.maxVelocity) sepV = sepV.subVec(predator.velocity) sepV = sepV.limit(PredatorBehavior.maxForce) return sepV
def mousePressEvent(self, e): self.setFocus() print('<MousePressEvent: button:{},x:{},y:{}>'.format( e.button(), e.x(), e.y())) logic_pos = Vec(((e.x() - self.zoom) / (self.zoom * 2), (e.y() - self.zoom) / (self.zoom * 2))) #selection old_selection = self.selected() if e.button() == 2: self.selected_planet = None self.selected_target_planet = None else: for planet in self.game.planetmap.to_list(): if abs(logic_pos - planet.pos) < 0.75: if self.selected_planet and not self.selected_target_planet: if self.selected_planet != planet: self.selected_target_planet = planet elif self.selected_target_planet: self.selected_planet = None self.selected_target_planet = None else: if planet.owner == self.game.get_current_player(): self.selected_planet = planet break new_selection = self.selected() if old_selection != new_selection and self.on_selected_func: self.on_selected_func(new_selection) self.repaint()
def bowyerWatson(points): # https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm # print("Running bowyerWatson on %d points" % len(points)) triangulation = [] # must be large enough to completely contain all the points in pointList P1 = Vec(-1e15, -1e15) P2 = Vec(1e15, -1e15) P3 = Vec(0, 1e15) megaTriangle = Triangle(P1, P2, P3) triangulation.append(megaTriangle) # add all the points one at a time to the triangulation for iP, P in enumerate(points): badTriangles = [] # first find all the triangles that are no longer valid due to the insertion for iT, T in enumerate(triangulation): if distance(P, T.C) < T.R: # If point inside triangle circumcircle badTriangles.append(T) # Triangle is bad # find the boundary of the polygonal hole polygon = [] for T in badTriangles: for V in T.vertices: # for each edge in triangle # if edge is not shared by any other triangles in badTriangles if not any([_T.hasVertex(V) for _T in badTriangles if T != _T]): polygon.append(V) for T in badTriangles: triangulation.remove(T) # re-triangulate the polygonal hole for v1, v2 in polygon: triangulation.append(Triangle(P, v1, v2)) # if triangle contains a vertex from original super-triangle triangulation = [ T for T in triangulation if not T.sharesCornerWith(megaTriangle) ] return triangulation #######################################
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -2.]) self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Part 2: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) #setup OpenGL scene self.glinit() #create our OpenCL instance self.kin = kinect.Kinect() self.cle = kinect.CL() self.cle.loadData(self.kin.pos_vbo, self.kin.col_vbo) #testing #rgb, depth = self.kin.get_particles() #self.cle.load_images(rgb, depth) #self.cle.execute(1) glutMainLoop()
def __init__(self, pos, velocity, radius): super().__init__() # pygame attributes used by group.draw self.image = pygame.Surface([radius*2, radius*2]) self.image.set_colorkey(BG_COLOR) self.rect = self.image.get_rect() self.position = pos self.velocity = Vec(*velocity) self.radius = radius
def rotateaxis(u,v,theta): """rotate v about u by angle theta (in degrees)""" theta *= numpy.pi/180. #matrix gotten from http://www.fastgraph.com/makegames/3drotation/ and originally from Graphics Gems 1990 s = sin(theta) c = cos(theta) t = 1. - cos(theta) x = u.x y = u.y z = u.z R = numpy.array([[t*x**2 + c, t*x*y - s*z, t*x*z + s*y, 0.], [t*x*y + s*z, t*y**2 + c, t*y*z - s*x, 0.], [t*x*z - s*y, t*y*z + s*x, t*z**2 + c, 0.], [0., 0., 0., 1.]]) v = Vec([v.x, v.y, v.z, 1.]) r = Vec(numpy.dot(R, v)) v = normalize(Vec([r.x, r.y, r.z])) return v
def __init__(self, data): self.START = self.previous = self.location = Vec((0, 0)) self.END = None self.map = {self.START: START} self.G = nx.Graph() self.stack = [] self.G.add_node(self.START) self.brain = Computer(int_code=data) self.computation = self.brain.compute_iter() self.display = Display()
def vec_from_center(self, theta, size=False): """ Return a relative position on a cirle of radius=size, center=relatice center of surface with angle theta starting from the nose up position """ size = size or self.radius rad = math.radians(theta - 90 % 360) return Vec( self.radius + size*math.cos(rad), self.radius + size*math.sin(rad) )
def collision_wall(sphp, domain, particles): dmin = domain.bnd_min * sphp.sim_scale dmax = domain.bnd_max * sphp.sim_scale bnd_dist = sphp.boundary_distance #float diff = params->boundary_distance - (p.z - gp->bnd_min.z); #if (diff > params->EPSILON) #r_f += calculateRepulsionForce(normal, v, params->boundary_stiffness, params->boundary_dampening, diff); #f_f += calculateFrictionForce(v, f, normal, friction_kinetic, friction_static_limit); for pi in particles: f = Vec([0.,0.]) p = pi.pos #X Min diff = bnd_dist - (p.x - dmin.x) if diff > 0: normal = Vec([1.,0.]) f += calcRepulsionForce(normal, pi.vel, sphp, diff) #calcFrictionForce(pi.v, pi.f, normal, friction_kinetic, friction_static_limit) #X Max diff = bnd_dist - (dmax.x - p.x) if diff > 0: normal = Vec([-1.,0.]) f += calcRepulsionForce(normal, pi.vel, sphp, diff) #calcFrictionForce(pi.v, pi.f, normal, friction_kinetic, friction_static_limit) #Y Min diff = bnd_dist - (p.y - dmin.y) if diff > 0: normal = Vec([0.,1.]) f += calcRepulsionForce(normal, pi.vel, sphp, diff) #calcFrictionForce(pi.v, pi.f, normal, friction_kinetic, friction_static_limit) #Y Max diff = bnd_dist - (dmax.y - p.y) if diff > 0: normal = Vec([0.,-1.]) f += calcRepulsionForce(normal, pi.vel, sphp, diff) #calcFrictionForce(pi.v, pi.f, normal, friction_kinetic, friction_static_limit) #print "collision force", f pi.force += f
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -2.]) self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Part 2: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) #setup OpenGL scene self.glinit() #set up initial conditions (pos_vbo, col_vbo, params) = initialize.wave(dt, dx, ntracers) #create our OpenCL instance #self.cle = part2.Part2(num, dt, "part2.cl") self.cle = wave.Wave(dt, dx, ntracers, params) self.cle.loadData(pos_vbo, col_vbo) self.cle.execute(subintervals) glutMainLoop()
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -200.]) self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Part 2: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) self.dim = 300 #setup OpenGL scene self.glinit() #set up initial conditions (pos_vbo, col_vbo, vel, acc, num) = initialize.boids(max_num) #create our OpenCL instance self.boids = boids.Boids(num, dt, self.dim) self.boids.loadData(pos_vbo, col_vbo, vel, acc) glutMainLoop()
def force_update(sphp, particles): #brute force rho0 = sphp.rho0 K = sphp.K for pi in particles: pi.force = Vec([0., 0.]) pi.xsph = Vec([0., 0.]) di = pi.dens #print "di", di Pi = K * (di - rho0) #print "Pi", Pi #print "pi.h", pi.h for pj in particles: if pj == pi: continue r = pi.pos - pj.pos #temporary optimization until we do efficient neighbor search if mag(r) > pi.h: continue #print "r", r dj = pj.dens Pj = K * (dj - rho0) #print "dWspiky", dWspiky(pi.h, r) #kern = .5 * (Pi + Pj) * dWspiky(pi.h, r) kern = .5 * (Pi + Pj) * sphp.kernels.dspiky(r) f = r * kern #does not account for variable mass f *= pi.mass / (di * dj) #print "force", f pi.force += f #XSPH #float4 xsph = (2.f * sphp->mass * Wijpol6 * (velj-veli)/(di.x+dj.x)); xsph = pj.veleval - pi.veleval xsph *= 2. * pi.mass * sphp.kernels.poly6(r) / (di + dj) pi.xsph += xsph
def setup(self, cell_size): #we create 2 cells of padding around the bounds s2 = 2. * cell_size self.min = self.bnd_min - Vec([s2, s2, s2]) self.max = self.bnd_max + Vec([s2, s2, s2]) self.size = self.max - self.min self.res = Vec([ math.ceil(self.size.x / cell_size), math.ceil(self.size.y / cell_size), math.ceil(self.size.z / cell_size) ]) self.size = self.res * cell_size self.max = self.min + self.size self.delta = Vec([ self.res.x / self.size.x, self.res.y / self.size.y, self.res.z / self.size.z ]) self.nb_cells = int(self.res.x * self.res.y * self.res.z)
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([90., 90., 0.]) self.translate = Vec([0., 0., 0.]) self.initrans = Vec([0., 0., -20.]) self.width = 1024 self.height = 768 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("The qMD Model") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) #setup OpenGL scene self.glinit() #set up initial conditions (pos_vbo, col_vbo, vel) = initialize.fountain(maxnum) num = len(vel) #create our OpenCL instance self.cle = physics.Particles(num, dt) self.cle.loadData(pos_vbo, col_vbo, vel) glutMainLoop()
class window(object): def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) #self.initrans = Vec([0., 0., -2.]) self.init_persp_trans = Vec([-.5, 0., -1.5]) self.init_ortho_trans = Vec([0., 0., 0.]) self.init_persp_rotate = Vec([0., 0., 0.]) self.init_ortho_rotate = Vec([90., -90., 0.]) self.ortho = False self.choice = 2 #self.stable = True self.stable = False #self.type = "square" self.wtype = "sin" #self.wtype = "sawtooth" #self.wtype = "sweep_poly" self.dt = dt self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("Part 2: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) glViewport(0, 0, self.width, self.height) #setup OpenGL scene self.glprojection() #set up initial conditions self.init_wave(self.dt, dx, ntracers, True) #create our OpenCL instance #self.cle = part2.Part2(num, dt, "part2.cl") self.cle = wave.Wave(self.dt, dx, ntracers, self.params) self.cle.loadData(self.pos_vbo, self.col_vbo) self.cle.execute(subintervals) glutMainLoop() def set_params(self): if self.choice == 1: #linear if not self.stable: c = 1 #unstable else: c = 10. #stable param = c ymin = -150. ymax = 150. elif self.choice == 2: #quadratic if not self.stable: #unstable for quadratic beta = .016568 else: beta = .0016568 #stable param = beta ymin = -12. ymax = 12. elif self.choice == 3: #cubic if not self.stable: #gamma = .509 gamma = .0509 #unstable else: gamma = .00509 #stable param = gamma ymin = -1. ymax = 1. self.params = (self.num, self.choice, param, ymin, ymax, self.dt) print "Parameters: ======================" if self.choice == 1: print "Linear Wave Equation" if self.choice == 2: print "Quadratic Wave Equation" if self.choice == 3: print "Cubic Wave Equation" if self.stable: print "Stability: Stable" else: print "Stability: Unstable" print "%s wave" % self.wtype print "Timestep: ", self.dt print "==================================" def init_wave(self, dt, dx, numtracers, init): """Initialize position, color and velocity arrays we also make Vertex Buffer Objects for the position and color arrays""" pos, col, self.num = initialize.wave_np(self.wtype, dt, dx, numtracers) self.set_params() #print timings if init: #create the Vertex Buffer Objects from OpenGL.arrays import vbo self.pos_vbo = vbo.VBO(data=pos, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.pos_vbo.bind() self.col_vbo = vbo.VBO(data=col, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER) self.col_vbo.bind() else: self.pos_vbo.bind() self.pos_vbo.set_array(pos) self.pos_vbo.copy_data() self.col_vbo.bind() self.col_vbo.set_array(col) self.col_vbo.copy_data() self.cle.set_params(self.params) self.cle.reloadData() #return (pos_vbo, col_vbo, params) def draw(self): """Render the particles""" #TODO: # * set up Ortho2D viewing and mouse controls # * find better color mapping for height #update or particle positions by calling the OpenCL kernel self.cle.execute(subintervals) glFlush() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #handle mouse transformations #glTranslatef(self.initrans.x, self.initrans.y, self.initrans.z) glRotatef(self.rotate.x, 1, 0, 0) glRotatef(self.rotate.y, 0, 1, 0) glTranslatef(self.translate.x, self.translate.y, self.translate.z) #render the particles self.cle.render() #draw the x, y and z axis as lines glutil.draw_axes() glutSwapBuffers() def glprojection(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() if self.ortho: glOrtho(0.0, 1.0, 0.0, -1.0, -1.5, 1.5) self.translate = self.init_ortho_trans.copy() self.rotate = self.init_ortho_rotate.copy() else: gluPerspective(60., self.width / float(self.height), .1, 1000.) self.translate= self.init_persp_trans.copy() self.rotate = self.init_persp_rotate.copy() glMatrixMode(GL_MODELVIEW) ###GL CALLBACKS def timer(self, t): glutTimerFunc(t, self.timer, t) glutPostRedisplay() def on_key(self, *args): ESCAPE = '\033' if args[0] == ESCAPE or args[0] == 'q': sys.exit() elif args[0] == 't': print initialize.timings elif args[0] == 'o': self.ortho = not self.ortho if self.ortho: self.translate = self.init_ortho_trans.copy() self.rotate = self.init_ortho_rotate.copy() else: self.translate = self.init_persp_trans.copy() self.rotate = self.init_persp_rotate.copy() self.glprojection() elif args[0] == '1': self.choice = 1 self.init_wave(self.dt, dx, ntracers, False) elif args[0] == '2': self.choice = 2 self.init_wave(self.dt, dx, ntracers, False) elif args[0] == '3': self.choice = 3 self.init_wave(self.dt, dx, ntracers, False) elif args[0] == 's': self.stable = not self.stable #print "Stable parameters: ", self.stable self.set_params() self.cle.set_params(self.params) #self.init_wave(self.dt, dx, ntracers, False) elif args[0] == 'v': self.wtype = "sin" self.init_wave(self.dt, dx, ntracers, False) elif args[0] == 'b': self.wtype = "sawtooth" self.init_wave(self.dt, dx, ntracers, False) elif args[0] == 'n': self.wtype = "square" self.init_wave(self.dt, dx, ntracers, False) elif args[0] == '-': self.dt *= .1 self.set_params() self.cle.set_params(self.params) elif args[0] == '=': self.dt *= 10 self.set_params() self.cle.set_params(self.params) """ elif args[0] == 'm': self.wtype = "sweep_poly" self.init_wave(self.dt, dx, ntracers, False) """ def on_click(self, button, state, x, y): if state == GLUT_DOWN: self.mouse_down = True self.button = button else: self.mouse_down = False self.mouse_old.x = x self.mouse_old.y = y def on_mouse_motion(self, x, y): dx = x - self.mouse_old.x dy = y - self.mouse_old.y if self.mouse_down and self.button == 0: #left button self.rotate.x += dy * .2 #self.rotate.y += dx * .2 elif self.mouse_down and self.button == 2: #right button self.translate.z -= dy * .01 self.mouse_old.x = x self.mouse_old.y = y
class window(object): def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) #self.initrans = Vec([0., 0., -2.]) self.init_persp_trans = Vec([-.5, -0.5, -2.5]) self.init_ortho_trans = Vec([0., 0., 0.]) self.init_persp_rotate = Vec([0., 0., 0.]) #self.init_ortho_rotate = Vec([90., -90., 0.]) self.init_ortho_rotate = Vec([0., 0., 0.]) self.ortho = True self.dt = dt self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("SPH: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) glViewport(0, 0, self.width, self.height) #setup OpenGL scene self.glprojection() ######################################################################### #max_num = 16384 max_num = 8192 #max_num = 2**12 #4096 #max_num = 2**10 #1024 #max_num = 2**8 #256 #max_num = 2**7 #128 dmin = Vec([0,0,0]) dmax = Vec([1,1,1]) self.domain = Domain(dmin, dmax) self.system = SPH(max_num, self.domain) self.ghost_domain = Domain(dmin, dmax) self.ghost = SPH(max_num * 36, self.ghost_domain) ipos = addRect(512, Vec([0.1, 0.1, 0.,0.]), Vec([1.,1.,0.,0.]), self.system) gpos = addRect(8192, Vec([0.1, 0.1, 0.,0.]), Vec([1.,1.,0.,0.]), self.ghost) #print ipos, "LEN", len(ipos) #print gpos, "LEN", len(gpos) self.clghost_system = clsph.CLSPH(dt, self.ghost, is_ghost=True) self.clsystem = clsph.CLSPH(dt, self.system) #ipos = sph.addRect3D(50, Vec([1.2, 1.2, .2,0.]), Vec([2.,2.,1.,0.]), self.system) self.clghost_system.push_particles(gpos, None, None) #self.clghost_system.update() self.clsystem.push_particles(ipos, None, None) color = [1., 0., 0., 1.] self.clsystem.set_color(color) color = [.75, 0.75, 0.75, 1.] self.clghost_system.set_color(color) ######################################################################### print "about to start main loop" glutMainLoop() def draw(self): """Render the particles""" #TODO: # * set up Ortho2D viewing and mouse controls # * find better color mapping for height #update or particle positions by calling the OpenCL kernel for i in range(subintervals): self.clsystem.update() #self.cle.execute(subintervals) glFlush() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #handle mouse transformations #glTranslatef(self.initrans.x, self.initrans.y, self.initrans.z) glRotatef(self.rotate.x, 1, 0, 0) glRotatef(self.rotate.y, 0, 1, 0) glTranslatef(self.translate.x, self.translate.y, self.translate.z) #render the particles self.clsystem.render() self.clghost_system.render() #draw the x, y and z axis as lines glutil.draw_axes() glutSwapBuffers() def glprojection(self): glMatrixMode(GL_PROJECTION) glLoadIdentity() if self.ortho: glOrtho(-.1, 1.2, -.1, 1.2, -2.5,2.5) self.translate = self.init_ortho_trans.copy() self.rotate = self.init_ortho_rotate.copy() else: gluPerspective(60., self.width / float(self.height), .1, 1000.) self.translate= self.init_persp_trans.copy() self.rotate = self.init_persp_rotate.copy() glMatrixMode(GL_MODELVIEW) ###GL CALLBACKS def timer(self, t): glutTimerFunc(t, self.timer, t) glutPostRedisplay() def on_key(self, *args): ESCAPE = '\033' if args[0] == ESCAPE or args[0] == 'q': sys.exit() elif args[0] == 't': print initialize.timings elif args[0] == 'o': self.ortho = not self.ortho if self.ortho: self.translate = self.init_ortho_trans.copy() self.rotate = self.init_ortho_rotate.copy() else: self.translate = self.init_persp_trans.copy() self.rotate = self.init_persp_rotate.copy() self.glprojection() def on_click(self, button, state, x, y): if state == GLUT_DOWN: self.mouse_down = True self.button = button else: self.mouse_down = False self.mouse_old.x = x self.mouse_old.y = y def on_mouse_motion(self, x, y): dx = x - self.mouse_old.x dy = y - self.mouse_old.y if self.mouse_down and self.button == 0: #left button self.rotate.x += dy * .2 self.rotate.y += dx * .2 elif self.mouse_down and self.button == 2: #right button self.translate.z -= dy * .01 self.mouse_old.x = x self.mouse_old.y = y
def main(): pygame.init() screen = pygame.display.set_mode((800, 800)) pygame.display.set_caption('SPH Forces') background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) clock = pygame.time.Clock() max_num = 2**12 #4096 #max_num = 2**10 #1024 #max_num = 2**8 #256 #max_num = 2**7 #128 dmin = Vec([0,0,0]) dmax = Vec([50,50,50]) domain = Domain(dmin, dmax)#, screen) system = sph.SPH(max_num, domain) #system = magnet.Magnet(max_num, domain) #particles = sph.init_particles(5, system, domain, screen) particles = [] p1 = Vec([25, 25]) * system.sim_scale np = Vec([.8, .8]) particles += [ Particle(p1, np, system, [0,128,128], screen) ] particles[0].lock = True p = Vec([25 + 8, 25]) * system.sim_scale particles += [ Particle(p, np, system, [128,128,0], screen) ] #""" p = Vec([25, 25 + 8]) * system.sim_scale particles += [ Particle(p, np, system, [128,128,0], screen) ] p = Vec([25 - 8, 25]) * system.sim_scale particles += [ Particle(p, np, system, [128,128,0], screen) ] p = Vec([25, 25 - 8]) * system.sim_scale particles += [ Particle(p, np, system, [128,128,0], screen) ] p = Vec([25 + 8, 25 + 8]) * system.sim_scale particles += [ Particle(p, np, system, [128,128,0], screen) ] #""" print "p0.pos:", particles[0].pos mouse_down = False pause = True pi = 1 tpi = pi while 1: tpi = pi tcol = particles[pi].col[:] particles[pi].col = [0, 200, 0] clock.tick(60) key = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == QUIT or key[K_ESCAPE] or key[K_q]: print "quit!" return elif key[K_t]: print timings elif key[K_0]: pi = 0 elif key[K_1]: pi = 1 elif key[K_2]: pi = 2 elif key[K_3]: pi = 3 elif key[K_4]: pi = 4 #elif key[K_5]: # pi = 5 elif key[K_p]: pause = not pause elif event.type == MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[2]: v = Vec([event.pos[0], event.pos[1]]) v = fromscreen(v, screen) p = Particle([0,0], [0,0], system, [128,128,0], screen) p.move(v) particles += [ p ] break tcol = particles[pi].col[:] mouse_down = True elif event.type == MOUSEMOTION: if(mouse_down): v = Vec([event.pos[0], event.pos[1]]) v = fromscreen(v, screen) print v particles[pi].move(v) particles[pi].vel = Vec([0.,0.]) particles[pi].force = Vec([0.,0.]) particles[pi].angular = Vec([0.,0.]) elif event.type == MOUSEBUTTONUP: particles[pi].vel = Vec([0.,0.]) particles[pi].force = Vec([0.,0.]) particles[pi].angular = Vec([0.,0.]) mouse_down = False screen.blit(background, (0, 0)) density_update(system, particles) if not pause: for i in range(10): #magnet_update(system, particles) #density_update(system, particles) force_update(system, particles) #contact_update(system, particles) collision_wall(system, domain, particles) #euler_update(system, particles, dt) leapfrog_update(system, particles) draw_particles(particles) pygame.display.flip() particles[tpi].col = tcol[:]
def __init__(self, *args, **kwargs): #mouse handling for transforming scene self.mouse_down = False self.mouse_old = Vec([0., 0.]) self.rotate = Vec([0., 0., 0.]) self.translate = Vec([0., 0., 0.]) #self.initrans = Vec([0., 0., -2.]) self.init_persp_trans = Vec([-.5, -0.5, -2.5]) self.init_ortho_trans = Vec([0., 0., 0.]) self.init_persp_rotate = Vec([0., 0., 0.]) #self.init_ortho_rotate = Vec([90., -90., 0.]) self.init_ortho_rotate = Vec([0., 0., 0.]) self.ortho = True self.dt = dt self.width = 640 self.height = 480 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) self.win = glutCreateWindow("SPH: Python") #gets called by GLUT every frame glutDisplayFunc(self.draw) #handle user input glutKeyboardFunc(self.on_key) glutMouseFunc(self.on_click) glutMotionFunc(self.on_mouse_motion) #this will call draw every 30 ms glutTimerFunc(30, self.timer, 30) glViewport(0, 0, self.width, self.height) #setup OpenGL scene self.glprojection() ######################################################################### #max_num = 16384 max_num = 8192 #max_num = 2**12 #4096 #max_num = 2**10 #1024 #max_num = 2**8 #256 #max_num = 2**7 #128 dmin = Vec([0,0,0]) dmax = Vec([1,1,1]) self.domain = Domain(dmin, dmax) self.system = SPH(max_num, self.domain) self.ghost_domain = Domain(dmin, dmax) self.ghost = SPH(max_num * 36, self.ghost_domain) ipos = addRect(512, Vec([0.1, 0.1, 0.,0.]), Vec([1.,1.,0.,0.]), self.system) gpos = addRect(8192, Vec([0.1, 0.1, 0.,0.]), Vec([1.,1.,0.,0.]), self.ghost) #print ipos, "LEN", len(ipos) #print gpos, "LEN", len(gpos) self.clghost_system = clsph.CLSPH(dt, self.ghost, is_ghost=True) self.clsystem = clsph.CLSPH(dt, self.system) #ipos = sph.addRect3D(50, Vec([1.2, 1.2, .2,0.]), Vec([2.,2.,1.,0.]), self.system) self.clghost_system.push_particles(gpos, None, None) #self.clghost_system.update() self.clsystem.push_particles(ipos, None, None) color = [1., 0., 0., 1.] self.clsystem.set_color(color) color = [.75, 0.75, 0.75, 1.] self.clghost_system.set_color(color) ######################################################################### print "about to start main loop" glutMainLoop()