057 实体系统与 Drawable 绑定

理解 viewer-2d 中 Entity、Drawable、Selectable 三大核心抽象,以及实体的完整生命周期

1. 为什么需要实体系统

viewer-2d 渲染的不是简单图形,而是领域对象:门、窗、房间、家具图例、尺寸标注……每个对象都携带业务数据(位置、尺寸、关联墙体),同时需要在画布上可视化并响应交互。实体系统就是把数据、渲染、交互三者统一封装的架构模式。

核心思路

Entity(实体)持有业务数据和逻辑;Drawable 负责将数据渲染到 PixiJS 画布;Selectable 负责选中、拖拽、缩放等交互。三者通过 KAF 框架的 API 注册机制自动绑定。

2. Entity 基类

viewer-2d 中的实体都继承自 KAF 框架提供的 Entity 基类。每个 Entity 实例代表场景中的一个领域对象,持有业务模型(model)和对全局状态管理器(RootStateManager)的引用。

// 典型的 Entity 类结构(以 DoorWindowEntity 为例)
import { Entity, EntityAPIs } from '@qunhe/kaf';

class DoorWindowEntity extends Entity {
    model: DoorWindowElement;       // 门窗业务数据
    rootState: RootStateManager;    // 全局状态引用

    constructor(model, rootState) {
        super();
        this.model = model;
        this.rootState = rootState;
    }
}

Entity 本身不包含任何渲染或交互代码。它通过 API 注册机制 声明自己提供哪些能力(Drawable、Highlight、Inference 等),由 KAF 框架在运行时自动连接。

EntityTypes:实体类型注册表

每种实体类型都有一个唯一的 Symbol 标识,定义在 entityTypes.ts 中:

export const EntityTypes = {
    RoomElementEntityType:          Symbol('RoomElementEntity'),
    DoorWindowEntityType:           Symbol('DoorWindowEntity'),
    FloorplanEntityType:            Symbol('FloorplanEntity'),
    FurnitureLegendEntityType:      Symbol('FurnitureLegendEntity'),
    FurniturePlanViewEntityType:    Symbol('FurniturePlanViewEntity'),
    Ksg2dContainerEntityType:       Symbol('Ksg2dContainerEntity'),
    RoomCoverEntityType:            Symbol('RoomCoverEntity'),
    SelectedNormalDirection:        Symbol('SelectedNormalDirection'),
    // ... 更多类型
};

3. Drawable 接口:从数据到像素

Drawable 是实体在 2D 画布上的"代言人"。每个实体类型都有一个对应的 Drawable2D 类,负责把业务数据翻译成 PixiJS 图形。

// Entity 通过装饰器声明 Drawable 绑定
@provideEntityAPIs([
    new EntityAPIs.DrawableAPI2D(function(this: DoorWindowEntity) {
        return new Drawable2D(this.model, this.rootState, this);
    }),
    // ... 其他 API
])
class DoorWindowEntity extends Entity { ... }
关键机制

DrawableAPI2D 的回调是一个工厂函数。KAF 框架在实体被添加到场景时自动调用它,创建 Drawable 实例并绑定到 PixiJS 容器。回调中的 this 指向 Entity 实例。这是高风险改动区域——修改绑定关系可能导致实体不渲染或渲染错乱。

每个 Drawable2D 通常负责:

Drawable 目录结构

src/app/Entities/
├── DoorWindow/
│   ├── index.ts              # DoorWindowEntity(实体类)
│   ├── Drawable2D.ts         # Drawable2D(渲染逻辑)
│   ├── TransformChecker.ts   # 变换合法性校验
│   └── dwshape/              # 各种门窗形状绘制
│       ├── drawDoor.ts
│       ├── drawWindow.ts
│       ├── drawSlidingDoor.ts
│       ├── drawDoubleDoor.ts
│       └── ...
├── Floorplan/
│   ├── index.ts
│   └── Drawable2D.ts
├── RoomElement/
│   ├── index.ts
│   └── Drawable2D.ts
├── FurnitureLegend/
│   ├── index.ts
│   ├── Drawable2D.ts
│   └── KsgFurnitureLegendEntity.ts
└── ...

4. Selectable 体系:选中与交互

实体不仅要渲染,还要能被用户选中、拖拽、缩放。这由 SystemPropertiesAPI 驱动——每个实体声明自己的交互能力:

new SystemPropertiesAPI(function(this: DoorWindowEntity) {
    return {
        entityTypeName: 'door-window',
        isDeletable: () => true,
        isMovable: () => true,
        isRotatable: () => false,    // 门窗不能旋转
        isResizable: () => true,
        getResizeAnchorOptions: () => ({ ... }),
        delete: () => {
            this.rootState.designDoc.removeDoorWindow(this.model.getId());
        },
        getTransform: () => { ... },
    };
})
设计原则

交互能力是逐实体声明的。门可以拖拽但不能旋转,家具图例可以缩放,标注只读——这些差异通过 SystemPropertiesAPI 的返回值控制,而非硬编码在通用逻辑中。

SelectedControls 模块(src/modules/SelectedControls/)负责统一的选中态渲染:高亮框、缩放手柄、旋转手柄等,根据实体声明的能力动态显示。

5. 实体生命周期:创建 → 更新 → 销毁

model 数据变更 → Entity 创建/更新 → DrawableAPI2D 回调 → Drawable2D 渲染 → PixiJS 画布

创建阶段

  1. 业务数据变更(如用户添加一扇门)触发 designDoc 更新
  2. EntityDocument 中注册的 entitiesCreator 根据数据创建对应 Entity 实例
  3. KAF 框架调用 DrawableAPI2D 工厂函数,创建 Drawable 并挂载到指定的 PixiJS 容器
  4. 容器按 order 排序,决定图层前后关系

更新阶段

  1. model 属性变化(如拖拽改变了门窗位置)
  2. Drawable2D 监听变更,重新计算图形
  3. PixiJS 重绘,画布自动刷新

销毁阶段

  1. 用户删除实体或场景切换
  2. KAF 框架调用 Entity 的 dispose
  3. Drawable2D 清理 PixiJS 资源(移除 Container、释放纹理等)
  4. Entity 从容器中移除
注意事项

实体的创建和销毁由 EntityDocument 集中管理。不要在 Entity 或 Drawable 外部手动 new 或 dispose,否则会导致场景状态不一致。

6. 常见实体类型

实体Entity 类职责容器层级
门窗DoorWindowEntity嵌入墙体的门/窗/飘窗,支持拖拽调整宽度order: 1009
房间RoomElementEntity房间区域,显示面积、名称order: 903
户型图FloorplanEntity整体户型轮廓和墙体(包含在 Wall 容器)
家具图例FurnitureLegendEntity2D 平面家具符号,支持拖拽/缩放order: 1006
家具俯视图FurniturePlanViewEntity家具俯视渲染图order: 1007
KSG 容器Ksg2dContainerEntityKSG 模型的 2D 投影容器order: 999
房间铺贴RoomCoverEntity房间地面材质铺贴效果order: 1200
选中方向SelectedNormalDirection选中实体的法线方向指示器(SelectControl 容器)

EntityDocument:容器编排中心

EntityDocument 是所有实体的"总管"。它定义了 2D 容器列表及其层序(order),以及每种数据类型对应哪个 Entity 构造器:

class EntityDocument implements Document {
    // 定义 2D 容器列表及层序
    readonly container2DConfigs = [
        { containerKey: WallContainerKey,         order: 1008 },
        { containerKey: RoomElementContainerKey,   order: 903  },
        { containerKey: DoorWindowContainerKey,    order: 1009 },
        { containerKey: FurnitureLegendContainerKey, order: 1006 },
        { containerKey: RoomCoverContainerKey,     order: 1200 },
        { containerKey: SelectControlContainerKey, order: 9999 }, // 最顶层
    ];

    // 数据 → Entity 的映射
    private getDoorWindowEntities = flatEntitiesCreator(
        dw => new DoorWindowEntity(dw, this.rootState)
    );
}
层序(order)

数值越大,图层越靠前(越先被渲染在上层)。SelectControl 的 order 为 9999,确保选中态永远在最顶层。RoomCover 的 order 为 1200,覆盖在房间元素之上。

7. 完整绑定链路图

┌─────────────────────────────────────────────────────┐
│  EntityDocument                                      │
│  持有所有 Entity 实例列表 + 容器配置                   │
└──────────────────────┬──────────────────────────────┘
                       │ 创建 Entity
┌──────────────────────▼──────────────────────────────┐
│  Entity(如 DoorWindowEntity)                       │
│  @provideEntityAPIs([                                │
│    DrawableAPI2D(...)      → 创建 Drawable2D         │
│    HighlightGeometryAPI2D  → 高亮区域                 │
│    InferenceSourceAPI2D    → 吸引/吸附数据源          │
│    SystemPropertiesAPI     → 交互能力声明             │
│  ])                                                  │
└──────────────────────┬──────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────┐
│  Drawable2D                                          │
│  接收 model + rootState + entity                     │
│  创建 PixiJS Graphics → 挂载到容器                    │
│  监听数据变更 → 重绘                                  │
└──────────────────────┬──────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────┐
│  PixiJS Container(按 order 排序)                   │
│  Wall(1008) → Room(903) → Door(1009) → ...          │
│  → SelectControl(9999)                               │
└─────────────────────────────────────────────────────┘

8. 自检 Quiz

Q1: Entity 与 Drawable 的绑定是通过什么机制实现的?
Q2: EntityDocument 中 container2DConfigs 的 order 字段决定了什么?
Q3: 如果要让一种新实体支持拖拽但不支持旋转,应该在哪里声明?

推荐阅读