Coding Adventure: Procedural Moons and Planets

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Man I get so excited every time Sebastian Lague uploads a video. His coding adventures series is truly one of the most interesting things I've ever seen on the internet. If there were enough videos, I think I could watch it for 20 hours straight!

👍︎︎ 88 👤︎︎ u/Log_Dogg 📅︎︎ Jul 11 2020 🗫︎ replies

He briefly mentions the cube sphere but then does the rest of the video with icospheres / octahedron spheres.

The cube sphere is my pet favorite and supposedly Google uses it in all their mapping stuff: http://s2geometry.io/devguide/s2cell_hierarchy along with a subdivision system that unrolls the whole Earth as one space-filling 2D curve with a 64-bit index.

The icosphere is fine for what he's doing, and the cube sphere has downsides, too. It has 8 poles, and as you get near the poles, the squares become distorted. Instead of 90 degree corners, they turn into diamonds with 120 degree corners so that 3 can join together at each pole.

The same problem happens with icospheres at their poles - Normally a vertex should be shared by 6 triangles, but at a pole it's shared by 5. Math hates us.

The same trick of "Don't do binary subdivisions, just divide however much you need in one step" could also be done for the cube faces, and it would be simpler there, but in practice I think S2 geometry uses binary subdivisions.

I had wanted for a while to make a game with cube spheres to prove how cool they are, but I couldn't think of anything worth doing. Maybe icospheres are better, since they have mostly the same weaknesses?

👍︎︎ 88 👤︎︎ u/VeganVagiVore 📅︎︎ Jul 11 2020 🗫︎ replies

This guys channel is amazing in general

👍︎︎ 23 👤︎︎ u/LionST1 📅︎︎ Jul 11 2020 🗫︎ replies

Wow, I didn't think I'd learn much, I knew about most of the stuff he talked about, until he talked about tri planar mapping. I swear to god nearly every other tutorial about tri planar mapping tries to make it out to be some mystic galaxy brain bullshit. This made it so simple and so easy to understand what is going on, and the purpose of it! People who make tutorials, take notes from Sebastian here: Quit tooting your horn when you write tutorials, and just explain what you mean, and absolutely don't try to fill in the gaps of your own knowledge when you write it either, like this cool dude who claimed:

The first downfall you will encounter is the performance. The fragments of the geometry are going to be rendered 3 times, once in each direction.

If you've watched Sebastian's video, you know this is bunk. You have to read from the same texture 3 different times, but you don't need to triple render the fragment. This guy didn't know what a "fragment" actually was, what he implied you had to somehow draw the same triangle multiple times. Or he made a strange misstatement I've never seen before, though he's had 6 years to fix his mistake if that was the case. These kinds of issues can stop people from implementing something even when you explain it well. People will second guess the knowledge they just learned "The author says I need to watch out for X, but I don't understand why, it doesn't make sense. But the author clearly cant be wrong because the tutorial was so good otherwise, and certainly I know less than him!" When Sebastian doesn't know something, he lets you know he doesn't know something. In his earlier terrain generation video where he moved things to the compute shader, he talked about how he didn't understand how to move his marching cubes generation over the the GPU. He thus had to use atomics in order to directly translate is CPU code over, essentially serializing the algorithm with out knowing it. The real solution to his problem is stream compaction, but that is a lot more difficult concept to tackle for someone who was just introduced to compute shaders. But he never made it seem like "Hey guys, I know everything, and this is exactly how you are supposed to do things". He lets you know when he's not an authority on something, so when he says something that doesn't make sense, he's already let you know "Hey, I might be wrong about this, take what I'm about to say with a huge grain of salt!".

Another thing is Sebastian only shows you what you need to see. He doesn't clutter your vision, or obscure the actual important code. Visualize, this is what you'll see. Background, this is how you'll be modelling it intuitively. Implementation. This snippet of code is self contained, and implements only what we just talked about, nothing else. Normally I find articles more efficient to learn from, but the articles that cover the same topics as his videos often fare much much worse. Get to the point, don't make me skip around your article to actually figure out what I need. As an example despite being a tutorial also in Unity and being only about triplanar mapping, this article manages to take more than 3 times as long to follow along and implement. They also made the code look... alien? It's the same language, yet they stuff it with so many unnecessary defines, macros and mixing shader FFI concepts and strange menu quirks it obscures the point.

I don't even use unity to do graphics development. I code everything in Vulkan and GLSL nowadays. I was able to translate what Sebastian showed us for triplanar mapping in only a couple minutes.

👍︎︎ 11 👤︎︎ u/Plazmatic 📅︎︎ Jul 12 2020 🗫︎ replies

Haha the animation he uses at ~9 minutes is credited to Inigo Quilez. The name sounded familiar so I went back to look at some old school work and it turns out I emailed and got permission from him to use some fractal imagery in a paper I was writing.

👍︎︎ 19 👤︎︎ u/dffffgdsdasdf 📅︎︎ Jul 11 2020 🗫︎ replies

all his videos are amazing.

👍︎︎ 8 👤︎︎ u/Femaref 📅︎︎ Jul 11 2020 🗫︎ replies

This looks strangely similar to game Outer Wilds

👍︎︎ 9 👤︎︎ u/Bladye 📅︎︎ Jul 11 2020 🗫︎ replies

What's the platform he's using to allow him to change parameters and show the resulting images in real time?

👍︎︎ 5 👤︎︎ u/bsmdphdjd 📅︎︎ Jul 11 2020 🗫︎ replies

I spent a weekend trying to create some interesting randomly generated stars for a game I was working on it. After adding a few different noise patterns with different rotations to create a seething surface, adding a corona and then spending hours looking into modeling diffraction patterns to create a cool lens flair effect like they get on the Hubble and making it all look good at different levels of zoom, well, I gave up and mostly had some slightly off-white spheres floating around in face.

It's a surprising deep/fun problem.

👍︎︎ 3 👤︎︎ u/periodic 📅︎︎ Jul 12 2020 🗫︎ replies
Captions
hi everyone i was recently messing about with gravity simulations and ended up making a little solar system which you could fly about and explore it's hard to get terribly excited about exploring a bunch of coloured spheres though so today i'm embarking on a journey to generate some simple procedural moons and planets [Music] i need a sphere to begin with so this bit of code is one way of calculating the points and it allows me to control the number of vertical and horizontal segments which means i can control how detailed the planet will be unfortunately a lot of that detail is clumped around the poles so this probably isn't the right sphere for me but plenty of fish in the sea for example if you've seen this video of mine on boyd's you may recall me getting wildly sidetracked by something called the fibonacci sphere this is a really cool method which allows us to choose exactly how many points we want and they're really evenly spread out as well i had no idea though how to turn these points into triangles to create a mesh because they aren't calculated in a neat winding order like the previous method but i found this interesting post which explains that you can project the points onto an infinite plane triangulate those and then wrap it back up into a sphere i thought that was really clever but i wouldn't mind something a little more straightforward so i'm going to keep exploring my options six planes can be arranged to form a cube and if we then force the points to all be the same distance from the center we get the humble cube sphere what's cool about this technique is that each face can be divided into smaller subfaces which means you can render nearby regions of a planet in high detail but save rendering time on more distant areas there's a lot of work i still need to do on this though fixing the gaps and lighting issues that occur at the seams which seems like quite a headache so since my goal for now is just simple miniature planets i'm going to have a look at another celebrity sphere the ico sphere to create this one i learnt that you start with three rectangles with side lengths in the golden ratio if you then join the points at the corners to form 20 triangles you have an icosahedron which is apparently ancient greek for 20 seat in case you were wondering in any case each triangle can then be divided into four sub-triangles and those new points projected onto the sphere we can repeat that as many times as we want to increase the resolution the only trouble is the number of vertices grows really rapidly with each division so you don't have such fine control at this point i came across an article about different types of spheres and in the comments was ben golis describing a different approach where you simply add however many points you want along the edges of each triangle and connect them up like so i spent a while figuring out all the index math for this on paper which worked out great for me as you can see but i swapped some numbers around and eventually ended up with something where i have decent control over the number of points and a pretty good distribution as well here's my code for this which is probably many times longer and more convoluted than it needs to be so nothing unusual there what i'd like to create first from this sphere is a little moon with a surface covered in craters and to do that i'll need to calculate a height for each vertex i have quite a lot of vertices so i'm going to do this in a compute shader so that i can process loads of them in parallel on the gpu compute shaders can be unbelievably fast but they also have this distressing habit of finding new and creative ways of crashing my computer so it's a bit of a love-hate relationship anyway i'll get the current vertex position and then write a value to my height buffer based on that so as a little test run for example i'll try 1 plus the sine of the position on the y axis multiplied by some test value this will then be used elsewhere in the code to actually modify the height of that vertex so i'll open up my shape settings here and if i increase that test value we can see the sphere wobbling along with the sine wave so with my basic setup working i've begun looking at some craters i basically just need to create a little bowl-shaped cavity with a raised rim around it and also a lot of craters seem to have flat floors formed from shattered and melted rock larger craters also undergo some fascinating transformations for example gravity causes the walls to slump down into step-like formations and somehow the ground is also pushed up to form these giant central peaks when some cases rings of peaks i then fell down a bit of a rabbit hole reading about the man who spent 27 years mining for the wealth of iron meteorite he figured it caused this crater only to then learn it had been vaporized in the impact more distressingly i came across the so-called mimas moon in orbit around saturn wake up sheeple that's no moon i should probably get back to work so i need to try come up with some equations to describe the basic shapes of a crater for the cavity for example i can just use a simple parabola like this to form the rim i experimented with a bunch of things but what i ended up with was another little parabola mirrored around the x-axis which can be shifted horizontally with the room width parameter and contracted or expanded using the rim steepness parameter then for the flow of the crater i'll just have a straight line which i can shift up and down now to combine these three equations together i'll make a crater shape function and this will first take the minimum value between the cavity and the room resulting in this and then take the maximum value between that and the floor which gives us the overall shape the lack of transition between the functions makes the shape really harsh and unnatural though so several episodes ago back when i was experimenting with ray marching i learnt about the smooth min function for blending shapes together this function just takes whichever is smallest between a and b but with some smoothing applied controlled by the parameter k to make this return the max instead of the min you can just make k negative by the way so if i use that for my craters and increase the smoothing parameter you can see it looks a lot more natural i now just need to translate that to my moon height compute shader and behind the scenes i'm also now feeding it a buffer containing a random position and radius for each crater plus all the various settings it needs then going into the scene i'll increase the maximum radius and we can see a single crater appear let me add in a bunch more of these and to try to get them looking a bit more crater-like i'll mess about with the room width and steepness parameters and then also the smoothing amount to make the shapes a little less harsh that's looking okay so i'll add in a bunch more of them it looks terrible now but i think would help is if smaller craters were a lot more common than larger ones so i'm generating a random number between 0 and 1 to determine the size of each crater and if we pass that value into this function that i'm graphing here we'll just get out the exact same thing we put in because y is equal to x at every point so that's pointless but here's the code for this function and as you can see it's controlled by a parameter called bias the bias is currently zero but as i increase it towards one you can see how the curve changes so now most values we input to the function will just get a small output and only a few will result in a relatively large output back to the moon i can now use this little slider to change the distribution of the crater sizes and make small craters more common than larger ones the last parameter to play around with is the floor height and currently this affects all of the craters but i'm going to make a little change to have the floor height determined per crater just to add some variation all right that was very long-winded but we now have some fairly cute little craters the moon is exceedingly smooth at the moment though so i want to add some little bumps and ridges using noise the noise function i'm using just takes in a point in space and gives back a value between negative one and one which changes smoothly as you move the point around the code for that noise function which is not something i wrote myself looks like this very confusing anyway we can make multiple layers of increasing detail by spacing the sample points further and further apart each time if we combine all these layers into one well it's a bit of a mess but if we make it so that each layer contributes less and less to the overall result we get some nice structured and detailed noise out of it the code for that looks like this we can do some fun things with it for example we're sampling the noise function at a point in space so what if we offset that point using more noise well as it turns out this warps the noise in pretty cool ways if you add a bit of color and animate some values you can get some pretty stunning results modifying it another way by taking 1 minus the absolute value of the noise results in a more ridge-like appearance useful for well ridges and mountains i had some fun playing around with different colors and just watching the noise scroll by just for fun let's try use this to create something similar to hyperion one of saturn's less threatening lumpy spongy looking moons so i have some different noise settings over here like the ridge noise i was just talking about this has a bunch of parameters i can play with like the scale and the power looks great we can also subtract the ridges instead of adding them which i think looks kind of interesting anyway to get a kind of lumpy shape like hyperion i'll add some simple noise and scale the frequency way down i can then offset the sample position until i get a shape that i like i'll then also add some higher frequency noise for a bit of detail hyperion had a lot of holes punched in it so i'll put the number of craters way up to something like 3000 and it's quite amazing that my terrible crater code which loops over every single crater on every single vertex is actually still running reasonably quickly anyway here's my little rock if i want to add more detail without increasing the number of vertices i'll need to use textures so typically someone creates a 3d model and then painstakingly adds seams to indicate how it can be unwrapped into two dimensions a talented artist then draws details on top of that and we get our beautiful result to bypass the annoying unwrapping step i'm going to try use a technique called tri-planar mapping and the idea is to just use the position of the model's vertices to read from the texture of course the position is in three dimensions and the texture in two so over here i've just picked the x and y axes of the position to sample from the texture this gives great results when we're looking into the x y plane but from other directions it's somewhat less convincing so the idea continues we sample the texture two more times using the zy and xz axes now we just need to blend between these three different textures to favor whichever one aligns best with the surface which we can do based on the surface normal we can also raise the normal to some power to affect the sharpness of the blending and multiply the position by some factor to control the scale of the texture if we look at the sphere now you can see it's blending between the projections but the result is kind of muddy and that's what the sharpness parameter was for i can fiddle with that and get it looking how i want also if i change the scale parameter surprise surprise it scales the texture i'll grab one of those textures from my warp noise experiments to use instead this needs some lighting so i'll quickly go back into the shader and calculate the dot product of the surface normal and the direction towards the light source and then multiply the output color by that this looks a bit bland though so i'd like to spice things up with a normal map i did some research on how to get that to work with tri-planar mapping and once again ben was there to guide the way with this very detailed article on the subject so here's the triplina code now modified to work with normal maps in my fragment shader i can then get the normal from the normal map and use that to calculate the lighting i found these two handsome maps online so let's try them out immediately the surface looks a lot more interesting in detail than it really is here's what the other map looks like so i'll switch over to my actual moon surface and raise the strength of the normal mapping here i'm actually using both normal maps and blending between them based on some noise to try break up the repetition a bit what i'd like to do next is add some color variation so i've generated some noise which is stored in the mesh uvs and using that i can split the moon into two color regions i also have some settings for warping that noise because i like warping everything now one little detail i wanted to add is these cool looking rays of ejected material you can see around relatively young craters before exposure to space darkens them and they fade into the background to do this i randomly pick a couple of craters to have this feature and i then did some slightly suspicious maths to calculate uv coordinates around them like so and it can then sample from a texture to draw the rays this doesn't look great to be honest and it only works for a small number of creators but it's better than nothing for now i think [Music] there's clearly still a lot of room for improvement of the moons but i'd like to move on for now and begin creating some little planets so i'll write a little shader that just uses the fractal noise from earlier to create some landmass shapes i'll smooth out the lower values to create an ocean bed and then i'll multiply all heights below zero by an ocean depth parameter i'll then also add in some ridge noise for mountains and finally add those noises together and write it to the height buffer so here's the noise in action i'll deepen the oceans and flatten the floor a little and then i'll go into the ridge noise settings and push up some mountains the only trouble is the mountains have kind of taken over and i'd like to retain some flat areas so i'll add another layer of noise to act as a mask and i'll multiply the mountain noise by that mask so now if i shift the mask around i have some control over how abundant the mountains are here's what the mask actually looks like by the way now i'm not sure what the best way to handle the oceans is because i want the player to be able to go underwater what i'm going to try for now is doing it as a post-processing effect so after everything else has been drawn this shader will be run for every pixel on the screen and in here we can access the camera's depth texture to figure out how far away everything is otherwise the ocean would just be drawn on top of everything i then collaborated with stack overflow to write this little ray sphere intersection function which can tell me the distance to the surface of a sphere and also the distance it travels through it to the other side in my ocean shader i'll then use that function to figure out how much water we're actually looking through for the current pixel if it's more than nothing i'll draw white otherwise i'll just leave the original color that gives me this to add some color i'll go back to the shader and use the depth of the water to blend between a shallow and deep color and also blend in some of the original color in shallow regions to give a soft transition at the shore so i can control the transparency with this parameter and the blending of the shallow and deep colors with this one i can also obviously change the colors [Music] now i'd like to be able to see the sun in the water so i looked up the equations for specular highlights and decided to go with the gaussian model because apparently it's slightly better citation needed the calculation is kind of expensive though primarily because of this arc cosine function which i hear as a big no-no in shaders so i might replace this with a cheaper model later i'll then also add some diffuse shading and apply this lighting to the ocean color so i can now use the smoothness slider to control the size of the highlight and behind the scenes i also added in some wave-like normal maps using that same triplanar technique from earlier and that gives a kind of nice effect it would of course be a lot nicer to have actual waves rising and falling but i have no clue how to do that especially using this technique on a sphere something to look into for sure now with the way i've done this it is possible to go underwater but the effect is quite underwhelming at the moment still i'm going to call it good enough for now and move on to coloring the terrain in one of my old tutorial series i tackled this problem by assigning colors based on elevation but this results in kind of silly looking bands of color i've learnt at least one new trick since then though which is to consider the steepness of the terrain calculated as the dot product between the surface normal and the up direction at that point we can then make grass for example appear only where the steepness is below a certain threshold i do still use the elevation to not allow grass to grow too high up and also to add some slight color variation something i've been struggling with a lot is the look of the mountains because they look too smooth i tried adding in a rocky normal map but it looked a little bit horrendous in an earlier iteration i experimented with flat shading and also adding a threshold so that only steep regions would be flat shaded but i wasn't so happy with this either ideally i'd like to use a technique i experimented with a while back where you simulate hundreds of thousands of droplets of water to try and mimic the effects of erosion just thinking about the changes i'd have to make for this to run on a spherical world seems like it'd become ridiculously slow though so my latest attempt has been this kind of cartoony effect with solid bands of color to try emphasize the rockiness of it [Music] i'm not sure if that's the style i want to go for or not but i've been experimenting a bit adding for example this sort of speckled effect to the grass up close you can see the terrain looks a bit raggedy so i do think it would help if i could increase the resolution some more i have several levels of detail that i can switch between but that's just for the entire planet so i think i might need to break it up into chunks after all headaches await me i guess anyway we can of course randomize the planet shape which just works by changing where in space the noise values are sampled from and we can randomize the colors although the combinations can sometimes be a bit of an eyesore i've then also been having some fun generating other little planets and moons to fill up my test solar system for example here's one that i've nicknamed cyclops because of its one giant crater i quite enjoy just messing about with the settings and seeing what happens as you can probably tell there's a lot of warping going on in this one so i'll play with that parameter a bit as well cyclops has a little moon based on those hyperion experiments from earlier there are a bunch more but i'm quickly going to hop over to blender and try whip up a blocky little astronaut so we can go explore them properly i'll get this imported into the game make a build and oh no what have i done this time well that was weird but here we are by the home planet and alongside it is its little moon i'm going to see if i can zip over that quickly [Music] [Music] well let's go see what's out there looks like a whole lot of nothing [Music] i'll head back to the ship because there's not actually much to see here but maybe several episodes down the line there'll be some little knife forms to go cat or something for now though i'll just hop over to the next door planet [Music] oh good thing i haven't added a damage system yet with the way i pilot this [Music] thing [Music] so obviously things are kind of wonky looking at the moment but if i can work on the graphics a bit and add in some trees and bushes and maybe some little life forms as i mentioned earlier i think it could potentially be a nice little place to wonder about for my last stop on today's journey i'll fly over to the twin planets which orbit up close and personal with the sun and i'll go pay a little visit to the fire twin that's going to be all from me for today obviously there's loads of things i could do to improve the look of the moons and planets i just wish i knew what they were and how to do them but that just means there's loads left to learn so i'd better get to it as always i hope you've enjoyed watching and until next time cheers
Info
Channel: Sebastian Lague
Views: 1,214,375
Rating: undefined out of 5
Keywords: programming, coding, game development
Id: lctXaT9pxA0
Channel Id: undefined
Length: 22min 47sec (1367 seconds)
Published: Sat Jul 11 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.