Building a Solar System in XNA (Part 3)

Posted on July 11, 2008 by Chris at 3:48 pm

Ok, so it’s been a while since I posted the last entry onto the blog. But, no one really pays any attention to this site, so I figure no harm done. This is the final part in my ongoing series of creating a solar system using XNA.

The all important gravitational fomulas

There are a couple of different ways to do gravitational calculations, we will be using Newton’s law of Universal Gravitation to do the calculations required. I’m sure that if there are any science nerds out there reading this, or even people who’ve actually read the linked wikipedia article, they would be screaming about now saying Einstein’s theory of general relativity is much more precise. Unfortunately, I just plain don’t understand the maths right now. I’m sure with some work, and a few models and examples, I would be able to figure out how to implement the field equations into my little universe, but to be honest it’s just a little outside the scope of my understanding at this stage.

In any case, the formula we will be using former formula due to simplicity (F1 = F2 = G * ((m1 * m2) / d^2)). We can always modify the application later if this one is too inacrate.

The Ultimate Goal of an Evil Genius

Today, I had a great time starting the simulation to test out the gravity stuff. It would appear that I have some malevolent being inside of me that enjoys watching as an entire solar system is sucked directly into the sun (bwoohoohoohahaha). The planets have not yet alligned to give me the correct results (pun intended).

It’s no surprise really, considering that each planet moves at a some velocity around the sun, and is also affected by each other plant’s gravitation. What we need to do now is get some realistic initial position and velocity information for each planet, so we can place them in the right spot.. and give them a little boot to get started.

We need to find some kind of place that we can get the locations of planets without too much difficulty. What place would keep this information, so that I don’t have to use a telescope? Perhaps some kind of space agency… NASA appear to have something here.. but I have to learn some more maths (doh!). I belive a quick rundown of Kepler’s Laws is appropriate, followed by some sligtly more difficult reading from the JPL site above.

Or you could just do what I ended up doing and take a look at wikipedia for all your data needs. Clicking on the links from Part 1, I found a nifty Average Orbital Speed entry in the information bar (good ol’ wikipedia, always there with the goods). So, for future reference here are the approximate speeds along with an even more aproximate speed in lightseconds per second. Since I don’t know what the SI units are for lightseconds (and I am too lazy to do a simple search) I’m going to take a WILD stab in the dark and call the units “ls/s”.

Planet Approx. Orbital Velocity
Mercury 47,870 m/s 1.5967e-4 ls/s
Venus 35,080 m/s 1.1701e-4 ls/s
Earth 29,783 m/s 9.9345e-5 ls/s
Mars 24,077 m/s 8.0312e-5 ls/s
Jupiter 13,070 m/s 4.3596e-5 ls/s
Saturn 9,690 m/s 3.2322e-5 ls/s
Uranus 6,810 m/s 2.2715e-5 ls/s
Neptune 5,430 m/s 1.8112e-5 ls/s

And viola, we have orbiting planets… kind of. I think some of them still head directly for the sun, but that’s probably more due to my fudging the velocity vector. Look for “TODO: Calculate the vector properly” in the code. For now, I’ve just made the initial position for each planet sit at 90o so that the Matrix.Forward vector is the one to use. Stangely now (unlike at the start of this section), the planets ARE in alignment.

Time.. Never enough time…

Morose

It takes a whole year to get the earth around the sun, or at least it should if I’ve done the maths right. Unfortunately I don’t have enough time to sit and watch right now, so being creator of the universe, I simply sped up time :). The planets now move 86,400 times faster, so there is about 1 day in every second.

A Tale of Two Spheres

Testing wheather two spheres are colliding is actually very simple, you simply compare their distance away from each other with the sum of their radii (I never thought that I would have a use for that word.. radii.. sounds cool, no?). If their distance apart is less than the sum of their radii, they are colliding.

This is where we get stuck in the funky physics dance, trying to add an appropriate response into the collision. I was thinking something along the lines of Pool Hall Lessons would be appropriate, but it is not just a simple matter of pluging in an equation and going.

Unless we are doing something wrong (or fun), we shouldn’t have any collisions to deal with. So, for now I’ll put this in the too hard basket, and enjoy the super warp speed that you can get from flying directly into the sun.

As usual, there’s always something left to do

So, now we can take a look at our todo list for more fun things to do that will make this simulation spectacular and exciting.

  • Ugly green planets - Yes, the planets are still ugly and green. I dont feel like chaning them right now, as I have the simulation working and it would take a bit of time to figure out how to skin them properly. If you feel so inclined, there are some free planet textures over at this site.
  • Hilarious exploding results - no, not this time
  • Stolen space ship? - It shouldn’t be too hard to replace the space ship model with another model, but I dont have another model to replace it with.
  • Orbits do not work properly unless the plants are aligned (and yes, all the pots in my garden form a perfectly strait line). I should make the initial velocity work correctly at a right angle of the vector to the sun, but I’m too lazy and my head hurts.
  • Flying into the sun (or a planet if you can catch them) causes a weird “Super Warp Fling” out the other side. This is something to do with getting too close to a single point gravitational field, and will be completely avoided with some collision detection and response.
  • Strange distortions in space-time occur at distances far away from the sun. An example of this can be seen in the image to the right (above) where our ship is looking somewhat crumpled at 120 AU from the sun.

Source Code: Download

Compiled: Download

Building a Solar System in XNA (Part 2)

Posted on April 28, 2008 by Chris at 10:42 am

As promised, here’s the second part in my effort to make a solar system in XNA. It’s not really as good as I’d have liked it, but it’s functionable, and it has some nifty things going on. As usual, I’ve provided a copy of the Code, and Binaries so that you can play with things yourself.

The first thing that I worked on was making a scene graph. This is a nifty class / algorithm that allows you to specify a hierarchical relationship between the objects within your scene. You can build the scene from diffent scene nodes, and depending on the order they appear in the scene graph, objects can be shown, or moved around.

In this example, I’ve written several different node types (some of which can be reused in other projects).

  • SceneGraphBase - This is the base node that all the other scene nodes implement. The class implements a list of SceneGraphBase nodes, so it basically becomes a big tree (similar to the image to the left). It contains code in it’s Update() and Draw() routines that all of it’s child node’s Update & Draw routines.
  • TransformNode - Multiplies it’s own Transform matrix against the world matrix prior to calling any child methods. This allows you to perform a Translation or Rotation (or pretty much any other matrix operation you can think of) to all subsequent nodes.
  • Camera - A flexible camera class that can walk, strafe, fly, pitch, yaw, and roll.. and (importantly) can be used to generate a View Matrix at the current camera location. This is one of my old pieces of code from another project, that’s been adapted many times. It would probably be better to implement the movement functions within the TransformNode if you were starting from scratch.
  • ModelNode - Draws a model at the current world location
  • PlanetNode - Draws a planet at the current world location. Note this could easily be replaced by a prettier ModelNode, but I wanted to write a routine that could generate a sphere.
  • Starfield - You may recognise the starfield from the origonal code, I modified it so that it implemented the SceneGraphBase class, and thus could be included as a scene node.

Building the HUD

So, once I got the scene graph working, I realised that the distances between the planets was HUGE. I could pretty much only find the Sun (which I put in as a planet, but should have some extra cool glowing effects), anc could only find that because I was parked right next to it, and it was so large. So the next thing that I worked on was heads up display (HUD) that could show me 1) how fast I was going, and 2) how to get to each of the planets.

After a bit of searching around for how to write text onto the screen, I found out about the SpriteFont content item. You can add a SpriteFont into your content folder by right clicking on the content folder, then choosing “Add -> New Item”, and selecting the SpriteFont item from the list. Once you have done this, it will add an XML file with the extension “.spritefont” to your content folder. Fill out this file with the font details, and the font will be imported into the project for use later on. You can then load the font during your LoadContent() routine (or whenever you like) by using the single line of code below.

   m_Font = m_Game.Content.Load<SpriteFont>(”SpriteFont”);

Then when you want to use the font to draw a string, you can use this line of code

   SpriteBatch.DrawString(m_Font, “Look at me, I’m a string”, new Vector2(0.0f, 0.0f), Color.Gold);

It’s probably worth mentioning that you probably still shouldn’t use the standard Microsoft fonts in a distributed game, as this would breach copyrights. Many fonts are not free to use, including those provided with Windows. Fortunately, most windows installations do come with a little known font editor. You can get to it in C:\Windows\System32\EUCEDIT.EXE. I’ve not tried to import fonts that have been written using this, but I would imagine that it’s possible.

Reaching the other planets became a huge problem, but fortunately, due to playing games like EVE I knew that building a snazzy HUD tracking system would do the trick. So, I just went ahead and whacked one in there (heh.. yeah right, it was that easy :D). After A L O T of trial and error (about 20-30 hours worth), I managed to re-invent the wheel, and come up with a genuine, planet tracking, boot-skootin HUD. Strangely (as all good solutions are), it was much simpler to do than I thought it would be, so naturally, I tried all the harder things first.

After about 20 hours worth of trial and error of more and more complicated techniques, I was amost completely exhausted and thought about throwing in the towel and cancelling the blog entry :).

Finally, I was ready to use my brain.. after a nice coffee, and some tv, and some sleep.. I got back to it and started by thinking “I wonder if there is any maths that will give me the screen relative position of an object”.. followed quickly by a forehead-slap moment (I have a lot of them). The VIEW and PROJECTION matrices do exactly that for all of the damed triangles that you look at in a 3d scene.

I simply took vector to the object (planet, or whatever), and transformed it with the view, then projection matrices. Suddenly my little tracking circles were working like they knew where things were. One last thing that I did with them, was to Normalize the object’s vector, prior to passing it through the matrices. After doing this, I was able to figure out where the object was using a 180? field of view, and hide everything that was behind the ship.

Finaly some minor tinkering

After spending all my time (and then some) on the HUD, I went to find the furthest reaches of our solar system. I noticed that after a while, the ship started breaking apart. It looked as though the triangles started to get distorted, and that things started shaking. So, naturally, I went into discovery mode to try and figure out what was happening.. It turns out that positioning system I was using was having a bit of Goldilocks syndrome. Floats are just too small to accuately handle points at 4,553,759,184 km (30.44 AU), and similarly, small objects in a ragnge of 0 AU to 30 AU were too small to be handled correctly. So, I translated everything to light-seconds… and they were just right… 1 light second ~ 299,792.458 km ~ 1/499 AU

Leaving the cleaning up for later

Being a lazy, lazy person, I like to leave the cleaning up for later.. or in other words.. never. There are a couple of fun bugs that you will no-doubt find with my code, and a few things that really should (but wont) be cleaned up before any real people look at it..

A couple of hilites you might want to see are:

  • Flying into the sun or a planet always produces hilarious exploding results… I just let you fly strait on in and have a look around under the planet’s skin.
  • It would appear that you can fit a whole planet between the ship and the camera (perspective ftw).
  • The space ship you are flying in is a stolen vehcle.
  • Planets look like ugly green blobs

Building a Solar System in XNA (Part 1)

Posted on March 25, 2008 by Chris at 1:52 pm

Building a virtual solar system cant be too hard, right? Well, I can imagine how people might think that it would just be a matter of whacking in a couple of planets, perhaps a little space ship, and Bob’s your uncle. I’m quite sure that by the end of this, I’ll have proven those people wrong.. I’m thinking that I’ve actually bitten off a bit more than I can chew with this one :)

Anyway.. the topic that this article will attempt to demonstrate is how to build a solar system, using Microsoft XNA as the basic framework. The reason for using XNA, as opposed to DirectX or Open GL, is that (if done correctly), games compiled with XNA can work directly on your Xbox 360. And since I have one of these nifty devices, and I bought it under the premise of writing programs for it.. I really thought I should try and learn a bit about.. well.. writing programs for it :)

I plan to separate this article into three parts, so that the information can be more easily assimilated, and so that I dont end up writing a HUGE blog entry containing too much information, which no one will read. (Who am I kidding.. I’m the only one who reads this blog anyway).

Part 1 - Will cover the basic preparations, and end with a simple application that we will use to build on.

Part 2 - We will do a bit of work with a Scene Graph, add some Planets (and maybe some sattelites), and get things moving.

Part 3 - We will add in some collision detection, and take a look at the gravity of the situation.

The Solar System

The zones of the Solar system: the inner solar system, the asteroid belt, the giant planets (jovians) and the Kuiper Belt. Orbits not to scale.(cue cool space theme music of your choice)

You all remember remember the lessons from school about our Solar System, and it’s 8 planets. I obviously dont remember correctly, cause when I went to school there were 9 planets, but aparently one of those planets exploded got re-categorised as a “dwarf planet”. In any case, our version of the Solar System is going to have 8 planets, and 1 asteroid belt, some sattelites(moons) if we get round to it, and we will let the astronomers argue about what happens out further.

Now, with our picture in hand, plus a little extra information, we can make a table of objects that will be included in the simulation.

Object Distance Radius Mass
Sun 0 AU 6.955 ? 105 km 1.9891 ? 1030 kg
Mercury 0.47 AU 2,439.7 km 3.3022 ? 1023 kg
Venus 0.73 AU 6,051.8 km 4.8685 ? 1024 kg
Earth 1.02 AU 6,371.0 km 5.9736 ? 1024 kg
Mars 1.67 AU 3,396.2 km 6.4185 ? 1023 kg
Asteroid Belt 2.80 AU N/A N/A
Jupiter 5.46 AU 71,492 km 1.8986 x 1027 kg
Saturn 10.12 AU 60,268 km 5.6846 x 1026 kg
Uranus 20.08 AU 25,559 km 8.6810 x 1025 kg
Neptune 30.44 AU 24,764 km 1.0243 x 1026 kg

One of the immediate problems that you can see here is that these objects are fairly big (one might say big enough to have their own gravitational pull). The problem with them being so large is that they are also visible from a loooonnnng way off. In most 3d games and whatnot, you would use a viewing frustrum to cut things off that were a long way away, because they would be simply too small to see. Everyone knows that the Sun is visible from Earth, even though it is 150 million km away, so you just wouldn’t get away with removing it from the scene. I’m thinking that perhaps we could use some kind of scaling algorigthm to determine if an object is visible, since the objects shown are basically going to be big spheres (really really big spheres), it shouldn’t be too difficult to do this. I’d be thinking that this will be requiring some trial and error testing out between Part 2 and Part 3.

Ixnay on Dissin’ the XNA

Ok, just between us, I’m all for Microsoft bashing.. I mean, they are a massive target, so you pretty much can’t miss.. and, you get cred for doing so :D

For all the Microsoft hating going around, I do like my Xbox, and I do like being able to potentially write games for it. However, I don’t like the need to pay membership to the XNA Creators Club, just to be able to play with your own applications on your own console. Fortunately, for us cheap soandsos, they have made XNA Game Studio 2.0 free to download and use. This means that you can write Xbox compatable code, and test it on your own system. Then, if you feel it is good enough to pay for, get a membership and show it off on your Xbox. Thus confirming (again) to all your friends that you are a complete nerd.

Since I own a legal a copy Visual Studio 2005, all the sample code should be compatable with that version. However, it should (in theory) work with any other version that you can install XNA Game Studio against. You might just have to do a bit of hammering to get it to work.

Now, I’m not going to walk through all of the “this is how you set up the project” to “here’s your first triangle” stuff.. there are plenty of other sites, including the XNA Creators Club which will run through this for you, and save ME the trouble of introducing you to 3d. So.. now.. for your homework, go download XNA, install it, run through some tutorials, and I’ll see you some time next week.

I’ve written a basic game that I will modify as we create the solarsystem. You can download the source here, or the binaries here. Just in case you were wondering, yes, that is the space ship model from the Spacewar starter kit. I’m no artist, nor do I have any art packages, so for this little example I hope it’s ok to use that model :)

Source: Download

Binaries: Download.