Load Assets¶
For simulated MJCF, URDF, and USD robots, see Articulations.
Asset loaders parse files into data. Scene helpers or visual classes decide how that data is displayed.
OBJ with materials¶
The OBJ and FBX snippets run inside App.setup(), with
import kangengine as ke. Set obj_file or fbx_file to your asset path
and scale to its unit conversion factor (use 1.0 for meter-scale assets).
The FBX snippet also uses a material created through the App; see
Materials and Textures.
result: ke.ObjImportView = self.scene.add_obj(
path="/environment",
obj_path=obj_file,
double_sided=True,
)
result.root.set_local_scale(scale=ke.Vec3(scale, scale, scale))
Run:
python ./python/examples/view_obj_scene.py --obj-file /path/to/model.obj
Complete source: view_obj_scene.py
1"""Generic OBJ/MTL scene viewer through the component/material path.
2
3This example is the reusable version of the Crytek Sponza viewer. It uses
4``SceneContext.add_obj()`` so imported meshes flow through:
5
6OBJ/MTL -> MeshComponent + MaterialBindingComponent + RenderComponent
7 -> SceneResourceManager metadata mirrors.
8
9Typical usage:
10
11 python ./python/examples/view_obj_scene.py --obj-file=./assets/external/Scenes/foo/foo.obj
12 python ./python/examples/view_obj_scene.py --obj-file=./assets/external/Scenes/CornellBox/CornellBox-Original.obj --root-path /cornell_box --scale 1.0
13 python ./python/examples/view_obj_scene.py --preset=CRYTEK_SPONZA
14"""
15
16from __future__ import annotations
17
18import argparse
19import math
20from pathlib import Path
21
22import kangengine as ke
23from kangengine.utils._example_args import render_example_parser
24from kangengine import imgui
25
26CRYTEK_SPONZA_OBJ = (
27 Path(__file__).resolve().parents[2]
28 / "assets"
29 / "external"
30 / "Scenes"
31 / "crytek_sponza"
32 / "sponza.obj"
33)
34
35
36def scene_root_from_path(path: Path) -> str:
37 """Return a stable, scene-safe root path derived from an OBJ filename."""
38
39 safe = "".join(ch if ch.isalnum() or ch == "_" else "_" for ch in path.stem)
40 safe = safe.strip("_") or "obj_scene"
41 if safe[0].isdigit():
42 safe = f"obj_{safe}"
43 return f"/{safe}"
44
45
46def normalize_root_path(path: str | None, obj_file: Path) -> str:
47 if not path:
48 return scene_root_from_path(obj_file)
49 path = path.strip()
50 if not path:
51 return scene_root_from_path(obj_file)
52 return path if path.startswith("/") else f"/{path}"
53
54
55def parse_up_axis(value: str):
56 value = value.upper()
57 if value == "Y":
58 return ke.UpAxis.Y
59 if value == "Z":
60 return ke.UpAxis.Z
61 raise ValueError(f"unsupported up axis: {value}")
62
63
64class ObjSceneViewer(ke.App):
65 def __init__(
66 self,
67 obj_file: Path,
68 *,
69 root_path: str | None = None,
70 title: str | None = None,
71 scale: float = 1.0,
72 double_sided: bool = True,
73 show_ground: bool = False,
74 ground_size: float | None = None,
75 ground_y: float | None = None,
76 light_direction=None,
77 light_color=None,
78 light_intensity: float = 1.15,
79 light_ambient=None,
80 camera_pos=None,
81 camera_fov: float = 58.0,
82 ):
83 super().__init__()
84 obj_file = Path(obj_file)
85 self.obj_file = str(obj_file)
86 self.root_path = normalize_root_path(root_path, obj_file)
87 self.title = title or f"OBJ Scene: {obj_file.name}"
88 self.scale = float(scale)
89 self.double_sided = bool(double_sided)
90 self.show_ground = bool(show_ground)
91 self.ground_size = None if ground_size is None else float(ground_size)
92 self.ground_y = None if ground_y is None else float(ground_y)
93 self.light_direction = light_direction or ke.Vec3(0.35, -0.82, 0.45)
94 self.light_color = light_color or ke.Vec3(1.0, 0.96, 0.9)
95 self.light_intensity = float(light_intensity)
96 self.light_ambient = light_ambient or ke.Vec3(0.32, 0.32, 0.32)
97 self.camera_pos = camera_pos if camera_pos else None
98 self.camera_fov = float(camera_fov)
99
100 def setup(self):
101 self.standard_materials = self.create_standard_materials()
102 self.normal_maps_enabled = True
103 self.normal_texture_bindings = []
104 self.specular_texture_count = 0
105 self.alpha_texture_count = 0
106
107 self._configure_lighting()
108
109 self.import_view = self.scene.add_obj(
110 self.root_path,
111 self.obj_file,
112 double_sided=self.double_sided,
113 )
114 self.import_view.root.set_local_scale(
115 ke.Vec3(self.scale, self.scale, self.scale)
116 )
117
118 for view in self.import_view:
119 material = view.prim.get_material()
120 normal_map = getattr(material, "normal_map", None)
121 if normal_map is not None:
122 self.normal_texture_bindings.append((material, normal_map))
123 if getattr(material, "specular_map", None) is not None:
124 self.specular_texture_count += 1
125 if getattr(material, "alpha_map", None) is not None:
126 self.alpha_texture_count += 1
127
128 self.bounds_min, self.bounds_max = compute_obj_bounds(self.import_view.info)
129 if self.bounds_min is not None and self.bounds_max is not None:
130 self.bounds_min *= self.scale
131 self.bounds_max *= self.scale
132 self._setup_camera()
133
134 if self.show_ground:
135 self._add_ground_from_bounds()
136
137 print(
138 "OBJ scene loaded: "
139 f"{self.obj_file} root={self.root_path} "
140 f"subsets={len(self.import_view)} "
141 f"materials={self.import_view.info.material_count} "
142 f"textures={len(self.textures)} "
143 f"alpha_mapped={self.alpha_texture_count} "
144 f"normal_mapped={len(self.normal_texture_bindings)} "
145 f"specular_mapped={self.specular_texture_count}"
146 )
147
148 def render(self):
149 imgui.begin(self.title)
150 imgui.text(Path(self.obj_file).name)
151 imgui.text(f"root: {self.root_path}")
152 imgui.text(f"subsets: {len(self.import_view)}")
153 imgui.text(f"materials: {self.import_view.info.material_count}")
154 imgui.text(f"textures: {len(self.textures)}")
155 imgui.text(f"alpha maps: {self.alpha_texture_count}")
156 imgui.text(f"normal maps: {len(self.normal_texture_bindings)}")
157 imgui.text(f"specular maps: {self.specular_texture_count}")
158 changed, self.normal_maps_enabled = imgui.checkbox(
159 "normal maps",
160 self.normal_maps_enabled,
161 )
162 if changed:
163 self._apply_normal_map_toggle()
164 if self.bounds_min is not None and self.bounds_max is not None:
165 size = self.bounds_max - self.bounds_min
166 imgui.text(f"bounds: {size[0]:.2f}, {size[1]:.2f}, {size[2]:.2f}")
167 imgui.end()
168
169 def _configure_lighting(self):
170 self.set_light_direction(self.light_direction)
171 self.set_light_color(self.light_color)
172 self.set_light_intensity(self.light_intensity)
173 self.set_light_ambient(self.light_ambient)
174
175 def _setup_camera(self):
176 camera = self.get_camera()
177 camera.set_near_plane(0.05)
178 camera.set_far_plane(5000.0)
179 camera.set_fov(self.camera_fov)
180 if self.camera_pos:
181 camera.set_camera_pos(self.camera_pos)
182 camera.set_target_pos(self.camera_pos + ke.Vec3(-3.0, 0.0, 0.0))
183 self.set_camera_move_speed(max(5.0, 20.0 * self.scale))
184 else:
185 if self.bounds_min is None or self.bounds_max is None:
186 camera.set_camera_pos(ke.Vec3(0.0, 4.0, 14.0))
187 camera.set_target_pos(ke.Vec3(0.0, 2.0, 0.0))
188 self.set_camera_move_speed(max(1.0, 20.0 * self.scale))
189 return
190
191 center = (self.bounds_min + self.bounds_max) * 0.5
192 size = self.bounds_max - self.bounds_min
193 radius = max(float(math.sqrt(float((size * size).sum()))) * 0.5, 1.0)
194 camera.set_target_pos(
195 ke.Vec3(float(center[0]), float(center[1]), float(center[2]))
196 )
197 camera.set_camera_pos(
198 ke.Vec3(
199 float(center[0] + radius * 0.15),
200 float(center[1] + radius * 0.10),
201 float(center[2] + radius * 0.85),
202 )
203 )
204 self.set_camera_move_speed(max(1.0, radius * 0.75))
205
206 def _add_ground_from_bounds(self):
207 size = None
208 ground_y = self.ground_y
209 if self.bounds_min is not None and self.bounds_max is not None:
210 bounds_size = self.bounds_max - self.bounds_min
211 size = max(float(bounds_size[0]), float(bounds_size[2]), 1.0) * 1.2
212 if ground_y is None:
213 ground_y = float(self.bounds_min[1])
214
215 ground_size = self.ground_size if self.ground_size is not None else size
216 if ground_size is None:
217 ground_size = max(20.0, 20.0 * self.scale)
218 if ground_y is None:
219 ground_y = 0.0
220
221 ground = self.add_ground(
222 "/ground",
223 scale=ground_size,
224 material=self.standard_materials.ground,
225 )
226 ground.prim.set_local_translation(ke.Vec3(0.0, ground_y, 0.0))
227
228 def _apply_normal_map_toggle(self):
229 for material, texture in self.normal_texture_bindings:
230 material.normal_map = texture if self.normal_maps_enabled else None
231 self.resources.invalidate_usage_cache()
232
233
234def compute_obj_bounds(info):
235 import numpy as np
236
237 mins = []
238 maxs = []
239 subsets = list(info.subsets)
240 meshes = [subset.mesh_data for subset in subsets] if subsets else [info.mesh_data]
241 for mesh in meshes:
242 vertices = mesh.vertices
243 if not vertices:
244 continue
245 arr = np.asarray([[v.x, v.y, v.z] for v in vertices], dtype=np.float32)
246 mins.append(arr.min(axis=0))
247 maxs.append(arr.max(axis=0))
248 if not mins:
249 return None, None
250 return np.stack(mins).min(axis=0), np.stack(maxs).max(axis=0)
251
252
253def build_parser() -> argparse.ArgumentParser:
254 parser = render_example_parser(description="View an OBJ/MTL scene.")
255 parser.add_argument("--obj-file", type=Path, default=None)
256 parser.add_argument("--preset", type=str, default=None)
257 parser.add_argument("--root-path", default=None)
258 parser.add_argument("--scale", type=float, default=None)
259 parser.add_argument("--width", type=int, default=1920)
260 parser.add_argument("--height", type=int, default=1080)
261 parser.add_argument("--single-sided", action="store_true")
262 parser.add_argument("--ground", action="store_true")
263 parser.add_argument("--ground-size", type=float, default=None)
264 parser.add_argument("--ground-y", type=float, default=None)
265 parser.add_argument("--up-axis", choices=("Y", "Z"), default="Y")
266 parser.add_argument("--title", default=None)
267 return parser
268
269
270def main():
271 parser = build_parser()
272 args = parser.parse_args()
273 if not args.preset and not args.obj_file:
274 raise RuntimeError("Need to specify --obj-file or --preset")
275
276 preset = args.preset.upper() if args.preset else None
277 if preset == "CRYTEK_SPONZA":
278 args.obj_file = CRYTEK_SPONZA_OBJ
279 elif preset is not None:
280 raise ValueError(f"unknown OBJ scene preset: {args.preset}")
281
282 obj_file = args.obj_file.expanduser().resolve()
283 if not obj_file.exists():
284 raise FileNotFoundError(obj_file)
285
286 app = None
287 if preset == "CRYTEK_SPONZA":
288 scale = 0.01 if args.scale is None else args.scale
289 app = ObjSceneViewer(
290 obj_file,
291 root_path=args.root_path or "/crytek_sponza",
292 title=args.title or "Crytek Sponza",
293 scale=scale,
294 double_sided=not args.single_sided,
295 show_ground=args.ground,
296 ground_size=(
297 1200.0 * scale if args.ground_size is None else args.ground_size
298 ),
299 ground_y=(-4.0 * scale if args.ground_y is None else args.ground_y),
300 light_direction=ke.Vec3(0.32, -0.93, 0.17),
301 light_color=ke.Vec3(1.0, 0.94, 0.86),
302 light_intensity=1.25,
303 light_ambient=ke.Vec3(0.38, 0.36, 0.32),
304 camera_pos=ke.Vec3(5.92, 4.87, -0.96),
305 camera_fov=58.0,
306 )
307 else:
308 scale = 1.0 if args.scale is None else args.scale
309 app = ObjSceneViewer(
310 obj_file,
311 root_path=args.root_path,
312 title=args.title,
313 scale=scale,
314 double_sided=not args.single_sided,
315 show_ground=args.ground,
316 ground_size=args.ground_size,
317 ground_y=args.ground_y,
318 )
319 app.initialize(
320 args.width, args.height, False, parse_up_axis(args.up_axis),
321 renderer=args.renderer,
322 )
323 app.start()
324
325
326if __name__ == "__main__":
327 main()
PLY meshes and point clouds¶
asset.load_ply() returns scene.MeshData without an App or graphics context:
import kangengine as ke
mesh: ke.scene.MeshData = ke.asset.load_ply(path="model.ply")
PLY 1.0 ASCII and little-/big-endian binary files are supported. Coordinates and
scale are preserved. The loader reads positions, normals, RGB, and vertex UVs
(u/v, s/t, or texture_u/texture_v). Separate multi_texture_vertex /
multi_texture_face UV tables support one texture and use the OBJ UV convention
after loading. Multiple texture IDs are rejected.
Triangulate concave polygons before loading; convex faces are triangulated
automatically. Missing mesh normals are generated, and missing UVs become zero.
Point clouds have empty indices and keep missing attributes empty.
Integer RGB is normalized to [0, 1]; floating RGB must already be in that range.
Colors are linear by default; pass colors_srgb=True for sRGB input. Alpha and
unknown properties are ignored. Materials and image references are not loaded.
Inside App.setup(), add a mesh:
material: ke.material.ColorMaterial = self.create_color_material()
material.unlit = True
self.scene.add_mesh(
path="/ply", mesh_data=mesh, material=material, color=ke.Vec4(1, 1, 1, 1),
)
For point clouds, add alpha to the RGB values for the point drawing API:
import numpy as np
points = np.asarray(mesh.vertices, dtype=np.float32)
rgb = mesh.colors
colors = None
if rgb:
colors = np.ones((len(points), 4), dtype=np.float32)
colors[:, :3] = np.asarray(rgb)
self.debug.overlay.points(path="/ply", points=points, colors=colors, size=6.0)
The viewer selects mesh or point rendering automatically. --up-axis Y|Z
sets the viewer’s up axis (default Y), without rotating the source coordinates:
python python/examples/asset/view_ply.py --ply-path /path/to/model.ply
For a mesh with UVs, use --texture-path to supply an image. The viewer loads it
as sRGB and displays it without lighting; image paths are not detected automatically:
python python/examples/asset/view_ply.py \
--ply-path "/path/to/model.ply" \
--texture-path "/path/to/model_color.jpg" --up-axis Z
Rigid body sources¶
These loaders prepare descriptions for the Rigid Bodies workflow. Construct the source first, then register or render instances.
OBJ files¶
This optional example needs your own meter-scale, Z-up chair.obj. Keep the
OBJ, MTL, and referenced textures together:
import kangengine as ke
obj_asset: ke.asset.RigidDesc = ke.asset.load_obj_rigid(obj_path="chair.obj")
Coordinates and scale are preserved. Material subsets, normals, and UVs are retained. The default triangle-mesh collider supports static or kinematic bodies. Dynamic triangle-mesh collision is unsupported by this rigid-body API.
For a box-shaped OBJ, supply a primitive collider in the same local frame:
import kangengine as ke
box_collider: ke.asset.CollisionGeomDesc = ke.asset.CollisionGeomDesc(
type=ke.asset.CollisionGeomDescType.BOX,
size=[0.5, 0.3, 0.4], # Half extents in meters; match your mesh.
position=[0.0, 0.0, 0.0],
quat_xyzw=[0.0, 0.0, 0.0, 1.0],
)
textured_box: ke.asset.RigidDesc = ke.asset.load_obj_rigid(
obj_path="textured_box.obj", collision_geoms=[box_collider]
)
For a concave object such as a cup, supply several primitive or convex pieces in
the same local frame as its visual mesh. The OBJ loader does not perform
automatic convex decomposition. Prepare the pieces separately and supply them
through collision_geoms.
Single-body imports¶
As an alternative to building a description, pass a single-body MJCF returned
by world.load_mjcf(mjcf_path=...) to world.add_rigid().
ke.asset.RigidDesc.from_articulation(description) is available when explicit
conversion from a single-body ArticulationDesc is needed.
FBX mesh¶
meshes: list[ke.asset.FBXMeshInfo] = ke.asset.FBXLoader.load_meshes(
fbx_path=fbx_file,
scale=scale,
)
for i, mesh in enumerate(meshes):
self.scene.add_mesh(
path=f"/fbx/mesh_{i}",
mesh_data=mesh.mesh_data,
material=material,
)
USD scenes¶
Build with USD support (make build_usd_python), then open the scene’s root
layer. Referenced layers and textures must remain in their original relative
locations:
python python/examples/view_usd_scene.py /path/to/scene.usda
The viewer uses the stage’s Y-up or Z-up axis and starts at its first authored perspective camera. Use Reset camera to return there or Frame scene to see the whole scene. Hold the right mouse button to look around; WASD moves parallel to the floor, Q/E moves down/up, and Shift increases speed. Movement is free of collision constraints. Physics and articulation loading are separate from this viewer.
USD RectLight and DomeLight objects are created as scene lights, with the source camera’s exposure and ACES tone mapping. The Exposure compensation control changes viewing exposure without modifying the source light values. See Scene Lighting for the supported controls and rendering limits.
The loader includes visible meshes with effective default or render
purpose, including native USD instances and material subsets. It respects
inherited visibility and purpose. A mesh with collision properties is still
displayed if it is also visible render geometry.
UsdPreviewSurface materials retain base color/opacity, metallic, roughness,
emission, normal maps and double-sided state. Texture connections can pass through
NodeGraph outputs. Supported UsdUVTexture maps include RGB colors, R-channel
scalar maps, RGB scalar maps (sampled from red), separate R/RGB opacity masks,
and packed G-roughness / B-metallic maps. Unsupported shader connections produce
diagnostics. Color maps use sRGB decoding unless sourceColorSpace is raw; normal and scalar
maps remain linear. For manually loaded textures, see
Materials and Textures.
OmniPBR materials retain constant diffuse color, metallic, and roughness values,
plus a directly assigned diffuse_texture and its diffuse_tint. The texture
replaces the constant color; colorSpace = "raw" disables sRGB decoding.
Other OmniPBR maps, albedo adjustments, and connected MDL networks are unsupported.
Articulation imports retain these mesh-bound materials and their base-color, normal, metallic, roughness, packed metallic-roughness, and emissive maps. Textures are loaded by the App when visuals are attached, preserving color-space settings and sharing cached textures across instances. Articulation opacity maps, alpha cutout, and per-face material assignments are not imported.
The parsing snippet uses usd_file, the path to your root USD layer:
import kangengine as ke
result: ke.asset.USDImportResult = ke.asset.USDLoader.parse(
usd_path=usd_file,
scale=1.0,
)
meshes: list[ke.asset.USDMeshInfo] = result.meshes
Mesh vertices, bounds and camera positions use authored scene units multiplied
by scale; axes are not rotated. result.meters_per_unit reports the original
stage unit. Camera vertical FOV is in degrees.
The returned meshes have transforms baked into their vertices. The result is
for static display, not editing and saving the original USD scene; keep the
source USD for that purpose. prim_path and material_path identify the source
objects. The viewer uses fallback lighting when no supported USD lights were
imported. MDL/MaterialX networks, arbitrary texture transforms and camera roll
are not reproduced.
Examples¶
python/examples/view_fbx_mesh.pypython/examples/view_obj_scene.pypython/examples/view_usd_scene.pypython/examples/usd_file_bridge.py
