chiark / gitweb /
curveopt: use a fresh findcurve process for each curve
[moebius3.git] / curveopt.py
1
2 from __future__ import print_function
3
4 import numpy as np
5 from numpy import cos, sin
6
7 import six
8 import sys
9 import subprocess
10 import math
11
12 from moedebug import *
13 from moenp import *
14 from moebez import *
15
16 from math import atan2, atan, sqrt
17
18 import symbolic
19
20 class OptimisedCurve():
21   def __init__(oc, cp, nt):
22     db = DiscreteBezier(cp, nt, bezier_constructor=BezierSegment)
23
24     fc_input = map(db.point_at_it, range(0, nt+1))
25     dbg(repr(fc_input))
26
27     for end in (False,True):
28       ei = nt if end else 0
29       fi = nt-1 if end else 1
30       cp0i = 3 if end else 0
31       cp1i = 2 if end else 1
32       e = np.array(cp[cp0i])
33       ef_dirn = unit_v(cp[cp1i] - cp[cp0i])
34       ef_len = np.linalg.norm(np.array(fc_input[fi]) - np.array(fc_input[ei]))
35       f = e + ef_dirn * ef_len
36       dbg(repr((end, e,f, ef_dirn, ef_len)))
37       fc_input[ei] = e
38       fc_input[fi] = f
39
40     dbg(repr(fc_input))
41
42     findcurve_epsilon = 0.01
43
44     cl = ['./findcurve', '%d' % (nt+1), '%.18g' % findcurve_epsilon]
45     dbg('STARTING FINDCURVE %s' % cl)
46     subproc = subprocess.Popen(
47       cl,
48       bufsize=1,
49       stdin=subprocess.PIPE,
50       stdout=subprocess.PIPE,
51       stderr=None,
52       close_fds=False,
53       # restore_signals=True, // want python2 compat, nnng
54       universal_newlines=True,
55     )
56
57     dbg('RUNNING FINDCURVE')
58
59     fc_input = np.hstack(fc_input)
60     s = ' '.join(map(str, fc_input))
61
62     dbg(('>> %s' % s))
63
64     print(s, file=subproc.stdin)
65     subproc.stdin.flush()
66
67     commentary = ''
68
69     while True:
70       l = subproc.stdout.readline()
71       l = l.rstrip()
72       dbg('<< ', l)
73       if not l: vdbg().crashing('findcurve EOF')
74       if not l.startswith('['):
75         commentary += ' '
76         commentary += l
77         continue
78
79       l = eval(l)
80       if not l: break
81
82       dbg('[%s] %s' % (l, commentary))
83       commentary = ''
84
85       findcurve_result = l
86
87     subproc.stdin.close()
88     subproc.wait()
89     assert(subproc.returncode == 0)
90
91     oc.nt = nt
92     oc._result = np.reshape(findcurve_result, (-1,3), 'C')
93     dbg(repr(oc._result))
94
95     vdbg().curve( oc.point_at_t )
96
97   def point_at_it(oc, it):
98     dbg(repr((it,)))
99     return oc._result[it]
100
101   def point_at_t(oc, t):
102     itd = t * oc.nt
103     it0 = int(math.floor(itd))
104     it1 = int(math.ceil(itd))
105     p0 = oc.point_at_it(it0)
106     p1 = oc.point_at_it(it1)
107     return p0 + (p1-p0) * (itd-it0)
108