Hi !
Featured games (91)
games approved by the League of Dukes
Games in Showcase (757)
Games in Android Showcase (229)
games submitted by our members
Games in WIP (844)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2 3 ... 9
1  Discussions / General Discussions / Re: Goso - new JVM language on: 2010-11-09 21:39:50
There are a couple of serious red flags that I see here, based on a brief look through:

1) Case insensitivity...just, why??!!!??  
2) "Gosu generics support array-style variance of different generic types. In Java, this is a compilation error, even though it is natural to assume it works."  Yipes.  Yeah, it's natural to assume that it works, until you take the example that they're complaining about (and that apparently is allowed in their language) and actually do something with the result:

ArrayList<Object> mylist;
mylist = new ArrayList<String>(); //apparently they don't think this should be a syntax error...
File myFile = new File();
BOOM!!!  We've just added a File to an ArrayList<String>, and congratulations, you've just completely destroyed the type-safety of your language, YAY!  This is why Arrays Are Not To Be Trusted in Java, every time you use one you carry around the risk that someone will assign your nice pure MySpecialObject[] array to an Object[] reference and then try to assign a String to some index in it.

The unwashed masses have little need to know about covariance/contravariance, but when a language designer doesn't understand why the concepts even exist, that makes me question whether they're really qualified to be designing a language...this stuff is literally the entire reason generics are so messy in Java, why we need wildcards and the extends and super tags, and yes, it's super nasty, but that's the price you pay if you want type safety.

I'd even be fine with it if they indicated that they were consciously making this tradeoff, but that's unclear.

3) Reification is great, but a lot less so if native Java types are not reified.  Wrap those suckers up, and hide the "native" ones if you want to do reification!  Halfway solutions are nasty, there's a reason that most other JVM languages wrap up even primitive types so that everything has the same semantics, and this is a similar issue!  If you don't fix these things, then you end up just inheriting most of the crap that made the original language imperfect.

Personally, I see a bunch of small improvements, but nothing that really sells this to me over Groovy, Scala, or Clojure (in rough order of "How far away from Java do I want to go?").
2  Game Development / Game Mechanics / Re: Collision detection efficiency on: 2010-11-09 21:09:14
The VisualVM profiler is quite nice, it's one of the few that I've found that tends to work on most systems without major amounts of pain:
3  Game Development / Newbie & Debugging Questions / Re: Which is better? on: 2010-11-09 06:58:28
Some people prefer brevity:

private Object checkSomething() {
  return (getSomeObject() == null) ? something : somethingElse;

And others get very upset with more than one return statement in a function; they also tend to hate the ternary operator:

private Object checkSomething() {
  Object obj = something;
  if (getSomeObject() != null) {
    obj = somethingElse;
  return obj;
4  Game Development / Newbie & Debugging Questions / Re: how to divide a triangle into smaller triangles on: 2010-11-05 16:33:18
Premature optimization is the (1.0f / fastInverseSqrt()) of all evil.

public static double fastInverseSqrt(double x){
    double xhalf = 0.5 * x;
    long i = Double.doubleToRawLongBits(x);
    i = 0x5FE6EB50C7B537AAL - (i>>1);
    x = Double.longBitsToDouble(i);
    x = x * (1.5 - xhalf*x*x);
    return x;

Fixed that up for you, should run a lot faster now.

At least that's what this awesome article about software rendering in C from the late 90s told me, and if it works in C, it must work even better in Java, since Java's so slow! I herd that the guy that made Doom invented it. Smiley
5  Games Center / Archived Projects / Re: Fizzy Bricks on: 2010-10-29 17:52:02
Not being able to play like tetris, this is true, I'm really not sure how to improve that side of things. Seems to be tiny inaccuracies occuring in the physics model that causes pieces that should slide by each other (and do in a lot of cases) not to. Even added some code to refix position of things as they fall but no luck there either.

You might try very slightly reducing the size of the physics objects, but leaving the graphics the same.  Box2d's solver doesn't handle flush sliding very well, so when you first get a corner-corner contact it's a crapshoot as to which way it will decide the normal should point, but if things are a tiny bit smaller they should fit better.  If you still want to mark them as having touched, consider making a sensor shape that's the size of the full object and checking for that contact event.
6  Java Game APIs & Engines / Engines, Libraries and Tools / Re: Fizzy - A wrapper around JBox2D on: 2010-10-27 16:55:19
Brilliant! - a proper wrapper is something that's been on my JBox2d todo list for a long time, I started one for Processing, but never quite got around to finishing it up.  Box2d is great, but it doesn't make much of an effort to make simple things easy to do, and due to time constraints I was never able to move very far away from a strict function-by-function port of the C++, so JBox2d inherited all that complexity.

Great job, I think this will be extremely useful!

Out of curiosity, what license is this under?  I'm thinking that a lot of this could be very useful within the Processing wrapper.
7  Games Center / WIP games, tools & toy projects / Re: Buildsim on: 2010-10-19 13:28:50
I think you need to set the MIME type differently on the "Play" link, for me it just prompts me to download the .php file (Firefox, OS X).
8  Games Center / Archived Projects / Re: RGB (unfinished, my first Java project) on: 2010-10-18 02:36:50
Agreed about the controls, if I do end up re-doing this and cleaning it up I'll definitely take those comments on board - if you think this is hard, you should have seen version 1, which didn't have rotation at all (apart from the natural physics), or version 2, which required you to swing the mouse in a circle around the player in order to rotate.

I agree - where at first it seems the core game is all about having the mental (and physical) dexterity to poke the right colour button at the right time, in reality, the game is about just going boing! as fast as you can towards the exit by flinging your little legs out, and the colour thing actually just gets in the way of the fun bit. Which is going boing.

Yeah, absolutely.  What the color bit adds is the ability to swing on ropes, but it might be possible to do that in another way.  Reducing controls to left/right/"jump" might be a good thing to try, I'll see how that works.  Especially when moving fast, it's pretty much impossible to time things correctly to hit the right color.

Re: graphics, there's definitely plenty to do there, this is actually slightly scaled back from what it was because the original version required Processing's OpenGL renderer, which is real buggy to use in applets (I think it's probably JOGL at fault, but it crashes a lot in any case).  I think if I actually try to clean this up I'll do it with a proper game engine rather than Processing. Smiley
9  Games Center / Archived Projects / RGB (unfinished, my first Java project) on: 2010-10-17 18:39:21
While recovering from a computer loss this week (now the second MBP I've lost within three months...I know this is probably as obvious as can be, but seriously, guys, don't use your laptops in the rain Undecided ) I unearthed a hard drive with a lot of old stuff on it, and ran across my first Java project that clocked in at more than a couple thousand LoC, a physics game (homemade physics engine) that I never quite got around to finishing: - this is what convinced me to port Box2d to Java instead of writing my own physics from scratch, though I never got around to rewriting the game using Box2d.

Controls are listed on the page, pretty simple, just r/g/b/space + the arrow keys to rotate.  Your goal is to get to the particle spew at the end of each level as fast as possible.  The levels are pretty crappy (you can skip through with Enter, I think there's about 12 total), also the replay function doesn't work right, and there's also some sort of static variable bug when you reload, don't know what that's about...might have to clear cache to reload it if no walls show up.

And the code...ah, the code.  It's truly horrifying.  I'll never be releasing or reusing even a shred of it, it's that bad.  But I was thinking of doing a rewrite at some point, so I'd be curious about any feedback.

The level of difficulty might be off, I don't know - I just ran through the levels and my worst score was -1200, but I think I'm a little too familiar with the controls and tricks.  Could probably use a better learning curve.
10  Game Development / Newbie & Debugging Questions / Re: Floating Point Determinism in Java on: 2010-10-12 15:47:52
strictfp *should* be required. But traditionally java has defaulted to strictfp despite the performance penalty. IIRC On x86 cpus the internal FP accumulator/register is quite a bit bigger than 64 bits (Or is it only for intermediate results in the FPU?). This changes rounding behavior from IEEE quite a bit, but most importantly, if the result is "pushed" back to ram and reloaded, it is now rounded like a 64bit IEEE number. Thus JIT could really change things here.

I understand these points, but what I don't really understand is, can any of this behavior change without recompiling the code?  I would have thought that behavior like what's kept in registers and what goes to RAM is coming in at the assembly level, not lower, right?

As suspected, it sounds like strictfp probably is the answer, based on thijs's link it's actually worked with JBox2d before, which I didn't know anyone had actually tried - the interesting bit here is that if this works, it's actually a lot easier to get cross-platform consistency in Java than in any other language (including C++, where it's a whole lot of work, and AS3, where as far as I can tell it's absolutely impossible w/o fixed point math) thanks to that flag.  I may try that out just to see for sure that it works, the question comes up a lot (though not enough to use strictfp in the library by default).
11  Game Development / Newbie & Debugging Questions / Re: Floating Point Determinism in Java on: 2010-10-11 16:22:52
Nope, uses fixed time steps (always recommended for physics, FWIW).  Also not a hash map in sight, I've been bitten by that one before, but the one hash map we use is manually managed and completely deterministic.

The slop factors should always be deterministic, they don't randomize at all, what those do is allow for overlap tolerances.

Tried Riven's code, seems to do fine on my computer.

Table based methods are very very bad for many simulation techniques which frequently depend on the properties of the function(s) in question.  As an example, sinusoids are assumed to be continuous everywhere and a table based version is discontinuous at each grid position.  Also note that table based methods have huge relative error to begin with.

Yes, I actually usually don't like using lookups because the speed improvements are not great anyways; as it turns out, trig functions actually aren't that important in the physics engine, they're so infrequently used that it's kind of pointless to optimize over them.

Still, though, shouldn't be causing non-determinism (also, I've tried using Math.* instead, results are the same).

I'm going to try to dig into this deeper, see if I can track down the first place that things go wrong.  Maybe I'm wrong, and I actually do have some indeterminate code somewhere in there that I just don't remember...
12  Game Development / Newbie & Debugging Questions / Floating Point Determinism in Java on: 2010-10-11 09:45:03
So I just discovered yesterday that JBox2d turns out to be wildly non-deterministic, as in, if you run the same physics simulation 10 times in a row (whether or not you're re-starting the entire program or not), you can very easily end up with 10 completely different results, even though locally all the physics seems perfectly normal.  This seems to show up more often with very complex simulations, which is not terribly surprising, chaos and all that meaning that smaller changes are magnified more with more complex systems.

Now, this was surprising to me, to say the least, because every line of code in the engine seems like it should be deterministic, as long as you're on the same machine with the same setup - there's not a Math.random() call in the entire thing (apart from testing code, at least), and I've even tested with everything set so that all Math.* calls are instead handled through lookup tables instead of through the Math library.  Every other operation is straightforward pure Java, almost no library calls, and plain old arithmetic.  Every container iteration (to the extent that we use containers at all, which is very little, most things are arrays) is indexed, so there should be no question about iteration order changing.  Single threaded operation, of course.

I'm aware that you can never rely on floating point consistency across processors or OSes, but this was surprising to me.  Results seem to keep changing even after substantial warmup, once all function compilations have stopped.

Any ideas what might be going on?  Has anyone ever noticed any non-obvious non-deterministic actions in Java? I realize I could probably tag everything with strictfp and ensure floating point consistency, but it just seems like I must be missing something, if no methods are being recompiled and I'm initializing everything in the same way, then running the same simulation, how can I possibly be getting different floating point results?

Is it possible that the compiled code the JVM is producing actually leaves some operation orderings up to the CPU or something like that?  In C++, typically you can at least rely on the same program to produce the same output on the same computer, but maybe the JVM is being more clever in some way?
13  Games Center / Featured Games / Re: Revenge of the Titans 1.52 released, and some interesting DRM news on: 2010-09-28 18:06:16
I'm trying to think of various alternative options to actually selling games for fixed prices, without resorting to begging Smiley Stuff like bargain bundles, or get-free-games-with-RoTT, or pay-what-you-want, that kind of thing. A series of experiments will probably be afoot. When I've finished the pesky game anyway.

Apart from use as a marketing gimmick, I'm not sure that most pricing experiments really tend to be effective in this area of business, most people just aren't that price sensitive.  Pay-what-you-want might get you more attention, so in that sense it could be worth pursuing.

The main problem with pay-what-you-want deals is that there's a massive incentive to pay ridiculously low prices, far lower than what the product is actually worth to you.

If you're brainstorming, there's an experiment I've always wanted to try in order to work around this problem (I've never had a product on sale to try it with, at least not in any market where I can get creative with pricing), basically a group version of Priceline (which also suffers a bit from the underbidding problem since the bids are individual, and people know that they just need to come in slightly above the marginal cost of the service in order to be accepted).  More specifically, people would submit the maximum price that they're willing to pay, commit to buy the product for any price under that amount, and then at the end of the "auction" period (maybe a few days or a week), the seller looks over the set of bids and picks a final price that everyone pays (well, everyone that was willing to pay at least that price); people that underbid don't get the product, though perhaps you could let them purchase it later at the settling price plus some premium, or wait for the next week/month/year's auction.

Obviously to implement something like this you need to be able to lock people into those purchase commitments, probably by pre-charging their credit cards for the full amount and then refunding them later or something like that.  I have no idea whatsoever how the details of that would work, or if it's even allowed by the processors...

The advantage over pay-what-you-want is that the incentive to underpay is removed, because you (the buyer) know that the seller will pick a settling price that makes them the most money overall, and if you come in too low, they'll just cut you out of the deal.  Their single bid won't change the settling price very much, so the motivation is strong to actually bid the maximum that you'd really want to pay for the product, otherwise you might miss out on getting it; once you remove a buyer's potential benefit from underbidding, "name your price" becomes a very powerful way to match supply and demand interests, especially when you're selling products with near zero marginal costs.

I've actually considered forming a startup around this idea and actually throwing some money at it, to create a web service that handled the details of this kind of pricing scheme for merchants (and, crucially, uses the data obtained from previous sales to optimize the free parameters in the scheme for profits, like figuring out the amount of time that each auction should last, and analyzing the chargebacks so that the optimal price selection is robust against them, etc. - there are actually some very interesting game theoretic problems underlying this, but that's a whole other story...), but even apart from implementation there are so many nasty details (mostly legal) that would need to be dealt with, at the moment it's too daunting to do as a side project; perhaps at some point in the future.
14  Games Center / Featured Games / Re: Revenge of the Titans 1.52 released, and some interesting DRM news on: 2010-09-27 18:11:37
Hmm, my server seems to have died. Again Sad It's really not fun doing this sometimes.

Sorry if it was the Hacker News link killing your server, I probably should have warned you before submitting - things almost never hit the front page there, so I didn't even think of it, but clearly this was an exception.

Hope you get a bit of a boost from the attention, let us know.
15  Games Center / Featured Games / Re: Minecraft on: 2010-09-22 21:53:16
That "Cubelands" game is an obvious Minecraft duplication, with just a different name.

The thing with clones - to really hit it big by ripping off an already successful game (esp. one that involves network effects), you have a few options:

1) Seriously outdo the original game execution-wise
2) Seriously outspend them marketing-wise
3) Add a substantial enough twist to the game to make the new one stand on its own

None of these are guarantees, either, unless you are Zynga and have such a massive userbase that any old crap you put out will get millions of hits in the first day.

But it's harder than it seems, and even when competitors do succeed, there's usually plenty of room in the market for clones since the bottleneck with game sales is always getting the customer's attention in the first place - potential customers on the net almost never even know that the competition's out there, let alone compare and contrast.  I'd be shocked if Minecraft would ever see a dent in users due to Cubeland, even if Cubeland ends up just as huge.

If Zynga cloned it, though, look out, they're one of the few companies around that can insta-saturate a market to the point where it would hurt the original game...pretty soon people would be looking at Minecraft and saying, "Hey, isn't that just a copy of that Cubecraft game on Facebook?"
16  Discussions / Miscellaneous Topics / Re: What's not going to make it in JDK7 on: 2010-09-22 16:19:58
I wonder how that could possibly be done... those lambda expressions can be executed at any time, by any (set of) thread for any number of times. How would your possibly handle the 'break' / 'continue' keyword if they are from another thread, and the loop may already have been left.

Actually, I'm pretty sure you're right, non-local control transfer has been taken off the table; you're definitely correct that it's tough to imagine any spec that would make them work intuitively.

FWIW, the main reason I keep getting confused about what's in and out is that Gafter has been very vocal in this whole process, and his preferred version of closures ( is quite a bit more complex than the one they're ultimately going to go with, though they did draw a lot from it.  In his version, there was a construct that allowed for certain transfers of control, but it wasn't completely general.

Hm I never really seem to have a problem with inner classes much. Or threads. And I do seriously complex multithreaded code.

Neither do I, really - don't get me wrong, I use them all the time, and they're not terrible to code, even if they're a little hard on the eyes.

But when a language is optimized so that these constructs are short and sweet, we can really lean on them, and that's what I'd look forward to.  Theoretically we could write (at least some subset of) the kind of code that you'd see in functional languages by using a lot of inline anonymous Callables all over the place, but you almost never see stuff like that because it turns out that stateful towers of for-loops with the logic in the middle take fewer characters to write than the equivalent fold/map/reduce/etc would.  We end up going for the path of least resistance, rightly.

Shift that balance, and I think we'll start to see a lot of really pleasant library APIs coming out for Java, which would be nice - a lot of other languages are doing much better at solving the "elegance" problem, Java could use a breath of life in that regard.
17  Discussions / Miscellaneous Topics / Re: What's not going to make it in JDK7 on: 2010-09-22 05:01:23
I'm sure this was part of the lambda proposal: write access to non-final (doh...) local variables.

You know, I actually forget whether or not that's planned to be allowed...people that want legit closures obviously want that (it's pretty much what "closure" means), but if I recall there was a lot of back and forth as to whether it would be done or not, and it may have been left out.  I remember some discussion about "auto-finalizing" variables whenever possible so that they could be referred to within a lambda, which implies that they came down against it, but I can't find a good reference right now...

Personally, I don't feel like it's that horrible, since if you're messing around with locals inside a closure, you're asking for what you get - typically you would never do this unless you actually wanted to pull some state within the thing, and sometimes that's useful to do.

I mean, is there really any difference between passing a closure that closes over a local variable to a multi-threaded operation and passing a single object reference to a bunch of different threads?  Closures are often used for exactly the same kind of encapsulation that we usually do with classes in OO-land, so...

YMMV, of course.

Whenever I look up closures I get a queasy feeling that treating blocks of code like objects is not a good idea and is going to lead to some very esoteric bugs.

In my experience, it's far less bug prone than you might think, because there really aren't that many gotchas - the one Riven noted can bite you once in a while, but if you're futzing with multithreaded code you're screwed anyways.  The only other trouble area is control flow funny business, like continue, break, return, and exception handling; getting all that right comes down to writing a good spec, and is one of the main reasons that this has been delayed.  They're taking that very seriously, so I'd expect the end result to be pretty clear and easy to digest.

FWIW, I just checked some of my code, and in the project I'm hacking on at the moment (a wrapper around some numerical optimization code that uses reflection to let you just point at an object and say "Optimize the fields in this object relative to this utility function", and presto!, the optimal values appear, like magic - I'm planning to lean on optimization and genetic algorithms very hard for some upcoming work, so it's crucial to have a very simple syntax for both of them, and you can't get much simpler than optimize(myObject, "fitnessFunctionName"), at least without first class functions.  I'd estimate that this would have taken about a quarter of the time if closures were available...), almost every method has at least one anonymous inner class, and some of them go several levels deep.  It's when you start to need functions that return functions that return functions that the syntax restrictions of Java get truly obnoxious.

Perhaps that's peculiar to my style of coding, or to my areas of interest, but I can tell you this, at least: any bugs that I'm running into are not coming from areas where I would be heavily using closures and am currently using anonymous inner classes, they're coming from places where the logic is actually difficult.  My experiences in Scala have been similar, closures are almost always a way to make your code easier to manage, even if some of the other features can get really confusing (implicit type conversions can be a real bitch, sometimes).
18  Discussions / Miscellaneous Topics / Re: What's not going to make it in JDK7 on: 2010-09-21 20:32:08
I use anonymous inner classes very rarely and don't find them that horrible to use so it may just be my programming style.

That's why you're not seeing the point; in my work, I end up with anonymous inner classes all over the place, and it's really an eyesore, it makes reading the code vastly more difficult.

Riven is dead on - multi-threaded code is the primary use case (and it's definitely why the addition is being considered, though it's by no means the only reasonable use, see pretty much any Lisp, Ruby, Haskell, or Scala program for examples of why it's effective).  A lot of this is focused at making multi-threaded collection manipulations easier; say I want to massively parallelize work that I'm doing over a billion element data set, and I want to abstract away that parallelization.  Further, say that there are dozens of different operations that I want to do to this data.  It's much easier to do this type of thing if I can write x => x+1 ) instead of turning the simple operation x => x+1 into its own anonymous class, which will take up several lines of space (or at least add a lot of line noise).

And yes, a lot of this is really just a matter of allowing shorter syntax, and given that you don't program using these ideas much it might seem like a meaningless detail; however, it's proven to be extremely effective (I'd say even crucial) in every other language that has it, and enables much more powerful programs to be specified in much less space, especially since generating higher order functions becomes rather pleasant.  The tricky thing is that Java has some peculiarities that make it much more difficult to get right (different scopes for methods vs. fields, checked exceptions, etc.).
19  Discussions / Miscellaneous Topics / Re: What's not going to make it in JDK7 on: 2010-09-21 06:32:02
JSR TBD: Project Lambda Sad
Lambda expressions (informally, "closures") and defender methods for the Java programming language


I mean, everyone following lambda-dev saw this coming, the thing is just so far away from being ready, but I can't even express how disappointed I am.  Here's hoping that this doesn't get cut from 8 as well...
* ewjordan pops open another tab to go download the latest versions of the Scala plugins for all my IDEs yet again to see if they're finally ready for some real use...
20  Game Development / Game Mechanics / Re: Grappling hook slowly getting larger on: 2010-08-23 18:55:31
I thought about directly correcting it as you suggest, but it didn't seem very elegant.

It might not be elegant, but the only other solution is really to use a different velocity update scheme, and actually calculate the force that the chain is applying on the hook so that you get better accuracy past first order.

Not worth the trouble, IMO - almost every general game physics engine in common use would (under the hood, after you strip away all the irrelevant complexity) do pretty much what you're doing, and correct the position after the fact.
21  Game Development / Game Mechanics / Re: Grappling hook slowly getting larger on: 2010-08-22 19:23:39
It's because of the finite step size - that linear trajectory is only valid for an infinitesimal, and over a finite step, you're diverging very slightly from the "correct" path.  In this case, the error is always in the same direction, growing the distance, so over time it really adds up.

I would suggest directly correcting the distance at each step.
22  Java Game APIs & Engines / Android / Re: Physics on Android on: 2010-08-10 18:13:40
For 2d physics, what we're using at the moment is the Emini engine (, which seems to run pretty well (it was originally developed for J2ME, so it's garbage-free and written using fixed point math).  The only problem is that it costs money to use in a game, so I know that might be a show-stopper for some.  It also doesn't have as many features as most of the Box2d-inspired engines, and as we all probably know (maybe we've blocked it out of our memories by now?), dealing with fixed point math in Java is a major pain in the ass because of the limitations of the language.

And yes, I do notice the irony that as one of the developers on JBox2d I'm going to be paying to use a closed source engine with fewer features, and I'm not terribly pleased about that, but it's the shortest path to market at the moment... Smiley

The JNI bindings to Box2d seem decent, AndEngine ( has all of that set up inside the engine if you're interested.  You can get a sense of performance here:

For us that's not an option because we're using a different framework that for various reasons makes using JNI very tricky.

@Mr EEK: I'm not sure if a few object pools will be enough, sadly.  Locally I've gotten JBox2d down to almost zero garbage (I probably chopped away 99% of the allocations in the entire engine), and it's still not as fast as I'd like, even on my Nexus One.  With 100 stacked objects, I'm ending up with about 20 fps, which is half the frame rate that AndEngine gets with the native binding (though to be fair, the drawing method that I've been using during debugging is extra slow b/c it's not using OpenGL, and I have no idea what sort of test config AndEngine uses, it might not be a full pile-up like I've been testing).

I think one of the problems is that the performance characteristics of Dalvik are very different from Hotspot, which we've gotten used to optimizing for over the years.  In particular, things like getters/setters which are almost free on Hotspot are very costly on Dalvik ( - there's a 3x speed penalty on crappy phones w/o JITs, and a 7x penalty on the ones with JITs!  I suspect this might be a large part of the reason that the native bindings work faster, the compiled code doesn't pay these penalties.

I'm going to see if JBox2d does any better when I pull out the getters/setters, but I'm not overly confident at the moment about finding any magic bullets for this...profiling seems to show no serious unexpected bottlenecks, compute time is pretty well distributed across the engine in proportion to where the actual work needs to happen, which leads me to think that without some major by-hand optimizations specific to Android (possibly including moving some code to use fixed point...blech), I may just be up against a performance wall.
23  Game Development / Shared Code / Re: Utils essentials on: 2010-07-24 21:10:44
Great idea for a thread!  I'll add my most used utility...

I often find myself needing to randomize amongst elements in a set with weighted probabilities; if probabilities are all equal, then Random::nextInt(n) is the way to go, but if you need to draw from a different distribution it's actually bit of work to get something that works right.

This code has only been lightly tested in its current form (I changed it a bit from where I last used it, mainly to accept varargs), and I have no guarantees that it's optimal, but I did run some basic tests and it appears to be working fairly well (seems correct, and runs at several millions of picks per second as long as the probabilities array is less than 50 or so, even using the garbage-producing version), and this is the several-th iteration of this code, so it shouldn't be too buggy; I use some variant of this all over the place both in game code and Monte Carlo simulation, so it might be useful to someone:

    * Spin a spinner with the given relative probabilities, get the index that results.  This
    * method does not alter the passed array.
    * <pre>
    * normalizedSpinner(10, 20, 30) => 1/6 chance of 0, 1/3 chance of 1, 1/2 chance of 2
    * normalizedSpinner(1,1,2) => 1/4 chance of 0, 1/4 chance of 1, 1/2 chance of 2
    * </pre>
    * Note: during intermediate steps, this method will cause two float[] creations, the
    * same length as the probabilities array.  If creation is a concern, use {@link #spinner(float[], float[])}
    * to pass your own pre-allocated intermediate array and handle the probability normalization yourself.
    * Also remember that unless probabilities is passed as an array, Java's varargs will create another
    * intermediate array.
    * @param probabilities a list of relative probabilities
    * @return the index of the event that is randomly chosen based on the provided probabilities

   public static int normalizedSpinner(float ... probabilities) {
      float sum = 0.0f;
      for (int i=0; i<probabilities.length; ++i) {
         sum += probabilities[i];
      if (sum == 0.0f) {
         throw new IllegalArgumentException("At least one probability must be non-zero.");
      } else if (sum < 0.0f) {
         throw new IllegalArgumentException("Probabilities may not be negative.");
      float[] normProbs = new float[probabilities.length];
      for (int i=0; i<probabilities.length; ++i) {
         normProbs[i] = probabilities[i] / sum;
      return spinner(normProbs);
     * Spin a spinner with the given probabilities, get the index that results.
     * Sum of probabilities should add up to 1f.
     * If the sum of probabilities is less than 1, the last index gets all the
     * remaining probability.
     * e.g. spinner(0.5f, 0.3f) => 50% chance of 0, 50% chance of 1
     * If the sum of probabilities is greater than 1, the probabilities are clipped
     * at 1.
     * e.g. spinner(0.5f, 0.3f, 0.5f) => 50% chance of 0, 30% chance of 1, 20% chance of 2 (extra 30% discarded)
     * This method creates an intermediate float array the same length as probabilities; if garbage
     * creation is a concern, use {@link #spinner(float[], float[])} instead, and provide a pre-allocated
     * array of the correct length as the first parameter.
     * @param probabilities a list of probabilities that should add up to 1
     * @return the index of the event that is randomly chosen based on the provided probabilities

    public static int spinner(float ... probabilities) {
        float[] mins = new float[probabilities.length];
        return spinner(mins, probabilities);
     * Used instead of {@link #spinner(float...)} to avoid garbage creation by manually supplying
     * intermediate array.
     * @param auxiliaryArray a pre-allocated array to use for intermediate step that should
     * have at least the same length as the probabilities array (used to avoid intermediate allocations)
     * @param probabilities a list of probabilities that should add up to 1
     * @return the index of the event that is chosen
     * @see Spinner#spinner(float...)

    public static int spinner(float[] auxiliaryArray, float[] probabilities) {
       if (auxiliaryArray.length < probabilities.length){
          throw new IllegalArgumentException("Auxiliary array must have at least the same length as probabilities array.");
       float sum = 0.0f;
        float[] mins = auxiliaryArray;
        for (int i = 0; i < probabilities.length; ++i) {
            if (probabilities[i] < 0.0f) {
                throw new IllegalArgumentException("Probabilities must be positive; received " + probabilities[i] +
                        " as parameter " + i + ".");
            mins[i] = sum;
            sum += probabilities[i];
        double randomNumber = Math.random();
        for (int i = probabilities.length - 1; i > 0; --i) {
            if (randomNumber >= mins[i]) {
                return i;
        return 0;

Sorry, more Javadoc than code, I know...

The idea is that you're spinning a spinner (like on a game board or something) with the passed probabilities, and the result is the array index of the probability that gets picked.  Probably not the clearest name, idunno.

Re: the different functions, normalizedSpinner first normalizes the passed probabilities to sum to 1, and the two-array version lets you pass your own auxiliary array to be used internally so that no garbage is created - when I use these methods, I'm sometimes running hundreds of thousands of trials over distributions with thousands of probabilities, so garbage becomes a huge issue; obviously in those cases I also swap out the Math.random() call with a faster RNG, and sometimes after debugging I strip the parameter checking code, too, though those branches are usually very predictable so it shouldn't make a big difference.
24  Discussions / General Discussions / Re: Geting started in game programming on: 2010-05-30 23:43:01
There is also beanshell which can also be used for scripting within Java apps. AFAIK the beanshell language is essentially Java, but can also allow the programmer to write dynamic code.

Beanshell is also great, and is likely to make it into J2SE eventually as an official javax.scripting language (, it's definitely worth looking into.  It's a bit behind the latest versions of Java (it's creeping towards 1.5 syntax compatibility right now), but it does the trick.  There's also something very nice about scripting Java using something very close to Java instead of an unrelated language.

That said, Javascript has some real advantages, too, mainly that it's very easy to create level specifications in Javascript that avoid the boilerplate code you'd need in Java - as long as you're using it for simple things and not serious coding, it can offer a huge productivity boost.  When you're not using Javascript in the browser, it's actually a pretty nice language for some tasks.
25  Discussions / General Discussions / Re: Geting started in game programming on: 2010-05-29 19:02:38
For research I'd look into the scripting langauges used by Scumm and other point and click engines as a basis. See what works well, what doesn't, which bits you'll need and which bits you don't want. Then I'd find a book on building parsers in Java, but would advise one that is not game oriented (most game oriented ones just skim over how to embed existing languages).

I would recommend against this until you're sure you'll need it.  If you don't know a lot about creating languages, you're going to waste a whole lot of time and end up with a very weak DSL that you have to fight tooth and nail to add any sort of normal scripting feature to.  Plus, that's a potential lifetime-long time-sink that you might get sidetracked thinking about, whereas you don't really need much to specify a game.

If you do really need scripting, Java 6 has a Javascript engine built in (javax.scripting, or look up Mozilla Rhino, which you can drop in as a .jar to a Java 5 project, it's almost exactly the same engine), and it's extremely simple to use once you know a bit of Javascript (plus, it performs well).  I would try to go as far as you can using that before designing your own thing, lately I've been using it for everything under the sun because it integrates so easily.  The functional programming abilities in Javascript make it very well suited to scripting behaviors, and it's also very easy to find people that know Javascript if you end up wanting to get other people to design levels for you, whereas getting people to learn a home-rolled DSL is an uphill battle.
26  Discussions / General Discussions / Re: Java 7 to get Closures! on: 2009-12-04 12:00:21
(I'm assuming that quaternions would be added to your list of basics).

Hehe, we can dream, can't we?  But I'm a realist - I think there's maybe a 5% shot of ever seeing vector or complex primitives, so I doubt quaternions are on the table, let alone octonions or any of the other fun stuff that a math dork might want...

Quote from: Roquen
3) Clifford came along: grokked Quaternions, grokked Exterior algebra.  Figure how to merge them, fills in the missing parts and works for topologies other than Euclidiean.  Then he died young.  He wasn't a rock star, so he was promptly forgotten...oh well.
Hey, don't be so hard on Clifford: we still have Clifford algebras, so he made his mark. Smiley  Then again, only people working on relativistic quantum mechanics ever touch the things, so maybe you're right...

Pretty good summary, by the way.  One thing I'd add is that David Hestenes really tried to push "geometric algebra", which is pretty much what you get when you try to handle all types of N-forms as pieces of the same object.  More accurately, it's a Clifford algebra equipped with a special product that does "nice" things.  I did a bit with these things when I was doing gravity stuff in college, and I remember thinking that they really did make a lot of vector analysis easier because you get a lot of extra information "for free"; might be worth reading up on if you like this stuff.

Sorry to drag this OT...
27  Discussions / General Discussions / Re: Java 7 to get Closures! on: 2009-11-27 16:39:45
WRT: Closures.  I have no feeling one way or the other about adding them to Java.  However there seems to be some confusion..they are not the simply sugar for anonymous functions.  Faking a closure in Java requires a fair amount of boilerplate code.

+1 to that - I think a lot of people seem to think that a closure is just a shorter syntax for an anonymous class, which is not the case.

At the moment it's not clear whether what they're proposing actually qualifies as a "closure" or not, though; plenty of folks are, in fact, pushing for no more than a simpler anonymous class syntax, and I really have to take issue with calling that a closure, since the more powerful things you can do with closures are not possible if that's all we get.

And FWIW, none of this stuff is even remotely new, even in OO languages, so I don't really buy the complaint that Java is trying to "keep up" or anything like that.  It's more that computing is necessarily pushing towards parallelism, and functional style becomes vastly more important there, so Java has to make some concessions in that direction to remain viable.  Without a serious effort to ease parallel programming, Java will fall further behind productivity-wise as we need to scale horizontally, which would be a shame.  Real closures would allow a lot of the important logic and optimization to be put into easy to use libraries instead of the rather low level concurrency support we have today, and I think that will be a major win if it's done right.

The current syntax seems kind of bizarre, though, and some of the discussions on the mailing lists make me worry that this implementation will be pretty seriously crippled, so I don't know how I feel about the addition overall...I'll have to see how the finalized proposal looks, I think.

Cas, as far as automatic conversions, Scala does lets you do that (basically, just write a conversion function and mark it implicit, and then it Just Works), and it is extremely convenient - it makes dealing with unit-ful values a breeze, whereas it's a major pain in the ass in Java because of the explicit conversions all over the place.

It would never make it into Java, though, because people in the Java community are psychotically paranoid about potential abuse of language features, and this one actually has some real potential for confusion and bug-hiding.

Can you define * and / for arbitrary vectors (other than component-wise)?
(Roquen already correctly noted that division requires a unique inverse, which is definitely true)

Sure, you can do anything you want, but it wouldn't necessarily have all the properties you might want from those operators, or a particularly natural meaning.  With vectors in N dimensions, there's the inner (dot) product, which returns a scalar, and an outer product, which returns an N-dimensional matrix in the obvious way.  Neither of these permit division as the inverse, since they don't create vectors.  If you want vector*vector = vector, then in 3D we usually use the dual of the exterior or wedge product of 2 vectors (which boils down to the cross product), but this doesn't generalize to other dimensionalities, since you need N-1 vectors as inputs to make the dual of a wedge come out as a vector (Google "exterior algebra" if you care what any of that means).  In 2D you can use complex multiplication, but that may or may not let you do something useful, depending on context.

Usually people define * and / between vectors and numbers, but not between vectors themselves, when operator overloading.  If you're dealing with complex numbers, you define them all.  Matrices get * defined, but oftentimes not /, because the operation of inverting a matrix can fail sometimes and it's usually best not to hide that by making it look like regular old division.

This is pretty much exactly how mathematicians use the objects and symbols as well, at least for these simple cases, except that sometimes it's implicit that if you multiply two vectors you're taking the inner product, which is a lot more clear in written math because you use a dot for multiplication anyways.

Personally, I'd love to see Java get some built in primitives (preferably stack-allocated and immutable) for vectors, matrices, and complex numbers, with these overloadings baked in; if that happened, I wouldn't care about operator overloading one bit, though I'd also like the big/arb. precision number classes to get the same treatment.  I can't come up with many other compelling or common use cases for operator overloading that make sense, but those ones cause a lot of pain if you work in areas that require them...
28  Discussions / General Discussions / Re: Holy Shit! Mario 64 works on Java on: 2009-11-24 16:42:02
Worked without nasty exceptions on Mac OS X on Safari for me.  Way to go!

Might be a Java version thing or a graphics card issue, then, I'll look into it a little later today.
29  Discussions / General Discussions / Re: Holy Shit! Mario 64 works on Java on: 2009-11-21 02:26:32
Crashing Safari and Firefox on OS X:

11/20/09 9:22:49 PM Safari[3812] *** Assertion failure in -[NSMenu removeItem:], /SourceCache/AppKit/AppKit-949.54/Menus.subproj/NSMenu.m:702 
11/20/09 9:22:49 PM Safari[3812] *** CPerformer: ignoring exception 'Invalid parameter not satisfying: item != nil' raised during perform of selector 'sharedDelegate' on target 'ApplicationDelegate' with args '(null)'
11/20/09 9:22:49 PM Safari[3812] *** Assertion failure in -[NSMenu removeItem:], /SourceCache/AppKit/AppKit-949.54/Menus.subproj/NSMenu.m:702
11/20/09 9:22:53 PM [0x0-0x17b17b][3812] Invalid memory access of location 0x1 eip=0x2b50a12e
11/20/09 9:22:59 PM[164] ([0x0-0x17b17b][3812]) Exited abnormally: Bus error

30  Games Center / WIP games, tools & toy projects / Re: Quick 'n Dirty Verlet Fluids v0.1 on: 2009-08-12 01:06:15
Looking very good, I'm impressed you're getting that many particles going at once without too much slowdown.

Going to release code, too?
Pages: [1] 2 3 ... 9
EgonOlsen (79 views)
2018-06-10 19:43:48

EgonOlsen (59 views)
2018-06-10 19:43:44

EgonOlsen (78 views)
2018-06-10 19:43:20

DesertCoockie (261 views)
2018-05-13 18:23:11

nelsongames (159 views)
2018-04-24 18:15:36

nelsongames (158 views)
2018-04-24 18:14:32

ivj94 (901 views)
2018-03-24 14:47:39

ivj94 (162 views)
2018-03-24 14:46:31

ivj94 (813 views)
2018-03-24 14:43:53

Solater (177 views)
2018-03-17 05:04:08
Java Gaming Resources
by philfrei
2017-12-05 19:38:37

Java Gaming Resources
by philfrei
2017-12-05 19:37:39

Java Gaming Resources
by philfrei
2017-12-05 19:36:10

Java Gaming Resources
by philfrei
2017-12-05 19:33:10

List of Learning Resources
by elect
2017-03-13 14:05:44

List of Learning Resources
by elect
2017-03-13 14:04:45

SF/X Libraries
by philfrei
2017-03-02 08:45:19

SF/X Libraries
by philfrei
2017-03-02 08:44:05 is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!