cubenet.html
001| '''Folding Cube Nets class.
001|
001| Implements net points and edges. The rotate function allows rotation of
001| specified points around another specified point. A code specifies the
001| axis and direction of rotation. Rotations are nominally 90 degrees, but
001| can be changed with the swing property.
001|
001| New Instance arguments:
001| config - Net configuration dictionary
001| props - Net properties dictionary
001|
001| Configuration (config) is a dictionary of point and edge definitions.
001| It consists of labeled net vertexes (the labels are the vertex keys).
001| Each vertex is a tuple: (x, y, z, [edge-connections])
001| The x,y,z components are the vertex location. The list of connections
001| names the vertexes connected to this one by edges. The names are the
001| same as the vertex keys (typically: 'a', 'b', 'c', etc).
001|
001| Properties (props) is a dictionary of special properties for tweaking
001| the behavior of the class methods. Defined properties include:
001|
001| nid - Net ID (expected but not required)
001| offset - vector for object translation
001| angles - vector for object rotation
001| translate - if present and true: use cn(offset) to translate net
001| rotate - if present and true: use cn(angles) to rotate net
001| facedefs - list of facedef tuples (p1,p2,p3,p4)
001| swing - angle of rotation (default is 90.0)
001| face.depth - height of face appexes (default is 0.10)
001|
001| Instance Attributes:
001| .net - dict of net points
001| .edges - dict of net edges
001| .props - dict of properties (see above)
001| .descriptions - dict of move descriptions
001| .frames - dict of rotation frames
001| .angle - angle of rotation
001| .steps - number of steps in rotation
001| .xs - the X-axis of rotation (linear)
001| .rm?? - rotation matrices (??=[xyz][np])
001| .facelists - list of face definitions
001| .face_depth - rise of face triangle apexes
001| .translate_ok - enables individual translate property
001| .rotate_ok - enables individual rotate property
001| .swing - angle of rotation (default is 90.0)
001|
001| Methods:
001| .points - (property) a list of vertex points
001| .lines - (property) a list of edge tuples (pt1,pt2)
001| .faces - (property) a list of faces (t1-t8)
001| obj(prop) - property named by prop
001|
001| .rotate - generate rotation points given a move description
001| .description - return a move description for a given point
001| - if propname given, return just the property
001| .feeder - return a list of labeled point iterators
001| e.g. [(pn,next(it)) for pn,it in cn.feeder()]
001| .first - (property) a list of the first rotation points
001| .last - (property) a list of the last rotation points
001| .frame - return a list of points for a given frame
001|
001| .pov_cubenet - Write POV-Ray file for the net
001| .pov_rotation - Write POV-Ray file for the rotation
001|
001| .prn_net - dump net point data to a stream (default: stdout)
001| .prn_edges - dump net edge data to a stream (default: stdout)
001| .prn_rotation_points - dump all rotation points
001| .prn_rotation_point - dump rotation points for a given point
001|
001| len(obj) - number of points in this net
001| obj[key] - vertex labeled by key (error if doesn't exist)
001| iter(obj) - iterator over the points in the net (sorted)
001| key in obj - true if key is a vertex key
001|
001| str(obj) - string listing all points (with labels)
001| repr(obj) - JSON-like string of crucial object properties
001| - (Note: debug only; not for object persistance)
001|
001| Class Data:
001| VertexRadius - radius of cube vertexes
001| EdgeRadius - radius of cube edges
001| FaceDepth - how far face appexes stick out
001| FaceDotRadius - radius of face appex dots
001| FaceColorSwx - color mode for faces [0=xyz, 1=gray, 2=dual]
001| Vface - (1,1,1) unit vector for color angle
001| Face?Color - colors for alternate face color modes
001| PointColor - default color for points
001|
001| Class Methods:
001| .pov_cubenet_list - POV-Ray file for a list of Cube Nets
001|
001| Global Data:
001| povData# -POV-Ray data file protocol codes, #=protocol command.
001|
001| Matrix Rotations (looking in minus direction along axis):
001| X: XP=CCW, XN=CW
001| Y: YP=CW , YN=CCW <<< note difference!
001| Z: ZP=CCW, ZN=CW
001|
001| TODO: Assign color to points (cubenet.PointColor)
001| '''
002|
003| from sys import stdout
004| from os import path
005| from logger import logger
006| from goodies import KWARG, typename, svec
007| from matrix import mvector3d, rotate3d_x, rotate3d_y, rotate3d_z
008| from vector import vector, VX, VY, VZ
009|
010| BasePath = r'C:\CJS\prj\Python\app\cubenets'
011| Log = logger('cubenet')
012|
013| cvec = lambda v:('<%.2f,%.2f,%.2f>' % (v[0], v[1], v[2]))
014|
015|
016| '''POV data file protocol.'''
017|
018| povData0 = '0,'
019|
020| povData1 = lambda gid,ix,a:('1, %d, %d, %.6f,' % (gid,ix,a))
021|
022| povData2 = lambda n,v1,c:('2, "%s", %s, %s,' % (n,svec(v1),cvec(c)))
023|
024| povData21 = lambda v1:('21, %.3f,' % v1)
025|
026| povData3 = lambda v1,v2,c:('3, %s, %s, %s,' % (svec(v1),svec(v2),cvec(c)))
027|
028| povData31 = lambda v1:('31, %.3f,' % v1)
029|
030| povData4 = lambda x,v1,v2,v3,c:('4, %+d, %s, %s, %s, %s,' % (x,svec(v1),svec(v2),svec(v3),cvec(c)))
031|
032| povData5 = lambda:('5,')
033|
034| povData6 = lambda:('6,')
035|
036| povData7 = lambda v1:('7, %s,' % svec(v1))
037|
038| povData8 = lambda v1:('8, %s,' % svec(v1))
039|
040| povData9 = '9,'
041|
042| povData90 = '90,'
043|
044| povData91 = lambda s:('91, "%s",' % s)
045|
046| povData92 = lambda s:('92, "%s", %s' % s)
047|
048| povData98 = lambda s:('98, "%s",' % s)
049|
050| povData99 = '99'
051|
052|
053| Black = (0.05, 0.04, 0.03)
054| Red = (0.90, 0.23, 0.11)
055| Green = (0.11, 0.90, 0.23)
056| Blue = (0.11, 0.23, 0.90)
057| Yellow = (0.90, 0.90, 0.11)
058| Cyan = (0.11, 0.90, 0.90)
059| Magenta = (0.90, 0.11, 0.90)
060| Silver = (0.90, 0.91, 0.98)
061|
062|
063|
064| class cubenet:
065| '''An Unfolding Cube Net class.'''
066| VertexRadius = 0.10
067| EdgeRadius = 0.05
068| FaceDepth = 0.25
069| FaceDotRadius = 0.02
070| FaceColorSwx = 0
071| Vface = (VX+VY+VZ).unit()
072| Face0Color = (0.68, 0.68, 0.68)
073| Face1Color = (0.50, 0.70, 0.90)
074| Face2Color = (0.90, 0.70, 0.50)
075| PointColor = Black
076|
077| def __init__ (self, config={}, props={}):
078| '''New cubenet instance. Expects a configuration dictionary.'''
079| self.net = {}
080| self.edges = {}
081| self.props = props
082| self.facelists = self('facedefs') if self('facedefs') else []
083| self.face_depth = self('face.depth') if self('face.depth') else cubenet.FaceDepth
084| self.translate_ok = False
085| self.rotate_ok = False
086| self.swing = self('swing') if self('swing') else 90.0
087|
088|
089| for ptname,vertex in config.items():
090| vec = mvector3d(*vertex[0:3])
091| self.net[ptname] = (vec, vertex[3])
092|
093|
094| watchdog = {}
095| for pt1name in self:
096| pt1def = self[pt1name]
097|
098| for pt2name in pt1def[1]:
099| pt2def = self[pt2name]
100|
101| edge_key = tuple(sorted([pt1name, pt2name]))
102|
103| if edge_key not in self.edges:
104| self.edges[edge_key] = [pt1def[0], pt2def[0]]
105| if edge_key not in watchdog:
106| watchdog[edge_key] = [pt1name]
107| else:
108| watchdog[edge_key].append(pt1name)
109|
110| Log.trace(watchdog)
111| for ek in watchdog:
112| if len(watchdog[ek]) == 2:
113| continue
114| raise RuntimeError('Invalid Edge: %s=%s' % (ek,watchdog[ek]))
115|
116| def __len__ (self): return len(self.net)
117| def __iter__ (self): return iter(sorted(self.net))
118| def __contains__ (self, key): return (key in self.net)
119| def __getitem__ (self, key): return self.net[key]
120|
121| def __call__ (self, propname):
122| '''Return named property (or None).'''
123| return self.props[propname] if propname in self.props else None
124|
125| @property
126| def points (self):
127| '''Return a list of points.'''
128| return [self[ptname][0] for ptname in self]
129|
130| @property
131| def lines (self):
132| '''Return a list of edges.'''
133| return [self.edges[ek] for ek in sorted(self.edges)]
134|
135| @property
136| def faces (self):
137| '''Return a list of faces.'''
138| buf = []
139| for facelist in self.facelists:
140|
141| corners = [self[pn][0] for pn in facelist]
142|
143| xmin = min([v.x for v in corners])
144| ymin = min([v.y for v in corners])
145| zmin = min([v.z for v in corners])
146| xmax = max([v.x for v in corners])
147| ymax = max([v.y for v in corners])
148| zmax = max([v.z for v in corners])
149|
150| xavg = ((xmax-xmin) / 2.0)
151| yavg = ((ymax-ymin) / 2.0)
152| zavg = ((zmax-zmin) / 2.0)
153|
154| va = vector(*corners[0])-vector(*corners[1])
155| vb = vector(*corners[0])-vector(*corners[3])
156| vc = va.cross(vb).unit() * self.face_depth
157|
158| vpcenter = mvector3d(xmin+xavg+vc.x, ymin+yavg+vc.y, zmin+zavg+vc.z)
159| vncenter = mvector3d(xmin+xavg-vc.x, ymin+yavg-vc.y, zmin+zavg-vc.z)
160|
161| face = [
162| (vpcenter,corners[0],corners[1]), (vpcenter,corners[1],corners[2]),
163| (vpcenter,corners[2],corners[3]), (vpcenter,corners[3],corners[0]),
164| (vncenter,corners[0],corners[1]), (vncenter,corners[1],corners[2]),
165| (vncenter,corners[2],corners[3]), (vncenter,corners[3],corners[0]),
166| ]
167| buf.append(face)
168| return buf
169|
170| @property
171| def angle2color (self):
172| '''Return f:angle->color'''
173| def color_from_angle (p1:mvector3d, p2:mvector3d):
174| '''Determine color from the angle between two vectors.'''
175|
176| p0 = vector(*(p2-p1).astuple()).unit()
177| match cubenet.FaceColorSwx:
178| case 1:
179| vc = cubenet.Face0Color
180| case 2:
181| q = cubenet.Vface.dot(p0)
182| vc = cubenet.Face1Color if 0 <= q else cubenet.Face2Color
183| case _:
184|
185| vc = (abs(VX.dot(p0)), abs(VY.dot(p0)), abs(VZ.dot(p0)))
186|
187| Log.trace()
188| Log.trace('ivec: %s' % str(p0))
189| Log.trace('cvec: %s' % str(vc))
190| return vc
191| return color_from_angle
192|
193| def rotate (self, move_desc={}, angle=1.0):
194| '''Rotate specified points around specified center point.'''
195| self.descriptions = dict(move_desc)
196| self.angle = angle
197| self.steps = int(1.0+(self.swing/self.angle))
198| self.xs = [(ix/float(self.steps-1)) for ix in range(self.steps)]
199| self.rmxp = rotate3d_x(+self.angle)
200| self.rmyp = rotate3d_y(+self.angle)
201| self.rmzp = rotate3d_z(+self.angle)
202| self.rmxn = rotate3d_x(-self.angle)
203| self.rmyn = rotate3d_y(-self.angle)
204| self.rmzn = rotate3d_z(-self.angle)
205| self.frames = {}
206|
207| for ptname in self.descriptions:
208| descr = self.descriptions[ptname]
209| rotmx = descr['matrix']
210| rotmx = getattr(self, 'rm%s' % rotmx)
211| pivpt = descr['pivot']
212|
213| vcenter = self[pivpt][0]
214|
215| vstart = self[ptname][0]
216|
217| vshift = vstart - vcenter
218|
219| lst = [vstart]
220|
221| for theta in self.xs[1:]:
222| p0 = lst[-1] - vcenter
223| p1 = (rotmx * p0) + vcenter
224| lst.append(p1)
225|
226| self.frames[ptname] = lst
227|
228| descr['@'] = 1
229| descr['name'] = ptname
230| descr['vstart'] = lst[0]
231| descr['vend'] = lst[-1]
232| descr['vcenter'] = vcenter
233| descr['vshift'] = vshift
234| descr['edges'] = self[ptname][1]
235|
236|
237| for ptname in self:
238| if ptname in self.descriptions:
239| continue
240|
241| pt = self[ptname][0]
242|
243| lst = [pt]*len(self.xs)
244|
245| self.frames[ptname] = lst
246|
247| self.descriptions[ptname] = {'@':0, 'name':ptname}
248| self.descriptions[ptname]['vstart'] = lst[0]
249| self.descriptions[ptname]['vend'] = lst[-1]
250| self.descriptions[ptname]['edges'] = self[ptname][1]
251|
252| def description (self, ptname, propname=None):
253| '''Return a rotation description (optionally, one of its properties).'''
254| if propname:
255|
256| return self.descriptions[ptname][propname]
257|
258| return self.descriptions[ptname]
259|
260| def feeder (self):
261| '''Return a list of (name,iter) tuples iterating over the rotation frames.'''
262| return [(pn,iter(self.frames[pn])) for pn in sorted(self.frames)]
263|
264| def frame (self, frame_index):
265| '''Return a specified rotation frame (by index).'''
266| return [(pn,self[pn][frame_index]) for pn in sorted(self.frames)]
267|
268| @property
269| def first (self):
270| '''Return the first frame in the rotation.'''
271| return [(pn,self[pn][0]) for pn in sorted(self.frames)]
272|
273| @property
274| def last (self):
275| '''Return the first frame in the rotation.'''
276| return [(pn,self[pn][-1]) for pn in sorted(self.frames)]
277|
278| def __str__ (self):
279| ss = ['(%s:%d,%d,%d)' % (pn,*self[pn][0]) for pn in self]
280| return ', '.join(ss)
281|
282| def __repr__ (self):
283| ftn = lambda pn:','.join(['%s'%en for en in self[pn][1]])
284| pts = ', '.join(['%s:[%d,%d,%d]' % (pn,*self[pn][0]) for pn in self])
285| lns = ', '.join(['_%s:[%s]' % (pn,ftn(pn)) for pn in self])
286| t = (typename(self), pts, lns)
287| s = '{%s:{%s, %s}}'
288| return s%t
289|
290| def prn_net (self, stream=stdout):
291| '''Print the points of the net.'''
292| for ptname in self:
293| ptdef = self[ptname]
294| es = ','.join(ptdef[1])
295| ss = '%s: %s [%s]' % (ptname, svec(ptdef[0]), es)
296| print(ss, file=stream)
297| Log.info(ss)
298| print(file=stream)
299| Log.info()
300|
301| def prn_edges (self, stream=stdout):
302| '''Print the edges of the net.'''
303| for ek in sorted(self.edges):
304| sv1 = svec(self.edges[ek][0])
305| sv2 = svec(self.edges[ek][1])
306| ss = '%s-%s: [%s--%s]' % (*ek, sv1,sv2)
307| print(ss, file=stream)
308| Log.info(ss)
309| print(file=stream)
310| Log.info()
311|
312| def prn_rotation_points (self, stream=stdout):
313| '''Print a list of all rotation points.'''
314| if stream is None:
315| from io import StringIO
316| stream = StringIO()
317|
318| for ptname in sorted(self.frames):
319| self.prn_rotation_point(ptname, stream=stream)
320| print(file=stream)
321| Log.debug()
322|
323| def prn_rotation_point (self, ptname, stream=stdout):
324| '''Print a listing of a given rotation point.'''
325| descr = self.description(ptname)
326| s1 = 'Point: %s' % ptname.upper()
327| s2 = '| vstart: %s (name: %s)' % (svec(descr['vstart']), descr['name'])
328| print(s1, file=stream)
329| print(s2, file=stream)
330| Log.debug(s1)
331| Log.debug(s2)
332|
333|
334| if descr['@']:
335| s1 = '| vpivot: %s (name: %s)' % (svec(descr['vcenter']), descr['pivot'])
336| s2 = '| vshift: %s' % svec(descr['vshift'])
337| print(s1, file=stream)
338| print(s2, file=stream)
339| Log.debug(s1)
340| Log.debug(s2)
341|
342|
343| s1 = '| number-of-points: %d' % len(self.frames)
344| print(s1, file=stream)
345| Log.debug(s1)
346|
347| for ix,pt in enumerate(self.frames):
348| pts = self.frames[pt]
349| s2 = '|%3d: %s' % (ix,pts)
350| print(s2, file=stream)
351| Log.debug(s2)
352|
353| print(file=stream)
354| Log.debug()
355|
356| def pov_cubenet (self, fname='cubenet-%s.dat', fpath=BasePath):
357| '''Write POV data file for a single net.'''
358| if fname and ('%s' in fname):
359|
360| nid = self('nid')
361|
362| fname = fname % nid
363|
364| fn = path.join(fpath,fname) if fpath else fname
365| fp = open(fn, mode='w', encoding='utf8') if fn else stdout
366| try:
367|
368| self._pov_write_file_head(fp, 'Cube Net Data')
369|
370| self._pov_write_cubenet(fp)
371|
372| self._pov_write_file_tail(fp)
373| except:
374| raise
375| finally:
376| if fn:
377| fp.close()
378| print('wrote: %s' % fn)
379| Log.info('wrote: %s' % fn)
380| Log.info()
381|
382| def pov_rotation (self, fname='cubenets.dat', fpath=BasePath):
383| '''Write POV data file for animating the move.'''
384| feed = self.feeder()
385|
386| fn = path.join(fpath,fname) if fpath else fname
387| fp = open(fn, mode='w', encoding='utf8') if fn else stdout
388| try:
389| nid = self('nid') if self('nid') else 0
390|
391|
392| self._pov_write_file_head(fp, 'Cube Net Animation Data')
393|
394|
395| for ix,theta in enumerate(self.xs):
396|
397| s = povData1(nid, ix, theta*self.swing)
398| print(s, file=fp)
399| Log.debug(s)
400|
401|
402| s = povData21(cubenet.VertexRadius)
403| print(s, file=fp)
404| Log.debug(s)
405|
406| pts = [(pn,next(it)) for pn,it in feed]
407| for pn,pt in pts:
408|
409| vec = self[pn][0]
410| vec.x = pt.x
411| vec.y = pt.y
412| vec.z = pt.z
413| s = povData2(pn.upper(), pt, cubenet.PointColor)
414| print(s, file=fp)
415| Log.debug(s)
416| print(povData0, file=fp)
417| Log.debug(povData0)
418|
419|
420| s = povData31(cubenet.EdgeRadius)
421| print(s, file=fp)
422| Log.debug(s)
423|
424| for ek,edge in self.edges.items():
425| clr = self.angle2color(edge[0], edge[1])
426| s = povData3(edge[0], edge[1], clr)
427| print(s, file=fp)
428| Log.debug(s)
429| print(povData0, file=fp)
430| Log.debug(povData0)
431|
432|
433| self._pov_write_cubenet_faces(fp)
434|
435|
436| print(povData9, file=fp)
437| print(povData0, file=fp)
438| Log.debug(povData9)
439| Log.debug(povData0)
440|
441|
442| self._pov_write_file_tail(fp)
443| except:
444| raise
445| finally:
446| if fn:
447| fp.close()
448| print('wrote: %s' % fn)
449| Log.info('wrote: %s' % fn)
450| Log.info()
451|
452| @classmethod
453| def pov_cubenet_list (cls, cns, fname, fpath):
454| '''Write a POV file from a list of Cube Nets.'''
455| fn = path.join(fpath, fname) if fpath else fname
456| fp = open(fn, mode='w', encoding='utf8') if fn else stdout
457| try:
458|
459| cls._pov_write_file_head(cls, fp, 'All Eleven Cube Nets')
460|
461| for ix,cn in enumerate(cns):
462| cn.rotate_ok = True if ix==0 else False
463| cn.props['rotate'] = True if ix==0 else False
464| cn.translate_ok = True
465| cn.props['translate'] = True
466| cn._pov_write_cubenet(fp)
467|
468|
469| cls._pov_write_file_tail(cls, fp)
470| except:
471| raise
472| finally:
473| if fn:
474| fp.close()
475| print('wrote: %s' % fn)
476| Log.info('wrote: %s' % fn)
477|
478| def _pov_write_cubenet (self, stream):
479| '''[internal] Write POV Cube Net data.'''
480|
481| nid = self('nid') if self('nid') else 0
482| s = povData1(nid, 0, 0)
483| print(s, file=stream)
484| Log.debug(s)
485|
486|
487| s = povData21(cubenet.VertexRadius)
488| print(s, file=stream)
489| Log.debug(s)
490|
491| for ptname in self:
492| s = povData2(ptname.upper(), self[ptname][0], cubenet.PointColor)
493| print(s, file=stream)
494| Log.debug(s)
495| print(povData0, file=stream)
496| Log.debug(povData0)
497|
498|
499| s = povData31(cubenet.EdgeRadius)
500| print(s, file=stream)
501| Log.debug(s)
502|
503| for a,b in self.lines:
504| clr = self.angle2color(a,b)
505| s = povData3(a,b, clr)
506| print(s, file=stream)
507| Log.debug(s)
508| print(povData0, file=stream)
509| Log.debug(povData0)
510|
511|
512| self._pov_write_cubenet_faces(stream)
513|
514| print(povData0, file=stream)
515| Log.debug(povData0)
516|
517|
518| if self.rotate_ok and self('rotate'):
519| vrotate = self('angles')
520| if vrotate:
521| print(povData7(vrotate), file=stream)
522| Log.debug(povData7(vrotate))
523| if self.translate_ok and self('translate'):
524| voffset = self('offset')
525| if voffset:
526| print(povData8(voffset), file=stream)
527| Log.debug(povData8(voffset))
528|
529|
530| print(povData9, file=stream)
531| print(povData0, file=stream)
532| print(povData0, file=stream)
533| Log.debug(povData9)
534| Log.debug(povData0)
535| Log.debug(povData0)
536|
537| def _pov_write_cubenet_faces (self, stream):
538| '''[internal] Write POV Cube Net face data.'''
539| for fx,face in enumerate(self.faces):
540| pt_p = face[0][0]
541| pt_n = face[4][0]
542|
543| clr = self.angle2color(pt_n, pt_p)
544|
545|
546| for tx,triangle in enumerate(face):
547| if tx < 4:
548| s = povData4(+1, *triangle, clr)
549| else:
550| s = povData4(-1, *triangle, clr)
551| print(s, file=stream)
552| Log.debug(s)
553|
554|
555| s0 = povData21(cubenet.FaceDotRadius)
556| s1 = povData2('_p%d' % fx, pt_p, Black)
557| s2 = povData2('_n%d' % fx, pt_n, Black)
558| print(s0, file=stream)
559| print(s1, file=stream)
560| print(s2, file=stream)
561| print(povData0, file=stream)
562| Log.debug(s0)
563| Log.debug(s1)
564| Log.debug(s2)
565| Log.debug(povData0)
566|
567| def _pov_write_file_head (obj, stream, title):
568| '''[internal] Write POV data file head. (obj=self or class)'''
569| s1 = povData91(title)
570| s2 = povData98('(Generated by Cube-Net; best to not modify.)')
571| s3 = povData98('((Unless, of course, you know what you\'re doing.))')
572| s4 = povData98('(((And you realize your changes could be overwritten.)))')
573|
574| print(povData90, file=stream)
575| print(s1, file=stream)
576| print(s2, file=stream)
577| print(s3, file=stream)
578| print(s4, file=stream)
579| print(povData0, file=stream)
580| print(povData0, file=stream)
581|
582| Log.debug(povData90)
583| Log.debug(s1)
584| Log.debug(s2)
585| Log.debug(s3)
586| Log.debug(s4)
587| Log.debug(povData0)
588| Log.debug(povData0)
589|
590| def _pov_write_file_tail (obj, stream):
591| '''[internal] Write POV data file tail. (obj=self or class)'''
592|
593| print(povData0, file=stream)
594| print(povData99, file=stream)
595| print(file=stream)
596|
597| Log.debug(povData0)
598| Log.debug(povData99)
599| Log.debug()
600|
601|
602|
603| """eof"""
604|