0

I'm working on a diamond-square heightmap generator and I've been stuck on a certain part for a while now.

I'm having trouble determining which tiles I need to run a square() function on and which tiles I need to run a diamond() function on.

I took a look at this guide: http://www.playfuljs.com/realistic-terrain-in-130-lines/ and I took their for loop they're using as an example, but it didn't seem to work at all.

The preferred language for the answer is Lua (or just kindly point me in the right direction). I just need someone to tell me what I need to do to get a for loop that works for both diamond and square functions.

Peter O.
  • 32,158
  • 14
  • 82
  • 96

1 Answers1

0
-- height constraints
local min_height = 10
local max_height = 100

-- the grid
local K = 4
local M = 2^K       -- the field is cyclic integer grid  0 <= x,y < M  (x=M is the same point as x=0)
local heights = {}  -- min_height <= heights[x][y] <= max_height
for x = 0, M-1 do
   heights[x] = {}
end

-- set corners height (all 4 corners are the same point because of cyclic field)
heights[0][0] = (min_height + max_height) / 2

local delta_height = (max_height - min_height) * 0.264
local side = M
local sqrt2 = 2^0.5

repeat
   local dbl_side = side
   side = side/2
   -- squares
   for x = side, M, dbl_side do
      for y = side, M, dbl_side do
         local sum =
              heights[(x-side)%M][(y-side)%M]
            + heights[(x-side)%M][(y+side)%M]
            + heights[(x+side)%M][(y-side)%M]
            + heights[(x+side)%M][(y+side)%M]
         heights[x][y] = sum/4 + (2*math.random()-1) * delta_height
      end
   end
   delta_height = delta_height / sqrt2
   -- diamonds
   for x = 0, M-1, side do
      for y = (x+side) % dbl_side, M-1, dbl_side do
         local sum =
              heights[(x-side)%M][y]
            + heights[x][(y-side)%M]
            + heights[x][(y+side)%M]
            + heights[(x+side)%M][y]
         heights[x][y] = sum/4 + (2*math.random()-1) * delta_height
      end
   end
   delta_height = delta_height / sqrt2
until side == 1

-- draw field
for x = 0, M-1 do
   local s = ''
   for y = 0, M-1 do
      s = s..'  '..tostring(math.floor(heights[x][y]))
   end
   print(s)
end
Egor Skriptunoff
  • 906
  • 1
  • 8
  • 23