Procedural Terrain and Collision¶
KangEngine can generate tiled height-field terrain in Python, render it as one continuous mesh, and use the same height samples for PhysX collision.
The complete example mixes stairs, slopes, waves, random ground, and discrete obstacles:
python ./python/examples/view_procedural_terrain.py
It also drops dynamic spheres and boxes onto the terrain to verify that the
rendered surface and PhysX heightfield agree. Press R to reset the bodies.
Complete source: view_procedural_terrain.py
1"""Generate a procedural terrain height field in Python and render it as mesh."""
2
3from __future__ import annotations
4
5import argparse
6
7import numpy as np
8
9import kangengine as ke
10from kangengine.utils._example_args import render_example_parser
11from kangengine import imgui, keys, terrain
12
13
14TERRAIN_TYPES = ("stairs", "slope", "pyramid", "wave", "random", "obstacles")
15
16
17class ProceduralTerrainViewer(ke.App):
18 def __init__(
19 self,
20 *,
21 terrain_type: str = "mixed",
22 rows: int = 3,
23 cols: int = 3,
24 tile_width: int = 96,
25 tile_length: int = 96,
26 horizontal_scale: float = 0.05,
27 vertical_scale: float = 0.005,
28 backend: str = "cpp",
29 seed: int = 7,
30 collision_test: bool = True,
31 test_bodies_per_type: int = 10,
32 ):
33 super().__init__()
34 self.terrain_type = terrain_type
35 self.rows = int(rows)
36 self.cols = int(cols)
37 self.tile_width = int(tile_width)
38 self.tile_length = int(tile_length)
39 self.horizontal_scale = float(horizontal_scale)
40 self.vertical_scale = float(vertical_scale)
41 self.backend = backend
42 self.seed = int(seed)
43 self.collision_test = bool(collision_test)
44 self.test_bodies_per_type = int(test_bodies_per_type)
45
46 def setup(self):
47 self.standard_materials = self.create_standard_materials()
48 self.set_light_direction(ke.Vec3(0.35, -0.82, 0.45))
49 self.set_light_intensity(1.25)
50 self.set_light_ambient(ke.Vec3(0.32, 0.32, 0.32))
51
52 self.rng = np.random.default_rng(self.seed)
53 self.grid = terrain.TerrainGrid(
54 self.rows,
55 self.cols,
56 self.tile_width,
57 self.tile_length,
58 horizontal_scale=self.horizontal_scale,
59 vertical_scale=self.vertical_scale,
60 )
61 self.grid.fill(self._generate_tile)
62 self.mesh = self.grid.to_mesh(up_axis=ke.UpAxis.Y, backend=self.backend)
63
64 self.material = self.create_phong_material(
65 ambient=ke.Vec3(0.10, 0.12, 0.10),
66 diffuse=ke.Vec3(0.27, 0.28, 0.27),
67 specular=ke.Vec3(0.06, 0.06, 0.06),
68 shininess=12.0,
69 )
70 self.view = self.scene.add_mesh("/procedural_terrain", self.mesh, self.material)
71 self.view.set_double_sided(False)
72
73 self.physics = None
74 self.collision_added = False
75 self.test_bodies = []
76 if self.collision_test:
77 physics_config = ke.physics.PhysicsConfig.y_up()
78 self.physics = ke.physics.PhysicsWorld(physics_config)
79 self.timing = self.configure_timing(
80 ke.SimulationTimingConfig.from_dt(
81 physics_dt=physics_config.dt,
82 fixed_dt=physics_config.dt,
83 render_hz=60.0,
84 )
85 )
86 self.set_simulation_hotkeys_enabled(True)
87 heights = np.ascontiguousarray(self.grid.height_meters(), dtype=np.float32)
88 self.collision_added = self.physics.add_heightfield(
89 heights.reshape(-1),
90 self.grid.width,
91 self.grid.length,
92 horizontal_scale=self.horizontal_scale,
93 up_axis=ke.UpAxis.Y,
94 center=True,
95 register_as_ground=True,
96 material=ke.physics.PhysicsMaterialDesc([1.0, 1.0, 0.0]),
97 )
98 if self.collision_added:
99 self._create_collision_test_bodies()
100
101 self._setup_camera()
102 print(
103 "Procedural terrain loaded: "
104 f"type={self.terrain_type} tiles={self.rows}x{self.cols} "
105 f"grid={self.grid.width}x{self.grid.length} "
106 f"vertices={len(self.mesh.vertices)} "
107 f"triangles={len(self.mesh.indices) // 3} "
108 f"collision={'yes' if self.collision_added else 'no'} "
109 f"test_bodies={len(self.test_bodies)}"
110 )
111
112 def pre_update(self):
113 if self.was_key_pressed(keys.R):
114 self._reset_collision_test_bodies()
115
116 def fixed_update(self, fixed_dt):
117 if self.physics:
118 self.physics.step()
119
120 def pre_render(self):
121 if self.physics:
122 self._sync_collision_test_bodies()
123
124 def render(self):
125 imgui.begin("Procedural Terrain")
126 imgui.text(f"type: {self.terrain_type}")
127 imgui.text(f"tiles: {self.rows} x {self.cols}")
128 imgui.text(f"tile: {self.tile_width} x {self.tile_length}")
129 imgui.text(f"grid: {self.grid.width} x {self.grid.length}")
130 imgui.text(f"backend: {self.backend}")
131 imgui.text(f"horizontal scale: {self.horizontal_scale:.3f}")
132 imgui.text(f"vertical scale: {self.vertical_scale:.4f}")
133 imgui.text(f"vertices: {len(self.mesh.vertices):,}")
134 imgui.text(f"triangles: {len(self.mesh.indices) // 3:,}")
135 imgui.text(
136 f"collision test: {'on' if self.collision_test and self.collision_added else 'off'}"
137 )
138 imgui.text(f"test bodies: {len(self.test_bodies)}")
139 if self.test_bodies:
140 paused = self.is_simulation_paused()
141 changed, paused = imgui.checkbox("pause physics", paused)
142 if changed:
143 self.set_simulation_paused(paused)
144 imgui.text("Enter: play/pause Space: pause/step")
145 if imgui.button("reset test bodies"):
146 self._reset_collision_test_bodies()
147 imgui.end()
148
149 def _generate_tile(
150 self, t: terrain.SubTerrain, tile_row: int, tile_col: int
151 ) -> terrain.SubTerrain:
152 kind = self._tile_type(tile_row, tile_col)
153 if kind == "stairs":
154 terrain.stairs_terrain(t, step_width=0.35, step_height=0.08)
155 elif kind == "slope":
156 direction = -1.0 if (tile_row + tile_col) % 2 else 1.0
157 terrain.sloped_terrain(t, slope=direction * 0.18)
158 elif kind == "pyramid":
159 terrain.pyramid_sloped_terrain(t, slope=0.28, platform_size=1.2)
160 elif kind == "wave":
161 terrain.wave_terrain(t, num_waves=3.0, amplitude=0.35)
162 elif kind == "random":
163 terrain.random_uniform_terrain(t, -0.05, 0.05, step=0.01, rng=self.rng)
164 elif kind == "obstacles":
165 terrain.discrete_obstacles_terrain(
166 t,
167 max_height=0.25,
168 min_size=0.2,
169 max_size=0.7,
170 num_rects=80,
171 platform_size=1.0,
172 rng=self.rng,
173 )
174 else:
175 raise ValueError(f"unknown terrain type: {kind}")
176 return t
177
178 def _tile_type(self, row: int, col: int) -> str:
179 kind = self.terrain_type.lower()
180 if kind != "mixed":
181 return kind
182 return TERRAIN_TYPES[(row * self.cols + col) % len(TERRAIN_TYPES)]
183
184 def _create_collision_test_bodies(self):
185 if self.physics is None or not self.collision_added:
186 return
187
188 count = max(0, self.test_bodies_per_type)
189 if count == 0:
190 return
191
192 sphere_material = self.create_phong_material(
193 ambient=ke.Vec3(0.12, 0.06, 0.03),
194 diffuse=ke.Vec3(0.95, 0.32, 0.08),
195 specular=ke.Vec3(0.08, 0.08, 0.08),
196 shininess=20.0,
197 )
198 box_material = self.create_phong_material(
199 ambient=ke.Vec3(0.03, 0.07, 0.12),
200 diffuse=ke.Vec3(0.12, 0.42, 0.95),
201 specular=ke.Vec3(0.08, 0.08, 0.08),
202 shininess=20.0,
203 )
204
205 radius = max(0.08, self.horizontal_scale * 5.0)
206 half = max(0.08, self.horizontal_scale * 4.0)
207 sphere_mesh_data = ke.geometry.create_sphere_data(radius, 20, 10)
208 box_mesh_data = ke.geometry.create_box_data(half * 2.0, half * 2.0, half * 2.0)
209
210 for index in range(count):
211 pos = self._random_spawn_position(index, count * 2)
212 actor = self.physics.create_dynamic_sphere(
213 radius,
214 [pos.x, pos.y, pos.z],
215 [0.0, 0.0, 0.0, 1.0],
216 1.0,
217 )
218 view = self.scene.add_mesh(
219 f"/collision_test/sphere_{index}", sphere_mesh_data, sphere_material
220 )
221 self.test_bodies.append(("sphere", actor, view, radius))
222
223 for index in range(count):
224 pos = self._random_spawn_position(count + index, count * 2)
225 actor = self.physics.create_dynamic_box(
226 [half, half, half],
227 [pos.x, pos.y, pos.z],
228 [0.0, 0.0, 0.0, 1.0],
229 1.0,
230 )
231 view = self.scene.add_mesh(
232 f"/collision_test/box_{index}", box_mesh_data, box_material
233 )
234 self.test_bodies.append(("box", actor, view, half))
235
236 self._sync_collision_test_bodies()
237
238 def _random_spawn_position(self, index: int, total: int):
239 width = (self.grid.length - 1) * self.horizontal_scale
240 length = (self.grid.width - 1) * self.horizontal_scale
241 margin = max(width, length) * 0.12
242 x = self.rng.uniform(-width * 0.5 + margin, width * 0.5 - margin)
243 z = self.rng.uniform(-length * 0.5 + margin, length * 0.5 - margin)
244 max_height = float(np.max(self.grid.height_meters()))
245 drop_span = max(2.0, max(width, length) * 0.25)
246 y = max_height + 1.0 + drop_span * (0.35 + 0.65 * index / max(total - 1, 1))
247 return ke.Vec3(float(x), float(y), float(z))
248
249 def _reset_collision_test_bodies(self):
250 total = len(self.test_bodies)
251 for index, (_kind, actor, _view, _size) in enumerate(self.test_bodies):
252 pos = self._random_spawn_position(index, total)
253 actor.set_root_state(
254 [pos.x, pos.y, pos.z],
255 [0.0, 0.0, 0.0, 1.0],
256 [0.0, 0.0, 0.0],
257 [0.0, 0.0, 0.0],
258 )
259 self._sync_collision_test_bodies()
260
261 def _sync_collision_test_bodies(self):
262 for _kind, actor, view, _size in self.test_bodies:
263 pos = actor.get_root_position()
264 rot = actor.get_root_quat_xyzw()
265 view.prim.set_local_translation(
266 ke.Vec3(float(pos[0]), float(pos[1]), float(pos[2]))
267 )
268 view.prim.set_local_quat_wxyz(
269 ke.Quat(float(rot[3]), float(rot[0]), float(rot[1]), float(rot[2]))
270 )
271
272 def _setup_camera(self):
273 camera = self.get_camera()
274 camera.set_near_plane(0.02)
275 camera.set_far_plane(1000.0)
276 camera.set_fov(55.0)
277 radius = max(self.grid.width, self.grid.length) * self.horizontal_scale
278 target = ke.Vec3(0.0, 0.0, 0.0)
279 camera.set_target_pos(target)
280 camera.set_camera_pos(
281 target + ke.Vec3(radius * 0.45, radius * 0.55, radius * 0.85)
282 )
283 self.set_camera_move_speed(max(1.0, radius * 0.35))
284
285
286def build_parser() -> argparse.ArgumentParser:
287 parser = render_example_parser(description="View Python-generated terrain.")
288 parser.add_argument(
289 "--type",
290 default="mixed",
291 choices=("mixed", *TERRAIN_TYPES),
292 )
293 parser.add_argument("--rows", type=int, default=3)
294 parser.add_argument("--cols", type=int, default=3)
295 parser.add_argument("--tile-width", type=int, default=96)
296 parser.add_argument("--tile-length", type=int, default=96)
297 parser.add_argument("--horizontal-scale", type=float, default=0.05)
298 parser.add_argument("--vertical-scale", type=float, default=0.005)
299 parser.add_argument("--backend", choices=("cpp", "python"), default="cpp")
300 parser.add_argument("--seed", type=int, default=7)
301 parser.add_argument(
302 "--no-collision-test",
303 action="store_true",
304 help="Disable both PhysX heightfield collision and falling test bodies.",
305 )
306 parser.add_argument("--test-bodies-per-type", type=int, default=10)
307 parser.add_argument("--window-width", type=int, default=1600)
308 parser.add_argument("--window-height", type=int, default=1000)
309 return parser
310
311
312def main():
313 args = build_parser().parse_args()
314 app = ProceduralTerrainViewer(
315 terrain_type=args.type,
316 rows=args.rows,
317 cols=args.cols,
318 tile_width=args.tile_width,
319 tile_length=args.tile_length,
320 horizontal_scale=args.horizontal_scale,
321 vertical_scale=args.vertical_scale,
322 backend=args.backend,
323 seed=args.seed,
324 collision_test=not args.no_collision_test,
325 test_bodies_per_type=args.test_bodies_per_type,
326 )
327 app.initialize(
328 args.window_width, args.window_height, False, ke.UpAxis.Y,
329 renderer=args.renderer,
330 )
331 app.start()
332
333
334if __name__ == "__main__":
335 main()

Generate the height field¶
TerrainGrid joins adjacent tiles with a shared edge, producing one continuous
height field rather than separate mesh islands.
import numpy as np
import kangengine as ke
rng = np.random.default_rng(7)
terrain_types = ("stairs", "slope", "wave", "random", "obstacles")
grid = ke.terrain.TerrainGrid(
rows=3,
cols=3,
tile_width=96,
tile_length=96,
horizontal_scale=0.05,
vertical_scale=0.005,
)
def generate_tile(tile, row, col):
kind = terrain_types[(row * grid.cols + col) % len(terrain_types)]
if kind == "stairs":
ke.terrain.stairs_terrain(tile, step_width=0.35, step_height=0.08)
elif kind == "slope":
ke.terrain.sloped_terrain(tile, slope=0.18)
elif kind == "wave":
ke.terrain.wave_terrain(tile, num_waves=3.0, amplitude=0.35)
elif kind == "random":
ke.terrain.random_uniform_terrain(
tile, -0.05, 0.05, step=0.01, rng=rng
)
else:
ke.terrain.discrete_obstacles_terrain(
tile,
max_height=0.25,
min_size=0.2,
max_size=0.7,
num_rects=80,
platform_size=1.0,
rng=rng,
)
return tile
grid.fill(generate_tile)
horizontal_scale is the distance between samples. vertical_scale converts
the integer height_field_raw values into meters.
Render the terrain¶
Convert the grid to MeshData and add it through the normal scene API:
mesh = grid.to_mesh(up_axis=ke.UpAxis.Y, backend="cpp")
material = self.create_standard_materials().common
terrain_view = self.scene.add_mesh(
"/procedural_terrain",
mesh,
material,
)
The C++ mesh backend is the normal path. Use backend="python" when
prototyping or comparing terrain conversion behavior.
Add PhysX collision¶
Create collision from the same meter-valued height array:
physics = ke.physics.PhysicsWorld(ke.physics.PhysicsConfig.y_up())
heights = np.ascontiguousarray(grid.height_meters(), dtype=np.float32)
collision_added = physics.add_heightfield(
heights.reshape(-1),
grid.width,
grid.length,
horizontal_scale=grid.horizontal_scale,
up_axis=ke.UpAxis.Y,
center=True,
register_as_ground=True,
material=ke.physics.PhysicsMaterialDesc([1.0, 1.0, 0.0]),
)
Keep these values identical for rendering and collision:
height samples from
grid.height_meters();horizontal_scale;up_axis;the
centersetting.
Changing one side independently makes the collision surface appear shifted, rotated, or scaled relative to the rendered mesh.
Step the PhysicsWorld each frame and copy dynamic actor poses to their
RenderablePrimView objects. The complete example implements creation, reset,
and synchronization for both spheres and boxes.
Terrain generators¶
The public generators modify a SubTerrain in place and can be composed:
random_uniform_terrain()sloped_terrain()pyramid_sloped_terrain()stairs_terrain()wave_terrain()discrete_obstacles_terrain()
Use a single SubTerrain for one patch or a TerrainGrid for tiled training
and visualization environments.
GPU collision and mesh height queries¶
Use TerrainMesh for GPU triangle-mesh collision and height queries.
It converts a height field to a Z-up mesh:
import kangengine as ke
field: ke.terrain.SubTerrain = ke.terrain.SubTerrain(
width=161, length=161, horizontal_scale=0.05, vertical_scale=0.005)
ke.terrain.random_uniform_terrain(field, min_height=-0.05, max_height=0.05)
asset: ke.terrain.TerrainMesh = ke.terrain.TerrainMesh.from_heightfield(field)
config: ke.physics.PhysicsConfig = ke.physics.PhysicsConfig.z_up()
config.enable_gpu = True
world: ke.physics.PhysicsWorld = ke.physics.PhysicsWorld(config)
instance: ke.terrain.TerrainInstance = asset.create(world, position=(0, 0, 0))
# Optional visualization: instance.add_visual(app.scene, "/terrain", material=material)
# Optional CPU/CUDA float32 tensor query: heights = instance.sample_height(positions)
instance.remove() # Before closing the viewer or physics world.
Install kangengine[terrain] to use sample_height(). It accepts CPU or CUDA
float32 position tensors and returns heights on the same device; misses return
-inf. Pass a render material to add_visual() and a physics material to
create().
PhysicsWorld.add_heightfield() uses native heightfield collision. PhysX 5.8.0
has a GPU sphere-heightfield boundary-contact error. Use triangle-mesh
collision for GPU terrain where boundary contacts are possible.
Cast diagonal rays from a robot root¶
Use raycast() when rays should start at the robot root and spread toward the
terrain. Unlike a vertical height scan at fixed XY positions, this pattern can
hit stair risers, and its footprint on level ground grows with the root height.
The interactive example creates a static stair mesh and draws an 11 by 11 fan. Move the root-height and heading sliders to inspect the hit positions:
python python/examples/terrain/diagonal_raycast.py
Cyan lines hit the terrain, orange lines miss, and yellow points mark hits and
the root. The example requires kangengine[terrain] and uses CPU queries.
Build a local fan, rotate it around Z by the robot heading, and cast it against the same mesh used for rendering and collision:
import torch
import kangengine as ke
asset: ke.terrain.TerrainMesh = ke.terrain.pyramid_stairs_mesh()
grid = torch.linspace(-1.0, 1.0, 11, dtype=torch.float32)
x, y = torch.meshgrid(grid, grid, indexing="ij")
local_directions = torch.stack((x, y, -torch.ones_like(x)), dim=-1)
# All rays share the root origin; only the directions follow its heading.
root = torch.tensor([-2.5, 0.0, 1.2], dtype=torch.float32)
heading = torch.tensor(0.3)
c, s = heading.cos(), heading.sin()
rotation = torch.tensor([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
directions = local_directions @ rotation.T
hits, distances = asset.raycast(
ray_starts=root, ray_directions=directions, max_distance=6.0
)
valid = torch.isfinite(distances)
relative_heights = hits[..., 2] - root[2]
ray_starts and ray_directions are float32 tensors on the same CPU or CUDA
device, with shape [..., 3]. Their leading dimensions broadcast, so one root
position can serve an entire fan. Directions are normalized internally;
max_distance and returned distances are in meters. For the example above,
hits has shape [11, 11, 3] and distances has shape [11, 11], on the input
device.
Misses, including zero-length directions, return +inf for both positions and
distances. Use the valid mask before rendering or passing heights to a policy;
choose the policy’s missing-height value explicitly. sample_height() keeps
its vertical-query behavior and returns -inf on misses.
TerrainMesh.raycast() uses mesh coordinates. For a translated scene instance,
use TerrainInstance.raycast() with world-space starts and directions; its hit
positions are also in world space. These queries cover the selected static
mesh, not dynamic actors in the physics world.
Place terrain in separate environments¶
Use ke.asset.rigid_from_terrain_mesh() to reuse a generated TerrainMesh
with GridCloner.add_rigid(..., kinematic=True). Each environment then has an
independent rigid pose while sharing the source geometry. See
Multi-Environment Simulation
for the stair batch example and collision constraints, and
Rigid Bodies for registration, resets, and visuals.
Try the interactive stair raycast example¶
Run from the repository root; no external asset files are needed:
python python/examples/asset/rigid_asset.py
With OBJ_PATHS = (), the example creates procedural stairs with step heights
of 0.1 and 0.18 meters. Change environment 1’s height, yaw, and pitch with the
sliders while environment 0 stays fixed. Cyan lines show rays; red points mark
surface hits.

Set OBJ_PATHS to two OBJ filenames to use your own geometry. Prepare meter-scale,
Z-up meshes with their MTL files and textures. They use kinematic triangle-mesh
collision. Ray queries require kangengine[terrain].