001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2022, by David Gilbert and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------------------------
028 * SamplingXYLineRenderer.java
029 * ---------------------------
030 * (C) Copyright 2008-2022, by David Gilbert.
031 *
032 * Original Author:  David Gilbert;
033 * Contributor(s):   -;
034 *
035 */
036
037package org.jfree.chart.renderer.xy;
038
039import java.awt.Graphics2D;
040import java.awt.Shape;
041import java.awt.geom.GeneralPath;
042import java.awt.geom.Line2D;
043import java.awt.geom.PathIterator;
044import java.awt.geom.Rectangle2D;
045import java.io.IOException;
046import java.io.ObjectInputStream;
047import java.io.ObjectOutputStream;
048import java.io.Serializable;
049
050import org.jfree.chart.axis.ValueAxis;
051import org.jfree.chart.plot.CrosshairState;
052import org.jfree.chart.plot.PlotOrientation;
053import org.jfree.chart.plot.PlotRenderingInfo;
054import org.jfree.chart.plot.XYPlot;
055import org.jfree.chart.api.RectangleEdge;
056import org.jfree.chart.api.PublicCloneable;
057import org.jfree.chart.internal.CloneUtils;
058import org.jfree.chart.internal.SerialUtils;
059import org.jfree.chart.internal.ShapeUtils;
060import org.jfree.data.xy.XYDataset;
061
062/**
063 * A renderer that draws line charts.  The renderer doesn't necessarily plot
064 * every data item - instead, it tries to plot only those data items that
065 * make a difference to the visual output (the other data items are skipped).  
066 * This renderer is designed for use with the {@link XYPlot} class.
067 */
068public class SamplingXYLineRenderer extends AbstractXYItemRenderer
069        implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
070
071    /** The shape that is used to represent a line in the legend. */
072    private transient Shape legendLine;
073
074    /**
075     * Creates a new renderer.
076     */
077    public SamplingXYLineRenderer() {
078        this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
079        setDefaultLegendShape(this.legendLine);
080        setTreatLegendShapeAsLine(true);
081    }
082
083    /**
084     * Returns the number of passes through the data that the renderer requires
085     * in order to draw the chart.  Most charts will require a single pass, but
086     * some require two passes.
087     *
088     * @return The pass count.
089     */
090    @Override
091    public int getPassCount() {
092        return 1;
093    }
094
095    /**
096     * Records the state for the renderer.  This is used to preserve state
097     * information between calls to the drawItem() method for a single chart
098     * drawing.
099     */
100    public static class State extends XYItemRendererState {
101
102        /** The path for the current series. */
103        GeneralPath seriesPath;
104
105        /**
106         * A second path that draws vertical intervals to cover any extreme
107         * values.
108         */
109        GeneralPath intervalPath;
110
111        /**
112         * The minimum change in the x-value needed to trigger an update to
113         * the seriesPath.
114         */
115        double dX = 1.0;
116
117        /** The last x-coordinate visited by the seriesPath. */
118        double lastX;
119
120        /** The initial y-coordinate for the current x-coordinate. */
121        double openY = 0.0;
122
123        /** The highest y-coordinate for the current x-coordinate. */
124        double highY = 0.0;
125
126        /** The lowest y-coordinate for the current x-coordinate. */
127        double lowY = 0.0;
128
129        /** The final y-coordinate for the current x-coordinate. */
130        double closeY = 0.0;
131
132        /**
133         * A flag that indicates if the last (x, y) point was 'good'
134         * (non-null).
135         */
136        boolean lastPointGood;
137
138        /**
139         * Creates a new state instance.
140         *
141         * @param info  the plot rendering info.
142         */
143        public State(PlotRenderingInfo info) {
144            super(info);
145        }
146
147        /**
148         * This method is called by the {@link XYPlot} at the start of each
149         * series pass.  We reset the state for the current series.
150         *
151         * @param dataset  the dataset.
152         * @param series  the series index.
153         * @param firstItem  the first item index for this pass.
154         * @param lastItem  the last item index for this pass.
155         * @param pass  the current pass index.
156         * @param passCount  the number of passes.
157         */
158        @Override
159        public void startSeriesPass(XYDataset dataset, int series,
160                int firstItem, int lastItem, int pass, int passCount) {
161            this.seriesPath.reset();
162            this.intervalPath.reset();
163            this.lastPointGood = false;
164            super.startSeriesPass(dataset, series, firstItem, lastItem, pass,
165                    passCount);
166        }
167
168    }
169
170    /**
171     * Initialises the renderer.
172     * <P>
173     * This method will be called before the first item is rendered, giving the
174     * renderer an opportunity to initialise any state information it wants to
175     * maintain.  The renderer can do nothing if it chooses.
176     *
177     * @param g2  the graphics device.
178     * @param dataArea  the area inside the axes.
179     * @param plot  the plot.
180     * @param data  the data.
181     * @param info  an optional info collection object to return data back to
182     *              the caller.
183     *
184     * @return The renderer state.
185     */
186    @Override
187    public XYItemRendererState initialise(Graphics2D g2,
188            Rectangle2D dataArea, XYPlot plot, XYDataset data,
189            PlotRenderingInfo info) {
190
191        double dpi = 72;
192    //        Integer dpiVal = (Integer) g2.getRenderingHint(HintKey.DPI);
193    //        if (dpiVal != null) {
194    //            dpi = dpiVal.intValue();
195    //        }
196        State state = new State(info);
197        state.seriesPath = new GeneralPath();
198        state.intervalPath = new GeneralPath();
199        state.dX = 72.0 / dpi;
200        return state;
201    }
202
203    /**
204     * Draws the visual representation of a single data item.
205     *
206     * @param g2  the graphics device.
207     * @param state  the renderer state.
208     * @param dataArea  the area within which the data is being drawn.
209     * @param info  collects information about the drawing.
210     * @param plot  the plot (can be used to obtain standard color
211     *              information etc).
212     * @param domainAxis  the domain axis.
213     * @param rangeAxis  the range axis.
214     * @param dataset  the dataset.
215     * @param series  the series index (zero-based).
216     * @param item  the item index (zero-based).
217     * @param crosshairState  crosshair information for the plot
218     *                        ({@code null} permitted).
219     * @param pass  the pass index.
220     */
221    @Override
222    public void drawItem(Graphics2D g2, XYItemRendererState state, 
223            Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
224            ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
225            int series, int item, CrosshairState crosshairState, int pass) {
226
227        // do nothing if item is not visible
228        if (!getItemVisible(series, item)) {
229            return;
230        }
231        RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
232        RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
233
234        // get the data point...
235        double x1 = dataset.getXValue(series, item);
236        double y1 = dataset.getYValue(series, item);
237        double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
238        double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
239
240        State s = (State) state;
241        // update path to reflect latest point
242        if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
243            float x = (float) transX1;
244            float y = (float) transY1;
245            PlotOrientation orientation = plot.getOrientation();
246            if (orientation == PlotOrientation.HORIZONTAL) {
247                x = (float) transY1;
248                y = (float) transX1;
249            }
250            if (s.lastPointGood) {
251                if ((Math.abs(x - s.lastX) > s.dX)) {
252                    if (s.lowY < s.highY) {
253                        s.intervalPath.moveTo((float) s.lastX, (float) s.lowY);
254                        s.intervalPath.lineTo((float) s.lastX, (float) s.highY);
255
256                        s.seriesPath.moveTo((float) s.lastX, (float) s.closeY);
257                    }
258                    s.seriesPath.lineTo(x, y);
259                    s.lastX = x;
260                    s.openY = y;
261                    s.highY = y;
262                    s.lowY = y;
263                    s.closeY = y;
264                }
265                else {
266                    s.highY = Math.max(s.highY, y);
267                    s.lowY = Math.min(s.lowY, y);
268                    s.closeY = y;
269                }
270            }
271            else {
272                s.seriesPath.moveTo(x, y);
273                s.lastX = x;
274                s.openY = y;
275                s.highY = y;
276                s.lowY = y;
277                s.closeY = y;
278            }
279            s.lastPointGood = true;
280        }
281        else {
282            s.lastPointGood = false;
283        }
284        // if this is the last item, draw the path ...
285        if (item == s.getLastItemIndex()) {
286            // draw path
287            PathIterator pi = s.seriesPath.getPathIterator(null);
288            int count = 0;
289            while (!pi.isDone()) {
290                count++;
291                pi.next();
292            }
293            g2.setStroke(getItemStroke(series, item));
294            g2.setPaint(getItemPaint(series, item));
295            g2.draw(s.seriesPath);
296            g2.draw(s.intervalPath);
297        }
298    }
299
300    /**
301     * Returns a clone of the renderer.
302     *
303     * @return A clone.
304     *
305     * @throws CloneNotSupportedException if the clone cannot be created.
306     */
307    @Override
308    public Object clone() throws CloneNotSupportedException {
309        SamplingXYLineRenderer clone = (SamplingXYLineRenderer) super.clone();
310        clone.legendLine = CloneUtils.clone(this.legendLine);
311        return clone;
312    }
313
314    /**
315     * Tests this renderer for equality with an arbitrary object.
316     *
317     * @param obj  the object ({@code null} permitted).
318     *
319     * @return {@code true} or {@code false}.
320     */
321    @Override
322    public boolean equals(Object obj) {
323        if (obj == this) {
324            return true;
325        }
326        if (!(obj instanceof SamplingXYLineRenderer)) {
327            return false;
328        }
329        if (!super.equals(obj)) {
330            return false;
331        }
332        SamplingXYLineRenderer that = (SamplingXYLineRenderer) obj;
333        if (!ShapeUtils.equal(this.legendLine, that.legendLine)) {
334            return false;
335        }
336        return true;
337    }
338
339    /**
340     * Provides serialization support.
341     *
342     * @param stream  the input stream.
343     *
344     * @throws IOException  if there is an I/O error.
345     * @throws ClassNotFoundException  if there is a classpath problem.
346     */
347    private void readObject(ObjectInputStream stream)
348            throws IOException, ClassNotFoundException {
349        stream.defaultReadObject();
350        this.legendLine = SerialUtils.readShape(stream);
351    }
352
353    /**
354     * Provides serialization support.
355     *
356     * @param stream  the output stream.
357     *
358     * @throws IOException  if there is an I/O error.
359     */
360    private void writeObject(ObjectOutputStream stream) throws IOException {
361        stream.defaultWriteObject();
362        SerialUtils.writeShape(this.legendLine, stream);
363    }
364
365}