Stuttering in even the simplest of projects - performance

I made a small "game" to test some stuttering I had noticed in my actual game, and I can't for the life of me figure out why this is happening. I made the simplest possible project I could to test this out, but I still get pretty heavy stuttering. The FPS is still 60, but every few seconds, sometimes more, the game will stutter.
I have tried it on both mobile and a high-end pc, and oddly enough, it's more noticeable on the PC, though it still occurs on mobile.
I can't upload a video of it, since it's gone in the recording, so feel free to compile the project yourself if you want to test it. Here's the code:
public class LagTest extends ApplicationAdapter {
SpriteBatch batch;
Texture dot;
float x;
float y;
float speed;
float dotWidth;
int screenWidth;
#Override
public void create () {
batch = new SpriteBatch();
dot = new Texture("dot.png");
x = 100;
y = Gdx.graphics.getHeight()/2 - dot.getHeight()/2;
speed = 500;
dotWidth = dot.getWidth();
screenWidth = Gdx.graphics.getWidth();
}
#Override
public void render () {
Gdx.gl.glClearColor(0.2f, 0.4f, 0.8f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(dot, x, y);
batch.end();
if (x < 0) {
speed = 500;
}
if (x > screenWidth - dotWidth) {
speed = -500;
}
x += speed * Gdx.graphics.getDeltaTime();
}
}
If anyone have some clue to what could be causing this, I'm all ears.
Edit:
So here's something fun. This only seems to occur in windowed mode, not in fullscreen. This might also be why it works better on mobile. Perhaps this is a bug then?

After trying some different methods (averaging delta / averaging raw delta / using raw delta / lowering frame rate to 30 / using a set delta each frame) getting the same stuttering on each one and then googling some on stuttering in windowed mode:
I would like to propose that the stuttering is not caused by LibGDX in itself, but rather is a general problem that occurs in windowed mode and which can have a number of different hardware-near causes. See here for one example and explanation: https://gamedev.stackexchange.com/questions/47356/why-would-a-borderless-full-screen-window-stutter-occasionally

Related

P5js [Violation] 'requestAnimationFrame' handler took 75ms

I am getting this 'requestAnimationFrame' error with this code. I guess there's something with the for loop that causes the problem but I can't figure an alternative way of getting the same visual result. Any idea?
let zoff = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
}
function draw() {
background(0);
translate(width / 2, height / 2);
scale(40);
noStroke();
fill(255);
for (let a = 0; a < 7; a += 0.0012) {
let x = cos(zoff) * 20 * sin(a);
let y = cos(zoff+x/2) * 10 * cos(a);
let e = cos(x) / sin(y) + zoff;
circle(sin(e) * y, cos(e) * y, 0.091);
}
zoff += map(mouseX, 0, width, -0.03, +0.03);
}
This isn't an error, just a warning. It just means your frame is taking a relatively long time to draw. Since each frame you are looping 7 / 0.0012 = 5833 loops * 8 trig functions = 46664 trig calls per frame. If you are doing something like drawing frames to be exported and rendered as a video, that would be safe to ignore, but if this is for something real time, you'll have to figure out some optimizations.
Well it doesn't give me the same, I just copied it into https://editor.p5js.org/ and works perfectly, maybe it's something with your html file. It also seems to have nice performance, so if copying it into a new sketch doesn't work try commenting different parts of the code or maybe using a different browser. It might just be a p5.js bug.

Drawing image(PGraphics) gives unwanted double image mirrored about x-axis. Processing 3

The code is supposed to fade and copy the window's image to a buffer f, then draw f back onto the window but translated, rotated, and scaled. I am trying to create an effect like a feedback loop when you point a camera plugged into a TV at the TV.
I have tried everything I can think of, logged every variable I could think of, and still it just seems like image(f,0,0) is doing something wrong or unexpected.
What am I missing?
Pic of double image mirror about x-axis:
PGraphics f;
int rect_size;
int midX;
int midY;
void setup(){
size(1000, 1000, P2D);
f = createGraphics(width, height, P2D);
midX = width/2;
midY = height/2;
rect_size = 300;
imageMode(CENTER);
rectMode(CENTER);
smooth();
background(0,0,0);
fill(0,0);
stroke(255,255);
}
void draw(){
fade_and_copy_pixels(f); //fades window pixels and then copies pixels to f
background(0,0,0);//without this the corners dont get repainted.
//transform display window (instead of f)
pushMatrix();
float scaling = 0.90; // x>1 makes image bigger
float rot = 5; //angle in degrees
translate(midX,midY); //makes it so rotations are always around the center
rotate(radians(rot));
scale(scaling);
imageMode(CENTER);
image(f,0,0); //weird double image must have something not working around here
popMatrix();//returns window matrix to normal
int x = mouseX;
int y = mouseY;
rectMode(CENTER);
rect(x,y,rect_size,rect_size);
}
//fades window pixels and then copies pixels to f
void fade_and_copy_pixels(PGraphics f){
loadPixels(); //load windows pixels. dont need because I am only reading pixels?
f.loadPixels(); //loads feedback loops pixels
// Loop through every pixel in window
//it is faster to grab data from pixels[] array, so dont use get and set, use this
for (int i = 0; i < pixels.length; i++) {
//////////////FADE PIXELS in window and COPY to f:///////////////
color p = pixels[i];
//get color values, mask then shift
int r = (p & 0x00FF0000) >> 16;
int g = (p & 0x0000FF00) >> 8;
int b = p & 0x000000FF; //no need for shifting
// reduce value for each color proportional
// between fade_amount between 0-1 for 0 being totallty transparent, and 1 totally none
// min is 0.0039 (when using floor function and 255 as molorModes for colors)
float fade_percent= 0.005; //0.05 = 5%
int r_new = floor(float(r) - (float(r) * fade_percent));
int g_new = floor(float(g) - (float(g) * fade_percent));
int b_new = floor(float(b) - (float(b) * fade_percent));
//maybe later rewrite in a way to save what the difference is and round it differently, like maybe faster at first and slow later,
//round doesn't work because it never first subtracts one to get the ball rolling
//floor has a minimum of always subtracting 1 from each value each time. cant just subtract 1 ever n loops
//keep a list of all the pixel as floats? too much memory?
//ill stick with floor for now
// the lowest percent that will make a difference with floor is 0.0039?... because thats slightly more than 1/255
//shift back and or together
p = 0xFF000000 | (r_new << 16) | (g_new << 8) | b_new; // or-ing all the new hex together back into AARRGGBB
f.pixels[i] = p;
////////pixels now copied
}
f.updatePixels();
}
This is a weird one. But let's start with a simpler MCVE that isolates the problem:
PGraphics f;
void setup() {
size(500, 500, P2D);
f = createGraphics(width, height, P2D);
}
void draw() {
background(0);
rect(mouseX, mouseY, 100, 100);
copyPixels(f);
image(f, 0, 0);
}
void copyPixels(PGraphics f) {
loadPixels();
f.loadPixels();
for (int i = 0; i < pixels.length; i++) {
color p = pixels[i];
f.pixels[i] = p;
}
f.updatePixels();
}
This code exhibits the same problem as your code, without any of the extra logic. I would expect this code to show a rectangle wherever the mouse is, but instead it shows a rectangle at a position reflected over the X axis. If the mouse is on the top of the window, the rectangle is at the bottom of the window, and vice-versa.
I think this is caused by the P2D renderer being OpenGL, which has an inversed Y axis (0 is at the bottom instead of the top). So it seems like when you copy the pixels over, it's going from screen space to OpenGL space... or something. That definitely seems buggy though.
For now, there are two things that seem to fix the problem. First, you could just use the default renderer instead of P2D. That seems to fix the problem.
Or you could get rid of the for loop inside the copyPixels() function and just do f.pixels = pixels; for now. That also seems to fix the problem, but again it feels pretty buggy.
If somebody else (paging George) doesn't come along with a better explanation by tomorrow, I'd file a bug on Processing's GitHub. (I can do that for you if you want.)
Edit: I've filed an issue here, so hopefully we'll hear back from a developer in the next few days.
Edit Two: Looks like a fix has been implemented and should be available in the next release of Processing. If you need it now, you can always build Processing from source.
An easier one, and works like a charm:
add f.beginDraw(); before and f.endDraw(); after using f:
loadPixels(); //load windows pixels. dont need because I am only reading pixels?
f.loadPixels(); //loads feedback loops pixels
// Loop through every pixel in window
//it is faster to grab data from pixels[] array, so dont use get and set, use this
f.beginDraw();
and
f.updatePixels();
f.endDraw();
Processing must know when it's drawing in a buffer and when not.
In this image you can see that works

Unity3D - How to control Light.Intensity without animation

I have the following animation:
See on video: Animation Light
Note: Below image of animation control
How can I get the same result using a script? My intention is that the script has no "if".
Don't like this:
public float minIntensity;
public float maxIntensity;
public float intensityAmount;
private Light light;
void Awake(){
light = GetComponent<Light>();
}
void Update(){
if (light.intensity > maxIntensity) {
light.intensity -= intensityAmount * Time.deltaTime;
}
else if (light.intensity < minIntensity) {
light.intensity += intensityAmount * Time.deltaTime;
}
}
I wonder if there is any possibility to do this using some native function ... like: (Math.Clamp, Math.Lerp, Quaternion.Slerp) without any condition as "if" in the code.
Thank you in advance.
Well like you mentioned, you can just use a clamp:
light.intensity = Mathf.Clamp(value, minIntensity, maxIntensity)
However, despite the lack of detail on what type of animation you want, I am assuming you want to "ping pong" between the min and the max. If that is the case, we can use our friendly neighborhood sine wave for that.
public float Frequency = 10f;
public float Magnitude = 2f;
void Update() {
light.Intensity = Magnitude + Mathf.Sin(Time.timeSinceLevelLoad * Frequency) * Magnitude;
}
The sine wave will go from -1 to 1, the magnitude value will make it go from (-magnitude to +magnitude) Since we don't want a negative light intensity, we add magnitude to the start, so the end result is (0 to 2 * magnitude) You can change this to work however you desire, but the point should be clear.
The Frequency variable will change how fast we animate back and forth.

Animate rotation in Unity3d

I'm working on a 2D game in Unity3D (using Orthello 2D).
Since I switched from Cocos2d and CoronaSDK, I'm wondering if there's a way of implementing the following behaviour for a sprite (or any Unity3D object) as it worked in Corona:
object = ...
transition.to ( object, { time = 1000, rotation = object.rotation + 100, onComplete = function ()
// do something
end })
So a sprite rotates by 100 degrees over 1 second.
In my script attached to a sprite I can have a rotation in my Update () function, but it's a bit different approach...
You can do it easily in an Update function.
float timer = 0f;
void Update()
{
if(timer <= 1)
{
// Time.deltaTime*100 will make sure we are moving at a constant speed of 100 per second
transform.Rotate(0f,0f,Time.deltaTime*100);
// Increment the timer so we know when to stop
timer += Time.deltaTime;
}
}
If you need to do another 100 degrees rotation you will just have to reset the timer.
You can see different version of the Rotate function here and more information about the lifesaver Time.deltaTime value here
There are several differnt ways of doing that. For example using a coroutine:
IEnumerator TweenRotation(Transform trans, Quaternion destRot, float speed, float threshold )
{
float angleDist = Quaternion.Angle(trans.rotation, destRot);
while (angleDist > threshold)
{
trans.rotation = Quaternion.RotateTowards(trans.rotation, destRot, Time.deltaTime * speed);
yield return null;
float angleDist = Quaternion.Angle(trans.rotation, destRot);
}
}

howto generate a smooth movement in xna for wp7?

i want to create a game and addes a image to my game, now i want it to move down smoothly. i have a code like this:
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
pos.Y = pos.Y + 1;
base.Update(gameTime);
}
the movement works but it dont looks smooth, it looks like it jiggle. pos is a vector2 for the position in the image.
how to make it more smooth?
If you want movement to be smooth without adding a physics library you just have to factor in gameTime to your position update.
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
pos.Y = pos.Y * 100 * (float)gameTime.ElapsedGameTime.TotalSeconds;
base.Update(gameTime);
}
I don't have access to XNA + visual studio right now, but the changes I made should give you an idea of what to try out. Keep in mind the Update call happens multiple times a second so the elapsed time will be a small number so then you have to multiply it by a larger "movement" value in this case I put 100. Tweak 100 until you see the movement speed you desire.
Beanish is right, you should multiply by GameTime if you want smoothness. Physics is an overkill if you only want your animation to look smooth.
The best way I've found to do animation is by using position interpolation, for this to work you have to know the initial (you already know this) and final position of the image.
If you want to move from A to B in, say, 2 seconds, you can use the following code.
Vector2 a = new Vector2(0, 0);
Vector2 b = new Vector2(0, 100);
float elapsedTime = 0;
float duration = 2.0;
public override void Update(GameTime gameTime)
{
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
elapsedTime += dt;
if (elapsedTime > 1)
elapsedTime = 1;
float param = elapsedTime / duration;
pos = Vector2.Lerp(a, b, param);
}
The best thing about using this approach is that you can now use "easing" to make you animation look really really nice.
To do this just add a Power operation to the interpolator parameter:
pos = Vector2.Lerp(a, b, (float)Math.Pow(param /2.0, 0.5));
This will make you image slow down as it arrives to B. You can play with the exponent value (0.5) to get different results, try 2.0 for example.
Another important thing is that your image will always stop at B. If you use the Euler integration approach (your approach, adding a velocity each frame) you might have some trouble making the image stop at the right position (aka B) and it gets even worse when using 2 or 3 dimesions.
To know more about easing, check Robert Penner's Easing Equations.
First I can tell you what the problem isn't. You don't need a physics engine to have smooth movement. And changing the Update to include the ElapsedGameTime will not make a lick of difference for the smoothness (assuming you haven't changed the default of IsFixedTimestep to false). When there is a fixed timestep, ElapsedGameTime will always have the same value, it will not vary.
I don't how much you are doing in your code, but if it's too much, XNA will start skipping the Draw portion of your code, and this can definitely cause jerkiness. One way to check: in your Update method, test the value of IsRunningSlowly. Whenever it is true, XNA will skip some Draw calls.
If you are not doing anything complicated, then the culprit may be the refresh rate of your monitor. If it is set to anything other than 60Hz, you will have jerkiness. You could fix this by changing your monitor's refresh rate. Alternatively you can change the value of TargetElapsedTime to match your monitor's rate.
You should consider adding to your game a library for handling physics, as for example FarseerPhysics. By calculating the position in a per time base with physics rules applied your movements will be smooth and natural.

Resources