> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/custom-vision-components.md).

# 自定义视觉组件

为需要向 Convai chatbot 提供场景帧的自定义 Unreal 图像管道实现一个 C++ 帧源组件。

本页面向高级 C++ 项目。大多数团队应使用内置的 **环境摄像头** 组件，参阅 [视觉快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/vision-quick-start.md).

如果项目需要使用不同的图像源，请创建一个实现 `IConvaiVisionInterface` 的自定义组件，这样 `UConvaiChatbotComponent` 就能发现或注册该组件。如果从 `UConvaiWebcamBase`派生，请将 `USceneComponent`.

### 前提条件

* 已启用 Convai 插件的 C++ Unreal 项目。
* `ConvaiVisionBase` 已添加到模块的 `PublicDependencyModuleNames` 中，位于 `Build.cs`.
* 已完成可正常运行的聊天机器人设置，参阅 [添加你的第一个 Convai 角色](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/getting-started/add-your-first-convai-character.md).

### 何时实现自定义组件

**环境摄像头** 会将 `USceneCaptureComponent2D` 的画面渲染到 `UTextureRenderTarget2D`中。可用于标准的引擎内场景捕获。

以下情况适合使用自定义组件：

* 图像源来自外部 SDK，该 SDK 会在 Unreal 纹理管线之外生成原始像素数据。
* 你的管线已生成图像字节数据，并且需要完全控制 RGBA 转换。
* 你需要将程序生成或生成式图像流注入对话。
* 你正在封装一个非组件后端，并且需要为聊天机器人提供组件外观层。

### 选择基类

| 选项                                                 | 适用情况                                                                |
| -------------------------------------------------- | ------------------------------------------------------------------- |
| 从以下类派生： `UConvaiWebcamBase`                        | 你希望在蓝图中使用 **启动**, **停止**, **获取状态**, **设置最大 FPS**、错误获取函数以及 **帧就绪时**. |
| 直接在 `IConvaiVisionInterface` 上实现 `UActorComponent` | 你需要一个不继承 `UConvaiWebcamBase`、但仍通过以下方式注册的组件 **设置视觉组件** 或角色发现。        |

对于大多数自定义来源，请继承 `UConvaiWebcamBase`。根据来源需要重写相应的捕获方法，并让基类处理状态、FPS 存储和错误报告。

`bAutoStartVision` 仅存在于 `UEnvironmentWebcam`。自定义子类必须在 **Start** 中调用 `BeginPlay` ，或者公开自己的自动启动属性。

### 接口约定

下表列出了 `IConvaiVisionInterface` 中定义的纯虚方法，位于 `VisionInterface.h`。继承 `UConvaiWebcamBase`时，重写 `CanStart`, `CaptureRaw`，并可选择重写 `GetImageTexture` 或 `CaptureCompressed`.

| 方法                                       | 用途                   | 备注                                            |
| ---------------------------------------- | -------------------- | --------------------------------------------- |
| `void Start()`                           | 开始捕获。                | 随附的基类会将状态设为 `Capturing`.                      |
| `void Stop()`                            | 结束捕获。                | 随附的基类会将状态设为 `Stopped`.                        |
| `EVisionState GetState() const`          | 返回当前生命周期状态。          | 聊天机器人每个 tick 都会调用此方法，以控制是否上传。                 |
| `void SetMaxFPS(int MaxFPS)`             | 设置最大捕获帧率。            | `UConvaiWebcamBase` 会拒绝 `<= 0`这样的值。默认值为 `15`. |
| `int GetMaxFPS() const`                  | 返回当前最大帧率。            | 聊天机器人的上传会将实际发送速率限制为 `1`–`60`.                 |
| `bool IsCompressedDataAvailable() const` | 返回 `true` 如果预压缩帧已就绪。 | 这是接口契约的一部分。随附的聊天机器人流程使用 `CaptureRaw()`.       |
| `bool GetCompressedData(...)`            | 获取预压缩帧。              | 自定义集成可选。                                      |
| `bool CaptureCompressed(...)`            | 按需采集并压缩。             | 可选。随附的聊天机器人流程使用 `CaptureRaw()`.               |
| `bool CaptureRaw(...)`                   | 采集原始 RGBA 帧。         | 聊天机器人上传所必需。填充行优先排列的 RGBA 字节，并在成功时返回 `true` 。  |
| `UTexture* GetImageTexture(...)`         | 返回当前帧纹理。             | 将 `TextureSourceType` 设置为与纹理类型匹配。             |
| `FString GetLastErrorMessage() const`    | 返回最近一次错误的易读描述。       | 如果未发生错误，则返回空字符串。                              |
| `int GetLastErrorCode() const`           | 返回最近一次错误的数值代码。       | `UConvaiWebcamBase` 会将此值初始化为 `-1`.            |

### 基于 UConvaiWebcamBase 实现

`UConvaiWebcamBase` 声明于 `ConvaiWebcamBase.h` 中，属于 `ConvaiVisionBase` 模块。

{% stepper %}
{% step %}

#### 声明类

创建一个 `USceneComponent` 子类，使其派生自 `UConvaiWebcamBase`。如果希望它出现在组件选择器中，请将其标记为 `BlueprintSpawnableComponent` 。

```cpp
// MyCustomVisionComponent.h
// 伪代码：请将 FMyImageSource 替换为你自己的图像源类型。
#pragma once

#include "ConvaiWebcamBase.h"
#include "MyCustomVisionComponent.generated.h"

UCLASS(ClassGroup=(Convai), meta=(BlueprintSpawnableComponent))
class MYPROJECT_API UMyCustomVisionComponent : public UConvaiWebcamBase
{
    GENERATED_BODY()

protected:
    virtual bool CanStart() override;
    virtual bool CaptureRaw(int& Width, int& Height, TArray<uint8>& Data) override;

private:
    TSharedPtr<FMyImageSource> MyImageSource;
};
```

{% endstep %}

{% step %}

#### 重写 CanStart

`CanStart` 会在基类转换到 `Capturing`之前运行。仅当数据源已初始化时，才返回 `true` 。数据源未就绪时，请调用 `SetErrorCodeAndMessage` ，以便 **Get Last Error Message** 和 **Get Last Error Code** 在 Blueprint 中返回有用的值。

```cpp
// MyCustomVisionComponent.cpp
// 伪代码
bool UMyCustomVisionComponent::CanStart()
{
    if (!MyImageSource.IsValid())
    {
        SetErrorCodeAndMessage(1, TEXT("Image source is not initialized."), /*bPrintToLog=*/true);
        return false;
    }
    return true;
}
```

{% endstep %}

{% step %}

#### 重写 CaptureRaw

`CaptureRaw` 由聊天机器人上传流程调用。将 `Width`, `Height`和 `Data` 填入按行优先排列的 RGBA 字节。成功时返回 `true` 。

```cpp
// 伪代码
bool UMyCustomVisionComponent::CaptureRaw(int& Width, int& Height, TArray<uint8>& Data)
{
    if (!MyImageSource.IsValid())
        return false;

    MyImageSource->GetRGBAFrame(Width, Height, Data);
    return Data.Num() > 0;
}
```

{% endstep %}
{% endstepper %}

### 向聊天机器人注册组件

将组件添加到与 `Actor` 相同的 `UConvaiChatbotComponent`.

* 当 `Actor`上只有一个视觉组件时，在 `BeginPlay` 期间发现该组件即可。
* 当存在多个视觉组件时，请调用 **设置视觉组件** 在 `BeginPlay` 并传入你想要使用的组件。
* 调用 **启动** 自 `BeginPlay`，或者在自定义类上添加自己的自动启动属性。

### 后续步骤

{% content-ref url="/pages/ec5b9bfb145ddc8145050976e8e8db28d33fc076" %}
[视觉 Blueprint 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/vision-blueprint-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/a5aa237a7b13fb2c8d46ff004c1de14a2c4cda2a" %}
[视觉帧源](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/vision-frame-sources.md)
{% endcontent-ref %}

{% content-ref url="/pages/63feddf4b54afd4fe7308827bee6b2f213dde1b6" %}
[视觉的工作原理](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/how-vision-works.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/vision/custom-vision-components.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
