Search Unity

  1. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  2. Unity 2017.2 beta is now available for download.
    Dismiss Notice
  3. Unity 2017.1 is now released.
    Dismiss Notice
  4. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  5. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice
  6. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice

[Tutorial] c# voxel terrain with infinite terrain, saving and loading

Discussion in 'Community Learning & Teaching' started by 12pt, Jan 25, 2015.

  1. 12pt

    12pt

    Joined:
    May 22, 2013
    Posts:
    20
    [​IMG]

    Hello game developers, I've written a tutorial in c# on creating voxel terrain that can be generated infinitely and saved and loaded wherever needed. Voxel terrain was made hugely popular by MineCraft and I think that's just fantastic because there's just so much you an do with infinite, destructible, buildable terrain so I encourage as many people as possible to try making something with voxels. I've been tinkering with voxel terrain in unity for a long time now and I think I have a solid grasp on developing voxels in unity.

    You may remember or have followed my last tutorial on voxel terrain which got fairly popular, I've decided to take what I learned from that and write a new tutorial that's slightly more advanced and includes more extendibility so that you could use the finished product without starting over to start a game.
    I've been trying to include the things people requested into the foundation of this tutorial so that we can support the biggest requests in the base tutorial or without big structural changes and I've made sure to pack up the assets folder at the end of every part so that in case of problems you can check against a working copy. I've also made the blocks into their own classes so that it's really simple to add new blocks with completely different looks and functions.

    So far I've written six parts in which we'll create the base structure that lets us create as many chunks as we would like in any direction and save and load chunks as we please. I'm planning more specific use tutorials covering the less essential parts for later. See the tutorial here: AlexStv.com Voxel tutorial

    Here are some pictures of the project after part 6 where we add terrain generation:

    [​IMG]

    [​IMG]

    [​IMG]

    If you're interested check out the tutorial on my website here: AlexStv.com
     
    BerniceChua, Wrymnn, EMGPY and 7 others like this.
  2. Lechado

    Lechado

    Joined:
    Mar 14, 2013
    Posts:
    24
    Love your tutorials! Would you consider doing something like a marching cubes tutorial or smoother terrain once you've completed this set?
     
  3. 12pt

    12pt

    Joined:
    May 22, 2013
    Posts:
    20
    The next part is in progress, I've been working on adding ambient occlusion to the mesh data in my own work so I thought I'd make it into the 7th part of the tutorial. Ambient occlusion adds shading in the corners of the mesh where one block meets another, unity pro has a built in AO screen effect but what we'll implement adds it as part of the vertex colors of the mesh and works in unity free. It makes it a lot easier to see the terrain clearly:

    [​IMG]

    See before and after here: http://imgur.com/a/i3rhJ#0

    I'm considering it because so many people have said they would be interested but it will probably have to wait until I have a lot more of this tutorial done.
     
  4. Lechado

    Lechado

    Joined:
    Mar 14, 2013
    Posts:
    24
    Completely understand, Eagerly awaiting the rest of them. :) The ambient oocclusion looks awesome btw :)
     
    Last edited: Feb 2, 2015
  5. Stroved

    Stroved

    Joined:
    Jan 3, 2014
    Posts:
    11
    Awesome tutorial and awesome update, looks interesting. What do you have planned to add to the tutorial? Are you going to go into greedy block rendering, or just stick to what you are using now? The greedy rendering looks pretty slick and cuts down on FPS from what I've read.

    Thank you for this tutorial, it's really helped me get going!
     
  6. WizzDE

    WizzDE

    Joined:
    Jul 24, 2013
    Posts:
    25
    Hi!

    First of all: Very nice tutorial. I have a lot of respect for you, spending so much time to create this detailed tutorials.
    I've benn working with voxels in Unity for quiet a while now and back then when I started I would have loved to find a tutorial like this.
    I've just downloaded the scripts from part 6 to compare your engine to mine and I actually found the same "problems".
    Updating the chunk will push up the Main Thread time from around 13-14ms to 17-18ms (at least on my computer), which becomes noticeable with a small lag. Also your chunks are very small. 16x16 blocks is really not much, but I am aware of Unity's verts limit so there is nothing you can really do about it.

    From what I know there are three optimisations you could do:
    - Greedy meshing (at least for the collision mesh, but actually I have no idea how to propely implement this :D)
    - Threading (very anoying thing to do with Unity but it is possible)
    - Jagged arrays (Block[][][] instead of Block[,,] however not really that much of a performance boost)

    I am currently looking forward to a voxel package that will be released on the Unity Assetstore that looks really promising. I might be able to learn some new things about voxels in Unity from it. We'll see ;)

    Sorry for my English
    Wizz
     
  7. Lechado

    Lechado

    Joined:
    Mar 14, 2013
    Posts:
    24
    He said something in the tutorial about changing the chunk size to 32x32 i believe :)
     
  8. 12pt

    12pt

    Joined:
    May 22, 2013
    Posts:
    20
    Part 7 is released: It loads chunks around the player as they move!

    [​IMG]

    I have some ambient occlusion code for a part in the tutorial and eventually I have an implementation of water I'll include but I haven't planned much else or what order to do things in. Greedy meshing really is cool but I haven't actually tried implementing it, I might look at it in the future.

    Yeah I would like to get chunks loading faster but I don't really want to dive into threading and jagged arrays in the tutorial. another thing is that the object oriented approach to blocks adds a bit of overhead but I think it's worth it for the extendibility. I can see how greedy meshing on the collision mesh would speed things up so maybe I will look into it.
     
  9. Stroved

    Stroved

    Joined:
    Jan 3, 2014
    Posts:
    11
    Awesome! I enjoy watching my terrain load as I fly around, its pretty cool. I think water and trees would be a good next step, as it would bring some life to the world!

    I hope ambient occlusion comes next as well, just to help with the lighting a bit. Do you have any plans to look into more advanced terrain loading, such as biomes and seas etc?

    Your series is amazing so far!
     
  10. Mishkasa

    Mishkasa

    Joined:
    Feb 13, 2015
    Posts:
    1
    This series is really good! I'm planning to make a similar 2D engine, so I'll try making some changes and see if it works :D
     
  11. toxicwolf

    toxicwolf

    Joined:
    Feb 25, 2015
    Posts:
    1
    Great tutorial! One thing I am curious about is how to allow the block textures to be spread over multiple image files?
     
  12. Martix10

    Martix10

    Joined:
    Oct 29, 2013
    Posts:
    1
    Nice tutorial, but I'm getting this error after the part 3:

    NullReferenceException: Object reference not set to an instance of an object
    Chunk.UpdateChunk () (at Assets/Scripts/WorldGeneration/Chunk.cs:92)
    Chunk.Update () (at Assets/Scripts/WorldGeneration/Chunk.cs:52)

    I tried to figure out how to fix, but didn't find anything :\
     
  13. Dunkelheit

    Dunkelheit

    Joined:
    Sep 3, 2013
    Posts:
    75
    Alex,

    How many parts are you willing to do about this tutorial so far?

    Thanks for sharing your knowledge, I'll take a look on it.
     
  14. 12pt

    12pt

    Joined:
    May 22, 2013
    Posts:
    20
    Hey everyone, I just got some time this weekend to work a little on part 8. I made some performance changes, added some trees and added caves. http://alexstv.com/index.php/posts/unity-voxel-block-tutorial-pt-8

    [​IMG]

    With the release of Unity5 screen space ambient occlusion is available for free so I decided not to make this part about ambient occlusion even though it looks cool.

    I've been looking into how to do biomes and I'm not sure yet what the best way is but I'm thinking it would be possible to adjust the variables for terrain generation based on location creating some variation in things like mountain height, tree density and cave size over large distances. As for the ambient occlusion, sorry if you were looking forward to that but try Unity's screen space AO, it's pretty good.

    I'm not sure how to do that really, I'm not all that great with shaders but someone that is might be able to do something like that.

    I'm not working on the tutorials routinely because I'm busy with my job and side projects but I really enjoy working on this tutorial when I can so I'll just keep going as I think of things to add. I hope as far as the project has gotten people using this tutorial to research how to make a voxel game could continue on their own if they feel like it since it's taking me so long. At some point I might consider moving from the tutorial model to creating an open github repository where I can just add new stuff continually and anyone who wants can just use it.
     
    Brendonm17 likes this.
  15. SchalaZeal

    SchalaZeal

    Joined:
    May 4, 2015
    Posts:
    10
    Finding this tutorial very useful! Of course, I'm having to greatly edit the code to suit the type of game I'm making, because there's already enough Minecraft clones lol

    One concern, however: what do I do for collision? Making a test FPSController leads me to fall right through the terrain.
     
    Last edited: May 5, 2015
  16. magic9cube

    magic9cube

    Joined:
    Jan 30, 2014
    Posts:
    38
    Could add a mesh collider;
    Code (CSharp):
    1. MeshCollider mc = chunkObject.GetComponent<MeshCollider>();
    2.  
    3. Mesh mesh = new Mesh();
    4. mesh.vertices = chunk.Verts.ToArray();
    5. mesh.triangles = chunk.Tris.ToArray();
    6. mc.sharedMesh = mesh;
    Can also pre optimise the mesh data with a greedy mesh algorithm.
     
  17. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    855
    You can also use box colliders around where the player is if you want much better performance, and shift them to fit the player's movement. Two downsides: you have to write your own voxel raycaster if you don't want to have to extend box colliders all the way out to the reaching distance for modifying the terrain, assuming that your players should be able to modify the terrain in this way.

    And also, it won't work well for non-cubic voxels. You would have to get around that by using multiple colliders for those types of blocks (assuming you don't want slopes. Those make things trickier!)

    Generally, much easier to go with a mesh collider. It's just awfully expensive.
     
  18. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    5,758
    Would be nice to see actual attempt to get rid of polygons completely and render voxel geometry directly, because when people talk about voxels and the first thing they say is "and that's how we will convert that to polygons", it is depressing. The point of voxels is to get rid of limitations imposed by polygonal systems.

    There should be plenty of papers on the subject, many of them have been around for years.
     
  19. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    855
    Would that apply if you want blocky voxels as well? I'm actually not sure what this means but you've made me curious about it. What does it mean to 'render voxel data directly'? Voxels could just be data, like the block type, and whether it's solid or not... not sure how to render that directly.
     
  20. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    5,758
    Yep, it would apply if you wanted blocky voxels, because that would be faster to compute render/optimize.

    It means that you do not ever create a mesh. You draw ONE fullscreen quad with a shader or use compute shader and it renders terrain/whatever using provided voxel data in a buffer (by highly optimizing raycasting, for example). No polygons, no triangles, no mesh management. Pretty much all modern hardware should be able to handle that easily. You could probably even plug unity effects like ssao in it, as long as you do it right.

    Yet every game insists on triangulating potentially infinite number of cubes. Which is why I said it is depressing.

    The beauty about voxel data is that you have fixed memory requirements, so no matter what happens, you'll always draw the scene. The problem with triangulation is that the scene has potentially infinite memory requirement (If I take 64x64x64 voxel block and kick out voxels in very specific patterns, it will result in 780k triangles).

    Here is 6 years old demo.



    And here's recent one:



    That's voxels.
     
    Last edited: May 22, 2015
    odival and JasonBricco like this.
  21. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    5,758
    Regarding square cubes.
    Here's quick test in unity (completely unoptimized, quick and dirty solution).

    Adding lighting and face textures should be trivial.

    [​IMG]

    Aside from original box that works as "portal to the voxel world", voxels do not use polygons here.
     
  22. Kristophbarbour

    Kristophbarbour

    Joined:
    Mar 21, 2014
    Posts:
    1
    Hey Alex,

    Would it be at all possible for you to do a "quick" tut on how to convert this from regular "Minecraft" style cube voxels to marching cubes to give a less blocky feel? I really like what you have done so far but would love to see a marching cubes version of this.

    Cheers,
    Chris B
     
  23. RIw

    RIw

    Joined:
    Jan 2, 2015
    Posts:
    72
    @12pt
    Excuse me,I'm learning from your tutorials now and I found a problem on Second part.I'm using your texture resource and on the any Block with this texture I can see the green lines on the contours.How can I solve this ?

    And what about placing new blocks in the World ?
     
    Last edited: Jul 20, 2015
  24. LiquidDarkness

    LiquidDarkness

    Joined:
    Apr 19, 2013
    Posts:
    18
    I loved the tutorials and hope you manage to do more in the future! :) I'm trying to use what I've learnt to generate a cubic terrain in the editor as my game will have one finite sized world, rather than infinite generated terrain. I'm a bit of a noob so was hoping someone could help. Essentially, I've got as far as the terrain generating in the editor, but it is all invisible. Nothing is rendering at all! I've tried fixing it but I don't really know where to begin.
     
  25. Kaerfca

    Kaerfca

    Joined:
    Aug 7, 2015
    Posts:
    1
    This is an amazing tutorial, 12pt! :) I've been adding my own things to the game on top of what you've taught me, and it's a very great learning experience.

    I have one question though, that I'm absolutely stuck on. I want to make my character spawn in a randomly-chosen location, sort of like Minecraft. I want to make sure the player spawns (preferably on a grass block, but I'm not too picky) above ground. How could I start going about that? Thanks in advance, and I hope you do more in the future!
     
  26. Unexpected_Persona

    Unexpected_Persona

    Joined:
    Jul 23, 2015
    Posts:
    9
    I have some very basic understanding of how this works in terms of generating the mesh and things like that, but I don't really understand how the UV system works/how to make my own custom textures work for it. I'm trying to make a 2-D voxel-terrain game and I'm not sure how to convert the files into a system where 2-D will work and allow me to use my own textures for tiles. Does anyone know of any tutorials that could help me make a 2D voxel terrain system? Thanks.
     
  27. 3dproject

    3dproject

    Joined:
    Jul 26, 2015
    Posts:
    14
    hi guys before i start .i would like to know if this tutorial includes voxel generation which is a lot less blocky.

    thanks
     
  28. SuperFranTV

    SuperFranTV

    Joined:
    Oct 18, 2015
    Posts:
    1
    Hello,

    Important,
    i want to single create the meshes in editor and make a world, i don't want to create the world in play mode, how can i do this, i must save the meshes in the asset folder but who must be the code in the scripts?

    Also is there a way to spawn random trees (prefabs) from asset folder?

    Why do you need a chunk loader, the better way is to take the occlusion culling from unity or?

    Thanks please answer!
    Sry i speak german
     
  29. CreativeN

    CreativeN

    Joined:
    Oct 30, 2015
    Posts:
    1
    Great tutorials !
    Will you add biomes like those ?
     
  30. NaXDy

    NaXDy

    Joined:
    May 12, 2014
    Posts:
    11
    Hey, what happened? Are you still working on those tutorials?
     
  31. datatype_void

    datatype_void

    Joined:
    Sep 2, 2015
    Posts:
    13
    An example or at least general direction with how to do this in Unity would be beneficial or at least some links to the reference materials you used. I would greatly appreciate this!
     
  32. Lagomorphic

    Lagomorphic

    Joined:
    Jun 4, 2017
    Posts:
    2
    Hi , if anyone wants to see what I did in great appreciation towards alex for writing this
    I've added a few more things like foliage gravity, liquids ......



    Yes sorry I know I sound 10....


    I know this topic is old : now we have draw mesh to my hurting eyes... instancing .... i've been in frustration as to what i'm doing now....
     
  33. Satyros

    Satyros

    Joined:
    Feb 8, 2015
    Posts:
    2
    Hey mate!
    Very helpful tutorials, but your domain name has expired (and just as I was working on them xD).
    Any chance of uploading all that information somewhere else?
     
  34. Balistic_penguin

    Balistic_penguin

    Joined:
    Jan 18, 2017
    Posts:
    104
    Same here
     
  35. TehGuy

    TehGuy

    Joined:
    Apr 27, 2013
    Posts:
    1
  36. aaronfranke

    aaronfranke

    Joined:
    Jan 23, 2017
    Posts:
    5
    I have a question. In Serialization.SaveChunk, you have this line:

    Code (CSharp):
    1. Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);
    Why do you use Stream instead of FileStream at the beginning of the line?