Search Results

Search found 38 results on 2 pages for 'accumulator'.

Page 1/2 | 1 2  | Next Page >

  • Is a safe accumulator really this complicated?

    - by Martin
    I'm trying to write an accumulator that is well behaved given unconstrained inputs. This seems to not be trivial and requires some pretty strict planning. Is it really this hard? int naive_accumulator(unsigned int max, unsigned int *accumulator, unsigned int amount) { if(*accumulator + amount >= max) return 1; // could overflow *accumulator += max; // could overflow return 0; } int safe_accumulator(unsigned int max, unsigned int *accumulator, unsigned int amount) { // if amount >= max, then certainly *accumulator + amount >= max if(amount >= max) { return 1; } // based on the comparison above, max - amount is defined // but *accumulator + amount might not be if(*accumulator >= max - amount) { return 1; } // based on the comparison above, *accumulator + amount is defined // and *accumulator + amount < max *accumulator += amount; return 0; }

    Read the article

  • What is the 'accumulator in HQ9+?

    - by Koning Baard XIV
    I was just reading a bit about the HQ9+ programming language ( http://esolangs.org/wiki/HQ9 , http://en.wikipedia.org/wiki/HQ9%2B and http://www.cliff.biffle.org/esoterica/hq9plus.html ), and it tells me something about a so called 'accumulator' which can be incremented, but not be accessed. Also, using the + doesn't manipulate the result: code H+H result Hello World Hello World Can anyone explain me how this works, what this does and if it even makes any sense? Thanks

    Read the article

  • accumulator don't compile

    - by Abruzzo Forte e Gentile
    HI All I am using boost accumulators. These 2 lines use to work fine with current version of boost in LInux. accumulator_set< double, stats< tag::covariance<double, tag::covariate1> > > acc_cov; accumulator_set< double, stats< tag::variance > > acc_var; When I moved to a Sun machine where it is installed boost v1.40 I have this building error "/opt/boost/boost/accumulators/framework/depends_on.hpp", line 276: Error:<no tag> cannot be initialized in a constructor. "/opt/boost/boost/fusion/container/list/cons.hpp", line 85: Where: While instantiating "boost::accumulators::detail::accumulator_wrapper<int, int>::accumulator_wrapper(const boost::accumulators::detail::accumulator_wrapper<int, int>&)". "/opt/boost/boost/fusion/container/list/cons.hpp", line 85: Where: Instantiated from non-template code. 1 Error(s) Do you know how can I fix those errors and why I have this issue? Thanks AFG

    Read the article

  • javascript fixed timestep gameloop with requestanimation frame

    - by coffeecup
    hello i just started to read through several articles, including http://gafferongames.com/game-physics/fix-your-timestep/ ...://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step/ ...//dewitters.koonsolo.com/gameloop.html ...://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html my understanding of this is that i need the currentTime and the timeStep size and integrate all states to the next state the time which is left is then passed into the render function to do interpolation i tried to implement glenn fiedlers "the final touch", whats troubling me is that each FrameTime is about 15 (ms) and the update loop runs at about 1500 fps which seems a little bit off? heres my code this.t = 0 this.dt = 0.01 this.currTime = new Date().getTime() this.accumulator = 0.0 this.animate() animate: function(){ var newTime = new Date().getTime() , frameTime = newTime - this.currTime , alpha if ( frameTime > 0.25 ) frameTime = 0.25 this.currTime = newTime this.accumulator += frameTime while (this.accumulator >= this.dt ) { this.prev_state = this.curr_state this.update(this.t,this.dt) this.t += this.dt this.accumulator -= this.dt } alpha = this.accumulator / this.dt this.render( this.t, this.dt, alpha) requestAnimationFrame( this.animate ) } also i would like to know, are there differences between glenn fiedlers implementation and the last solution presented here ? gameloop1 gameloop2 [ sorry couldnt post more than 2 links.. ] edit : i looked into it again and adjusted the values this.currTime = new Date().getTime() this.accumulator = 0 this.p_t = 0 this.p_step = 1000/100 this.animate() animate: function(){ var newTime = new Date().getTime() , frameTime = newTime - this.currTime , alpha if(frameTime > 25) frameTime = 25 this.currTime = newTime this.accumulator += frameTime while(this.accumulator >= this.p_step){ // prevstate = currState this.update() this.p_t+=this.p_step this.accumulator -= this.p_step } alpha = this.accumulator / this.p_step this.render(alpha) requestAnimationFrame( this.animate ) now i can set the physics update rate, render runs at 60 fps and physics update at 100 fps, maybe someone could confirm this because its the first time i'm playing around with game development :-)

    Read the article

  • how to build an accumulator array in matlab

    - by schwiz
    I'm very new to matlab so sorry if this is a dumb question. I have to following matrices: im = imread('image.jpg'); %<370x366 double> [y,x] = find(im); %x & y both <1280x1 double> theta; %<370x366 double> computed from gradient of image I can currently plot points one at a time like this: plot(x(502) + 120*cos(theta(y(502),x(502))),y(502) + 120*sin(theta(y(502),x(502))),'*b'); But what I want to do is some how increment an accumulator array, something like this: acc = zeros(size(im)); acc(y,x) = acc(x + 120*cos(theta(y,x)),y + 120*sin(theta(y,x)),'*b')) + 1; It would be nice if the 120 could actually be another matrix containing different radius values as well.

    Read the article

  • IBasic Accumulator

    - by Tara
    I am trying to do an accumulator in IBasic for a college assignment and I have the general stuff down but I cannot get it to accumulate. The code is below. My question is how do I get it to accumulate and pass to the different module. I'm trying to calculate how many right answers the user gets. Also, i need to calculate the percentage of right answers. so if the user gets 9 out of 10 right theyed answer 90% right. 'October 15, 2009 ' 'Lab 7.5 Programming Challenge 1 - Average Test Scores ' 'This is a dice game ' declare main() declare inputName(name:string) declare getAnswer(num1:int, num2:int) declare getResult(num1:int, num2:int, answer:int) declare avgRight(getRight:int) declare printInfo(name:string, getRight:int, averege:float) openconsole main() do:until inkey$<>"" closeconsole end sub main() def name:string def num1, num2, answer, total, getRight:int def averege:float inputName (name) getRight = 0 For counter = 1 to 10 getRight = getAnswer(num1, num2) getRight = getRight + 1 next counter average = avgRight (getRight) printInfo(Name, getRight, average) end sub inputName (name) Input "Please enter your name: " ,name return sub getAnswer(num1, num2) def answer, getRight:int num1 = rnd (10) + 1 num2 = rnd (10) + 1 Print num1, "+ " ,num2 Input "What is the answer to the equation? " ,answer getRight = getResult(num1, num2, answer) return getRight sub getResult(num1, num2, answer) def getRight:int if answer = num1 + num2 getRight = 1 else getRight = 0 endif return getRight sub avgRight(getRight) def average:float average = getRight / 10 return average sub printInfo(name, getRight, averege) Print "The students name is: " ,name Print "The number right is: " ,getRight Print Using ("&##.#&", "The average right is " ,averege * 100, "%") return

    Read the article

  • Storing multiple discarded datas in a single variable using a string accumulator

    - by dan
    For an assignment for my intro to python course, we are to write a program that generates 100 sets of x,y coordinates. X must be a float between -100.0 and 100.0 inclusive, but not 0. Y is Y = ((1/x) * 3070) but if the absolute value of Y is greater than 100, both numbers must be discarded (BUT STORED) and another set generated. The results must be displayed in a table, and then after the table, the discarded results must be shown. The teacher said we should use a "string accumulator" to store the discarded data. This is what I have so far, and I'm stuck at storing the discarded data. # import random.py import random # import math.py import math # define main def main(): x = random.uniform(-100.0, 100.0) while x == 0: x = random.uniform(-100.0, 100.0) y = ((1/x) * 3070) while math.fabs(y) > 100: xDiscarded = yDiscarded = y = ((1/x) * 3070) As you can see, I run into the problem of when abs(y) 100, I'm not too sure how to store the discarded data and let it accumulate every time abs(y) 100. I'm cool with the data being stored as "351.2, 231.1, 152.2" I just don't know how to turn the variable into a string and store it. We haven't learned arrays yet so I can't do that. Any help would be much appreciated. Thanks!

    Read the article

  • C++: Best text accumulator

    - by MInner
    Text gets accumulates piecemeal before being sent to client. Now we use own class that allocates memory for each piece as char massive. (Anyway, works like char[][] + std::list<char*>). Then we build the whole string, convert it into std::sting and then create boost::asio::streambuf using it. That's slow enough, I assume. Correct me if I'm wrong. I know, in many cases simple FILE type from stdio.h is used. How does it works? Allocates memory at every write into it. So, is it faster and is there any way to read into boost::asio::streambuf from FILE?

    Read the article

  • Haskell: foldl' accumulator parameter

    - by Clinton
    I've been asking a few questions about strictness, but I think I've missed the mark before. Hopefully this is more precise. Lets say we have: n = 1000000 f z = foldl' (\(x1, x2) y -> (x1 + y, y - x2)) z [1..n] Without changing f, what should I set z = ... So that f z does not overflow the stack? (i.e. runs in constant space regardless of the size of n) Its okay if the answer requires GHC extensions. My first thought is to define: g (a1, a2) = (!a1, !a2) and then z = g (0, 0) But I don't think g is valid Haskell.

    Read the article

  • Smooth animation when using fixed time step

    - by sythical
    I'm trying to implement the game loop where the physics is independent from rendering but my animation isn't as smooth as I would like it to be and it seems to periodically jump. Here is my code: // alpha is used for interpolation double alpha = 0, counter_old_time = 0; double accumulator = 0, delta_time = 0, current_time = 0, previous_time = 0; unsigned frame_counter = 0, current_fps = 0; const unsigned physics_rate = 40, max_step_count = 5; const double step_duration = 1.0 / 40.0, accumulator_max = step_duration * 5; // information about the circ;e (position and velocity) int old_pos_x = 100, new_pos_x = 100, render_pos_x = 100, velocity_x = 60; previous_time = al_get_time(); while(true) { current_time = al_get_time(); delta_time = current_time - previous_time; previous_time = current_time; accumulator += delta_time; if(accumulator > accumulator_max) { accumulator = accumulator_max; } while(accumulator >= step_duration) { if(new_pos_x > 1330) velocity_x = -15; else if(new_pos_x < 70) velocity_x = 15; old_pos_x = new_pos_x; new_pos_x += velocity_x; accumulator -= step_duration; } alpha = accumulator / static_cast<double>(step_duration); render_pos_x = old_pos_x + (new_pos_x - old_pos_x) * alpha; al_clear_to_color(al_map_rgb(20, 20, 40)); // clears the screen al_draw_textf(font, al_map_rgb(255, 255, 255), 20, 20, 0, "current_fps: %i", current_fps); // print fps al_draw_filled_circle(render_pos_x, 400, 15, al_map_rgb(255, 255, 255)); // draw circle // I've added this to test how the program will behave when rendering takes // considerably longer than updating the game. al_rest(0.008); al_flip_display(); // swaps the buffers frame_counter++; if(al_get_time() - counter_old_time >= 1) { current_fps = frame_counter; frame_counter = 0; counter_old_time = al_get_time(); } } I have added a pause during the rendering part because I wanted to see how the code would behave when a lot of rendering is involved. Removing it makes the animation smooth but then I'll have to make sure that I don't let the frame rate drop too much and that doesn't seem like a good solution. I've been trying to fix this for a week and have had no luck so I'd be very grateful if someone can read through my code. Thank you! Edit: I added the following code to work out the actual velocity (pixels per second) of the ball each time the ball is rendered and surprisingly it's not constant so I'm guessing that's the issue. I'm not sure why it's not constant. alpha = accumulator / static_cast<double>(step_duration); render_pos_x = old_pos_x + (new_pos_x - old_pos_x) * alpha; cout << (render_pos_x - old_render_pos) / delta_time << endl; old_render_pos = render_pos_x;

    Read the article

  • using Python reduce over a list of pairs

    - by user248237
    I'm trying to pair together a bunch of elements in a list to create a final object, in a way that's analogous to making a sum of objects. I'm trying to use a simple variation on reduce where you consider a list of pairs rather than a flat list to do this. I want to do something along the lines of: nums = [1, 2, 3] reduce(lambda x, y: x + y, nums) except I'd like to add additional information to the sum that is specific to each element in the list of numbers nums. For example for each pair (a,b) in the list, run the sum as (a+b): nums = [(1, 0), (2, 5), (3, 10)] reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) This does not work: >>> reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: 'int' object is unsubscriptable Why does it not work? I know I can encode nums as a flat list - that is not the point - I just want to be able to create a reduce operation that can iterate over a list of pairs, or over two lists of the same length simultaneously and pool information from both lists. thanks.

    Read the article

  • Haskell Add Function Return to List Until Certain Length

    - by kienjakenobi
    I want to write a function which takes a list and constructs a subset of that list of a certain length based on the output of a function. If I were simply interested in the first 50 elements of the sorted list xs, then I would use fst (splitAt 50 (sort xs)). However, the problem is that elements in my list rely on other elements in the same list. If I choose element p, then I MUST also choose elements q and r, even if they are not in the first 50 elements of my list. I am using a function finderFunc which takes an element a from the list xs and returns a list with the element a and all of its required elements. finderFunc works fine. Now, the challenge is to write a function which builds a list whose total length is 50 based on multiple outputs of finderFunc. Here is my attempt at this: finish :: [a] -> [a] -> [a] --This is the base case, which adds nothing to the final list finish [] fs = [] --The function is recursive, so the fs variable is necessary so that finish -- can forward the incomplete list to itself. finish ps fs -- If the final list fs is too small, add elements to it | length fs < 50 && length (fs ++ newrs) <= 50 = fs ++ finish newps newrs -- If the length is met, then add nothing to the list and quit | length fs >= 50 = finish [] fs -- These guard statements are currently lacking, not the main problem | otherwise = finish [] fs where --Sort the candidate list sortedps = sort ps --(finderFunc a) returns a list of type [a] containing a and all the -- elements which are required to go with it. This is the interesting -- bit. rs is also a subset of the candidate list ps. rs = finderFunc (head sortedps) --Remove those elements which are already in the final list, because -- there can be overlap newrs = filter (`notElem` fs) rs --Remove the elements we will add to the list from the new list -- of candidates newps = filter (`notElem` rs) ps I realize that the above if statements will, in some cases, not give me a list of exactly 50 elements. This is not the main problem, right now. The problem is that my function finish does not work at all as I would expect it to. Not only does it produce duplicate elements in the output list, but it sometimes goes far above the total number of elements I want to have in the list. The way this is written, I usually call it with an empty list, such as: finish xs [], so that the list it builds on starts as an empty list.

    Read the article

  • Semi Fixed-timestep ported to javascript

    - by abernier
    In Gaffer's "Fix Your Timestep!" article, the author explains how to free your physics' loop from the paint one. Here is the final code, written in C: double t = 0.0; const double dt = 0.01; double currentTime = hires_time_in_seconds(); double accumulator = 0.0; State previous; State current; while ( !quit ) { double newTime = time(); double frameTime = newTime - currentTime; if ( frameTime > 0.25 ) frameTime = 0.25; // note: max frame time to avoid spiral of death currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt ) { previousState = currentState; integrate( currentState, t, dt ); t += dt; accumulator -= dt; } const double alpha = accumulator / dt; State state = currentState*alpha + previousState * ( 1.0 - alpha ); render( state ); } I'm trying to implement this in JavaScript but I'm quite confused about the second while loop... Here is what I have for now (simplified): ... (function animLoop(){ ... while (accumulator >= dt) { // While? In a requestAnimation loop? Maybe if? ... } ... // render requestAnimationFrame(animLoop); // stand for the 1st while loop [OK] }()) As you can see, I'm not sure about the while loop inside the requestAnimation one... I thought replacing it with a if but I'm not sure it will be equivalent... Maybe some can help me.

    Read the article

  • Why Enumerable.Range is faster than a direct yield loop?

    - by Morgan Cheng
    Below code is checking performance of three different ways to do same solution. public static void Main(string[] args) { // for loop { Stopwatch sw = Stopwatch.StartNew(); int accumulator = 0; for (int i = 1; i <= 100000000; ++i) { accumulator += i; } sw.Stop(); Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, accumulator); } //Enumerable.Range { Stopwatch sw = Stopwatch.StartNew(); var ret = Enumerable.Range(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n); sw.Stop(); Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret); } //self-made IEnumerable<int> { Stopwatch sw = Stopwatch.StartNew(); var ret = GetIntRange(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n); sw.Stop(); Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret); } } private static IEnumerable<int> GetIntRange(int start, int count) { int end = start + count; for (int i = start; i < end; ++i) { yield return i; } } } The result is like this: time = 306; result = 987459712 time = 1301; result = 987459712 time = 2860; result = 987459712 It is not surprising that "for loop" is faster than the other two solutions, because Enumerable.Aggregate takes more method invocations. However, it really surprises that "Enumerable.Range" is faster than the "self-made IEnumerable". I thought that Enumerable.Range will take more overhead than the simple GetIntRange method. What is the possible reason for this?

    Read the article

  • Objective-C scanf spaces issue

    - by Rob
    I am learning objective-C and for the life of me can't figure out why this is happening. When the user inputs when the code is: scanf("%c %lf", &operator, &number); For some reason it messes with this code: doQuit = 0; [deskCalc setAccumulator: 0]; while (doQuit == 0) { NSLog(@"Please input an operation and then a number:"); scanf("%c %lf", &operator, &number); switch (operator) { case '+': [deskCalc add: number]; NSLog (@"%lf", [deskCalc accumulator]); break; case '-': [deskCalc subtract: number]; NSLog (@"%lf", [deskCalc accumulator]); break; case '*': case 'x': [deskCalc multiply: number]; NSLog (@"%lf", [deskCalc accumulator]); break; case '/': if (number == 0) NSLog(@"You can't divide by zero."); else [deskCalc divide: number]; NSLog (@"%lf", [deskCalc accumulator]); break; case 'S': [deskCalc setAccumulator: number]; NSLog (@"%lf", [deskCalc accumulator]); break; case 'E': doQuit = 1; break; default: NSLog(@"You did not enter a valid operator."); break; } } When the user inputs for example "E 10" it will exit the loop but it will also print "You did not enter a valid operator." When I change the code to: scanf(" %c %lf", &operator, &number); It all of a sudden doesn't print this last line. What is it about the space before %c that fixes this?

    Read the article

  • Different results coming out of an init method than those expected. Why does this happen and how can

    - by Mark Reid
    When I run this method the two properties I have are set to (NULL) when I try and access them outside of the if statement. But they are set to 0 and NO if I check them inside the for loop. -(id) init { NSLog(@"Jumping into the init method!"); if (self = [super init]) { NSLog(@"Running the init method extras"); accumulator = 0; NSLog(@"self.accumulator is %g", accumulator); decimal = NO; } NSLog(@"Calc after init is: %@ and %@", self.accumulator, self.decimal); return self; } Any suggestions as to why what comes out is different from what's done in the for loop?

    Read the article

  • Interpolation using a sprite's previous frame and current frame

    - by user22241
    Overview I'm currently using a method which has been pointed out to me is extrapolation rather than interolation. As a result, I'm also now looking into the possibility of using another method which is based on a sprite's position at it's last (rendered) frame and it's current one. Assuming an interpolation value of 0.5 this is, (visually), how I understand it should affect my sprite's position.... This is how I'm obtaining an inerpolation value: public void onDrawFrame(GL10 gl) { // Set/re-set loop back to 0 to start counting again loops=0; while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip) { SceneManager.getInstance().getCurrentScene().updateLogic(); nextGameTick += skipTicks; timeCorrection += (1000d / ticksPerSecond) % 1; nextGameTick += timeCorrection; timeCorrection %= 1; loops++; tics++; } interpolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks; render(interpolation); } I am then applying it like so (in my rendering call): render(float interpolation) { spriteScreenX = (spriteScreenX - spritePreviousX) * interpolation + spritePreviousX; spritePreviousX = spriteScreenX; // update and store this for next time } Results This unfortunately does nothing to smooth the movement of my sprite. It's pretty much the same as without the interpolation code. I can't get my head around how this is supposed to work and I honestly can't find any decent resources which explain this in any detail. My understanding of extrapolation is that when we arrive at the rendering call, we calculate the time between the last update call and the render call, and then adjust the sprite's position to reflect this time (moving the sprite forward) - And yet, this (Interpolation) is moving the sprite back, so how can this produce smooth results? Any advise on this would be very much appreciated. Edit I've implemented the code from OriginalDaemon's answer like so: @Override public void onDrawFrame(GL10 gl) { newTime = System.currentTimeMillis()*0.001; frameTime = newTime - currentTime; if ( frameTime > (dt*25)) frameTime = (dt*25); currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt ) { SceneManager.getInstance().getCurrentScene().updateLogic(); previousState = currentState; t += dt; accumulator -= dt; } interpolation = (float) (accumulator / dt); render(); } Interpolation values are now being produced between 0 and 1 as expected (similar to how they were in my original loop) - however, the results are the same as my original loop (my original loop allowed frames to skip if they took too long to draw which I think this loop is also doing). I appear to have made a mistake in my previous logging, it is logging as I would expect it to (interpolated position does appear to be inbetween the previous and current positions) - however, the sprites are most definitely choppy when the render() skipping happens.

    Read the article

  • Frameskipping in Android gameloop causing choppy sprites (Open GL ES 2.0)

    - by user22241
    I have written a simple 2d platform game for Android and am wondering how one deals with frame-skipping? Are there any alternatives? Let me explain further. So, my game loop allows for the rendering to be skipped if game updates and rendering do not fit into my fixed time-slice (16.667ms). This allows my game to run at identically perceived speeds on different devices. And this works great, things do run at the same speed. However, when the gameloop skips a render call for even one frame, the sprite glitches. And thinking about it, why wouldn't it? You're seeing a sprite move say, an average of 10 pixels every 1.6 seconds, then suddenly, there is a pause of 3.2ms, and the sprite then appears to jump 20 pixels. When this happens 3 or 4 times in close succession, the result is very ugly and not something I want in my game. Therfore, my question is how does one deal with these 'pauses' and 'jumps' - I've read every article on game loops I can find (see below) and my loops are even based off of code from these articles. The articles specifically mention frame skipping but they don't make any reference to how to deal with visual glitches that result from it. I've attempted various game-loops. My loop must have a mechanism in-place to allow rendering to be skipped to keep game-speed constant across multiple devices (or alternative, if one exists) I've tried interpolation but this doesn't eliminate this specific problem (although it looks like it may mitigate the issue slightly as when it eventually draws the sprite it 'moves it back' between the old and current positions so the 'jump' isn't so big. I've also tried a form of extrapolation which does seem to keep things smooth considerably, but I find it to be next to completely useless because it plays havoc with my collision detection (even when drawing with a 'display only' coordinate - see extrapolation-breaks-collision-detection) I've tried a loop that uses Thread.sleep when drawing / updating completes with time left over, no frame skipping in this one, again fairly smooth, but runs differently on different devices so no good. And I've tried spawning my own, third thread for logic updates, but this, was extremely messy to deal with and the performance really wasn't good. (upon reading tons of forums, most people seem to agree a 2 thread loops ( so UI and GL threads) is safer / easier). Now if I remove frame skipping, then all seems to run nice and smooth, with or without inter/extrapolation. However, this isn't an option because the game then runs at different speeds on different devices as it falls behind from not being able to render fast enough. I'm running logic at 60 Ticks per second and rendering as fast as I can. I've read, as far as I can see every article out there, I've tried the loops from My Secret Garden and Fix your timestep. I've also read: Against the grain deWITTERS Game Loop Plus various other articles on Game-loops. A lot of the others are derived from the above articles or just copied word for word. These are all great, but they don't touch on the issues I'm experiencing. I really have tried everything I can think of over the course of a year to eliminate these glitches to no avail, so any and all help would be appreciated. A couple of examples of my game loops (Code follows): From My Secret Room public void onDrawFrame(GL10 gl) { //Rre-set loop back to 0 to start counting again loops=0; while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip) { SceneManager.getInstance().getCurrentScene().updateLogic(); nextGameTick += skipTicks; timeCorrection += (1000d / ticksPerSecond) % 1; nextGameTick += timeCorrection; timeCorrection %= 1; loops++; } extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks; render(extrapolation); } And from Fix your timestep double t = 0.0; double dt2 = 0.01; double currentTime = System.currentTimeMillis()*0.001; double accumulator = 0.0; double newTime; double frameTime; @Override public void onDrawFrame(GL10 gl) { newTime = System.currentTimeMillis()*0.001; frameTime = newTime - currentTime; if ( frameTime > (dt*5)) //Allow 5 'skips' frameTime = (dt*5); currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt ) { SceneManager.getInstance().getCurrentScene().updateLogic(); previousState = currentState; accumulator -= dt; } interpolation = (float) (accumulator / dt); render(interpolation); }

    Read the article

  • Glenn Fiedler's fixed timestep with fake threads

    - by kaoD
    I've implemented Glenn Fiedler's Fix Your Timestep! quite a few times in single-threaded games. Now I'm facing a different situation: I'm trying to do this in JavaScript. I know JS is single-threaded, but I plan on using requestAnimationFrame for the rendering part. This leaves me with two independent fake threads: simulation and rendering (I suppose requestAnimationFrame isn't really threaded, is it? I don't think so, it would BREAK JS.) Timing in these threads is independent too: dt for simulation and render is not the same. If I'm not mistaken, simulation should be up to Fiedler's while loop end. After the while loop, accumulator < dt so I'm left with some unspent time (dt) in the simulation thread. The problem comes in the draw/interpolation phase: const double alpha = accumulator / dt; State state = currentState*alpha + previousState * ( 1.0 - alpha ); render( state ); In my render callback, I have the current timestamp to which I can subtract the last-simulated-in-physics-timestamp to have a dt for the current frame. Should I just forget about this dt and draw using the physics thread's dt? It seems weird, since, well, I want to interpolate for the unspent time between simulation and render too, right? Of course, I want simulation and rendering to be completely independent, but I can't get around the fact that in Glenn's implementation the renderer produces time and the simulation consumes it in discrete dt sized chunks. A similar question was asked in Semi Fixed-timestep ported to javascript but the question doesn't really get to the point, and answers there point to removing physics from the render thread (which is what I'm trying to do) or just keeping physics in the render callback too (which is what I'm trying to avoid.)

    Read the article

  • Can I specify the order of how changes happen in an single App Engine transaction ? Is it equal to t

    - by indiehacker
    If I passed a list of key ids as an argument in a transaction, would the change associated with the first key in the list happen first? And if not, how do I specify the order that I want the changes to happen in? As a concrete example, consider this code below from Google Docs Transactions--would changes to the first item in acc.key() happen first? class Accumulator(db.Model): counter = db.IntegerProperty() Docshttp://code.google.com/appengine/docs/python/datastore/transactions.html: def increment_counter(key, amount): obj = db.get(key) obj.counter += amount obj.put() q = db.GqlQuery("SELECT * FROM Accumulator") acc = q.get() db.run_in_transaction(increment_counter, acc.key(), 5)

    Read the article

  • how to do partial updates in OpenGL?

    - by Will
    It is general wisdom that you redraw the entire viewport on each frame. I would like to use partial updates; what are the various ways can do that, and what are their pros, cons and relative performance? (Using textures, FBOs, the accumulator buffer, any kind of scissors that can affect swapbuffers etc?) A scenario: a scene with a fair few thousand visible trees; although the textures are mipmapped and they are drawn via VBOs roughly front-to-back with so on, its still a lot of polys. Would streaming a single screen-sized texture be better than throwing them at the screen every frame? You'd have to redraw and recapture them only on camera movement or as often as your wind model updates or whatever, which need not be every frame.

    Read the article

  • is Boost Library's weighted median broken?

    - by user624188
    I confess that I am no expert in C++. I am looking for a fast way to compute weighted median, which Boost seemed to have. But it seems I am not able to make it work. #include <iostream> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/median.hpp> #include <boost/accumulators/statistics/weighted_median.hpp> using namespace boost::accumulators; int main() { // Define an accumulator set accumulator_set<double, stats<tag::median > > acc1; accumulator_set<double, stats<tag::median >, float> acc2; // push in some data ... acc1(0.1); acc1(0.2); acc1(0.3); acc1(0.4); acc1(0.5); acc1(0.6); acc2(0.1, weight=0.); acc2(0.2, weight=0.); acc2(0.3, weight=0.); acc2(0.4, weight=1.); acc2(0.5, weight=1.); acc2(0.6, weight=1.); // Display the results ... std::cout << " Median: " << median(acc1) << std::endl; std::cout << "Weighted Median: " << median(acc2) << std::endl; return 0; } produces the following output, which is clearly wrong. Median: 0.3 Weighted Median: 0.3 Am I doing something wrong? Any help will be greatly appreciated. * however, the weighted sum works correctly * @glowcoder: The weighted sum works perfectly fine like this. #include <iostream> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <boost/accumulators/statistics/weighted_sum.hpp> using namespace boost::accumulators; int main() { // Define an accumulator set accumulator_set<double, stats<tag::sum > > acc1; accumulator_set<double, stats<tag::sum >, float> acc2; // accumulator_set<double, stats<tag::median >, float> acc2; // push in some data ... acc1(0.1); acc1(0.2); acc1(0.3); acc1(0.4); acc1(0.5); acc1(0.6); acc2(0.1, weight=0.); acc2(0.2, weight=0.); acc2(0.3, weight=0.); acc2(0.4, weight=1.); acc2(0.5, weight=1.); acc2(0.6, weight=1.); // Display the results ... std::cout << " Median: " << sum(acc1) << std::endl; std::cout << "Weighted Median: " << sum(acc2) << std::endl; return 0; } and the result is Sum: 2.1 Weighted Sum: 1.5

    Read the article

  • Fixed timestep with interpolation in AS3

    - by Jim Sreven
    I'm trying to implement Glenn Fiedler's popular fixed timestep system as documented here: http://gafferongames.com/game-physics/fix-your-timestep/ In Flash. I'm fairly sure that I've got it set up correctly, along with state interpolation. The result is that if my character is supposed to move at 6 pixels per frame, 35 frames per second = 210 pixels a second, it does exactly that, even if the framerate climbs or falls. The problem is it looks awful. The movement is very stuttery and just doesn't look good. I find that the amount of time in between ENTER_FRAME events, which I'm adding on to my accumulator, averages out to 28.5ms (1000/35) just as it should, but individual frame times vary wildly, sometimes an ENTER_FRAME event will come 16ms after the last, sometimes 42ms. This means that at each graphical redraw the character graphic moves by a different amount, because a different amount of time has passed since the last draw. In theory it should look smooth, but it doesn't at all. In contrast, if I just use the ultra simple system of moving the character 6px every frame, it looks completely smooth, even with these large variances in frame times. How can this be possible? I'm using getTimer() to measure these time differences, are they even reliable?

    Read the article

  • Quick, beginner MASM register question - DX:AX

    - by Francisco P.
    Hello, I am currently studying for an exam I'll have on x86 assembly. I didn't have much luck googling for ":", too common of a punctuation mark :/ IDIV - Signed Integer Division Usage: IDIV src Modifies flags: (AF,CF,OF,PF,SF,ZF undefined) Signed binary division of accumulator by source. If source is a byte value, AX is divided by "src" and the quotient is stored in AL and the remainder in AH. If source is a word value, DX:AX is divided by "src", and the quotient is stored in AL and the remainder in DX. Taken from "Intel Opcodes and Mnemonics" What does DX:AX mean? Thanks a lot for your time :)

    Read the article

1 2  | Next Page >