bl_info = {
"name": "GPU Terrain Generator",
"author": "Bard",
"version": (1, 0, 0),
"blender": (4, 4, 0),
"location": "View3D > Sidebar > My Addon",
"description": "Procedural terrain generation using compute shaders.",
"category": "Object",
}
import bpy
import gpu
from mathutils import Matrix
from gpu_extras.batch import batch_for_shader
import time
import random
class GPUPTerrainGeneratorProperties(bpy.types.PropertyGroup):
terrain_size: bpy.props.IntProperty(
name="Terrain Size",
description="Size of the terrain texture (power of 2)",
default=128,
min=64,
max=2048,
update=lambda self, context: generate_terrain(context),
)
seed: bpy.props.IntProperty(
name="Seed",
description="Random seed for terrain generation",
default=1,
update=lambda self, context: generate_terrain(context),
)
height_scale: bpy.props.FloatProperty(
name="Height Scale",
description="Overall height multiplier",
default=1.0,
min=0.0,
max=10.0,
update=lambda self, context: generate_terrain(context),
)
# Global variables (to hold resources)
texture = None
compute_shader = None
shader = None
batch = None
start_time = None
properties = None # To store the property group
def create_texture(size):
return gpu.types.GPUTexture((size, size), format='RGBA32F')
def create_compute_shader(size):
compute_shader_info = gpu.types.GPUShaderCreateInfo()
compute_shader_info.image(0, 'RGBA32F', "FLOAT_2D", "img_output", qualifiers={"WRITE"})
compute_shader_info.push_constant('FLOAT', "time")
compute_shader_info.push_constant('INT', "seed")
compute_shader_info.push_constant('FLOAT', "height_scale")
compute_shader_info.local_group_size(8, 8) # Adjust based on your needs
compute_shader_info.compute_source(f"""
#version 430
layout(local_size_x = 8, local_size_y = 8) in;
layout(rgba32f, binding = 0) uniform image2D img_output;
uniform float time;
uniform int seed;
uniform float height_scale;
// Simple noise function (you can replace this with something better)
float noise(ivec2 pos, int seed) {{
uint hash = uint(seed);
hash = (hash + uint(pos.x)) * 0x45d9f3b;
hash = (hash + uint(pos.y)) * 0x45d9f3b;
hash = hash * 0x45d9f3b;
return float(hash & 0x7fffffff) / float(0x7fffffff);
}}
void main() {{
ivec2 pixel_coord = ivec2(gl_GlobalInvocationID.xy);
float u = float(pixel_coord.x) / float({size});
float v = float(pixel_coord.y) / float({size});
//Base Height
float height = 0.25;
// Add some noise
height += noise(pixel_coord, seed) * 0.5;
height += noise(pixel_coord * 2, seed * 2) * 0.25;
height += noise(pixel_coord * 4, seed * 4) * 0.125;
height *= height_scale;
vec4 pixel = vec4(height, height, height, 1.0); // Greyscale heightmap
imageStore(img_output, pixel_coord, pixel);
}}
""")
try:
compute_shader = gpu.shader.create_from_info(compute_shader_info)
except Exception as e:
print(f"Error creating compute shader: {e}")
return None
return compute_shader
def create_shader():
vert_out = gpu.types.GPUStageInterfaceInfo("my_interface")
vert_out.smooth('VEC2', "uvInterp")
shader_info = gpu.types.GPUShaderCreateInfo()
shader_info.push_constant('MAT4', "viewProjectionMatrix")
shader_info.push_constant('MAT4', "modelMatrix")
shader_info.sampler(0, 'FLOAT_2D', "img_input")
shader_info.vertex_in(0, 'VEC2', "position")
shader_info.vertex_in(1, 'VEC2', "uv")
shader_info.vertex_out(vert_out)
shader_info.fragment_out(0, 'VEC4', "FragColor")
shader_info.vertex_source(
"""
void main()
{
uvInterp = uv;
gl_Position = viewProjectionMatrix * modelMatrix * vec4(position, 0.0, 1.0);
}
"""
)
shader_info.fragment_source(
"""
void main()
{
FragColor = texture(img_input, uvInterp);
}
"""
)
try:
shader = gpu.shader.create_from_info(shader_info)
except Exception as e:
print(f"Error creating shader: {e}")
return None
return shader
def create_batch(shader):
return batch_for_shader(
shader, 'TRI_FAN',
{
"position": ((-1, -1), (1, -1), (1, 1), (-1, 1)),
"uv": ((0, 0), (1, 0), (1, 1), (0, 1)),
},
)
def generate_terrain(context):
global texture, compute_shader, properties
if compute_shader is None:
print("Compute shader not initialized.")
return
size = properties.terrain_size
texture = create_texture(size)
compute_shader.image('img_output', texture)
compute_shader.uniform_int("seed", properties.seed)
compute_shader.uniform_float("height_scale", properties.height_scale)
gpu.compute.dispatch(compute_shader, size // 8, size // 8, 1) # divide size by local group size
def draw():
global shader, batch, texture, start_time, properties
if shader is None or batch is None or texture is None:
return
shader.uniform_float("modelMatrix", Matrix.Translation((0, 0, 0)) @ Matrix.Scale(1, 1, 1)) # Scale Z to 1 to avoid the terrain becoming invisible
shader.uniform_float("viewProjectionMatrix", bpy.context.region_data.perspective_matrix)
shader.uniform_sampler("img_input", texture)
batch.draw(shader)
def draw_callback():
draw()
return
def drawTimer():
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
area.tag_redraw()
return 1.0 / 60.0
def initialize():
global texture, compute_shader, shader, batch, start_time
size = bpy.context.scene.GPUPTerrainGeneratorProperties.terrain_size
texture = create_texture(size)
compute_shader = create_compute_shader(size)
shader = create_shader()
if shader:
batch = create_batch(shader)
start_time = time.time()
if compute_shader is None:
print("Compute shader is not supported or failed to compile. Terrain generation will not work.")
return False
return True
def clear():
global texture, compute_shader, shader, batch
if texture:
texture.free()
texture = None
if compute_shader:
gpu.shader.delete(compute_shader)
compute_shader = None
if shader:
gpu.shader.delete(shader)
shader = None
batch = None
class GPU_TERRAIN_GENERATOR_PT_panel(bpy.types.Panel):
bl_label = "GPU Terrain Generator"
bl_idname = "GPU_TERRAIN_GENERATOR_PT_panel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'My Addon'
def draw(self, context):
layout = self.layout
props = context.scene.GPUPTerrainGeneratorProperties
layout.prop(props, "terrain_size")
layout.prop(props, "seed")
layout.prop(props, "height_scale")
if compute_shader is None:
layout.label(text="Compute shader failed to initialize!", icon="ERROR")
def register():
global properties
bpy.utils.register_class(GPUPTerrainGeneratorProperties)
bpy.types.Scene.GPUPTerrainGeneratorProperties = bpy.props.PointerProperty(type=GPUPTerrainGeneratorProperties)
properties = bpy.context.scene.GPUPTerrainGeneratorProperties
bpy.utils.register_class(GPU_TERRAIN_GENERATOR_PT_panel)
if initialize():
bpy.types.SpaceView3D.draw_handler_add(draw_callback, (), 'WINDOW', 'POST_VIEW')
bpy.app.timers.register(drawTimer)
else:
print("Addon initialization failed.")
def unregister():
bpy.utils.unregister_class(GPU_TERRAIN_GENERATOR_PT_panel)
bpy.utils.unregister_class(GPUPTerrainGeneratorProperties)
del bpy.types.Scene.GPUPTerrainGeneratorProperties
clear()
for handler in bpy.types.SpaceView3D.draw_handler_find('WINDOW', 'POST_VIEW'):
bpy.types.SpaceView3D.draw_handler_remove(handler)
bpy.app.timers.unregister(drawTimer)
if __name__ == "__main__":
register()
bl_info = {
"name": "GPU Terrain Generator",
"author": "Bard",
"version": (1, 0, 0),
"blender": (4, 4, 0),
"location": "View3D > Sidebar > My Addon",
"description": "Procedural terrain generation using compute shaders.",
"category": "Object",
}
import bpy
import gpu
from mathutils import Matrix
from gpu_extras.batch import batch_for_shader
import time
import random
class GPUPTerrainGeneratorProperties(bpy.types.PropertyGroup):
terrain_size: bpy.props.IntProperty(
name="Terrain Size",
description="Size of the terrain texture (power of 2)",
default=128,
min=64,
max=2048,
update=lambda self, context: generate_terrain(context),
)
seed: bpy.props.IntProperty(
name="Seed",
description="Random seed for terrain generation",
default=1,
update=lambda self, context: generate_terrain(context),
)
height_scale: bpy.props.FloatProperty(
name="Height Scale",
description="Overall height multiplier",
default=1.0,
min=0.0,
max=10.0,
update=lambda self, context: generate_terrain(context),
)
# Global variables (to hold resources)
texture = None
compute_shader = None
shader = None
batch = None
start_time = None
properties = None # To store the property group
draw_handler = None # Store draw handler to remove it properly
def create_texture(size):
return gpu.types.GPUTexture((size, size), format='RGBA32F')
def create_compute_shader(size):
compute_shader_info = gpu.types.GPUShaderCreateInfo()
compute_shader_info.image(0, 'RGBA32F', "FLOAT_2D", "img_output", qualifiers={"WRITE"})
compute_shader_info.push_constant('FLOAT', "time")
compute_shader_info.push_constant('INT', "seed")
compute_shader_info.push_constant('FLOAT', "height_scale")
compute_shader_info.local_group_size(8, 8) # Adjust based on your needs
compute_shader_info.compute_source(f"""#version 430
layout(local_size_x = 8, local_size_y = 8) in;
layout(rgba32f, binding = 0) uniform image2D img_output;
uniform float time;
uniform int seed;
uniform float height_scale;
// Simple noise function (you can replace this with something better)
float noise(ivec2 pos, int seed) {{
uint hash = uint(seed);
hash = (hash + uint(pos.x)) * 0x45d9f3b;
hash = (hash + uint(pos.y)) * 0x45d9f3b;
hash = hash * 0x45d9f3b;
return float(hash & 0x7fffffff) / float(0x7fffffff);
}}
void main() {{
ivec2 pixel_coord = ivec2(gl_GlobalInvocationID.xy);
float u = float(pixel_coord.x) / float({size});
float v = float(pixel_coord.y) / float({size});
//Base Height
float height = 0.25;
// Add some noise
height += noise(pixel_coord, seed) * 0.5;
height += noise(pixel_coord * 2, seed * 2) * 0.25;
height += noise(pixel_coord * 4, seed * 4) * 0.125;
height *= height_scale;
vec4 pixel = vec4(height, height, height, 1.0); // Greyscale heightmap
imageStore(img_output, pixel_coord, pixel);
}}
""")
try:
compute_shader = gpu.shader.create_from_info(compute_shader_info)
except Exception as e:
print(f"Error creating compute shader: {e}")
return None
return compute_shader
def create_shader():
vert_out = gpu.types.GPUStageInterfaceInfo("my_interface")
vert_out.smooth('VEC2', "uvInterp")
shader_info = gpu.types.GPUShaderCreateInfo()
shader_info.push_constant('MAT4', "viewProjectionMatrix")
shader_info.push_constant('MAT4', "modelMatrix")
shader_info.sampler(0, 'FLOAT_2D', "img_input")
shader_info.vertex_in(0, 'VEC2', "position")
shader_info.vertex_in(1, 'VEC2', "uv")
shader_info.vertex_out(vert_out)
shader_info.fragment_out(0, 'VEC4', "FragColor")
shader_info.vertex_source(
"""
void main()
{
uvInterp = uv;
gl_Position = viewProjectionMatrix * modelMatrix * vec4(position, 0.0, 1.0);
}
"""
)
shader_info.fragment_source(
"""
void main()
{
FragColor = texture(img_input, uvInterp);
}
"""
)
try:
shader = gpu.shader.create_from_info(shader_info)
except Exception as e:
print(f"Error creating shader: {e}")
return None
return shader
def create_batch(shader):
return batch_for_shader(
shader, 'TRI_FAN',
{
"position": ((-1, -1), (1, -1), (1, 1), (-1, 1)),
"uv": ((0, 0), (1, 0), (1, 1), (0, 1)),
},
)
def generate_terrain(context):
global texture, compute_shader, properties
if compute_shader is None:
print("Compute shader not initialized.")
return
size = properties.terrain_size
compute_shader.image('img_output', texture)
compute_shader.uniform_int("seed", properties.seed)
compute_shader.uniform_float("height_scale", properties.height_scale)
compute_shader.uniform_float("time", time.time() - start_time)
gpu.compute.dispatch(compute_shader, size // 8, size // 8, 1) # divide size by local group size
def draw():
global shader, batch, texture, start_time, properties
if shader is None or batch is None or texture is None:
return
shader.uniform_float("modelMatrix", Matrix.Translation((0, 0, 0)) @ Matrix.Scale(1, 1, 1)) # Scale Z to 1 to avoid the terrain becoming invisible
shader.uniform_float("viewProjectionMatrix", bpy.context.region_data.perspective_matrix)
shader.uniform_sampler("img_input", texture)
batch.draw(shader)
def draw_callback():
draw()
return
def drawTimer():
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
area.tag_redraw()
return 1.0 / 60.0
def initialize():
global texture, compute_shader, shader, batch, start_time, draw_handler
size = bpy.context.scene.GPUPTerrainGeneratorProperties.terrain_size
texture = create_texture(size)
compute_shader = create_compute_shader(size)
shader = create_shader()
if shader:
batch = create_batch(shader)
start_time = time.time()
if compute_shader is None:
print("Compute shader is not supported or failed to compile. Terrain generation will not work.")
return False
return True
def clear():
global texture, compute_shader, shader, batch, draw_handler
if draw_handler:
bpy.types.SpaceView3D.draw_handler_remove(draw_handler)
draw_handler = None
if texture:
texture.free()
texture = None
if compute_shader:
gpu.shader.delete(compute_shader)
compute_shader = None
if shader:
gpu.shader.delete(shader)
shader = None
batch = None
def update_terrain(context):
global texture, compute_shader, shader, batch
clear()
size = context.scene.GPUPTerrainGeneratorProperties.terrain_size
texture = create_texture(size)
compute_shader = create_compute_shader(size)
shader = create_shader()
if shader:
batch = create_batch(shader)
generate_terrain(context)
class GPU_TERRAIN_GENERATOR_PT_panel(bpy.types.Panel):
bl_label = "GPU Terrain Generator"
bl_idname = "GPU_TERRAIN_GENERATOR_PT_panel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'My Addon'
def draw(self, context):
layout = self.layout
props = context.scene.GPUPTerrainGeneratorProperties
layout.prop(props, "terrain_size")
layout.prop(props, "seed")
layout.prop(props, "height_scale")
if compute_shader is None:
layout.label(text="Compute shader failed to initialize!", icon="ERROR")
def register():
global properties, draw_handler
bpy.utils.register_class(GPUPTerrainGeneratorProperties)
bpy.types.Scene.GPUPTerrainGeneratorProperties = bpy.props.PointerProperty(type=GPUPTerrainGeneratorProperties)
properties = bpy.context.scene.GPUPTerrainGeneratorProperties
bpy.utils.register_class(GPU_TERRAIN_GENERATOR_PT_panel)
if initialize():
draw_handler = bpy.types.SpaceView3D.draw_handler_add(draw_callback, (), 'WINDOW', 'POST_VIEW')
bpy.app.timers.register(drawTimer)
else:
print("Addon initialization failed.")
def unregister():
bpy.utils.unregister_class(GPU_TERRAIN_GENERATOR_PT_panel)
bpy.utils.unregister_class(GPUPTerrainGeneratorProperties)
del bpy.types.Scene.GPUPTerrainGeneratorProperties
clear()
bpy.app.timers.unregister(drawTimer)
if __name__ == "__main__":
register()