File size: 11,939 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
export type Dist = number | string
  | {dist: 'fixed'; value: number | string}
  | {dist: 'uniform'; lo: number; hi: number}
  | {dist: 'normal'; mean: number; sd: number; lo?: number; hi?: number}
  | {dist: 'lognormal'; median: number; sigma: number; lo?: number; hi?: number}
  | {dist: 'choice'; values: (number | string)[]; weights?: number[]}
  | {dist: 'mixture'; of: Dist[]; weights?: number[]};
export type Group = {
  duration: Dist; cast_mix: Record<string, Dist>; profile_mix?: Record<string, Dist>;
  observer_mix: {count: Dist; kind: Dist; motion_mode: Dist; view?: Dist; body?: Dist; profile?: Dist; calibration?: boolean; eye_height_m?: Dist};
  flavor_mix: Dist; arrangement_quota: Quota[];
  decoy_rate: number; recording?: Recording;
};
// 单条安排的可选字段原样进单段配置(gen/expand.py arrangement_quota;who 仍由抽签定),录像参数每段抽一次(expand.py recording)
export type Quota = {type: string; count: Dist; strength: 'hard' | 'soft'; where?: string | number; when?: 'auto' | [number, number];
  dwell_s?: number; event?: 'dynamic'; times?: 1; decoy?: boolean};
export type Recording = {length_frac?: Dist; link_overlap_frac?: Dist; split_frac?: Dist; split_excl_frac?: Dist; split_offset_max_frac?: Dist; max_shared?: Dist};
export const RECORDING_KEYS = ['length_frac', 'link_overlap_frac', 'split_frac', 'split_excl_frac', 'split_offset_max_frac', 'max_shared'] as const;
// 各类安排读哪些字段(gen/arrange.py、detect.py);when、decoy 各类都认
export const QUOTA_FIELDS: Record<string, ('where' | 'dwell_s' | 'event' | 'times')[]> = {
  stop_at: ['where', 'dwell_s'], meet: ['where', 'dwell_s'], covisible_event: ['event'],
  observer_body: ['times'], covisible_region: [],
};
// 设一个可选键;undefined 就删掉,不留空键(不写的批量和以前逐字节一样)
export function setOptional<T extends object, K extends keyof T>(obj: T, key: K, value: T[K] | undefined): T {
  const next = {...obj};
  if (value === undefined) delete next[key]; else next[key] = value;
  return next;
}
export type BatchSettings = {seed: number; scenes: {scene: string; count: number}[]; template: {groups: Group[]}};
export type GenSchema = {
  schema: 'np-gen-schema/1'; generator_revision: string; keys: Record<string, string[]>;
  flavors: string[]; implemented_flavors: string[]; observer_kinds: Record<string, string>;
  motion_modes: string[]; implemented_motion_modes: string[]; view_modes: string[]; arrangements: Record<string, number>;
  arrangement_labels: Record<string, string>;
  arrangement_fields: Record<string, Record<string, {type: string; values?: string[]; value?: number; min?: number}>>;
  recording_keys: (keyof Recording)[];
  bodies: Record<string, Record<string, unknown>>; profiles: Record<string, Record<string, unknown>>;
  profile_keys: string[]; default_profile: Record<string, string>; default_observer: Record<string, unknown>;
  dist_kinds: string[]; max_humans: number;
};
export type SingleConfig = {
  id?: string; scene: string; seed: number; duration_s: number; flavor?: string; decoy_rate?: number;
  cast: {id: string; kind: string; profile?: string; appearance?: unknown}[];
  observers?: {id: string; kind: string; body?: string; motion_mode?: string; view?: {mode?: string; [key: string]: unknown}; calibration?: boolean}[];
  arrangements?: {type: string; who?: string[]; strength?: string; where?: unknown; when?: unknown}[];
  [key: string]: unknown;
};
export type ExpandedConfig = {config: SingleConfig; errors: string[]};
export type ExpandResult = {generator_revision: string; count: number; configs: ExpandedConfig[]};

export const LABELS: Record<string, string> = {
  humanoid: '人形', quadruped: '机器狗', humanoid_cam: '人形机身(眼位相机)', quadruped_cam: '机器狗机身(背相机)', camera: '无机身相机', embodied: '实体观察者', virtual_bound: '虚拟观察者(沿通行区走)', virtual_free: '虚拟观察者(自由走,未实现)',
  seek: '去目标点', roam: '漫游', static: '不动', follow: '跟随', heading: '朝前进方向', look_at: '盯住目标', scan: '扫视', auto: '自动',
  walker: '步行者', wanderer: '闲逛者', robot: '机器人', observer: '巡视者',
  plain: '普通', body_visible: '机身可见', identical_group: '同外观一组', hard: '必须', soft: '尽量',
  recording: '录像', length_frac: '每路录像长度(占世界时长)', link_overlap_frac: '相邻两路至少重合(占世界时长)',
  split_frac: '把一名主体两次过门分给两路的比例', max_shared: '一路被别路看到的时空上限',
  where: '地点(房间名、region-N 或停点号)', when: '限定时段', dwell_s: '停留秒数', event: '共视动态事件',
  split_excl_frac: '分路独占比例', split_offset_max_frac: '分路偏移上限比例', times: '可见次数(固定 1)', decoy: '当干扰(不出题)',
  body: '机身', profile: '行为档案', calibration: '标定停留(在看得见两处门口的点停一下)', eye_height_m: '眼高(m)',
  duration: '时长', cast_mix: '主体组成', profile_mix: '行为档案', observer_mix: '观察者', flavor_mix: '段风格', arrangement_quota: '情形安排', decoy_rate: '干扰比例',
};
// 安排类型的中文名只有一处:生成器 schema 的 arrangement_labels(np/planning.py GENERATOR_TYPE_LABELS),载入 schema 时填进来
const arrangementLabels: Record<string, string> = {};
export const setArrangementLabels = (labels: Record<string, string>) => {Object.assign(arrangementLabels, labels);};
export const label = (value: string) => arrangementLabels[value] || LABELS[value] || value;
export const unimplementedMotion = (schema: GenSchema) => schema.motion_modes.filter(m => !schema.implemented_motion_modes.includes(m));

// A batch's segments follow from its seed (expand.py: scene × group × item under the batch seed), so two batches on one
// seed repeat each other's scripts and questions.
export const freshSeed = () => crypto.getRandomValues(new Uint32Array(1))[0] >>> 1;

export function defaultBatch(readyScenes: string[], seed = freshSeed()): BatchSettings {
  return {seed, scenes: readyScenes.map(scene => ({scene, count: 4})), template: {groups: [{
    duration: {dist: 'choice', values: [90, 360], weights: [3, 1]},
    cast_mix: {humanoid: {dist: 'choice', values: [2, 3, 4]}, quadruped: {dist: 'choice', values: [0, 1]}},
    observer_mix: {count: {dist: 'choice', values: [1, 2]}, kind: {dist: 'choice', values: ['embodied', 'virtual_bound'], weights: [2, 1]}, motion_mode: {dist: 'choice', values: ['seek', 'roam']}, view: {dist: 'fixed', value: 'auto'}},
    flavor_mix: {dist: 'fixed', value: 'plain'}, arrangement_quota: [{type: 'stop_at', count: {dist: 'choice', values: [0, 1]}, strength: 'hard'}], decoy_rate: 0,
  }]}};
}
// 批量设定编辑器要逐组读的字段;schema 的默认值是 groups:[{}],种默认分布之前、或贴进来的 JSON 缺字段时,不能交给编辑器
const GROUP_FIELDS = ['duration', 'cast_mix', 'observer_mix', 'flavor_mix', 'arrangement_quota'] as const;
export function missingGroupFields(batch: BatchSettings): string[] {
  const groups = batch.template?.groups;
  if (!Array.isArray(groups) || !groups.length) return ['template.groups'];
  return groups.flatMap((group, i) => GROUP_FIELDS.filter(key => group?.[key] == null).map(key => `第 ${i + 1} 组 ${label(key)}`));
}
// 第 5 卡“版本要的安排”一键加进批量设定:每组加一条必须、每段 1 次;已有同类型的组不重复加
export function addArrangement(batch: BatchSettings, type: string): BatchSettings {
  return {...batch, template: {groups: batch.template.groups.map(group => group.arrangement_quota.some(q => q.type === type) ? group
    : {...group, arrangement_quota: [...group.arrangement_quota, {type, count: 1, strength: 'hard' as const}]})}};
}
export const batchTotal = (batch: BatchSettings) => batch.scenes.reduce((sum, scene) => sum + scene.count, 0) * batch.template.groups.length;
export function toggleScene(batch: BatchSettings, id: string): BatchSettings {
  return {...batch, scenes: batch.scenes.some(row => row.scene === id) ? batch.scenes.filter(row => row.scene !== id) : [...batch.scenes, {scene: id, count: 4}]};
}
export function setSceneCount(batch: BatchSettings, id: string, n: number): BatchSettings {
  return {...batch, scenes: batch.scenes.map(row => row.scene === id ? {...row, count: n} : row)};
}
// 观察者机身要和种类配(config.validate:实体配 observer_embodied 机身,虚拟配 observer_virtual);种类混抽时定不了机身,返回空
const OBSERVER_SCRIPT_KIND: Record<string, string> = {embodied: 'observer_embodied', virtual_bound: 'observer_virtual', virtual_free: 'observer_virtual'};
export function observerBodies(schema: GenSchema, kind: Dist): string[] {
  const one = typeof kind !== 'object' ? kind : kind.dist === 'fixed' ? kind.value : kind.dist === 'choice' && kind.values.length === 1 ? kind.values[0] : null;
  return one == null ? [] : Object.keys(schema.bodies).filter(b => schema.bodies[b].script_kind === OBSERVER_SCRIPT_KIND[String(one)]);
}
export const castKinds = (schema: GenSchema) => Object.keys(schema.bodies).filter(key => key !== 'camera' && !key.endsWith('_cam'));

export function distSummary(d: Dist, unit = ''): string {
  const show = (value: number | string) => typeof value === 'string' ? label(value) : `${value}${unit ? ' ' + unit : ''}`;
  if (typeof d !== 'object') return show(d);
  if (d.dist === 'fixed') return '固定 ' + show(d.value);
  if (d.dist === 'uniform') return `均匀 ${d.lo}–${d.hi}${unit ? ' ' + unit : ''}`;
  if (d.dist === 'choice') return '选一:' + d.values.map((value, i) => show(value) + (d.weights ? ` 占 ${d.weights[i]} 份` : '')).join('、') + (d.weights ? '' : '(等概率)');
  if (d.dist === 'mixture') return `混合 ${d.of.length} 种`;
  const bounds = d.lo !== undefined || d.hi !== undefined ? `(限 ${d.lo ?? '−∞'}–${d.hi ?? '∞'})` : '';
  return (d.dist === 'normal' ? `正态 均值 ${show(d.mean)},标准差 ${show(d.sd)}` : `对数正态 中位 ${show(d.median)},sigma ${d.sigma}`) + bounds;
}
// 生成器 expand 记下的“抽到了却放不下”(gen/expand.py unfilled):必须的已由 config.validate 报成问题,
// 这里只列尽量的,原因原文放在悬停提示里
const UNFILLED: Record<string, string> = {cast: '主体', observer: '观察者', arrangement: '情形安排'};
export function unfilledHints(cfg: SingleConfig): {text: string; reason: string}[] {
  const rows = (cfg.unfilled || []) as {what?: string; type: string; strength?: string; reason?: string}[];
  return rows.filter(u => u.strength !== 'hard').map(u => ({text: `${UNFILLED[u.what || 'arrangement'] ?? u.what} ${label(u.type)} 没放下(尽量)`, reason: u.reason || ''}));
}
export function configRow(cfg: SingleConfig) {
  const counts: Record<string, number> = {};
  for (const actor of cfg.cast) counts[actor.kind] = (counts[actor.kind] || 0) + 1;
  return {id: cfg.id ?? '', scene: cfg.scene, seed: cfg.seed, duration: cfg.duration_s,
    cast: Object.entries(counts).map(([kind, count]) => `${label(kind)} ${count}`).join(' · ') || '无',
    observers: (cfg.observers || []).map(o => `${o.id} ${label(o.kind)}·${label(o.motion_mode || '')}·${label(o.view?.mode || '')}`).join(';') || '无',
    arrangements: (cfg.arrangements || []).map(a => `${label(a.type)}(${(a.who || []).join('、')})`).join(';') || '无'};
}

// Explicit type changes discard fields belonging to the previous arrangement. Imported JSON stays untouched.
export function changeQuotaType(quota: Quota, type: string): Quota {
  const {count, strength, when, decoy} = quota;
  return {type, count, strength, ...(when === undefined ? {} : {when}), ...(decoy === undefined ? {} : {decoy})};
}