def profile(): start = Vec2D(random() * 1000, random() * 1000) #start=Vec2D(21,25) t0 = Vec2D(r=100, t=radians(random() * 360)) #t0=Vec2D(r=100,t=radians(45)) tgoal = Vec2D(r=1, t=radians(random() * 360)) end = Vec2D(random() * 1000, random() * 1000) p = PrettyPath(start, t0, -2, 2) #print("start",start.x,start.y) #print("p.start",p.start.x,p.start.y) #print("end",end.x,end.y) #p.pathpoints(5) #print("p.start",p.start.x,p.start.y) #print("p.end",p.end.x,p.end.y) #p.path_to(end,5) o = optimize(width=10, error=1, path=p, start=start, t0=t0, t1=tgoal, end=end, segs=5, bounds=10) return o
def draw(self): self.screen.fill((255, 255, 255)) fill_color = (100, 100, 100) border_color = (0, 0, 0) if not self.is_hex(): for c in self.game.grid.get_live_cells(): square_offset = (self.offset + Vec2D(*c)) \ * self.square_size \ + self.window_center coords = (square_offset.x, square_offset.y, self.square_size, self.square_size) pygame.draw.rect(self.screen, fill_color, coords, 0) pygame.draw.rect(self.screen, border_color, coords, 1) else: points = list( map( lambda i: Vec2D(math.sin(i * math.pi / 3), math.cos(i * math.pi / 3)), range(0, 6))) for c in self.game.grid.get_live_cells(): hex_center = Vec2D(c[0] + math.cos(math.pi / 3) * c[1], math.sin(math.pi / 3) * c[1]) hex_center = (hex_center + self.offset) \ * self.square_size \ + self.window_center coords = [] for p in points: coords.append( tuple(p * (self.square_size / 2) + hex_center)) pygame.draw.polygon(self.screen, fill_color, coords, 0) pygame.draw.polygon(self.screen, border_color, coords, 1) pygame.display.flip()
def parse_command(self, command): # regex = r'([0-9]+) ([_a-z]+) \(?(-?[0-9]+,? -?[0-9]+)\)?(?: (.*))?' regex = r'([A-Z]) ([_a-z]+) (-?[0-9] -?[0-9])(?: (.*))?' try: m = re.match(regex, command).groups() except AttributeError as e: raise InvalidCommand('Invalid command format') ship_id, action, coords = m[0], m[1], Vec2D.parse(m[2]) ships = [ship for ship in self.fleet if ship.id == ship_id] if len(ships) != 1: raise InvalidCommand('You don\'t own a ship with that name') if action not in Settings.RESOURSES.keys(): raise InvalidCommand('There is no such action') if action == 'fire_gun': target = coords elif action == 'torpedo': try: target = (coords, Vec2D.parse(m[3])) except TypeError: raise InvalidCommand('Invalid direction format') else: target = (coords, int(m[3] or 0)) return (ships[0], action, target)
def pathpoints(self,segs): #self.straights=0 t=Vec2D(r=self.t0.r,t=self.t0.t) delta=Vec2D() #t=self.t0 ret=[] p=Vec2D(self.start.x,self.start.y) #max dtheta! that's what we care about. c=0 #print('segs:',segs) for i in range(segs): s=_map(i,0,segs,0,1) curvature=self._cp(s) dt=curvature*(1/segs) subdiv=int(abs(dt)//MAXDTHETA)+1 #print('subdiv:',subdiv) jret=[] for j in range(subdiv): #print("i:",i," j:",j," t:",t) #print(p.x,p.y) jret.append((p,1/c if c!=0 else None,t.t)) s=_map(i+j/subdiv,0,segs,0,1) curvature=self._cp(s) dt=curvature*(1/(segs*subdiv)) #print('dt:',dt) if curvature<-MIN_C or curvature>MIN_C: pass else: curvature=0 c=curvature/t.r if curvature: #r.r=1/c #r.t=t.t delta.r=2/c*np.sin(dt/2) delta.t=t.t+dt/2 #delta.x=2/c*np.sin(dt/2)*np.cos(t.t+dt/2) #delta.y=2/c*np.sin(dt/2)*np.sin(t.t+dt/2) p.add(delta) t.rotate(dt) else: #self.straights+=1 delta=t*(1/(segs*subdiv)) p.add(delta) ret.append(jret) #print(p.x,p.y) ret.append([(p,1/c if c!=0 else None,t.t)]) #assert(len(ret)>1) self.end=p self.t1=t return(ret)
def main(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return elif event.type == pygame.MOUSEMOTION and event.dict[ 'buttons'][0]: self.offset += Vec2D( *event.dict['rel']) * (1 / self.square_size) elif event.type == pygame.MOUSEBUTTONUP: if event.dict['button'] is 4: self.square_size += 1 elif event.dict['button'] is 5 and self.square_size > 1: self.square_size -= 1 elif event.dict['button'] is 3: coords = Vec2D(*event.dict['pos']) - self.window_center coords *= 1 / self.square_size coords -= self.offset if self.is_hex(): coords = Vec2D( coords.x - coords.y / math.tan(math.pi / 3), coords.y / math.sin(math.pi / 3)) coords = (round(coords.x), round(coords.y)) else: coords = (math.floor(coords.x), math.floor(coords.y)) if self.game.grid.is_alive(coords): self.game.grid.kill(coords) else: self.game.grid.live(coords) elif event.type == pygame.KEYDOWN: if event.dict['key'] == pygame.K_SPACE: if not self.running: self.next_grid_step = pygame.time.get_ticks() self.running = not self.running if event.dict['key'] in [pygame.K_PLUS, pygame.K_KP_PLUS]: self.speedUp() if event.dict['key'] in [ pygame.K_MINUS, pygame.K_KP_MINUS ]: self.slowDown() if self.save_call and event.dict['key'] == pygame.K_s: self.save_call(self) self.clock.tick(self.fps) self.draw() if self.running and self.next_grid_step <= pygame.time.get_ticks(): self.next_grid_step += 1000 / self.grid_freq self.game.step()
def __init__(self, game): pygame.init() window_size = (640, 480) self.screen = pygame.display.set_mode(window_size) self.clock = pygame.time.Clock() self.square_size = 10 self.offset = Vec2D(0, 0) self.window_center = Vec2D(*window_size) * 0.5 self.fps = 30 self.game = game self.next_grid_step = 0 self.grid_freq = 2
def taperedpath(self,segs,start_width,**kwargs): kwargs['debug']=debug end_width=kwargs.pop('end_width',0) closed=kwargs.pop('closed',False) p=svgwrite.path.Path(**kwargs) points=[] for i in self.pathpoints(segs): points.extend(i) left=[] right=[] for i in range(len(points)): pt=points[i] width=_map(i,0,len(points)-1,start_width,end_width) left.append((pt[0]+Vec2D(r=width/2,t=(pt[2]-np.pi*0.5)),pt[1]+width/2 if pt[1] else None,pt[2])) right.append((pt[0]+Vec2D(r=width/2,t=(pt[2]+np.pi*0.5)),pt[1]-width/2 if pt[1] else None,pt[2])) right.reverse() points=left+right p.push(['M',left[0][0].car()]) #p.push(['M',self.right[0][0].car()]) #p.push(['L',self.left[0][0].car()]) down=False for i in range(1,len(points)): pt=points[i] if i==len(left): down=True if end_width!=0: if True:#closed: p.push(['L',pt[0].car()]) else: p.push(['M',pt[0].car()]) else: if (not down and pt[1]) or (down and points[i-1][1]): deltat=pt[2]- points[i-1][2] a='+' if deltat>0 else '-' p.push_arc(pt[0].car(),0,abs(points[i-1][1]) if down else abs(pt[1]),large_arc=False,angle_dir=a,absolute=True) else: if i>2 and i+2<len(points): if down: b=catmull2bezier([points[i-1][0],points[i][0],points[i+1][0],points[i+2][0]])[1] else: b=catmull2bezier([points[i-1][0],points[i][0],points[i+1][0],points[i+2][0]])[1] p.push(['C',b[1].x,b[1].y,b[2].x,b[2].y,b[3].x,b[3].y]) else: p.push(['L',pt[0].car()]) if closed: p.push(['Z']) return p
def get_point(p,segs,xpos): #accepts pathpoints object, returns position, tangent #xpos from 0 to t0.r s=xpos/p.t0.r path=p.pathpoints(segs) assert(s<1) segs=len(path)-1 pathi=int(s*segs) lowersegs=len(path[pathi]) loweri=int((s-pathi/segs)*lowersegs*segs) lowerpoint=path[pathi][loweri] lower_s=pathi/segs+loweri/(segs*lowersegs) upper_pathi=pathi upperi=loweri+1 if upperi==len(path[pathi]): upperi=0 upper_pathi+=1 upperpoint=path[upper_pathi][upperi] upper_s=upper_pathi/segs+upperi/(segs*lowersegs) #print('s=',s,'lowerpoint:',(pathi,loweri),'upperpoint:',(upper_pathi,upperi)) interp=(s-lower_s)/(upper_s-lower_s) #print(interp,lower_s,upper_s) t1=upperpoint[2] t0=lowerpoint[2] t=interp*(t1-t0) r=upperpoint[1] lowerx=lowerpoint[0].x lowery=lowerpoint[0].y upperx=upperpoint[0].x uppery=upperpoint[0].y if r==None:#line p=Vec2D(lowerx+interp*(upperx-lowerx),lowery+interp*(uppery-lowery)) else: delt=Vec2D(r=2*r*np.sin(t/2),t=t0+t/2) delt._update_car #print(delt) p=Vec2D(lowerx,lowery)+delt return(p,t0+t)
def parse_prettypaths(ElementTree): def s(): for g in ElementTree.findall('.//svg:g',ns): if g.get('id').startswith('prettypath'): yield g for g in s(): widths=[] pathstuff={} paths=g.findall('svg:path',ns) for p in paths: d=p.get('d').split(' ') r=[] for i in d: r.extend(i.split(',')) d=r if len(d)==5:#width line st=Vec2D(*d[1:3]) en=Vec2D(*d[3:5]) w=(st-en).r m=(st+en)*0.5 widths.append(w,m) else:#path assert(d.pop(0)=='M')#will not work if relative coordinates st=Vec2D(d.pop(0),d.pop(0)) assert(d.pop(0)=='C') tan0=Vec2D(d.pop(0),d.pop(0)) tan1=Vec2D(d.pop(0),d.pop(0)) en=Vec2D(d.pop(0),d.pop(0)) assert(len(d)==0)#should be it pathstuff['start']=st pathstuff['end']=en pathstuff['theta0']=tan0-st pathstuff['theta1']=tan1-en pathstuff['width0']=min(((w[1]-pathstuff['start']).r,w[0]) for w in widths)[1] pathstuff['width1']=max(((w[1]-pathstuff['end']).r,w[0]) for w in widths)[1] yield pathstuff
def s(): for g in ElementTree.findall('.//svg:g',ns): if g.get('id').startswith('prettypath'): yield g for g in s(): widths=[] pathstuff={} paths=g.findall('svg:path',ns) for p in paths: d=p.get('d').split(' ') r=[] for i in d: r.extend(i.split(',')) d=r if len(d)==5:#width line st=Vec2D(*d[1:3]) en=Vec2D(*d[3:5]) w=(st-en).r m=(st+en)*0.5 widths.append(w,m) else:#path assert(d.pop(0)=='M')#will not work if relative coordinates st=Vec2D(d.pop(0),d.pop(0)) assert(d.pop(0)=='C') tan0=Vec2D(d.pop(0),d.pop(0)) tan1=Vec2D(d.pop(0),d.pop(0)) en=Vec2D(d.pop(0),d.pop(0)) assert(len(d)==0)#should be it pathstuff['start']=st pathstuff['end']=en pathstuff['theta0']=tan0-st
def test_add(self): result = self.a + self.b self.assertEqual(result, Vec2D(42 + 23, 26 - 12))
from cprettypath import PrettyPath from vec2d import Vec2D p=PrettyPath(Vec2D(0,0),Vec2D(r=100,t=90),-2,2) p.pathpoints(5)
#!/usr/bin/python import sys import importlib if 'generate' in sys.modules: importlib.reload(sys.modules['generate']) import xml.etree.ElementTree as etree from vec2d import Vec2D from cprettypath import radians import svgwrite from random import random,randrange,gauss,randint #archea. #myArchea.root start=Vec2D(3000,3000) from generate import metatree,Branch from cprettypath import degrees def myround(n,sigfigs): ret=int(n*(10**sigfigs))/(10**sigfigs) return str(ret) from multiprocessing import Process from subprocess import run def generate_a_tree(cladname,numbranches,numtrees,filenames_in,t1,t2,theta,length): branchings=numbranches x=[branchings]*numtrees
def generate_a_tree(cladname, numbranches, numtrees, filenames_in): branchings = numbranches x = [branchings] * numtrees t1 = gauss(radians(-29), radians(2)) #t1=radians(-32) t2 = gauss(radians(75), radians(3)) #t2=radians(78) theta = Branch(Branch(gauss(0.725, 0.03), gauss(0.86, 0.03)), Branch(gauss(1.05, 0.3), gauss(0.807, 0.2))) #theta=Branch(Branch(0.738,0.897),Branch(1.05,0.951)) length = Branch(0.79 + random() * 0.05, 0.63 + random() * 0.17) #length=Branch(0.8,0.63) m = metatree(start, x, 10, Branch(t1, t2), theta, length, render=True, debug=False) termpos = [] dwg = svgwrite.Drawing(size=('3600mm', '3600mm'), debug=False) threadfilt = dwg.defs.add(svgwrite.filters.Filter()) threadfilt.feMerge(['SourceGraphic'], result='bypass') for i in range(3): threadfilt.feTurbulence(stitchtiles='stitch', type='turbulence', baseFrequency=gauss(0.07, 0.03), numOctaves=16, result='haze' + str(i), seed=randrange(193048148176)) threadfilt.feTurbulence(stitchtiles='stitch', type='fractalNoise', baseFrequency=0.1, numOctaves=4, result='noise' + str(i), seed=randrange(109861223425)) threadfilt.feDisplacementMap(in_='SourceGraphic', in2='haze' + str(i), scale=gauss(3.5, 0.9), xChannelSelector='R', yChannelSelector='G', result="twiddle" + str(i)) threadfilt.feColorMatrix( in_='twiddle' + str(i), result='black_twiddle' + str(i), type='matrix', values="1 0 0 0 0.7 0 1 0 0 0.7 0 0 1 0 0 0.4 0.4 0.6 0 0", debug=False) threadfilt.feGaussianBlur(in_='black_twiddle' + str(i), result='shadow_twiddle' + str(i), stdDeviation=0.15) threadfilt.feGaussianBlur(in_='twiddle' + str(i), result='hazy_twiddle' + str(i), stdDeviation=0.07) threadfilt.feComposite(in_='hazy_twiddle' + str(i), in2='shadow_twiddle' + str(i), result='shadowed_twiddle' + str(i), operator='over') threadfilt.feMerge(['shadowed_twiddle' + str(i) for i in range(3)], result='twisted_flax') threadfilt.feMorphology(in_='SourceGraphic', operator='dilate', radius=1.25, result='blurrr') threadfilt.feTurbulence(stitchtiles='stitch', type='turbulence', baseFrequency=0.1, numOctaves=4, result='noise') threadfilt.feDisplacementMap(in_='blurrr', in2='noise', scale=1.2, result='fuzzy') threadfilt.feComposite(in_='twisted_flax', in2='fuzzy', operator='in', result='reeesult') threadfilt.feGaussianBlur(in_='reeesult', stdDeviation=0.05) threadfilt.feMerge(['bypass']) #g=dwg.g(id='topgroup',filter=threadfilt.get_funciri()) for idx, t in enumerate(m['trees']): pos = tuple(float(s) for s in t['transform'][7:-1].split(',')[1:]) termpos.append(Vec2D(*pos)) t['id'] = 'fungaltree_' + str(idx) dwg.add(t) filename = '/tmp/' + cladname + '.svg' + '_t1=' + myround( degrees(t1), 1) + '_t2=' + myround(degrees(t2), 1) + '_thet=((' + myround( theta.l.l, 3) + '_' + myround(theta.l.r, 3) + ')(' + myround( theta.r.l, 3) + '_' + myround(theta.r.r, 3) + ')' + '_len=(' + myround( length.l, 2) + '_' + myround(length.r, 2) + ').svg' print(filename) with open(filename, 'w') as f: f.write(dwg.tostring()) with open(filenames_in, 'a') as f: f.write(filename + '\n')
def generate_a_tree(cladname, numbranches, numtrees, filenames_in): branchings = numbranches x = [branchings] * numtrees #t1=radians(-29)+radians(randint(-5,5)) t1 = gauss(radians(-29), radians(2)) t1 = gauss(radians(-26.8), radians(1)) #t2=radians(75)+radians(randint(-9,9)) t2 = gauss(radians(75), radians(3)) t2 = gauss(radians(72.9), radians(1.5)) #theta=Branch(Branch(0.68+random()*0.09,0.83+random()*0.09),Branch(1.05,0.75+random()*0.45)) theta = Branch(Branch(gauss(0.725, 0.03), gauss(0.86, 0.03)), Branch(gauss(1.05, 0.3), gauss(0.807, 0.2))) length = Branch(0.79 + random() * 0.05, 0.63 + random() * 0.17) theta = Branch(Branch(gauss(0.733, 0.03), gauss(0.825, 0.03)), Branch(gauss(0.9, 0.1), gauss(0.62, 0.2))) #Metazoa:t1=-31.0_t2=68.0_thet=((0.757_0.892)(1.05_0.842)_len=(0.8_0.66) t1 = radians(-31) t2 = radians(68) theta = Branch(Branch(0.757, 0.892), Branch(1.05, 0.842)) length = Branch(0.8, 0.66) #theta=Branch(Branch(0.72,0.79),Branch(0.89,0.84)) #length=Branch(0.81,0.68) #file:///home/bwsq/Documents/TreeOfLife/processing-lite/test_15px_2*2%5E15 #t1=-25.0,t2=82.0,thet%3A((0.75,0.87),(1.05,1.054),len=(0.83,0.7).svg #t1=-29.0,t2=78.0,thet:((0.718,0.873),(1.05,0.808),len=(0.81,0.65) #t1=radians(-28) #t2=radians(78) #theta=Branch(Branch(0.694,0.897),Branch(1.05,0.896)) #length=Branch(0.79,0.77) import cProfile #cProfile.run(''' m = metatree(start, x, 10, Branch(t1, t2), theta, length, render=True, debug=False) #''') termpos = [] dwg = svgwrite.Drawing(size=('3600mm', '3600mm'), debug=False) threadfilt = dwg.defs.add(svgwrite.filters.Filter()) threadfilt.feMerge(['SourceGraphic'], result='bypass') for i in range(3): threadfilt.feTurbulence(stitchtiles='stitch', type='turbulence', baseFrequency=gauss(0.07, 0.03), numOctaves=16, result='haze' + str(i), seed=randrange(193048148176)) threadfilt.feTurbulence(stitchtiles='stitch', type='fractalNoise', baseFrequency=0.1, numOctaves=4, result='noise' + str(i), seed=randrange(109861223425)) threadfilt.feDisplacementMap(in_='SourceGraphic', in2='haze' + str(i), scale=gauss(3.5, 0.9), xChannelSelector='R', yChannelSelector='G', result="twiddle" + str(i)) threadfilt.feColorMatrix( in_='twiddle' + str(i), result='black_twiddle' + str(i), type='matrix', values="1 0 0 0 0.7 0 1 0 0 0.7 0 0 1 0 0 0.4 0.4 0.6 0 0", debug=False) threadfilt.feGaussianBlur(in_='black_twiddle' + str(i), result='shadow_twiddle' + str(i), stdDeviation=0.15) threadfilt.feGaussianBlur(in_='twiddle' + str(i), result='hazy_twiddle' + str(i), stdDeviation=0.07) threadfilt.feComposite(in_='hazy_twiddle' + str(i), in2='shadow_twiddle' + str(i), result='shadowed_twiddle' + str(i), operator='over') threadfilt.feMerge(['shadowed_twiddle' + str(i) for i in range(3)], result='twisted_flax') threadfilt.feMorphology(in_='SourceGraphic', operator='dilate', radius=1.25, result='blurrr') threadfilt.feTurbulence(stitchtiles='stitch', type='turbulence', baseFrequency=0.1, numOctaves=4, result='noise') threadfilt.feDisplacementMap(in_='blurrr', in2='noise', scale=1.2, result='fuzzy') threadfilt.feComposite(in_='twisted_flax', in2='fuzzy', operator='in', result='reeesult') threadfilt.feGaussianBlur(in_='reeesult', stdDeviation=0.05) threadfilt.feMerge(['bypass']) g = dwg.g(id='topgroup', filter=threadfilt.get_funciri()) for t in m['trees']: pos = tuple(float(s) for s in t['transform'][7:-1].split(',')[1:]) termpos.append(Vec2D(*pos)) g.add(t) dwg.add(g) filename = cladname + '_t1=' + myround(degrees(t1), 1) + '_t2=' + myround( degrees(t2), 1) + '_thet=((' + myround(theta.l.l, 3) + '_' + myround( theta.l.r, 3) + ')(' + myround(theta.r.l, 3) + '_' + myround( theta.r.r, 3) + ')' + '_len=(' + myround( length.l, 2) + '_' + myround(length.r, 2) + ').svg' print(filename) with open(filename, 'w') as f: f.write(dwg.tostring()) with open(filenames_in, 'a') as f: f.write(filename + '\n')
def test_mult(self): result = self.a * 2 self.assertEqual(result, Vec2D(84, 52))
def test_neg(self): self.assertEqual(-self.a, Vec2D(-42, -26))
def pathpoints(self,int segs): cdef int i=0 cdef int j=0 cdef int subdiv #self.straights=0 t=Vec2D(r=self.t0.r,t=self.t0.t) delta=Vec2D() ret=[] p=Vec2D(self.start.x,self.start.y) #max dtheta! that's what we care about. c=0 cdef double dt #print('segs:',segs) for i in range(segs): s=_map(i,0,segs,0,1) curvature=self._cp(s) dt=curvature*(1/float(segs)) subdiv=int(abs(dt)//MAXDTHETA)+1 #print('subdiv:',subdiv) jret=[] for j in range(subdiv): #print("i:",i," j:",j," t:",t) #print(p.x,p.y) jret.append((Vec2D(p.x,p.y),1/c if c!=0 else None,t.t)) s=_map(i+j/float(subdiv),0,segs,0,1) curvature=self._cp(s) #print("curvature: ",curvature) dt=curvature*(1/float(segs*subdiv)) #print('dt:',dt) if curvature<-MIN_C or curvature>MIN_C: pass else: curvature=0 c=curvature/t.r if curvature: #r.pol=(1/c,t.t) delta.pol=(2/c*np.sin(dt/2),t.t+dt/2) #print("delta:",delta) p.add(delta) t.rotate(dt) else: #self.straights+=1 delta=t*(1/float(segs*subdiv)) #print("delta:",delta) p.add(delta) ret.append(jret) #print(p.x,p.y) ret.append([(Vec2D(p.x,p.y),1/c if c!=0 else None,t.t)]) #assert(len(ret)>1) self.end=p #self.t1=t self.t1=Vec2D(r=t.r,t=t.t) return(ret)
def test_eq(self): self.assertEqual(self.a, self.a) self.assertEqual(Vec2D(2, 3), Vec2D(2, 3)) self.assertNotEqual(Vec2D(2, 3), Vec2D(3, 2))
def setUp(self): self.a = Vec2D(42, 26) self.b = Vec2D(23, -12)