Files
2026-01-23 00:31:21 +08:00

240 lines
9.1 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
BladeSmith is an Unreal Engine 5.6 C++ blacksmith simulation game where players forge bladed weapons through realistic physical processes. The core feature is GPU-accelerated plastic deformation of metal using compute shaders, combined with a voxel-based temperature system that determines material plasticity.
**Engine Version:** UE 5.6
**Language:** C++ with Blueprint integration
**Platform:** Windows (primary development target)
## Build and Development Commands
### Building the Project
From the UE5 engine directory:
```bash
# Build game target
"C:\Program Files\Epic Games\UE_5.6\Engine\Build\BatchFiles\Build.bat" BladeSmith Win64 Development "E:\MiceCola\work\BladeSmith\BladeSmith.uproject"
# Build editor target
"C:\Program Files\Epic Games\UE_5.6\Engine\Build\BatchFiles\Build.bat" BladeSmithEditor Win64 Development "E:\MiceCola\work\BladeSmith\BladeSmith.uproject"
```
Alternatively, open `BladeSmith.sln` in Visual Studio and build from there.
### Running the Project
1. Open `BladeSmith.uproject` in UE5.6 Editor
2. Press Alt+P or click Play to run in editor
3. Use Ctrl+F11 for hot reload after C++ changes
### Testing
Unreal Engine uses the Automation System:
- **In Editor:** Window → Developer Tools → Automation Sessions
- **Command Line:** `UE5Editor.exe BladeSmith.uproject -ExecCmds="Automation RunTests"`
## Architecture Overview
### Core Systems
**1. Dynamic Mesh Deformation System**
- `ADynamicIronBlock` (Source/BladeSmith/DynamicIronBlock.h/cpp) - Main iron block actor that handles all deformation
- Uses UE5's GeometryScripting API for runtime mesh manipulation
- Implements plastic deformation with volume-preserving bulge effects
- BVH acceleration structure for efficient collision detection
**2. Voxel-Based Temperature System**
- 3D temperature voxel grid (`FTemperatureVoxel`) stores temperature and plasticity coefficients
- Temperature affects material plasticity: 800-1200°C is the forging range
- Heat conduction simulation with surface cooling
- Per-vertex color visualization of temperature (black body radiation approximation)
- GPU-accelerated temperature computation using ping-pong buffers
**3. GPU Compute Pipeline (MiceShaders Plugin)**
- Custom compute shaders for physics simulation
- `FDeformComputeShader` - Plastic deformation calculations
- `FTemperatureComputeShader` - Heat conduction and cooling
- Located in `Plugins/MiceShaders/`
- Shaders written in HLSL (`.usf` files in `Shaders/Private/`)
- Uses RDG (Render Dependency Graph) for GPU dispatch
**4. Hammer Interaction System**
- `UBladeSmithWeaponComponent` (Source/BladeSmith/BladeSmithWeaponComponent.h/cpp) - First-person hammer tool
- Ray-cast based collision detection
- Enhanced Input system integration
- Triggers deformation on `ADynamicIronBlock` via `OnHammerImpact()`
### Key Classes and Their Relationships
```
ABladeSmithCharacter (Player)
└── UBladeSmithWeaponComponent (Hammer Tool)
└── OnHammerImpact()
└── ADynamicIronBlock (Iron Workpiece)
├── Temperature Voxel Grid (CPU/GPU)
├── Dynamic Mesh (GeometryScripting)
└── MiceShaders Compute Shaders
```
### Data Flow: Hammer Impact to Deformation
1. Player swings hammer (`UBladeSmithWeaponComponent::SwingHammer()`)
2. Ray-cast detects hit on `ADynamicIronBlock`
3. `OnHammerImpact()` receives: location, normal, radius, depth, force
4. Sample plasticity coefficient from temperature voxels at hit location
5. Apply plastic deformation to mesh vertices via `EditMesh()` lambda
6. Volume-preserving bulge effect applied around impact zone
7. Update vertex colors to visualize temperature
8. GPU compute shader updates temperature distribution
## Module Dependencies
**BladeSmith Module (Source/BladeSmith/BladeSmith.Build.cs):**
- GeometryScriptingCore, GeometryFramework, DynamicMesh
- GeometryCore, GeometryAlgorithms, ModelingComponents
- RenderCore, RHI, Renderer, PhysicsCore
- EnhancedInput
- AudioExtensions, AudioMixer, AudioPlatformConfiguration
- **MiceShaders** (custom plugin)
**MiceShaders Plugin:**
- Core, RenderCore, RHI
- Projects (for shader path resolution)
## Code Conventions
### File Headers
All source files must start with Epic copyright notice (as required by UE5 licensing).
### Naming Conventions
- **Actors:** `AClassName` (e.g., `ADynamicIronBlock`)
- **Components:** `UClassName` (e.g., `UBladeSmithWeaponComponent`)
- **Structs:** `FStructName` (e.g., `FTemperatureVoxel`)
- **Enums:** `EEnumName`
- **Functions:** PascalCase (e.g., `OnHammerImpact()`)
- **Variables:** PascalCase for properties, camelCase for locals
- **Constants:** PascalCase
### Type Usage
- Use UE5 types: `TArray<T>`, `TMap<K,V>`, `TSet<T>`, `FVector`, `FString`, `int32`, `uint8`
- Use `float` by default (not `double`)
- Smart pointers: rely on UObject garbage collection; use `TSharedPtr<T>` for non-UObjects
- String literals: wrap in `TEXT()` macro
### Indentation and Formatting
- **4 spaces** (no tabs)
- **Allman style braces** (opening brace on new line)
- Line length under 120 characters
### Threading and GPU Operations
```cpp
// Atomic flags for thread-safe GPU buffer status
std::atomic<bool> bGPUBuffersReady{false};
// Render thread commands
ENQUEUE_RENDER_COMMAND(CommandName)(
[Params](FRHICommandListImmediate& RHICmdList)
{
// GPU operations here
}
);
```
### Documentation
Comments use Chinese for domain-specific logic (e.g., "锤子组件", "温度体素结构").
## Important Implementation Details
### Temperature-Plasticity Relationship
- Plasticity = 0 below `ForgeTemperatureMin` (800°C by default)
- Plasticity = 1 above `ForgeTemperatureMax` (1200°C by default)
- Linear interpolation between min and max
- Deformation depth is multiplied by plasticity coefficient
### Deformation Parameters
- `FalloffExponent`: Controls edge transition smoothness (default: 2.0)
- `BulgeRatio`: Bulge radius relative to compression zone (default: 0.8)
- `BulgeStrength`: Bulge height intensity (default: 0.5)
- These simulate realistic plastic flow and volume conservation
### Vertex Color Mapping
- Each vertex samples temperature from voxel grid via trilinear interpolation
- Temperature is converted to color using black body radiation approximation
- Updated every frame when temperature changes occur
### GPU Buffer Management
- Uses ping-pong double buffering for temperature compute shader
- `TemperatureBufferA` and `TemperatureBufferB` alternate as read/write buffers
- Separate `PlasticityBuffer` stores derived plasticity coefficients
- `SurfaceVoxelFlagsBuffer` marks surface voxels for cooling calculations
- Buffers created on render thread, accessed via UAV/SRV
## Performance Targets
- **Frame time budget:** <7ms for deformation calculations
- **Target FPS:** 60 FPS during hammer operations
- **Mesh complexity:** Tested with ~100k vertices using GPU acceleration
- **Voxel resolution:** 50x50x50 typical (configurable via `TemperatureVoxelSize`)
## Adding New Compute Shaders
1. Create `.h` and `.cpp` in `Plugins/MiceShaders/Source/MiceShaders/Public|Private/`
2. Define shader class inheriting from `FGlobalShader`
3. Create corresponding `.usf` HLSL shader in `Plugins/MiceShaders/Shaders/Private/`
4. Use `IMPLEMENT_GLOBAL_SHADER()` macro to register
5. Dispatch via RDG in actor's Tick or specialized function
6. Reference existing shaders: `FDeformComputeShader`, `FTemperatureComputeShader`
## Key UE5 Patterns Used
**Dynamic Mesh Editing:**
```cpp
DynamicMesh->EditMesh([&](FDynamicMesh3& EditMesh)
{
// Modify mesh vertices/triangles here
}, EDynamicMeshChangeType::GeneralEdit);
```
**Material Parameter Updates:**
```cpp
DynamicMaterialInstance->SetScalarParameterValue(TEXT("AvgTemperature"), AvgTemp);
DynamicMaterialInstance->SetVectorParameterValue(TEXT("Color"), FLinearColor(R,G,B,A));
```
**Enhanced Input Binding:**
```cpp
if (UEnhancedInputComponent* EnhancedInput = Cast<UEnhancedInputComponent>(InputComponent))
{
EnhancedInput->BindAction(HammerAction, ETriggerEvent::Triggered, this, &ThisClass::SwingHammer);
}
```
## Plugin Structure
**Enabled Plugins (BladeSmith.uproject):**
- GeometryScripting (UE5 built-in)
- ModelingToolsEditorMode (UE5 built-in)
- HDRIBackdrop (UE5 built-in)
- RiderLink (in repository, for JetBrains Rider integration)
- MiceShaders (custom plugin)
## Content Organization
- `Content/BP/` - Blueprint actors and components
- `Content/Res/` - Game resources (meshes, materials, textures)
- `Content/Maps/` - Level maps
- `Content/Input/` - Enhanced Input assets
- `Content/FirstPersonArms/`, `Content/FPWeapon/` - First-person character assets
## Notes for AI Agents
- The AGENTS.md file contains comprehensive coding style guidelines; refer to it for detailed conventions
- When modifying deformation logic, always consider the temperature-plasticity coupling
- GPU buffer operations must be thread-safe; use atomic flags and render thread commands
- Test deformation with varying temperatures to ensure plasticity affects results correctly
- Voxel resolution trades off between accuracy and performance; adjust `TemperatureVoxelSize` accordingly