povray.html


001| '''POV-Ray Utilities.
001| 
001| Commands:
001|     html        do_images_html_page
001|     ini         do_ini_file_set
001| 
001|     grid        do_gen_long_lat_map
001|     bits        do_page_of_bits
001|     pan         do_camera_pan_test
001| 
001|     test        do_test
001| 
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date
007| from random import random
008| import math
009| from PIL import Image, ImageDraw
010| from logger import logger,info,debug,trace, LogFilenameTimestamp
011| from goodies import KWARG
012| from files import filefinder, textfile
013| from webpage import WebPage
014| ####################################################################################################
015| BasePath = r'C:\CJS\prj\Python\app'
016| WorkPath = r'C:\CJS\prj\pov\ws'
017| Log = logger('POV-RAY')
018| 
019| CMND = ''
020| ARGS = {
021|     'ttl': '',
022|     'dir': '',
023|     'fn' : '',
024|     'tag': '',
025|     'num': '10',
026|     'cam': 'view',
027|     #'fname': 'pov-ray.dat',
028|     #'fpath': BasePath,
029| }
030| 
031| ##------------------------------------------------------------------------------------------------##
032| ImageFolders = [
033|     r"C:\CJS\prj\pov\ws\cube\gallery",
034|     r"C:\CJS\prj\pov\ws\various\out",
035|     r"C:\CJS\prj\pov\ws\various\pub",
036|     r"C:\CJS\prj\pov\ws\xyz\out",
037|     r"C:\CJS\prj\pov\ws\xyz\gallery",
038| ]
039| 
040| ##------------------------------------------------------------------------------------------------##
041| main_ini_text = '''\
041| ;; POV-Ray Project INI File
041| ;; {proj_title}
041| ;; Developer@Sonnack.com
041| ;; {curr_date:%A %B %d, %Y}
041| ;;
041| "{pov_path}\\{proj_path}\\ini\\cam.ini"
041| 
041| Input_File_Name = "{pov_path}\\{proj_path}\\{proj_file}.pov"
041| 
041| ;Width  = 1280
041| ;Height =  720
041| 
041| Width  = 1920
041| Height = 1080
041| 
041| ;Width  = 1600
041| ;Height =  900
041| 
041| Quality = 11
041| 
041| Antialias           = On
041| Sampling_Method     = 2
041| Antialias_Threshold = 0.1
041| Antialias_Depth     = 5
041| 
041| 
041| %s
041| 
041| 
041| ;;eof
041| '''

042| ##------------------------------------------------------------------------------------------------##
043| main_ini_item_text = '''\
043| [{cam_name}{cam_ix:02d}]
043| "{pov_path}\\{proj_path}\\ini\\{proj_name}.ini"
043| Output_File_Name = "{pov_path}\\{proj_path}\\out\\{proj_file}-{cam_ix:02d}.png"
043| Declare = "CameraIndex={cam_ix:d}"
043| 
043| '''

044| ##------------------------------------------------------------------------------------------------##
045| sub_ini_text = '''\
045| ;; POV-Ray Camera INI File
045| ;; {proj_title}
045| ;; Developer@Sonnack.com
045| ;; {curr_date:%A %B %d, %Y}
045| ;; 
045| 
045| "{pov_path}\\{proj_path}\\ini\\{proj_name}[{cam_name}{cam_ix:02d}].ini"
045| 
045| ;;eof
045| '''

046| 
047| ##------------------------------------------------------------------------------------------------##
048| html_css = '''
048| body {
048|     color: black;
048|     background-color: white;
048|     font-family: "Verdana", "Arial", "Helvetica", sans-serif;
048|     font-size: 9pt;
048|     font-weight: normal;
048|     font-style: normal;
048|     line-height: 1.25;
048|     text-decoration: none;
048|     text-align: left;
048|     vertical-align: top;
048|     padding: 0;
048|     border: 0;
048|     margin: 0;
048| }
048| h1 {
048|     color: #000000;
048|     font-family: "Tahoma", "Verdana", "Arial", "Helvetica", sans-serif;
048|     font-size: 20px;
048|     font-weight: normal;
048|     font-style: normal;
048|     line-height: 1.0;
048|     text-decoration: none;
048|     text-align: left;
048|     vertical-align: top;
048|     padding: 0;
048|     border: 0;
048|     margin: 0;
048| }
048| h2 {padding:0; margin:0;}
048| #PageHead {
048|     background-color: #cccccc;
048|     padding: 10px 20px;
048|     border-bottom: 1px solid black;
048|     margin: 0;
048| }
048| #PageBody {
048|     padding: 20px 10px;
048|     margin: 0;
048| }
048| #PageFoot {
048|     color: #808080;
048|     background-color: #e0e0e0;
048|     font-family: sans-serif;
048|     font-size: xx-small;
048|     font-weight: normal;
048|     font-style: normal;
048|     line-height: 1.0;
048|     text-align: center;
048|     padding: 4px 20px 6px 20px;
048|     border-top: 2px solid black;
048|     margin: 0;
048| }
048| #PageFoot .Lt {
048|     float: left;
048|     text-align: left;
048| }
048| #PageFoot .Rt {
048|     float: right;
048|     text-align: right;
048| }
048| #PageBody table {
048|     border-spacing: 0;
048|     padding: 0;
048|     border: 2px solid blue;
048|     margin: 10px;
048| }
048| #PageBody table td {
048|     text-align: center;
048|     vertical-align: top;
048| }
048| '''

049| 
050| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
051| class IniProps (dict):
052|     """Properties class for INI file creation."""
053| 
054|     def __init__ (self, **kwargs):
055|         self['curr_date'] = date.today()
056|         self['pov_path'] = WorkPath
057|         self['proj_title'] = KWARG('title', 'New Project', str, kwargs)
058|         self['proj_path']  = KWARG('fpath', 'project', str, kwargs)
059|         self['proj_file']  = KWARG('fname', 'file', str, kwargs)
060|         self['proj_name']  = KWARG('tag' , 'name', str, kwargs)
061|         self['cam_count']  = KWARG('ncam' , 10, int, kwargs)
062|         self['cam_name']   = KWARG('cam' , 'cam', str, kwargs)
063|         self['cam_ix'] = 0
064| 
065|     def __repr__ (self):
066|         return f'{self.title}: {self.fpath}/{self.fname} [{self.tag}/{self.nbrcams}]'
067| 
068|     @property
069|     def title (self): return self['proj_title']
070|     @property
071|     def fpath (self): return self['proj_path']
072|     @property
073|     def fname (self): return self['proj_file']
074|     @property
075|     def name (self): return self['proj_name']
076|     @property
077|     def nbrcams (self): return self['cam_count']
078|     @property
079|     def tag (self): return self['cam_name']
080| 
081| ##================================================================================================##
082| def do_ini_file_set (**kwargs):
083|     """CMND: Generate a set of project INI files."""
084|     #ATTN:TODO: ini-name isn't POV-name, so add the latter!
085|     fpath = KWARG('fpath', BasePath, str, kwargs)
086|     fname = KWARG('fname', 'inifiles.out', str, kwargs)
087|     title = KWARG('ttl', 'Untitled', str, kwargs)
088|     vpath = KWARG('dir', 'project' , str, kwargs)
089|     vname = KWARG('fn' , 'filename', str, kwargs)
090|     tag   = KWARG('tag', 'projname', str, kwargs)
091|     num   = KWARG('num',  10       , int, kwargs)
092|     cam   = KWARG('cam', 'cam'     , str, kwargs)
093|     Log.info('CREATE-INI-FILE-SET:: %s' % str(list(kwargs.keys())))
094|     Log.debug(f'{fpath=}')
095|     Log.debug(f'{fname=}')
096|     Log.debug(f'{title=}')
097|     Log.debug(f'{vpath=}')
098|     Log.debug(f'{tag =}')
099|     Log.debug(f'{num=}')
100|     Log.debug(f'{cam=}')
101|     Log.info()
102|     filename = path.join(fpath,fname)
103|     Log.debug(f'{filename=}')
104|     Log.debug()
105| 
106|     # Initialize new properties object...
107|     props = IniProps(title=title, fpath=vpath,fname=vname, tag=tag, ncam=num, cam=cam)
108|     Log.info(props)
109|     Log.info()
110| 
111|     # Generate main INI filename and text...
112|     ini_fname = path.join(WorkPath, props.fpath, 'ini', f'{props.name}.ini')
113|     main_text = main_ini_text.format(**props)
114| 
115|     # Generate main INI [cam##] text...
116|     buff = []
117|     for ix in range(props.nbrcams):
118|         props['cam_ix'] = ix
119|         txt = main_ini_item_text.format(**props)
120|         buff.append(txt)
121|     ini_text = main_text % ''.join(buff)
122| 
123|     Log.info(f'Main INI File: {ini_fname}')
124|     Log.info(f'\n{ini_text}\n')
125|     Log.info()
126| 
127|     # Write main INI file...
128|     fo = textfile(ini_fname)
129|     fo.data = ini_text
130|     fo.save()
131|     Log.info()
132| 
133|     # Generate sub-ini files...
134|     for ix in range(props.nbrcams):
135|         props['cam_ix'] = ix
136| 
137|         # Generate sub INI filename and text...
138|         sub_fname = path.join(WorkPath, props.fpath, 'ini', f'{props.name}-{ix:02d}.ini')
139|         sub_ftext = sub_ini_text.format(**props)
140| 
141|         Log.info(f'{ix:02}: {sub_fname}')
142|         Log.info(f'\n{sub_ftext}\n')
143|         Log.info()
144| 
145|         # Write sub INI file...
146|         fo = textfile(sub_fname)
147|         fo.data = sub_ftext
148|         fo.save()
149|         Log.info()
150| 
151|     Log.info()
152|     return 'Done'
153| 
154| ##================================================================================================##
155| def do_images_html_page (**kwargs):
156|     """CMND: Create an HTML page of images in a folder."""
157|     fpath = KWARG('fpath', BasePath, str, kwargs)
158|     fname = KWARG('fname', 'index.html', str, kwargs)
159|     width = KWARG('width', 540, int, kwargs)
160|     ncols = KWARG('ncols', 3, int, kwargs)
161|     Log.info('CREATE-IMAGES-HTML-PAGE:: %s' % str(list(kwargs.keys())))
162|     Log.debug(f'{fpath=}')
163|     Log.debug(f'{fname=}')
164|     Log.info()
165| 
166|     ff = filefinder(fpath, subs=0)
167|     ff.add_include_item(r'\.png$')
168|     ff.scan()
169| 
170|     for ix,fn in enumerate(ff):
171|         Log.info(f'{ix:2d}: {fn}')
172|     Log.info()
173| 
174|     props = dict(h1=fpath, h2='', h3=None, csstxt=html_css)
175| 
176|     htmlimg = '<a target="POVIMG" href="%s"><img style="%s" src="%s" width="%d"></a>'
177|     cssimg = 'padding:0;border:0;margin:0;'
178| 
179|     htmldiv = '<div style="%s">%s<div style="%s">%s</div></div>'
180|     css1div = 'padding:5px 10px;border:1px solid black;margin:3px 0;'
181|     css2div = 'font-family:sans-serif;font-size:28px;text-align:center;padding:7px 5px 3px 5px;border:0;margin:0;'
182| 
183|     pg = WebPage('Image Index', **props)
184|     pg.body = []
185| 
186|     pg.add('')
187|     pg.add('<table>')
188|     pg.add('<tbody>')
189| 
190|     column = 0
191|     pg.add('<tr>')
192|     for fn in ff:
193|         name = path.basename(fn)
194|         img = htmlimg % (fn, cssimg, fn, width)
195|         div = htmldiv % (css1div, img, css2div, name)
196|         pg.add('<td>%s</td>' % div)
197| 
198|         column += 1
199|         if ncols <= column:
200|             pg.add()
201|             pg.add('</tr><tr>')
202|             pg.add()
203|             column = 0
204|     pg.add('</tr>')
205| 
206|     pg.add('</tbody>')
207|     pg.add('</table>')
208| 
209|     fn = path.join(fpath,fname)
210|     pg.save(fn)
211|     Log.info(f'wrote: {fn}')
212| 
213|     Log.info()
214|     return 'Done'
215| 
216| ##================================================================================================##
217| def do_camera_pan_test (**kwargs):
218|     """CMND: Calculate POV on prorated angle in XZ plane (plus prorated elevation)."""
219|     fpath = KWARG('fpath', BasePath, str, kwargs)
220|     fname = KWARG('fname', 'test.out', str, kwargs)
221|     count = KWARG('num', 25, int, kwargs)
222|     Log.info('CAMERA-PAN-TEST:: %s' % str(list(kwargs.keys())))
223|     Log.debug(f'{fpath=}')
224|     Log.debug(f'{fname=}')
225|     Log.debug(f'{count=}')
226|     Log.info()
227|     filename = path.join(fpath,fname)
228|     Log.debug(f'{filename=}')
229|     Log.debug()
230| 
231|     tAdd = lambda ta,tb: [a+b for a,b in zip(ta, tb)]
232|     tSub = lambda ta,tb: [a-b for a,b in zip(ta, tb)]
233|     tMul = lambda ta,m: [a*m for ta in ta]
234|     tLen = lambda ta: math.sqrt(sum(pow(x,2) for x in ta))
235|     Diffs = lambda ns: [a-b for a,b in zip(ns[:len(ns)-1], ns[1:])]
236| 
237|     def std_dev (ns):
238|         count = len(ns)
239|         total = sum(ns)
240|         mean = total / count
241|         sum_dif_sqrs = sum(pow(n-mean, 2) for n in ns)
242|         return math.sqrt(sum_dif_sqrs / count)
243| 
244|     def calc_pov (clk, cam, p1, p2):
245|         '''Algorithm #1. Calculate POV based on prorated angle in XZ plane plus prorated elevation.'''
246|         Log.info(f'clk={clk}')
247|         # v_p1 = p1 - <cam_x,cam_y,cam_z>; // vector from cam -> p1
248|         # v_p2 = p2 - <cam_x,cam_y,cam_z>; // vector from cam -> p2
249|         v_p1 = tSub(p1, cam)
250|         v_p2 = tSub(p2, cam)
251|         Log.info(f'v_p1={v_p1}')
252|         Log.info(f'v_p2={v_p2}')
253| 
254|         # p1_d = vlength(<v_p1.x, 0, v_p1.z>); // length of p1 vector
255|         # p2_d = vlength(<v_p2.x, 0, v_p2.z>); // length of p2 vector
256|         p1_d = tLen((v_p1[0], 0, v_p1[2]))
257|         p2_d = tLen((v_p2[0], 0, v_p2[2]))
258|         Log.info(f'p1_d={p1_d}')
259|         Log.info(f'p2_d={p2_d}')
260| 
261|         # pov_d = (p1_d * (1-clk)) + (p2_d * clk); // current prorated p1/p2 distance
262|         pov_d = (p1_d * (1-clk)) + (p2_d * clk)
263|         Log.info(f'pov_d={pov_d}')
264| 
265|         # p1_a = atan2(v_p1.z, v_p1.x); // angle of p1 vector
266|         # p2_a = atan2(v_p2.z, v_p2.x); // angle of p2 vector
267|         p1_a = math.atan2(v_p1[2], v_p1[0])
268|         p2_a = math.atan2(v_p2[2], v_p2[0])
269|         Log.info(f'p1_a={math.degrees(p1_a)}')
270|         Log.info(f'p2_a={math.degrees(p2_a)}')
271| 
272|         # tot_a = p2_a - p1_a; // p1/p2 difference angle
273|         # pov_a = p1_a + (tot_a * clk); // current prorated angle
274|         tot_a = p2_a - p1_a
275|         pov_a = p1_a + (tot_a * clk)
276|         Log.info(f'tot_a={math.degrees(tot_a)}')
277|         Log.info(f'pov_a={math.degrees(pov_a)}')
278| 
279|         # pov_x = pov_d * cos(pov_a); // POV X
280|         # pov_z = pov_d * sin(pov_a); // POV Z
281|         # pov_y = p1.y + (clk * (p2.y - p1.y)); // POV Y
282|         pov_x = pov_d * math.cos(pov_a)
283|         pov_z = pov_d * math.sin(pov_a)
284|         pov_y = p1[1] + (clk * (p2[1] - p1[1]))
285| 
286|         pov = (pov_x, pov_y, pov_z, math.degrees(pov_a), pov_d)
287|         Log.info(f'pov={pov}')
288|         Log.info()
289|         return pov
290| 
291|     clks = [t * 0.01 for t in range(count)]
292|     cam = (   0,  +5,   0)
293|     p1  = (  -8, +50, +33)
294|     p2  = ( +25,  +5, -33)
295| 
296|     povs = [calc_pov(c, cam, p1, p2) for c in clks]
297| 
298|     dx = Diffs([p[0] for p in povs])
299|     dy = Diffs([p[1] for p in povs])
300|     dz = Diffs([p[2] for p in povs])
301|     da = Diffs([p[3] for p in povs])
302|     dd = Diffs([p[4] for p in povs])
303| 
304|     Log.info('==========')
305|     Log.info('Camera Pan')
306|     Log.info('----------')
307|     Log.info(f'CAM={cam}')
308|     Log.info(f'P1={p1}')
309|     Log.info(f'P2={p2}')
310|     Log.info()
311|     Log.info(f'stddev(dx)={std_dev(dx):.3f}')
312|     Log.info(f'stddev(dy)={std_dev(dy):.3f}')
313|     Log.info(f'stddev(dz)={std_dev(dz):.3f}')
314|     Log.info(f'stddev(da)={std_dev(da):.3f}')
315|     Log.info(f'stddev(dd)={std_dev(dd):.3f}')
316|     Log.info()
317| 
318|     Log.info('POVs:')
319|     for c,p in zip(clks,povs):
320|         Log.info('[%.3f] <%2.3f, %2.3f, %2.3f> (%2.3f, %2.3f)' % (c, *p))
321|     Log.info()
322| 
323|     Log.info('deltas:')
324|     for x,y,z,a,d in zip(dx,dy,dz, da, dd):
325|         Log.info('[%2.3f, %2.3f, %2.3f] [%2.3f, %2.3f]' % (x, y, z, a, d))
326|     Log.info()
327| 
328|     Log.info()
329|     return 'Done'
330| 
331| ##================================================================================================##
332| def do_page_of_bits (**kwargs):
333|     """CMND: Generate a text file of random 1s and 0s."""
334|     fpath = KWARG('fpath', BasePath, str, kwargs)
335|     fname = KWARG('fname', 'bits.txt', str, kwargs)
336|     rows = KWARG('rows', 60, int, kwargs)
337|     cols = KWARG('cols', 80, int, kwargs)
338|     Log.info('PAGE-OF-BITS:: %s' % str(list(kwargs.keys())))
339|     Log.debug(f'{fpath=}')
340|     Log.debug(f'{fname=}')
341|     Log.info()
342|     filename = path.join(fpath,fname)
343|     Log.debug(f'{filename=}')
344|     Log.debug()
345| 
346|     fp = open('bits.txt', 'w')
347|     try:
348|         # For each row...
349|         for r in range(rows):
350|             # For each column...
351|             for c in range(cols):
352| 
353|                 # Write random bit...
354|                 fp.write('0' if random() < 0.5 else '1')
355| 
356|             fp.write('\n')
357| 
358|     except Exception as e:
359|         raise
360| 
361|     finally:
362|         fp.close()
363| 
364|     Log.info()
365|     return 'Done'
366| 
367| ##================================================================================================##
368| def do_gen_long_lat_map (**kwargs):
369|     """CMND: Generate a Longitude and Latitude map for POV sphere mapping."""
370|     fpath = KWARG('fpath', BasePath, str, kwargs)
371|     fname = KWARG('fname', 'long-lat.png', str, kwargs)
372|     Log.info('GEN-LONG-LAT-MAP:: %s' % str(list(kwargs.keys())))
373|     Log.debug(f'{fpath=}')
374|     Log.debug(f'{fname=}')
375|     Log.info()
376|     filename = path.join(fpath,fname)
377|     Log.info(f'{filename=}')
378|     Log.info()
379| 
380|     dims = (1200, 600)
381|     c_bg = (127,191,255)
382|     c_fg = (  0,  0,  0)
383|     incr = 60
384|     ln_w = 5
385|     offs = int(ln_w/2)
386| 
387|     img = Image.new('RGB', dims, c_bg)
388|     pen = ImageDraw.Draw(img)
389| 
390|     for py in range(0, dims[1], incr):
391|         pen.line([(0,py+offs), (dims[0],py+offs)], fill=c_fg, width=ln_w)
392| 
393|     for px in range(0, dims[0], incr):
394|         pen.line([(px+offs,0), (px+offs,dims[1])], fill=c_fg, width=ln_w)
395| 
396|     img.save(filename, 'PNG')
397|     Log.info(f'wrote: {filename}')
398| 
399|     Log.info()
400|     return 'Done'
401| 
402| ##================================================================================================##
403| def do_test (**kwargs):
404|     """CMND: Do a test."""
405|     fpath = KWARG('fpath', BasePath, str, kwargs)
406|     fname = KWARG('fname', 'test.out', str, kwargs)
407|     Log.info('TEST:: %s' % str(list(kwargs.keys())))
408|     Log.debug(f'{fpath=}')
409|     Log.debug(f'{fname=}')
410|     Log.info()
411|     filename = path.join(fpath,fname)
412|     Log.debug(f'{filename=}')
413|     Log.debug()
414| 
415|     Log.info()
416|     return 'Done'
417| ####################################################################################################
418| def dispatch (cmd, **kwargs):
419|     """Dispatch to a module function based on CMD."""
420|     Log.info(f'CMD: {cmd}')
421|     for kw in kwargs:
422|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
423|     Log.info()
424|     if cmd == 'html': return do_images_html_page(**kwargs)
425|     if cmd == 'ini': return do_ini_file_set(**kwargs)
426|     if cmd == 'grid': return do_gen_long_lat_map(**kwargs)
427|     if cmd == 'bits': return do_page_of_bits(**kwargs)
428|     if cmd == 'pan': return do_camera_pan_test(**kwargs)
429|     if cmd == 'test': return do_test(**kwargs)
430|     return 'Nothing to do!'
431| ####################################################################################################
432| if __name__ == '__main__':
433|     print('autorun: %s' % argv[0])
434|     Log.start(path.join(BasePath,'povray.log'))
435|     Log.level(trace())
436|     Log.info(argv[0])
437|     Log.info()
438|     cmd = argv[1] if 1 < len(argv) else CMND
439|     kwargs = ARGS
440|     for a in argv[2:]:
441|         nv = a.split('=', 1)
442|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
443|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
444|     try:
445|         print(f'CMD: {cmd}')
446|         print()
447|         obj = dispatch(cmd, **kwargs)
448|         print()
449|         print(obj)
450|         Log.info()
451|         Log.info(obj)
452|     except:
453|         etype, evalue, tb = exc_info()
454|         ts = extract_tb(tb)
455|         Log.error()
456|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
457|         Log.error()
458|         for t in ts[-5:]:
459|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
460|             Log.error(' %s' % t[3])
461|             Log.error()
462|         raise
463|     finally:
464|         Log.end()
465| ####################################################################################################
466| '''eof'''
467|