# TarkovAddonsRefactored Architecture

## 1. Purpose and Scope

TarkovAddonsRefactored is a Windows x64 C++20 DLL organized as a modular monolith. It integrates with an IL2CPP/Unity host process, installs game-loop and DirectX 11 hooks, executes feature logic on host-owned update callbacks, and renders an ImGui-based user interface.

The architecture separates feature policy from platform and game-specific mechanisms. Feature code depends on application contracts and abstract gateways. EFT, IL2CPP, Unity, Windows, persistence, hooking, and rendering details are implemented in adapter projects and assembled by the bootstrap project.

## 2. Architectural Style

The codebase combines several compatible patterns:

- **Layered architecture** for dependency control.
- **Ports and adapters** for isolating game, platform, persistence, and rendering APIs.
- **Composition root** for explicit runtime assembly.
- **Modular monolith** for separately compiled internal libraries linked into one DLL.
- **Command and snapshot messaging** for communication across callback and render threads.
- **Transactional lifecycle management** for startup rollback and controlled shutdown.

The intended dependency rule is inward-facing: platform and game details depend on feature/application contracts, while the core layers remain independent of Windows, Unity, EFT, IL2CPP, DirectX, and ImGui implementations.

## 3. Project Dependency Graph

```text
TarkovAddonsRefactored.dll
├── ta_presentation
├── ta_adapters
├── ta_features
├── ta_application
└── ta_foundation

 ta_presentation ──> ta_features ──> ta_application ──> ta_foundation
        │                 │                 │
        └─────────────────┴─────────────────┘

 ta_adapters ─────> ta_features
        ├─────────> ta_application
        └─────────> ta_foundation
```

### Build targets

| Target | Output | Responsibility |
|---|---|---|
| `ta_foundation` | Static library | General-purpose runtime primitives and utilities |
| `ta_application` | Static library | Use-case contracts, configuration, lifecycle, messaging, scheduling, diagnostics |
| `ta_features` | Static library | Feature behavior and feature-facing ports |
| `ta_adapters` | Static library | EFT, IL2CPP, Unity, Windows, hooking, rendering, and persistence implementations |
| `ta_presentation` | Static library | ImGui menus, pages, widgets, overlays, fonts, themes, localization |
| `TarkovAddonsRefactored` | DLL | Composition root, startup, shutdown, module registration, exported shutdown entry point |

## 4. Source Layout

```text
src/
├── foundation/       Low-level reusable primitives
├── application/      Runtime policy and cross-layer contracts
├── features/         Feature implementations and ports
├── adapters/         External-system implementations
├── presentation/     ImGui UI and overlays
├── bootstrap/        Composition root and runtime lifecycle
├── external/         Third-party source and libraries
├── locales/          UI localization resources
└── resources/        Runtime binary resources
```

### Foundation

`foundation` contains code that has no product-specific orchestration responsibility. Important areas include:

- `concurrency`: atomic ports, command queues, coalescing slots, copy snapshots, shared immutable snapshots.
- `diagnostics`: logging, crash diagnostics, build options.
- `math`, `memory`, `serialization`, `text`, `time`, `types`, `io`, `input`, and hashing utilities.

### Application

`application` defines the runtime-facing contracts and shared policy:

- UI command and read-model contracts.
- Configuration registry, persistence abstraction, command processing, and UI snapshot production.
- Application and game tick interfaces.
- Runtime phase, callback barrier, raid context, and lifecycle state.
- Diagnostic aggregation and loop timing.
- UI action dispatch and presentation state bridges.

This layer should remain independent of EFT, IL2CPP, Unity, DirectX, Windows, and ImGui implementation headers.

### Features

`features` contains feature behavior grouped by domain:

- Aimbot, conditionally compiled.
- Chams.
- ESP.
- Items.
- Player.
- Quests.
- Watermark.
- World.

A feature typically consumes abstract settings and gateway interfaces and may implement `IApplicationTick`, `IGameTick`, initialization, or session-reset behavior.

### Adapters

`adapters` supplies implementations for external systems:

- EFT object access, localization, player/world/item services, and feature gateways.
- IL2CPP exports, metadata, method invocation, collections, and object wrappers.
- Unity bindings and resources.
- Windows input, display metrics, storage, console, window procedures, and DirectX 11 rendering.
- Hook installation and callback bridges.
- File-backed configuration persistence.

### Presentation

`presentation` converts application snapshots and feature query results into ImGui views. It owns menu state, pages, widgets, overlays, fonts, themes, viewport scaling, action feedback, and UI localization.

Presentation submits commands through contracts. It does not directly mutate game objects.

### Bootstrap

`bootstrap` is the executable composition boundary. It creates concrete adapters, features, module ports, the application runtime, and the menu controller. It also controls DLL startup, hook installation, shutdown, and rollback.

## 5. Composition Model

`ApplicationRuntime` is the central application composition object. It owns shared services and feature modules, including:

- `EftGameContext`.
- Item catalog and wishlist services.
- UI action dispatcher.
- Feature modules.
- Configuration persistence and `ConfigService`.
- Application and game tick schedulers.
- Diagnostics registry.
- UI locale controller.

Each bootstrap module follows a consistent assembly pattern:

```text
Config adapter ─┐
                ├──> Feature ───> ModulePorts
Gateway ────────┘
```

`ModulePorts::bind` performs lightweight compile-time capability detection. It exposes only the capabilities implemented by a feature:

- `IApplicationTick`.
- `IGameTick`.
- `initialize()`.
- `reset_session()`.
- Optional configuration ownership.

`ApplicationRuntime` registers these ports with the appropriate schedulers and lifecycle collections. This keeps feature-specific lifecycle details out of the central coordinator.

## 6. Runtime Lifecycle

### DLL entry

`DllMain` performs minimal loader-lock-safe work:

1. Disables thread attach/detach notifications.
2. Captures the module path while the loader entry is still available.
3. Starts a dedicated runtime thread.

Shutdown is explicit through the exported `TarkovAddonsRefactoredRequestShutdown` function. Hook removal and callback waiting are intentionally kept outside `DllMain`.

### Startup sequence

`RuntimeHost::start` changes the runtime phase to `Starting` and delegates to `RuntimeStartup`. Startup proceeds through named stages:

```text
Storage and logging
→ Localization
→ Chams resource initialization
→ Unity window discovery
→ IL2CPP initialization
→ Unity API initialization
→ Application graph construction
→ Display metrics discovery
→ DirectX library readiness
→ DXGI Present hook installation
→ Game/feature hook installation
→ Running
```

Every startup failure returns a structured stage, code, and detail. `RuntimeHost` then executes shutdown as a rollback and moves the runtime to `Failed`.

### Shutdown sequence

`RuntimeShutdown` follows an ownership-safe order:

1. Stop accepting feature work through `CallbackBarrier`.
2. Detach the Present hook and game hooks.
3. Wait for in-flight callbacks to leave the barrier.
4. Release hook-owned rendering and callback state.
5. Destroy the menu and application graph only when callbacks are idle and relevant hooks are detached.
6. Reset shared resources, localization, diagnostics, storage, and console state.

When a hook cannot detach or the barrier times out, dependent state is preserved to avoid use-after-free behavior from a remaining callback.

### Runtime phases

The runtime state machine is:

```text
None → Starting → Running → Stopping → Stopped
                  │             │
                  └─────────────┴→ Failed
```

Callbacks check runtime state before executing feature work.

## 7. Execution Loops

The runtime is driven by host callbacks rather than a private polling loop.

### Application update loop

The application loop is invoked from the hooked application update path. `ApplicationRuntime::application_update` performs:

1. Read the stable raid state.
2. Detect raid entry or exit.
3. Reset raid-scoped modules after raid exit.
4. Consume pending configuration commands.
5. Execute registered `IApplicationTick` participants.
6. Persist changed configuration and publish updated UI/settings snapshots.
7. Record loop timing and crash-diagnostic stages.

### Game-world update loop

The game loop is invoked from the hooked game-world update path. `ApplicationRuntime::gameworld_update` performs:

1. Update the item template catalog.
2. Update wishlist state using the current main player.
3. Publish the current EFT game context.
4. Execute registered `IGameTick` participants.
5. Record loop timing and crash-diagnostic stages.

Game-object operations belong on this loop because it receives valid host-owned IL2CPP objects.

### Render loop

The DirectX 11 adapter hooks `IDXGISwapChain::Present`. The render callback:

1. Enters crash diagnostics and the callback barrier.
2. Falls back to the original Present call when runtime callbacks are disabled.
3. Lazily initializes the D3D11 device, context, render target, window hook, and ImGui host.
4. Starts an ImGui frame.
5. Calls the presentation client to capture snapshots and draw menus/overlays.
6. Renders ImGui draw data to the current render target.
7. Calls the original Present function.

## 8. Threading and Data Exchange

The host controls the application, game, and render callback threads. Direct cross-thread mutation is minimized through explicit messaging primitives.

### Commands

UI operations are submitted to application-owned queues and consumed on a host update callback.

- `CommandQueue<T>` preserves every command in FIFO order.
- `CoalescingCommandSlot<T>` retains only the latest pending value for replaceable requests.

### Snapshots

Application and feature state is published for readers as snapshots.

- `SharedSnapshotPublisher<T>` publishes immutable `shared_ptr<const T>` snapshots with atomic release/acquire semantics.
- `CopySnapshotPublisher<T>` protects small optional value snapshots with a mutex.
- `AtomicPort<T>` publishes trivially copyable bridge state.

The normal UI flow is:

```text
Render thread
  └── submit command
          ↓
Application or game callback
  ├── consume command
  ├── mutate owned state
  └── publish immutable snapshot
          ↓
Render thread
  └── acquire and render snapshot
```

### Callback barrier

`CallbackGuard` increments an active callback count before checking whether feature work is accepted. During shutdown, the barrier rejects new feature work and waits for all entered callbacks to leave. This closes the race between callback admission and object destruction.

## 9. Configuration Architecture

`ConfigService` is the application-level coordinator for configuration. It owns:

- A registry of the global configuration owner and feature configuration owners.
- A command processor for UI-submitted configuration changes.
- A persistence coordinator backed by the `IConfigPersistence` port.
- Settings and UI snapshot publishers.
- Command diagnostics and revision tracking.

The configuration update cycle is:

```text
UI command submission
→ command queue
→ application update consumption
→ registry mutation
→ persistence on revision change
→ settings/UI snapshot publication
```

Concrete file storage is implemented by `FileConfigPersistence` in the adapter layer.

## 10. Diagnostics and Failure Handling

Diagnostics are integrated at several boundaries:

- Named startup stages and structured startup errors.
- Runtime phase tracking.
- Crash stage markers around application, game, render, and module callbacks.
- Hook installation and hit diagnostics.
- Application/game/render duration metrics.
- Configuration and feature command requested/consumed counters.
- Session log rotation and dedicated crash-diagnostics logs.

`DiagnosticsRegistry` composes subsystem snapshots for the diagnostics page only when requested by the presentation layer.

## 11. Build and Packaging

The supported build platform is Windows x64 with C++20 and MSBuild. The primary script is:

```powershell
.\build.ps1 -Configuration Release -Flavor NoAimbot
.\build.ps1 -Configuration Release -Flavor WithAimbot
```

Convenience wrappers are provided by `build-no-aimbot.bat` and `build-with-aimbot.bat`.

### Build flavors

| Flavor | `EnableAimbot` | `INCLUDE_AIMBOT` scope |
|---|---:|---|
| `NoAimbot` | `false` | Disabled |
| `WithAimbot` | `true` | Final DLL, `ta_adapters`, and `ta_features` |

`build/Flavor.props` determines whether a project is aimbot-aware from `$(MSBuildProjectName)`. The final DLL project must match `TarkovAddonsRefactored` exactly so the composition root and conditional bootstrap module compile with the same feature definition as the feature and adapter libraries.

The `Package` target builds the DLL, copies locale files and `chams.bundle`, validates required files, and removes import/debug artifacts from the package directory.

## 12. Adding a Feature Module

A new feature should follow this sequence:

1. Define settings, commands, queries, and external gateway interfaces in `features/<feature>` or application contracts where shared.
2. Implement feature policy without including adapter-specific APIs.
3. Implement EFT/Unity/Windows gateway and persistence details in `adapters`.
4. Add a bootstrap module that constructs the settings adapter, gateway, feature, and `ModulePorts`.
5. Register the module in `ApplicationRuntime`.
6. Add presentation pages or overlays that consume query/read-model snapshots and submit commands.
7. Register configuration ownership and diagnostics when applicable.
8. Define reset scope as `Raid` or `Session`.
9. Verify both `NoAimbot` and `WithAimbot` build flavors when conditional code is involved.

## 13. Architectural Constraints

The following constraints preserve the current design:

- Core layers must not include Windows, DirectX, Unity, EFT, IL2CPP, or ImGui implementation headers.
- Presentation must communicate through read models, queries, and commands.
- Game object access must remain in adapter implementations and host-safe callback paths.
- Cross-thread state should use commands, snapshots, or atomic bridge types.
- Hook callbacks must preserve the original host call path when runtime work is unavailable.
- Shutdown must detach callbacks before destroying callback-owned state.
- Feature modules should expose lifecycle capabilities through `ModulePorts` instead of adding feature-specific branches to `ApplicationRuntime`.

## 14. Known Architectural Risks

Current areas that require continued attention:

- Tick schedulers do not isolate C++ exceptions per module; an exception escaping a callback can terminate the process.
- The adapter project has a broad responsibility surface and may benefit from decomposition into EFT, IL2CPP, Unity, Windows/rendering, hooking, and persistence libraries.
- Several runtime bridges use singleton or file-static state, which limits restartability and test isolation.
- `ApplicationRuntime` may become a central coordinator with excessive responsibilities as modules are added.
- Automated unit, integration, and build-flavor regression tests are not currently present in the repository.

These risks do not invalidate the dependency model, but they define the highest-value areas for further hardening.
