### Python Navmesh Pathfinding Examples Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Provides Python examples demonstrating how to create a navigation mesh from raw data and find paths between points. Includes an example using data from a text file. ```python # Placeholder for navmesh_examples.py content # This script shows navmesh creation from raw data and pathfinding. ``` -------------------------------- ### Python Graph and A* Pathfinding Examples Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Contains Python examples for creating graphs and utilizing the A* algorithm to find the shortest path. Includes plotting the results using Matplotlib. ```python # Placeholder for graph_examples.py content # This script demonstrates graph creation and A* pathfinding. ``` -------------------------------- ### Agent Management and Simulation Setup (Python) Source: https://context7.com/tugcga/path-finder/llms.txt This Python snippet demonstrates the initial setup for agent management and simulation using the `PathFinder` class. It involves creating a simple navigation mesh and initializing the `PathFinder` object with agent-related parameters. This serves as a base for adding agents, setting destinations, and simulating movement with collision avoidance. ```python from pathfinder import PathFinder import time # Create simple square navigation mesh vertices = [ (-4.0, 0.0, -4.0), (4.0, 0.0, -4.0), (4.0, 0.0, 4.0), (-4.0, 0.0, 4.0) ] polygons = [[0, 1, 2, 3]] pathfinder = PathFinder(vertices, polygons, agent_radius=0.5) ``` -------------------------------- ### Example Navigation Mesh Data Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Example arrays demonstrating how to define navigation mesh vertices and polygons for creating a PathFinder or Navmesh object. This example shows a 6-gon defined as two 4-sided polygons. ```AssemblyScript let vertices = [ 1.0, 0.0, 0.0, // the first vertex 0.5, 0.0, -1.0, // the second vertex -0.5, 0.0, -1.0, // and so on -1.0, 0.0, 0.0, -0.5, 0.0, 1.0, 0.5, 0.0, 1.0]; let polygons = [0, 1, 2, 3, // the first polygon 0, 3, 4, 5]; //the second polygon let sizes = [4, 4]; // because both polygons are 4-sided ``` -------------------------------- ### Install and Use Python Path Finder Module Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Installs the pynavmesh library and demonstrates how to bake a navigation mesh using the NavmeshBaker class. This involves creating a baker object, adding geometry data (vertices and polygons), and initiating the baking process. ```python pip install pynavmesh from pathfinder import navmesh_baker as nmb # create baker object baker = nmb.NavmeshBaker() # add geometry, for example a simple plane # the first array contains vertex positions, the second array contains polygons of the geometry baker.add_geometry([(-4.0, 0.0, -4.0), (-4.0, 0.0, 4.0), (4.0, 0.0, 4.0), (4.0, 0.0, -4.0)], [[0, 1, 2, 3]]) # bake navigation mesh baker.bake() ``` -------------------------------- ### Python Examples for Navmesh Generation Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Demonstrates loading geometry into a baker object and generating a navigation mesh using Python. This involves adding polygonal data and baking the mesh. ```python from path_finder.navmesh_baker import NavmeshBaker baker = NavmeshBaker() # Assuming vertices and polygons are defined # baker.add_geometry(vertices, polygons) baker.bake() vertices, polygons = baker.get_polygonization() baker.save_to_binary('navmesh.bin') baker.save_to_text('navmesh.txt') ``` -------------------------------- ### Python RVO Simulation Examples Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Illustrates how to use raw Reciprocal Velocity Obstacles (RVO) simulation and its integration as a sub-object within the PathFinder. ```python # Placeholder for rvo_examples.py content # This script demonstrates RVO simulation usage. ``` -------------------------------- ### Use Navmesh Module for Pathfinding (AssemblyScript) Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Example of how to import and use the navigation mesh module to find a path. It involves creating a navigation mesh from vertex and polygon data, and then searching for a path between two points. ```typescript import * as navmesh_exports from "./navmesh.js"; const vertices = [1.0, 0.0, 0.0, 0.5, 0.0, -1.0, -0.5, 0.0, -1.0, -1.0, 0.0, 0.0, -0.5, 0.0, 1.0, 0.5, 0.0, 1.0]; const polygons = [0, 1, 2, 3, 0, 3, 4, 5]; const sizes = [4, 4]; const navmesh_ptr = navmesh_exports.create_navmesh(vertices, polygons, sizes); const path = navmesh_exports.navmesh_search_path(navmesh_ptr, 0.5, 0.0, 0.5, -0.5, 0.0, -0.5); ``` -------------------------------- ### Navigation Mesh Sampling and Raycasting with Pathfinder Source: https://context7.com/tugcga/path-finder/llms.txt Shows how to load a navigation mesh from a binary file, create a Pathfinder instance, and use the 'sample' method to find the closest point on the navmesh to a given query point. ```python import pathfinder as pf # Load navigation mesh vertices, polygons = pf.read_from_binary("navmesh.nm") pathfinder = pf.PathFinder(vertices, polygons) # Sample: find closest point on navmesh query_point = (1.5, 2.0, 3.2) closest_point = pathfinder.sample(query_point, is_slow=False) if closest_point: print(f"Query point: ({query_point[0]}, {query_point[1]}, {query_point[2]})") print(f"Closest navmesh point: ({closest_point[0]:.2f}, {closest_point[1]:.2f}, {closest_point[2]:.2f})") # Calculate distance dx = query_point[0] - closest_point[0] dy = query_point[1] - closest_point[1] dz = query_point[2] - closest_point[2] distance = (dx*dx + dy*dy + dz*dz) ** 0.5 print(f"Distance to navmesh: {distance:.2f}") else: print("Failed to find closest point on navmesh") ``` -------------------------------- ### Add and Manage Agents with Pathfinder Source: https://context7.com/tugcga/path-finder/llms.txt Demonstrates adding multiple agents, setting their destinations, running a simulation loop, and retrieving agent data like positions and paths. It also shows how to delete agents and check agent counts. ```python agent_id_1 = pathfinder.add_agent( position=(2.0, 0.0, 2.0), radius=0.5, speed=2.0 ) agent_id_2 = pathfinder.add_agent( position=(-2.0, 0.0, -2.0), radius=0.4, speed=1.5 ) if agent_id_1 >= 0: print(f"Agent 1 created with ID: {agent_id_1}") # Set destination for agent pathfinder.set_agent_destination(agent_id_1, (-2.0, 0.0, -2.0)) if agent_id_2 >= 0: print(f"Agent 2 created with ID: {agent_id_2}") pathfinder.set_agent_destination(agent_id_2, (2.0, 0.0, 2.0)) # Simulation loop for step in range(50): # Update pathfinder (calculates velocities and moves agents) pathfinder.update() time.sleep(0.1) # 100ms between updates # Get agent positions positions = pathfinder.get_all_agents_positions() activities = pathfinder.get_all_agents_activities() if step % 10 == 0: print(f"\nStep {step}:") for idx, agent_id in enumerate(pathfinder.get_agents_id()): pos = positions[idx] active = activities[idx] print(f" Agent {agent_id}: pos=({pos[0]:.2f}, {pos[1]:.2f}), active={active}") # Get final agent positions final_position_1 = pathfinder.get_agent_position(agent_id_1) print(f"\nAgent 1 final position: ({final_position_1[0]:.2f}, {final_position_1[1]:.2f})") # Get agent paths path_1 = pathfinder.get_agent_path(agent_id_1) print(f"Agent 1 path has {len(path_1)} waypoints") # Delete agent pathfinder.delete_agent(agent_id_2) print(f"Deleted agent {agent_id_2}") print(f"Active agents: {pathfinder.get_active_agents_count()}/{pathfinder.get_agents_count()}") ``` -------------------------------- ### Pathfinder: Get Navmesh Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves the navigation mesh subcomponent of the pathfinder object. Returns null if the navigation mesh is not defined. ```c pathfinder_get_navmesh(pathfinder: PathFinder): Navmesh | null ``` -------------------------------- ### PathFinder Initialization and Path Search Source: https://context7.com/tugcga/path-finder/llms.txt This section covers initializing the `PathFinder` object with a navigation mesh and performing path searches between two points. It also shows how to load meshes from files and use optional parameters for pathfinding accuracy. ```APIDOC ## PathFinder Initialization and Path Search ### Description Initialize the pathfinding system with a navigation mesh and then use it to find paths between specified start and end points. The initialization involves loading mesh data and configuring agent and simulation parameters. Path searches can be refined using a length limit. ### Method Instantiate `pathfinder.PathFinder` and call its `search_path` method. ### Endpoint N/A (Library functions) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import pathfinder as pf # Load navigation mesh from file vertices, polygons = pf.read_from_binary("navmesh.nm") # Or load from text file # vertices, polygons = pf.read_from_text("navmesh.txt") # Create PathFinder object pathfinder = pf.PathFinder( vertices=vertices, polygons=polygons, neighbor_dist=1.5, # Search distance for other agents max_neighbors=5, # Max neighbors for collision avoidance time_horizon=1.5, # Time horizon for agent collision time_horizon_obst=2.0, # Time horizon for obstacle collision max_speed=10.0, # Maximum agent speed agent_radius=0.2, # Default agent radius update_path_find=1.0, # Path recalculation interval (seconds) continuous_moving=False, # Keep moving after reaching target move_agents=True, # Update agent positions automatically snap_to_navmesh=False # Snap agents to navmesh surface ) # Search path between two points start = (-2.0, 0.0, -2.0) finish = (2.0, 0.0, 2.0) path = pathfinder.search_path(start, finish) if path: print(f"Found path with {len(path)} points:") for i, point in enumerate(path): print(f" Point {i}: ({point[0]:.2f}, {point[1]:.2f}, {point[2]:.2f})") else: print("No path found between start and finish") # Search with length limit for more accurate results path_accurate = pathfinder.search_path(start, finish, length_limit_coefficient=1.5) ``` ### Response #### Success Response (path found) - **path** (list of tuples) - A list of points (x, y, z) representing the path. #### Response Example ```json { "path": [ [-2.0, 0.0, -2.0], [-1.5, 0.0, -1.5], [2.0, 0.0, 2.0] ] } ``` #### Success Response (no path found) - **path** (empty list or None) - Indicates no path could be found. #### Response Example ```json { "path": [] } ``` ``` -------------------------------- ### Navmesh API - Get BVH Delta Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves the delta value used for constructing BVH structures within the navigation mesh. ```APIDOC ## navmesh_get_bvh_delta ### Description Returns the delta-value used for constructing the BVH (Bounding Volume Hierarchy) inside the navigation mesh. ### Method N/A (This appears to be a function call within a WASM context, not a typical HTTP API) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **navmesh** (Navmesh) - The navigation mesh object. ### Request Example ```javascript // Assuming 'navmesh' is a valid Navmesh object const currentBvhDelta = navmesh_get_bvh_delta(navmesh); console.log(`Current BVH delta: ${currentBvhDelta}`); ``` ### Response #### Success Response - **currentBvhDelta** (float) - The delta value used for BVH construction. #### Response Example ```json 0.1 ``` ``` -------------------------------- ### Initialize PathFinder and Search Paths (Python) Source: https://context7.com/tugcga/path-finder/llms.txt This Python snippet shows how to initialize the `PathFinder` object with a loaded navigation mesh and then search for paths between specified points. It requires a pre-baked navigation mesh file (binary or text). The output is a list of points representing the found path or a message indicating no path was found. ```python import pathfinder as pf # Load navigation mesh from file vertices, polygons = pf.read_from_binary("navmesh.nm") # Or load from text file # vertices, polygons = pf.read_from_text("navmesh.txt") # Create PathFinder object pathfinder = pf.PathFinder( vertices=vertices, polygons=polygons, neighbor_dist=1.5, # Search distance for other agents max_neighbors=5, # Max neighbors for collision avoidance time_horizon=1.5, # Time horizon for agent collision time_horizon_obst=2.0, # Time horizon for obstacle collision max_speed=10.0, # Maximum agent speed agent_radius=0.2, # Default agent radius update_path_find=1.0, # Path recalculation interval (seconds) continuous_moving=False, # Keep moving after reaching target move_agents=True, # Update agent positions automatically snap_to_navmesh=False # Snap agents to navmesh surface ) # Search path between two points start = (-2.0, 0.0, -2.0) finish = (2.0, 0.0, 2.0) path = pathfinder.search_path(start, finish) if path: print(f"Found path with {len(path)} points:") for i, point in enumerate(path): print(f" Point {i}: ({point[0]:.2f}, {point[1]:.2f}, {point[2]:.2f})") else: print("No path found between start and finish") # Search with length limit for more accurate results path_accurate = pathfinder.search_path(start, finish, length_limit_coefficient=1.5) ``` -------------------------------- ### Navigation Mesh File I/O with Pathfinder Source: https://context7.com/tugcga/path-finder/llms.txt Shows how to create, bake, save, and load navigation meshes using the pathfinder library. Supports both binary (recommended for production) and text (human-readable) formats for saving and loading. This functionality is useful for persisting and reusing navigation data. ```python import pathfinder as pf from pathfinder import navmesh_baker as nmb # Create and bake navigation mesh baker = nmb.NavmeshBaker() baker.add_geometry( [(-10.0, 0.0, -10.0), (-10.0, 0.0, 10.0), (10.0, 0.0, 10.0), (10.0, 0.0, -10.0)], [[0, 1, 2, 3]] ) baker.bake() # Save to binary format (recommended for production) baker.save_to_binary("level_navmesh.nm") print("Saved to binary format") # Save to text format (human-readable, for debugging) baker.save_to_text("level_navmesh.txt") print("Saved to text format") # Load from binary file vertices_bin, polygons_bin = pf.read_from_binary("level_navmesh.nm") print(f"Loaded from binary: {len(vertices_bin)} vertices, {len(polygons_bin)} polygons") # Load from text file vertices_txt, polygons_txt = pf.read_from_text("level_navmesh.txt") print(f"Loaded from text: {len(vertices_txt)} vertices, {len(polygons_txt)} polygons") # Create pathfinder from loaded data pathfinder_from_binary = pf.PathFinder(vertices_bin, polygons_bin) pathfinder_from_text = pf.PathFinder(vertices_txt, polygons_txt) # Test path search start = (-5.0, 0.0, -5.0) finish = (5.0, 0.0, 5.0) path_bin = pathfinder_from_binary.search_path(start, finish) path_txt = pathfinder_from_text.search_path(start, finish) print(f"Path from binary navmesh: {len(path_bin)} points") print(f"Path from text navmesh: {len(path_txt)} points") # Verify both produce same results assert len(path_bin) == len(path_txt), "Paths should be identical" print("Binary and text formats produce identical results") ``` -------------------------------- ### Pathfinder: Get RVO Simulator Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves the RVOSimulator for a given group within the navigation mesh. If the navigation mesh is not defined, the 'group' parameter should be 0. ```c pathfinder_get_rvo_simulator(pathfinder: PathFinder, group: i32): RVOSimulator | null ``` -------------------------------- ### Pathfinder: Get and Set Move Agents Parameter Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves and sets the 'move_agents' parameter for the PathFinder. This parameter likely determines if agents are allowed to move. ```c pathfinder_get_move_agents(pathfinder: PathFinder): bool pathfinder_set_move_agents(pathfinder: PathFinder, value: bool) ``` -------------------------------- ### Pathfinder Initialization and Usage in NodeJS Source: https://github.com/tugcga/path-finder/blob/main/rust/pathfinder/README.md Demonstrates how to import and use the Pathfinder module in NodeJS. It includes creating a new Pathfinder instance with mesh data (vertices and triangles) and then using it to search for a path or sample a point. ```javascript const wasm_module = require("./pathfinder.js"); const pathfinder = new wasm_module.Pathfinder( [0.0, 0.0, 0.0, // vertex 0 4.0, 0.0, 0.0, // vertex 1 4.0, 0.0, 4.0, // vertex 2 0.0, 0.0, 4.0], //vertex 3 [0, 1, 2, // triangle 0 0, 2, 3]); // triangle 1 const path = pathfinder.search_path(0.0, 0.0, 0.0, 3.0, 0.0, 3.0); const s = pathfinder.sample(2.0, 2.0, 2.0); ``` -------------------------------- ### Pathfinder: Get and Set Use Normals Parameter Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves and sets the 'use_normals' parameter for the PathFinder. This parameter likely affects how surface normals are utilized in pathfinding calculations. ```c pathfinder_get_use_normals(pathfinder: PathFinder): bool pathfinder_set_use_normals(pathfinder: PathFinder, value: bool) ``` -------------------------------- ### Search Path using PathFinder Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Searches for a path between a start and finish point within the navigation mesh. The function returns a sequence of corners defining the path segments. ```python path = pathfinder.search_path(start, finish) ``` -------------------------------- ### Get Polygonal Description of Mesh using Baker Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Retrieves the polygonal description (vertices and polygons) of a mesh using the baker module. This is a foundational step before generating a navigation mesh. ```python vertices, polygons = baker.get_polygonization() ``` -------------------------------- ### Navmesh API - Search Path Batch Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Finds shortest paths for multiple start-end point pairs efficiently. ```APIDOC ## navmesh_search_path_batch ### Description This function is similar to `navmesh_search_path` but allows finding paths for multiple pairs of start-end points in a single call. The input `coordinates` array should contain coordinates in the order: first three values for the first start point, next three for the first end point, and so on. The output array contains the number of points for each path followed by the path coordinates. ### Method N/A (This appears to be a function call within a WASM context, not a typical HTTP API) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **navmesh** (Navmesh) - The navigation mesh object. - **coordinates** (StaticArray) - A flattened array of start and end point coordinates for multiple paths. ### Request Example ```javascript // Assuming 'navmesh' is a valid Navmesh object const pathCoordinates = [ 1.0, 2.0, 3.0, // First start point 10.0, 11.0, 12.0, // First end point 4.0, 5.0, 6.0, // Second start point 15.0, 16.0, 17.0 // Second end point ]; const results = navmesh_search_path_batch(navmesh, pathCoordinates); console.log('Batch path results:', results); ``` ### Response #### Success Response - **results** (StaticArray) - An array containing the number of points for each path, followed by the coordinates of each path. #### Response Example ```json [5, 1.0, 2.0, 3.0, 5.5, 6.0, 6.5, 10.0, 11.0, 12.0, 7, 4.0, 5.0, 6.0, 8.0, 9.0, 10.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0] ``` ``` -------------------------------- ### Pathfinder: Get and Set Snap Agents Parameter Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves and sets the 'snap_agents' parameter for the PathFinder. This parameter may control whether agents snap to the navigation mesh polygons. ```c pathfinder_get_snap_agents(pathfinder: PathFinder): bool pathfinder_set_snap_agents(pathfinder: PathFinder, value: bool) ``` -------------------------------- ### WebAssembly Pathfinder Usage in JavaScript Source: https://context7.com/tugcga/path-finder/llms.txt Demonstrates how to import and use compiled WebAssembly modules for pathfinding in JavaScript. It covers creating a pathfinder instance, adding agents, setting destinations, simulating movement, and retrieving path information. Dependencies include the compiled WASM module. ```javascript // Import the WASM module import * as pathfinder_exports from "./pathfinder.wasm"; // Define navigation mesh data const vertices = new Float32Array([ 1.0, 0.0, 0.0, 0.5, 0.0, -1.0, -0.5, 0.0, -1.0, -1.0, 0.0, 0.0, -0.5, 0.0, 1.0, 0.5, 0.0, 1.0 ]); const polygons = new Int32Array([0, 1, 2, 3, 0, 3, 4, 5]); const sizes = new Int32Array([4, 4]); // Create PathFinder object (returns pointer) const pathfinder_ptr = pathfinder_exports.create_pathfinder(vertices, polygons, sizes); // Add agent at position (2.0, 0.0, 2.0) with radius 0.5 and speed 2.0 const agent_id = pathfinder_exports.pathfinder_add_agent( pathfinder_ptr, 2.0, 0.0, 2.0, // position 0.5, // radius 2.0 // speed ); console.log("Created agent with ID:", agent_id); // Set agent destination const success = pathfinder_exports.pathfinder_set_agent_destination( pathfinder_ptr, agent_id, -2.0, 0.0, -2.0 // destination position ); if (success) { console.log("Destination set successfully"); } // Simulation loop for (let step = 0; step < 50; step++) { // Update simulation (0.1 second delta time) pathfinder_exports.pathfinder_update(pathfinder_ptr, 0.1); // Get agent position every 10 steps if (step % 10 === 0) { const position = pathfinder_exports.pathfinder_get_agent_position(pathfinder_ptr, agent_id); console.log(`Step ${step}: Agent at (${position[0].toFixed(2)}, ${position[1].toFixed(2)}, ${position[2].toFixed(2)})`); } } // Get agent path const path = pathfinder_exports.pathfinder_get_agent_path(pathfinder_ptr, agent_id); console.log("Agent path has", path.length / 3, "waypoints"); // Search path between two points const path_coords = pathfinder_exports.pathfinder_search_path( pathfinder_ptr, 0.5, 0.0, 0.5, // start -0.5, 0.0, -0.5 // finish ); console.log("Found path with", path_coords.length / 3, "points"); // Get all agents information const agent_count = pathfinder_exports.pathfinder_get_agents_count(pathfinder_ptr); const active_count = pathfinder_exports.pathfinder_get_active_agents_count(pathfinder_ptr); console.log(`Total agents: ${agent_count}, Active: ${active_count}`); ``` -------------------------------- ### Navmesh Baker: Get Navmesh Vertex Data Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves a plain float array containing the vertex coordinates of the baked navigation mesh. Returns an empty array if the navigation mesh has not been baked. ```c baker_get_navmesh_vertices(baker: NavmeshBaker): StaticArray ``` -------------------------------- ### Navmesh Baker: Get Navmesh Polygon Data Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves a plain integer array containing the vertex indices for each polygon in the baked navigation mesh. Returns an empty array if the navigation mesh has not been baked. ```c baker_get_navmesh_polygons(baker: NavmeshBaker): StaticArray ``` -------------------------------- ### Simulation Control Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Functions for controlling the simulation steps and querying visibility. ```APIDOC ## Simulation Control This section covers the API endpoints for controlling the simulation steps and querying visibility within the RVOSimulator. ### Do Step **Endpoint:** `rvo_do_step` **Description:** Updates the velocities and optionally the positions of all agents in the simulator. It calculates optimal velocities based on preferred velocities and updates agent positions if `move_agents` is true. **Parameters:** - `rvo` (RVOSimulator): The RVO simulator instance. - `delta_time` (f32): The time step for the simulation update. - `move_agents` (bool, optional): If true, agent positions are updated. Defaults to `true`. ### Query Visibility **Endpoint:** `rvo_query_visibility` **Description:** Checks if a target position is visible from a starting position, considering potential obstacles. **Parameters:** - `rvo` (RVOSimulator): The RVO simulator instance. - `start_x` (f32): The x-coordinate of the starting position. - `start_y` (f32): The y-coordinate of the starting position. - `end_x` (f32): The x-coordinate of the target position. - `end_y` (f32): The y-coordinate of the target position. - `radius` (f32): The radius to consider for visibility checks. **Returns:** - `bool`: `true` if the end position is visible from the start position, `false` otherwise. ``` -------------------------------- ### PathFinder Initialization Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Initializes a PathFinder object with configurable parameters for RVO simulation and navigation mesh properties. ```APIDOC ## PathFinder Initialization ### Description Creates a new pathfinder object. 'vertices' and 'polygons' define the navigation mesh and obstacles for RVO. Other parameters configure RVO behavior. If 'continuous_moving' is True, agents continuously move towards destinations. If 'move_agents' is False, agent positions are not updated directly by the update() method. If 'snap_to_navmesh' is True, agents are forced onto the navigation mesh after each simulation step. ### Method PathFinder(...) ### Parameters - **vertices** (Optional[List[Tuple[float, float, float]]]) - Used for navigation mesh. - **polygons** (Optional[List[List[int]]]) - Used for obstacles in RVO. - **neighbor_dist** (float) - Default: 1.5 - Distance for neighbor searching. - **max_neighbors** (int) - Default: 5 - Maximum number of neighbors to consider. - **time_horizon** (float) - Default: 1.5 - Time horizon for RVO calculations. - **time_horizon_obst** (float) - Default: 2.0 - Time horizon for obstacle avoidance. - **max_speed** (float) - Default: 10.0 - Maximum speed for agents. - **agent_radius** (float) - Default: 0.2 - Default radius for agents. - **update_path_find** (float) - Default: 1.0 - Interval for pathfinding updates. - **continuous_moving** (bool) - Default: False - If True, agents always attempt to move to destinations. - **move_agents** (bool) - Default: True - If True, agent positions are updated based on velocities. - **snap_to_navmesh** (bool) - Default: False - If True, agents are snapped to the navigation mesh. ### Request Example ```python pathfinder = PathFinder(vertices=[(0,0,0), (1,0,0), ...], polygons=[[0,1,2], ...]) ``` ### Response An initialized PathFinder object. ``` -------------------------------- ### Navmesh Baker: Get Navmesh Polygon Sizes Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Retrieves a plain integer array indicating the number of vertices for each polygon in the baked navigation mesh. Returns an empty array if the navigation mesh has not been baked. ```c baker_get_navmesh_sizes(baker: NavmeshBaker): StaticArray ``` -------------------------------- ### Agent Management and Simulation Source: https://context7.com/tugcga/path-finder/llms.txt This section describes how to manage agents within the simulation environment, including adding agents, setting their destinations, and enabling automatic movement and collision avoidance. ```APIDOC ## Agent Management and Simulation ### Description Add agents to the simulation, assign them destinations, and let the `PathFinder` manage their movement, including collision avoidance with other agents and static obstacles. The simulation can be configured to automatically update agent positions and handle path recalculations. ### Method Instantiate `pathfinder.PathFinder` and use its methods for agent management. ### Endpoint N/A (Library functions) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pathfinder import PathFinder import time # Create simple square navigation mesh vertices = [ (-4.0, 0.0, -4.0), (4.0, 0.0, -4.0), (4.0, 0.0, 4.0), (-4.0, 0.0, 4.0) ] polygons = [[0, 1, 2, 3]] pathfinder = PathFinder(vertices, polygons, agent_radius=0.5) # Add an agent (example - actual agent addition might be a method call) # agent_id = pathfinder.add_agent(start_position=(-3.0, 0.0, -3.0)) # Set a destination for the agent # pathfinder.set_agent_destination(agent_id, destination=(3.0, 0.0, 3.0)) # The simulation loop (if move_agents=True) would automatically update positions. # If move_agents=False, manual updates would be needed. # while True: # pathfinder.update_agents(time_step=0.1) # # Render or process agent positions... # time.sleep(0.1) ``` ### Response This section pertains to the internal state updates of agents managed by the `PathFinder`. Specific responses depend on the simulation's state and whether `move_agents` is enabled. Typically, agent positions are updated internally. #### Success Response (agent state updated) - **agent_positions** (dict) - Mapping of agent IDs to their current (x, y, z) coordinates. #### Response Example ```json { "agent_positions": { "agent_1": [1.2, 0.0, 1.5], "agent_2": [-0.5, 0.0, 2.1] } } ``` ``` -------------------------------- ### Build Navigation Mesh Baker Module with AssemblyScript Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md This command builds the 'baker.wasm' module using AssemblyScript. It exports functions and the runtime. The 'baker.wasm' module contains navigation mesh baking functionality. ```bash asc assembly/baker_api.ts --outFile build/baker.wasm --bindings esm --exportRuntime ``` -------------------------------- ### Insert Multiple Edges into RTree Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Efficiently inserts multiple edges into the RTree from a single, flat array of coordinates. Each set of four float values represents an edge's start and end points. Available in navmesh.wasm, pathfinder.wasm, and pathfinder_full.wasm. ```Rust rtree_insert_edges(tree: RTree, coordinates: Float32Array): void ``` -------------------------------- ### RVO Simulation for Collision Avoidance with Python Source: https://context7.com/tugcga/path-finder/llms.txt Implements RVO2 algorithm for collision avoidance without a navigation mesh. It sets up a simulator, adds agents and obstacles, and runs a simulation loop to calculate agent movements. ```python import pathfinder.pyrvo as rvo import random import math # Create RVO simulator simulator = rvo.create_simulator( neighbor_dist=1.0, # Max distance to consider neighbors max_neighbors=5, # Max neighbors per agent time_horizon=1.0, # Time horizon for agents time_horizon_obst=1.0, # Time horizon for obstacles radius=0.5, # Default agent radius max_speed=5.0 # Maximum agent speed ) # Add multiple agents at random positions agents_count = 100 for a in range(agents_count): position = (random.uniform(-5.0, 5.0), random.uniform(-5.0, 5.0)) rvo.add_agent(simulator, position) # Add circular obstacle obstacle_points = [] num_obstacle_points = 16 obstacle_radius = 2.0 for i in range(num_obstacle_points): angle = 2.0 * math.pi * i / num_obstacle_points obstacle_points.append( ( obstacle_radius * math.cos(angle), obstacle_radius * math.sin(angle) ) ) rvo.add_obstacle(simulator, obstacle_points) rvo.process_obstacles(simulator) # Define target for all agents target = (0.0, 0.0) # Simulation loop for step in range(100): # Set preferred velocities for each agent for a in range(agents_count): pos = rvo.get_agent_position(simulator, a) to_vector = (target[0] - pos[0], target[1] - pos[1]) to_length = math.sqrt(to_vector[0]**2 + to_vector[1]**2) if to_length > 1.0: to_vector = (to_vector[0] / to_length, to_vector[1] / to_length) rvo.set_agent_pref_velocity(simulator, a, to_vector) # Simulate one step with 0.1 second delta time rvo.simulate(simulator, 0.1, move_agents=True) # Get final positions for a in range(min(5, agents_count)): final_pos = rvo.get_agent_position(simulator, a) print(f"Agent {a}: ({final_pos[0]:.2f}, {final_pos[1]:.2f})") ``` -------------------------------- ### Graph Search using Dijkstra's Algorithm Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Performs a shortest path search on a given Graph from a start vertex to an end vertex using Dijkstra's algorithm. The function returns an array of vertex IDs representing the path. Available in navmesh.wasm, pathfinder.wasm, and pathfinder_full.wasm. ```Rust graph_search(graph: Graph, start_vertex: i32, end_vertex: i32): StaticArray ``` -------------------------------- ### Simulation Control and Status Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Functions for controlling and querying the state of the RVO simulation. `update_time` increments the internal timer, while `update` advances the simulation step, calculating new velocities and optionally updating agent positions. Functions are also provided to get the total and active agent counts, as well as the default agent radius. ```python pathfinder.update_time() pathfinder.update() pathfinder.get_agents_count() pathfinder.get_active_agents_count() pathfinder.get_default_agent_radius() ``` -------------------------------- ### NavmeshBaker API in Python Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Python code demonstrating the usage of the NavmeshBaker API for generating navigation meshes. Includes adding geometry, baking, retrieving polygonal descriptions, and saving to files. ```python from typing import List, Tuple from path_finder.navmesh_baker import NavmeshBaker # Create a baker object baker = NavmeshBaker() # Add input polygonal data # vertices: List[Tuple[float, float, float]] = [...] # polygons: List[List[int]] = [...] # baker.add_geometry(vertices, polygons) # Generate navigation mesh baker.bake() # Get polygonal description # baked_vertices, baked_polygons = baker.get_polygonization() # Save navigation mesh # baker.save_to_binary('navmesh.bin') # baker.save_to_text('navmesh.txt') ``` -------------------------------- ### Build Navmesh Module with AssemblyScript Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md This command builds the 'navmesh.wasm' module using AssemblyScript. It exports functions and the runtime. The 'navmesh.wasm' module contains graph and navigation mesh functionality. ```bash asc assembly/navmesh_api.ts --outFile build/navmesh.wasm --bindings esm --exportRuntime ``` -------------------------------- ### Navigation Mesh Baking Source: https://context7.com/tugcga/path-finder/llms.txt This section details how to create and bake navigation meshes from input geometry using the `NavmeshBaker` class. It includes adding geometry, setting baking parameters, and saving the baked mesh. ```APIDOC ## Navigation Mesh Baking ### Description Create and bake navigation meshes from input geometry. This process involves adding geometric data, configuring various baking parameters to define walkable areas and mesh properties, and finally generating the navigation mesh. ### Method Instantiate `pathfinder.navmesh_baker.NavmeshBaker` and call its methods. ### Endpoint N/A (Library functions) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pathfinder import navmesh_baker as nmb # Create baker object baker = nmb.NavmeshBaker() # Add geometry (vertices and polygons) # Plane geometry baker.add_geometry( [(-4.0, 0.0, -4.0), (-4.0, 0.0, 4.0), (4.0, 0.0, 4.0), (4.0, 0.0, -4.0)], [[0, 1, 2, 3]] ) # Cube geometry baker.add_geometry( [(-1.0, 0.0, -1.0), (-1.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 0.0, -1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -1.0)], [[0, 3, 2, 1], [2, 6, 5, 1], [4, 5, 6, 7], [0, 4, 7, 3], [2, 3, 7, 6], [0, 1, 5, 4]] ) # Bake with parameters is_bake = baker.bake( cell_size=0.3, # Voxel size for rasterization cell_height=0.2, # Voxel height agent_height=2.0, # Agent height agent_radius=0.6, # Agent radius (affects mesh boundaries) agent_max_climb=0.9, # Maximum climbable height agent_max_slope=45.0, # Maximum walkable slope in degrees region_min_size=8, # Minimum region size region_merge_size=20, # Region merge threshold edge_max_len=12.0, # Maximum polygon edge length edge_max_error=1.3, # Edge simplification error verts_per_poly=6, # Maximum vertices per polygon (3 = triangles) detail_sample_distance=6.0, detail_sample_maximum_error=1.0 ) if is_bake: # Get polygonal description vertices, polygons = baker.get_polygonization() # Save to binary file baker.save_to_binary("navmesh.nm") # Or save to text file baker.save_to_text("navmesh.txt") print(f"Baked {len(vertices)} vertices, {len(polygons)} polygons") else: print("Failed to bake navigation mesh") ``` ### Response #### Success Response (bake successful) - **is_bake** (boolean) - True if baking was successful, False otherwise. - **vertices** (list of tuples) - List of vertex coordinates [(x, y, z), ...]. - **polygons** (list of lists) - List of polygon vertex indices [[v1, v2, ...], ...]. #### Response Example ```json { "is_bake": true, "vertices": [[-4.0, 0.0, -4.0], ...], "polygons": [[0, 1, 2, 3], ...] } ``` #### Error Response (bake failed) - **is_bake** (boolean) - False. #### Error Response Example ```json { "is_bake": false } ``` ``` -------------------------------- ### Build Full Pathfinder Module with AssemblyScript Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md This command builds the 'pathfinder_full.wasm' module, combining navmesh, RVO, and baking functionalities. It exports functions and the runtime. This module is suitable for applications needing all pathfinding and baking features. ```bash asc assembly/pathfinder_api.ts assembly/navmesh_api.ts assembly/rvo_api.ts assembly/baker_api.ts --outFile build/pathfinder_full.wasm --bindings esm --exportRuntime ``` -------------------------------- ### Create Extended PathFinder Object Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Creates an extended PathFinder object with detailed configuration for RVOSimulator subcomponents and agent movement. Navigation mesh boundary edges can serve as obstacles. Various parameters control agent interaction, movement, and simulation stability. ```AssemblyScript create_pathfinder_ext(vertices: StaticArray | null, polygons: StaticArray | null, sizes: StaticArray | null, neighbor_dist: f32, max_neighbors: i32, time_horizon: f32, time_horizon_obst: f32, agent_radius: f32, update_path_find: f32, continuous_moving: bool, move_agents: bool, snap_agents: bool, use_normals: bool): PathFinder ``` -------------------------------- ### Create PathFinder Object and Initialize Source: https://github.com/tugcga/path-finder/blob/main/python/README.md Initializes a PathFinder object with the provided vertices and polygons representing the navigation mesh. This object is then used for pathfinding and agent simulation. ```python import pathfinder as pf pathfinder = pf.PathFinder(vertices, polygons) ``` -------------------------------- ### Obstacle Management Source: https://github.com/tugcga/path-finder/blob/main/assemblyscript/README.md Functions for adding and managing obstacles in the RVO simulator. ```APIDOC ## Obstacle Management This section covers the API endpoints for managing obstacles within the RVOSimulator. ### Add Obstacle Array **Endpoint:** `rvo_add_obstacle_array` **Description:** Adds obstacles to the simulator. The input is an array of 2D positions defining line segments. The last segment connecting the first and last points is automatically included. **Parameters:** - `rvo` (RVOSimulator): The RVO simulator instance. - `vertices` (StaticArray): An array of 2D coordinates representing the vertices of the obstacle segments. **Returns:** - `i32`: The index of the added obstacle (or the first obstacle if multiple segments form one obstacle). ```