Skip to content

Latest commit

 

History

History
418 lines (331 loc) · 11.4 KB

File metadata and controls

418 lines (331 loc) · 11.4 KB

🏗️ Native 架构设计

文档版本:v0.0.1
最后更新:2025-10-11


📐 总体架构

┌─────────────────────────────────────────────────────┐
│                  Examples Layer                      │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐          │
│  │ CPP 组件 │  │ Bit 组件 │  │自定义组件│          │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘          │
│       │             │             │                  │
└───────┼─────────────┼─────────────┼──────────────────┘
        │             │             │
        └─────────────┴─────────────┘
                      │
┌─────────────────────┼──────────────────────────────┐
│         Runtime API Interface (runtime_api.h)      │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐            │
│  │ IWindow │  │IRenderer│  │ IInput  │            │
│  └─────────┘  └─────────┘  └─────────┘            │
└─────────────────────┼──────────────────────────────┘
                      │
┌─────────────────────┼──────────────────────────────┐
│            Native Implementation Layer              │
│  ┌──────────────┐  ┌──────────────┐               │
│  │  Window Mgr  │  │  Input Mgr   │               │
│  │ (Win32/...)  │  │              │               │
│  └──────────────┘  └──────────────┘               │
│                                                     │
│  ┌──────────────────────────────────────┐         │
│  │      Vulkan Renderer (VkApp)         │         │
│  │  ┌────────┐  ┌────────┐  ┌────────┐ │         │
│  │  │Swapchain│ │RenderPass│ │Pipeline│ │         │
│  │  └────────┘  └────────┘  └────────┘ │         │
│  └──────────────────────────────────────┘         │
└───────────────────────────────────────────────────┘
                      │
┌─────────────────────┼──────────────────────────────┐
│                  Platform Layer                     │
│  ┌──────────────┐  ┌──────────────┐               │
│  │   Vulkan     │  │  Win32 API   │               │
│  │   (Instance, │  │  (Window,    │               │
│  │    Device)   │  │   Message)   │               │
│  └──────────────┘  └──────────────┘               │
└───────────────────────────────────────────────────┘

🎯 设计原则

1. 接口抽象

目标:隔离平台细节,提供统一的运行时接口

// 组件只需要知道接口,不需要知道实现
BitHCI::IRenderer* renderer;
renderer->drawTriangle(vertices, colors);

优势

  • ✅ 平台无关性
  • ✅ 易于测试和模拟
  • ✅ 支持多后端(Vulkan, DirectX, Metal...)

2. 组件隔离

目标:每个组件独立运行,互不干扰

// 组件通过标准接口加载
IComponent* component = loadComponent("triangle.dll");
component->onInit(window, renderer, input, resources);

优势

  • ✅ 模块化开发
  • ✅ 热重载支持
  • ✅ 动态加载/卸载

3. 生命周期管理

组件生命周期

   [创建]
      ↓
   onInit()  ← 初始化资源
      ↓
   ┌────────┐
   │ 主循环 │
   │        │
   │ onUpdate() → onRender()
   │    ↑            ↓
   │    └────────────┘
   └────────┘
      ↓
  onDestroy() ← 清理资源
      ↓
   [销毁]

🔌 接口设计

核心接口

namespace BitHCI {

// 窗口接口
class IWindow {
    virtual int getWidth() const = 0;
    virtual int getHeight() const = 0;
    virtual bool shouldClose() const = 0;
};

// 渲染接口
class IRenderer {
    virtual void beginFrame() = 0;
    virtual void endFrame() = 0;
    virtual void drawTriangle(...) = 0;
    virtual void drawRectangle(...) = 0;
    virtual void drawText(...) = 0;
};

// 输入接口
class IInput {
    virtual bool isKeyPressed(int keyCode) const = 0;
    virtual void getMousePosition(float& x, float& y) const = 0;
};

// 资源接口
class IResourceManager {
    virtual void* loadTexture(const char* path) = 0;
    virtual void* loadFont(const char* path, float size) = 0;
};

// 组件接口
class IComponent {
    virtual void onInit(...) = 0;
    virtual void onUpdate(float deltaTime) = 0;
    virtual void onRender() = 0;
    virtual void onDestroy() = 0;
};

} // namespace BitHCI

🎨 渲染管线

Vulkan 渲染流程

帧开始
  ↓
acquireNextImage() ← 获取可用的交换链图像
  ↓
beginCommandBuffer() ← 开始记录命令
  ↓
beginRenderPass() ← 开始渲染通道
  ↓
[组件渲染调用]
  ↓
  drawTriangle()
  drawRectangle()
  drawText()
  ...
  ↓
endRenderPass() ← 结束渲染通道
  ↓
endCommandBuffer() ← 结束命令记录
  ↓
queueSubmit() ← 提交到 GPU
  ↓
queuePresent() ← 呈现到屏幕
  ↓
帧结束

同步机制

// 帧同步对象
VkSemaphore imageAvailableSemaphore;  // 图像可用信号
VkSemaphore renderFinishedSemaphore;  // 渲染完成信号
VkFence inFlightFence;                // 帧完成栅栏

// 等待上一帧完成
vkWaitForFences(device, 1, &inFlightFence, VK_TRUE, UINT64_MAX);

// 获取下一帧图像
vkAcquireNextImageKHR(..., imageAvailableSemaphore, ...);

// 提交渲染命令
VkSubmitInfo submitInfo = {};
submitInfo.waitSemaphores = {imageAvailableSemaphore};
submitInfo.signalSemaphores = {renderFinishedSemaphore};
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFence);

// 呈现
VkPresentInfoKHR presentInfo = {};
presentInfo.waitSemaphores = {renderFinishedSemaphore};
vkQueuePresentKHR(presentQueue, &presentInfo);

📦 组件加载机制

动态库加载

// Windows 平台
HMODULE dll = LoadLibrary("component.dll");
ComponentFactory factory = (ComponentFactory)GetProcAddress(dll, "createComponent");
IComponent* component = factory();

// Linux 平台
void* so = dlopen("component.so", RTLD_LAZY);
ComponentFactory factory = (ComponentFactory)dlsym(so, "createComponent");
IComponent* component = factory();

组件注册

// 组件管理器
class ComponentManager {
private:
    std::vector<IComponent*> components;
    
public:
    void registerComponent(IComponent* component) {
        components.push_back(component);
        component->onInit(window, renderer, input, resources);
    }
    
    void updateAll(float deltaTime) {
        for (auto* comp : components) {
            comp->onUpdate(deltaTime);
        }
    }
    
    void renderAll() {
        renderer->beginFrame();
        for (auto* comp : components) {
            comp->onRender();
        }
        renderer->endFrame();
    }
};

🔧 扩展点

1. 新增平台支持

// 添加新平台
#ifdef BITUI_PLATFORM_LINUX
    // Linux 窗口实现
    LinuxWindow window;
#elif BITUI_PLATFORM_MACOS
    // macOS 窗口实现
    CocoaWindow window;
#endif

2. 新增渲染后端

// 抽象渲染器接口
class IRendererBackend {
    virtual void initialize() = 0;
    virtual void shutdown() = 0;
    virtual void drawPrimitive(...) = 0;
};

// Vulkan 实现
class VulkanRenderer : public IRendererBackend { ... };

// DirectX 实现
class DX12Renderer : public IRendererBackend { ... };

// Metal 实现
class MetalRenderer : public IRendererBackend { ... };

3. 新增输入设备

class IInput {
    // 键盘
    virtual bool isKeyPressed(int key) = 0;
    
    // 鼠标
    virtual void getMousePosition(float& x, float& y) = 0;
    
    // 触摸屏(扩展)
    virtual int getTouchCount() = 0;
    virtual void getTouchPosition(int index, float& x, float& y) = 0;
    
    // 游戏手柄(扩展)
    virtual bool isGamepadConnected(int id) = 0;
    virtual float getGamepadAxis(int id, int axis) = 0;
};

📊 性能考虑

1. 命令缓冲复用

// 预分配命令缓冲
std::vector<VkCommandBuffer> commandBuffers(swapchainImages.size());

// 重用而非每帧重新分配
vkResetCommandBuffer(commandBuffers[currentFrame], 0);

2. 描述符池管理

// 使用对象池避免频繁分配
class DescriptorPool {
    std::vector<VkDescriptorSet> freeDescriptors;
    
    VkDescriptorSet allocate() {
        if (freeDescriptors.empty()) {
            // 批量分配
            allocateDescriptors(freeDescriptors, 100);
        }
        return freeDescriptors.pop_back();
    }
};

3. 资源缓存

class ResourceCache {
    std::unordered_map<std::string, Texture*> textures;
    std::unordered_map<std::string, Font*> fonts;
    
    Texture* getTexture(const char* path) {
        auto it = textures.find(path);
        if (it != textures.end()) return it->second;
        // 否则加载
        return loadAndCache(path);
    }
};

🐛 错误处理

Vulkan 错误检查

#define VK_CHECK(call) \
    do { \
        VkResult result = call; \
        if (result != VK_SUCCESS) { \
            throw std::runtime_error("Vulkan error: " + std::to_string(result)); \
        } \
    } while(0)

// 使用
VK_CHECK(vkCreateInstance(&createInfo, nullptr, &instance));

组件错误隔离

try {
    component->onRender();
} catch (const std::exception& e) {
    // 记录错误但不影响其他组件
    logError("Component render failed: ", e.what());
    // 可选:标记组件为 disabled
    component->setEnabled(false);
}

🔗 相关文档


维护者:Bit Project 团队
文档版本:v0.0.1
最后更新:2025-10-11