-
Notifications
You must be signed in to change notification settings - Fork 183
/
renderer.py
352 lines (305 loc) · 13.2 KB
/
renderer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# to allow for typing to refer to class being defined (Renderer)
from __future__ import annotations
import importlib.resources as pkg_resources
import logging
import os
from threading import Lock
from typing import NamedTuple
import gltf
from direct.showbase.ShowBase import ShowBase
from panda3d.core import (
FrameBufferProperties,
GraphicsOutput,
GraphicsPipe,
NodePath,
OrthographicLens,
Shader,
Texture,
WindowProperties,
loadPrcFileData,
)
from . import glsl, models
from .colors import SceneColors
from .coordinates import Pose
from .masks import RenderMasks
from .scenario import Scenario
class _ShowBaseInstance(ShowBase):
""" Wraps a singleton instance of ShowBase from Panda3D. """
def __new__(cls):
# Singleton pattern: ensure only 1 ShowBase instance
if "__it__" not in cls.__dict__:
# loadPrcFileData("", "gl-debug #t")
loadPrcFileData("", f"load-display p3headlessgl")
loadPrcFileData("", "aux-display p3headlessgl")
loadPrcFileData("", "aux-display pandagl")
loadPrcFileData("", "aux-display pandadx9")
loadPrcFileData("", "aux-display pandagles")
loadPrcFileData("", "aux-display pandagles2")
loadPrcFileData("", "aux-display p3tinydisplay")
# disable vsync otherwise we are limited to refresh-rate of screen
loadPrcFileData("", "sync-video false")
loadPrcFileData("", "model-path %s" % os.getcwd())
# TODO: the following speeds up rendering a bit... might consider it.
# loadPrcFileData("", "model-cache-dir %s/.panda3d_cache" % os.getcwd())
loadPrcFileData("", "audio-library-name null")
loadPrcFileData("", "gl-version 3 3")
loadPrcFileData("", "notify-level error")
loadPrcFileData("", "print-pipe-types false")
# https://www.panda3d.org/manual/?title=Multithreaded_Render_Pipeline
# loadPrcFileData('', 'threading-model Cull/Draw')
# have makeTextureBuffer create a visible window
# loadPrcFileData('', 'show-buffers true')
it = cls.__dict__.get("__it__")
if it is None:
cls.__it__ = it = object.__new__(cls)
it.init()
return it
def __init__(self):
pass # singleton pattern, uses init() instead (don't call super().__init__() here!)
def init(self):
"""Initializer for the purposes of maintaining a singleton of this class."""
self._render_lock = Lock()
try:
# There can be only 1 ShowBase instance at a time.
super().__init__(windowType="offscreen")
gltf.patch_loader(self.loader)
self.setBackgroundColor(0, 0, 0, 1)
# Displayed framerate is misleading since we are not using a realtime clock
self.setFrameRateMeter(False)
except Exception as e:
raise e
def destroy(self):
"""Destroy this renderer and clean up all remaining resources."""
super().destroy()
self.__class__.__it__ = None
def __del__(self):
self.destroy()
def setup_sim_root(self, simid: str):
"""Creates the simulation root node in the scene graph."""
root_np = NodePath(simid)
with self._render_lock:
root_np.reparentTo(self.render)
with pkg_resources.path(
glsl, "unlit_shader.vert"
) as vshader_path, pkg_resources.path(
glsl, "unlit_shader.frag"
) as fshader_path:
unlit_shader = Shader.load(
Shader.SL_GLSL,
vertex=str(vshader_path.absolute()),
fragment=str(fshader_path.absolute()),
)
root_np.setShader(unlit_shader)
return root_np
def render_node(self, sim_root: NodePath):
"""Render a panda3D scene graph from the given node."""
# Hack to prevent other SMARTS instances from also rendering
# when we call poll() here.
hidden = []
with self._render_lock:
for np in self.render.children:
if np != sim_root and not np.isHidden():
np.hide()
hidden.append(np)
self.taskMgr.mgr.poll()
for np in hidden:
np.show()
class Renderer:
"""The utility used to render simulation geometry."""
def __init__(self, simid: str):
self._log = logging.getLogger(self.__class__.__name__)
self._is_setup = False
self._simid = simid
self._root_np = None
self._vehicles_np = None
self._road_map_np = None
self._vehicle_nodes = {}
# Note: Each instance of the SMARTS simulation will have its own Renderer,
# but all Renderer objects share the same ShowBaseInstance.
self._showbase_instance = _ShowBaseInstance()
@property
def id(self):
"""The id of the simulation rendered."""
return self._simid
def setup(self, scenario: Scenario):
"""Initialize this renderer."""
self._root_np = self._showbase_instance.setup_sim_root(self._simid)
self._vehicles_np = self._root_np.attachNewNode("vehicles")
map_path = scenario.map_glb_filepath
if self._road_map_np:
self._log.debug(
"road_map={} already exists. Removing and adding a new "
"one from glb_path={}".format(self._road_map_np, map_path)
)
map_np = self._showbase_instance.loader.loadModel(map_path, noCache=True)
np = self._root_np.attachNewNode("road_map")
map_np.reparent_to(np)
np.hide(RenderMasks.OCCUPANCY_HIDE)
np.setColor(SceneColors.Road.value)
self._road_map_np = np
self._is_setup = True
def render(self):
"""Render the scene graph of the simulation."""
assert self._is_setup
self._showbase_instance.render_node(self._root_np)
def step(self):
""" provided for non-SMARTS uses; normally not used by SMARTS. """
self._showbase_instance.taskMgr.step()
def teardown(self):
"""Clean up internal resources."""
if self._root_np is not None:
self._root_np.clearLight()
self._root_np.removeNode()
self._root_np = None
self._vehicles_np = None
self._road_map_np = None
self._is_setup = False
def destroy(self):
"""Destroy the renderer. Cleans up all remaining renderer resources."""
self.teardown()
self._showbase_instance = None
def __del__(self):
self.destroy()
def create_vehicle_node(self, glb_model: str, vid: str, color, pose: Pose):
"""Create a vehicle node."""
with pkg_resources.path(models, glb_model) as path:
node_path = self._showbase_instance.loader.loadModel(str(path.absolute()))
node_path.setName("vehicle-%s" % vid)
node_path.setColor(color)
pos, heading = pose.as_panda3d()
node_path.setPosHpr(*pos, heading, 0, 0)
node_path.hide(RenderMasks.DRIVABLE_AREA_HIDE)
self._vehicle_nodes[vid] = node_path
def begin_rendering_vehicle(self, vid: str, is_agent: bool):
"""Add the vehicle node to the scene graph """
vehicle_path = self._vehicle_nodes.get(vid, None)
if not vehicle_path:
self._log.warning(f"Renderer ignoring invalid vehicle id: {vid}")
return
# TAI: consider reparenting hijacked vehicles too?
vehicle_path.reparentTo(self._vehicles_np if is_agent else self._root_np)
def update_vehicle_node(self, vid: str, pose: Pose):
"""Move the specified vehicle node."""
vehicle_path = self._vehicle_nodes.get(vid, None)
if not vehicle_path:
self._log.warning(f"Renderer ignoring invalid vehicle id: {vid}")
return
pos, heading = pose.as_panda3d()
vehicle_path.setPosHpr(*pos, heading, 0, 0)
def remove_vehicle_node(self, vid: str):
"""Remove a vehicle node"""
vehicle_path = self._vehicle_nodes.get(vid, None)
if not vehicle_path:
self._log.warning(f"Renderer ignoring invalid vehicle id: {vid}")
return
vehicle_path.removeNode()
class OffscreenCamera(NamedTuple):
"""A camera used for rendering images to a graphics buffer."""
camera_np: NodePath
buffer: GraphicsOutput
tex: Texture
renderer: Renderer
def wait_for_ram_image(self, img_format: str, retries=100):
"""Attempt to acquire a graphics buffer."""
# Rarely, we see dropped frames where an image is not available
# for our observation calculations.
#
# We've seen this happen fairly reliable when we are initializing
# a multi-agent + multi-instance simulation.
#
# To deal with this, we can try to force a render and block until
# we are fairly certain we have an image in ram to return to the user
for i in range(retries):
if self.tex.mightHaveRamImage():
break
self.renderer._log.debug(
f"No image available (attempt {i}/{retries}), forcing a render"
)
region = self.buffer.getDisplayRegion(0)
region.window.engine.renderFrame()
assert self.tex.mightHaveRamImage()
ram_image = self.tex.getRamImageAs(img_format)
assert ram_image is not None
return ram_image
def update(self, pose: Pose, height: float):
"""Update the location of the camera.
Args:
pose:
The pose of the camera target.
height:
The height of the camera above the camera target.
"""
pos, heading = pose.as_panda3d()
self.camera_np.setPos(pos[0], pos[1], height)
self.camera_np.lookAt(*pos)
self.camera_np.setH(heading)
def teardown(self):
"""Clean up internal resources."""
self.camera_np.removeNode()
region = self.buffer.getDisplayRegion(0)
region.window.clearRenderTextures()
self.buffer.removeAllDisplayRegions()
self.renderer._showbase_instance.graphicsEngine.removeWindow(self.buffer)
def build_offscreen_camera(
self,
name: str,
mask: int,
width: int,
height: int,
resolution: float,
) -> Renderer.OffscreenCamera:
"""Generates a new offscreen camera."""
# setup buffer
win_props = WindowProperties.size(width, height)
fb_props = FrameBufferProperties()
fb_props.setRgbColor(True)
fb_props.setRgbaBits(8, 8, 8, 1)
# XXX: Though we don't need the depth buffer returned, setting this to 0
# causes undefined behavior where the ordering of meshes is random.
fb_props.setDepthBits(8)
buffer = self._showbase_instance.win.engine.makeOutput(
self._showbase_instance.pipe,
"{}-buffer".format(name),
-100,
fb_props,
win_props,
GraphicsPipe.BFRefuseWindow,
self._showbase_instance.win.getGsg(),
self._showbase_instance.win,
)
buffer.setClearColor((0, 0, 0, 0)) # Set background color to black
# setup texture
tex = Texture()
region = buffer.getDisplayRegion(0)
region.window.addRenderTexture(
tex, GraphicsOutput.RTM_copy_ram, GraphicsOutput.RTP_color
)
# setup camera
lens = OrthographicLens()
lens.setFilmSize(width * resolution, height * resolution)
camera_np = self._showbase_instance.makeCamera(
buffer, camName=name, scene=self._root_np, lens=lens
)
camera_np.reparentTo(self._root_np)
# mask is set to make undesirable objects invisible to this camera
camera_np.node().setCameraMask(camera_np.node().getCameraMask() & mask)
return Renderer.OffscreenCamera(camera_np, buffer, tex, self)