How to slow down javafx animation - animation

I'm trying to make the stage.show() slow down. I figured out I might need to set KeyFrame, but am stuck at KeyValue, not understanding T endValue or Interpolator interpolator. Is this the right approach? If so could anyone explain to me what type is T.
Thank you!

You can't slow stage.show() down, if stage is a JavaFX Stage, because this is not an animation.

Controlling Animation Speed
An animation's speed is primarily controlled by its rate. Varying either the rate of playback of the animation or the duration of the animation will probably be all you need to do to get the animation speed you want.
animation.setRate(2) // play the animation at double speed.
animation.setRate(0.5) // play the animation at half speed.
On Interpolation
An interpolator is a mathematical function for calculating intermediate values between points. Here is an article on interpolation.
In JavaFX, the interpolators are used to define easing functions for changing values between keyframes of an animation. Likely, for what you are doing, either a straight linear interpolator or an ease in + ease out interpolator will be fine (those are the two most commonly used interpolators). Most of the time, the default interpolator used by JavaFX suffices and you don't have to change it.
The apparent speed of an animation might also be effected by the interpolated easing function applied to the animation's key values or by the magnitude of a keyvalue change (e.g. number of pixels translated, number of times to scale) divided by the keyframe's duration.
Further reference
If you don't understand what this means, then read the JavaFX animation documentation which will define the terms referenced and provide examples on how to use them.
Additional items in your question
What you want to do ("stage.show() slow down") is ambiguous to me in the context of animations, so I couldn't advise an approach for that - as TheJeed correctly states stage.show() is not an animation, so it makes no sense to try to apply animation to a stage.show() call.
T in the context of a KeyValue is a generic type, which seems to answer the question in your question but not the question in your title.

I agree the question was poorly asked. I didn't have the right approach. Just simply changing thread.sleep() will do the work.
But thank you guys anyway!

Related

Efficiently rendering tiled map using SpriteKit

As an exercise, I decided to write a SimCity (original) clone in Swift for OSX. I started the project using SpriteKit, originally having each tile as an instance of SKSpriteNode and swapping the texture of each node when that tile changed. This caused terrible performance, so I switched the drawing over to regular Cocoa windows, implementing drawRect to draw NSImages at the correct tile position. This solution worked well until I needed to implement animated tiles which refresh very quickly.
From here, I went back to the first approach, this time using a texture atlas to reduce the amount of draws needed, however, swapping textures of nodes that need to be animated was still very slow and had a huge detrimental effect on frame rate.
I'm attempting to display a 44x44 tile map where each tile is 16x16 pixels. I know here must be an efficient (or perhaps more correct way) to do this. This leads to my question:
Is there an efficient way to support 1500+ nodes in SpriteKit and which are animated through changing their textures? More importantly, am I taking the wrong approach by using SpriteKit and SKSpriteNode for each tile in the map (even if I only redraw the dirty ones)? Would another approach (perhaps, OpenGL?) be better?
Any help would be greatly appreciated. I'd be happy to provide code samples, but I'm not sure how relevant/helpful they would be for this question.
Edit
Here are some links to relevant drawing code and images to demonstrate the issue:
Screenshot:
When the player clicks on the small map, the center position of the large map changes. An event is fired from the small map the central engine powering the game which is then forwarded to listeners. The code that gets executed on the large map the change all of the textures can be found here:
https://github.com/chrisbenincasa/Swiftopolis/blob/drawing-performance/Swiftopolis/GameScene.swift#L489
That code uses tileImages which is a wrapper around a Texture Atlas that is generated at runtime.
https://github.com/chrisbenincasa/Swiftopolis/blob/drawing-performance/Swiftopolis/TileImages.swift
Please excuse the messiness of the code -- I made an alternate branch for this investigation and haven't cleaned up a lot of residual code that has been hanging around from pervious iterations.
I don't know if this will "answer" your question, but may help.
SpriteKit will likely be able to handle what you need but you need to look at different optimizations for SpriteKit and more so your game logic.
SpriteKit. Creating a .atlas is by far one of the best things you can do and will help keep your draw calls down. Also as I learned the hard way keep a pointer to your SKTextures as long as you need them and only generate the ones you needs. For instance don't create textureWithImageNamed#"myImage" every time you need a texture for myImage instead keep reusing a texture and store it in a dictionary. Also skView.ignoresSiblingOrder = YES; helps a bunch but you have to manage your own zPosition on all the sprites.
Game logic. Updating every tile every loop is going to be very expensive. You will want to look at a better way to do that. keeping smaller arrays or maybe doing logic (model) updates on a background thread.
I currently have a project you can look into if you want called Old Frank. I have a map that is 75 x 75 with 32px by 32px tiles that may be stacked 2 tall. I have both Mac and iOS target so you could in theory blow up the scene size and see how the performance holds up. Not saying there isn't optimization work to be done (it is a work in progress), but I feel it might help get you pointed in the right direction at least.
Hope that helps.

Is it "right" to use rigidbody forces to animate in Unity3D?

I wan't to implement a frictionless spring in unity3D to animate a gameobject as if it where floating by moving up and down. I am doing it with an animation but if I use forces they can combine an create richer sequences.
I could do:
//Update
rigidbody.addforce( springForce );
The force is just the change in the velocity so I could also do
//Update
rigidbody.velocity += Time.deltaTime * springForce / rigidbody.mass;
The question remains, is adding a force each frame efficient? Should I skip some frames or just do the animation to avoid performance issues? Note: I program for mobile.
The difference between Update and FixedUpdate is this:
Update is always called as quickly as possible. The time between calls is tracked in deltaTime. Even if "as quickly as possible" turns out to be really slow, only a single call to Update is made with a high DeltaTime value.
FixedUpdate is never called more often than the physics framerate. If things slow down and the time for several physics frames passes without the necessary calls being made, Unity will try to catch up by calling FixedUpdate multiple times. For example, if the physics framerate is 0.02 and slow code holds up the game for 0.06 seconds, Unity will call FixedUpdate 3 times to try and catch up.
You can probably see the problem at this stage: physics movement tends to be complicated with acceleration, deceleration, collisions etc. If you add forces in Update then the amount of force added and the exact timing with which it is added will vary based on the speed the game is running at. Also, if the game slows down, the physics engine will be doing multiple updates per physics frame to catch up (it works in the same way FixedUpdate does) and your Update method would be unable to compensate for this (actually, it is possible, but only if you basically duplicate the catch-up code Unity already has which is pointless)
To use your spring example, assuming you had all the spring behaviour correct but in Update instead of FixedUpdate, if the game was running fast then Update could be called several times with the object not moving - not because the spring force has failed to move it but because the physics engine has not yet run to actually pay attention to the force and make the object move. If the game was running slow then the object could hit the spring and then the effect of the forces on the object would be calculated multiple times before the spring was calculated again. This could cause the object to move a tiny bit out of contact with the spring and end up bouncing, or to actually interpenetrate the spring and force restitution to occur.
If an object is just moving in a straight line with no physics then its position over time is defined by very simple equations which can be evaluated at any value, so you can use Update.
Unlike the previous answer there is actually a good reason to use deltaTime in a FixedUpdate method - Unity automatically sets it equal to fixedDeltaTime in this case, so your code can adapt if you change the physics framerate.
First you would do physics updates in die FixedUpdate method. So the force wouldn't be applied every frame but every physics tick (default 0.02 seconds I think).
If you should do that heavily depends on your needs. If you want a realistic simulation of a floating object you probably need to apply the force every physics tick. Wether you should use a spring for that is another question. There are some floating scripts in the unify wiki:
http://wiki.unity3d.com/index.php?title=Main_Page
Or you could have a look at this very interesting script:
http://forum.unity3d.com/threads/72974-Buoyancy-script
When adding a force in Unity through the use of AddForce you have the choice of a couple of ForceModes (http://docs.unity3d.com/Documentation/ScriptReference/ForceMode.html). So it might be a little different to your change of velocity depending on the mode you will use.
Another point: When using FixedUpdate you won't need to use Time.deltaTime as the ticks always have the same time-lag.
If you decide to apply the force less often you can change the time between physics ticks to increase performance:
http://docs.unity3d.com/Documentation/ScriptReference/Time-fixedDeltaTime.html
http://docs.unity3d.com/Documentation/ScriptReference/Time-timeScale.html

j2me: what is effect of 'g.clipRect()' on speed?

I'm developing in j2me and using canvas to drawing some images.
Now, my question is : what is difference of below sample codes in speed of drawing?
drawing after clipping area rectangle:
g.clipRect(x, y, myImage.getWidth(), myImage.getHeight());
g.drawImage(myImage, x , y, Graphics.TOP | Graphics.LEFT);
g.setClip(0, 0, screenWidth, screenHeight);
drawing without clip:
g.drawImage(myImage, x, y, Graphics.TOP | Graphics.LEFT);
is the first one is faster? I'm drawing on screen a lot.
Well the direct answer to your question would be Mu I'm afraid - because you appear to approach the issue from the wrong direction.
Thing is, clipping API is not intended for performance considerations / optimizations. You can find full coverage of its purpose in API documentation (available online), it does not state anything related to performance impact:
Clipping
The clip is the set of pixels in the destination of the Graphics object that may be modified by graphics rendering operations.
There is a single clip per Graphics object. The only pixels modified by graphics operations are those that lie within the clip. Pixels outside the clip are not modified by any graphics operations.
Operations are provided for intersecting the current clip with a given rectangle and for setting the current clip outright...
Attempting to use clipping API for imaginary performance considerations will make your code a nightmare to understand for future maintainers. Note this future maintainer may be you yourself, just few weeks / months / years later - I for one had my nose broken on my own code written some time ago without clearly understandable intent - trust me, it hurts the same as messing with poor code written by anyone else.
Don't get me wrong - there is a chance that clipping may have substantial performance impact in some particular case on specific device - why not, everything is possible given the variety of MIDP implementations. Know what? there is even a chance of it having an opposite impact on some other device, why not.
If (if) that happens, if (if) you'll somehow get a clear, solid, tested and proven justification of specific performance impact - then (then), go ahead, implement whatever tricks necessary to reach required performance, no matter how perverse they may be (BTDTGTTS). Until then, though, drop any baseless assumptions that just may come to your mind.
Until then... Just. Drop. It.
Developers love to optimize code and with good reason. It is so satisfying and fun. But knowing when to optimize is far more important. Unfortunately, developers generally have horrible intuition about where the performance problems in an application will actually be... Most performance tuning reminds me of the old joke about the guy who's looking for his keys in the kitchen even though he lost them in the street, because the light's better in the kitchen... (Brian Goetz)
This will almost certainly vary between platforms, and will depend on how much you're actually drawing.
I suggest you measure performance yourself by logging the number of paints per second, or the average duration of a paint method, and painting this on screen.
Drawing without clip should be faster on any platform for the simple reason that you are not calling two clip methods. But I might ask, why are you using clip to begin with?
You usually use clipping when you have an animation sprite or an icon variation in the same file. In this case you can create a file for each frame/icon. It will increase your jar file size and will use more heap space to hold these images on memory, but will be drawn faster.

Efficient method to draw a line with millions of points

I'm writing an audio waveform editor in Cocoa with a wide range of zoom options. At its widest, it shows a waveform for an entire song (~10 million samples in view). At its narrowest, it shows a pixel accurate representation of the sound wave (~1 thousand samples in a view). I want to be able to smoothly transition between these zoom levels. Some commercial editors like Ableton Live seem to do this in a very inexpensive fashion.
My current implementation satisfies my desired zoom range, but is inefficient and choppy. The design is largely inspired by this excellent article on drawing waveforms with quartz:
http://supermegaultragroovy.com/blog/2009/10/06/drawing-waveforms/
I create multiple CGMutablePathRef's for the audio file at various levels of reduction. When I'm zoomed all the way out, I use the path that's been reduced to one point per x-thousand samples. When I'm zoomed in all the way in, I use that path that contains a point for every sample. I scale a path horizontally when I'm in between reduction levels. This gets it functional, but is still pretty expensive and artifacts appear when transitioning between reduction levels.
One thought on how I might make this less expensive is to take out anti-aliasing. The waveform in my editor is anti-aliased while the one in Ableton is not (see comparison below).
I don't see a way to turn off anti-aliasing for CGMutablePathRef's. Is there a non-anti-aliased alternative to CGMutablePathRef in the world of Cocoa? If not, does anyone know of some OpenGL classes or sample code that might set me on course to drawing my huge line more efficiently?
Update 1-21-2014: There's now a great library that does exactly what I was looking for: https://github.com/syedhali/EZAudio
i use CGContextMoveToPoint+CGContextAddLineToPoint+CGContextStrokePath in my app. one point per onscreen point to draw using a pre-calculated backing buffer for the overview. the buffer contains the exact points to draw, and uses an interpolated representation of the signal (based on the zoom/scale). although it could be faster and look better if i rendered to an image buffer, i've never had a complaint. you can calc and render all of this from a secondary thread, if you set it up correctly.
anti-aliasing pertains to the graphics context.
CGFloat (the native input for CGPaths) is overkill for an overview, as an intermediate representation, and for calculating the waveform overview. 16 bits should be adequate. of course, you'll have to convert to CGFloat when passing to CG calls.
you need to profile to find out where your time is spent -- focus on the parts that take the most time. also, make you sure you only draw what you must, when you must and avoid overlays/animations where possible. if you need overlays, it's better to render to an image/buffer and update that as needed. sometimes it helps to break up the display into multiple drawing surfaces when the surface is large.
semi-OT: ableton's using s+h values this can be slightly faster but... i much prefer it as an option. if your implementation uses linear interpolation (which it may, based on its appearance), consider a more intuitive approach. linear interpolation is a bit of a cheat, and really not what the user would expect if you're developing a pro app.
In relation to the particular question of anti-aliasing. In Quartz the anti-aliasing is applied to the context at the moment of drawing. The CGPathRef is agnostic to the drawing context. Thus, the same CGPathRef can be rendered into an antialiased context or to a non-antialiased context. For example, to disable antialiasing during animations:
CGContextRef context = UIGraphicsGetCurrentContext();
GMutablePathRef fill_path = CGPathCreateMutable();
// Fill the path with the wave
...
CGContextAddPath(context, fill_path);
if ([self animating])
CGContextSetAllowsAntialiasing(context, NO);
else
CGContextSetAllowsAntialiasing(context, YES);
// Do the drawing
CGContextDrawPath(context, kCGPathStroke);

How I do I make controls/elements move with inertia?

Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?
You're talking about two different things here.
One is momentum - giving things residual motion when you release them from a drag. This is simply about remembering the velocity of a thing when the user releases it, then applying that velocity to the object every frame and also reducing the velocity every frame by some amount. How you reduce velocity every frame is what you experiment with to get the feel right.
The other thing is ease-in and ease-out animation. This is about smoothly accelerating/decelerating objects when you move them between two positions, instead of just linearly interpolating. You do this by simply feeding your 'time' value through a sigmoid function before you use it to interpolate an object between two positions. One such function is
smoothstep(t) = 3*t*t - 2*t*t*t [0 <= t <= 1]
This gives you both ease-in and ease-out behaviour. However, you'll more commonly see only ease-out used in GUIs. That is, objects start moving snappily, then slow to a halt at their final position. To achieve that you just use the right half of the curve, ie.
smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1
Mike F's got it: you apply a time-position function to calculate the position of an object with respect to time (don't muck around with velocity; it's only useful when you're trying to figure out what algorithm you want to use.)
Robert Penner's easing equations and demo are superb; like the jQuery demo, they demonstrate visually what the easing looks like, but they also give you a position time graph to give you an idea of the equation behind it.
What you are looking for is interpolation. Roughly speaking, there are functions that vary from 0 to 1 and when scaled and translated create nice looking movement. This is quite often used in Flash and there are tons of examples: (NOTE: in Flash interpolation has picked up the name "tweening" and the most popular type of interpolation is known as "easing".)
Have a look at this to get an intuitive feel for the movement types:
SparkTable: Visualize Easing Equations.
When applied to movement, scaling, rotation an other animations these equations can give a sense of momentum, or friction, or bouncing or elasticity. For an example when applied to animation have a look at Robert Penners easing demo. He is the author of the most popular series of animation functions (I believe Adobe's built in ones are based on his). This type of transition works equally as well on alpha's (for fade in).
There is a bit of method to the usage. easeInOut start slow, speeds up and the slows down. easeOut starts fast and slows down (like friction) and easeIn starts slow and speeds up (like momentum). Depending on the feel you want you choose the appropriate one. Then you choose between Sine, Expo, Quad and so on for the strength of the effect. The others are easy to work out by their names (e.g. Bounce bounces, Back goes a little further then comes back like an elastic).
Here is a link to the equations from the popular Tweener library for AS3. You should be able to rewrite these in JavaScript (or any other language) with little to no trouble.
It's playing with the numbers.. What feels good is good.
I've tried to develop magic formulas myself for years. In the end the ugly hack always felt best. Just make sure you somehow time your animations properly and don't rely on some kind of redraw/refresh rate. These tend to change based on the OS.
Im no expert on this either, but I beleive they are done with quadratic formulas, that, when given the correct parameters, start fast or slow and dramatically increase or decrease towards the end until a certain point is reached.

Resources