Debian Codegraph @

texmf-dist/doc/latex/figput/javascript/tikz.js

raw
1 "use strict";
2 /*
3 Code necessary to output tikz for figures. It spoofs the normal canvas
4 drawing code so that the output comes here, and is then converted to
5 tizk output.
6
7 One problem with JS is that there is no path interator. You can't obtain
8 the segments that make up an entire path. I don't see any way around this
9 other than writing my own wrapper around Path2D. It might be possible to
10 somehow hack the internals of Path2D, but that would be brittle, even if
11 it works.
12
13 BUG: The long-term solution is to eliminate use of the JS Path2D class,
14 but it's not possible to entirely eliminate it since it's the only way to
15 draw to the browser window. What I *could* do is sub-class
16 CanvasRenderingContext2D so that this sub-class take my own path class
17 objects and converts them to Path2D for drawing. Another hurdle is
18 isPointInPath(), which is used in a few places. I could provide a separate
19 implementation of that, but it's fiddly. isPointInStroke() is a bit harder.
20
21 BUG: It's tempting to come up with a framework under which a "path"
22 is closer to our intuition of something that can be drawn as a continuous
23 thing, without lifting your pencil. Then, have a second-order thing that
24 may hold several of these continuous paths. Intuitively one wants a "path"
25 to have a clear start-point and end-point, but you also need to be able
26 to handle things like winding number for multiple paths when filling.
27
28 BUG: There are many cases where you might want the online version to be
29 different from what is printed. I just gave the example of filling a path,
30 and color is similar. There's lots of things that might make sense on a
31 computer screen, but wouldn't work well on printed paper.
32
33 */
34 // Turns out that Point used to be part of js, but was deprecated, and
35 // seems not to exist any longer.
36 class Point2D {
37 constructor(x, y) {
38 this._x = x;
39 this._y = y;
40 }
41 toString() {
42 // May be handy for debugging.
43 return "( " + this._x.toFixed(2) + "," + this._y.toFixed(2) + ")";
44 }
45 get x() {
46 return this._x;
47 }
48 get y() {
49 return this._y;
50 }
51 copy() {
52 return new Point2D(this._x, this._y);
53 }
54 negate() {
55 // return -this.
56 return new Point2D(-this._x, -this.y);
57 }
58 negateSelf() {
59 this._x = -this.x;
60 this._y = -this.y;
61 }
62 minus(p) {
63 // return this - p. Redunant since it's just a form of translation.
64 return new Point2D(this._x - p.x, this._y - p.y);
65 }
66 minusSelf(p) {
67 this._x -= p._x;
68 this._y -= p._y;
69 }
70 translate2(u, v) {
71 return new Point2D(u + this._x, v + this._y);
72 }
73 translate(p) {
74 return new Point2D(p.x + this._x, p.y + this._y);
75 }
76 translateSelf2(u, v) {
77 this._x += u;
78 this._y += v;
79 }
80 translateSelf(p) {
81 this._x += p.x;
82 this._y += p.y;
83 }
84 scale(s) {
85 return new Point2D(s * this._x, s * this._y);
86 }
87 scaleSelf(s) {
88 // As above, but it's done in-place rather than returning a copy.
89 this._x *= s;
90 this._y *= s;
91 }
92 rotate(theta) {
93 // Apply rotation matrix in the usual (RH) way. theta in radians.
94 let c = Math.cos(theta);
95 let s = Math.sin(theta);
96 return new Point2D(c * this._x - s * this._y, s * this._x + c * this._y);
97 }
98 rotateSelf(theta) {
99 let c = Math.cos(theta);
100 let s = Math.sin(theta);
101 let u = c * this._x - s * this._y;
102 let v = s * this._x + c * this._y;
103 this._x = u;
104 this._y = v;
105 }
106 rotateAbout(c, theta) {
107 // Rotate this about c by angle theta, returning the result.
108 let answer = new Point2D(this.x - c.x, this.y - c.y);
109 answer = answer.rotate(theta);
110 answer._x += c.x;
111 answer._y += c.y;
112 return answer;
113 }
114 dot(a) {
115 // Return this dot a.
116 return a.x * this._x + a.y * this._y;
117 }
118 length() {
119 return Math.sqrt(this._x ** 2 + this._y ** 2);
120 }
121 static dot(a, b) {
122 // This looks like Java-style overloading, but it's not. One dot()
123 // is static and the other is not.
124 return a.dot(b);
125 }
126 angleBetween(a) {
127 // Return angle between this and a, based on
128 // this dot a = |this| |a| cos angle
129 // This is the angle between the two, without any orientation.
130 let cos = this.dot(a) / (this.length() * a.length());
131 return Math.acos(cos);
132 }
133 cliffordBetween(a) {
134 // The "clifford angle," which is like angleBetween(), but it takes
135 // orientation into account. The angle is given relative to ("from") this.
136 return Math.atan2(this.x * a.y - a.x * this.y, this.x * a.x + this.y * a.y);
137 }
138 }
139 // Almost everything here is static because this is essentially a factory for the
140 // various segment types.
141 class PathSegment {
142 constructor(kind, d) {
143 // One of the values above.
144 this.type = PathSegment.UNKNOWN;
145 this.type = kind;
146 this.s = d;
147 }
148 static getClose() {
149 let d = {};
150 return new PathSegment(PathSegment.CLOSE, d);
151 }
152 static getMoveTo(x, y) {
153 let d = { x: x, y: y };
154 return new PathSegment(PathSegment.MOVE_TO, d);
155 }
156 static getLineTo(x, y) {
157 let d = { x: x, y: y };
158 return new PathSegment(PathSegment.LINE_TO, d);
159 }
160 static getBezier(cx1, cy1, cx2, cy2, x, y) {
161 let d = { cx1: cx1, cy1: cy1, cx2: cx2, cy2: cy2, x: x, y: y };
162 return new PathSegment(PathSegment.BEZIER, d);
163 }
164 static getQuadratic(cx, cy, x, y) {
165 let d = { cx: cx, cy: cy, x: x, y: y };
166 return new PathSegment(PathSegment.QUADRATIC, d);
167 }
168 static getArc(x, y, r, a0, a1, ccw) {
169 let d = { x: x, y: y, r: r, a0: a0, a1: a1, ccw: ccw };
170 return new PathSegment(PathSegment.ARC, d);
171 }
172 static getArcTo(x1, y1, x2, y2, r) {
173 let d = { x1: x1, y1: y1, x2: x2, y2: y2, r: r };
174 return new PathSegment(PathSegment.ARC_TO, d);
175 }
176 static getEllipse(x, y, rx, ry, rot, a0, a1, ccw) {
177 // BUG: If I convert everything to bezier, then many of these static
178 // methods can be eliminated.
179 // YES. THIS IS A BAD IDEA IN EVERY WAY. ONLY BEZIER CURVES SHOULD
180 // BE ALLOWED INTERNALLY.
181 // OTOH, there are certain shapes, like an ellipse or rectangle, that
182 // should be treated as a single unitary thing.
183 // What I should probably do is sub-class FPath for these. Interally, they
184 // can be represented as a messy bezier thing, but that would be hidden from the user.
185 // At the same time, one might want to add an ellipse or rect to an existing path to
186 // obtain various fill effects. So, the ellipse sub-class will need something like
187 // a toFPath() method so that it can be added to a normal FPath.
188 let d = { x: x, y: y, rx: rx, ry: ry, rot: rot, a0: a0,
189 a1: a1, ccw: ccw };
190 return new PathSegment(PathSegment.ELLIPSE, d);
191 }
192 static getRect(x, y, w, h) {
193 let d = { x: x, y: y, w: w, h: h };
194 return new PathSegment(PathSegment.RECT, d);
195 }
196 }
197 // The various kinds of segment.
198 // I'm being sloppy about typing here since the use is uncomplicated and
199 // private. Some kind of enumerated type would be better in the abstract.
200 // BUG: I should get rid of anything after the QUADRATIC type. The
201 // mathematically clean way to do this is to convert *everything* to beziers,
202 // including ellipses. In fact (?) is a quadratic just a cubic where the
203 // control points coincide? If so, I could get rid of QUADRATIC too.
204 PathSegment.MOVE_TO = 1;
205 PathSegment.LINE_TO = 2;
206 PathSegment.BEZIER = 3;
207 PathSegment.QUADRATIC = 4;
208 PathSegment.ARC = 5;
209 PathSegment.ARC_TO = 6;
210 PathSegment.ELLIPSE = 7;
211 PathSegment.RECT = 8;
212 PathSegment.CLOSE = 9;
213 PathSegment.UNKNOWN = -1;
214 // BUG: Add some flags so that things could be drawn or not drawn based
215 // on whether the output is going to tikz or to the screen.
216 class FPath extends Path2D {
217 constructor() {
218 super();
219 // An array of PathSegments.
220 this.segs = [];
221 }
222 addPath(p) {
223 // Append the elements of p to this.
224 for (let i = 0; i < p.segs.length; i++)
225 this.segs.push(p.segs[i]);
226 }
227 closePath() {
228 super.closePath();
229 this.segs.push(PathSegment.getClose());
230 }
231 moveTo(x, y) {
232 super.moveTo(x, y);
233 this.segs.push(PathSegment.getMoveTo(x, y));
234 }
235 frontLineTo(x, y) {
236 // To tack a line segment to the *begining* of an existing path.
237 // This assumes that segs[0] is a moveTo() -- as I think (?) it must be
238 // in any reasonable case.
239 // So, you start with a path that looks like
240 // moveTo(a,b) ...whatever
241 // and it becomes
242 // moveTo(x,y) lineTo(a,b) ...whatever.
243 // You're basically drawing as usual, but "from the wrong end."
244 let s = this.segs[0];
245 if (s.type != PathSegment.MOVE_TO)
246 console.log("ERROR: frontLineTo() doesn't start with moveTo(): " + s.type);
247 let newfirst = PathSegment.getMoveTo(x, y);
248 // Convert the initial moveto to a lineto.
249 // In fact, this is sort of pointless, and is only done this way to respect
250 // the type-checker. It's (x,y) whether it's a lineto or a moveto.
251 let m = s.s;
252 let newsecond = PathSegment.getLineTo(m.x, m.y);
253 this.segs[0] = newsecond;
254 this.segs.unshift(newfirst);
255 }
256 lineTo(x, y) {
257 super.lineTo(x, y);
258 this.segs.push(PathSegment.getLineTo(x, y));
259 }
260 bezierCurveTo(cx1, cy1, cx2, cy2, x, y) {
261 super.bezierCurveTo(cx1, cy1, cx2, cy2, x, y);
262 this.segs.push(PathSegment.getBezier(cx1, cy1, cx2, cy2, x, y));
263 }
264 quadraticCurveTo(cx, cy, x, y) {
265 super.quadraticCurveTo(cx, cy, x, y);
266 this.segs.push(PathSegment.getQuadratic(cx, cy, x, y));
267 }
268 translate(p) {
269 // Translate this entire path by the given point.
270 // BUG: Not implemented for every possible type of segment.
271 let answer = new FPath();
272 for (let i = 0; i < this.segs.length; i++) {
273 let s = this.segs[i];
274 if (s.type == PathSegment.MOVE_TO) {
275 let m = s.s;
276 answer.moveTo(m.x + p.x, m.y + p.y);
277 }
278 else if (s.type == PathSegment.LINE_TO) {
279 let m = s.s;
280 answer.lineTo(m.x + p.x, m.y + p.y);
281 }
282 else if (s.type == PathSegment.BEZIER) {
283 let m = s.s;
284 answer.bezierCurveTo(m.cx1 + p.x, m.cy1 + p.y, m.cx2 + p.x, m.cy2 + p.y, m.x + p.x, m.y + p.y);
285 }
286 else if (s.type == PathSegment.ELLIPSE) {
287 let m = s.s;
288 answer.ellipse(m.x + p.x, m.y + p.y, m.rx, m.ry, m.rot, m.a0, m.a1, m.ccw);
289 }
290 else {
291 console.log("whatever translattion you want, it's not done.");
292 }
293 }
294 return answer;
295 }
296 rotate(a) {
297 // Rotate this entire path about the origin and return the result.
298 // BUG: I have only implemented this for bezier curves and lines.
299 // Expanding this probably doesn't make sense until I settle on a
300 // framework to more fully replace Path2D.
301 let answer = new FPath();
302 for (let i = 0; i < this.segs.length; i++) {
303 let s = this.segs[i];
304 if (s.type == PathSegment.MOVE_TO) {
305 let m = s.s;
306 let p = new Point2D(m.x, m.y).rotate(a);
307 answer.moveTo(p.x, p.y);
308 }
309 else if (s.type == PathSegment.LINE_TO) {
310 let m = s.s;
311 let p = new Point2D(m.x, m.y).rotate(a);
312 answer.lineTo(p.x, p.y);
313 }
314 else if (s.type == PathSegment.BEZIER) {
315 let m = s.s;
316 let c1 = new Point2D(m.cx1, m.cy1).rotate(a);
317 let c2 = new Point2D(m.cx2, m.cy2).rotate(a);
318 let e = new Point2D(m.x, m.y).rotate(a);
319 answer.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, e.x, e.y);
320 }
321 else {
322 console.log("whatever rotation you want, it's not done.");
323 }
324 }
325 return answer;
326 }
327 scale(r) {
328 // Scale this entire path about the origin and return the result.
329 // BUG: I have only implemented this for bezier curves and lines.
330 let answer = new FPath();
331 for (let i = 0; i < this.segs.length; i++) {
332 let s = this.segs[i];
333 if (s.type == PathSegment.MOVE_TO) {
334 let m = s.s;
335 let p = new Point2D(r * m.x, r * m.y);
336 answer.moveTo(p.x, p.y);
337 }
338 else if (s.type == PathSegment.LINE_TO) {
339 let m = s.s;
340 // BUG:
341 console.log("scale not done for lines");
342 }
343 else if (s.type == PathSegment.BEZIER) {
344 let m = s.s;
345 let c1 = new Point2D(r * m.cx1, r * m.cy1);
346 let c2 = new Point2D(r * m.cx2, r * m.cy2);
347 let p = new Point2D(r * m.x, r * m.y);
348 answer.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
349 }
350 else {
351 console.log("whatever scale you want, it's not done.");
352 }
353 }
354 return answer;
355 }
356 reflectX() {
357 // Reflect this entire path about the x-axis and return the result.
358 // BUG: not implemented for every case.
359 let answer = new FPath();
360 for (let i = 0; i < this.segs.length; i++) {
361 let s = this.segs[i];
362 if (s.type == PathSegment.MOVE_TO) {
363 let m = s.s;
364 let p = new Point2D(m.x, -m.y);
365 answer.moveTo(p.x, p.y);
366 }
367 else if (s.type == PathSegment.LINE_TO) {
368 let m = s.s;
369 let p = new Point2D(m.x, -m.y);
370 answer.lineTo(p.x, p.y);
371 }
372 else if (s.type == PathSegment.BEZIER) {
373 let m = s.s;
374 let c1 = new Point2D(m.cx1, -m.cy1);
375 let c2 = new Point2D(m.cx2, -m.cy2);
376 let p = new Point2D(m.x, -m.y);
377 answer.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
378 }
379 else if (s.type == PathSegment.ELLIPSE) {
380 let m = s.s;
381 answer.ellipse(m.x, -m.y, m.rx, m.ry, m.rot, m.a0, m.a1, m.ccw);
382 }
383 else {
384 console.log("whatever reflect you want, it's not done.");
385 }
386 }
387 return answer;
388 }
389 reflectXY() {
390 // Reflect this entire path about the x-axis AND y-axis.
391 // BUG: not implemented for every case.
392 // BUG: Also, what about reflectY()?
393 let answer = new FPath();
394 for (let i = 0; i < this.segs.length; i++) {
395 let s = this.segs[i];
396 if (s.type == PathSegment.MOVE_TO) {
397 let m = s.s;
398 let p = new Point2D(-m.x, -m.y);
399 answer.moveTo(p.x, p.y);
400 }
401 else if (s.type == PathSegment.LINE_TO) {
402 let m = s.s;
403 // BUG:
404 console.log("reflect not done for lines");
405 }
406 else if (s.type == PathSegment.BEZIER) {
407 let m = s.s;
408 let c1 = new Point2D(-m.cx1, -m.cy1);
409 let c2 = new Point2D(-m.cx2, -m.cy2);
410 let p = new Point2D(-m.x, -m.y);
411 answer.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
412 }
413 else {
414 console.log("whatever reflect you want, it's not done.");
415 }
416 }
417 return answer;
418 }
419 rotateAbout(a, p) {
420 // Rotate this entire path about p and return the result.
421 let t1 = this.translate(new Point2D(-p.x, -p.y));
422 let t2 = t1.rotate(a);
423 return t2.translate(p);
424 }
425 static arcToBezierNEW(r, a0, a1) {
426 // Generate a series of bezier curves to represent an arc. The result
427 // represents an arc of a circle of radius r, centered
428 // at (0,0), going from angle a0 to a1, in radians.
429 // Each step should subtend no more than pi/4 radians. Most of the
430 // time pi/2 would be accurate enough, but pi/4 is better, and not that
431 // much extra work.
432 let totalAngle = a1 - a0;
433 if (totalAngle < 0)
434 totalAngle += 2 * Math.PI;
435 let numCurves = Math.ceil(4 * totalAngle / Math.PI);
436 let subtend = totalAngle / numCurves;
437 // See the manual for where this comes from. It's the crucial constant
438 // for approximating arcs of circles by cubics.
439 let k = (4 / 3) * Math.tan(subtend / 4);
440 // Everything is built out of a single arc for a circle of radius r,
441 // going cw, starting at (1,0) and angle subtend.
442 let s = Math.sin(subtend);
443 let c = Math.cos(subtend);
444 let p1 = new Point2D(r, 0);
445 let p2 = new Point2D(r, r * k);
446 let p3 = new Point2D(r * (c + k * s), r * (s - k * c));
447 let p4 = new Point2D(r * c, r * s);
448 // The arc determined by the p_i above must be rotated to create
449 // a series of sub-arcs to get the total arc we want.
450 let answer = new FPath();
451 answer.moveTo(p1.x, p1.y);
452 for (let i = 0; i < numCurves; i++) {
453 answer.bezierCurveTo(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
454 p2.rotateSelf(subtend);
455 p3.rotateSelf(subtend);
456 p4.rotateSelf(subtend);
457 }
458 // Rotate the entire thing so that it starts at a0.
459 answer = answer.rotate(a0);
460 return answer;
461 }
462 arc(x, y, r, a0, a1, ccw) {
463 // BUG: I am pretty sure this isn't right. There are things about
464 // being cw/cww and things like that. It needs to be tested.
465 // A circular arc, centered at (x,y) and radius r, from angle
466 // a0 to angle a1 (in radians), going cw or ccw. Like ellipse, this
467 // is basically independent of the surrounding segments. Actually,
468 // the documentation I've found is a little vague on this point,
469 // but it looks like that is how it works.
470 //
471 // Another issue is the fact that these angles, a0 and a1, may
472 // have "extra" multiples of 2pi in them and whether a1>a0.
473 // The first thing this does is reduce the angles to be in [0,2pi).
474 //
475 // The whole cw versus ccw issue amounts to whether you're getting
476 // the "large" arc or the "small" arc. If a1 > a0, then the ccw arc
477 // is the small arc and the cw arc is the large arc. If a1 < a0,
478 // then the ccw arc is the large arc and the cw arc is the small arc.
479 // To untangle this, assume that the arc will be treated ccw, and
480 // swap a1 and a0, if necessary, to make that the case.
481 //
482 // Finally, there's the issue of what cw and ccw mean when in
483 // left or right handed coordinate systems. Ugh.
484 //
485 // See
486 // https://pomax.github.io/bezierinfo/#circles_cubic
487 // for an explanation of the math, which is just HS algrbra.
488 //
489 //
490 // BUG: Seems like this is a special case of an arc of an ellipse.
491 if (ccw === undefined)
492 ccw = false;
493 // Reduce angles to be in [0,2pi).
494 while (a0 < 0)
495 a0 += 2 * Math.PI;
496 while (a1 < 0)
497 a1 += 2 * Math.PI;
498 while (a0 >= 2 * Math.PI)
499 a0 -= 2 * Math.PI;
500 while (a1 >= 2 * Math.PI)
501 a1 -= 2 * Math.PI;
502 // If the user asked for cw, then swap the angles so that we only
503 // need to consider the ccw case below.
504 if (ccw === true) {
505 let temp = a1;
506 a1 = a0;
507 a0 = temp;
508 }
509 // Get the various arcs for a circle centered at zero.
510 let arcs = FPath.arcToBezierNEW(r, a0, a1);
511 // Translate them all by (x,y).
512 arcs = arcs.translate(new Point2D(x, y));
513 this.addPath(arcs);
514 }
515 ellipse(x, y, rx, ry, rot, a0, a1, ccw) {
516 // BUG: Long-term, the right thing to do here is convert it (internally)
517 // to a series of bezier curves.
518 if (ccw === undefined)
519 ccw = false;
520 super.ellipse(x, y, rx, ry, rot, a0, a1, ccw);
521 this.segs.push(PathSegment.getEllipse(x, y, rx, ry, rot, a0, a1, ccw));
522 }
523 rect(x, y, w, h) {
524 // BUG: As above, make into a series of line segments. This one is easy.
525 super.rect(x, y, w, h);
526 this.segs.push(PathSegment.getRect(x, y, w, h));
527 }
528 static circArcToBezier(r, a0, a1) {
529 // Return a series of n bezier curves for a circle of radius r, extending
530 // from r(cos a0,sin a0) to r (cos a1,sin a1).
531 //
532 // BUG: This should really be part of ellipse().
533 let answer = FPath.arcToBezierNEW(r, a0, a1);
534 return answer;
535 }
536 static parametricToBezier(f, t0, t1, n) {
537 // Given a 2D parametric curve, f(t) = x(t),y(t)), this returns a bezier
538 // approximation from t=t0 to t=t1 by taking n time-steps. Obviously,
539 // f must be a function returning f.x and f.y.
540 //
541 // This works by sampling f (n+1) times, plus n times at the in
542 // between points, and fitting a Bezier to each trio of points. It
543 // follows the notes in the "main" manual. This is a hard problem -- or
544 // a messy one. There are various strategies. The one used here is to
545 // choose the tangent at the intermediate point (which I call B) to be
546 // parallel to the line between the two end-points of the Bezier segment.
547 // This is relatively straightforward, but one problem with this is that
548 // the slopes where these segments meet need not be the same -- the
549 // resulting curve is not G_1. I'm pretty sure that I worked out a method
550 // once that was based (somehow?) on the way MetaPost works, but it's
551 // complicated and messy and uses complex numbers.
552 let p = new FPath();
553 let p1 = f(t0);
554 p.moveTo(p1.x, p1.y);
555 for (let i = 0; i < n; i++) {
556 let p4 = f(t0 + (i + 1) * (t1 - t0) / n);
557 let B = f(t0 + (i + 0.5) * (t1 - t0) / n);
558 // Work out an appropriate value for t based on relative distances.
559 let d1 = Math.sqrt((B.x - p1.x) ** 2 + (B.y - p1.y) ** 2);
560 let d2 = Math.sqrt((B.x - p4.x) ** 2 + (B.y - p4.y) ** 2);
561 let t = d1 / (d1 + d2);
562 // The p4 to p1 vector:
563 let V = new Point2D(p4.x - p1.x, p4.y - p1.y);
564 // e1 = B - (1-t)(p4-p1)/3 and e2 = B + t(p4-p1)/3.
565 let e1 = new Point2D(B.x - (1 - t) * V.x / 3, B.y - (1 - t) * V.y / 3);
566 let e2 = new Point2D(B.x + t * V.x / 3, B.y + t * V.y / 3);
567 // Run de Casteljau's algorithm backwards. I call this alpha too,
568 // but r is a better name since it's a ratio.
569 let r = 1 - 1 / (t ** 3 + (1 - t) ** 3);
570 let u = (1 - r) * (1 - t) ** 3;
571 let C = new Point2D(p1.x * u + p4.x * (1 - u), p1.y * u + p4.y * (1 - u));
572 let A = new Point2D(B.x + (C.x - B.x) / r, B.y + (C.y - B.y) / r);
573 let v1 = new Point2D((e1.x - A.x * t) / (1 - t), (e1.y - A.y * t) / (1 - t));
574 let v2 = new Point2D((e2.x - A.x * (1 - t)) / t, (e2.y - A.y * (1 - t)) / t);
575 let p2 = new Point2D((v1.x - p1.x * (1 - t)) / t, (v1.y - p1.y * (1 - t)) / t);
576 let p3 = new Point2D((v2.x - p4.x * t) / (1 - t), (v2.y - p4.y * t) / (1 - t));
577 p.bezierCurveTo(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
578 p1 = p4.copy();
579 }
580 return p;
581 }
582 }
583 // Text is a special case because it expects a LH coordinate system, but
584 // everything else is set up for a RH coordinate system. The end-user
585 // shouldn't make a direct call to ctx.fillText(). If he does, then the
586 // the text will be upside-down. So, call this instead.
587 //
588 // Getting the placement of the js to match the placement of the tikz exactly
589 // is difficult because they're using two different fonts. So the tikz
590 // is drawn at (x+dx,y+dy). The dx and dy are optional and default to zero.
591 //
592 // BUG: I *could* create a class, something like FPath, to handle all drawing
593 // of text, which may be more natural to the user. But I would probably have
594 // to extend CanvasRenderingContext2D somehow and use that everywhere, not
595 // just when creating TikZ. For now, this is a sufficient solution.
596 // Another approach would be to overwrite the existing
597 // CanvasRenderingContext2D.fillText method to call the function below.
598 // In some ways, that's the "right" thing to do, but my gut is that
599 // it could lead to various problems and make the code generally brittle.
600 function drawText(ctx, txt, x, y, dx = 0, dy = 0) {
601 let saveT = ctx.getTransform();
602 if (ctx instanceof CTX) {
603 // Don't fool around. Just write it to the .tikz file.
604 // BUG: The ts compiler complains about this, but it works fine.
605 ctx.fillText(txt, x + dx, y + dy);
606 ctx.setTransform(saveT);
607 return;
608 }
609 // Get the measurements -- all we really care about is the baseline.
610 // Transform the ctx so that the horizontal line at y becomes the
611 // origin, flip the scale, and draw at (x,0).
612 //
613 // Recapitulating the info on MDN, we care about m.actualBoundingBoxAscent
614 // and m.actualBoundBoxDescent, which give distances from ctx.textBaseline
615 // to the relevant side of the bounding box of the text. The baseline
616 // defaults to the 'alphabetic' setting, which puts the baseline just
617 // under where you normally draw the letter -- B sits on the baseline,
618 // while p hangs below it.
619 let m = ctx.measureText(txt);
620 ctx.translate(0, y);
621 ctx.scale(1, -1);
622 ctx.textBaseline = 'bottom';
623 ctx.fillText(txt, x, 0);
624 ctx.setTransform(saveT);
625 }
626 // As above, but these to draw the text in only one scenario or
627 // the other. This could be handled with boolean arguments to the
628 // above, but this seems clearer for the user.
629 function drawTextBrowserOnly(ctx, txt, x, y, dx = 0, dy = 0) {
630 if (ctx instanceof CTX)
631 // Skip it.
632 return;
633 drawText(ctx, txt, x, y, dx, dy);
634 }
635 function drawTextTikZOnly(ctx, txt, x, y, dx = 0, dy = 0) {
636 if (ctx instanceof CTX)
637 ctx.fillText(txt, x + dx, y + dy);
638 }
639 // This is to act much like the object returned from
640 // canvas.getContext('2d').
641 // Only a few elements of the standard context class are needed.
642 // I purposely did *not* make this extend CanvasRenderingContext2D.
643 // By not extending, you can't accidentally make use of some feature
644 // of the normal ctx framework and have it silently fail.
645 //
646 // This is one major difference. Each time you want to render a figure,
647 // you need a new one of these since the tikz text goes out to a file
648 // with a different name. In principle, it would be possible to allow
649 // reusing these, but there's no value in allowing for that.
650 // I had hoped not to need to deal with transformation matricies, and
651 // just (implicitly) use the identity matrix. However, certain things
652 // are easier for the user if they are permitted. See
653 // www.alanzucconi.com/2016/02/10/tranfsormation-matrix
654 // for a brief summary of how these work.
655 //
656 // Think of the matrix as R in the upper left, for rotation etc, and
657 // (tx,ty,1) in the right column for translation, with M as the overall
658 // matrix. The bottom row is always (0 0 1). If the user gives (x y) as
659 // some position relative to M, then the "real" position is M(x y 1).
660 // By "real" I mean that position relative to the identity matrix.
661 //
662 // BUG: I think I am doing this the wrong way. As things stand, I store
663 // the thing the user does (the path and any points or whatever that
664 // specify) in terms given by the user. Then I convert those values to
665 // their "unadjusted" values when written to tikz output. Instead, I should
666 // convert things as they come in. For one thing, as things stand, if
667 // the user adjusts the t-matrix as things are drawn, it would mess up
668 // everything. This would also side-step certain questions like what
669 // a shear transformation should mean for something like an ellipse. If
670 // we correct things as just described, then an ellipse is an ellipse,
671 // and it is not shear-transformed, although the points where ellipse
672 // is located would be shear-transformed.
673 //
674 // BUG: Add a flag, like CTX.paper, and set is to true here.
675 // That way, the rendering process can output something different on paper.
676 // This flag will be undefined when run in a browser.
677 class CTX {
678 constructor(name) {
679 // Transformation matrix.
680 // BUG: Try to get rid of this. I think that, now that all drawing is
681 // done with a RH system, this is unnecessary. Everything related to
682 // tmatrix is private and I think it's effectively unused.
683 this.tmatrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
684 // BUG: This is *not* the right way to do things, but it's easier.
685 // The problem is in scaling lengths, which are not points. This is a
686 // particular problem with radii. The proper solution is to work this value
687 // out from the tmatrix, but that's messy.
688 // This is why things like ellipses should be treated as beziers.
689 this.netScale = 1.0;
690 // To allow the user to set the linewidth. Otherwise, tikz uses a
691 // default value of 0.4pt. Tikz has certained named line widths, like
692 // 'semithick' and 'ultra thin' but I don't care about those. It's better
693 // to stick with numerical values to be consistent with js.
694 // This name matches what's used in a "normal" ctx.
695 // The way to specify line width in tikz is as an option to \draw:
696 // \draw[line width = 1mm] ...whatever...
697 // for example.
698 this.lineWidth = 1.0;
699 // File name (without the '.tizk') for the figure.
700 this.figureName = "";
701 // This holds the output as it is generated.
702 this.tikzstr = "";
703 // Provide the name of the figure whose tikz is being generated.
704 // This goes to a file, which is fiddly with js. The contents of the
705 // file will be sent to the server, and it is assumed that the server
706 // knows what to do. A normal HTTP server will choke on it (really,
707 // it will just ignore it).
708 //
709 // As each call to stroke(), fill(), and so forth is made, the corresponding
710 // tikz is noted. When all these are calls are done, call close() to write it out.
711 this.figureName = name;
712 this.tikzstr = "";
713 // The tikz file needs a bit of a heading.
714 this.tikzstr += "\\begin{tikzpicture}\n";
715 // And everything is clipped to the permitted drawing area. To obtain
716 // that area, we need to look at the figure specification.
717 let myFunc = getAugmentedFunction(name);
718 let fpc = myFunc.figurePanelClass;
719 // Neither one really seems to give the right thing.
720 // Maybe use \clip as an option to
721 // \begin{tikzpicture}[\clip something?]
722 //this.tikzstr += "\\clip (0bp,0bp) rectangle (" +fpc.textWidth+
723 // "bp," + fpc.h+ "bp);\n";
724 this.tikzstr += "\\useasboundingbox (0bp,0bp) rectangle (" + fpc.textWidth.toFixed(2) +
725 "bp," + (fpc.h - fpc.lowerPadding - fpc.upperPadding).toFixed(2) + "bp);\n";
726 }
727 close() {
728 // Finalize the tikz specification, and write it out.
729 //
730 // Note that, under Firefox, this generates an error on the console:
731 //
732 // XML Parsing Error: no root element found
733 // Location: http://localhost:8000/geartest01.tikz
734 // Line Number 1, Column 1:
735 //
736 // or whatever the file name is that's saved. Apparently this is a
737 // "known issue" (aka, a bug) with Firefox. No such message appears
738 // with MS Edge. It works the same either way.
739 this.tikzstr += "\\end{tikzpicture}\n";
740 // BUG: No doubt there is a more modern fetch() way to do this.
741 let req = new XMLHttpRequest();
742 // This is *really* not the standard way to do things.
743 // Pass the file name to save under, then the text to save.
744 // I *should* be passing some cgi script that takes input, but
745 // I've tweaked the http server so that it's non-standard,
746 // and does what I want instead of what it is supposed to do.
747 let fname = this.figureName + ".tikz";
748 req.open("POST", fname);
749 // I have no idea whether this is really necessary.
750 req.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
751 req.send(this.tikzstr);
752 }
753 static clone3x3Matrix(m) {
754 // JS seems not to have a standard way of creating a copy of a matrix.
755 // This does it for a 3x3 matrix and returns the result.
756 let a = [];
757 a[0] = [];
758 a[0][0] = m[0][0];
759 a[0][1] = m[0][1];
760 a[0][2] = m[0][2];
761 a[1] = [];
762 a[1][0] = m[1][0];
763 a[1][1] = m[1][1];
764 a[1][2] = m[1][2];
765 a[2] = [];
766 a[2][0] = m[2][0];
767 a[2][1] = m[2][1];
768 a[2][2] = m[2][2];
769 return a;
770 }
771 getTransform() {
772 return CTX.clone3x3Matrix(this.tmatrix);
773 }
774 setTransform(t) {
775 this.tmatrix = CTX.clone3x3Matrix(t);
776 }
777 translate(tx, ty) {
778 // Adjust the transformation matrix. Going forward, this will have the
779 // effect of converting (x,y) to (tx + x,ty+y) whenever the user
780 // refers to (x,y).
781 this.tmatrix[0][2] += tx;
782 this.tmatrix[1][2] += ty;
783 }
784 scale(sx, sy) {
785 // Scale the transformation matrix.
786 // Let S = diag(sx,sy,1). The new t-matrix is the old t-matrix times S.
787 //
788 // BUG: I am not sure. Maybe it should be S times old t-matrix, and
789 // I have the order wrong. For the time being it doesn't matter since
790 // every case I care about has sx=sy and the matrices commute in that
791 // special case.
792 this.tmatrix[0][0] *= sx;
793 this.tmatrix[0][1] *= sy;
794 this.tmatrix[1][0] *= sx;
795 this.tmatrix[1][1] *= sy;
796 // Track this here too.
797 // BUG: This assumes that sx = xy.
798 this.netScale *= sx;
799 }
800 applyTMatrix(x, y) {
801 // Return tmatrix times (x,y). As a matrix operation, this is
802 // tmatrix x (x y 1), but we only return the first two entries.
803 let ax = this.tmatrix[0][0] * x + this.tmatrix[0][1] * y + this.tmatrix[0][2];
804 let ay = this.tmatrix[1][0] * x + this.tmatrix[1][1] * y + this.tmatrix[1][2];
805 return { x: ax, y: ay };
806 }
807 handlePath(path) {
808 // Called by either fill() or stroke().
809 var segs = path.segs;
810 for (let i = 0; i < segs.length; i++) {
811 // s is a PathSegment object.
812 let s = segs[i];
813 if (s.type == PathSegment.MOVE_TO) {
814 let m = s.s;
815 let t = this.applyTMatrix(m.x, m.y);
816 //this.tikzstr += "(" +s.x+ "pt, " + s.y+ "pt) ";
817 this.tikzstr += "(" + t.x.toFixed(2) + "bp, " + t.y.toFixed(2) + "bp) ";
818 }
819 else if (s.type == PathSegment.LINE_TO) {
820 // Lines are drawn with the tikz \draw command. It takes the form
821 // \draw [options] (x1,y1) -- (x2,y2);
822 // Note that I include "bp" for the dimensions. I think that tikz
823 // defaults to cm if no dimension is given, so I should specify
824 // something. Note also that I use bp, not pt.
825 //
826 // BUG: I am not sure whether the tikz point is 72ppi or 72.27 ppi
827 // to match latex.
828 //
829 // BUG: For the time being, I will ignore these options, but they
830 // can be things like fill or dashed, or to set the color or line
831 // width, and probably a mess of other stuff.
832 let m = s.s;
833 let t = this.applyTMatrix(m.x, m.y);
834 this.tikzstr += "-- (" + t.x.toFixed(2) + "bp, " + t.y.toFixed(2) + "bp) ";
835 }
836 else if (s.type == PathSegment.BEZIER) {
837 // The sources I found aren't very explicit about exactly how
838 // this is implemented. I assume it's done in the usual way.
839 // We have
840 // P(t) = B(3,0)*CP + B(3,1)*P1 + B(3,2)*P2 + B(3,3)*P3,
841 // where t\in [0,1] and B are the usual Bernstein polynomials (the
842 // functions of t):
843 // B(n,m) = C(n,m) t^m (1-t)^(n-m),
844 // and C is the choice function.
845 // See also the tikz/pgf manual (v3.1.9a), p. 156, for the output.
846 // However the manual is wrong, or not clear. Use 'and' between
847 // the control points.
848 //
849 // The gist is that CP is fixed point where the curve starts;
850 // it's implicit for both Java and tikz. P1 and P2 are the control
851 // points and P3 is where the curve terminates. Fortunately this
852 // matches up nicely with the tikz syntax.
853 let m = s.s;
854 let t1 = this.applyTMatrix(m.cx1, m.cy1);
855 let t2 = this.applyTMatrix(m.cx2, m.cy2);
856 let t3 = this.applyTMatrix(m.x, m.y);
857 this.tikzstr +=
858 ".. controls (" + t1.x.toFixed(2) + "bp, " + t1.y.toFixed(2) + "bp) and (" +
859 t2.x.toFixed(2) + "bp, " + t2.y.toFixed(2) + "bp) .. (" +
860 t3.x.toFixed(2) + "bp, " + t3.y.toFixed(2) + "bp)";
861 }
862 else if (s.type == PathSegment.QUADRATIC) {
863 // BUG: Put this back.
864 console.log("quadratic does not work");
865 // Tikz has this too (whew). Oddly, it's part of the pgf stuff.
866 // Everything else is drawn with \draw (or \fill), but this
867 // uses \pgfpathquadraticcurveto. I'm not sure if that matters,
868 // and I hope that you can mix these freely in the middle of
869 // a \draw command. The tikz/pgf manual isn't very clear on
870 // mixing these.
871 // BUG: I wonder if I should be using commands like \pgflineto,
872 // \pgfcurveto, and so forth, throughout what I've done.
873 // See the tikz/pgf manul (v3.1.9a), p. 1095.
874 //
875 // BUG: I'm going to code this hoping that it works, but I suspect
876 // that it will not, and will need to go back and change to
877 // something other than \draw or \fill to start with.
878 // Maybe I need to define an entire path and then \draw or \fill
879 // it? It looks like you define that path, then say
880 // \pgfusepath{fill} or whatever.
881 //
882 // BUG: Maybe I could convert this to a cubic here and avoid this
883 // entire messy issue?
884 //
885 // NOTE: pgf has some nice commands for drawing only *part* of
886 // a Bezier curve. See p. 1097 for \pgfpathcurvebetweentime.
887 // BUG: Maybe I'll be lucky and this is never called.
888 // I think (?) it must be that the only time this type of
889 // segment ever arises is if the user users a QuadCurve2D, which
890 // seems (?) unlikely.
891 /*
892 let t1 = this.applyTMatrix(s.cx,s.cy);
893 let t2 = this.applyTMatrix(s.x,s.y);
894
895 //this.tikzstr +=
896 // "\\pgfpathquadraticcurveto {\\pgfpoint{" +
897 // s.cx+ "pt}{" +x.cy+ "pt}}{\\pgfpoint{" +
898 // s.x+ "pt}{" +s.y+ "pt}}";
899 this.tikzstr +=
900 "\\pgfpathquadraticcurveto {\\pgfpoint{" +
901 t1.x+ "bp}{" +t1.y+ "bp}}{\\pgfpoint{" +
902 t2.x+ "bp}{" +t2.y+ "bp}}";
903 */
904 }
905 else if (s.type == PathSegment.ARC) {
906 console.log("arc");
907 // This is a circular arc of a circle
908 // centered at (x,y) over a given range of angles (cw or ccw).
909 //
910 // BUG: For the remaining cases, I may need to do something
911 // special. It's not clear exactly what the browser is doing
912 // with these. Are they converted, internally, to bezier
913 // curves or are they somehow rendered more directly.
914 this.tikzstr += "no arc implemented";
915 }
916 else if (s.type == PathSegment.ARC_TO) {
917 console.log("arc to not done");
918 // This is essentially a bezier curve.
919 // You have two control points and a radius. It is not
920 // clear exactly how it works.
921 this.tikzstr += "no arcTo implemented";
922 }
923 else if (s.type == PathSegment.ELLIPSE) {
924 // BUG: This will only draw a complete ellipse, not an arc of
925 // an ellipse.
926 // BUG: The foolishness with netScale is another reason not
927 // to allow an ellipse type. If an ellipse were really a series
928 // of bezier curves, then this would be a non-issue.
929 let m = s.s;
930 let c = this.applyTMatrix(m.x, m.y);
931 //console.log(s.x+ "," +s.y+ " becomes " +c.x+ " " +c.y);
932 //this.tikzstr += "(" +c.x+ "pt," +c.y+
933 // "pt) ellipse [x radius=" +s.rx*this.netScale+
934 // "pt,y radius =" + s.ry*this.netScale+ "pt]";
935 this.tikzstr += "(" + c.x.toFixed(2) + "bp," + c.y.toFixed(2) +
936 "bp) ellipse [x radius=" + (m.rx * this.netScale).toFixed(2) +
937 "bp,y radius =" + (m.ry * this.netScale).toFixed(2) + "bp]";
938 }
939 else if (s.type == PathSegment.RECT) {
940 console.log("rect not done");
941 this.tikzstr += "no rect implemented";
942 }
943 else if (s.type == PathSegment.CLOSE) {
944 this.tikzstr += "-- cycle";
945 }
946 else {
947 console.log("unknown FPath: " + s.type);
948 }
949 }
950 this.tikzstr += ";\n";
951 }
952 stroke(path) {
953 let segs = path.segs;
954 if (segs.length === 0)
955 return;
956 this.tikzstr += "\\draw[line width=" + this.lineWidth.toFixed(2) + "bp] ";
957 this.handlePath(path);
958 }
959 fill(path) {
960 let segs = path.segs;
961 if (segs.length === 0)
962 return;
963 this.tikzstr += "\\fill ";
964 this.handlePath(path);
965 }
966 fillText(s, x, y) {
967 // BUG: This is now done with top-level functions now and shouldn't
968 // be called (or callable) by outside code.
969 //
970 // BUG: I have my doubts about including this one. It needs to be done
971 // *somehow*, but I am concerned about a mismatch between the JS
972 // font and the fonts used by latex.
973 //
974 // BUG: I am ignoring the ctx.font setting. It does seem that if you
975 // set it to '10px san-serif' you get something reasonable for the
976 // browswer that doesn't look too different than latex.
977 //
978 // BUG: This is so fussy that I suspect that any drawing that is at
979 // all tricky will require that the user provide different placement for
980 // text on the browser and text on the page. Getting things to match
981 // up *exactly* may be impossible.
982 let t = this.applyTMatrix(x, y);
983 // I had this as 'anchor=south west', but 'base west' seems closer
984 // to what latex does.
985 // BUG: It's all a mystery.
986 this.tikzstr +=
987 "\\node [anchor=base west] at (" + t.x.toFixed(2) + "pt, " + t.y.toFixed(2) + "pt) {" + s + "};\n";
988 }
989 }
990 class Numerical {
991 static newton(f, g, a, b, y, e) {
992 // Given a function, f, and an initial guess, g, bracketed between a and b,
993 // for the argument to f, and a target value, y, this returns x such that
994 // f(x) = y to within error, e.
995 //
996 // A crude off-the-cuff implementation of Newton-Raphson.
997 // This will only work in the tamest situations.
998 //
999 // Recall that the idea is that
1000 // f(x0 + dx) ~ f(x0) + f'(x0) dx
1001 // We want y = f(x + dx) and that is approximately equivalent to
1002 // y = f(x0) + f'(x0) dx or dx = ( y - f(x0) ) / f'(x0)
1003 // so that x0 becomes x1 = x0 + dx = x0 + ( y - f(x0) ) / f'(x0)
1004 //
1005 // NOTE: I had hoped to avoid the need to bracket entirely, and for
1006 // some functions (and sufficiently good initial guesses), you could,
1007 // but it's too easy for the algorithm to get lost among local extrema
1008 // if there is no bracket.
1009 //
1010 // In fact, here is a good example of why bracketing is needed.
1011 // Let f = cos x + x sin x, which happens to be the x-coordinate for
1012 // the parameterization of the unit involute. Suppose that you want
1013 // to find x for which f(x) = 1.5, and you start off with a guess of
1014 // x = 0.5. The slope of f at 0.5 is small so that Newton-Raphson
1015 // sends x1 to a value that is beyond the inflection point near x = 3.
1016 // At that point things go haywire.
1017 let x0 = g;
1018 let y0 = f(x0);
1019 let i = 0;
1020 while (Math.abs(y - y0) > e) {
1021 let fplus = f(x0 + e);
1022 let fminus = f(x0 - e);
1023 let fprime = (fplus - fminus) / (2 * e);
1024 let dx = (y - y0) / fprime;
1025 let x1 = x0 + dx;
1026 // Make sure we haven't passed a bracket. Just subdivide if we have.
1027 if (x1 > b)
1028 x1 = (x1 - x0) / 2;
1029 if (x1 < a)
1030 x1 = (x0 - x1) / 2;
1031 x0 = x1;
1032 y0 = f(x0);
1033 // Don't allow an infinite loop
1034 ++i;
1035 if (i > 100)
1036 return x0;
1037 }
1038 return x0;
1039 }
1040 }