01 
02 /*
03  *  JScripter Standard 1.0 - To Script In Java
04  *  Copyright (C) 2008-2011  J.J.Liu<jianjunliu@126.com> <http://www.jscripter.org>
05  *  
06  *  This program is free software: you can redistribute it and/or modify
07  *  it under the terms of the GNU Affero General Public License as published by
08  *  the Free Software Foundation, either version 3 of the License, or
09  *  (at your option) any later version.
10  *  
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU Affero General Public License for more details.
15  *  
16  *  You should have received a copy of the GNU Affero General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 package jsx.motion;
21 
22 import js.ArrayLike;
23 import jsx.core.ArrayLikes;
24 import jsx.core.Maths;
25 
26 /**
27  * <p>An abstract base class to define motions by approximating sample data with 
28  * various interpolation methodologies.</p>
29  * 
30  * @author <a href="mailto:jianjunliu@126.com">J.J.Liu (Jianjun Liu)</a> at <a href="http://www.jscripter.org" target="_blank">http://www.jscripter.org</a>
31  */
32 public abstract class Interpolator extends Motion
33 {
34     /**
35      * <p>An array of sample data held by this object.</p>
36      * @since 1.0
37      */
38     protected final ArrayLike<Number> values;
39 
40     /**
41      * <p>The typical constructor to construct a motion of this type.</p>
42      * @param values An array of sample data to be held by this object.
43      * @since 1.0
44      */
45     protected Interpolator(ArrayLike<Number> values) {
46         this.values = values;
47         normalize(this.values);
48     }
49 
50     /**
51      * <p>Normalize an array of sample data to be held by an approximation motion.</p>
52      * <p>A series of sample data is said to be normalized if and only if they are all 
53      * between -1 and 1. This method simply divides each of the sample data by their 
54      * absolute maximum value.</p>
55      * @param values An array of sample data to be normalized and held by an approximation 
56      * motion.
57      * @since 1.0
58      */
59     protected static final void normalize(ArrayLike<Number> values) {
60         double max = max(values);
61         if (max > 0) {
62             for (int i = 0, len = ArrayLikes.length(values); i < len; i++) {
63                 values.set(i, values.get(i).doubleValue() / max);
64             }
65         }
66     }
67 
68     private static final double max(ArrayLike<Number> values) {
69         double max = 0;
70         for (int i = 0, len = ArrayLikes.length(values); i < len; i++) {
71             double abs = Maths.abs(values.get(i));
72             max = Maths.max(max, abs).doubleValue();
73         }
74         return max;
75     }
76 }