### Bullet Physics Example Setup in C++ Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/physics/bullet/hello-world.rst This C++ code provides a basic setup for a Bullet physics simulation within Panda3D. It includes necessary header files, initializes the Panda3D framework, and sets up a function to retrieve the physics world. The comments indicate that physics_world should be a global variable, but suggests using static keyword instead. ```cpp // Bullet Physics Example. // The following example is done from Python sources, Panda Reference and Panda Manual, // for more information, visit Panda3D and/or Bullet physics web site. // Compiling and Linking documentation and notes are not // covered in this file, check manual for more information. #include "pandaFramework.h" #include "windowFramework.h" #include "nodePath.h" #include "clockObject.h" #include "asyncTask.h" #include "genericAsyncTask.h" #include "bulletWorld.h" #include "bulletPlaneShape.h" #include "bulletBoxShape.h" BulletWorld *get_physics_world() { // physics_world is supposed to be an global variable, // but declaring global variables is not cool // for good programmers lol, instead, should use static keyword. ``` -------------------------------- ### Install Sphinx and Extensions using pip Source: https://github.com/panda3d/panda3d-docs/blob/1.10/README.md This command installs Sphinx and its required extensions using pip, based on the dependencies listed in the requirements.txt file. It is a prerequisite for building the Panda3D documentation. ```Python pip install -r requirements.txt ``` -------------------------------- ### Simple Console Application with Win32 - setup.py (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/setuptools-examples.rst This setup.py file extends the previous example to include win32 as a target platform. It defines the platforms explicitly to ensure that a win32 build is created, in addition to the default platforms. ```python import setuptools setup( name="Hello World", options = { 'build_apps': { 'console_apps': {'hello_world': 'main.py'}, 'platforms': [ 'manylinux1_x86_64', 'macosx_10_6_x86_64', 'win_amd64', 'win32', ], } } ) ``` -------------------------------- ### Running Panda3D Sample Programs in Linux Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/installation-linux.rst This snippet demonstrates how to navigate to the Panda3D samples directory, select a sample program, and run it using Python. It assumes Panda3D is installed and the samples are located in /usr/share/panda3d/samples. ```bash $ cd /usr/share/panda3d/samples $ ls asteroids ball-in-maze boxing-robots bump-mapping carousel cartoon-shader chessboard culling disco-lights distortion fireflies fractal-plants gamepad glow-filter infinite-tunnel looking-and-gripping media-player motion-trails mouse-modes music-box particles procedural-cube render-to-texture roaming-ralph rocket-console shader-terrain shadows solar-system $ cd boxing-robots $ python3 main.py ``` -------------------------------- ### Example: Viewing Panda Model in PView Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/previewing-models.rst This command opens the panda.egg model in PView. This is a basic example using a model distributed with the Panda3D source. ```text pview panda.egg ``` -------------------------------- ### Initializing Panda3D Framework in C++ Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/tutorial/starting-panda3d.rst This C++ code initializes the Panda3D framework, opens a window, and starts the main loop. It includes necessary headers, opens a window framework, sets the window title, and then enters the main loop. The main_loop() function handles rendering and background tasks. ```cpp #include "pandaFramework.h" #include "pandaSystem.h" int main(int argc, char *argv[]) { // Open a new window framework PandaFramework framework; framework.open_framework(argc, argv); // Set the window title and open the window framework.set_window_title("My Panda3D Window"); WindowFramework *window = framework.open_window(); // Here is room for your own code // Do the main loop, equal to run() in python framework.main_loop(); framework.close_framework(); return (0); } ``` -------------------------------- ### Initializing ShowBase for Panda3D in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/tutorial/starting-panda3d.rst This code initializes Panda3D using the ShowBase class, which loads necessary modules and creates a 3D window. The MyApp class inherits from ShowBase, and the run() method starts the Panda3D main loop, rendering frames and handling background tasks. The script creates an empty grey window. ```python from direct.showbase.ShowBase import ShowBase class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) app = MyApp() app.run() ``` -------------------------------- ### DirectWaitBar Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directwaitbar.rst This example demonstrates how to create and use a DirectWaitBar in Panda3D. It includes importing necessary modules, creating a DirectWaitBar instance, and updating its value using buttons. ```python import direct.directbase.DirectStart from direct.gui.OnscreenText import OnscreenText from direct.gui.DirectGui import * from panda3d.core import * # Add some text bk_text = "This is my Demo" textObject = OnscreenText(text=bk_text, pos=(0.95, -0.95), scale=0.07, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) # Callback function to set text def incBar(arg): bar['value'] += arg text = "Progress is:" + str(bar['value']) + '%' textObject.setText(text) # Create a frame frame = DirectFrame(text="main", scale=0.001) # Add button bar = DirectWaitBar(text="", value=50, pos=(0, .4, .4)) # Create 4 buttons button_1 = DirectButton(text="+1", scale=0.05, pos=(-.3, .6, 0), command=incBar, extraArgs=[1]) button_10 = DirectButton(text="+10", scale=0.05, pos=(0, .6, 0), command=incBar, extraArgs=[10]) button_m1 = DirectButton(text="-1", scale=0.05, pos=(0.3, .6, 0), command=incBar, extraArgs=[-1]) button_m10 = DirectButton(text="-10", scale=0.05, pos=(0.6, .6, 0), command=incBar, extraArgs=[-10]) # Run the tutorial base.run() ``` -------------------------------- ### Starting an Interval in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/intervals/index.rst These code snippets demonstrate how to start an interval playing in Python. The start() and loop() methods can be used with optional startT, endT, and playRate parameters to control the playback. ```python interval.start() ``` ```python interval.start(startT, endT, playRate) ``` ```python interval.loop() ``` ```python interval.loop(startT, endT, playRate) ``` -------------------------------- ### Interrogate Module Command Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/tools/interrogate.rst Example of using the interrogate_module command to generate a module file. Includes options for output file, module name, library name, and Python native wrappers. ```c++ interrogate_module -oc myModule_module.cxx -module libMyModule -library libMyModule -python-native myModule.in ``` -------------------------------- ### Interrogate Command Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/tools/interrogate.rst Example of using the interrogate command with various options to generate C++ wrappers for a module. Includes options for defines, include paths, output files, string handling, reference counting, assertions, and Python native wrappers. ```c++ interrogate -DCPPPARSER -D__STDC__=1 -D__cplusplus=201103L -S/usr/include/panda3d/parser-inc -S/usr/include/ -I/usr/include/panda3d/ -oc myModule_igate.cxx -od myModule.in -fnames -string -refcount -assert -python-native -module libMyModule -library libMyModule myModule.h ``` -------------------------------- ### Run the Panda3D Application Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directradiobutton.rst Starts the Panda3D application, displaying the GUI and handling user interactions. ```python # Run the tutorial base.run() ``` -------------------------------- ### Running the Panda3D Application - Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directoptionmenu.rst This snippet starts the Panda3D application loop, which is necessary to display the DirectOptionMenu and handle user interactions. ```python base.run() ``` -------------------------------- ### Starting Particle Effect Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/particle-effects/loading-particle-systems.rst This code snippet shows how to start a ParticleEffect, specifying the parent node and render parent node. The parent determines the birth-relative position, while renderParent determines the rendering level. ```python p.start(parent = render, renderParent = render) ``` -------------------------------- ### Exporting Maya Model to Egg Format (Static) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/converting-from-maya.rst This command-line example demonstrates how to convert a Maya binary file (.mb) to an Egg file using the maya2egg utility. The -o option specifies the output Egg file, and the input Maya file is provided as the last argument. This example assumes the files are organized in a specific directory structure, and the resulting Egg file will contain relative texture paths. ```command line c:\ cd c:\My Models\ maya2egg -o "Egg Files/Character.egg" "Maya Files/Character.mb" ``` -------------------------------- ### Running Panda3D Program in Linux/macOS Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/tutorial/starting-panda3d.rst This command is used to execute a Panda3D application written in Python on GNU/Linux or macOS. It uses the 'python' interpreter to run the specified Python file. ```bash python filename.py ``` -------------------------------- ### Running the Panda3D application Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directbutton.rst This snippet starts the Panda3D application by calling the run method on the base object. This is necessary to display the GUI elements and handle user interactions. ```python base.run() ``` -------------------------------- ### Simple Console Application - setup.py (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/setuptools-examples.rst This setup.py file configures setuptools to build a simple console application named "Hello World". It specifies the main script (main.py) as the entry point and includes Panda3D as a dependency via requirements.txt. ```python import setuptools setup( name="Hello World", options = { 'build_apps': { 'console_apps': {'hello_world': 'main.py'}, } } ) ``` -------------------------------- ### NodePath Position Lerp Example in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/intervals/lerp-intervals.rst This code demonstrates how to use the posInterval() method to move an actor to different points over specified durations. It showcases moving to a point, specifying a duration, and including a starting position. ```python # This lets the actor move to point 10, 10, 10 in 1.0 second. myInterval1 = myActor.posInterval(1.0, Point3(10, 10, 10)) # This move takes 2.0 seconds to complete. myInterval2 = myActor.posInterval(2.0, Point3(8, -5, 10)) # You can specify a starting position, too. myInterval3 = myActor.posInterval(1.0, Point3(2, -3, 8), startPos=Point3(2, 4, 1)) # This rotates the actor 180 degrees on heading and 90 degrees on pitch. myInterval4 = myActor.hprInterval(1.0, Vec3(180, 90, 0)) ``` -------------------------------- ### Simple Console Application - Main Script (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/setuptools-examples.rst This is a basic Python script that prints "Hello world" to the console. It serves as the main entry point for a simple console application packaged using setuptools. ```python print("Hello world") ``` -------------------------------- ### Asteroids Sample - setup.py (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/setuptools-examples.rst This setup.py file configures setuptools to build the Asteroids sample program. It includes patterns for including image and egg files, specifies the main script (main.py) as a GUI application, and lists required plugins. ```python from setuptools import setup setup( name="asteroids", options = { 'build_apps': { 'include_patterns': [ '**/*.png', '**/*.jpg', '**/*.egg', ], 'gui_apps': { 'asteroids': 'main.py', }, 'plugins': [ 'pandagl', 'p3openal_audio', ], } } ) ``` -------------------------------- ### Getting Frame Time using globalClock in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/reference/builtins.rst This code snippet demonstrates how to retrieve the frame time (in seconds since the program started) using the globalClock object in Panda3D. The globalClock provides timing information for the application. ```python frameTime = globalClock.getFrameTime() ``` -------------------------------- ### Asteroids Sample - setup.cfg (INI) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/setuptools-examples.rst This setup.cfg file provides an alternative configuration for building the Asteroids sample program. It uses the INI format to specify the application name, include patterns, GUI application entry point, and required plugins. ```ini [metadata] name = asteroids [build_apps] include_patterns = **/*.png **/*.jpg **/*.egg gui_apps = asteroids = main.py plugins = pandagl p3openal_audio ``` -------------------------------- ### Importing PandAI Module in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/pandai/getting-started.rst This code snippet demonstrates how to import the PandAI module into your Python code, which is the first step to using the PandAI library in your Panda3D project. This import statement makes all the PandAI classes and functions available for use. ```python from panda3d.ai import * ``` -------------------------------- ### Sweep Test Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/physics/bullet/queries.rst This code snippet demonstrates how to perform a sweep test to check for collisions with a convex shape as it moves from one position to another. It creates TransformState objects for the start and end positions, defines a sphere shape, and then calls the sweepTestClosest method to find the closest hit. ```python tsFrom = TransformState.makePos(Point3(0, 0, 0)) tsTo = TransformState.makePos(Point3(10, 0, 0)) shape = BulletSphereShape(0.5) penetration = 0.0 result = world.sweepTestClosest(shape, tsFrom, tsTo, penetration) print(result.hasHit()) print(result.getHitPos()) print(result.getHitNormal()) print(result.getHitFraction()) print(result.getNode()) ``` -------------------------------- ### Packaging Asteroids Sample Program with Setuptools Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This example demonstrates how to package the Asteroids sample program into a self-contained executable using setuptools. It configures the build_apps command to build a GUI application, set up logging, specify included files, and include necessary plugins. ```python from setuptools import setup setup( name='asteroids', options={ 'build_apps': { # Build asteroids.exe as a GUI application 'gui_apps': { 'asteroids': 'main.py', }, # Set up output logging, important for GUI apps! 'log_filename': '$USER_APPDATA/Asteroids/output.log', 'log_append': False, # Specify which files are included with the distribution 'include_patterns': [ '**/*.png', '**/*.jpg', '**/*.egg', ], # Include the OpenGL renderer and OpenAL audio plug-in 'plugins': [ 'pandagl', 'p3openal_audio', ], } } ) ``` -------------------------------- ### Including Assets with include_patterns Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This example shows how to use the include_patterns key to specify a list of files or patterns to include with the application. It demonstrates including specific files, all files in a directory, and files with a specific extension in any subdirectory. ```python 'include_patterns': [ # Path to a specific file 'CREDITS.txt', # All files in the assets/textures/ directory, but not in subdirectories # (use ** instead of * if that is desirable) 'assets/textures/*', # All files with the .jpg extension in any subdirectory under assets/, # even if nested under multiple directories 'assets/**/*.jpg', # A file with the .egg extension anywhere in the hierarchy '**/*.egg', ] ``` -------------------------------- ### Installing panda3d-gltf using pip Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/model-file-formats.rst This command installs the panda3d-gltf plugin, which is recommended for loading glTF files into Panda3D. It uses pip, the Python package installer, to download and install the latest version of the plugin. ```python python -m pip install -U panda3d-gltf ``` -------------------------------- ### Implementing Seek Behavior with PandAI in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/pandai/getting-started.rst This code demonstrates how to implement a simple seek behavior using the PandAI library in Panda3D. It involves creating an AIWorld, AICharacter, and setting up the seek behavior between a seeker (Ralph) and a target (arrow model). The AIWorld update task is also set up to continuously update the AI behaviors. ```python import direct.directbase.DirectStart from panda3d.core import * from direct.showbase.DirectObject import DirectObject from direct.task import Task from direct.actor.Actor import Actor #for Pandai from panda3d.ai import * class World(DirectObject): def __init__(self): base.disableMouse() base.cam.setPosHpr(0, 0, 55, 0, -90, 0) self.loadModels() self.setAI() def loadModels(self): # Seeker ralphStartPos = Vec3(-10, 0, 0) self.seeker = Actor("models/ralph", {"run":"models/ralph-run"}) self.seeker.reparentTo(render) self.seeker.setScale(0.5) self.seeker.setPos(ralphStartPos) # Target self.target = loader.loadModel("models/arrow") self.target.setColor(1, 0, 0) self.target.setPos(5, 0, 0) self.target.setScale(1) self.target.reparentTo(render) def setAI(self): #Creating AI World self.AIworld = AIWorld(render) self.AIchar = AICharacter("seeker",self.seeker, 100, 0.05, 5) self.AIworld.addAiChar(self.AIchar) self.AIbehaviors = self.AIchar.getAiBehaviors() self.AIbehaviors.seek(self.target) self.seeker.loop("run") #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") #to update the AIWorld def AIUpdate(self,task): self.AIworld.update() return Task.cont w = World() base.run() ``` -------------------------------- ### Building a wheel file using setup.py Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/troubleshooting.rst Building a .whl file for a pure-Python package using setup.py. This involves downloading the package, running ``python setup.py bdist_wheel``, and then adding ``-f path/to/directory/`` on a blank line to your ``requirements.txt`` pointing pip to the directory containing the .whl file. ```python python setup.py bdist_wheel ``` -------------------------------- ### Installing blend2bam using pip Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/converting-from-blender.rst Installs the blend2bam utility using pip, which is used to convert .blend files to .bam files for use in Panda3D. This command adds blend2bam to your Panda3D installation. ```python python -m pip install -U panda3d-blend2bam ``` -------------------------------- ### Creating and Starting a MopathInterval in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/intervals/motion-paths.rst This code snippet shows how to create and start a MopathInterval in Panda3D. It requires the motion path object, the NodePath to be affected, and an optional name. The interval is then started to initiate the motion. ```python myInterval = MopathInterval(myMotionPathName, myNodePath, name = "Name") myInterval.start() ``` -------------------------------- ### Getting Duration of an Interval in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/intervals/index.rst This code snippet shows how to get the length of the interval in seconds in Python. ```python interval.getDuration() ``` -------------------------------- ### Including Panda3D Plug-ins in Build Configuration (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This code snippet demonstrates how to include specific Panda3D plug-ins in the build configuration. It shows how to enable OpenGL rendering and OpenAL audio support by adding 'pandagl' and 'p3openal_audio' to the 'plugins' list. This configuration is essential for enabling graphics and audio functionality in a Panda3D application. ```python 'plugins': ['pandagl', 'p3openal_audio'] ``` -------------------------------- ### Installing panda3d-gltf using pip Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/gltf-files.rst This command installs the panda3d-gltf plugin using pip, which is required for high-quality glTF loading in Panda3D. ```python python -m pip install -U panda3d-gltf ``` -------------------------------- ### Main Function: Setting up Panda3D and Bullet Physics Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/physics/bullet/hello-world.rst This is the main function that initializes the Panda3D framework, sets up a window, creates a Bullet physics world, adds a static ground plane and a dynamic box with collision shapes, and runs the physics simulation in the main loop. It also loads a model for the box and attaches it to the box's NodePath. ```C++ int main(int argc, char *argv[]) { // All variables. PandaFramework framework; WindowFramework *window; NodePath camera; PT(AsyncTaskManager) task_mgr; // Init everything :D framework.open_framework(argc, argv); framework.set_window_title("Bullet Physics"); window = framework.open_window(); window->enable_keyboard(); window->setup_trackball(); camera = window->get_camera_group(); task_mgr = AsyncTaskManager::get_global_ptr(); // Make physics simulation. // Static world stuff. get_physics_world()->set_gravity(0, 0, -9.81f); PT(BulletPlaneShape) floor_shape = new BulletPlaneShape(LVecBase3(0, 0, 1), 1); PT(BulletRigidBodyNode) floor_rigid_node = new BulletRigidBodyNode("Ground"); floor_rigid_node->add_shape(floor_shape); NodePath np_ground = window->get_render().attach_new_node(floor_rigid_node); np_ground.set_pos(0, 0, -2); get_physics_world()->attach(floor_rigid_node); // Dynamic world stuff. PT(BulletBoxShape) box_shape = new BulletBoxShape(LVecBase3(0.5, 0.5, 0.5)); PT(BulletRigidBodyNode) box_rigid_node = new BulletRigidBodyNode("Box"); box_rigid_node->set_mass(1.0f); // Gravity affects this rigid node. box_rigid_node->add_shape(box_shape); NodePath np_box = window->get_render().attach_new_node(box_rigid_node); np_box.set_pos(0, 0, 2); get_physics_world()->attach(box_rigid_node); NodePath np_box_model = window->load_model(framework.get_models(), "models/box"); np_box_model.set_pos(-0.5,-0.5,-0.5); np_box.flatten_light(); np_box_model.reparent_to(np_box); PT(GenericAsyncTask) task; task = new GenericAsyncTask("Scene update", &update_scene, nullptr); task_mgr->add(task); framework.main_loop(); framework.close_framework(); return (0); } ``` -------------------------------- ### Getting Playback Rate in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get a sound's playback rate using the get_play_rate() method. ```cpp mySound->get_play_rate(); ``` -------------------------------- ### Importing DirectStart and running the application in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/reference/direct.directbase.DirectStart.rst This code snippet demonstrates how to import the DirectStart module, which automatically instantiates ShowBase, and then runs the application using base.run(). This approach is suitable for quick prototyping but is deprecated for application development. ```python import direct.directbase.DirectStart base.run() ``` -------------------------------- ### Getting Playback Rate in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get a sound's playback rate using the getPlayRate() method. ```python mySound.getPlayRate() ``` -------------------------------- ### Getting Sound Length in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get the length of a sound file in seconds using the length() method. ```cpp mySound->length(); ``` -------------------------------- ### Specifying Panda3D Dependency in requirements.txt Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This example shows how to specify a Panda3D dependency in a requirements.txt file, indicating that a release of Panda3D 1.10 of at least 1.10.9 is required. This file is used by pip to fetch the necessary dependencies for building the application. ```text panda3d~=1.10.9 ``` -------------------------------- ### Specifying Target Platforms for Panda3D Build (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This code snippet shows how to specify the target platforms for a Panda3D build using platform tags. It sets the 'platforms' list to include 64-bit Linux, macOS, and Windows, targeting specific versions of each operating system. This is useful for ensuring compatibility with different environments. ```python 'platforms': ['manylinux1_x86_64', 'macosx_10_6_x86_64', 'win_amd64'] ``` -------------------------------- ### Getting Sound Length in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get the length of a sound file in seconds using the length() method. ```python mySound.length() ``` -------------------------------- ### Getting Current Playback Time in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get the current playback time of a sound in seconds using the get_time() method. ```cpp mySound->get_time(); ``` -------------------------------- ### Linking with GCC/Clang Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/running-your-program.rst Links the object file to create an executable, specifying the Panda3D libraries to link against. Replace `{panda3dlibs}` with the actual path to the Panda3D libraries. ```bash g++ filename.o -o filename -L{panda3dlibs} -lp3framework -lpanda -lpandafx -lpandaexpress -lp3dtoolconfig -lp3dtool -lp3direct ``` -------------------------------- ### Getting Current Playback Time in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/manipulating-sounds.rst This code snippet shows how to get the current playback time of a sound in seconds using the getTime() method. ```python mySound.getTime() ``` -------------------------------- ### Running Python with optimization flags Source: https://github.com/panda3d/panda3d-docs/blob/1.10/more-resources/faq.rst These commands show how to run Python with optimization flags to generate .pyo files instead of .pyc files. -O removes assert statements, and -OO removes docstrings. ```bash python -O file.py python -OO file.py ``` -------------------------------- ### Getting Current Time of an Interval in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/intervals/index.rst This code snippet shows how to get the current elapsed time within the interval, since the beginning of the interval, in Python. ```python interval.getT() ``` -------------------------------- ### Initializing AI Server with ShowBase in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/networking/distributed/servers.rst This code snippet demonstrates how to initialize the AI server by setting the `simbase` global variable to a ShowBase instance and creating an AI repository instance. It requires the `builtins` module and a ShowBase instance named `base`, as well as a custom AI repository class `MyAIRepository`. The `air` attribute is then assigned to the `simbase` instance. ```python builtins.simbase = base air = MyAIRepository() simbase.air = air ``` -------------------------------- ### Build HTML Documentation with Make Source: https://github.com/panda3d/panda3d-docs/blob/1.10/README.md This command builds the Panda3D documentation in HTML format using the Sphinx build system. The resulting HTML files are placed in the `_build/html` directory. ```Makefile make html ``` -------------------------------- ### PGButton Callback Function Example - C++ Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/index.rst This snippet provides an example of a callback function that is executed when a PGButton is clicked. It receives the event and button data, allowing you to perform custom actions. ```cpp static void GUI_Callback_Button_Clicked(const Event *ev, void *data) { PGButton *button = (PGButton *)data; // Your action here printf("%s has been pressed.\n", button->get_name().c_str()); } ``` -------------------------------- ### Bullet Debug Node Example in C++ Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/physics/bullet/debug-renderer.rst This C++ code snippet provides an example of how to use the BulletDebugNode. It is based on Python sources, Panda Reference, and the Panda Manual. ```cpp // Bullet Debug Node Example. // The following example is done from Python sources, Panda Reference and Panda Manual, // for more information, visit Panda3D and/or Bullet physics web site. // Compiling and Linking documentation and notes are not ``` -------------------------------- ### Collision Handler Event Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/collision-detection/event-example.rst This Python code demonstrates how to use collision handler events in Panda3D. It shows how to set up collision detection and handle events triggered by collisions. ```python from panda3d.core import CollisionTraverser, CollisionNode, CollisionTube from panda3d.core import CollisionHandlerEvent, CollisionHandlerQueue from panda3d.core import Point3 from direct.showbase.ShowBase import ShowBase class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Create a traverser that will handle the collisions. self.cTrav = CollisionTraverser() # Create a collision node. self.cNode = CollisionNode('myColNode') self.cNodePath = self.render.attachNewNode(self.cNode) self.cNodePath.show() # Create a collision tube. self.cTube = CollisionTube(0, 0, 0, 1, 0, 0, 1) self.cNode.addSolid(self.cTube) # Create a collision handler event. self.cHandler = CollisionHandlerEvent() self.cHandler.addInPattern('myColNode-into-%in') self.cHandler.addOutPattern('myColNode-out-%in') # Traverse the scene graph. self.cTrav.addCollider(self.cNodePath, self.cHandler) # Accept the events. self.accept('myColNode-into-floor', self.onCollision) self.accept('myColNode-out-floor', self.onCollisionOut) # Load the environment model. self.environ = self.loader.loadModel("models/environment") self.environ.reparentTo(self.render) self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) # Create a floor. self.floor = self.loader.loadModel("models/plane") self.floor.reparentTo(self.render) self.floor.setScale(10, 10, 10) self.floor.setPos(0, 0, -2) self.floor.setName("floor") self.floor.setCollideMask(1) def onCollision(self, entry): print("Collision!") def onCollisionOut(self, entry): print("Collision Out!") app = MyApp() app.run() ``` -------------------------------- ### Initializing DirectOptionMenu with Items and Callback - Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directoptionmenu.rst This example demonstrates how to create a DirectOptionMenu with a list of items, an initial selection, and a callback function that updates a text object when an item is selected. It showcases the basic usage of the DirectOptionMenu for creating interactive menus in Panda3D. ```python import direct.directbase.DirectStart from direct.gui.OnscreenText import OnscreenText from direct.gui.DirectGui import * from panda3d.core import * # Add some text bk_text = "DirectOptionMenu Demo" textObject = OnscreenText(text=bk_text, pos=(0.85, 0.85), scale=0.07, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) # Add some text output = "" textObject = OnscreenText(text=output, pos=(0.95, -0.95), scale=0.07, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) # Callback function to set text def itemSel(arg): output = "Item Selected is: " + arg textObject.setText(output) # Create a frame menu = DirectOptionMenu(text="options", scale=0.1, command=itemSel, items=["item1", "item2", "item3"], initialitem=2, highlightColor=(0.65, 0.65, 0.65, 1)) # Run the tutorial base.run() ``` -------------------------------- ### Delaying Interval Start with doMethodLater in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/more-resources/faq.rst This code snippet demonstrates how to use taskMgr.doMethodLater() to delay the start of an interval until the next frame. This is useful for scheduling tasks that need to be executed after a certain delay. ```python taskMgr.doMethodLater(0, lambda task, posival=posival: posival.start(), 'startInterval') ``` -------------------------------- ### Adding use_optimized_wheels to setup.py Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/troubleshooting.rst Adding 'use_optimized_wheels': False to setup.py to use a non-optimized build of Panda3D. This can be done by adding ``'use_optimized_wheels': False`` to ``setup.py``. ```python 'use_optimized_wheels': False ``` -------------------------------- ### Posing an Actor at a Specific Frame Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/models-and-actors/actor-animations.rst The `pose` method allows setting the actor to a specific frame of the animation. Frames are numbered starting from 0. This method does not automatically set the starting frame for the next animation. ```python actor.pose('Animation Name', FrameNumber) ``` -------------------------------- ### Importing DirectStart for Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/gui/directgui/directradiobutton.rst This code snippet imports the DirectStart module, which is essential for initializing and running a Panda3D application. It provides the necessary base functionality for creating a 3D environment and handling user input. ```python import direct.directbase.DirectStart ``` -------------------------------- ### Starting Smooth Movement Task in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/networking/distributed/distributed-smooth-node.rst This method starts the underlying task that handles the smooth positioning logic. While the task is running, directly positioning or lerping the node is not possible, as the update task will overwrite it. ```python DistributedSmoothNode.startSmooth() ``` -------------------------------- ### Initializing ShowBase and Running the Application in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/reference/builtins.rst This code snippet demonstrates how to initialize the ShowBase class, which sets up the Panda3D environment, and then starts the application's main loop. It requires importing ShowBase from direct.showbase.ShowBase and calling the ShowBase() constructor, followed by base.run(). ```python from direct.showbase.ShowBase import ShowBase base = ShowBase() base.run() ``` -------------------------------- ### Loading a Sound in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/audio/loading-playing-sounds-music.rst Loads a sound file using the loader class in Python. Requires a ShowBase instance and the path to the sound file. Returns an AudioSound object. ```python base = ShowBase() mySound = base.loader.loadSfx("path/to/sound_file.ogg") ``` -------------------------------- ### ODE Falling Boxes Example - Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/physics/ode/collision-detection.rst This code provides a complete example of simulating falling boxes in ODE. It sets up the physics world, creates boxes with random positions and orientations, and simulates their collision with the floor. ```Python from direct.directbase import DirectStart from panda3d.ode import OdeWorld, OdeSimpleSpace, OdeJointGroup from panda3d.ode import OdeBody, OdeMass, OdeBoxGeom, OdePlaneGeom from panda3d.core import BitMask32, CardMaker, Vec4, Quat from random import randint, random # Setup our physics world world = OdeWorld() world.setGravity(0, 0, -9.81) # The surface table is needed for autoCollide world.initSurfaceTable(1) world.setSurfaceEntry(0, 0, 150, 0.0, 9.1, 0.9, 0.00001, 0.0, 0.002) # Create a space and add a contactgroup to it to add the contact joints space = OdeSimpleSpace() space.setAutoCollideWorld(world) contactgroup = OdeJointGroup() space.setAutoCollideJointGroup(contactgroup) # Load the box box = loader.loadModel("box") # Make sure its center is at 0, 0, 0 like OdeBoxGeom box.setPos(-.5, -.5, -.5) box.flattenLight() # Apply transform box.setTextureOff() # Add a random amount of boxes boxes = [] for i in range(randint(15, 30)): # Setup the geometry boxNP = box.copyTo(render) boxNP.setPos(randint(-10, 10), randint(-10, 10), 10 + random()) boxNP.setColor(random(), random(), random(), 1) boxNP.setHpr(randint(-45, 45), randint(-45, 45), randint(-45, 45)) # Create the body and set the mass boxBody = OdeBody(world) M = OdeMass() M.setBox(50, 1, 1, 1) ``` -------------------------------- ### Single-File Cg Shader Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/shaders/shader-basics.rst This example demonstrates a basic Cg shader in a single file that preserves vertex position but swaps the red and green color channels. It defines a vertex shader (vshader) and a fragment shader (fshader). ```glsl //Cg void vshader(float4 vtx_position : POSITION, float4 vtx_color: COLOR, out float4 l_position : POSITION, out float4 l_color0 : COLOR0, uniform float4x4 mat_modelproj) { l_position = mul(mat_modelproj, vtx_position); l_color0 = vtx_color; } void fshader(float4 l_color0 : COLOR0, out float4 o_color : COLOR) { o_color = l_color0.grba; } ``` -------------------------------- ### Setting GUI Application Icons in setup.py (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/distribution/building-binaries.rst This code snippet demonstrates how to modify the setup.py file to specify custom icons for a GUI application in Panda3D. It defines the 'gui_apps' and 'icons' dictionaries, linking the application name ('asteroids') to its main script and a list of icon files in various resolutions. Panda3D 1.10.4 or later is required. ```python "gui_apps": { "asteroids": "src/main.py", }, "icons": { # The key needs to match the key used in gui_apps/console_apps. # Alternatively, use \"*\" to set the icon for all apps. "asteroids": ["icon-256.png", "icon-128.png", "icon-48.png", "icon-32.png", "icon-16.png"], }, ``` -------------------------------- ### Initializing Spotlight in Panda3D (Python) Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/render-attributes/lighting.rst This code snippet demonstrates how to create a spotlight, set its color, define its lens, position it in the scene, and make it point at an object. Spotlights provide focused illumination within a field of view. ```python slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(10, 20, 0) slnp.lookAt(myObject) render.setLight(slnp) ``` -------------------------------- ### GLSL Fragment Shader Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/shaders/shader-basics.rst This is an example of a GLSL fragment shader that samples a texture and swaps the red and blue color channels. It uses GLSL version 150 and takes a 2D texture sampler and texture coordinates as input. ```glsl #version 150 uniform sampler2D p3d_Texture0; // Input from vertex shader in vec2 texcoord; // Output to the screen out vec4 p3d_FragColor; void main() { vec4 color = texture(p3d_Texture0, texcoord); p3d_FragColor = color.bgra; } ``` -------------------------------- ### GLSL Vertex Shader Example Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/shaders/shader-basics.rst This is an example of a GLSL vertex shader that transforms vertex positions and passes texture coordinates to the fragment shader. It uses GLSL version 150 and takes a model-view-projection matrix and vertex position as input. ```glsl #version 150 // Uniform inputs uniform mat4 p3d_ModelViewProjectionMatrix; // Vertex inputs in vec4 p3d_Vertex; in vec2 p3d_MultiTexCoord0; // Output to fragment shader out vec2 texcoord; void main() { gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex; texcoord = p3d_MultiTexCoord0; } ``` -------------------------------- ### Creating a Display Region Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/rendering-process/display-regions.rst Creates a DisplayRegion within a window. The first example creates a region that fills the entire window. The second example specifies the size and placement of the DisplayRegion within the window, with coordinates ranging from 0 to 1. ```cpp PT(DisplayRegion) region = win.make_display_region(); PT(DisplayRegion) region = win.make_display_region(left, right, bottom, top); ``` -------------------------------- ### Instantiating ShowBase directly in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/reference/direct.directbase.DirectStart.rst This code snippet shows the recommended way to instantiate ShowBase directly, which is the preferred approach for application development since Panda3D 1.9. It imports ShowBase from direct.showbase.ShowBase and creates an instance named base. ```python from direct.showbase.ShowBase import ShowBase base = ShowBase() ``` -------------------------------- ### Creating a Display Region Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/rendering-process/display-regions.rst Creates a DisplayRegion within a window. The first example creates a region that fills the entire window. The second example specifies the size and placement of the DisplayRegion within the window, with coordinates ranging from 0 to 1. ```python region = win.makeDisplayRegion() region = win.makeDisplayRegion(left, right, bottom, top) ``` -------------------------------- ### Displaying Maya2egg Help Source: https://github.com/panda3d/panda3d-docs/blob/1.10/pipeline/converting-from-maya.rst This command displays a complete list of options available for the maya2egg tool. It's useful for understanding all the available functionalities and parameters for exporting models and animations from Maya. ```none maya2egg -h ``` -------------------------------- ### Setting Background Color and Camera in Panda3D Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/shaders/cg-shader-tutorial/part-2.rst This Python script sets the background color to black, disables mouse control, and adjusts the near and far clipping planes of the camera. It initializes the Panda3D environment and prepares it for rendering with the loaded shader. ```python #Lesson2.py import sys import direct.directbase.DirectStart base.setBackgroundColor(0.0, 0.0, 0.0) base.disableMouse() base.camLens.setNearFar(1.0, 50.0) ``` -------------------------------- ### Demonstrating setColor and setColorScale in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/render-attributes/tinting-and-recoloring.rst This Python code loads three instances of a 3D model with vertex colors, then applies setColor to one and setColorScale to another, demonstrating the difference between recoloring and tinting. It requires the direct.directbase.DirectStart and panda3d.core modules. ```python import direct.directbase.DirectStart from panda3d.core import ColorAttrib # Load three copies of Nik's dragon, which has vertex colors. model1 = loader.loadModel("nik-dragon") model2 = loader.loadModel("nik-dragon") model3 = loader.loadModel("nik-dragon") # Put them in the scene. model1.reparentTo(render) model2.reparentTo(render) model3.reparentTo(render) # Arrange them left-to-right model1.setPos(-10,50,0) model2.setPos( 0,50,0) model3.setPos( 10,50,0) # Model 1 will be left alone, so you can see the original. # Model 2 will be recolored light blue. # Model 3 will be tinted light blue. model2.setColor(0.6, 0.6, 1.0, 1.0) model3.setColorScale(0.6, 0.6, 1.0, 1.0) base.run() ``` -------------------------------- ### Running the executable Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/running-your-program.rst Runs the compiled executable. ```bash ./filename ``` -------------------------------- ### Starting a Debugging Session with pdb Source: https://github.com/panda3d/panda3d-docs/blob/1.10/debugging/python-debugger.rst This code snippet demonstrates how to start a debugging session using the pdb module. It imports the pdb module and then uses the pdb.run() function to execute a function from another module under the debugger's control. ```python import pdb import pdb.run('mymodule.test()') ``` -------------------------------- ### Loading and Animating the Panda Model in Python Source: https://github.com/panda3d/panda3d-docs/blob/1.10/introduction/tutorial/loading-and-animating-the-panda-model.rst This Python code snippet demonstrates how to load an animated model using the Actor class in Panda3D and start the walk animation. It uses the Actor class for animated models and the loop method to start the animation. ```python from direct.actor.Actor import Actor from direct.showbase.ShowBase import ShowBase class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Load the environment model. self.scene = self.loader.loadModel("models/environment") # Reparent the model to render. self.scene.reparentTo(self.render) # Apply scale and position the model. self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 42, 0) # Load the panda actor, and loop its animation. self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) self.pandaActor.loop("walk") app = MyApp() app.run() ``` -------------------------------- ### Mounting a Webserver Directory - C++ Source: https://github.com/panda3d/panda3d-docs/blob/1.10/programming/advanced-loading/multifiles.rst Mounts a directory from a web server into Panda3D's virtual file system. This allows loading assets directly from the web server. Requires the panda3d core library. ```cpp VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->mount(new VirtualFileMountHTTP("http://myserver/mydir"), "/mydir", 0); get_model_path().append_directory("/mydir"); ```