poolballs.html
001| """Pool Balls Simulation (2D and 3D).
001|
001| Classes:
001| Ball2D (x,y, px,py, color, tag)
001| Ball3D (x,y,z, px,py,pz, color, tag)
001| DataBase ()
001|
001| Functions:
001| dispatch (cmd, **kwargs)
001| run (ballset, n_ticks, framerate, pscale, filename, x_mom)
001|
001| collision_check_2d (tk, b1, b2, db, check)
001| collision_check_3d (tk, b1, b2, db, check)
001|
001| set_ball_colors (scheme, ballset)
001| get_2d_ballset (mode, n_balls, walls)
001| get_3d_ballset (mode, n_balls, walls)
001|
001| get_2d_ballset_pool (apex, separation)
001| get_2d_ballset_grid (xgrid, ygrid, offset)
001| get_3d_ballset_grid (xgrid, ygrid, zgrid, offset)
001| get_2d_ballset_square (n_balls, p_max, offset, separation)
001| get_3d_ballset_square (n_balls, p_max, offset, separation)
001| get_2d_ballset_random (n_balls, p_max, walls, min_separation, wall_separation, max_tries)
001| get_3d_ballset_random (n_balls, p_max, walls, min_separation, wall_separation, max_tries)
001| get_2d_ballset_special (walls)
001|
001| Commands:
001| pool do_pool_table - 2D Simulation -- Normal 16 balls.
001| 2d do_run_2d - 2D Simulation.
001| 3d do_run_3d - 3D Simulation.
001| -2d do_reverse_2d - 2D Reverse Simulation.
001| /lst do_table_list - List tables in a database.
001| /pov do_table_pov_file - Generate POV-Ray file from a database.
001| /his do_scan_history - Scan history table and do stuff with the data.
001| /sql do_table_sql - SQL query platform
001| test do_test - Test platform
001|
001| Videos:
001| https://youtu.be/GQ-hNJ6OpHo -- Pool Balls v0.1 (poolballs-2d-01.mp4)
001| https://youtu.be/QojyPFTNQi8 -- Pool Balls v0.2 (poolballs-2d-02.mp4)
001| https://youtu.be/TcgEhpe1BYo -- Pool Balls v0.3 (poolballs-2d-03.mp4)
001| https://youtu.be/imAVSERQ9Ic -- Pool Balls v1.0 (poolballs-2d-10.mp4)
001| https://youtu.be/WUAWtNpjEek -- Pool Balls v1.1 (poolballs-2d-11.mp4)
001| https://youtu.be/VxDTnReSAlk -- Pool Balls v1.2 (poolballs-2d-12.mp4)
001| https://youtu.be/T0P5Uf8gsEs -- Pool Balls v1.3 (poolballs-2d-13.mp4)
001| https://youtu.be/dNB3fFTLPqc -- Pool Balls v1.4 (poolballs-2d-14.mp4)
001| https://youtu.be/JLVQk3YvPWk -- Pool Balls v1.5 (poolballs-2d-15.mp4)
001| https://youtu.be/or8KeQxgSWU -- Pool Balls v1.6 (poolballs-2d-16.mp4)
001| https://youtu.be/Dq9W4HKAUNM -- Pool Balls v1.7 (poolballs-2d-17.mp4)
001| https://youtu.be/sC1Nru6OH7E -- Pool Balls v2.0 (poolballs-2d-20.mp4)
001| https://youtu.be/PkI3li2RkfA -- Pool Balls v2.1 (poolballs-2d-21.mp4)
001| https://youtu.be/N1orfP_XRzA -- Pool Balls v2.2 (poolballs-2d-22.mp4)
001| https://youtu.be/r96dW9ZhgEI -- Pool Balls v2.3 (poolballs-2d-23.mp4)
001| https://youtu.be/-L93jPoyC1M -- Pool Balls v3.0 (poolballs-2d-30.mp4)
001| https://youtu.be/qZS4DpXbNX0 -- Pool Balls v3.1 (poolballs-2d-31.mp4)
001| https://youtu.be/WCwI3G5yrII -- Pool Balls v3.2 (poolballs-2d-32.mp4)
001|
001| https://youtu.be/I676QitYqDA -- Pool Balls 3D v0.1 (poolballs-3d-01.mp4)
001| https://youtu.be/NUDk-lIIqJA -- Pool Balls 3D v0.2 (poolballs-3d-02.mp4)
001| https://youtu.be/CMmbrbLADDM -- Pool Balls 3D v1.0 (poolballs-3d-10.mp4)
001| https://youtu.be/8WggBJ-T5CI -- Pool Balls 3D v1.1 (poolballs-3d-11.mp4)
001| https://youtu.be/qWiqhiqmiog -- Pool Balls 3D v1.2 (poolballs-3d-12.mp4)
001| https://youtu.be/UTGqr2lqCW4 -- Pool Balls 3D v1.3 (poolballs-3d-13.mp4)
001| https://youtu.be/hcU7NXZU79k -- Pool Balls 3D v1.4 (poolballs-3d-14.mp4)
001| https://youtu.be/5ik79EPzztQ -- Pool Balls 3D v2.0 (poolballs-3d-20.mp4)
001| https://youtu.be/ikjVzLKpQQI -- Pool Balls 3D v2.1 (poolballs-3d-21.mp4)
001| """
002|
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from time import perf_counter, perf_counter_ns
007| from datetime import datetime
008| from math import sqrt, sin,cos, radians
009| from random import random, randint
010| import sqlite3
011| from logger import logger,info,debug,trace, LogFilenameTimestamp
012| from webpage import KWARG
013| from colors import color_function_1, color_function_2
014| from files import linefile, tabfile, csvfile
015| from matrix import matrix2d, mvector2d, matrix3d, mvector3d
016| from vector import vector
017| from goodies import distance
018|
019|
020|
021| BasePath = r'C:\CJS\prj\Python\app\sims\poolballs'
022| DataPath = BasePath
023| AnimPath = r'C:\CJS\prj\pov\ws\xyz'
024| Log = logger('Balls')
025|
026| CMND = ''
027| ARGS = {
028| '/b': 'square',
029| '/c': 'rand',
030| 'b': '125',
031| 'n': '24000',
032| 'fr': '12',
033| 'ps': '2000',
034| 'fro': '-1',
035| 'fpath': BasePath,
036|
037| 'dpath': BasePath,
038| 'db': 'poolballs_221121034348',
039| }
040|
041| """Timestamp for database group key. (TODO: eliminate the need!)"""
042| TS = datetime.now()
043| TimeStamp = lambda s:(s % TS.strftime('%y%m%d%H%M%S'))
044|
045|
046| """Note that these are POV-Ray colors, not PIL colors."""
047| ColorWhite = (1.00, 1.00, 1.00)
048| ColorRed = (0.81, 0.25, 0.25)
049| ColorYellow = (0.64, 0.64, 0.25)
050| ColorGreen = (0.25, 0.81, 0.25)
051| ColorBlue = (0.36, 0.36, 0.81)
052|
053| RandColor = lambda: (random(), random(), random())
054|
055| a30x = cos(radians(30))
056| a30y = sin(radians(30))
057|
058| """Ball color triplets, relative coordates for racked position, ball labels."""
059| PoolBallConfig = [
060| ((0.91, 0.93, 0.97), (-2, 0), 'cue'),
061| ((1.00, 0.84, 0.00), (0, 0), '1'),
062| ((0.00, 0.00, 1.00), (2*a30x, +2*a30y), '2'),
063| ((1.00, 0.00, 0.00), (2*a30x, -2*a30y), '3'),
064| ((0.38, 0.00, 0.51), (4*a30x, +4*a30y), '4'),
065| ((1.00, 0.38, 0.00), (4*a30x, 0 ), '5'),
066| ((0.13, 0.54, 0.13), (4*a30x, -4*a30y), '6'),
067| ((0.50, 0.00, 0.00), (6*a30x, +6*a30y), '7'),
068| ((0.00, 0.00, 0.00), (6*a30x, +2*a30y), '8'),
069| ((1.00, 0.84, 0.33), (6*a30x, -2*a30y), '9'),
070| ((0.33, 0.33, 1.00), (6*a30x, -6*a30y), '10'),
071| ((1.00, 0.33, 0.33), (8*a30x, +8*a30y), '11'),
072| ((0.58, 0.25, 0.77), (8*a30x, +4*a30y), '12'),
073| ((1.00, 0.44, 0.27), (8*a30x, 0 ), '13'),
074| ((0.38, 0.83, 0.38), (8*a30x, -4*a30y), '14'),
075| ((0.70, 0.25, 0.25), (8*a30x, -8*a30y), '15'),
076| ]
077|
078|
079| class Ball2D ():
080| """2D Ball class for poolball simulation."""
081| _sn = 0
082| @classmethod
083| def SN (cls):
084| """Unique serial number for balls."""
085| cls._sn += 1
086| return int(cls._sn)
087|
088| ScaleFactor = 1000
089|
090| Wall_XN = -50.0
091| Wall_XP = -50.0
092| Wall_YN = -50.0
093| Wall_YP = -50.0
094| Wall_ZN = -50.0
095| Wall_ZP = -50.0
096|
097| def __init__ (self, x=0.0,y=0.0, px=0.0,py=0.0, color=ColorWhite, tag=''):
098| """New Ball2D instance."""
099| self.bid = Ball2D.SN()
100| self.bix = self.bid
101| self.x = float(x)
102| self.y = float(y)
103| self.px = float(px) / self.ScaleFactor
104| self.py = float(py) / self.ScaleFactor
105| self.tag = str(tag)
106| self.color = color
107|
108| def set_momentum (self, px, py):
109| """Set ball's momentum. [NEVER set PX or PY directly!!]"""
110| self.px = float(px) / self.ScaleFactor
111| self.py = float(py) / self.ScaleFactor
112|
113| def momentum (self):
114| """Return momentum vector."""
115| return vector(self.px, self.py)
116|
117| def speed (self):
118| """Return speed. (momentum "distance")"""
119| return self.ScaleFactor * sqrt(pow(self.px,2) + pow(self.py,2))
120|
121| def distance (self, other):
122| """Return distance from another ball."""
123| assert isinstance(other,Ball2D), TypeError(Ball2D.E_DIST)
124| dx = (self.x - other.x)
125| dy = (self.y - other.y)
126| return sqrt(pow(dx,2) + pow(dy,2))
127|
128| def asvector (self):
129| """Return a VECTOR object with our XY."""
130| return vector(self.x, self.y)
131|
132| def move (self, multiplier=+1.0):
133| """Move ball one time tick based on its momentum."""
134| self.x += (self.px * multiplier)
135| self.y += (self.py * multiplier)
136| return self()
137|
138| def wall_check (self, ts=0):
139| """Test for wall collision and change momentum as required."""
140| n = 0
141|
142| if self.x < (self.Wall_XN+1.0):
143| Log.debug('[%d]WALL.X.max: %d/%d' % (ts, self.bix,self.bid))
144| dx = (self.Wall_XN+1.0) - self.x
145| Log.trace('>>>>>>>> %s (%f)' % (self,dx))
146| self.x += (2 * dx)
147| self.px = abs(self.px)
148| dx = (self.Wall_XN+1.0) - self.x
149| Log.trace('>>>>>>>> %s (%f)' % (self,dx))
150| Log.debug()
151| n += 1
152|
153| if (self.Wall_XP-1.0) < self.x:
154| Log.debug('[%d]WALL.X.min: %d/%d' % (ts, self.bix,self.bid))
155| dx = self.x - (self.Wall_XP-1.0)
156| Log.trace('>>>>>>>> %s (%f)' % (self,dx))
157| self.x -= (2 * dx)
158| self.px = -abs(self.px)
159| dx = self.x - (self.Wall_XP-1.0)
160| Log.trace('>>>>>>>> %s (%f)' % (self,dx))
161| Log.debug()
162| n += 1
163|
164| if self.y < (self.Wall_YN+1.0):
165| Log.debug('[%d]WALL.Y.min: %d/%d' % (ts, self.bix,self.bid))
166| dy = (self.Wall_YN+1.0) - self.y
167| Log.trace('>>>>>>>> %s (%f)' % (self,dy))
168| self.y += (2 * dy)
169| self.py = abs(self.py)
170| dy = (self.Wall_YN+1.0) - self.y
171| Log.trace('>>>>>>>> %s (%f)' % (self,dy))
172| Log.debug()
173| n += 1
174|
175| if (self.Wall_YP-1.0) < self.y:
176| Log.debug('[%d]WALL.Y.max: %d/%d' % (ts, self.bix,self.bid))
177| dy = self.y - (self.Wall_YP-1.0)
178| Log.trace('>>>>>>>> %s (%f)' % (self,dy))
179| self.y -= (2 * dy)
180| self.py = -abs(self.py)
181| dy = self.y - (self.Wall_YP-1.0)
182| Log.trace('>>>>>>>> %s (%f)' % (self,dy))
183| Log.debug()
184| n += 1
185| return n
186|
187| def color_momentum (self):
188| """Set color based on momentum."""
189| k0,k1,k2,k3,k4,k5 = (5.0, 50.0, 100.0, 160.0, 220.0, 280.0)
190| def get_color (mom):
191| if mom < k0: return (0.0, 0.0, 0.0)
192| if mom < k1: return (0.0, 0.0, ((mom-k0)/(k1-k0)))
193| if mom < k2: return (((mom-k1)/(k2-k1)), 0.0, 1.0)
194| if mom < k3: return (1.0, 0.0, 1.0-((mom-k2)/(k3-k2)))
195| if mom < k4: return (1.0, ((mom-k3)/(k4-k3)), 0.0)
196| if mom < k5: return (1.0, 1.0, ((mom-k4)/(k5-k4)))
197| return (1.0, 1.0, 1.0)
198|
199| p = self.speed()
200| c = get_color(p)
201| self.color = c
202| Log.trace('Set-Ball-Color(%f): %s' % (p,c))
203|
204| def __call__ (self, ts=0):
205| """Return ball data as a history record 10-tuple."""
206| return (ts, self.bix, self.x,self.y, self.px,self.py, self.color[0],self.color[1],self.color[2], self.tag)
207|
208| def __eq__ (self, other):
209| assert isinstance(other,Ball2D), TypeError(Ball2D.E_COMP)
210| return (True if self.bix == other.bix else False)
211| def __lt__ (self, other):
212| assert isinstance(other,Ball2D), TypeError(Ball2D.E_COMP)
213| return self.bix < other.bix
214| def __gt__ (self, other):
215| assert isinstance(other,Ball2D), TypeError(Ball2D.E_COMP)
216| return self.bix > other.bix
217|
218| def __ne__ (self, other): return not self.__eq__(other)
219| def __le__ (self, other): return not self.__gt__(other)
220| def __ge__ (self, other): return not self.__lt__(other)
221|
222| def __str__ (self):
223| t = (self.bix, self.bid, self.x,self.y, self.px,self.py)
224| s = '%04d[%04d] [%+10.6f, %+10.6f] {%+9.6f, %+9.6f}'
225| return s%t
226| def __repr__ (self):
227| t = (self.bix, self.bid, self.x,self.y, self.px,self.py, self.tag, *self.color)
228| s = '{Ball2D:{bix:%d, bid:%d, x:%+f, y:%+f, px:%+f, py:%+f, tag:"%s", color:[%f,%f,%f]}}'
229| return s%t
230|
231| E_DIST = 'Another Ball object required to calculate distance!'
232| E_COMP = 'Another Ball object required for comparison!'
233|
234|
235| class Ball3D (Ball2D):
236| """3D Ball class for poolball simulation."""
237|
238| def __init__ (self, x=0.0,y=0.0,z=0.0, px=0.0,py=0.0,pz=0.0, color=ColorWhite, tag=''):
239| """New Ball3D instance."""
240| super().__init__(x=x,y=y, px=px,py=py, color=color, tag=tag)
241| self.z = float(z)
242| self.pz = float(pz) / self.ScaleFactor
243|
244| def set_momentum (self, px, py, pz):
245| """Set ball's momentum. [NEVER set PX or PY directly!!]"""
246| super().set_momentum(px,py)
247| self.pz = float(pz) / self.ScaleFactor
248|
249| def speed (self):
250| """Return speed. (momentum "distance")"""
251| return self.ScaleFactor * sqrt(pow(self.px,2) + pow(self.py,2) + pow(self.pz,2))
252|
253| def distance (self, other):
254| """Return distance from another ball."""
255| assert isinstance(other,Ball3D), TypeError(Ball3D.E_DIST)
256| dx = (self.x - other.x)
257| dy = (self.y - other.y)
258| dz = (self.z - other.z)
259| return sqrt(pow(dx,2) + pow(dy,2) + pow(dz,2))
260|
261| def move (self, multiplier=+1.0):
262| """Move ball one time tick based on its momentum."""
263| super().move(multiplier=multiplier)
264| self.z += (self.pz * multiplier)
265| return self()
266|
267| def wall_check (self, ts=0):
268| """Test for wall collision and change momentum as required."""
269| n = super().wall_check(ts=ts)
270|
271| if self.z < (self.Wall_ZN+1.0):
272| Log.debug('[%d]WALL.Z.min: %d/%d' % (ts, self.bix,self.bid))
273| dz = (self.Wall_ZN+1.0) - self.z
274| Log.trace('>>>>>>>> %s (%f)' % (self,dz))
275| self.z += (2 * dz)
276| self.pz = abs(self.pz)
277| dz = (self.Wall_ZN+1.0) - self.z
278| Log.trace('>>>>>>>> %s (%f)' % (self,dz))
279| Log.debug()
280| n += 1
281|
282| if (self.Wall_ZP-1.0) < self.z:
283| Log.debug('[%d]WALL.Z.max: %d/%d' % (ts, self.bix,self.bid))
284| dz = self.z - (self.Wall_ZP-1.0)
285| Log.trace('>>>>>>>> %s (%f)' % (self,dz))
286| self.z -= (2 * dz)
287| self.pz = -abs(self.pz)
288| dz = self.z - (self.Wall_ZP-1.0)
289| Log.trace('>>>>>>>> %s (%f)' % (self,dz))
290| Log.debug()
291| n += 1
292| return n
293|
294| def asvector (self):
295| """Return a VECTOR object with our XY."""
296| return vector(self.x, self.y, self.z)
297|
298| def __call__ (self, ts=0):
299| """Return ball data as a history record 12-tuple."""
300| return (ts, self.bix, self.x,self.y,self.z, self.px,self.py,self.pz, self.color[0],self.color[1],self.color[2], self.tag)
301|
302| def __str__ (self):
303| t = (self.bix, self.bid, self.x,self.y,self.z, self.px,self.py,self.pz)
304| s = '%04d[%04d] [%+10.6f, %+10.6f, %+10.6f] {%+9.6f, %+9.6f, %+9.6f}'
305| return s%t
306| def __repr__ (self):
307| t = (self.bix, self.bid, self.x,self.y,self.z, self.px,self.py,self.pz, self.tag, *self.color)
308| s = '{Ball3D:{bix:%d, bid:%d, x:%+f, y:%+f, z:%+f, px:%+f, py:%+f, pz:%+f, tag:"%s", color:[%f,%f,%f]}}'
309| return s%t
310|
311|
312| class DataBase:
313| """Poolballs Simulation Data. Ball History; Collision Events; Wall Collision Events."""
314| dataPath = BasePath
315| SqlCreateTable = 'CREATE TABLE "%s" (%s)'
316| SqlDropTable = 'DROP TABLE "%s"'
317| SqlInsert = 'INSERT INTO "%s" VALUES (%s)'
318| SqlList = 'SELECT * from "%s" ORDER BY 1,2,3'
319|
320| tab0Name = 'stats'
321| tab0Cols = [
322| '"grp_id" INTEGER NOT NULL',
323| '"n_ticks" INTEGER NOT NULL',
324| '"n_balls" INTEGER NOT NULL',
325| '"n_frames" INTEGER NOT NULL',
326| '"n_slices" INTEGER NOT NULL',
327| ]
328| tab1Name = 'history'
329| tab1Cols = [
330| '"grp_id" INTEGER NOT NULL',
331| '"tick" INTEGER NOT NULL',
332| '"ball_id" INTEGER NOT NULL',
333| '"ball_x" FLOAT NOT NULL',
334| '"ball_y" FLOAT NOT NULL',
335| '"ball_z" FLOAT NOT NULL',
336| '"ball_px" FLOAT NOT NULL',
337| '"ball_py" FLOAT NOT NULL',
338| '"ball_pz" FLOAT NOT NULL',
339| '"ball_cr" FLOAT NOT NULL',
340| '"ball_cg" FLOAT NOT NULL',
341| '"ball_cb" FLOAT NOT NULL',
342| ]
343| tab2Name = 'collisions'
344| tab2Cols = [
345| '"grp_id" INTEGER NOT NULL',
346| '"tick" INTEGER NOT NULL',
347| '"ball1_id" INTEGER NOT NULL',
348| '"ball2_id" INTEGER NOT NULL',
349| ]
350| tab3Name = 'walls'
351| tab3Cols = [
352| '"grp_id" INTEGER NOT NULL',
353| '"tick" INTEGER NOT NULL',
354| '"ball_id" INTEGER NOT NULL',
355| ]
356| def __init__(self, filename=None):
357| """New Poolballs Database instance."""
358| self.dbName = filename if filename else TimeStamp('poolballs_%s.sqlite')
359| self.grp_id = perf_counter_ns()
360| self.is_open = False
361| self.conn = None
362| self.crsr = None
363|
364| self.col0_names = []
365| self.col0_types = []
366| for c in self.tab0Cols:
367| t = c.split()
368| self.col0_names.append(t[0])
369| self.col0_types.append(t[1] if 1 < len(t) else '')
370| self.qms0 = ','.join('?'*len(self.tab0Cols))
371|
372| self.col1_names = []
373| self.col1_types = []
374| for c in self.tab1Cols:
375| t = c.split()
376| self.col1_names.append(t[0])
377| self.col1_types.append(t[1] if 1 < len(t) else '')
378| self.qms1 = ','.join('?'*len(self.tab1Cols))
379|
380| self.col2_names = []
381| self.col2_types = []
382| for c in self.tab2Cols:
383| t = c.split()
384| self.col2_names.append(t[0])
385| self.col2_types.append(t[1] if 1 < len(t) else '')
386| self.qms2 = ','.join('?'*len(self.tab2Cols))
387|
388| self.col3_names = []
389| self.col3_types = []
390| for c in self.tab3Cols:
391| t = c.split()
392| self.col3_names.append(t[0])
393| self.col3_types.append(t[1] if 1 < len(t) else '')
394| self.qms3 = ','.join('?'*len(self.tab3Cols))
395|
396| def open (self):
397| """Begin recording a session."""
398| Log.debug('db[%s] OPEN' % self.dbName)
399| Log.debug()
400| if self.is_open:
401| Log.warn('Database already open! (Closing it...)')
402| self.close()
403| self.conn = sqlite3.connect(self.dbName)
404| self.crsr = self.conn.cursor()
405| self.grp_id = perf_counter_ns()
406| self.is_open = True
407| return self.grp_id
408| def close (self):
409| """Done with the current session."""
410| Log.debug('db[%s] CLOSE' % self.dbName)
411| Log.debug()
412| if not self.is_open:
413| Log.warn('Database already closed! (Nothing done.)')
414| return
415| self.conn.commit()
416| self.conn.close()
417| self.is_open = False
418| return self.grp_id
419|
420| def create_tables (self):
421| """Create all tables."""
422| self.open()
423| try:
424|
425| Log.debug('db[%s] Create %s Table' % (self.dbName, self.tab0Name))
426| sql = self.SqlCreateTable % (self.tab0Name, ','.join(self.tab0Cols))
427| Log.trace(sql)
428| self.crsr.execute(sql)
429|
430| Log.debug('db[%s] Create %s Table' % (self.dbName, self.tab1Name))
431| sql = self.SqlCreateTable % (self.tab1Name, ','.join(self.tab1Cols))
432| Log.trace(sql)
433| self.crsr.execute(sql)
434|
435| Log.debug('db[%s] Create %s Table' % (self.dbName, self.tab2Name))
436| sql = self.SqlCreateTable % (self.tab2Name, ','.join(self.tab2Cols))
437| Log.trace(sql)
438| self.crsr.execute(sql)
439|
440| Log.debug('db[%s] Create %s Table' % (self.dbName, self.tab3Name))
441| sql = self.SqlCreateTable % (self.tab3Name, ','.join(self.tab3Cols))
442| Log.trace(sql)
443| self.crsr.execute(sql)
444| except Exception as e:
445| Log.error(e)
446| raise
447| finally:
448| self.close()
449| def destroy_tables (self):
450| """Drop all tables."""
451| self.open()
452| try:
453|
454| Log.debug('dbTable[%s] Destroy' % (self.dbName, self.tab0Name))
455| sql = self.SqlDropTable % self.tab0Name
456| Log.trace(sql)
457| self.crsr.execute(sql)
458|
459| Log.debug('dbTable[%s] Destroy' % (self.dbName, self.tab1Name))
460| sql = self.SqlDropTable % self.tab1Name
461| Log.trace(sql)
462| self.crsr.execute(sql)
463|
464| Log.debug('dbTable[%s] Destroy' % (self.dbName, self.tab2Name))
465| sql = self.SqlDropTable % self.tab2Name
466| Log.trace(sql)
467| self.crsr.execute(sql)
468|
469| Log.debug('dbTable[%s] Destroy' % (self.dbName, self.tab3Name))
470| sql = self.SqlDropTable % self.tab3Name
471| Log.trace(sql)
472| rs = self.crsr.execute(sql)
473| except Exception as e:
474| Log.error(e)
475| raise
476| finally:
477| self.close()
478|
479| def write_pov_file (self, filename, framerate, n_balls, n_frames):
480| """Write HISTORY data to a POV-Ray data file."""
481| assert self.is_open, RuntimeError('Database not open!')
482| fo = linefile(filename)
483| fo.add('%d,%d,%d,' % (n_frames, n_balls, framerate))
484|
485| fmt = '%d,%d,<%+f,%+f,%+f>,<%+f,%+f,%+f>,<%.2f,%.2f,%.2f>,'
486|
487| sql = 'SELECT * from "%s" ORDER BY 1,2,3' % self.tab1Name
488| Log.trace(sql)
489| rs = self.crsr.execute(sql)
490| for r in rs:
491| if (framerate==0) or ((r[1] % framerate)==0):
492| fo.add(fmt % r[1:])
493| fo.save()
494| Log.info('wrote: %s' % filename)
495| Log.info()
496|
497| def stats (self, ticks, balls, framerate, pscale):
498| """Write a STATS record to the database."""
499| assert self.is_open, RuntimeError('Database not open!')
500| sql = self.SqlInsert % (self.tab0Name, self.qms0)
501| rcd = (self.grp_id, ticks, balls, framerate, pscale)
502| rs = self.crsr.execute(sql,rcd)
503| return rcd[0:2]
504| def get_stats (self):
505| """Get the (current) STATS record."""
506| assert self.is_open, RuntimeError('Database not open!')
507| sql = 'SELECT * FROM "%s" ORDER BY 1 DESC' % self.tab0Name
508| Log.trace(sql)
509| rs = self.crsr.execute(sql)
510| return list(rs)[0]
511|
512| def history (self, tick, ball):
513| """Write a HISTORY record to the database."""
514| assert self.is_open, RuntimeError('Database not open!')
515| z = ball.z if isinstance(ball,Ball3D) else 0
516| pz = ball.pz if isinstance(ball,Ball3D) else 0
517| sql = self.SqlInsert % (self.tab1Name, self.qms1)
518| rcd = (self.grp_id, tick, ball.bix, ball.x,ball.y,z, ball.px,ball.py,pz, *ball.color)
519| rs = self.crsr.execute(sql,rcd)
520| return rcd[0:2]
521|
522| def collision (self, tick, b1, b2):
523| """Write a COLLISION record to the database."""
524| assert self.is_open, RuntimeError('Database not open!')
525| sql = self.SqlInsert % (self.tab2Name, self.qms2)
526| rcd = (self.grp_id, tick, b1.bix, b2.bix)
527| rs = self.crsr.execute(sql,rcd)
528| return rcd[0:2]
529|
530| def wall_collision (self, tick, b1):
531| """Write a WALL-COLLISION record to the database."""
532| assert self.is_open, RuntimeError('Database not open!')
533| sql = self.SqlInsert % (self.tab3Name, self.qms3)
534| rcd = (self.grp_id, tick, b1.bix)
535| rs = self.crsr.execute(sql,rcd)
536| return rcd[0:2]
537|
538| def list_stats (self, fout=Log.info):
539| """List STATS data to the Log."""
540| assert self.is_open, RuntimeError('Database not open!')
541| sql = self.SqlList % self.tab0Name
542| Log.trace(sql)
543| Log.trace()
544| rs = self.crsr.execute(sql)
545| rx = 0
546| fout(['Group','Ticks','Balls','Frames','Slices'])
547| for rx,r in enumerate(rs):
548| fout(r)
549| return rx
550|
551| def list_history (self, fout=Log.info):
552| """List HISTORY data to the Log."""
553| assert self.is_open, RuntimeError('Database not open!')
554| sql = self.SqlList % self.tab1Name
555| Log.trace(sql)
556| Log.trace()
557| rs = self.crsr.execute(sql)
558| rx = 0
559| fout(['Group','Tick','bid','x','y','z', 'px','py','pz', 'cr','cg','cb'])
560| for rx,r in enumerate(rs):
561| fout(r)
562| return rx
563|
564| def list_collisions (self, fout=Log.info):
565| """List COLLISION data to the Log."""
566| assert self.is_open, RuntimeError('Database not open!')
567| sql = self.SqlList % self.tab2Name
568| Log.trace(sql)
569| Log.trace()
570| rs = self.crsr.execute(sql)
571| rx = 0
572| fout(['Group','Tick','b1id','b2id'])
573| for rx,r in enumerate(rs):
574| fout(r)
575| return rx
576|
577| def list_wall_collisions (self, fout=Log.info):
578| """List WALL-COLLISION data to the Log."""
579| assert self.is_open, RuntimeError('Database not open!')
580| sql = self.SqlList % self.tab3Name
581| Log.trace(sql)
582| Log.trace()
583| rs = self.crsr.execute(sql)
584| rx = 0
585| fout(['Group','Tick','bid'])
586| for rx,r in enumerate(rs):
587| fout(r)
588| return rx
589|
590|
591|
592| def set_ball_colors (scheme, ballset):
593| """Set ball color scheme."""
594|
595| if scheme == 'pool':
596| for bx,b in enumerate(ballset):
597| b.color = PoolBallConfig[b.bix % 16][0]
598| return
599| if scheme == 'rand':
600| for bx,b in enumerate(ballset):
601| b.color = RandColor()
602| return
603|
604| if scheme == 'cf1':
605| for bx,b in enumerate(ballset):
606| b.color = color_function_1(b.bix/len(ballset))
607| return
608|
609| if scheme == 'cf2':
610| for bx,b in enumerate(ballset):
611| b.color = color_function_2(b.bix/len(ballset))
612| return
613|
614| if scheme == 'mom':
615| for bx,b in enumerate(ballset):
616| if bx == 0:
617| b.color = ColorWhite
618| continue
619| b.color_momentum()
620| return
621|
622| if scheme == '10%':
623| for bx,b in enumerate(ballset):
624| b.color = ColorRed if b.bix==0 else (ColorWhite if (b.bix % 10) else ColorBlue)
625| return
626|
627| if scheme == 'half':
628| for bx,b in enumerate(ballset):
629| b.color = ColorWhite if b.bix==0 else (ColorRed if b.x < 0.0 else ColorBlue)
630| return
631|
632| if scheme == 'quad':
633| for bx,b in enumerate(ballset):
634| if 0 <= b.x:
635| if 0 <= b.y:
636|
637| b.color = ColorYellow
638| else:
639|
640| b.color = ColorBlue
641| else:
642| if 0 < b.y:
643|
644| b.color = ColorRed
645| else:
646|
647| b.color = ColorGreen
648| return
649|
650| return
651|
652|
653| def get_2d_ballset_special (walls, separation=2.0):
654| """Return a custom ballset."""
655| bs = [Ball2D() for _ in range(5)]
656| bs[0].bix = 0
657| bs[0].tag = 'Cue'
658| bs[0].x = walls[0]/2.0
659| bs[0].y = 0.0
660| bs[0].color = ColorWhite
661|
662| bs[1].bix = 1
663| bs[1].tag = '1'
664| bs[1].x = (walls[1]/2.0) - separation
665| bs[1].y = 0.0
666| bs[1].color = ColorRed
667|
668| bs[2].bix = 2
669| bs[2].tag = '2'
670| bs[2].x = (walls[1]/2.0)
671| bs[2].y = +separation
672| bs[2].color = ColorRed
673|
674| bs[3].bix = 3
675| bs[3].tag = '3'
676| bs[3].x = (walls[1]/2.0)
677| bs[3].y = -separation
678| bs[3].color = ColorRed
679|
680| bs[4].bix = 4
681| bs[4].tag = '4'
682| bs[4].x = (walls[1]/2.0) + separation
683| bs[4].y = 0.0
684| bs[4].color = ColorRed
685| return bs
686|
687|
688| def get_2d_ballset_pool (apex=(0.0, 0.0), separation=(1.0, 1.0)):
689| """Return standard pool triangular starting configuration."""
690| def NewBall (ix):
691| bcolor,bpos,btag = PoolBallConfig[ix]
692| bx = apex[0] + (separation[0] * bpos[0])
693| by = apex[1] + (separation[1] * bpos[1])
694| b = Ball2D(x=bx, y=by, color=bcolor, tag=btag)
695| b.bix = ix
696| return b
697|
698| return [NewBall(ix) for ix in range(16)]
699|
700|
701| def get_2d_ballset_grid (xgrid=(5,5), ygrid=(7,5), offset=(0,0)):
702| """Return a set of balls in a grid formation (rectangular)."""
703| ballset = [Ball2D(tag='Cue')]
704| for x in range(xgrid[0]):
705| for y in range(ygrid[0]):
706| bx = offset[0] + (x * xgrid[1])
707| by = offset[1] + (y * ygrid[1])
708| ball = Ball2D(x=bx, y=by)
709| ballset.append(ball)
710| for bx,b in enumerate(ballset):
711| b.bix = bx
712| return ballset
713|
714| def get_3d_ballset_grid (xgrid=(3,5), ygrid=(5,5), zgrid=(5,5), offset=(0,0,0)):
715| """Return a set of balls in a grid formation (rectangular)."""
716| ballset = []
717| for x in range(xgrid[0]):
718| for y in range(ygrid[0]):
719| for z in range(zgrid[0]):
720| bx = offset[0] + (x * xgrid[1])
721| by = offset[1] + (y * ygrid[1])
722| bz = offset[2] + (z * zgrid[1])
723| ball = Ball2D(x=bx, y=by, z=bz)
724| ballset.append(ball)
725| for bx,b in enumerate(ballset):
726| b.bix = bx
727| return ballset
728|
729| def get_2d_ballset_square (n_balls, p_max, offset=(0,0), separation=2.5):
730| """Return a set of balls with random momentums in a square formation."""
731| def NewBall (x, y):
732| bx = (offset[0]+(separation*x)) if offset[0]<0 else (offset[0]-(separation*x))
733| by = (offset[1]+(separation*y)) if offset[1]<0 else (offset[1]-(separation*y))
734| px = -p_max + (random() * (2*p_max))
735| py = -p_max + (random() * (2*p_max))
736| b = Ball2D(x=bx, y=by, px=px, py=py)
737| return b
738|
739| x_sqr = round(pow(n_balls, 1/2))
740| y_sqr = n_balls/x_sqr
741| y_sqr = int(y_sqr) if y_sqr==int(y_sqr) else int(y_sqr+1)
742|
743| ballset = [NewBall(x,y) for x in range(x_sqr) for y in range(y_sqr)]
744| for bx,b in enumerate(ballset):
745| b.bix = bx
746| return ballset[0:n_balls]
747|
748| def get_3d_ballset_square (n_balls, p_max, offset=(0,0,0), separation=2.5):
749| """Return a set of balls with random momentums in a cube formation."""
750| def NewBall (x, y, z):
751| bx = (offset[0]+(separation*x)) if offset[0]<0 else (offset[0]-(separation*x))
752| by = (offset[1]+(separation*y)) if offset[1]<0 else (offset[1]-(separation*y))
753| bz = (offset[2]+(separation*z)) if offset[2]<0 else (offset[2]-(separation*z))
754| px = -p_max + (random() * (2*p_max))
755| py = -p_max + (random() * (2*p_max))
756| pz = -p_max + (random() * (2*p_max))
757| b = Ball3D(x=bx, y=by, z=bz, px=px, py=py, pz=pz)
758| return b
759|
760| x_cube = round(pow(n_balls, 1/3))
761| r = n_balls/x_cube
762| y_cube = round(pow(r, 1/2))
763| z_cube = r/y_cube
764| z_cube = int(z_cube) if z_cube==int(z_cube) else int(z_cube+1)
765|
766| ballset = [NewBall(x,y,z) for x in range(x_cube) for y in range(y_cube) for z in range(z_cube)]
767| for bx,b in enumerate(ballset):
768| b.bix = bx
769| return ballset[0:n_balls]
770|
771|
772| def get_2d_ballset_random (n_balls, p_max, walls, min_separation=2.5, wall_separation=1.5, max_tries=1000):
773| """Return a set of balls with random positions and momentums."""
774| xmin = walls[0] + wall_separation
775| xmax = walls[1] - wall_separation
776| ymin = walls[2] + wall_separation
777| ymax = walls[3] - wall_separation
778| def Rando (ix):
779| bx = xmin + (random() * (xmax-xmin))
780| by = ymin + (random() * (ymax-ymin))
781| px = -p_max + (random() * (2*p_max))
782| py = -p_max + (random() * (2*p_max))
783| b = Ball2D(x=bx, y=by, px=px, py=py, color=RandColor())
784| return b
785| ballset = []
786|
787| for ix in range(n_balls):
788|
789| if ix == 0:
790| ballset.append(Rando(ix))
791| continue
792|
793| for tries in range(max_tries):
794| this_ball = Rando(ix)
795|
796| min_sep = min([this_ball.distance(b) for b in ballset])
797|
798| if min_separation < min_sep:
799| break
800|
801|
802| if min_separation < min_sep:
803|
804| ballset.append(this_ball)
805| Log.trace('%3d[%05d]: minimum-separation=%.3f (tries=%d)' % (ix, this_ball.bid, min_sep, tries))
806| else:
807| Log.error('Unable to place ball at safe distance!')
808| raise RuntimeError('Unable to place ball at safe distance!')
809| Log.trace()
810| for bx,b in enumerate(ballset):
811| b.bix = bx
812| return ballset
813|
814| def get_3d_ballset_random (n_balls, p_max, walls, min_separation=2.5, wall_separation=1.5, max_tries=1000):
815| """Return a set of balls with random positions and momentums."""
816| xmin = walls[0] + wall_separation
817| xmax = walls[1] - wall_separation
818| ymin = walls[2] + wall_separation
819| ymax = walls[3] - wall_separation
820| zmin = walls[4] + wall_separation
821| zmax = walls[5] - wall_separation
822| def Rando (ix):
823| bx = xmin + (random() * (xmax-xmin))
824| by = ymin + (random() * (ymax-ymin))
825| bz = zmin + (random() * (zmax-zmin))
826| px = -p_max + (random() * (2*p_max))
827| py = -p_max + (random() * (2*p_max))
828| pz = -p_max + (random() * (2*p_max))
829| b = Ball3D(x=bx, y=by, z=bz, px=px, py=py, pz=pz, color=RandColor())
830| return b
831| ballset = []
832|
833| for ix in range(n_balls):
834|
835| if ix == 0:
836| ballset.append(Rando(ix))
837| continue
838|
839| for tries in range(max_tries):
840| this_ball = Rando(ix)
841|
842| min_sep = min([this_ball.distance(b) for b in ballset])
843|
844| if min_separation < min_sep:
845| break
846|
847| if min_separation < min_sep:
848|
849| ballset.append(this_ball)
850| Log.trace('%3d[%05d]: minimum-separation=%.3f (tries=%d)' % (ix, this_ball.bid, min_sep, tries))
851| else:
852| Log.error('Unable to place ball at safe distance!')
853| raise RuntimeError('Unable to place ball at safe distance!')
854| Log.trace()
855| for bx,b in enumerate(ballset):
856| b.bix = bx
857| return ballset
858|
859|
860| def get_2d_ballset (mode, n_balls, walls):
861| if mode == 'rand':
862| return get_2d_ballset_random(n_balls, 200, walls=walls)
863| if mode == 'grid':
864| return get_2d_ballset_grid (xgrid=(5,5), ygrid=(7,5), offset=(+10,-15))
865| if mode == 'square':
866| return get_2d_ballset_square(n_balls, 120, offset=(-12,-12), separation=2.0)
867| if mode == 'pool':
868| return get_2d_ballset_pool(apex=(walls[1]/2, 0))
869| if mode == 'spcl':
870| return get_2d_ballset_special(walls)
871| raise RuntimeError('Invalid mode (%s)' % mode)
872|
873|
874| def get_3d_ballset (mode, n_balls, walls):
875| if mode == 'rand':
876| return get_3d_ballset_random(n_balls, 60, walls=walls)
877| if mode == 'grid':
878| return get_3d_ballset_grid (xgrid=(5,5), ygrid=(7,5), offset=(+10,-15))
879| if mode == 'square':
880| return get_3d_ballset_square(n_balls, 0, offset=(walls[0]+2, walls[2]+2, walls[4]+2), separation=5.0)
881| raise RuntimeError('Invalid mode (%s)' % mode)
882|
883|
884| def collision_check_2d (tk, b1, b2, check=True):
885| """Process two balls that have intersected.
885| (New and Improved! 11 lines replaced 57! Look, Ma, no quadrants!!)
885|
885| This builds two rotation matrices, one that rotates the momentum vectors
885| of the balls such that the collision normal axis (a line intersecting the
885| ball centers) is parallel to the X-axis; one that rotates the momentum
885| vectors back to their original orientations. This allows us to simply
885| exchange the X-axis components of the respective momentums.
885|
885| Returns the two matrices.
885| """
886| dist = b1.distance(b2)
887| if check and (2.0 < dist):
888| return ()
889| Log.info('[%d]Collision: %f' % (tk, 2.0-dist))
890| Log.info('Ball1: %s' % b1)
891| Log.info('Ball2: %s' % b2)
892| tpa = (b1.momentum()+b2.momentum()).magnitude()
893| Log.info('T-momentum: %s' % tpa)
894| mx = (b2.x - b1.x) / dist
895| my = (b2.y - b1.y) / dist
896| Log.info('distance: %s' % dist)
897| Log.trace('mx,my: [%+f, %+f]' % (mx,my))
898|
899| ma = matrix2d([mx,+my,-my,mx])
900| mb = matrix2d([mx,-my,+my,mx])
901| Log.trace('Matrix-a: %s' % ma)
902| Log.trace('Matrix-b: %s' % mb)
903|
904| vtb1 = ma * mvector2d(b1.x, b1.y)
905| vtb2 = ma * mvector2d(b2.x, b2.y)
906| vtp1 = ma * mvector2d(b1.px, b1.py)
907| vtp2 = ma * mvector2d(b2.px, b2.py)
908| Log.trace('b1-transformed: %s' % vtb1)
909| Log.trace('b2-transformed: %s' % vtb2)
910| Log.trace('p1-transformed: %s' % vtp1)
911| Log.trace('p2-transformed: %s' % vtp2)
912|
913| dx_old = abs((vtb1.x+vtp1.x) - (vtb2.x+vtp2.x))
914| dx_new = abs((vtb1.x+vtp2.x) - (vtb2.x+vtp1.x))
915| Log.trace('dx-old/new: %s, %s' % (dx_old,dx_new))
916| if dx_new <= dx_old:
917| Log.warn('FALSE POSITIVE! Ignoring collision! (%d, %d)' % (b1.bix, b2.bix))
918| Log.info('Ball1: %s' % b1)
919| Log.info('Ball2: %s' % b2)
920| Log.info('distance: %s' % b1.distance(b2))
921| Log.info()
922| return (ma,mb)
923|
924| vtp1s = mvector2d(vtp2.x, vtp1.y)
925| vtp2s = mvector2d(vtp1.x, vtp2.y)
926| vrp1 = mb * vtp1s
927| vrp2 = mb * vtp2s
928| Log.trace('p1-swapped: %s' % vtp1s)
929| Log.trace('p2-swapped: %s' % vtp2s)
930| Log.trace('p1-restored: %s' % vrp1)
931| Log.trace('p2-restored: %s' % vrp2)
932|
933| dt = (2.0 - dist) / (abs(vtp1.x) + abs(vtp2.x))
934| Log.trace('dt: %s' % dt)
935|
936|
937|
938|
939| b1.move(-dt)
940| b2.move(-dt)
941|
942| b1.px = vrp1.x
943| b1.py = vrp1.y
944| b2.px = vrp2.x
945| b2.py = vrp2.y
946|
947| b1.move(+dt)
948| b2.move(+dt)
949| Log.info('Ball1: %s' % b1)
950| Log.info('Ball2: %s' % b2)
951| tpb = (b1.momentum()+b2.momentum()).magnitude()
952| Log.info('T-momentum: %s (diff: %s)' % (tpb, tpb-tpa))
953| Log.info('new-distance: %s' % b1.distance(b2))
954| Log.info()
955|
956| return (ma,mb)
957|
958| def collision_check_3d (tk, b1, b2, check=True):
959| """Process two balls that have intersected. In 3D!
959|
959| This is similar to the 2D version, but builds four matrices because rotating
959| a 3D momentum vector to be parallel with the X-axis requires two rotations.
959| The first swings the vector on the Y-axis so its projection aligns with the
959| X-axis (but may be pointing up or down relative to it). The second swings it
959| on the Z-axis to bring it down or up to the X-axis.
959|
959| Restoring the momentum vectors works the opposite way. First a counter rotation
959| on the Z-axis to restore the elevation, and then a counter rotation on the
959| Y-axis to fully restore the original orientation.
959| """
960| dist = b1.distance(b2)
961| if check and (2.0 < dist):
962| return ()
963| Log.info('[%d]Collision: %f' % (tk, 2.0-dist))
964| Log.info('Ball1: %s' % b1)
965| Log.info('Ball2: %s' % b2)
966| dx = b2.x - b1.x
967| dy = b2.y - b1.y
968| dz = b2.z - b1.z
969| nx = dx / dist
970| ny = dy / dist
971| nz = dz / dist
972|
973| phi_sin = dy / dist
974| phi_cos = sqrt(pow(dx,2)+pow(dz,2)) / dist
975| theta_sin = dz / sqrt(pow(dx,2)+pow(dz,2))
976| theta_cos = dx / sqrt(pow(dx,2)+pow(dz,2))
977| Log.debug('distance: %f' % dist)
978| Log.trace('dx,dy,dz: [%+f, %+f, %+f]' % (dx,dy,dz))
979| Log.trace('nx,ny,nz: [%+f, %+f, %+f]' % (nx,ny,nz))
980| Log.trace('phi: (%f, %f)' % (phi_cos,phi_sin))
981| Log.trace('theta: (%f, %f)' % (theta_cos,theta_sin))
982|
983|
984| ma = matrix3d([theta_cos,0,theta_sin, 0,1,0, -theta_sin,0,theta_cos])
985|
986| mc = matrix3d([-theta_cos,0,theta_sin, 0,1,0, -theta_sin,0,-theta_cos])
987|
988|
989| mb = matrix3d([phi_cos,phi_sin,0, -phi_sin,phi_cos,0, 0,0,1])
990|
991| md = matrix3d([-phi_cos,phi_sin,0, -phi_sin,-phi_cos,0, 0,0,1])
992| Log.trace('Matrix-a: %s' % str(ma.m))
993| Log.trace('Matrix-b: %s' % str(mc.m))
994| Log.trace('Matrix-c: %s' % str(mb.m))
995| Log.trace('Matrix-d: %s' % str(md.m))
996|
997| vb1 = mvector3d(b1.x, b1.y, b1.z)
998| vb2 = mvector3d(b2.x, b2.y, b2.z)
999| vbta1 = ma * vb1
1000| vbta2 = ma * vb2
1001| vbtb1 = mb * vbta1
1002| vbtb2 = mb * vbta2
1003| Log.trace('ball1: %s' % vb1)
1004| Log.trace('ball2: %s' % vb2)
1005| Log.trace('b1-transformed-a: %s' % vbta1)
1006| Log.trace('b2-transformed-a: %s' % vbta2)
1007| Log.trace('b1-transformed-b: %s' % vbtb1)
1008| Log.trace('b2-transformed-b: %s' % vbtb2)
1009|
1010| vp1 = mvector3d(b1.px, b1.py, b1.pz)
1011| vp2 = mvector3d(b2.px, b2.py, b2.pz)
1012| vpta1 = ma * vp1
1013| vpta2 = ma * vp2
1014| vptb1 = mb * vpta1
1015| vptb2 = mb * vpta2
1016| Log.trace('momentum1: %s' % vp1)
1017| Log.trace('momentum2: %s' % vp2)
1018| Log.trace('p1-transformed-a: %s' % vpta1)
1019| Log.trace('p2-transformed-a: %s' % vpta2)
1020| Log.trace('p1-transformed-b: %s' % vptb1)
1021| Log.trace('p2-transformed-b: %s' % vptb2)
1022|
1023| dx_old = abs((vbtb1.x+vptb1.x) - (vbtb2.x+vptb2.x))
1024| dx_new = abs((vbtb1.x+vptb2.x) - (vbtb2.x+vptb1.x))
1025| Log.trace('dx-old/new: %f, %f' % (dx_old,dx_new))
1026| if dx_new <= dx_old:
1027| Log.warn('FALSE POSITIVE! Ignoring collision! (%d, %d)' % (b1.bix, b2.bix))
1028| Log.info('Ball1: %s' % b1)
1029| Log.info('Ball2: %s' % b2)
1030| Log.debug('distance: %f' % b1.distance(b2))
1031| Log.info()
1032| return (ma,mb,mc,md)
1033|
1034| px_temp = vptb1.x
1035| vptb1.x = vptb2.x
1036| vptb2.x = px_temp
1037|
1038| vpra1 = mc * vptb1
1039| vpra2 = mc * vptb2
1040| vprb1 = md * vpra1
1041| vprb2 = md * vpra2
1042| Log.trace('p1-restored-a: %s' % vpra1)
1043| Log.trace('p2-restored-a: %s' % vpra2)
1044| Log.trace('p1-restored-b: %s' % vprb1)
1045| Log.trace('p2-restored-b: %s' % vprb2)
1046|
1047| dt = (2.0 - dist) / (abs(vptb1.x) + abs(vptb2.x))
1048| Log.trace('dt: %f' % dt)
1049|
1050|
1051|
1052|
1053|
1054|
1055|
1056| b1.move(-dt)
1057| b2.move(-dt)
1058|
1059| b1.px = vprb1.x
1060| b1.py = vprb1.y
1061| b1.pz = vprb1.z
1062| b2.px = vprb2.x
1063| b2.py = vprb2.y
1064| b2.pz = vprb2.z
1065|
1066| b1.move(+dt)
1067| b2.move(+dt)
1068| Log.info('Ball1: %s' % b1)
1069| Log.info('Ball2: %s' % b2)
1070| Log.debug('new-distance: %f' % b1.distance(b2))
1071| Log.info()
1072|
1073| return (ma,mb,mc,md)
1074|
1075|
1076| def run (ballset, n_ticks, framerate, pscale, filename, x_mom=False):
1077| """Run the clock. (x-mom: enable momentum coloring)"""
1078| n_balls = len(ballset)
1079|
1080|
1081| db = DataBase()
1082| db.create_tables()
1083| db.open()
1084| db.stats(n_ticks, n_balls, framerate, pscale)
1085|
1086|
1087| for b in ballset:
1088|
1089| if x_mom:
1090| b.color_momentum()
1091|
1092| db.history(0, b)
1093| Log.info(b)
1094| Log.info()
1095|
1096|
1097| for tk in range(n_ticks):
1098| for bx,b1 in enumerate(ballset):
1099|
1100| b1.move()
1101|
1102| nw = b1.wall_check(tk)
1103| if 0 < nw:
1104| db.wall_collision(tk+1, b1)
1105|
1106| for b2 in ballset[bx+1:]:
1107| ms = collision_check_2d(tk, b1,b2)
1108| if 0 < len(ms):
1109| db.collision(tk+1, b1, b2)
1110|
1111| if x_mom:
1112| b1.color_momentum()
1113|
1114| db.history(tk+1, b1)
1115|
1116| if (tk % framerate) == 0:
1117| print(tk)
1118| Log.info()
1119|
1120|
1121| db.write_pov_file(filename, framerate, len(ballset), (n_ticks/framerate))
1122| db.close()
1123| Log.info()
1124|
1125|
1126|
1127| def do_pool_table (**kwargs):
1128| """CMND: RUN 2D Pool Ball Simulation -- Normal 16 balls."""
1129| povpath = KWARG('fpath', AnimPath, str, kwargs)
1130| povname = KWARG('fname', 'balls-2d', str, kwargs)
1131| n_ticks = KWARG('n', 1500, int, kwargs)
1132| framer = KWARG('fr', 15, int, kwargs)
1133| pscale = KWARG('ps', 2000, int, kwargs)
1134| wxn = KWARG('wxn', -40.0, float, kwargs)
1135| wxp = KWARG('wxp', +40.0, float, kwargs)
1136| wyn = KWARG('wyn', -22.5, float, kwargs)
1137| wyp = KWARG('wyp', +22.5, float, kwargs)
1138| walls = (wxn, wxp, wyn, wyp)
1139| filename = path.join(povpath, '%s.dat' % povname)
1140| Log.info('RUN/PoolTable:: %s' % str(list(kwargs.keys())))
1141| Log.debug('povpath="%s"' % povpath)
1142| Log.debug('povname="%s"' % povname)
1143| Log.debug('filename="%s"' % filename)
1144| Log.debug('number-of-ticks=%d' % n_ticks)
1145| Log.debug('framerate=%d' % framer)
1146| Log.debug('momentum-scaling=%d' % pscale)
1147| Log.debug('walls=%.2f, %.2f, %.2f, %.2f' % walls)
1148| Log.info()
1149| Ball2D.ScaleFactor = pscale
1150| Ball2D.Wall_XN = walls[0]
1151| Ball2D.Wall_XP = walls[1]
1152| Ball2D.Wall_YN = walls[2]
1153| Ball2D.Wall_YP = walls[3]
1154|
1155|
1156| ballset = get_2d_ballset_pool(apex=(walls[1]/2, 0), separation=(1.01,1.01))
1157|
1158|
1159| u,v = PoolBallConfig[7][1]
1160| aim = vector((wxp/2)+u, v)
1161|
1162| cue = vector(wxn/2, 0)
1163| shot = (aim - cue).unit() * 300
1164| b = ballset[0]
1165| b.x = cue.x
1166| b.y = cue.y
1167| b.set_momentum(shot.x, shot.y)
1168| Log.info('Cue-Ball-Position: (%f, %f)' % (b.x, b.y))
1169| Log.info('Cue-Ball-Speed: %f' % b.speed())
1170|
1171|
1172| run(ballset, n_ticks, framer, pscale, filename)
1173| Log.info()
1174| return 'Done'
1175|
1176|
1177| def do_run_2d (**kwargs):
1178| """CMND: RUN 2D Pool Ball Simulation."""
1179| povpath = KWARG('fpath', AnimPath, str, kwargs)
1180| povname = KWARG('fname', 'balls-2d', str, kwargs)
1181| b_mode = KWARG('/b', 'rand', str, kwargs)
1182| c_mode = KWARG('/c', 'rand', str, kwargs)
1183| n_balls = KWARG('b', 16, int, kwargs)
1184| n_ticks = KWARG('n', 1500, int, kwargs)
1185| framer = KWARG('fr', 15, int, kwargs)
1186| pscale = KWARG('ps', 2000, int, kwargs)
1187| wxn = KWARG('wxn', -40.0, float, kwargs)
1188| wxp = KWARG('wxp', +40.0, float, kwargs)
1189| wyn = KWARG('wyn', -22.5, float, kwargs)
1190| wyp = KWARG('wyp', +22.5, float, kwargs)
1191| walls = (wxn, wxp, wyn, wyp)
1192| filename = path.join(povpath, '%s.dat' % povname)
1193| Log.info('RUN/2D:: %s' % str(list(kwargs.keys())))
1194| Log.debug('povpath="%s"' % povpath)
1195| Log.debug('povname="%s"' % povname)
1196| Log.debug('filename="%s"' % filename)
1197| Log.debug('ballset-mode="%s"' % b_mode)
1198| Log.debug('color-mode="%s"' % c_mode)
1199| Log.debug('number-of-balls=%d' % n_balls)
1200| Log.debug('number-of-ticks=%d' % n_ticks)
1201| Log.debug('framerate=%d' % framer)
1202| Log.debug('momentum-scaling=%d' % pscale)
1203| Log.debug('walls=%.2f, %.2f, %.2f, %.2f' % walls)
1204| Log.info()
1205| Ball2D.ScaleFactor = pscale
1206| Ball2D.Wall_XN = walls[0]
1207| Ball2D.Wall_XP = walls[1]
1208| Ball2D.Wall_YN = walls[2]
1209| Ball2D.Wall_YP = walls[3]
1210|
1211|
1212| ballset = get_2d_ballset(b_mode, n_balls, walls)
1213|
1214| set_ball_colors(c_mode, ballset)
1215| for b in ballset:
1216| Log.info(b)
1217| Log.info()
1218|
1219|
1220|
1221|
1222|
1223|
1224|
1225|
1226|
1227|
1228|
1229|
1230|
1231| aim = vector(wxp/2, 0)
1232| cue = vector(wxn/2, +2)
1233| shot = (aim - cue).unit() * 333
1234| b = ballset[0]
1235| b.x = cue.x
1236| b.y = cue.y
1237| b.set_momentum(shot.x, shot.y)
1238| Log.info('Cue-Ball-Position: (%f, %f)' % (b.x, b.y))
1239| Log.info('Cue-Ball-Speed: %f' % b.speed())
1240|
1241|
1242| run(ballset, n_ticks, framer, pscale, filename, x_mom=False)
1243| Log.info()
1244| return 'Done'
1245|
1246|
1247| def do_run_3d (**kwargs):
1248| """CMND: RUN 3D Pool Ball Simulation. (REMEMBER: y=vertical!)"""
1249| povpath = KWARG('fpath', AnimPath, str, kwargs)
1250| povname = KWARG('fname', 'balls-3d', str, kwargs)
1251| b_mode = KWARG('/b', 'rand', str, kwargs)
1252| c_mode = KWARG('/c', 'rand', str, kwargs)
1253| n_balls = KWARG('b', 42, int, kwargs)
1254| n_ticks = KWARG('n', 1000, int, kwargs)
1255| framer = KWARG('fr', 15, int, kwargs)
1256| pscale = KWARG('ps', 2000, int, kwargs)
1257| wxp = KWARG('wxp', +40.0, float, kwargs)
1258| wxn = KWARG('wxn', -40.0, float, kwargs)
1259| wyp = KWARG('wyp', +22.5, float, kwargs)
1260| wyn = KWARG('wyn', -22.5, float, kwargs)
1261| wzp = KWARG('wzp', +30.0, float, kwargs)
1262| wzn = KWARG('wzn', -30.0, float, kwargs)
1263| walls = (wxn, wxp, wyn, wyp, wzn, wzp)
1264| filename = path.join(povpath, '%s.dat' % povname)
1265| Log.info('RUN/3D:: %s' % str(list(kwargs.keys())))
1266| Log.debug('povpath="%s"' % povpath)
1267| Log.debug('povname="%s"' % povname)
1268| Log.debug('filename="%s"' % filename)
1269| Log.debug('ballset-mode="%s"' % b_mode)
1270| Log.debug('color-mode="%s"' % c_mode)
1271| Log.debug('number-of-balls=%d' % n_balls)
1272| Log.debug('number-of-ticks=%d' % n_ticks)
1273| Log.debug('framerate=%d' % framer)
1274| Log.debug('momentum-scaling=%d' % pscale)
1275| Log.debug('walls=%.2f, %.2f, %.2f, %.2f, %.2f, %.2f' % walls)
1276| Log.info()
1277| Ball3D.ScaleFactor = pscale
1278| Ball3D.Wall_XN = walls[0]
1279| Ball3D.Wall_XP = walls[1]
1280| Ball3D.Wall_YN = walls[2]
1281| Ball3D.Wall_YP = walls[3]
1282| Ball3D.Wall_ZN = walls[4]
1283| Ball3D.Wall_ZP = walls[5]
1284|
1285|
1286| ballset = get_3d_ballset(b_mode, n_balls, walls)
1287|
1288| set_ball_colors(c_mode, ballset)
1289|
1290| aim = vector(wxn, wyn, wzn)
1291| cue = vector(wxp-2, wyp-2, wzp-2)
1292| shot = (aim - cue).unit() * 300
1293| b = ballset[0]
1294| b.x = cue.x
1295| b.y = cue.y
1296| b.z = cue.z
1297| b.set_momentum(shot.x, shot.y, shot.z)
1298| Log.info('Cue-Ball-Position: (%f, %f, %f)' % (b.x, b.y, b.z))
1299| Log.info('Cue-Ball-Speed: %f' % b.speed())
1300| Log.info()
1301|
1302|
1303| run(ballset, n_ticks, framer, pscale, filename, x_mom=False)
1304| Log.info()
1305| return 'Done'
1306|
1307|
1308| def do_reverse_2d (**kwargs):
1309| """CMND: RUN Reverse 2D Pool Ball Simulation."""
1310| dbpath = KWARG('dpath', DataPath, str, kwargs)
1311| dbname = KWARG('db', 'poolballs', str, kwargs)
1312| povpath = KWARG('fpath', AnimPath, str, kwargs)
1313| povname = KWARG('fname', 'balls-2d', str, kwargs)
1314| wxn = KWARG('wxn', -40.0, float, kwargs)
1315| wxp = KWARG('wxp', +40.0, float, kwargs)
1316| wyn = KWARG('wyn', -22.5, float, kwargs)
1317| wyp = KWARG('wyp', +22.5, float, kwargs)
1318| walls = (wxn, wxp, wyn, wyp)
1319| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1320| filename = path.join(povpath, '%s.dat' % povname)
1321| Log.info('RUN/Reverse-2D:: %s' % str(list(kwargs.keys())))
1322| Log.debug('dbfilename="%s"' % dbfilename)
1323| Log.debug('dbpath="%s"' % dbpath)
1324| Log.debug('dbname="%s"' % dbname)
1325| Log.debug('filename="%s"' % filename)
1326| Log.debug('povpath="%s"' % povpath)
1327| Log.debug('povname="%s"' % povname)
1328| Log.debug('walls=%.2f, %.2f, %.2f, %.2f' % walls)
1329| Log.info()
1330|
1331|
1332| db2 = DataBase(dbfilename)
1333| db2.open()
1334| stats = db2.get_stats()
1335| db2.close()
1336| n_ticks = stats[1]
1337| n_balls = stats[2]
1338| framer = stats[3]
1339| pscale = stats[4]
1340| Ball2D.ScaleFactor = pscale
1341| Ball2D.Wall_XN = walls[0]
1342| Ball2D.Wall_XP = walls[1]
1343| Ball2D.Wall_YN = walls[2]
1344| Ball2D.Wall_YP = walls[3]
1345| Log.debug('poolballs: %d' % n_balls)
1346| Log.debug('timeticks: %d' % n_ticks)
1347| Log.debug('framerate: %d' % framer)
1348| Log.debug('p-scaling: %d' % pscale)
1349| Log.debug()
1350|
1351|
1352| db2.open()
1353| sql = 'SELECT * FROM "%s" ORDER BY 1,2 DESC,3' % db2.tab1Name
1354| Log.trace(sql)
1355| Log.trace()
1356| rs = db2.crsr.execute(sql)
1357| tk = 0
1358| ballset = []
1359| for rcd in rs:
1360| if rcd[1] != tk:
1361| if tk == 0:
1362| tk = rcd[1]
1363| else:
1364| break
1365|
1366| b = Ball2D(x=rcd[3],y=rcd[4])
1367| b.px = -rcd[6]
1368| b.py = -rcd[7]
1369| b.color = (rcd[9], rcd[10], rcd[11])
1370| b.bix = rcd[2]
1371| ballset.append(b)
1372| Log.info(rcd)
1373| Log.info()
1374| db2.close()
1375|
1376|
1377| run(ballset, n_ticks, framer, pscale, filename)
1378|
1379| Log.info()
1380| return 'Done'
1381|
1382|
1383| def do_table_list (**kwargs):
1384| """CMND: List tables in a given database."""
1385| dbpath = KWARG('dpath', DataPath, str, kwargs)
1386| dbname = KWARG('db', 'poolballs', str, kwargs)
1387| fpath = KWARG('fpath', BasePath, str, kwargs)
1388| fname = KWARG('fname', 'poolballs', str, kwargs)
1389| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1390| filename = path.join(fpath, '%s_%s.list' % (fname,dbname[-12:]))
1391| Log.info('table-list:: %s' % str(list(kwargs.keys())))
1392| Log.debug('dbfilename="%s"' % dbfilename)
1393| Log.debug('filename="%s"' % filename)
1394| Log.info()
1395|
1396| spool = tabfile(filename)
1397| def spooler (txt=''):
1398| spool.data.append(txt)
1399|
1400| db = DataBase(dbfilename)
1401| db.open()
1402| try:
1403| spooler(['##','BEGIN', 'STATS'])
1404| db.list_stats(fout=spooler)
1405| spooler(['##', 'END', 'STATS'])
1406| spooler()
1407| spooler(['##','BEGIN', 'COLLISIONS'])
1408| db.list_collisions(fout=spooler)
1409| spooler(['##', 'END', 'COLLISIONS'])
1410| spooler()
1411| spooler(['##','BEGIN', 'WALL COLLISIONS'])
1412| db.list_wall_collisions(fout=spooler)
1413| spooler(['##', 'END', 'WALL COLLISIONS'])
1414| spooler()
1415| spooler(['##','BEGIN', 'HISTORY'])
1416| db.list_history(fout=spooler)
1417| spooler(['##', 'END', 'HISTORY'])
1418| spooler()
1419| except:
1420| raise
1421| finally:
1422| db.close()
1423| Log.info()
1424| spool.save()
1425| Log.info()
1426| return 'Done'
1427|
1428|
1429| def do_table_pov_file (**kwargs):
1430| """CMND: Generate the POV-Ray file from a given database."""
1431| dbpath = KWARG('dpath', DataPath, str, kwargs)
1432| dbname = KWARG('db', 'poolballs', str, kwargs)
1433| fpath = KWARG('fpath', BasePath, str, kwargs)
1434| fname = KWARG('fname', 'poolballs', str, kwargs)
1435| frm_rat_ov = KWARG('fro', -1, int, kwargs)
1436| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1437| filename = path.join(fpath, '%s.dat' % fname)
1438| Log.info('table-POV-file:: %s' % str(list(kwargs.keys())))
1439| Log.debug('dbfilename="%s"' % dbfilename)
1440| Log.debug('filename="%s"' % filename)
1441| Log.debug('frame-rate-override=%d' % frm_rat_ov)
1442| Log.info()
1443|
1444|
1445| db = DataBase(dbfilename)
1446| db.open()
1447| try:
1448| rcd = db.get_stats()
1449| Log.info('Group-Id: %s' % rcd[0])
1450| Log.info('Ticks: %s' % rcd[1])
1451| Log.info('Balls: %s' % rcd[2])
1452| Log.info('Frames: %s' % rcd[3])
1453| Log.info('Slices: %s' % rcd[4])
1454| Log.info()
1455|
1456| framerate = rcd[3] if frm_rat_ov < 0 else frm_rat_ov
1457| db.write_pov_file(filename, framerate, rcd[2], (rcd[1]/framerate))
1458| except:
1459| raise
1460| finally:
1461|
1462| db.close()
1463|
1464| Log.info()
1465| return 'Done'
1466|
1467|
1468| def do_scan_history (**kwargs):
1469| """CMND: Scan the history table in a database and do math stuff with the data."""
1470| dbpath = KWARG('dpath', DataPath, str, kwargs)
1471| dbname = KWARG('db', 'poolballs', str, kwargs)
1472| fpath = KWARG('fpath', BasePath, str, kwargs)
1473| fname = KWARG('fname', 'poolballs', str, kwargs)
1474| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1475| filename = path.join(fpath, '%s_%s.out' % (fname,dbname[-12:]))
1476| Log.info('scan-history-table:: %s' % str(list(kwargs.keys())))
1477| Log.debug('dbfilename="%s"' % dbfilename)
1478| Log.debug('filename="%s"' % filename)
1479| Log.info()
1480| hdrs = ['Group','Tick','bid','x','y','z', 'px','py','pz', 'cr','cg','cb']
1481|
1482|
1483| db = DataBase(dbfilename)
1484| db.open()
1485|
1486| rcd = db.get_stats()
1487| Log.info('Balls: %s' % rcd[2])
1488| Log.info('Ticks/Frames: %s, %s' % (rcd[1],rcd[3]))
1489| Log.info('Slices: %s' % rcd[4])
1490| Log.info()
1491| try:
1492| sql = db.SqlList % db.tab1Name
1493| Log.trace(sql)
1494| Log.trace()
1495| rs = db.crsr.execute(sql)
1496| data = {}
1497| for rx,rcd in enumerate(rs):
1498| tk = rcd[1]
1499| bid = rcd[2]
1500| if tk not in data:
1501| data[tk] = vector(0.0, 0.0, 0.0)
1502| data[tk] += vector(rcd[6], rcd[7], rcd[8])
1503|
1504| fout = linefile(filename)
1505| last = None
1506| for datum in sorted(data):
1507| tmom = data[datum].magnitude()
1508| if last:
1509| if last == tmom:
1510|
1511| continue
1512| else:
1513| last = tmom
1514|
1515| fout.data.append('%5d: %s' % (datum, tmom))
1516| fout.save()
1517| Log.info()
1518| except:
1519| raise
1520| finally:
1521|
1522| db.close()
1523|
1524| Log.info()
1525| return 'Done'
1526|
1527|
1528| def do_table_sql (**kwargs):
1529| """CMND: Do an SQL query of some kind."""
1530| dbpath = KWARG('dpath', DataPath, str, kwargs)
1531| dbname = KWARG('db', 'poolballs', str, kwargs)
1532| fpath = KWARG('fpath', BasePath, str, kwargs)
1533| fname = KWARG('fname', 'test', str, kwargs)
1534| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1535| filename = path.join(fpath, '%s.out' % fname)
1536| Log.info('table-SQL:: %s' % str(list(kwargs.keys())))
1537| Log.debug('dbfilename="%s"' % dbfilename)
1538| Log.debug('filename="%s"' % filename)
1539| Log.info()
1540| SQL = 'SELECT * FROM "%s"'
1541|
1542| db = DataBase(dbfilename)
1543| db.open()
1544| try:
1545| sql = SQL % db.tab0Name
1546| Log.trace(sql)
1547| Log.trace()
1548| rs = db.crsr.execute(sql)
1549| for r in rs:
1550| print(r)
1551| Log.info(r)
1552| Log.info()
1553| except Exception as e:
1554| Log.error()
1555| Log.error(e)
1556| Log.error()
1557| finally:
1558| db.close()
1559| Log.info()
1560| return 'Done'
1561|
1562|
1563| def do_test (**kwargs):
1564| """CMND: Do a test of some kind."""
1565| dbpath = KWARG('dpath', DataPath, str, kwargs)
1566| dbname = KWARG('db', 'poolballs', str, kwargs)
1567| fpath = KWARG('fpath', BasePath, str, kwargs)
1568| fname = KWARG('fname', 'test', str, kwargs)
1569| n_ticks = KWARG('n', 1500, int, kwargs)
1570| framer = KWARG('fr', 15, int, kwargs)
1571| pscale = KWARG('ps', 2000, int, kwargs)
1572| dbfilename = path.join(dbpath, '%s.sqlite' % dbname)
1573| filename = path.join(fpath, '%s.dat' % fname)
1574| Log.info('test:: %s' % str(list(kwargs.keys())))
1575| Log.debug('dbfilename="%s"' % dbfilename)
1576| Log.debug('filename="%s"' % filename)
1577| Log.info()
1578|
1579| walls = (-40, +40, -22.5, +22.5)
1580|
1581| Ball2D.ScaleFactor = pscale
1582| Ball2D.Wall_XN = walls[0]
1583| Ball2D.Wall_XP = walls[1]
1584| Ball2D.Wall_YN = walls[2]
1585| Ball2D.Wall_YP = walls[3]
1586|
1587| ballset = [
1588| Ball2D(-5,0, 100,0, ColorWhite, 'A'),
1589| Ball2D(0,-5, 0,100, ColorRed , 'B')
1590| ]
1591| run(ballset, n_ticks, 1, pscale, filename, x_mom=False)
1592| Log.info()
1593| return 'Done'
1594|
1595| def dispatch (cmd, **kwargs):
1596| """Dispatch CMD to a function in the module."""
1597| Log.info('command: %s' % cmd)
1598| for kw in sorted(kwargs):
1599| Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
1600| Log.info()
1601| if cmd == 'pool': return do_pool_table(**kwargs)
1602| if cmd == '3d': return do_run_3d(**kwargs)
1603| if cmd == '2d': return do_run_2d(**kwargs)
1604| if cmd == '-2d': return do_reverse_2d(**kwargs)
1605| if cmd == '/his': return do_scan_history(**kwargs)
1606| if cmd == '/lst': return do_table_list(**kwargs)
1607| if cmd == '/sql': return do_table_sql(**kwargs)
1608| if cmd == '/pov': return do_table_pov_file(**kwargs)
1609| if cmd == 'test': return do_test(**kwargs)
1610| Log.info('BasePath: "%s"' % BasePath)
1611| Log.info('AnimPath: "%s"' % AnimPath)
1612| Log.info('DataPath: "%s"' % DataPath)
1613| Log.info('TS: %s' % TS)
1614| Log.info()
1615| return 'Nothing to do!'
1616|
1617| if __name__ == '__main__':
1618| print('autorun: %s' % argv[0])
1619| Log.start(path.join(BasePath,TimeStamp('poolballs_%s.log')))
1620|
1621| Log.level(info())
1622| Log.info(argv[0])
1623| Log.info()
1624| cmd = argv[1] if 1 < len(argv) else CMND
1625| kwargs = ARGS
1626| for a in argv[2:]:
1627| nv = a.split('=', 1)
1628| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
1629| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
1630| try:
1631| print('CMD: %s' % cmd)
1632| print()
1633| obj = dispatch(cmd, **kwargs)
1634| print()
1635| print(obj)
1636| Log.info()
1637| Log.info(obj)
1638| except:
1639| etype, evalue, tb = exc_info()
1640| ts = extract_tb(tb)
1641| Log.error()
1642| Log.error('%s: %s' % (etype.__name__,str(evalue)))
1643| Log.error()
1644| for t in ts[-5:]:
1645| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
1646| Log.error(' %s' % t[3])
1647| Log.error()
1648| raise
1649| finally:
1650| Log.end()
1651|
1652| '''eof'''
1653|