1 /*
  2     Copyright 2008-2016
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <http://www.gnu.org/licenses/>
 29     and <http://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 
 33 /*global JXG: true, define: true*/
 34 /*jslint nomen: true, plusplus: true*/
 35 
 36 /* depends:
 37  jxg
 38  math/geometry
 39  math/math
 40  base/coords
 41  base/circle
 42  utils/type
 43  base/constants
 44   elements:
 45    curve
 46    midpoint
 47    circumcenter
 48  */
 49 
 50 /**
 51  * @fileoverview In this file the geometry object Arc is defined. Arc stores all
 52  * style and functional properties that are required to draw an arc on a board.
 53  */
 54 
 55 define([
 56     'jxg', 'math/geometry', 'math/math', 'base/coords', 'base/circle', 'utils/type', 'base/constants',
 57     'base/curve', 'element/composition'
 58 ], function (JXG, Geometry, Mat, Coords, Circle, Type, Const, Curve, Compositions) {
 59 
 60     "use strict";
 61 
 62     /**
 63      * @class An arc is a segment of the circumference of a circle. It is defined by a center, one point that
 64      * defines the radius, and a third point that defines the angle of the arc.
 65      * @pseudo
 66      * @name Arc
 67      * @augments Curve
 68      * @constructor
 69      * @type JXG.Curve
 70      * @throws {Error} If the element cannot be constructed with the given parent objects an exception is thrown.
 71      * @param {JXG.Point_JXG.Point_JXG.Point} p1,p2,p3 The result will be an arc of a circle around p1 through p2. The arc is drawn
 72      * counter-clockwise from p2 to p3.
 73      * @example
 74      * // Create an arc out of three free points
 75      * var p1 = board.create('point', [2.0, 2.0]);
 76      * var p2 = board.create('point', [1.0, 0.5]);
 77      * var p3 = board.create('point', [3.5, 1.0]);
 78      *
 79      * var a = board.create('arc', [p1, p2, p3]);
 80      * </pre><div class="jxgbox"id="114ef584-4a5e-4686-8392-c97501befb5b" style="width: 300px; height: 300px;"></div>
 81      * <script type="text/javascript">
 82      * (function () {
 83      *   var board = JXG.JSXGraph.initBoard('114ef584-4a5e-4686-8392-c97501befb5b', {boundingbox: [-1, 7, 7, -1], axis: true, showcopyright: false, shownavigation: false}),
 84      *       p1 = board.create('point', [2.0, 2.0]),
 85      *       p2 = board.create('point', [1.0, 0.5]),
 86      *       p3 = board.create('point', [3.5, 1.0]),
 87      *
 88      *       a = board.create('arc', [p1, p2, p3]);
 89      * })();
 90      * </script><pre>
 91      */
 92     JXG.createArc = function (board, parents, attributes) {
 93         var el, attr, i, points;
 94 
 95         // This method is used to create circumcirclearcs, too. If a circumcirclearc is created we get a fourth
 96         // point, that's why we need to check that case, too.
 97         points = Type.providePoints(board, parents, attributes, 'point');
 98         if (points === false || points.length < 3) {
 99             throw new Error("JSXGraph: Can't create Arc with parent types '" +
100                 (typeof parents[0]) + "' and '" + (typeof parents[1]) + "' and '" +
101                 (typeof parents[2]) + "'." +
102                 "\nPossible parent types: [point,point,point]");
103         }
104 
105         attr = Type.copyAttributes(attributes, board.options, 'arc');
106         el = board.create('curve', [[0], [0]], attr);
107 
108         el.elType = 'arc';
109         el.setParents(points);
110 
111         /**
112          * documented in JXG.GeometryElement
113          * @ignore
114          */
115         el.type = Const.OBJECT_TYPE_ARC;
116 
117         /**
118          * Center of the arc.
119          * @memberOf Arc.prototype
120          * @name center
121          * @type JXG.Point
122          */
123         el.center = points[0];
124 
125         /**
126          * Point defining the arc's radius.
127          * @memberOf Arc.prototype
128          * @name radiuspoint
129          * @type JXG.Point
130          */
131         el.radiuspoint = points[1];
132         el.point2 = el.radiuspoint;
133 
134         /**
135          * The point defining the arc's angle.
136          * @memberOf Arc.prototype
137          * @name anglepoint
138          * @type JXG.Point
139          */
140         el.anglepoint = points[2];
141         el.point3 = el.anglepoint;
142 
143         // Add arc as child to defining points
144         el.center.addChild(el);
145         el.radiuspoint.addChild(el);
146         el.anglepoint.addChild(el);
147 
148         // should be documented in options
149         el.useDirection = attr.usedirection;
150 
151         // documented in JXG.Curve
152         el.updateDataArray = function () {
153             var ar, phi, v, det, p0c, p1c, p2c,
154                 sgn = 1,
155                 A = this.radiuspoint,
156                 B = this.center,
157                 C = this.anglepoint;
158 
159             phi = Geometry.rad(A, B, C);
160             if ((this.visProp.selection === 'minor' && phi > Math.PI) ||
161                     (this.visProp.selection === 'major' && phi < Math.PI)) {
162                 sgn = -1;
163             }
164 
165             // This is true for circumCircleArcs. In that case there is
166             // a fourth parent element: [center, point1, point3, point2]
167             if (this.useDirection) {
168                 p0c = points[1].coords.usrCoords;
169                 p1c = points[3].coords.usrCoords;
170                 p2c = points[2].coords.usrCoords;
171                 det = (p0c[1] - p2c[1]) * (p0c[2] - p1c[2]) - (p0c[2] - p2c[2]) * (p0c[1] - p1c[1]);
172 
173                 if (det < 0) {
174                     this.radiuspoint = points[1];
175                     this.anglepoint = points[2];
176                 } else {
177                     this.radiuspoint = points[2];
178                     this.anglepoint = points[1];
179                 }
180             }
181 
182             A = A.coords.usrCoords;
183             B = B.coords.usrCoords;
184             C = C.coords.usrCoords;
185 
186             ar = Geometry.bezierArc(A, B, C, false, sgn);
187 
188             this.dataX = ar[0];
189             this.dataY = ar[1];
190 
191             this.bezierDegree = 3;
192 
193             this.updateStdform();
194             this.updateQuadraticform();
195         };
196 
197         /**
198          * Determines the arc's current radius. I.e. the distance between {@link Arc#center} and {@link Arc#radiuspoint}.
199          * @memberOf Arc.prototype
200          * @name Radius
201          * @function
202          * @returns {Number} The arc's radius
203          */
204         el.Radius = function () {
205             return this.radiuspoint.Dist(this.center);
206         };
207 
208         /**
209          * @deprecated Use {@link Arc#Radius}
210          * @memberOf Arc.prototype
211          * @name getRadius
212          * @function
213          * @returns {Number}
214          */
215         el.getRadius = function () {
216             JXG.deprecated('Arc.getRadius()', 'Arc.Radius()');
217             return this.Radius();
218         };
219 
220         /**
221          * Returns the length of the arc.
222          * @memberOf Arc.prototype
223          * @name Value
224          * @function
225          * @returns {Number} The arc length
226          */
227         el.Value = function () {
228             return this.Radius() * Geometry.rad(this.radiuspoint, this.center, this.anglepoint);
229         };
230 
231         // documented in geometry element
232         el.hasPoint = function (x, y) {
233             var dist, checkPoint,
234                 has, angle, alpha, beta,
235                 invMat, c,
236                 prec = this.board.options.precision.hasPoint / this.board.unitX,
237                 r = this.Radius();
238 
239             checkPoint = new Coords(Const.COORDS_BY_SCREEN, [x, y], this.board);
240 
241             if (this.transformations.length > 0) {
242                 // Transform the mouse/touch coordinates
243                 // back to the original position of the curve.
244                 this.updateTransformMatrix();
245                 invMat = Mat.inverse(this.transformMat);
246                 c = Mat.matVecMult(invMat, checkPoint.usrCoords);
247                 checkPoint = new Coords(Const.COORDS_BY_USER, c, this.board);
248             }
249 
250             dist = this.center.coords.distance(Const.COORDS_BY_USER, checkPoint);
251             has = (Math.abs(dist - r) < prec);
252 
253             /**
254              * At that point we know that the user has touched the circle line.
255              */
256             if (has) {
257                 angle = Geometry.rad(this.radiuspoint, this.center, checkPoint.usrCoords.slice(1));
258                 alpha = 0.0;
259                 beta = Geometry.rad(this.radiuspoint, this.center, this.anglepoint);
260 
261                 if ((this.visProp.selection === 'minor' && beta > Math.PI) ||
262                         (this.visProp.selection === 'major' && beta < Math.PI)) {
263                     alpha = beta;
264                     beta = 2 * Math.PI;
265                 }
266                 if (angle < alpha || angle > beta) {
267                     has = false;
268                 }
269             }
270 
271             return has;
272         };
273 
274         /**
275          * Checks whether (x,y) is within the sector defined by the arc.
276          * @memberOf Arc.prototype
277          * @name hasPointSector
278          * @function
279          * @param {Number} x Coordinate in x direction, screen coordinates.
280          * @param {Number} y Coordinate in y direction, screen coordinates.
281          * @returns {Boolean} True if (x,y) is within the sector defined by the arc, False otherwise.
282          */
283         el.hasPointSector = function (x, y) {
284             var angle, alpha, beta,
285                 checkPoint = new Coords(Const.COORDS_BY_SCREEN, [x, y], this.board),
286                 r = this.Radius(),
287                 dist = this.center.coords.distance(Const.COORDS_BY_USER, checkPoint),
288                 has = (dist < r);
289 
290             if (has) {
291                 angle = Geometry.rad(this.radiuspoint, this.center, checkPoint.usrCoords.slice(1));
292                 alpha = 0;
293                 beta = Geometry.rad(this.radiuspoint, this.center, this.anglepoint);
294 
295                 if ((this.visProp.selection === 'minor' && beta > Math.PI) ||
296                         (this.visProp.selection === 'major' && beta < Math.PI)) {
297                     alpha = beta;
298                     beta = 2 * Math.PI;
299                 }
300                 if (angle < alpha || angle > beta) {
301                     has = false;
302                 }
303             }
304 
305             return has;
306         };
307 
308         // documented in geometry element
309         el.getTextAnchor = function () {
310             return this.center.coords;
311         };
312 
313         // documented in geometry element
314         el.getLabelAnchor = function () {
315             var coords, vecx, vecy, len,
316                 angle = Geometry.rad(this.radiuspoint, this.center, this.anglepoint),
317                 dx = 10 / this.board.unitX,
318                 dy = 10 / this.board.unitY,
319                 p2c = this.point2.coords.usrCoords,
320                 pmc = this.center.coords.usrCoords,
321                 bxminusax = p2c[1] - pmc[1],
322                 byminusay = p2c[2] - pmc[2];
323 
324             // If this is uncommented, the angle label can not be dragged
325             //if (Type.exists(this.label)) {
326             //    this.label.relativeCoords = new Coords(Const.COORDS_BY_SCREEN, [0, 0], this.board);
327             //}
328 
329             if ((this.visProp.selection === 'minor' && angle > Math.PI) ||
330                     (this.visProp.selection === 'major' && angle < Math.PI)) {
331                 angle = -(2 * Math.PI - angle);
332             }
333 
334             coords = new Coords(Const.COORDS_BY_USER, [
335                 pmc[1] + Math.cos(angle * 0.5) * bxminusax - Math.sin(angle * 0.5) * byminusay,
336                 pmc[2] + Math.sin(angle * 0.5) * bxminusax + Math.cos(angle * 0.5) * byminusay
337             ], this.board);
338 
339             vecx = coords.usrCoords[1] - pmc[1];
340             vecy = coords.usrCoords[2] - pmc[2];
341 
342             len = Math.sqrt(vecx * vecx + vecy * vecy);
343             vecx = vecx * (len + dx) / len;
344             vecy = vecy * (len + dy) / len;
345 
346             return new Coords(Const.COORDS_BY_USER, [pmc[1] + vecx, pmc[2] + vecy], this.board);
347         };
348 
349         // documentation in jxg.circle
350         el.updateQuadraticform = Circle.Circle.prototype.updateQuadraticform;
351 
352         // documentation in jxg.circle
353         el.updateStdform = Circle.Circle.prototype.updateStdform;
354 
355         el.methodMap = JXG.deepCopy(el.methodMap, {
356             getRadius: 'getRadius',
357             radius: 'Radius',
358             center: 'center',
359             radiuspoint: 'radiuspoint',
360             anglepoint: 'anglepoint',
361             Value: 'Value'
362         });
363 
364         el.prepareUpdate().update();
365         return el;
366     };
367 
368     JXG.registerElement('arc', JXG.createArc);
369 
370     /**
371      * @class A semicircle is a special arc defined by two points. The arc hits both points.
372      * @pseudo
373      * @name Semicircle
374      * @augments Arc
375      * @constructor
376      * @type Arc
377      * @throws {Error} If the element cannot be constructed with the given parent objects an exception is thrown.
378      * @param {JXG.Point_JXG.Point} p1,p2 The result will be a composition of an arc drawn clockwise from <tt>p1</tt> and
379      * <tt>p2</tt> and the midpoint of <tt>p1</tt> and <tt>p2</tt>.
380      * @example
381      * // Create an arc out of three free points
382      * var p1 = board.create('point', [4.5, 2.0]);
383      * var p2 = board.create('point', [1.0, 0.5]);
384      *
385      * var a = board.create('semicircle', [p1, p2]);
386      * </pre><div class="jxgbox"id="5385d349-75d7-4078-b732-9ae808db1b0e" style="width: 300px; height: 300px;"></div>
387      * <script type="text/javascript">
388      * (function () {
389      *   var board = JXG.JSXGraph.initBoard('5385d349-75d7-4078-b732-9ae808db1b0e', {boundingbox: [-1, 7, 7, -1], axis: true, showcopyright: false, shownavigation: false}),
390      *       p1 = board.create('point', [4.5, 2.0]),
391      *       p2 = board.create('point', [1.0, 0.5]),
392      *
393      *       sc = board.create('semicircle', [p1, p2]);
394      * })();
395      * </script><pre>
396      */
397     JXG.createSemicircle = function (board, parents, attributes) {
398         var el, mp, attr, points;
399 
400         // we need 2 points
401         points = Type.providePoints(board, parents, attributes, 'point');
402         if (points === false || points.length !== 2) {
403             throw new Error("JSXGraph: Can't create Semicircle with parent types '" +
404                 (typeof parents[0]) + "' and '" + (typeof parents[1]) + "'." +
405                 "\nPossible parent types: [point,point]");
406         }
407 
408         attr = Type.copyAttributes(attributes, board.options, 'semicircle', 'midpoint');
409         mp = board.create('midpoint', points, attr);
410         mp.dump = false;
411 
412         attr = Type.copyAttributes(attributes, board.options, 'semicircle');
413         el = board.create('arc', [mp, points[1], points[0]], attr);
414         el.elType = 'semicircle';
415         el.setParents([points[0].id, points[1].id]);
416         el.subs = {
417             midpoint: mp
418         };
419 
420         /**
421          * The midpoint of the two defining points.
422          * @memberOf Semicircle.prototype
423          * @name midpoint
424          * @type Midpoint
425          */
426         el.midpoint = el.center = mp;
427 
428         return el;
429     };
430 
431     JXG.registerElement('semicircle', JXG.createSemicircle);
432 
433     /**
434      * @class A circumcircle arc is an {@link Arc} defined by three points. All three points lie on the arc.
435      * @pseudo
436      * @name CircumcircleArc
437      * @augments Arc
438      * @constructor
439      * @type Arc
440      * @throws {Error} If the element cannot be constructed with the given parent objects an exception is thrown.
441      * @param {JXG.Point_JXG.Point_JXG.Point} p1,p2,p3 The result will be a composition of an arc of the circumcircle of
442      * <tt>p1</tt>, <tt>p2</tt>, and <tt>p3</tt> and the midpoint of the circumcircle of the three points. The arc is drawn
443      * counter-clockwise from <tt>p1</tt> over <tt>p2</tt> to <tt>p3</tt>.
444      * @example
445      * // Create a circum circle arc out of three free points
446      * var p1 = board.create('point', [2.0, 2.0]);
447      * var p2 = board.create('point', [1.0, 0.5]);
448      * var p3 = board.create('point', [3.5, 1.0]);
449      *
450      * var a = board.create('arc', [p1, p2, p3]);
451      * </pre><div class="jxgbox"id="87125fd4-823a-41c1-88ef-d1a1369504e3" style="width: 300px; height: 300px;"></div>
452      * <script type="text/javascript">
453      * (function () {
454      *   var board = JXG.JSXGraph.initBoard('87125fd4-823a-41c1-88ef-d1a1369504e3', {boundingbox: [-1, 7, 7, -1], axis: true, showcopyright: false, shownavigation: false}),
455      *       p1 = board.create('point', [2.0, 2.0]),
456      *       p2 = board.create('point', [1.0, 0.5]),
457      *       p3 = board.create('point', [3.5, 1.0]),
458      *
459      *       cca = board.create('circumcirclearc', [p1, p2, p3]);
460      * })();
461      * </script><pre>
462      */
463     JXG.createCircumcircleArc = function (board, parents, attributes) {
464         var el, mp, attr, points;
465 
466         // We need three points
467         points = Type.providePoints(board, parents, attributes, 'point');
468         if (points === false || points.length !== 3) {
469             throw new Error("JSXGraph: create Circumcircle Arc with parent types '" +
470                 (typeof parents[0]) + "' and '" + (typeof parents[1]) + "' and '" + (typeof parents[2]) + "'." +
471                 "\nPossible parent types: [point,point,point]");
472         }
473 
474         attr = Type.copyAttributes(attributes, board.options, 'circumcirclearc', 'center');
475         mp = board.create('circumcenter', points, attr);
476         mp.dump = false;
477 
478         attr = Type.copyAttributes(attributes, board.options, 'circumcirclearc');
479         attr.usedirection = true;
480         el = board.create('arc', [mp, points[0], points[2], points[1]], attr);
481 
482         el.elType = 'circumcirclearc';
483         el.setParents([points[0].id, points[1].id, points[2].id]);
484         el.subs = {
485             center: mp
486         };
487 
488         /**
489          * The midpoint of the circumcircle of the three points defining the circumcircle arc.
490          * @memberOf CircumcircleArc.prototype
491          * @name center
492          * @type Circumcenter
493          */
494         el.center = mp;
495 
496         return el;
497     };
498 
499     JXG.registerElement('circumcirclearc', JXG.createCircumcircleArc);
500 
501     /**
502      * @class A minor arc is a segment of the circumference of a circle having measure less than or equal to
503      * 180 degrees (pi radians). It is defined by a center, one point that
504      * defines the radius, and a third point that defines the angle of the arc.
505      * @pseudo
506      * @name MinorArc
507      * @augments Curve
508      * @constructor
509      * @type JXG.Curve
510      * @throws {Error} If the element cannot be constructed with the given parent objects an exception is thrown.
511      * @param {JXG.Point_JXG.Point_JXG.Point} p1,p2,p3 . Minor arc is an arc of a circle around p1 having measure less than or equal to
512      * 180 degrees (pi radians) and starts at p2. The radius is determined by p2, the angle by p3.
513      * @example
514      * // Create an arc out of three free points
515      * var p1 = board.create('point', [2.0, 2.0]);
516      * var p2 = board.create('point', [1.0, 0.5]);
517      * var p3 = board.create('point', [3.5, 1.0]);
518      *
519      * var a = board.create('arc', [p1, p2, p3]);
520      * </pre><div class="jxgbox"id="64ba7ca2-8728-45f3-96e5-3c7a4414de2f" style="width: 300px; height: 300px;"></div>
521      * <script type="text/javascript">
522      * (function () {
523      *   var board = JXG.JSXGraph.initBoard('64ba7ca2-8728-45f3-96e5-3c7a4414de2f', {boundingbox: [-1, 7, 7, -1], axis: true, showcopyright: false, shownavigation: false}),
524      *       p1 = board.create('point', [2.0, 2.0]),
525      *       p2 = board.create('point', [1.0, 0.5]),
526      *       p3 = board.create('point', [3.5, 1.0]),
527      *
528      *       a = board.create('minorarc', [p1, p2, p3]);
529      * })();
530      * </script><pre>
531      */
532 
533     JXG.createMinorArc = function (board, parents, attributes) {
534         attributes.selection = 'minor';
535         return JXG.createArc(board, parents, attributes);
536     };
537 
538     JXG.registerElement('minorarc', JXG.createMinorArc);
539 
540     /**
541      * @class A major arc is a segment of the circumference of a circle having measure greater than or equal to
542      * 180 degrees (pi radians). It is defined by a center, one point that
543      * defines the radius, and a third point that defines the angle of the arc.
544      * @pseudo
545      * @name MajorArc
546      * @augments Curve
547      * @constructor
548      * @type JXG.Curve
549      * @throws {Error} If the element cannot be constructed with the given parent objects an exception is thrown.
550      * @param {JXG.Point_JXG.Point_JXG.Point} p1,p2,p3 . Major arc is an arc of a circle around p1 having measure greater than or equal to
551      * 180 degrees (pi radians) and starts at p2. The radius is determined by p2, the angle by p3.
552      * @example
553      * // Create an arc out of three free points
554      * var p1 = board.create('point', [2.0, 2.0]);
555      * var p2 = board.create('point', [1.0, 0.5]);
556      * var p3 = board.create('point', [3.5, 1.0]);
557      *
558      * var a = board.create('minorarc', [p1, p2, p3]);
559      * </pre><div class="jxgbox"id="17a10d38-5629-40a4-b150-f41806edee9f" style="width: 300px; height: 300px;"></div>
560      * <script type="text/javascript">
561      * (function () {
562      *   var board = JXG.JSXGraph.initBoard('17a10d38-5629-40a4-b150-f41806edee9f', {boundingbox: [-1, 7, 7, -1], axis: true, showcopyright: false, shownavigation: false}),
563      *       p1 = board.create('point', [2.0, 2.0]),
564      *       p2 = board.create('point', [1.0, 0.5]),
565      *       p3 = board.create('point', [3.5, 1.0]),
566      *
567      *       a = board.create('majorarc', [p1, p2, p3]);
568      * })();
569      * </script><pre>
570      */
571     JXG.createMajorArc = function (board, parents, attributes) {
572         attributes.selection = 'major';
573         return JXG.createArc(board, parents, attributes);
574     };
575 
576     JXG.registerElement('majorarc', JXG.createMajorArc);
577 
578     return {
579         createArc: JXG.createArc,
580         createSemicircle: JXG.createSemicircle,
581         createCircumcircleArc: JXG.createCircumcircleArc,
582         createMinorArc: JXG.createMinorArc,
583         createMajorArc: JXG.createMajorArc
584     };
585 });
586