Wednesday, June 14, 2017

TilesFX 1.4.4

Aloha,

Just on time before my next visit to Singapore I was able to release a new version of TilesFX. Last weekend I finally found some time to add some more features to TilesFX which I had on my list for some time.
First of all I've added a skin that simply shows a smoothed area chart called SmoothAreaChartTileSkin. As parameters you just have to add a list of ChartData objects.
The skin looks as follows...



This might sometime be useful for some dashboards if you would like to keep it simple :)

The next one that I've added is a RadarChartTileSkin which has two different Modes (Mode.POLYGON and Mode.SECTOR). Also the RadarChart takes a list of ChartData objects as parameter in Tile. The two different modes will look as follows...



As you can see both variants can be useful. In the example above I've used the RadarChart to visualize the temperature on every hour of the day which gives a nice temperature overview for measurements.
For the RadarChartTile I have implemented a limit of 128 ChartData elements which will be supported. The reason for this is that if you have more than 128 elements in a RadarChart you can't identify any value on the chart any more.

The third new skin I've added is a CountryTileSkin. In principle this tile simply shows the selected country as a SVGPath and a value with a unit.
This might come in handy if you would like to compare the data of a few countries on a dashboard with a little eye candy.
The CountryTileSkin looks like this...



Nothing really special but like I said...sometimes it could be handy :)
Because if I only show a single country I need SVG paths with a higher resolution which is the reason why I've added the hires.properties file that contains the SVG paths for nearly all countries that you can also find in Java Locale.
The problem with this high resolution SVG paths is that they are big...the properties file alone is 1.3 MB which is the reason why the library is now 1.3 MB big.
For the WorldTileSkin I've only used lo resolution SVG paths where the file is only 125kb big but they don't look nice when used as a single country.

Well that's it for today, as always you can find the source code and binaries here:

Source Code: github

Binaries      : bintray

If you would like to know how to use the different skins in TilesFX you might want to check out the code from github and take a look at the Demo.java Class that is part of the TilesFX library. If you run this Demo.java Class you will get this...



In this demo I make use of nearly all skins that are available in TilesFX at the moment.

If you have any idea for tiles you need for you dashboard, please let me know and don't forget...keep coding... ;)

Friday, June 9, 2017

Java Geek Bike Ride + BBQ

Aloha,

Over the years it became some kind of tradition that the Java User Group M√ľnster organizes a little community event...the Java BBQ at my place in the summer. But this year I thought we need to improve that a bit. Instead of only having the BBQ, I thought we first should do some exercise before we start the BBQ :)
And for that reason we will do a little Java Geek Bike ride this year followed by the traditional Java BBQ.
So here is my plan for our ride...it's around 25km which should be ok because we are not on a hurry..



Because we'll do the bike ride everyone who would like to attend should bring a bike :)
And no worries...it won't be a race but a relaxed ride with enough time to have some "Fahrbier" ;)
If you have no chance to bring a bike with you, I could offer one more bike, otherwise feel free to only join the BBQ part. I could also offer a place to sleep for at least 2 person so just let me know if you need a place to stay, otherwise there are some B&B close by which might work for you.
As always feel free to present things you would like to talk about, e.g. last year one of our attendees presented some interesting stuff which ended in a session at the JavaLand conference... :)

The date for the Java Geek Bike Ride + BBQ will be the 

Saturday the 29th of July

I would suggest that we will start not too late which means maybe around 12pm.
As always I will take care about the drinks and you only have to bring some stuff for the BBQ.
Everyone should bring the kind of meat/sausages etc. she/he would like to eat and it would be awesome if some of you might be able to also bring some salad and bread for the BBQ.

If you are interested but don't know if you are "allowed" to come...just ping me...everybody is welcome as always.

You can find the place here:



Looking forward to spend a great day with you guys...

Keep coding...

Thursday, June 8, 2017

Another new TilesFX skin...

Aloha,

Last time when I was sitting in Singapore skimming the web for some interesting stuff I've stumbled upon a dashboard where a gauge was in front of a line graph. Unfortunately I did not save the image but it was stuck in my head and I thought it might sometime be useful to see not only the current value but also a little history of formerly measured values.
Here is a little screenshot of what I came up with...


As you can see the control shows a bar graph gauge which visualizes the current value. In the center of this gauge you will find a line graph that shows the history of the measured values. In this case I've made use of the strokeWithGradient() feature in combination with gradientStops() to color the line graph.
The time in the lower right corner shows the time of the last update and the text in the lower center shows the time from the first measurement in the line graph to the last measurement.
I think I should also add min- and maxValue to the gauge to get a better idea about the possible range but that's not done yet.
I can imagine that this kind of visualization might be interesting for some use cases but to be honest I'm not sure :)

The new skin can be found in the latest release of TilesFX (1.4.3) which you can find here

Source: github

Binary: bintray

The name of the skin is: SkinType.GAUGE_SPARK_LINE

The screenshot above was create using the following TileBuilder code:

tile = TileBuilder.create().skinType(SkinType.GAUGE_SPARK_LINE)
                  .prefSize(400, 400)
                  .minValue(0)
                  .maxValue(100)
                  .title("Data")
                  .text("Test")
                  .textVisible(false)
                  .averagingPeriod(25)
                  .autoReferenceValue(true)
                  .tooltipText("")
                  .barColor(Tile.YELLOW_ORANGE)
                  .barBackgroundColor(Color.rgb(255, 255, 255, 0.1))
                  .sections(new Section(0, 33, Tile.LIGHT_GREEN),
                            new Section(33, 67, Tile.YELLOW),
                            new Section(67, 100, Tile.LIGHT_RED))
                  .sectionsVisible(true)
                  .highlightSections(true)
                  .animated(true)
                  .strokeWithGradient(true)
                  .gradientStops(new Stop(0.0, Tile.LIGHT_GREEN),
                                 new Stop(0.33, Tile.LIGHT_GREEN),
                                 new Stop(0.33,Tile.YELLOW),
                                 new Stop(0.67, Tile.YELLOW),
                                 new Stop(0.67, Tile.LIGHT_RED),
                                 new Stop(1.0, Tile.LIGHT_RED))
                  .build();

And that's it for today, short but hopefully useful :)

Keep coding...

Monday, May 1, 2017

Formatting numbers in Medusa

Aloha,

Because of the the current project in Singapore I do not have a lot of time to code JavaFX but I try make use of every minute I can find :)
Last week someone found an interesting bug in Medusa that I was not aware of because it never showed up in my tests.
The following screenshot of the bugreport directly shows the problem...


The gauges on the screenshot use the Medusa DashboardSkin and the interesting part is the visualization of the value text.
In Medusa I have a method to adjust the font size so that the given text will fit into a given width. Means if the width of the given text will exceed the given width the font size will be decreased as along as the text will fit in the given width.
This behaviour leads to the different font size used for e.g. -54.90 and 0.0 in the screenshot above.
Well if you just use one gauge or all gauges are always in the same range this is no problem but if you have multiple gauges with values in different ranges (which is often the case) it simply doesn't look good.
So I've started to fix this problem and figured out that it was not that easy as I first thought.

The solution to this problem (at least the one that I've found...there might be better ones) is as follows.
First I figure out the longest text for the value. Therefor I measure the length of the minValue and the maxValue text. When doing this I have to take the number of decimals into account that was set by the user. Doing this gives me the maximum number of characters that can appear in the value text incl. the minus for negative values.
With having this numbers I can make use of the String.format() method to make sure the text will be formatted the right way.
But before I can do that I also have to take into account that instead of rounding the values I would like to simply cut of the decimals after the given number of decimals.
Therefor I have to take into account to use Math.floor() for positive and Math.ceil() for negative values when using String.format().
You might think why not simply use NumberFormat in combination with DecimalFormat because with this you can use patterns like "000.00" and a RoundingMode to format numbers but here you will run into problems with negative numbers and their minus character.
Well like I mentioned my solution might not be the perfect one but it works for Medusa and because of the limited time I have it is good enough for me :)

Here is a method that will format a given value in the range of the given min- and maxValue, the given number of decimals and the given locale...

public static String formatNumber(final Locale LOCALE, final double MIN_VALUE, 
                                  final double MAX_VALUE, final int DECIMALS, 
                                  final double VALUE) {
    StringBuilder sb        = new StringBuilder("%.").append(DECIMALS).append("f");
    String        f         = sb.toString();
    int           minLength = String.format(Locale.US, f, MIN_VALUE).length();
    int           maxLength = String.format(Locale.US, f, MAX_VALUE).length();
    int           length    = Math.max(minLength, maxLength);

    StringBuilder formatStringBuilder = new StringBuilder("%").append(length).append(".").append(DECIMALS).append("f");
    String        formatString        = formatStringBuilder.toString();

    double value = VALUE;
    if (value > 0) {
        value = Math.floor(VALUE * Math.pow(10, DECIMALS)) / Math.pow(10, DECIMALS);
    } else if (value < 0) {
        value = Math.ceil(VALUE * Math.pow(10, DECIMALS)) / Math.pow(10, DECIMALS);
    }

    return String.format(LOCALE, formatString, value);
}

I don't know if this might be useful for someone else but even if not it fixed the bug in Medusa which is all I wanted :)

That's all for today, so...keep coding...


Friday, April 7, 2017

Friday Fun XLVI - Image Matrix

Aloha,

Last weekend when sitting in my hotel room in Singapore I had the idea to test the performance of my DotMatrix control again. So I thought what about pixelating an image and visualize it using the control.
Well to be honest it was just too easy to do...so here is the result...



On the left side you see the original picture and on the right side the related pixelated matrix image.
So I thought why not adding some text and figured out that when I draw the text on the DotMatrix control I usually set all "transparent" pixels to the dotOffColor which doesn't look good in this example.
Therefor I've added another method to the DotMatrix control which only draws the pixels in a character that are "on". The method is called

  • setCharAtWithBackground()

So with this it was easy to add some text on top of the pixelated image without destroying the existing background pixels.
Now that this was done I decided it might be nice to be able to simply shift the DotMatrix in each direction. Long story short I've implemented for additional methods which are

  • shiftLeft()
  • shiftRight()
  • shiftUp()
  • shiftDown()

When calling one of this methods the whole DotMatrix will be shifted by one dot in the choosen direction and redraws itself.
Now I could really test the capability of the DotMatrix by calling for example the shiftLeft method in an AnimationTimer with an update rate of 10ms. So the result was nice as you can see in the following video...



You could also combine the calls like first calling shiftLeft() and after that shiftUp(). It's not perfect because both times the drawMatrix() method will be called but even with this little drawback the DotMatrix is fast enough to create a smooth scrolling effect.

Please keep in mind that you should not go crazy with the no of dots in the DotMatrix control. You will definitely see a decrease in performance if you go to a high number of columns and rows. In the video I use 100x85 dots for the DotMatrix which I think is good enough to use it also for images.

So I don't have any use case for the DotMatrix control at the moment but maybe one of you has and therefor you can find the source code as always over at github.

You will also find 2 other demos in the source code (Main2 and Main3). In Main2 I show you how to create one DotMatrix out of two images and in Main3 I show you how to use two images and draw them alternating on the DotMatrix...so have fun playing around with it :)

Well that's it for today...like always I wish you a nice weekend and never forget...keep coding... ;)

Friday, March 31, 2017

Friday Fun XLV - StockTicker

Aloha,

On my way back from Singapore last time I've created a little Demo that shows the new StockTileSkin of my TilesFX library.
In principle the StockTileSkin is very similar to the SparkLineTileSkin with the difference that it always shows the increase/decrease of the reference value in percentage and as a number.

So in the demo I get the current stock quote of Oracle and IBM once a minute from the NYSE. Because I'm not really into the broker and banking business I have no idea if that makes sense, so forgive me if this idea is totally stupid :)

To understand how this Skin works it needs some more explanation...
First of all you have to define the so called averaging period, this number represents the number of values that you would like to show in the line graph.

In this example I've decided to poll the stock quote every minute and set the averaging period to 120 which means the graph will show the last 2 hours when filled up
If no value is present the min and max values will be taken from Tile.getMinValue() and Tile.getMaxValue(). You also have to make sure that these values are in a usable range because values in Tile will be clamped to the min- and maxValue (I might change this for this specific skin in the future).

For a real good demo I should preload the line chart with the data of the previous day but I did not had the time to extend the demo to this.
Means if you start the demo and the NYSE is closed at that time you won't see any change in the value at all. But if you start it during the trading hours of the NYSE you might see some changes over time (but keep in mind that I only poll once a 1 minute).
If you did not set the reference value, the first value of the data list will be taken to calculate the increase of decrease of the current value. 
If you would like to stick your manual set reference value you might want to set autoReferenceValue property to false.
The reference value will be visualized using a dashed line color with the tresholdColor.

In addition to the StockTileSkin I thought it might be nice to make use of my DotMatrix control and create and add a scrolling ticker too.
To give you an idea what I'm talking about, here is a screenshot of the demo...



The service that I use to get the stock quotes can be found at http://dev.markitondemand.com and is nice for testing some things. The problem is that first of all the data is not available for all companies so it took me some time to figure out two quotes that are updated regularly which made me end up with Oracle and IBM :)

If you would like to add another company stock symbol you can simply add it to the list of symbols in the Main.class. For example let's add Microsoft to the list


public class Main extends Application {
    private static final List<String> SYMBOLS;
    static {
        SYMBOLS = new ArrayList<>();
        SYMBOLS.add("IBM");
        SYMBOLS.add("ORCL");
        SYMBOLS.add("MSFT"); // Simply add it to the list
    }

Be aware that I did not spend much time in layouting mulitple stock items...means I've tried it with 2 and 3 stock symbols...it might look bad with 4 but you will figure out how to make it better ;)

I hope that the StockTileSkin is somehow useful and if you have suggestions on how to improve it...please let me know :)

If you are interested in the source code of this demo you can find it as always on github.

And at last here is a little video that shows the StockTicker Demo in action after it ran for some time.



That's it for today...cheers from Singapore and...keep coding... :)

Friday, March 24, 2017

Friday Fun XLIV - The Matrix

Aloha,

Last weekend I was thinking about a dot matrix display and remembered that this was always something I would like to do in JavaFX. Well after spending nearly 2 weeks in Singapore working on infrastructure documentation etc. I really needed some coding and because of the jetlag I had enough time during the early mornings to create a little control.
To give you an idea what I'm talking about here is a little screenshot of the control...



So as you can see this is not a really fancy control but more something simple and there is a reason for that. I remember that I've once started to create some kind of matrix control for JavaFX but that was in the early JavaFX 2 days and we had no Canvas node which was the reason why I've used nodes for each dot in the old version. But with this amount of dots the whole thing became really slow and because of that I simply never tried again.
But when I thought about it over the weekend the Canvas node came to my mind again and so I've started a new approach with the dot matrix control.
So this version runs completely in one Canvas node and is based on an integer array to make it fast. The main idea behind the dot matrix display was to create some kind of animated stock ticker.
This idea lead to 3 requirements

  1. the matrix size has to be configurable
  2. it must be fast enough for animation
  3. it must be possible to set colors for each dot
  4. it should be possible to show text

So let's take a short look at each requirement.

1. To make the matrix size configurable it is in principle only needed to define the number of dots per column and row you would like to see in the dot matrix. But there is one drawback here, if the control should be resizable you will also need to define the preferred size of the control to be able to resize it with the right aspect ratio.
Therefor you will find a constructor that not only takes the number of columns and rows but also the preferredWidth and preferredHeight. In addition you could also add a color for the dot on and dot off state. 
So to create a DotMatrix with a size of 128x16 dots and a dot on color of red and a dot off color of dark gray you have to write the following code...


DotMatrix m = new DotMatrix(128, 16, 264, 33, Color.RED, Color.DARKGRAY);

or if you prefer using the DotMatrixBuilder it will look like follows...


DotMatrix m = DotMatrixBuilder.create()
                              .prefSize(264, 33)
                              .colsAndRows(128, 16)
                              .dotOnColor(Color.RED)
                              .dotOffColor(Color.DARKGRAY)
                              .build();

2. To make the dot matrix fast enough for animation I've tried to avoid as much overhead as possible. With overhead I mean things like 

  • many nodes on the scene graph
  • crazy graphics (e.g. each dot has light reflection etc.)
  • complex drawing method

To avoid as many nodes on the scene graph as possible the best solution is to make use of the Canvas node. This represents only one node on the scenegraph, can contain complex graphics and the redraw is more or less under your control (immediate mode rendering).
And in addition the Canvas node is really fast :)
A picture explains more than 1000 words...so here is a screenshot of a former matrix that I did in Enzo...



I think you now understand what I mean with crazy graphics...I mean it looks nice but for a bigger display this is simply overkill. For this control I used nodes for each dot...or better each LED.
Because when animating the control I have to call the drawing method a lot and therefor this drawing method has to be as short and simple as possible. So let's take a look at the drawing method in the DotMatrix control...


private void drawMatrix() {
    ctx.clearRect(0, 0, width, height);
    for (int y = 0; y < rows; y++) {
        for (int x = 0; x < cols; x++) {
            ctx.setFill(convertToColor(matrix[x][y]));
            ctx.fillOval(x * dotSize + spacer, y * dotSize + spacer, 
                         dotSizeMinusDoubleSpacer, dotSizeMinusDoubleSpacer);
        }
    }
}

That's all, I clear the canvas, then simply iterate over the rows and columns, set the fill for the current dot and draw a circle at the current position defined by x and y.
Keeping things simple makes the drawing fast enough to do some animation.

3. To make it possible to set the color for each dot you need a 2d data structure which defines the position and stores the color. You can think of all possible combinations of Lists, Maps and custom Objects to realize that but if you would like to keep it simple you could simply stick with a simple 2-dimensional integer array. This will contain the x and y coordinates of each dot and you could use a 1 to enable the dot or a 0 to disable the dot.
This works and is simple and fast BUT how to enable custom colors for each dot???
For this it would be great to represent a color as an integer value but if you take a look at the javafx.scene.paint.Color class you will find all sorts of methods but unfortunately no method that returns the color as an integer value. Lucky me I remembered that the java.awt.Color class had such a method and so it was easy to take a look at the source code of OpenJDK (it's so nice to be able to have the source code of Java available).
To convert a color into an integer you simply can make use of some bit-shifting and the code to convert a color into an integer looks as follows...


public int convertToInt(final float R, final float G, final float B, final float A) {
    int red   = Math.round(255 * R);
    int green = Math.round(255 * G);
    int blue  = Math.round(255 * B);
    int alpha = Math.round(255 * A);
    return (alpha << 24) | (red << 16) | (green << 8) | blue;
}

Now with this in place it was easy to store the color value as integer in the 2-dimensional array of the matrix. Oh and of course it would also be nice to have a method to convert an integer back to a Color, so here it is...


public static Color convertToColor(final int COLOR_VALUE) {
    return Color.rgb((COLOR_VALUE & RED_MASK) >> 16, 
                     (COLOR_VALUE & GREEN_MASK) >> 8, 
                     (COLOR_VALUE & BLUE_MASK), 
                     ALPHA_FACTOR * ((COLOR_VALUE & ALPHA_MASK) >>> 24));
}

In JavaFX the opacity is defined by a double compared to an int in the AWT color which is the reason for the ALPHA_FACTOR multiplication here.
So now we can define for each dot in the matrix the location and the color by simply using a 2-dimensional integer array which is good for the performance.
Means most of the work in the drawing method is done by converting an integer back to a Color. But because all of the operations used for the conversion are mainly bit-shifting and object creation this is not a problem.

4. To be able to show text on the DotMatrix I needed to create some mapping of characters to dots. So my idea was to keep the DotMatrix close to a real hardware DotMatrix where you can define the xy position of the dot and a color. Means in the DotMatrix control switching on a dot is done by calling the method


public void setPixel(final int X, final int Y, final int COLOR_VALUE) {
    if (X >= cols || X < 0) return;
    if (Y >= rows || Y < 0) return;
    matrix[X][Y] = COLOR_VALUE;
}

As you can see I don't call the drawMatrix() method automatically which means I leave that up to you. So first one can set all the pixels needed and then you can call the drawMatrix() method. With this approach you can avoid a redraw after set a pixel.
This is a big advantage when doing some kind of dot matrix ticker where text is moving from right to left. In this case you can first set a vertical line of pixels before you really draw them.
But if you would like to automatically redraw after a pixel was set you will also find a method called setPixelWithRedraw() which does exactly this.
Now back to the character mapping, here I've decided to create an 8x8 font for the ASCII characters between 32 - 126. And if you only need numbers I've also created an 8x8 font that only contains the numbers from 0 - 9.
Again the goal was to keep it as simple as possible which was the reason to define each character by an integer array. So for example the digit 0 looks like this...


{
    0b00111000,
    0b01000100,
    0b01000100,
    0b01000100,
    0b01000100,
    0b01000100,
    0b01000100,
    0b00111000
}

As you can see I used the binary literals which is nice to represent a matrix of dots.
Now the only thing I had to do was to read out each bit of each row and do some math related to the dot position.
These calculations can be found in the setCharAt() and setDigitAt() methods in the DotMatrix control. 
A demo of how to use the DotMatrix control for a running text display can be found in the Demo class in the source code.

I will definitely add this control also to TilesFX because it could be handy as a stock ticker on a dashboard.
So that's it for today, I hope this control will be useful for someone except me :)

UPDATE:
I've removed the plain digits and added another MatrixFont which is 8x11 pixels. So now you can choose between 

  • MatrixFont8x8
  • MatrixFont8x11

In addition I've also added the possibility to set the dot shape to either DotShape.ROUND which is default or to DotShape.SQUARE.

Here is a little video which shows the control in action...


Please find the source code as usual at github.

More examples can be found here

Enjoy the upcoming weekend and keep coding...