Voxel generation

It’d have to be combined tho? 2d for creating like the basic land, and then 3d for hills/etc??

Not necessarily, though possible I don’t think I’ve ever seen anyone do it.

Biomes, such as hilly areas, deserts, etc, are typically made by taking the x and z, determining what biome in the world grid you are, and using that in a noise function.

Then just using if statements to determine what each biome is per noise.

Sample code
local biomesize = 1000
local biomex,biomez = math.floor(x/biomesize),math.floor(z/biomesize)
local biomenoise = .5+math.noise((biomex)/100,(biomez)/100,seed) -- i like to add .5 because it gives values between 0,1 (most of the time)
if biomenoise <= .1 then
   print("biome is sandy, only make sand blocks")
elseif biomenoise < .5 then
   print("regular terriain")
elseif biomnoise >= .5 then
   print("biome is hills")
end

This is how I would do it. Some people do it different by introducing different levels in the original Y calculation of math.noise.

What minecraft does(for general generation, not just for biomes) is use Octave Perlin noise.
This is a great video on it, but this uses 2D octave perlin noise.

I use flat 3D generation here for planet like structures, https://www.roblox.com/games/3698012389/Spacecraft-Pre-Alpha

1 Like

Welp, you got me started down a really deep rabbit hole… Here’s what I found :stuck_out_tongue:

There’s no reason that you can’t use both 2D noise for a heightmap and use 3D noise to determine which cells are solid and which are air. The height map can influence the 3D “density map”. This is probably the best way of making sure you have no floating islands that aren’t connected to the rest of the terrain while still allowing overhangs. At least that’s my preferred method. To get the overhangs you need to somehow offset the input coordinates to your heightmap function. I like to “twirl” them with coherent noise. Yes, this means you’ll use coherent noise to generate the coordinates that you sample coherent noise at. Weird.

Here's a Module for generating fractal (or Perlin?) noise. It's great for making more interesting terrain, with details at different scales.
local r = Random.new(os.time())

function fractalNoiseGenerator(seed, amplitude, frequency, octaves, lacunarity, persistence)
	--Generates a noise generator using cohrent noise (math.noise)
	--Uses "sensible" default values. 
	--Check out this glossary: http://libnoise.sourceforge.net/glossary/index.html
	
	local noise = math.noise
	local seed = seed or (r:NextInteger(-10e3, 10e3) * math.pi) -- * pi because math.noise is weird at integer coordinates, and pi is irrational
	local amplitude = amplitude or 1
	local frequency = frequency or 4
	local period = 1/frequency
	local octaves = octaves or 3
	local lacunarity = lacunarity or 1.75
	local persistence = persistence or 0.8
	
	return function(x, y, z)
		local v = 0
		local a = amplitude
		local f = frequency
		
		for o = 1, octaves do
			v = v + noise(seed + x*f, seed + y*f, seed + z*f) * a
			a = a * persistence
			f = f * lacunarity	
		end
		
		return v
	end
end

return fractalNoiseGenerator
Here's a script for actually generating the terrain (requires the Fractal noise thing)
local FractalNoise = require(game.ServerStorage.FractalNoise)
local heightmapNoise = FractalNoise(nil, 0.6, 2, 2, nil, nil) --These are just magic numbers
local swirlNoise = FractalNoise(nil, .3, 5, 2) --These are just magic numbers

function mapSet(map, x, y, z, value)
	map[x] = map[x] or {}
	map[x][y] = map[x][y] or {}
	map[x][y][z] = value
end

function mapGet(map, x, y, z)
	if map[x] then
		if map[x][y] then
			return map[x][y][z]
		end
	end
end

function twirlCoordinates(x, y, z, power)
	local power = power or 1
	local tX, tY, tZ = 	
		swirlNoise(x, y, z),
		swirlNoise(x+1000, y, z), --Don't want the *same* twirl on each axis
		swirlNoise(x, y+1000, z)
		
	return x + tX * power, y + tY * power, z + tZ * power
end

function heightMap(x, z)
	return heightmapNoise(x, 0, z)
end

function density(x, y, z)
	--If you twirl with power 0, you'll just get a plain heightmap
	local tX, tY, tZ = twirlCoordinates(x, y, z, 1)
	tZ = tZ / (1 + y)
	tX = tX / (1 + y)
	local densityOffset = 0.5 + heightMap(tX, tZ) - y --Add 0.5 density so that there's a guaranteed bottom layer
	return densityOffset
end

function generateTerrain(mapSize)
	local densityMap = {}
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				mapSet(densityMap, x, y, z, density(x/mapSize, y/(mapSize/2), z/mapSize))
			end
		end
	end
	
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				local d = mapGet(densityMap, x, y, z)
				if d >= 0 then
					local block = script.Block:Clone()
					block.CFrame = CFrame.new(x, y, z)
					block.Color = Color3.fromHSV(((y/mapSize)%1), .75, 1 - (y/mapSize))
					block.Parent = game.Workspace
				end
			end
		end
	end
end

generateTerrain(64)
Here's a simplified terrain generation script, to see how 3D noise can be used to make a "height map".
local FractalNoise = require(game.ServerStorage.FractalNoise)
local heightmapNoise = FractalNoise(nil, 0.6, 2, 2, nil, nil) --These are just magic numbers

function mapSet(map, x, y, z, value)
	map[x] = map[x] or {}
	map[x][y] = map[x][y] or {}
	map[x][y][z] = value
end

function mapGet(map, x, y, z)
	if map[x] then
		if map[x][y] then
			return map[x][y][z]
		end
	end
end

function heightMap(x, z)
	return heightmapNoise(x, 0, z)
end

function density(x, y, z)
	local densityOffset = 0.5 + heightMap(x, z) - y --Add 0.5 density so that there's a guaranteed bottom layer
	return densityOffset
end

function generateTerrain(mapSize)
	local densityMap = {}
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				mapSet(densityMap, x, y, z, density(x/mapSize, y/(mapSize/2), z/mapSize))
			end
		end
	end
	
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				local d = mapGet(densityMap, x, y, z)
				if d >= 0 then
					local block = script.Block:Clone()
					block.CFrame = CFrame.new(x, y, z)
					block.Color = Color3.fromHSV(((y/mapSize)%1), .75, 1 - (y/mapSize))
					block.Parent = game.Workspace
				end
			end
		end
	end
end

generateTerrain(64)
Here is a (huge) picture gallery of stuff I found out when playing around :P

Toothpaste series

:tooth:
Basic examples of combining height maps and twirled coordinates. Nice overhangs, no floaties.

“Fire” series

Because I picked some cool colors and the shapes look like licking flames \m/. Examples of extreme amounts of twirl (the “bases” of the “mountains” are horizontally far away from their “peaks”).

Rainbow series

:rainbow: :rainbow: :rainbow: :rainbow: :rainbow:

Experiment with twirling more at the top, and less and less towards the bottom. Extreme twirl can generate really nice caves, but reducing twirl near the bottom of the world prevents them from going too deep.

Various

This one colors blocks depending on the “density” at their position, instead of their height. I don’t have anything clever to say about this :

Here’s a 2D version of many of the same concepts. Instead of using coherent noise for the height, a simple sine curve is used. The X coordinate is still twirled, giving it overhangs. Using a sine curve instead of a noisy heightmap gives a better understanding of what exactly “twirling” the coordinates does (there are regular peaks and valleys, with consistent heights and depths. The noise is only used for “surface level” features). Also it looks like fire :fire: :fire: :fire:

Annotation%202019-08-28%20021740

Here’s a cartoony version of the same thing. The sine of the y coordinate is used for twirling the input to math.noise(), which is kind of the opposite of the other flames. Any coherent function can be used to “twirl” the coordinates. I’m really interested in what other examples of smoothly varying functions I can find.

Just a heads up you can still totally get floaties, but only if you twirl too hard. You’ll have to tune your specific parameters to your needs.
Hope this rambly post is some help, and let me know if you have questions :slight_smile:

45 Likes

My word! :scream: I’m incredibly excited to get home and try all this out! :smiley::smiley: Should def make a post in #development-resources:community-tutorials about this tho :+1:

3 Likes

I might, but I feel like there’s so much more to explore on the topic. Perhaps when I’ve seen a few more techniques to make sure it’s not just a buch of pretty pictures :stuck_out_tongue:

So just doing some tests with it.

Few questions:

  • You had two separate scripts (the second two) that did different things. I’m not entirely sure what was the difference exactly in what it was actually generating.
  • Secondly, I’m guessing you used a part 1x1x1? Is there a line where I can change it to be any size block? (preferably 4x4x4, as that’s what I’m using, but would love to test with all kinds of sizes)
  • And finally, the colours. Can you show me how you got the different colors for the generation? And how to be able to actually set it so like grass would appear on top, dirt underneath, stones, etc.?

Also, just come across this, but changing the map size causes errors, [Game script timeout] (changed from 64 to 256)

1 Like

This is because the script takes too long to run, so Roblox stops the script because it thinks you might have made an infinite loop (it’s better than crashing Studio I guess). You’ll have to make the script yield in between different layers (i.e. inside the for loops) to prevent this from happening.

Color3 has a few different constructors, here I used Color3.fromHSV(hue, saturation, value) instead of the default which makes a Color3 from rgb values. Read more about HSV color space here. HSV is super nice when you want smoothly varying colors. Lerping RGB colors tends to move from e.g. yellow to gray to blue (because ((255, 255, 0) + (0, 0, 255))/2=(127, 127, 127)). If you lerp the hue of a color, it will lerp from e.g. red to yellow to orange to green to blue (IIRC), which feels much more natural. You can also play with the saturation (how POWERFUL the color is) and the value (how light [i.e. NOT BLACK] it is)

Here’s one example of choosing a hue for the blocks:

    block.Color = Color3.fromHSV(((y/mapSize)%1), .75, 1 - (y/mapSize)) 

Since y varies from 1 to mapSize , the value (lightness) varies from 1 to 0. This makes the map lighter near the top and darker towards the bottom. Same thing with the hue, it starts at ~0 (red) and moves around the color circle until it eventually reaches 1 (red again) after having moved through all the hues. This gives a rainbow effect.

Here’s another effect:

    block.Color = Color3.fromHSV( 
        ( (y*0.1) / mapSize ) %1, .75, 1
    ) 

Once again the hue changes with the y coordinate, but this times the coordinate is scaled by 0.1, meaning the hue changes less fast. Overall, it’ll move 1/10th around the color circle, which is probably in the orange or yellow region. So it should have a “firey” look to it. In the flames examples I believe I used the density to determine the hue, giving the terrain a reddish color at the edges and a more yellowish color deeper into the terrain where it’s even denser. All of the arguments to fromHSV should be between 0 and 1, so if you see (something)%1 that’s just to make sure that something loops around.

Sure, change the relevant part of the script to this:

local block = script.Block:Clone() 
block.Size = Vector3.new(1, 1, 1) * blockSize
block.CFrame = CFrame.new(x * blockSize, y * blockSize, z * blockSize) 
block.Color = Color3.fromHSV(((y/mapSize)%1), .75, 1 - (y/mapSize)) 
block.Parent = game.Workspace

And also add a blockSize constant somewhere near the top of the script. Notice that the coordinates aren’t scaled when sampling the density function, which is handy.

The first one is full- on 2D coherent-noise height map + 3D coherent-noise swirling. The second one is just a 2D coherent-noise height map. In both cases, the 2D height map doesn’t directly say “this is the height of the terrain at any given point”, it’s merely a suggestion. The density function uses the 2D height map to figure out “at which height the density should be > 0”, so in the second case where this isn’t modified at all, we just get a simple height map. The second script is equivalent to just generating a 2D height map and creating blocks from the height that the heightmap tells to the bottom of the world. The whole point of the second script is to show how you can use a 2D height map alongside a fully 3D density function.

1 Like

I’m off the PC atm, but just to follow up. The yield in the for loops, that can just be a wait() ye?

And one thing I just thought about, is this is generating the entire area, while my original code from the question only generated the height map. Problem with this is it’s generating blocks that the player can’t see, so they aren’t necessary. So is there a way to incorporate my original code of creating the height map into this? Or a way to just not generate blocks if they are out of sight?

ye

For any cell that is above the density threshold, you can check if it has one or more neighbors who are below the threshold. If that is the case, then it’s a surface cell.

Here’s a 2D image showing what I mean. Each number is the number of empty neighbors a cell has. Blue cells are empty, dark orange are solid, and yellow cells are solid but shouldn’t be built (with parts), because they’re not visible from any empty blocks.

image

One optimization with this is only ever checking cells that are below a certain threshold. E.g. if the surface threshold is density >= 0, then you can also choose to only generate blocks in cells where density <= 0.25. (0.25 is magic number that would need to be tuned for your specific case)

Here’s a side- view illustration of what I mean. Blue is empty cells, brown is solid cells. Yellow is cells that are solid but shouldn’t be built because they’re not visible from any empty cells.

Generating everything where `density > 0´

Generating everything where lower_threshold > density > 0

You’ll have to tune your thresholds so that there’s never any gaps. This means the “band” of blocks will end up being between 1 and a few blocks thick everywhere. This is where the “check if neighbors are empty” method comes in, allowing you to make sure the terrain “skin” is always only 1 block thick. By only counting neighbors for cells in the orange band, you avoid doing a lot of checks.

As an aside, this is also why I decided to first calculate the density for the whole map and then constructing blocks where the density is > 0. It’s often useful to be able to get the density at a given point without having to calculate it. Looking it up in a density map is faster than calculating it every time. I didn’t actually do that with the scripts in my first reply, but that’s the explanation for why I did it the way I did.

The neighbor checking thing means doing a lot more calculations, which means terrain generation will be slower up front. But you’ll probably save some frames-per-second when the terrain is done generating and players are just running around doing whatever.

1 Like

When I set ‘d’ (guessing that’s density?) to > 0 instead of >= 0, it still generated the blocks below other blocks

function generateTerrain(mapSize)
	local densityMap = {}
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				mapSet(densityMap, x, y, z, density(x/mapSize, y/(mapSize/2), z/mapSize))
			end
		end
	end
	
	for x = 1, mapSize do
		for y = 1, mapSize/2 do
			for z = 1, mapSize do
				local d = mapGet(densityMap, x, y, z)
				if d > 0 then
					local block = script.Block:Clone()
					block.CFrame = CFrame.new(x * 4, y * 4, z * 4)
					block.BrickColor = BrickColor.Green()
					block.Parent = game.Workspace
				end
			end
		end
		wait()
	end
end

Not sure what ‘lower_threshold’ actually equals? And another question that’s popped up. Increasing sizes. Atm it seems like a constant ‘size’ in terms of height. Is there a way I can add a variable or something to make it so some areas are really flat, while others are quite hilly/high

I meant something along these lines:

local d = mapGet(densityMap, x, y, z)
if d  0 and d <= lower_threshold then
	--generate block
end

Yes, you can scale/multiply the “height” that the heightmap function outputs at a given coordinate by some factor that you get by sampling a noise function at the same coordinates. This noise function would then describe the “hillyness” at any coordinate, meaning high values of the noise function are more hilly while values near 0 are more flat.

A code example might look like

function heightMap(x, z)
	return heightmapNoise(x, 0, z) * hillynessNoise(x, 0, z)
end

What is lower_threshold tho???

It’s a level of density. If the density at a point is > 0, then we generate a block. UNLESS it’s above this lower_threshold. Which, thinking about it makes it sound like a pretty confusing variable name. You might want to come up with something better :stuck_out_tongue: This means where before our terrain was filled in all the way through, now it will only be filled in when the density is between 0 and this threshold. This lets us avoid generating unnecessary blocks that we later have to check with the “number of neighbors” method.

That makes sense XD Few tweaking of things and I managed to also figure out how to make dirt go on blocks below green ones (doesn’t always work, but I guess it’s close enough :smiley: ) :+1:

If you know of a way to actually make blocks below the green ones brown 100% then that would be amazing

Changed the parts to be models too :smiley:


Can see that the grass parts still spawn below other grass parts tho :confused:

if d > 0 and d < 0.04 then
					local block
					if d > 0.0175 then
						block = script.Dirt:Clone()
					else
						block = script.Grass:Clone()
					end
					
					block:SetPrimaryPartCFrame(CFrame.new(x * 4, y * 4, z * 4))
					block.Parent = workspace
				end

And what about getting different heights? Ways to see how high the actual blocks are, allowing change to color based on height, or overhangs? Instead of just being hills

And is there a faster way to generate the land? If I have it so the player doesnt spawn till all the land has been created then it takes forever? Would I be best to say ‘create’ the land via the code, but not insert the blocks unless the player is within a certain radious of the blocks?

‘hillnessNoise’ would be what exactly? just math.noise??

Yeah, the y coordinate is the height.

for x = 1, mapSize do
	for y = 1, mapSize/2 do
		for z = 1, mapSize do
                local height = y
		end
	end
end

You can use this if you want all horizontal layers to be a specific color/block type.

If you want to see how “deep” into the ground a block is, accounting for both horizontal and vertical depth, I can’t think of a really good way of doing it. Points where the density function is higher will usually be deeper, but there’s no obvious way to see how far away a block is from the nearest air block. A simple flood fill might work, but will take a while to run for every block.

You’re not getting any overhangs because you aren’t twirling the coordinates enough. Here’s the density function from the original script I posted:

function density(x, y, z)
	--If you twirl with power 0, you'll just get a plain heightmap
	local tX, tY, tZ = twirlCoordinates(x, y, z, 1)
	tZ = tZ / (1 + y)
	tX = tX / (1 + y)
	local densityOffset = 0.5 + heightMap(tX, tZ) - y --Add 0.5 density so that there's a guaranteed bottom layer
	return densityOffset
end

You might want to increase the “twirl power” if you haven’t tried that yet.

You could make your own “chunk” system a la Minecraft. Or check out StreamingEnabled to see if that’s an option for you.

I’m not sure, but with a chunk system you can avoid having to generate the whole world at a time, instead generating it when it becomes relevant (e.g. when a player moves closer to it).

1 Like

ik its like a year later so this may not be so relevant, but how would i make it so the terrain is mostly around a specific height then occasionally there would be a huge mountain?

1 Like

Check out this page, especially under “Redistribution”.

You can get a similar result by multiplying the height value at a given point by the “height value” of a different noise function, assuming the second one is between 0 and 1.

6 Likes

ik this is an old thread but you could do a system like minecraft where blocks turn into dirt if they are under something or grass if they arent then just run it at like 1000x times speed when game first starts

Something else that made voxel generation run much faster for me is checking the surrounding blocks for a transparent block e.g. air, glass and if they r there it renders the block, otherwise it’s just kept in a table. When a block is broken it should update the surrounding blocks to see if they should be rendered.

This method increased my frame rate by tons.

1 Like