GithubHelp home page GithubHelp logo

javier-garzo / marching-cubes-on-unity-3d Goto Github PK

View Code? Open in Web Editor NEW
330.0 19.0 41.0 11.41 MB

Terrain voxel engine with the use of Marching Cubes implemented in Unity 2020.3.17f1 (LTS).

License: MIT License

C# 93.80% ShaderLab 6.20%
marching-cubes voxel-engine terrain-generation

marching-cubes-on-unity-3d's Introduction

Marching-cubes-on-Unity-3D

Terrain voxel engine with the use of Marching Cubes implemented in Unity 2020.3.17f1 (LTS). You can clone and run the project or download only the Marching_cubes folder and add to your project assets.

GifEdition



Table of contents

  1. Introduction
  2. Unity scenes
  3. Configuration
    1. Constants
    2. Managers
  4. Biome system
    1. Edit biomes
    2. Create new biomes
  5. World manager
  6. Future work
  7. References

Introduction

The unity project is a implementation of the algorithm Marching Cubes for the generation of a voxel engine for generate a random and infinite terrain. The idea is try to offer a flexible solution for developers that want integrate a free Voxel engine in his game or give a base for develop your own Marching Cube engine. Some of the actual properties of the engine:

  • Marching cubes: Used in the terrain generation, support edition in real time and Job System + Burst for generate the chunks (it improve the efficiency).
  • Chunk System: Chunk system for load the terrain near the player.
  • Random terrain and biomes: The terrain have random generation (seed) and support different types of biomes for the generation.
  • Save system: The data saved in a .reg files inside the dir: Application.persistentDataPath + /worlds + WorldName (Default one: "/default").


Unity scenes

The unity project have a total of 3 different scenes:

  • FirstPersonLevel: An example of a first person level and the recommended test level for check the project. Load/generate a terrain where you can add voxels with the left click and remove voxels the right click. Controls: AWSD, mause and + - keys.
  • ChunkVisualization: Similar to FirstPersonLevel but the generated terrain use a material that give each chunk a color, for help to visualize them.
  • TerrainViewer: Used to debug terrain/biomes in real time, when you modify a data of the NoiseManager get update in the terrain. Controls: AWSD, mause and + - keys.

Configuration

You can configure the project to adapt it to your necessities. You have two type configurations: constants or managers.

Constants

The configurations of the constants used internally in the engine, all indicated in the "Constants" script. You can modify the region of "Configurable variables" (don't touch other regions). You have the explanation of each variable in the script or in the below list:

  • CHUNK_SIZE: The size of a chunk, all the chunks have the same x and z size.
  • MAX_HEIGHT: The total height of the chunk, also the max terrain height.
  • VOXEL_SIDE: The size of a voxel, now it's 1 so one voxel have 1x1x1 size.
  • REGION_SIZE: The number of chunks per region side. That indicate the dimension of a region, actual 32 x 32 (x,z).
  • REGION_LOOKTABLE_POS_BYTE: Used in the save .reg files. Number of byte needed for represent (REGION_SIZE * REGION_SIZE) +1. Example: (32 x 32) +1= 1025 = 2 bytes needed. MAX = 4.
  • NUMBER_MATERIALS: Total number of materials inside the material grid texture.
  • MATERIAL_FOR_ROW: The number of materials in each row of the grid texture.
  • SAVE_GENERATED_CHUNKS: Used for save generate chunks without modify (when true). Recommend: false,
  • REGION_SAVE_COMPRESSED:Compress the .reg files . -File size -write time +CPU cost of compress a file. Recommend: TRUE
  • AUTO_CLEAR_WHEN_NOISE_CHANGE: If World Manager not exists in the scene and the current noise change, we clear the old world data (this remove the old chunks which generate wrong connections with new chunks).

Managers

Each manager (GameObjects inside Unity scene) have some parameters that you can modify for get different results, the majority of them only apply changes when new chunks are loaded if not indicate the contrary.

Mesh builder manager ("MeshBuilder"):

  • isoLevel: Indicate the value above which the vertices of the voxel are inside of the terrain (Not air).
  • Interpolate: Allow to generate a more organic terrain using interpolation when build the mesh.

Noise manager ("NoiseManager"):

  • World Seed: Seed of the world, for pseudo-random terrain generation.
  • Biome Scale: Size of the biomes.
  • Diff To Merge: The biomes.appearValue difference for merge.
  • Surface Level: Surface desired level, height where biomes merge.
  • Octaves: Octaves used in the biome noise.
  • Persistance: Amplitude decrease of biomes noise per octave,very low recommended.
  • Lacunarity: Frequency increase of biomes per octave.
  • Biomes: Biomes class array. Empty for get all Biomes of inside the GameObject (recommend).
The noise manager also contains biomes that with parameters to modify but this is explained in the biome section.

Chunk manager ("ChunkManager"):

  • Terrain Material: Terrain applied to all chunks of the terrain. The material of the terrain.
  • Chunk View Distance: Chunks load and visible for the player,number of chunks distance. (Render distance of chunks). Change in play mode supported.
  • Chunk maintain distance: Distance extra for destroy inactive chunks, this chunks consume ram, but load faster.

Biome system

The biome system allow you to generate different types of terrain generated in the infinite world. It used a value between 1 and 0 where each biome has appear range, so each biome can have 1 or 2 possible neighbors biomes.

Desert-mountains biome and the "NoiseManager" with the biomes:

Biome frontier

Ice biome and plains biome: ice-grass biomes


Edit biomes

For edit a biome you can use the TerrainViewer scene. You only need to remove all the biomes classes from the "NoiseManager" except the one which you want edit and then modify the values of the inspector.

You can use the "NoiseTerrainViewer" for use a bigger or smaller test area or apply offset to the terrain. All the changes applied in this scene update the test terrain, so you need start the scene, apply the changes to the biome, copy the component, stop the scene and paste the component values to the biome.

Example of edition of the "B_Mountains" biome: B_Mountains edition

Create custom biomes

For create the a biome you need create a class that heir from the class "Biome" and that must have the function "public override byte[] GenerateChunkData(Vector2Int vecPos, float[] biomeMerge)" used for generate the biome texturization. For this process you can copy a paste the code of some actual biome and apply the necessary changes to the code for get your custom biome.

When you have the new biome class create, use the edit biome section for edit the parameters in a real time test terrain.

For apply this to other levels just add this new custom biome to the NoiseManager in the other scenes. Like in the image we add the new biome "B_NewBIome" to the NoiseManager:



World Manager

The world manager is a optional manager (if not exist "default" world name is selected) to support multiple worlds folder system, just to allow multiple games in different worlds. You can found the prefab in "Assets > Marching Cubes > WorldManager", this prefab contain a gameobject with the manager script. This manager supports:

  • Change default world when manager is instanced: You can change the public variable "World" on inspector for select the loaded world. The default name if not change the variable or the manager is not instanced is "default".
  • Fast access button to worlds data folder on script: Exists a button on the inspector at the end of the script, that allow you to open the computer folder where all data/worlds are stored.
  • Functions for menu: If you open the script you can see the multiple function that the manager support, get all the worlds created, get the current selected world, select/create a new world o see the data size of world. The idea is that you have all this functions for create a world menu or similar.

Future work

The priority of next update will be:

  • Fix the texturization system: The texturizations is not correct and can be visible in geometrical textures (ex: brick textures). Update: Some improvements but need some fixes.
  • Support of multiple worlds in the ChunkSystem/file system (Actual only one word is used by all levels) (WorldManager added).
  • Different types of terrain modifications.

Others futures updates:

  • Upgrade the biome system for support 2D noise biome creator (Actual the biome is created using 1D noise from 0-1).
  • Add a vegetation system to the biome system.
  • Cave system suApport for NoiseManager/Biome system.
  • Extend the Job System and Burst to the NoiseManager (efficiency improvements).
  • Add support to filesystem to save entities (animals, monsters ...)
  • Add a LOD system for the far chunks of the player.

References

The Marching Cube algorithm:

Noise system:

Others:

marching-cubes-on-unity-3d's People

Contributors

javier-garzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

marching-cubes-on-unity-3d's Issues

Sphere world generation

Hi, how can I make spherical world shape? What should I change in marching cube algorithm to make world spherical?

Getting deeper

Hi, thanks for your project!
Ater changing to HDRP and using the lit texture on terrain I have this weird problem where I can only light up in one direction.
Something like this.
helpas
Do you have any clue what happened there?

How to prevent interpolation?

Hi @Javier-Garzo,
I am building a voxel game and I managed to make cubes but I couldn't find a way to prevent interpolation between ground and placed cube.
image
I want to combine Minecraft-looking blocky voxels combined with a marching cube but this ugly-looking interpolation prevents me, how can I solve this?

Is there any option to do voxels smoother?

Hi, I suppose I can speak in Spanish but I'll keep talking in English for the community.

Is there any option to make voxels shape smoother? I think yes, but I'm a little bit newbie with voxels.

I bought FastNoise (https://assetstore.unity.com/packages/tools/particles-effects/fastnoise-70706) in the past which could help me to make me an idea about this, so when I have it available I'll come with a PR.

PD: Also I have this tutorial: https://github.com/z3nth10n/AlexStv-Unity-Voxel-Block-Tutorial so I'll be investigating, I'll like to do some kind of procedural cave system with this: https://github.com/z3nth10n/AlexStv-Unity-Voxel-Block-Tutorial

In the meanwhile, you can add me on discord: @z3nth10n#0775

Thanks for your attention!

Changing VOXEL_SIDE Error

I'm changing the voxel side to 0.5f and the result is, How to subdivide chunk to get more vertices?
image

UV issue

There seems to be an issue with UV. Sometimes texture gets stretched
image

Too much vertices?

Hi, I have been having fun with your code, and making some changes. I realized on flat planes mesh has 1536 vertices, and 512 triangles. Shouldn't there be 289 vertices since plane is 17 * 17. I just wanted to ask if i could improve performance by reducing the number of vertices somehow.

Get Byte data from a vertex (placement objects)

Hi, I am trying to implement a vegetation system (not seed yet), but I have not fully understood how the bytes work to obtain if a vertex is grass or snow for example.

The trees are placed on the ground not by biome, but by the type of vertex it is (material), but it does not work quite well

Is there any way to get the byte of a certain vertex with raycast?

This is an image of the progress:
Biome Vegetation

Questions

I have two questions.

  1. How and where can I add the code to smooth the terrain.
  2. Does this support underground generation for example ores.

Is the overhang right above slopes expected?

image

I have really enjoyed looking through this project, but it seems that there is an overhang that appears immediately above slopes like the image above. These overhangs look a little strange, but they also interfere with a character attempting to walk up these slopes. Is that overhang intentional?

Alternative Biome Selection

Hey just an idea, but wouldn't it be better to pick a biome by generating 3 sets of float2 perlin or simplex noise, then you can treat those 3 noise values at every place as an rgb colour. Each biome can have a user set colour, whichever biome is closest to that colour at any given point is chosen as the biome. Due to it being perlin or simplex noise this gives quite satisfying biome blobs. But beware that some colours that the eye thinks look different, might actually be quite close in terms of distance! Hope ya have a great day!

Chunks are saved even when SAVE_GENERATED_CHUNKS is false.

First off, imo this is one of the best unity marching cubes repos that exists. It's just so damn good.

I was playing around with the FPS scene digging craters and making hills, and the edits I made stay afterwards, even if I close the editor and come back. if the seed is changed, it still keeps that chunk and it leads to that specific memorized chunk having huge holes where the neighbors are supposed to connect and it just doesnt match the surrounding chunks at all.

I read the repo and it said saved files will show up in Application.persistentDataPath+"/chunks". no chunks folder exists. I assume this is due to Save_generated_chunks being false. however, instead there's a worlds folder containing a default folder which has reg files. Im not really sure why this is, or how to make it stop.

Is this intentional?
Is there a way to tell it to clear those reg files on playmode exit?
Or, at the very least, is there a way to have it only load reg files with the same seed?

Again, this system is great and I thank you for it. So much hard work obviously went into this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.