Enterprise-grade NPC management system for FiveM with server-side A pathfinding, secure client-server architecture, and navmesh integration*
Author: Alex SKYLINE
Compatibility: .NET Framework 4.5.2 / FiveM
Latest Version: 2.1.0
- Overview
- Key Features
- Architecture
- Installation
- Configuration
- API Documentation
- Performance
- Security
- Troubleshooting
- Contributing
- License
The FiveM Advanced NPC & Pathfinding Framework is a production-ready system designed for high-performance NPC management in FiveM servers. It combines sophisticated server-side pathfinding using the A* algorithm with a secure, optimized client-server architecture.
- Server-Side Intelligence: All pathfinding computations are executed on the server using optimized A* algorithm with spatial indexing
- Navmesh Integration: Full support for custom navmesh data with efficient loading and querying
- Zero Client Trust: Clients never access configuration files directly - all data is validated and distributed by the server
- FiveM Optimized: Manual JSON parsing eliminates common Newtonsoft.Json initialization issues in FiveM environments
- Modular Architecture: Clean separation of concerns with dependency injection patterns for easy maintenance and extension
- Realistic NPC Populations: Create immersive environments with static and dynamic NPCs
- Intelligent Navigation: NPCs navigate complex environments using server-calculated optimal paths
- Dynamic Spawn Zones: Define multiple zones with custom NPC templates and spawn probabilities
- Security-First Design: Prevent client-side manipulation of NPC configurations and behaviors
- ✅ A Algorithm Implementation* with optimized priority queue
- ✅ Spatial Indexing for O(1) nearest node lookups using grid-based partitioning
- ✅ Wall Avoidance System with proximity cost penalties
- ✅ Waypoint Generation for smooth path following
- ✅ Performance Safeguards with iteration limits and time constraints
- ✅ Navmesh Data Management with batch save/load operations
- ✅ Static NPCs with fixed positions and scenarios
- ✅ Dynamic Spawn Zones with radius-based spawning
- ✅ Model Validation with existence checks and loading verification
- ✅ Behavior Configuration (invincibility, freeze position, event blocking)
- ✅ Real-time Updates for NPC state modifications
- ✅ Automatic Cleanup on player disconnect
- ✅ Authentication System with token-based validation
- ✅ Secure Configuration Broadcast with encrypted channels
- ✅ Manual JSON Parsing to avoid FiveM compatibility issues
- ✅ Message Validation with structure verification
- ✅ Event-Driven Architecture for responsive communication
- ✅ Heartbeat Monitoring for connection health
- ✅ Comprehensive Logging with categorized severity levels
- ✅ Modular Service Architecture for easy testing and extension
- ✅ Dependency Injection patterns throughout codebase
- ✅ Type-Safe Models for all data structures
- ✅ Configuration Hot-Reload support (server restart required)
- ✅ Detailed Error Messages for debugging
┌─────────────────────────────────────────────────────────────┐
│ FiveM Server │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Server-Side Components │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐ │ │
│ │ │ Pathfinding │ │Configuration │ │ Auth │ │ │
│ │ │ Service │ │ Service │ │ Service │ │ │
│ │ └──────┬───────┘ └──────┬───────┘ └──────┬──────┘ │ │
│ │ │ │ │ │ │
│ │ ┌────▼──────────────────▼──────────────────▼─────┐ │ │
│ │ │ Server Script (ServerScript.cs) │ │ │
│ │ └────────────────────┬──────────────────────────┘ │ │
│ └─────────────────────────┼─────────────────────────────┘ │
└────────────────────────────┼───────────────────────────────┘
│ Network Events
│ (TriggerClientEvent)
▼
┌─────────────────────────────────────────────────────────────┐
│ FiveM Clients │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Client-Side Components │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐ │ │
│ │ │ NPC │ │ Network │ │ Config │ │ │
│ │ │ Manager │ │ Service │ │ Receiver │ │ │
│ │ └──────┬───────┘ └──────┬───────┘ └──────┬──────┘ │ │
│ │ │ │ │ │ │
│ │ ┌────▼──────────────────▼──────────────────▼─────┐ │ │
│ │ │ Client Script (ClientScript.cs) │ │ │
│ │ └────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
FiveM-NPC-Pathfinding/
├── 📂 Server/ # Server-side code (.NET 4.5.2)
│ ├── 📂 Services/
│ │ ├── AStarPathfindingService.cs # A* pathfinding implementation
│ │ ├── NavmeshDataService.cs # Navmesh load/save operations
│ │ ├── SpatialIndexService.cs # Grid-based spatial indexing
│ │ ├── WallProximityService.cs # Wall avoidance calculations
│ │ ├── WaypointGenerationService.cs # Path smoothing
│ │ ├── ConfigurationService.cs # JSON config management
│ │ ├── ConfigurationBroadcastService.cs # Secure config distribution
│ │ ├── ClientAuthenticationService.cs # Client validation
│ │ ├── PathfindingRequestHandler.cs # Path request processing
│ │ └── LoggingService.cs # Structured logging
│ ├── 📂 Algorithms/
│ │ └── AStarAlgorithm.cs # Core A* algorithm logic
│ ├── 📂 Models/
│ │ ├── Node.cs # Navmesh node structure
│ │ ├── PathfindingConfig.cs # Algorithm parameters
│ │ ├── PathfindingState.cs # Search state tracking
│ │ ├── OptimizedPathfindingState.cs # Performance-optimized state
│ │ └── OptimizedPriorityQueue.cs # Custom priority queue
│ ├── 📂 Converters/
│ │ ├── Vector3Converter.cs # JSON Vector3 serialization
│ │ └── TupleConverter.cs # JSON Tuple serialization
│ └── 📄 ServerScript.cs # Main server script
│
├── 📂 Client/ # Client-side code (.NET 4.5.2)
│ ├── 📂 Services/
│ │ ├── NpcManagerService.cs # NPC spawning and management
│ │ ├── NetworkService.cs # Server communication
│ │ ├── ConfigurationReceiver.cs # Config data handling
│ │ └── LoggingService.cs # Client-side logging
│ ├── 📂 Models/
│ │ ├── ClientNpcData.cs # NPC data structure
│ │ └── NetworkMessage.cs # Network message format
│ ├── 📂 Handlers/
│ │ └── NpcEventHandler.cs # NPC event processing
│ └── 📄 ClientScript.cs # Main client script
│
├── 📂 config/ # Configuration files
│ ├── 📄 setting.json # General settings
│ ├── 📄 npc_static.json # Static NPC definitions
│ └── 📄 spawnzone.json # Dynamic spawn zones
│
├── 📂 save/ # Runtime data
│ └── navmesh_data_*.json # Generated navmesh files
│
├── 📄 fxmanifest.lua # FiveM resource manifest
├── 📄 NavMeshServer.csproj # Server project file
├── 📄 NavMeshClient.csproj # Client project file
└── 📄 README.md # This file
All major functionality is encapsulated in dedicated services with single responsibilities:
- Separation of Concerns: Each service handles one specific domain
- Dependency Injection: Services are injected through constructors
- Interface Segregation: Pathfinding uses
IPathfindingServiceinterface
Manual JSON parsing eliminates TypeInitializationException common in FiveM:
// Manual JSON construction (NetworkService.cs)
var authData = $"{{\"clientId\":\"{clientId}\",\"timestamp\":\"{timestamp}\",\"version\":\"{version}\"}}";
// Manual JSON parsing with validation
private ClientNpcData ParseNpcDataFromJson(string json)
{
// Extract values using string operations instead of JsonConvert
// Robust against FiveM environment limitations
}Custom implementation for A* pathfinding that outperforms standard .NET collections:
// OptimizedPriorityQueue.cs - O(log n) operations
public class OptimizedPriorityQueue
{
private List<(int nodeId, float priority)> _heap;
public void Enqueue(int nodeId, float priority) { /* Min-heap insertion */ }
public int Dequeue() { /* Extract minimum */ }
}All pathfinding operations are protected with locks to prevent race conditions:
private static readonly object _pathfindingLock = new object();
public void HandlePathRequest(Player source, /* params */)
{
lock (_pathfindingLock)
{
// Thread-safe path calculation
}
}- FiveM Server (latest build recommended)
- .NET SDK 4.5.2 or higher
- Visual Studio 2019+ or JetBrains Rider (for development)
- Git (for version control)
# Clone the repository
git clone https://github.com/yourusername/fivem-npc-pathfinding.git
cd fivem-npc-pathfinding
# Build server-side DLL
dotnet build NavMeshServer.csproj -c Release
# Build client-side DLL
dotnet build NavMeshClient.csproj -c Release# Copy entire folder to your FiveM resources directory
cp -r fivem-npc-pathfinding [FiveM-Server]/resources/
# Add to server.cfg
echo "ensure fivem-npc-pathfinding" >> server.cfg# Start your FiveM server
# Check console for:
[VitalityNPC_csharp] Server script initialization completed successfully
[VitalityNPC_csharp] Configuration ready for useEnsure these files exist in bin/Release/net452/ (or Debug for development):
✓ NavMeshServer.net.dll
✓ NavMeshClient.net.dll
✓ CitizenFX.Core.Server.dll
✓ CitizenFX.Core.Client.dll
✓ Newtonsoft.Json.dll
✓ Microsoft.CSharp.dll
For active development with debugging enabled:
# Build in debug mode
dotnet build NavMeshServer.csproj
dotnet build NavMeshClient.csproj
# FiveM console commands
refresh
restart fivem-npc-pathfinding{
"debug": true, // Enable verbose logging
"maxNpcs": 50, // Maximum NPCs per client
"spawnDistance": 100.0, // Spawn radius in meters
"refreshInterval": 5000, // Update interval in ms
"enableStaticNpcs": true, // Enable static NPC system
"enableDynamicNpcs": true, // Enable dynamic spawn zones
"modelLoadTimeout": 5000, // Model loading timeout (ms)
"maxAuthAttempts": 3, // Max authentication retries
"sessionDuration": 3600 // Session lifetime (seconds)
}Define NPCs with fixed positions and behaviors:
{
"npcs": [
{
"id": 1,
"name": "Reception Desk Clerk",
"model": "a_m_m_business_01",
"position": {
"x": -1006.1578,
"y": -2782.7275,
"z": 21.3617
},
"heading": 80.0,
"scenario": "WORLD_HUMAN_STAND_IMPATIENT",
"behavior": {
"isInvincible": true, // Cannot be killed
"freezePosition": true, // Cannot move from position
"blockEvents": true, // Ignore game events
"useScenario": true, // Play animation scenario
"canWander": false, // Allow random movement
"wanderRadius": 5.0, // Wander distance (if enabled)
"wanderInterval": 60000 // Time between wanders (ms)
}
}
]
}Common GTA V scenarios for realistic NPC behavior:
WORLD_HUMAN_STAND_IMPATIENT- Standing impatientlyWORLD_HUMAN_GUARD_STAND- Security guard stanceWORLD_HUMAN_CLIPBOARD- Holding clipboardWORLD_HUMAN_STAND_MOBILE- Using mobile phoneWORLD_HUMAN_SMOKING- Smoking cigaretteWORLD_HUMAN_LEANING- Leaning against wallWORLD_HUMAN_TOURIST_MAP- Looking at mapWORLD_HUMAN_AA_COFFEE- Drinking coffee
Create areas where NPCs spawn dynamically:
{
"spawnZones": [
{
"id": 1,
"name": "Downtown Business District",
"center": {
"x": -1000.0,
"y": -2800.0,
"z": 20.0
},
"radius": 200.0, // Zone radius in meters
"maxNpcs": 15, // Max NPCs in this zone
"isActive": true, // Enable/disable zone
"priority": 1, // Spawn priority (1 = highest)
"npcTemplates": [
{
"model": "a_m_m_business_01",
"name": "Business Worker",
"scenario": "WORLD_HUMAN_STAND_MOBILE",
"spawnChance": 0.6 // 60% spawn probability
},
{
"model": "a_f_m_business_02",
"name": "Business Woman",
"scenario": "WORLD_HUMAN_CLIPBOARD",
"spawnChance": 0.4 // 40% spawn probability
}
]
}
]
}| Parameter | Type | Description | Default |
|---|---|---|---|
isInvincible |
boolean | NPC cannot take damage | false |
freezePosition |
boolean | NPC stays at spawn point | false |
blockEvents |
boolean | NPC ignores game events | false |
useScenario |
boolean | Play specified scenario animation | false |
canWander |
boolean | Allow random movement | false |
wanderRadius |
float | Maximum wander distance (meters) | 0.0 |
wanderInterval |
integer | Time between wanders (milliseconds) | 0 |
npc:requestAuthentication
-- Client sends authentication request
TriggerServerEvent("npc:requestAuthentication", authDataJson)
-- Parameters:
-- authDataJson (string): JSON with clientId, timestamp, versionnpc:requestConfiguration
-- Client requests specific configuration
TriggerServerEvent("npc:requestConfiguration", requestDataJson)
-- Parameters:
-- requestDataJson (string): JSON with configType, authTokennavmesh:requestPath
-- Request server-side pathfinding calculation
TriggerServerEvent("navmesh:requestPath",
startX, startY, startZ, -- Start position
endX, endY, endZ, -- End position
requestId -- Unique request identifier
)navmesh:requestLoadZone
-- Load navmesh data for current zone
TriggerServerEvent("navmesh:requestLoadZone")navmesh:startBatchSave
-- Begin batch navmesh save operation
TriggerServerEvent("navmesh:startBatchSave", totalChunks)navmesh:saveZoneChunk
-- Save a chunk of navmesh data
TriggerServerEvent("navmesh:saveZoneChunk", chunkData)navmesh:endBatchSave
-- Complete batch save operation
TriggerServerEvent("navmesh:endBatchSave")npc:authenticationToken
-- Receive authentication token from server
RegisterNetEvent("npc:authenticationToken")
AddEventHandler("npc:authenticationToken", function(token)
-- Store token for subsequent requests
end)npc:connectionValidated
-- Connection validation status
RegisterNetEvent("npc:connectionValidated")
AddEventHandler("npc:connectionValidated", function(isValid)
-- Handle validation result
end)npc:configurationData
-- Receive configuration data
RegisterNetEvent("npc:configurationData")
AddEventHandler("npc:configurationData", function(configType, configDataJson)
-- Process configuration (npc_static, spawnzone, setting)
end)npc:configurationUpdate
-- Receive real-time configuration updates
RegisterNetEvent("npc:configurationUpdate")
AddEventHandler("npc:configurationUpdate", function(configType, updateDataJson)
-- Apply configuration changes
end)npc:spawnCommand
-- Spawn NPC command
RegisterNetEvent("npc:spawnCommand")
AddEventHandler("npc:spawnCommand", function(npcDataJson)
-- Parse and spawn NPC
end)npc:updateCommand
-- Update existing NPC
RegisterNetEvent("npc:updateCommand")
AddEventHandler("npc:updateCommand", function(npcDataJson)
-- Update NPC state
end)npc:removeCommand
-- Remove NPC by ID
RegisterNetEvent("npc:removeCommand")
AddEventHandler("npc:removeCommand", function(npcId)
-- Delete NPC entity
end)public interface IPathfindingService
{
bool IsReady { get; }
void LoadNavmesh();
List<Vector3> FindPath(Vector3 start, Vector3 end);
}
// Usage example
var path = _pathfindingService.FindPath(startPos, endPos);
if (path != null && path.Count > 0)
{
// Use path waypoints
}public class NpcManagerService
{
public bool SpawnNpc(ClientNpcData npcData);
public bool UpdateNpc(ClientNpcData npcData);
public bool RemoveNpc(int npcId);
public ClientNpcData GetNpc(int npcId);
public List<ClientNpcData> GetAllNpcs();
}
// Usage example
var success = _npcManager.SpawnNpc(new ClientNpcData
{
Id = 1,
Name = "Security Guard",
Model = "s_m_m_security_01",
Position = new Vector3(100.0f, 200.0f, 20.0f),
Heading = 90.0f
});sequenceDiagram
participant C as Client
participant S as Server
C->>S: npc:requestAuthentication
Note over C,S: {clientId, timestamp, version}
S->>S: Generate SHA256 Token
S->>C: npc:authenticationToken
Note over S,C: Base64 encoded token
S->>C: npc:connectionValidated(true)
S->>C: npc:configurationData
Note over S,C: Secured config with integrity hash
✅ Token-Based Authentication
- SHA256 hashed authentication tokens
- Unique client identification
- Session management with automatic cleanup
✅ Message Integrity Validation
- SHA256 hash verification on all messages
- Timestamp-based replay attack prevention
- Structured message format validation
✅ Zero Client Trust Architecture
- Configuration files only accessible server-side
- All NPC data validated before distribution
- Client cannot modify server state directly
✅ Session Management
- Automatic session cleanup on player disconnect
- Configurable session duration
- Maximum authentication attempt limits
Server Messages (Newtonsoft.Json format)
{
"Data": { /* payload */ },
"MessageType": "npc_static",
"Timestamp": "2025-10-12T12:00:00.000Z",
"MessageId": "unique-guid",
"MessageHash": "sha256-integrity-hash"
}Client Messages (Manual format)
{
"data": { /* payload */ },
"authToken": "authentication-token",
"timestamp": "2025-10-12T12:00:00.000Z",
"messageId": "unique-guid",
"messageHash": "sha256-integrity-hash"
}Grid-based spatial partitioning for O(1) nearest node queries:
Traditional Search: O(n) - Check all nodes
Spatial Index: O(1) - Direct grid cell lookup
Result: 100x-1000x faster for large navmeshes
- Custom priority queue with O(log n) operations
- Early termination on unreachable paths
- Configurable iteration and time limits
// Optimized model loading with validation
1. Check if model exists in game files
2. Validate model hash
3. Request with extended timeout
4. Monitor loading with exponential backoff
5. Automatic cleanup on failure- Node connection caching
- Spatial grid reuse
- Automatic navmesh cleanup
- Client-side NPC dictionary management
| Operation | Time | Notes |
|---|---|---|
| Navmesh Load | ~500-2000ms | Depends on file size |
| Path Calculation | <50ms | Typical 100-node path |
| NPC Spawn | ~100-500ms | Includes model loading |
| Spatial Query | <1ms | O(1) grid lookup |
| Authentication | <10ms | Token generation |
- ✅ Supports 1000+ navmesh nodes with minimal performance impact
- ✅ 50+ concurrent NPCs per client (configurable)
- ✅ Multiple spawn zones with independent management
- ✅ Thread-safe pathfinding for concurrent requests
[YYYY-MM-DD HH:mm:ss.fff] [ResourceName] [ClientID] [LEVEL] [Component] Message
| Level | Usage | Example |
|---|---|---|
INFO |
General information | NPC Manager service initialized |
SUCCESS |
Successful operations | NPC spawned successfully |
WARNING |
Non-critical issues | Model loading timeout, retrying |
ERROR |
Errors with stack traces | Failed to parse JSON: {exception} |
SECURITY |
Security events | Client authenticated with token |
NETWORK_IN |
Incoming network data | Configuration data received |
NETWORK_OUT |
Outgoing network data | Authentication request sent |
CONFIGURATION |
Config status | Setting.json loaded successfully |
DEBUG |
Debug information | Pathfinding iteration 150/1000 |
[2025-10-12 14:30:15.234] [VitalityNPC_csharp] [Server] [INFO] [ServerScript] Initializing server script
[2025-10-12 14:30:15.456] [VitalityNPC_csharp] [Server] [CONFIGURATION] [ConfigurationService] setting.json loaded (6 properties)
[2025-10-12 14:30:15.789] [VitalityNPC_Client] [Client_12345] [SECURITY] [NetworkService] Authentication request sent
[2025-10-12 14:30:15.890] [VitalityNPC_csharp] [Server] [SECURITY] [AuthService] Client authenticated: Client_12345
[2025-10-12 14:30:16.012] [VitalityNPC_Client] [Client_12345] [SUCCESS] [NpcManager] NPC 'Security Guard' spawned
Error:
The type initializer for 'Newtonsoft.Json.Serialization.DefaultSerializationBinder' threw an exception
Cause: FiveM environment doesn't properly initialize some .NET reflection features required by Newtonsoft.Json
Solution: ✅ This framework uses manual JSON parsing to avoid this issue completely
- Network messages: Manual string construction
- NPC data: Custom parsing without JsonConvert
- Configuration: Direct string manipulation
Error:
[ERROR] Failed to load NPC model after 50 attempts: a_m_m_business_01
Possible Causes:
- Model name typo in configuration
- Model not available in GTA V
- Server performance issues
Solutions:
// 1. Verify model exists
// Use https://wiki.rage.mp/index.php?title=Peds for valid model names
// 2. Increase timeout in setting.json
{
"modelLoadTimeout": 10000 // Increase from 5000 to 10000ms
}
// 3. Check console for specific errors
[INFO] [NpcManagerService] Requesting model: a_m_m_business_01 (Hash: 123456789)Error:
[ERROR] [NetworkService] Authentication failed: timeout
Solutions:
- Check server is running and resource loaded
- Verify network events are registered
- Check F8 console for error messages
- Restart resource:
restart fivem-npc-pathfinding
Checklist:
- ✅ Static NPCs enabled in
setting.json("enableStaticNpcs": true) - ✅ Valid model names in
npc_static.json - ✅ Client authenticated with server
- ✅ No errors in F8 console
- ✅ Player within spawn distance (if configured)
Debug Steps:
# 1. Enable debug logging
# In setting.json: "debug": true
# 2. Check server console for:
[CONFIGURATION] npc_static.json loaded successfully
# 3. Check client console (F8) for:
[SUCCESS] NPC spawned successfully
# 4. If nothing appears, check authentication:
[SECURITY] Client authenticated with tokenError:
[A*] Could not find nearest nodes
Cause: Navmesh data not loaded
Solution:
# 1. Generate navmesh data (if not exists)
TriggerServerEvent("navmesh:requestLoadZone")
# 2. Check save folder for navmesh files
ls save/navmesh_data_*.json
# 3. Verify navmesh loaded in console
[PATHFINDING] Successfully loaded 5000 nodes in 1500msSymptoms:
- Server slowdown after extended runtime
- Increasing memory usage
Solutions:
// 1. Reduce max NPCs in setting.json
{
"maxNpcs": 25 // Reduce from 50
}
// 2. Decrease spawn zones
// Remove or disable unused zones in spawnzone.json
// 3. Implement automatic cleanup
// NPCs are automatically cleaned up on player disconnectError:
Could not load file or assembly 'NavMeshServer.net.dll'
Solutions:
-
Verify build completed:
dotnet build NavMeshServer.csproj dotnet build NavMeshClient.csproj
-
Check file locations:
✓ bin/Debug/net452/NavMeshServer.net.dll ✓ bin/Debug/net452/NavMeshClient.net.dll -
Verify fxmanifest.lua:
server_script 'bin/Debug/net452/NavMeshServer.net.dll' client_script 'bin/Debug/net452/NavMeshClient.net.dll'
-
Refresh and restart:
refresh restart fivem-npc-pathfinding
The system supports two message formats for maximum compatibility:
{
"Data": { /* payload */ },
"MessageType": "npc_static",
"Timestamp": "2025-10-12T12:00:00.000Z",
"MessageId": "unique-guid",
"MessageHash": "sha256-integrity-hash"
}{
"data": { /* payload */ },
"authToken": "authentication-token",
"timestamp": "2025-10-12T12:00:00.000Z",
"messageId": "guid-unique",
"messageHash": "sha256-integrity-hash"
}Edit Server/Models/PathfindingConfig.cs:
public static class PathfindingConfig
{
public const int MAX_ITERATIONS = 1000; // Max A* iterations
public const int MAX_PROCESSING_TIME_MS = 100; // Max calculation time
public const int YIELD_EVERY_N_ITERATIONS = 100; // Thread yield frequency
public const float WALL_PROXIMITY_THRESHOLD = 2.0f; // Wall avoidance distance
public const float WALL_AVOIDANCE_COST = 2.0f; // Wall proximity penalty
}Recommendations:
- High-traffic servers: Reduce
MAX_ITERATIONSto 500 - Complex navmesh: Increase
MAX_PROCESSING_TIME_MSto 200 - Performance issues: Increase
YIELD_EVERY_N_ITERATIONSto 50
Edit Server/Services/SpatialIndexService.cs:
public SpatialIndexService(List<Node> nodes, float gridSize = 50.0f)Grid Size Guidelines:
- Dense urban areas: 25.0f (smaller cells, more precision)
- Open areas: 100.0f (larger cells, better performance)
- Mixed environments: 50.0f (default, balanced)
{
"id": 5,
"name": "Wandering Civilian",
"model": "a_m_m_tourist_01",
"position": {"x": 100.0, "y": 200.0, "z": 20.0},
"heading": 0.0,
"scenario": "WORLD_HUMAN_TOURIST_MAP",
"behavior": {
"isInvincible": true,
"freezePosition": false,
"blockEvents": true,
"useScenario": false,
"canWander": true,
"wanderRadius": 50.0, // 50 meter radius
"wanderInterval": 30000 // Move every 30 seconds
}
}{
"id": 6,
"name": "Shop Keeper",
"model": "s_m_m_autoshop_01",
"position": {"x": 150.0, "y": 250.0, "z": 20.0},
"heading": 90.0,
"scenario": "WORLD_HUMAN_STAND_IMPATIENT",
"behavior": {
"isInvincible": true,
"freezePosition": true,
"blockEvents": false, // Allow interactions
"useScenario": true,
"canWander": false
}
}{
"debug": true,
"maxNpcs": 10,
"spawnDistance": 50.0,
"refreshInterval": 2000,
"enableStaticNpcs": true,
"enableDynamicNpcs": false,
"modelLoadTimeout": 10000
}{
"debug": false,
"maxNpcs": 50,
"spawnDistance": 100.0,
"refreshInterval": 5000,
"enableStaticNpcs": true,
"enableDynamicNpcs": true,
"modelLoadTimeout": 5000
}We welcome contributions to improve this framework!
-
Fork and clone the repository
git clone https://github.com/yourusername/fivem-npc-pathfinding.git cd fivem-npc-pathfinding -
Create a feature branch
git checkout -b feature/your-feature-name
-
Make your changes
- Follow existing code style
- Add XML documentation for public methods
- Update README if adding new features
-
Test thoroughly
- Build both server and client projects
- Test in FiveM development environment
- Check F8 console for errors
-
Submit pull request
- Describe your changes clearly
- Reference any related issues
- Include screenshots if UI changes
- Naming: PascalCase for classes/methods, camelCase for variables
- Documentation: XML docs for all public APIs
- Logging: Use appropriate log levels
- Error Handling: Try-catch with detailed error messages
- Thread Safety: Use locks for shared resources
- 🎯 Additional pathfinding algorithms (Dijkstra, Jump Point Search)
- 🤖 Advanced NPC behaviors (patrol routes, reactions)
- 🗺️ Navmesh generation tools
- 📊 Performance monitoring dashboard
- 🌐 Multi-language support
- 📝 Documentation improvements
- FiveM Native Reference: https://docs.fivem.net/natives/
- CitizenFX Documentation: https://docs.fivem.net/docs/
- GTA V Ped Models: https://wiki.rage.mp/index.php?title=Peds
- A Algorithm*: https://en.wikipedia.org/wiki/A*_search_algorithm
- FiveM Docs: Official FiveM documentation
- CFX Forums: Community support and discussions
- GTA V Modding: Resources for GTA V development
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Discord: Join our Discord
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2025 Alex SKYLINE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- FiveM Team for the excellent multiplayer framework
- CitizenFX Collective for C# scripting support
- GTA V Modding Community for resources and documentation
- Contributors who helped improve this project
Author: Alex SKYLINE
Version: 2.1.0
Last Updated: October 2025
For questions, suggestions, or support:
- Open an issue on GitHub
- Join our Discord community
- Check the documentation wiki
⭐ If this project helped you, please consider giving it a star! ⭐
Made with ❤️ for the FiveM community
| Service | Fichier | Responsabilités | Améliorations v2.1.0 |
|---|---|---|---|
LoggingService |
Client/Services/LoggingService.cs |
Logging client avec IDs uniques | Sync avec logging serveur |
NetworkService |
Client/Services/NetworkService.cs |
Communication sécurisée | Parsing JSON manuel + validation bidirectionnelle |
NpcManagerService |
Client/Services/NpcManagerService.cs |
Gestion complète des NPCs | Chargement modèles optimisé + validation avancée |
ConfigurationReceiver |
Client/Services/ConfigurationReceiver.cs |
Réception de configurations | Extraction JSON manuelle + processing automatique |
| Handler | Fichier | Responsabilités | Améliorations v2.1.0 |
|---|---|---|---|
NpcEventHandler |
Client/Handlers/NpcEventHandler.cs |
Events de gestion NPC | Parsing NPC manuel + validation complète |
{
"npcs": [
{
"id": 1,
"name": "Reception Desk Clerk",
"model": "a_m_m_business_01",
"position": {
"x": -1006.1578,
"y": -2782.7275,
"z": 21.3617
},
"heading": 80.0,
"scenario": "WORLD_HUMAN_STAND_IMPATIENT",
"behavior": {
"isInvincible": true,
"freezePosition": true,
"blockEvents": true,
"useScenario": true,
"canWander": false,
"wanderRadius": 5.0,
"wanderInterval": 60000
}
},
{
"id": 3,
"name": "Information Assistant",
"model": "a_f_m_business_02",
"position": {
"x": -1000.0,
"y": -2785.0,
"z": 21.3617
},
"heading": 270.0,
"scenario": "WORLD_HUMAN_CLIPBOARD",
"behavior": {
"isInvincible": true,
"freezePosition": false,
"blockEvents": true,
"useScenario": true,
"canWander": true,
"wanderRadius": 5.0,
"wanderInterval": 60000
}
}
]
}| Paramètre | Type | Description | Valeur par défaut |
|---|---|---|---|
isInvincible |
boolean | Rend le NPC invulnérable aux dégâts | false |
freezePosition |
boolean | Empêche le NPC de bouger de sa position | false |
blockEvents |
boolean | Bloque les événements externes sur le NPC | false |
useScenario |
boolean | Active l'utilisation du scénario spécifié | false |
canWander |
boolean | Permet au NPC de se déplacer aléatoirement | false |
wanderRadius |
float | Rayon de déplacement en mètres | 0.0 |
wanderInterval |
int | Intervalle entre déplacements (ms) | 0 |
{
"debug": true,
"maxNpcs": 50,
"spawnDistance": 100.0,
"refreshInterval": 5000,
"enableStaticNpcs": true,
"enableDynamicNpcs": true,
"modelLoadTimeout": 5000,
"maxAuthAttempts": 3,
"sessionDuration": 3600
}{
"spawnZones": [
{
"id": 1,
"name": "Downtown Business District",
"center": { "x": -1000.0, "y": -2800.0, "z": 20.0 },
"radius": 200.0,
"maxNpcs": 15,
"isActive": true,
"priority": 1,
"npcTemplates": [
{
"model": "a_m_m_business_01",
"name": "Business Worker",
"scenario": "WORLD_HUMAN_STAND_MOBILE",
"spawnChance": 0.6
}
]
}
]
}[YYYY-MM-DD HH:mm:ss.fff] [ResourceName] [ClientID] [LEVEL] [Component] Message
INFO- Informations généralesSUCCESS- Opérations réussies (spawn NPCs, authentification)WARNING- Avertissements (modèles non trouvés, timeouts)ERROR- Erreurs avec stack traces complètesSECURITY- Événements de sécurité (authentification, sessions)NETWORK_IN/OUT- Communication réseau détailléeCONFIGURATION- Status des configurations chargéesDEBUG- Messages de débogage (build debug uniquement)
[2025-07-07 12:45:00.503] [VitalityNPC_Client] [Client_61480] [SECURITY] [NetworkService] Client-server secure connection established
[2025-07-07 12:45:00.515] [VitalityNPC_Client] [Client_61480] [NETWORK_IN] [ConfigurationReceiver] Configuration data received: npc_static
[2025-07-07 12:45:00.518] [VitalityNPC_Client] [Client_61480] [INFO] [NpcManagerService] Requesting model: a_m_m_business_01 (Hash: 123456789)
[2025-07-07 12:45:00.647] [VitalityNPC_Client] [Client_61480] [SUCCESS] [NpcManagerService] NPC 'Reception Desk Clerk' (ID: 1) spawned successfully
[2025-07-07 12:45:00.648] [VitalityNPC_Client] [Client_61480] [SUCCESS] [ConfigurationReceiver] Static NPC configuration processed: 5 NPCs
<PackageReference Include="CitizenFX.Core.Server" Version="1.0.*" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" /><PackageReference Include="CitizenFX.Core.Client" Version="1.0.*" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />- ✅ .NET Framework 4.5.2 (requis pour FiveM)
- ✅ FiveM Latest (testé sur builds récents)
- ✅ GTA V (tous les modèles de NPCs standards)
⚠️ Newtonsoft.Json 11.0.2 (version fixe pour compatibilité FiveM)
# Build complet avec nettoyage
dotnet clean && dotnet build NavMeshServer.csproj && dotnet build NavMeshClient.csproj
# Build release optimisé pour production
dotnet build -c Release NavMeshServer.csproj
dotnet build -c Release NavMeshClient.csproj
# Déploiement FiveM automatique
refresh && start VitalityNPC_csharp- ✅ Injection de dépendances : Services chaînés avec logging intégré
- ✅ Parsing JSON manuel : Indépendance complète de Newtonsoft.Json côté parsing
- ✅ Gestion d'erreurs robuste : Try-catch avec logging détaillé
- ✅ Documentation XML : Complète sur toutes les méthodes publiques
- ✅ Compatibilité FiveM : Tests complets des méthodes synchrones
Error: The type initializer for 'Newtonsoft.Json.Serialization.DefaultSerializationBinder' threw an exception
Solution : Le système utilise maintenant un parsing JSON manuel. Cette erreur ne devrait plus se produire.
Error: Cannot load method from token 0x0a0000d3 for call at 0x00c0
Solution : Toutes les méthodes async ont été remplacées par des versions synchrones FiveM-compatibles.
Error: Failed to load NPC model: a_m_m_tourist_01
Solutions :
- Vérifier que le modèle existe dans GTA V avec
API.IsModelInCdimage() - Augmenter le timeout de chargement dans
setting.json - Utiliser des modèles de NPCs standards
Error: Client authentication failed
Solutions :
- Vérifier la synchronisation d'horloge serveur/client
- Contrôler les timestamps dans les logs
- Redémarrer la ressource si les sessions sont corrompues
# 1. Vérifier la compilation
dotnet build NavMeshServer.csproj
dotnet build NavMeshClient.csproj
# 2. Vérifier les DLL générées
ls -la bin/Debug/net452/
# 3. Tester dans FiveM
refresh
start VitalityNPC_csharp
# 4. Vérifier les logs
# Rechercher : "VitalityNPC_csharp server script initialization completed"
# Rechercher : "Client-server secure connection established"- ✅ Résolution TypeInitializationException : Parsing JSON manuel dans NetworkService, ConfigurationReceiver, NpcEventHandler
- ✅ Élimination BadImageFormatException : Remplacement async/await par méthodes synchrones
- ✅ Chargement modèles optimisé : Validation avancée avec
IsModelInCdimage()et timing amélioré - ✅ Communication bidirectionnelle : Support format serveur (Newtonsoft) et client (manuel)
- ✅ Parsing JSON manuel sécurisé : Indépendance complète de JsonConvert côté client
- ✅ Validation multi-format : Détection automatique format serveur vs client
- ✅ Logging spécialisé : Niveaux NETWORK, SECURITY, CONFIGURATION
- ✅ Gestion de sessions robuste : Cleanup automatique et refresh tokens
- ✅ Services refactorisés : NetworkService, NpcManagerService, ConfigurationReceiver
- ✅ Extraction NPCs automatique : Parsing manuel des configurations complexes
- ✅ Validation comportements : Support complet wandering et scenarios
- ✅ Documentation enrichie : Guide troubleshooting et exemples détaillés
- ✅ Messages bidirectionnels : Validation serveur ↔ client avec hash SHA256
- ✅ Sessions authentifiées : Tokens sécurisés avec expiration automatique
- ✅ Audit logging : Traçabilité complète des opérations sensibles
- Client passif : Le client ne peut jamais accéder directement aux fichiers de configuration
- Parsing manuel : Évite les problèmes d'initialisation Newtonsoft.Json dans FiveM
- Communication sécurisée : Tous les messages utilisent SHA256 pour l'intégrité
- Sessions temporaires : Nettoyage automatique lors des déconnexions
- Chargement asynchrone : Models NPCs chargés avec validation et timeout
- Communication optimisée : Messages compacts avec validation bidirectionnelle
- Gestion mémoire : Cleanup automatique des sessions et NPCs
- Logging intelligent : Niveaux spécialisés pour debugging FiveM
- FiveM natif : Architecture testée avec les dernières versions FiveM
- .NET Framework 4.5.2 : Compatibilité garantie avec l'environnement FiveM
- Modèles GTA V : Support de tous les modèles standards du jeu
- Extensibilité : Architecture modulaire facilement extensible
- Vérifier les logs : Rechercher les erreurs dans les niveaux ERROR et SECURITY
- Tester l'authentification : Vérifier la séquence d'authentification complète
- Valider les modèles : Contrôler l'existence des modèles NPCs avec IsModelInCdimage
- Vérifier la compilation : S'assurer que les deux DLL sont présentes et à jour
- Logs détaillés avec composants et timestamps
- Validation de structure des messages en temps réel
- Monitoring des sessions d'authentification
- Traces complètes du chargement des modèles NPCs
Cette architecture v2.1.0 garantit une compatibilité FiveM native, une communication sécurisée optimisée et une gestion NPCs robuste sans les problèmes de dépendances qui affectaient les versions précédentes.