0
# Application Framework
1
2
The ShowBase class provides the main application framework for Panda3D applications. It handles window creation, system initialization, main loop management, and provides access to core subsystems.
3
4
## Capabilities
5
6
### ShowBase - Main Application Class
7
8
ShowBase is the foundation class for all Panda3D applications. It initializes the graphics system, creates the main window, and provides access to core engine subsystems.
9
10
```python { .api }
11
class ShowBase:
12
def __init__(self, fStartDirect: bool = True, windowType: str = None) -> None:
13
"""
14
Initialize Panda3D application.
15
16
Args:
17
fStartDirect: Whether to start DirectStart subsystem
18
windowType: Graphics window type ('onscreen', 'offscreen', etc.)
19
"""
20
21
def run(self) -> None:
22
"""Start the main application loop. This method blocks until the application exits."""
23
24
def destroy(self) -> None:
25
"""Clean up and destroy the application."""
26
27
def userExit(self) -> None:
28
"""Handle user-initiated exit (window close, Alt+F4, etc.)."""
29
30
def finalExitCallbacks(self) -> None:
31
"""Execute final cleanup callbacks before exit."""
32
33
# Core subsystem access
34
loader: Loader # Asset loading system
35
render: NodePath # Main 3D scene root
36
render2d: NodePath # 2D overlay root
37
aspect2d: NodePath # Aspect-corrected 2D root
38
pixel2d: NodePath # Pixel-coordinate 2D root
39
camera: NodePath # Default 3D camera
40
cam: NodePath # Camera node (different from camera)
41
camNode: Camera # Actual camera object
42
cam2d: NodePath # 2D camera
43
taskMgr: TaskManager # Task scheduling system
44
messenger: Messenger # Event messaging system
45
eventMgr: EventManager # Event management
46
accept: callable # Event acceptance method
47
ignore: callable # Event ignore method
48
ignoreAll: callable # Ignore all events method
49
50
# Graphics and windowing
51
win: GraphicsWindow # Main graphics window
52
winList: List[GraphicsWindow] # All graphics windows
53
pipe: GraphicsPipe # Graphics pipe
54
55
# Audio system
56
sfxManagerList: List # Sound effect managers
57
musicManager # Music manager
58
59
# Input systems
60
mouseWatcherNode: MouseWatcher # Mouse input handling
61
buttonThrowers: List # Keyboard input handling
62
63
# Configuration and system
64
config: Config # Configuration system
65
```
66
67
### Window and Graphics Management
68
69
Control graphics windows, display properties, and rendering pipeline configuration.
70
71
```python { .api }
72
class ShowBase:
73
def openDefaultWindow(self, **props) -> bool:
74
"""Open the default graphics window with specified properties."""
75
76
def openMainWindow(self, **props) -> GraphicsWindow:
77
"""Open main graphics window."""
78
79
def closeWindow(self, win: GraphicsWindow) -> None:
80
"""Close a graphics window."""
81
82
def makeCamera(self,
83
win: GraphicsWindow,
84
sort: int = 0,
85
displayRegion: DisplayRegion = None,
86
camName: str = 'cam') -> NodePath:
87
"""Create a camera for a graphics window."""
88
89
def setupRender(self) -> None:
90
"""Initialize the 3D rendering system."""
91
92
def setupRender2d(self) -> None:
93
"""Initialize the 2D overlay system."""
94
95
def enableParticles(self) -> None:
96
"""Enable particle system rendering."""
97
98
def disableParticles(self) -> None:
99
"""Disable particle system rendering."""
100
```
101
102
### Event and Input Integration
103
104
ShowBase integrates with Panda3D's event system and provides convenience methods for input handling.
105
106
```python { .api }
107
class ShowBase:
108
def accept(self, event: str, method: callable, extraArgs: List = []) -> None:
109
"""Accept an event and bind it to a method."""
110
111
def acceptOnce(self, event: str, method: callable, extraArgs: List = []) -> None:
112
"""Accept an event only once."""
113
114
def ignore(self, event: str) -> None:
115
"""Stop accepting a specific event."""
116
117
def ignoreAll(self) -> None:
118
"""Stop accepting all events."""
119
120
def getAllAccepting(self) -> List[str]:
121
"""Get list of all accepted events."""
122
123
def isAccepting(self, event: str) -> bool:
124
"""Check if currently accepting an event."""
125
```
126
127
### Task Management Integration
128
129
ShowBase provides direct access to the task management system for frame-based logic.
130
131
```python { .api }
132
class ShowBase:
133
def taskMgr: TaskManager
134
"""Access to global task manager."""
135
136
# Common task management patterns
137
def addTask(self, task: callable, name: str, priority: int = 0) -> Task:
138
"""Add a task to the task manager."""
139
140
def removeTask(self, task: str | Task) -> bool:
141
"""Remove a task from the task manager."""
142
143
def doMethodLater(self, delay: float, task: callable, name: str) -> Task:
144
"""Schedule a task to run after a delay."""
145
```
146
147
### Configuration and System Access
148
149
Access engine configuration, system information, and performance monitoring.
150
151
```python { .api }
152
class ShowBase:
153
def getConfigShowbase(self) -> ConfigVariableBool:
154
"""Get ShowBase configuration variable."""
155
156
def getAspectRatio(self) -> float:
157
"""Get current window aspect ratio."""
158
159
def adjustWindowAspectRatio(self, aspectRatio: float) -> None:
160
"""Adjust 2D display region for aspect ratio."""
161
162
def getSize(self) -> Tuple[int, int]:
163
"""Get window size as (width, height)."""
164
165
def getFrameRateMeter(self) -> FrameRateMeter:
166
"""Get frame rate monitoring object."""
167
168
def setFrameRateMeter(self, flag: bool) -> None:
169
"""Enable or disable frame rate display."""
170
```
171
172
### Audio System Integration
173
174
ShowBase provides access to the audio system for music and sound effects.
175
176
```python { .api }
177
class ShowBase:
178
def enableMusic(self, bEnableMusic: bool) -> None:
179
"""Enable or disable music system."""
180
181
def enableSoundEffects(self, bEnableSoundEffects: bool) -> None:
182
"""Enable or disable sound effects system."""
183
184
def enableAllAudio(self) -> None:
185
"""Enable all audio subsystems."""
186
187
def disableAllAudio(self) -> None:
188
"""Disable all audio subsystems."""
189
```
190
191
## Usage Examples
192
193
### Basic Application Setup
194
195
```python
196
from direct.showbase.ShowBase import ShowBase
197
from panda3d.core import Vec3
198
from direct.task import Task
199
200
class MyGame(ShowBase):
201
def __init__(self):
202
ShowBase.__init__(self)
203
204
# Basic setup
205
self.setBackgroundColor(0.1, 0.1, 0.8, 1)
206
self.camera.setPos(0, -10, 0)
207
208
# Load content
209
self.setupScene()
210
211
# Start game logic
212
self.setupTasks()
213
214
# Setup input handling
215
self.setupInput()
216
217
def setupScene(self):
218
"""Initialize 3D scene content."""
219
self.model = self.loader.loadModel("models/teapot")
220
self.model.reparentTo(self.render)
221
self.model.setScale(2)
222
223
def setupTasks(self):
224
"""Setup frame-based tasks."""
225
self.taskMgr.add(self.updateGame, "update-game")
226
227
def updateGame(self, task):
228
"""Main game update loop."""
229
dt = globalClock.getDt()
230
231
# Rotate the model
232
self.model.setH(self.model.getH() + 30 * dt)
233
234
return task.cont
235
236
def setupInput(self):
237
"""Setup input event handling."""
238
self.accept("escape", self.userExit)
239
self.accept("space", self.toggleAnimation)
240
241
def toggleAnimation(self):
242
"""Toggle model animation."""
243
# Custom input handling logic
244
pass
245
246
# Start the application
247
app = MyGame()
248
app.run()
249
```
250
251
### Multi-Window Application
252
253
```python
254
from direct.showbase.ShowBase import ShowBase
255
from panda3d.core import *
256
257
class MultiWindowApp(ShowBase):
258
def __init__(self):
259
ShowBase.__init__(self)
260
261
# Create additional window
262
self.createSecondWindow()
263
264
def createSecondWindow(self):
265
"""Create a second graphics window."""
266
# Window properties
267
props = WindowProperties()
268
props.setTitle("Second Window")
269
props.setSize(400, 300)
270
props.setOrigin(100, 100)
271
272
# Create window
273
self.second_win = self.openWindow(props=props)
274
275
if self.second_win:
276
# Create camera for second window
277
self.second_cam = self.makeCamera(self.second_win)
278
self.second_cam.setPos(5, -10, 2)
279
self.second_cam.lookAt(0, 0, 0)
280
281
app = MultiWindowApp()
282
app.run()
283
```
284
285
### Offscreen Rendering Application
286
287
```python
288
from direct.showbase.ShowBase import ShowBase
289
from panda3d.core import *
290
291
class OffScreenApp(ShowBase):
292
def __init__(self):
293
# Initialize with offscreen rendering
294
ShowBase.__init__(self, windowType='offscreen')
295
296
# Setup scene for rendering
297
self.setupOffscreenScene()
298
299
# Render frame and save
300
self.renderAndSave()
301
302
# Exit after rendering
303
self.userExit()
304
305
def setupOffscreenScene(self):
306
"""Setup scene for offscreen rendering."""
307
self.model = self.loader.loadModel("models/teapot")
308
self.model.reparentTo(self.render)
309
self.camera.setPos(0, -5, 2)
310
self.camera.lookAt(0, 0, 0)
311
312
def renderAndSave(self):
313
"""Render frame and save to file."""
314
# Force a frame render
315
self.graphicsEngine.renderFrame()
316
317
# Save screenshot
318
self.screenshot("output.png")
319
320
app = OffScreenApp()
321
app.run()
322
```
323
324
## Types
325
326
```python { .api }
327
class GraphicsWindow:
328
"""Represents a graphics window."""
329
def getXSize(self) -> int: ...
330
def getYSize(self) -> int: ...
331
def isClosed(self) -> bool: ...
332
333
class GraphicsPipe:
334
"""Graphics rendering pipeline."""
335
def makeOutput(self, **props) -> GraphicsWindow: ...
336
337
class Config:
338
"""Configuration system access."""
339
def GetBool(self, var: str, default: bool = False) -> bool: ...
340
def GetString(self, var: str, default: str = "") -> str: ...
341
342
class Task:
343
"""Task object for task management."""
344
cont: int # Continue task constant
345
done: int # Complete task constant
346
again: int # Restart task constant
347
```