Files
systemrevivalserver/PROJECTILE_SYSTEM_IMPLEMENTATION_PLAN.md
T
2026-01-18 00:17:06 -05:00

554 lines
16 KiB
Markdown

# Projectile & Equipment System - Implementation Plan
## 📌 Overview
This document outlines the implementation of:
1. New equipment slots (Quiver, Necklace)
2. Projectile firing system (arrows, bolts, javelins)
3. Quiver container system (holds multiple ammunition types)
4. Arrow recovery mechanics (5% base chance)
5. Damage calculation for ranged weapons
6. Damage notifications for both players and mobs
---
## 🗂️ Phase 1: Database Schema Changes
### 1.1 Equipment Slots
**Status:** ✅ COMPLETED
- Added `Necklace` to `DungeonEquipmentSlot` enum (position 8)
- Added `Quiver` to `DungeonEquipmentSlot` enum (position 11)
### 1.2 Required Database Migration
**SQL Migration:**
```sql
-- Add new enum values (MySQL handles this automatically via EF migrations)
-- No table schema changes needed - enum values are stored as integers
-- Optional: Add equipped columns to DungeonCharacter for caching
ALTER TABLE `dungeon_characters`
ADD COLUMN `EquippedNecklace` BIGINT UNSIGNED NULL,
ADD COLUMN `EquippedQuiver` BIGINT UNSIGNED NULL;
```
### 1.3 Item Type Extensions
**New Item Types Needed:**
```csharp
public enum ItemType
{
// Existing...
Weapon,
Armor,
Consumable,
Accessory,
// NEW ADDITIONS:
Ammunition, // Arrows, bolts, javelins (stackable, equippable)
QuiverContainer, // Leather quiver, etc. (container item)
Necklace // Or just use Accessory with EquipSlot = Necklace
}
```
---
## 🎯 Phase 2: Ammunition & Quiver System
### 2.1 Ammunition Items
**Properties:**
- `ItemType = Ammunition`
- `Stackable = true`
- `MaxStack = 100` (or configurable)
- `EquipSlot = Quiver` (can be equipped directly)
- Stats that affect damage:
- `BonusDamage` (flat bonus)
- `DamageMultiplier` (percentage)
- `ArmorPenetration`
- `CritChance`
**Examples:**
- Wooden Arrow (8-12 damage, common)
- Iron Arrow (15-20 damage, uncommon)
- Fire Arrow (10-15 damage + 5 fire DoT)
- Broadhead Arrow (20-30 damage, +10% armor pen)
### 2.2 Quiver Container System
**Two Modes:**
1. **Direct Ammunition Equip:** Place a stack of arrows directly in Quiver slot
2. **Quiver Container Equip:** Place a quiver (container) in Quiver slot, which holds multiple ammo types
**Quiver Container Properties:**
```csharp
public class QuiverContainer
{
public int Capacity { get; set; } // Number of ammo slots (e.g., 3-5)
public List<AmmoSlot> Slots { get; set; }
// Optional bonuses from the quiver itself
public int BonusArrowRecovery { get; set; } // +5% recovery chance
public float BonusDrawSpeed { get; set; } // -10% draw time
}
public class AmmoSlot
{
public int ItemDefinitionId { get; set; }
public int Quantity { get; set; }
public int MaxQuantity { get; set; } = 100;
}
```
**Database Storage Options:**
- **Option A:** JSON column on equipped quiver item (`AmmoSlotsJson`)
- **Option B:** Separate table `dungeon_quiver_ammo_slots`
- Links to the character item ID of the equipped quiver
- Allows proper querying and constraints
**Recommended: Option B**
```sql
CREATE TABLE `dungeon_quiver_ammo_slots` (
`Id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`QuiverCharacterItemId` BIGINT UNSIGNED NOT NULL,
`SlotIndex` INT NOT NULL,
`ItemDefinitionId` INT NOT NULL,
`Quantity` INT NOT NULL DEFAULT 0,
FOREIGN KEY (`QuiverCharacterItemId`) REFERENCES `dungeon_character_items`(`Id`) ON DELETE CASCADE,
FOREIGN KEY (`ItemDefinitionId`) REFERENCES `dungeon_item_definitions`(`Id`),
UNIQUE KEY `unique_quiver_slot` (`QuiverCharacterItemId`, `SlotIndex`)
);
```
---
## 🏹 Phase 3: Projectile Firing Mechanics
### 3.1 Weapon Requirements
**Ranged Weapons:**
- Bows (require arrows/bolts in quiver)
- Crossbows (require bolts in quiver)
- Javelins (throwable, don't require quiver)
- Throwing knives (throwable, don't require quiver)
**Item Properties:**
```csharp
public class DungeonItemDefinition
{
// Existing...
// NEW:
public bool RequiresAmmunition { get; set; } // Bows = true, throwing knives = false
public string? AmmunitionType { get; set; } // "arrow", "bolt", null for throwables
public float ProjectileSpeed { get; set; } // Pixels per second
public int Range { get; set; } // Max range in pixels
}
```
### 3.2 Firing Logic Flow
**Server-Side (DungeonHandler.cs):**
```csharp
// New opcode: FIRE_PROJECTILE
private async Task HandleFireProjectile(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var request = Deserialize<FireProjectileRequest>(payload);
// 1. Validate player has ranged weapon equipped
var weapon = GetEquippedItem(session, DungeonEquipmentSlot.MainHand);
if (weapon == null || weapon.ItemDefinition.Type != ItemType.Weapon)
return;
// 2. Get ammunition
Ammunition? ammo = null;
if (weapon.ItemDefinition.RequiresAmmunition)
{
ammo = ConsumeAmmunitionFromQuiver(session);
if (ammo == null)
{
SendError(connection, "No ammunition!");
return;
}
}
// 3. Create projectile
var projectile = new Projectile
{
Id = Guid.NewGuid(),
OwnerId = session.CharacterId,
X = session.PlayerInstance.X,
Y = session.PlayerInstance.Y,
DirectionX = request.DirectionX,
DirectionY = request.DirectionY,
Speed = weapon.ItemDefinition.ProjectileSpeed,
Range = weapon.ItemDefinition.Range,
Damage = CalculateProjectileDamage(session, weapon, ammo),
DamageType = weapon.ItemDefinition.DamageTypeKey,
AmmunitionDefinitionId = ammo?.ItemDefinitionId
};
// 4. Add to dungeon simulation
dungeon.Projectiles.Add(projectile);
// 5. Broadcast to all players in dungeon
BroadcastProjectileSpawned(dungeon, projectile);
}
```
### 3.3 Damage Calculation Formula
```csharp
private int CalculateProjectileDamage(DungeonPlayerSession session, EquippedItem weapon, Ammunition? ammo)
{
var player = session.PlayerInstance;
var weaponDef = weapon.ItemDefinition;
// Base damage from weapon
int baseDamage = Random.Shared.Next(weaponDef.MinDamage, weaponDef.MaxDamage + 1);
// Add ammunition bonus
if (ammo != null)
{
baseDamage += Random.Shared.Next(ammo.MinDamage, ammo.MaxDamage + 1);
}
// Calculate stat contribution
// Formula: (STR * 0.3 + DEX * 0.7) = stat modifier
float statModifier = (player.Strength * 0.3f + player.Dexterity * 0.7f);
// Apply stat scaling (1% per point)
float statBonus = baseDamage * (statModifier / 100f);
int totalDamage = (int)(baseDamage + statBonus);
return totalDamage;
}
```
**Alternative Formulas to Consider:**
- **STR 50% / DEX 50%:** `(STR * 0.5 + DEX * 0.5) * 0.01 * baseDamage`
- **DEX Only:** `DEX * 0.015 * baseDamage` (pure dex scaling)
- **Weapon Dependent:** Bows use DEX, crossbows use STR+DEX
---
## 💥 Phase 4: Projectile Physics & Collision
### 4.1 Server-Side Projectile Tick
```csharp
private void UpdateProjectiles(DungeonInstance dungeon, float deltaTime)
{
var toRemove = new List<Projectile>();
foreach (var projectile in dungeon.Projectiles)
{
// Move projectile
projectile.X += projectile.DirectionX * projectile.Speed * deltaTime;
projectile.Y += projectile.DirectionY * projectile.Speed * deltaTime;
projectile.DistanceTraveled += projectile.Speed * deltaTime;
// Check range
if (projectile.DistanceTraveled >= projectile.Range)
{
toRemove.Add(projectile);
continue;
}
// Check mob collision
foreach (var mob in dungeon.Simulation.Mobs.Values)
{
if (IsColliding(projectile, mob))
{
// Deal damage
ApplyDamage(mob, projectile.Damage, projectile.DamageType);
// Show damage notification
BroadcastDamageNotification(dungeon, mob.Id, projectile.Damage, projectile.DamageType, isCrit: false);
// Arrow recovery chance
if (projectile.AmmunitionDefinitionId.HasValue)
{
TryRecoverArrow(dungeon, projectile, mob);
}
toRemove.Add(projectile);
BroadcastProjectileHit(dungeon, projectile.Id, mob.Id);
break;
}
}
}
// Remove finished projectiles
foreach (var p in toRemove)
dungeon.Projectiles.Remove(p);
}
```
### 4.2 Arrow Recovery System
```csharp
private void TryRecoverArrow(DungeonInstance dungeon, Projectile projectile, MobInstance mob)
{
const float BASE_RECOVERY_CHANCE = 0.05f; // 5%
// TODO: Add bonuses from:
// - Quiver bonuses
// - Skill perks
// - Enchantments
float recoveryChance = BASE_RECOVERY_CHANCE;
if (Random.Shared.NextDouble() < recoveryChance)
{
// Add to mob's guaranteed loot
if (!mob.GuaranteedLoot.ContainsKey(projectile.AmmunitionDefinitionId.Value))
{
mob.GuaranteedLoot[projectile.AmmunitionDefinitionId.Value] = 0;
}
mob.GuaranteedLoot[projectile.AmmunitionDefinitionId.Value]++;
_log.LogDebug("Arrow recovered! Added {AmmoId} to mob {MobId} loot",
projectile.AmmunitionDefinitionId.Value, mob.Id);
}
}
```
---
## 🔔 Phase 5: Damage Notifications
### 5.1 Server Broadcast
```csharp
private void BroadcastDamageNotification(
DungeonInstance dungeon,
ulong targetId,
int damage,
string damageType,
bool isCrit,
bool isPlayer = false)
{
var notification = new
{
targetId,
targetType = isPlayer ? "player" : "mob",
damage,
damageType,
isCrit,
timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
};
BroadcastToAll(dungeon, DungeonOpCodes.DAMAGE_NOTIFICATION, notification);
}
```
### 5.2 Client-Side Display (Pseudocode for Client)
```javascript
// Client receives DAMAGE_NOTIFICATION
onDamageNotification(data) {
const target = data.targetType === 'player'
? getPlayer(data.targetId)
: getMob(data.targetId);
if (!target) return;
// Create floating damage text
const damageText = {
x: target.x,
y: target.y - 30,
text: `-${data.damage}`,
color: getDamageColor(data.damageType),
fontSize: data.isCrit ? 24 : 16,
duration: 1500,
velocity: { x: 0, y: -50 }
};
floatingTexts.push(damageText);
}
function getDamageColor(damageType) {
switch(damageType) {
case 'physical': return '#ffffff';
case 'fire': return '#ff4500';
case 'ice': return '#00bfff';
case 'poison': return '#00ff00';
case 'holy': return '#ffd700';
default: return '#ffffff';
}
}
```
---
## 🎨 Phase 6: Client-Side Integration Needs
### 6.1 Required Client Features
1. **Input Handling:**
- Detect mouse click / attack button
- Calculate direction from player to mouse cursor
- Send `FIRE_PROJECTILE` packet with direction
2. **Projectile Rendering:**
- Spawn projectile sprite at player position
- Animate movement from server updates
- Play arrow whoosh sound
- Remove on hit/expire
3. **UI Updates:**
- Quiver slot in equipment panel
- Necklace slot in equipment panel
- Ammunition count display
- Quiver container UI (if using container)
4. **Damage Numbers:**
- Floating text system
- Color-coded by damage type
- Critical hit animations (larger, different color)
### 6.2 Network Protocol
**New OpCodes:**
```csharp
public enum DungeonOpCodes
{
// Existing...
// NEW:
FIRE_PROJECTILE = 400, // Client → Server
PROJECTILE_SPAWNED = 401, // Server → Client
PROJECTILE_HIT = 402, // Server → Client
PROJECTILE_EXPIRED = 403, // Server → Client
DAMAGE_NOTIFICATION = 404, // Server → Client
QUIVER_UPDATE = 405, // Server → Client (ammo count changed)
}
```
**Packet Structures:**
```csharp
// Client sends this
public class FireProjectileRequest
{
public float DirectionX { get; set; } // Normalized
public float DirectionY { get; set; } // Normalized
}
// Server broadcasts this
public class ProjectileSpawnedEvent
{
public Guid ProjectileId { get; set; }
public ulong OwnerId { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float DirectionX { get; set; }
public float DirectionY { get; set; }
public float Speed { get; set; }
public int SpriteId { get; set; }
}
public class ProjectileHitEvent
{
public Guid ProjectileId { get; set; }
public ulong TargetId { get; set; }
public bool IsPlayer { get; set; }
}
```
---
## 📋 Phase 7: Implementation Checklist
### Database & Schema
- [ ] Create EF Core migration for new equipment slots
- [ ] Add `ItemType.Ammunition` and `ItemType.QuiverContainer`
- [ ] Create `dungeon_quiver_ammo_slots` table
- [ ] Add weapon properties: `RequiresAmmunition`, `AmmunitionType`, `ProjectileSpeed`, `Range`
- [ ] Add ammunition properties: damage ranges, bonuses, recovery modifiers
### Server-Side Core
- [ ] Add `Projectile` class to dungeon simulation
- [ ] Implement `HandleFireProjectile` handler
- [ ] Implement `UpdateProjectiles` tick logic
- [ ] Implement `CalculateProjectileDamage` formula
- [ ] Implement arrow recovery mechanic
- [ ] Add quiver slot handling to equip/unequip logic
- [ ] Add necklace slot handling to equip/unequip logic
### Quiver Container System
- [ ] Create `QuiverContainer` entity/model
- [ ] Implement quiver ammo slot management
- [ ] Handle equipping/unequipping quiver containers
- [ ] Handle adding/removing ammo from quiver slots
- [ ] UI for managing quiver contents (admin panel)
### Damage System
- [ ] Implement `BroadcastDamageNotification`
- [ ] Add damage type tracking
- [ ] Add critical hit logic
- [ ] Integrate with existing damage calculation
### UI Updates
- [ ] Update admin Character.cshtml equipment list (add Quiver, Necklace)
- [ ] Update Character.cshtml.cs computed stats (if quiver/necklace provide stats)
- [ ] Add quiver management UI (if using containers)
### Client-Side (Path Needed!)
- [ ] Add FIRE_PROJECTILE input handling
- [ ] Add projectile rendering system
- [ ] Add damage notification floating text
- [ ] Add equipment slots UI (quiver, necklace)
- [ ] Add quiver ammo count display
- [ ] Add sounds (arrow whoosh, hit, etc.)
### Testing
- [ ] Test direct ammo equip (stack of arrows in quiver slot)
- [ ] Test quiver container equip (quiver with multiple ammo types)
- [ ] Test firing with different weapons (bow, crossbow, throwables)
- [ ] Test arrow recovery at 5% rate
- [ ] Test damage calculations with various stat combinations
- [ ] Test damage notifications appearance
- [ ] Test edge cases (no ammo, out of range, invalid targets)
---
## 🔧 Technical Considerations
### Performance
- **Projectiles:** Limit max projectiles per dungeon (e.g., 100)
- **Collision:** Use spatial partitioning for large dungeons
- **Broadcasting:** Only send projectile updates to players in same dungeon
### Balance
- **Arrow Recovery:** Start at 5%, allow buffs up to 100%
- **Damage Scaling:** Fine-tune STR/DEX ratio after testing
- **Ammunition Cost:** Make arrows cheap enough to use freely
- **Quiver Capacity:** 3-5 slots for containers, 100 stack for direct equip
### Security
- **Validate Direction:** Ensure normalized vectors
- **Rate Limiting:** Prevent spam (max 2-3 attacks per second)
- **Range Checks:** Don't trust client, validate server-side
- **Ammunition Checks:** Server is source of truth for ammo count
---
## 🚀 Recommended Implementation Order
1. ✅ **Phase 1:** Database schema (equipment slots enum) - DONE
2. **Phase 2:** Database migration + ammunition item types
3. **Phase 3:** Basic projectile firing (no quiver, simple damage)
4. **Phase 4:** Damage notifications
5. **Phase 5:** Arrow recovery mechanic
6. **Phase 6:** Quiver container system
7. **Phase 7:** Client-side rendering & UI
8. **Phase 8:** Polish, balancing, testing
---
## ❓ Questions for You
1. **Client Path:** What's the absolute path to your client codebase?
2. **Client Technology:** What's the client built with? (Unity, Godot, Phaser, custom engine?)
3. **Quiver Preference:** Should we start with simple (direct ammo equip) or complex (container system)?
4. **Damage Formula:** Prefer STR 30% / DEX 70%, or different ratio?
5. **Arrow Recovery:** Should recovery chance vary by arrow type? (cheap arrows = 5%, expensive = 20%)
6. **Throwables:** Should throwing knives/axes consume from inventory or be infinite?
Let me know your answers and I'll proceed with implementation!