# GameKit Host 通信接入案例

本文用一个“房间内主持人向游戏发送公告”的场景，演示 Unity 游戏如何接收 Host
推送的文本、表情混合消息和语音活动事件。Host（Desktop 或 Mobile）负责登录、审核、
权限、房间路由和发送资格；游戏只消费已经通过 Host 处理的消息。

## 场景准备

1. 安装同版本的 `cn.indiegp.sdk.unity` 和 `cn.indiegp.sdk.unity.game-kit`。
2. 在场景中创建一个长期存在的 GameObject，例如 `IGP Runtime`。
3. 将 `IGPRuntimeManager` 和 `IGPGameKitRuntime` 添加到同一个 GameObject。
4. 在启动流程中调用 `IGPRuntimeManager.InitializeAsync()`。
5. 在初始化前注册业务事件，避免错过已经排队的 Host 消息。

`IGPGameKitRuntime` 不需要游戏主动请求。Core 会接收 Host Session 消息，并由
`IGPRuntimeManager.Update()` 在 Unity 主线程按接收顺序交付事件。

一个最小启动脚本如下。`HostCommunicationExample.OnEnable()` 会先注册事件，随后再由
启动脚本初始化 Core；这样初始化期间到达的消息也能交付给游戏。

```csharp
using IGP.UnitySDK;
using UnityEngine;

public sealed class GameStartup : MonoBehaviour
{
    [SerializeField] private IGPRuntimeManager runtimeManager = null!;

    private async void Start()
    {
        bool initialized = await runtimeManager.InitializeAsync();
        if (!initialized)
        {
            Debug.LogError("IGP SDK initialization failed");
        }
    }
}
```

## 完整示例

下面的组件可以直接放在 UI 或游戏状态管理对象上。它保留混合消息的顺序：文本段和表情段
都作为子节点追加到同一个容器，文本按原值显示，表情段使用游戏自己的资源表渲染。示例
使用 Unity UI 的 `Text` 和 `Image`，不依赖语音或表情 SDK。

```csharp
using System;
using System.Collections.Generic;
using IGP.UnitySDK;
using IGP.UnitySDK.GameKit;
using UnityEngine;
using UnityEngine.UI;

public sealed class HostCommunicationExample : MonoBehaviour
{
    [Serializable]
    private sealed class EmotionResource
    {
        public string id = string.Empty;
        public Sprite? sprite;
    }

    [SerializeField] private IGPGameKitRuntime gameKitRuntime = null!;
    [SerializeField] private Transform segmentRoot = null!;
    [SerializeField] private Text textTemplate = null!;
    [SerializeField] private Image emotionTemplate = null!;
    [SerializeField] private EmotionResource[] emotionResources = Array.Empty<EmotionResource>();

    private readonly Dictionary<string, Sprite> emotionSprites =
        new Dictionary<string, Sprite>(StringComparer.Ordinal);

    private void Awake()
    {
        foreach (EmotionResource resource in emotionResources)
        {
            if (!string.IsNullOrEmpty(resource.id) && resource.sprite != null)
            {
                emotionSprites[resource.id] = resource.sprite;
            }
        }
    }

    private void OnEnable()
    {
        gameKitRuntime.CommunicationMessageReceived += OnCommunicationMessage;
        gameKitRuntime.VoiceSpeakingStarted += OnVoiceSpeakingStarted;
        gameKitRuntime.VoiceSpeakingStopped += OnVoiceSpeakingStopped;
    }

    private void OnDisable()
    {
        gameKitRuntime.CommunicationMessageReceived -= OnCommunicationMessage;
        gameKitRuntime.VoiceSpeakingStarted -= OnVoiceSpeakingStarted;
        gameKitRuntime.VoiceSpeakingStopped -= OnVoiceSpeakingStopped;
    }

    private void OnCommunicationMessage(IGPCommunicationMessageEvent message)
    {
        // 每条消息先清空旧视图，避免把两条 Host 消息拼成一条内容。
        ClearSegments();

        foreach (IGPCommunicationSegment segment in message.Segments)
        {
            switch (segment)
            {
                case IGPCommunicationTextSegment text:
                    AppendText(text.Text);
                    break;
                case IGPCommunicationEmotionSegment emotion:
                    AppendEmotion(emotion.EmotionId);
                    break;
            }
        }

        // MessageId 是 Host envelope 的 ID，可用于游戏内去重或埋点关联。
    }

    private void AppendText(string text)
    {
        // SDK 不 trim 或合并文本；这里按游戏 UI 规则追加。
        Text instance = Instantiate(textTemplate, segmentRoot);
        instance.gameObject.SetActive(true);
        instance.text = text;
    }

    private void AppendEmotion(string emotionId)
    {
        if (!emotionSprites.TryGetValue(emotionId, out Sprite? sprite))
        {
            // Host 只发送已审核的 emotionId，但客户端仍应为资源缺失准备降级行为。
            Text fallback = Instantiate(textTemplate, segmentRoot);
            fallback.gameObject.SetActive(true);
            fallback.text = "[表情]";
            return;
        }

        Image image = Instantiate(emotionTemplate, segmentRoot);
        image.gameObject.SetActive(true);
        image.sprite = sprite;
    }

    private void ClearSegments()
    {
        for (int index = segmentRoot.childCount - 1; index >= 0; index--)
        {
            Destroy(segmentRoot.GetChild(index).gameObject);
        }
    }

    private void OnVoiceSpeakingStarted(IGPVoiceSpeakingEvent value)
    {
        // 例如：在玩家头像旁显示 speaking 状态。
    }

    private void OnVoiceSpeakingStopped(IGPVoiceSpeakingEvent value)
    {
    }
}
```

### Inspector 配置

- `gameKitRuntime`：拖入与 `IGPRuntimeManager` 同一个 GameObject 上的组件。
- `segmentRoot`：用于按顺序放置文本和表情节点的容器；实际项目可替换为自定义富文本控件。
- `segmentRoot` 建议配置 `HorizontalLayoutGroup` 或项目自己的混排布局组件；布局组件会按
  子节点顺序排列文本和表情。
- `textTemplate`：预制的文本 `Text`，示例会复制它并设置 `text`；模板自身应保持 inactive。
- `emotionTemplate`：预制的表情 `Image`，示例会复制它并设置 `sprite`；模板自身应保持 inactive。
- `emotionResources`：将 Host 约定的字符串 ID 映射到本地 `Sprite`。SDK 不解释 ID，
  也不会下载或查询表情目录。

## Host 消息示例

Host 发送 `GAME_KIT_COMMUNICATION_MESSAGE` 时，envelope 的 `message_id` 会成为事件的
`MessageId`，`content_json` 只包含业务 payload：

```json
{
  "schemaVersion": 1,
  "roomId": "room-123",
  "senderPlayerId": "player-456",
  "sentAtUnixMs": 1788775200123,
  "segments": [
    { "type": "text", "text": "大家好，" },
    { "type": "emotion", "emotionId": "emotion.cato-hello" },
    { "type": "text", "text": "准备开始！" }
  ]
}
```

`segments` 的顺序就是最终展示顺序，因此可以在任意位置混合文本和表情。文本不能为空
字符串；`emotionId` 是非空不透明字符串。SDK 不做文本审核、表情权限检查、成员资格
审计或目录查询，这些工作由 Host 在发送前完成。

## 语音状态处理

语音事件只表示开始或结束，不携带音频和转写。对同一个 `(roomId, playerId)`，重复的
started 会被忽略，只有匹配当前 `voiceActivityId` 的 stopped 才会触发事件。Host Session
断开、换房或 GameKit shutdown 时会清理状态，但不会合成 stopped 事件。

## 异常与兼容行为

- 未知 subcommand、非法 JSON、错误 schema、空 segments 或未知 segment 类型会忽略整条
  消息，不展示部分内容，也不会关闭 Host Session。
- GameKit 未安装或未初始化时，Core 可以安全忽略 Host 推送。
- SDK 会记录收发方向、subcommand、消息 ID、字节数和处理结果等安全元数据；不会记录
  `content_json`、文本、`emotionId`、音频、转写或凭证。
- 业务若需要去重，应使用 `MessageId`；Service Message 不自动回复，也不提供协议级超时。

## 接入检查表

- [ ] Core 与 GameKit 版本一致。
- [ ] 两个 runtime 组件位于同一个 GameObject。
- [ ] 事件订阅发生在 `InitializeAsync()` 之前，并在 `OnDisable()` 取消订阅。
- [ ] 文本按 `Segments` 原顺序渲染，没有重新排序或合并。
- [ ] 游戏维护自己的 `emotionId -> Sprite` 映射，并为缺失资源提供降级显示。
- [ ] 游戏不在日志中输出消息正文、表情 ID 或凭证。
