chiark / gitweb /
curveopt: wip, demos more of the same bug
[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 findcurve_subprocs = { }
21
22 class OptimisedCurve():
23   def __init__(oc, cp, nt):
24     db = DiscreteBezier(cp, nt, bezier_constructor=BezierSegment)
25
26     fc_input = map(db.point_at_it, range(0, nt+1))
27     dbg(repr(fc_input))
28
29     for end in (False,True):
30       ei = nt if end else 0
31       fi = nt-1 if end else 1
32       cp0i = 3 if end else 0
33       cp1i = 2 if end else 1
34       e = np.array(cp[cp0i])
35       ef_dirn = unit_v(cp[cp1i] - cp[cp0i])
36       ef_len = np.linalg.norm(np.array(fc_input[fi]) - np.array(fc_input[ei]))
37       f = e + ef_dirn * ef_len
38       dbg(repr((end, e,f, ef_dirn, ef_len)))
39       fc_input[ei] = e
40       fc_input[fi] = f
41
42     dbg(repr(fc_input))
43
44     findcurve_epsilon = 0.01
45
46     try:
47       subproc = findcurve_subprocs[nt]
48     except KeyError:
49       cl = ['./findcurve', '%d' % (nt+1), '%.18g' % findcurve_epsilon]
50       dbg('STARTING FINDCURVE %s' % cl)
51       subproc = subprocess.Popen(
52         cl,
53         bufsize=1,
54         stdin=subprocess.PIPE,
55         stdout=subprocess.PIPE,
56         stderr=None,
57         close_fds=False,
58         # restore_signals=True, // want python2 compat, nnng
59         universal_newlines=True,
60       )
61       findcurve_subprocs[nt] = subproc
62
63     dbg('RUNNING FINDCURVE')
64
65     fc_input = np.hstack(fc_input)
66     s = ' '.join(map(str, fc_input))
67
68     dbg(('>> %s' % s))
69
70     print(s, file=subproc.stdin)
71     subproc.stdin.flush()
72
73     commentary = ''
74
75     while True:
76       l = subproc.stdout.readline()
77       l = l.rstrip()
78       dbg('<< ', l)
79       if not l: vdbg().crashing('findcurve EOF')
80       if not l.startswith('['):
81         commentary += ' '
82         commentary += l
83         continue
84
85       l = eval(l)
86       if not l: break
87
88       dbg('[%s] %s' % (l, commentary))
89       commentary = ''
90
91       findcurve_result = l
92
93     oc.nt = nt
94     oc._result = np.reshape(findcurve_result, (-1,3), 'C')
95     dbg(repr(oc._result))
96
97     vdbg().curve( oc.point_at_t )
98
99   def point_at_it(oc, it):
100     dbg(repr((it,)))
101     return oc._result[it]
102
103   def point_at_t(oc, t):
104     itd = t * oc.nt
105     it0 = int(math.floor(itd))
106     it1 = int(math.ceil(itd))
107     p0 = oc.point_at_it(it0)
108     p1 = oc.point_at_it(it1)
109     return p0 + (p1-p0) * (itd-it0)
110