http://code.google.com/p/glumpy/source/detail?r=cbb0708f5422
Modified:
/demos/boids.py
=======================================
--- /demos/boids.py Thu Mar 22 02:05:20 2012
+++ /demos/boids.py Fri Mar 23 03:53:45 2012
@@ -33,13 +33,13 @@
'''
import numpy as np
import OpenGL.GL as gl
+from scipy.spatial import cKDTree
from glumpy import figure, Trackball
-from scipy.spatial.distance import cdist
if __name__ == '__main__':
- fig = figure(size=(512,512))
+ fig = figure(size=(800,800))
trackball = Trackball(65, 135, 1., 2.0)
@fig.event
@@ -78,35 +78,36 @@
n = len(boids)
P = boids['position']
V = boids['velocity']
- D = cdist(P,P)
-
- Mr = (D < 0.05)
- Mr = np.repeat(Mr,3,axis=1).reshape(n,n,3)
- # Nr = Mr.sum(axis=0)
# Cohesion: steer to move toward the average position of local
flockmates
C = -(P - P.sum(axis=0)/n)
+
# Alignment: steer towards the average heading of local flockmates
A = -(V - V.sum(axis=0)/n)
+
# Repulsion: steer to avoid crowding local flockmates
- R = -((np.repeat(P,n,axis=0).reshape(n,n,3)-P)*Mr).sum(axis=0)
+ D,I = cKDTree(P).query(P,5)
+ M = np.repeat(D < 0.05, 3, axis=1).reshape(n,5,3)
+ Z = np.repeat(P,5,axis=0).reshape(n,5,3)
+ R = -((P[I]-Z)*M).sum(axis=1)
+
# Target : Follow target
T = target - P
+
# Predator : Move away from predator
dP = P - predator
D = np.maximum(0, 0.35 - np.sqrt(dP[:,0]**2
+dP[:,1]**2+dP[:,2]**2) )
- dP[:,0] *= D
- dP[:,1] *= D
- dP[:,2] *= D
-
- boids['velocity'] += 0.0005*C + 0.01*A + 0.01*R + 0.0005*T +
0.005*dP
+ D = np.repeat(D,3,axis=0).reshape(n,3)
+ dP *= D
+
+ boids['velocity'] += 0.0005*C + 0.01*A + 0.01*R + 0.0005*T +
0.0025*dP
boids['position'] += boids['velocity']
fig.redraw()
t = 0
- n = 500
+ n = 1000
boids = np.zeros(n, [ ('position', 'f4', 3),
('position_1', 'f4', 3),
('position_2', 'f4', 3),