@things-factory/figure-service 10.1.277 → 10.1.279

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/package.json +23 -8
  2. package/dist-server/index.js.map +0 -1
  3. package/dist-server/migrations/index.js.map +0 -1
  4. package/dist-server/routers/figure-mesh-router.js.map +0 -1
  5. package/dist-server/routers/figure-package-router.js.map +0 -1
  6. package/dist-server/routers/figure-thumbnail-router.js.map +0 -1
  7. package/dist-server/routes.js.map +0 -1
  8. package/dist-server/service/figure/event-subscriber.js.map +0 -1
  9. package/dist-server/service/figure/figure-ai-scenarios-run.js.map +0 -1
  10. package/dist-server/service/figure/figure-ai-scenarios.js.map +0 -1
  11. package/dist-server/service/figure/figure-categories.js.map +0 -1
  12. package/dist-server/service/figure/figure-context.js.map +0 -1
  13. package/dist-server/service/figure/figure-format.js.map +0 -1
  14. package/dist-server/service/figure/figure-glb.js.map +0 -1
  15. package/dist-server/service/figure/figure-history.js.map +0 -1
  16. package/dist-server/service/figure/figure-llm-provider.js.map +0 -1
  17. package/dist-server/service/figure/figure-mesh-store.js.map +0 -1
  18. package/dist-server/service/figure/figure-mutation.js.map +0 -1
  19. package/dist-server/service/figure/figure-namespace-entity.js.map +0 -1
  20. package/dist-server/service/figure/figure-namespace-resolver.js.map +0 -1
  21. package/dist-server/service/figure/figure-namespace.js.map +0 -1
  22. package/dist-server/service/figure/figure-package-export.js.map +0 -1
  23. package/dist-server/service/figure/figure-proposal-record.js.map +0 -1
  24. package/dist-server/service/figure/figure-proposal.js.map +0 -1
  25. package/dist-server/service/figure/figure-propose-steps.js.map +0 -1
  26. package/dist-server/service/figure/figure-propose-type.js.map +0 -1
  27. package/dist-server/service/figure/figure-public.js.map +0 -1
  28. package/dist-server/service/figure/figure-query.js.map +0 -1
  29. package/dist-server/service/figure/figure-rename.js.map +0 -1
  30. package/dist-server/service/figure/figure-replaced-draft.js.map +0 -1
  31. package/dist-server/service/figure/figure-revert.js.map +0 -1
  32. package/dist-server/service/figure/figure-subject.js.map +0 -1
  33. package/dist-server/service/figure/figure-thumbnail-reader.js.map +0 -1
  34. package/dist-server/service/figure/figure-thumbnail-store.js.map +0 -1
  35. package/dist-server/service/figure/figure-thumbnail-upgrade.js.map +0 -1
  36. package/dist-server/service/figure/figure-tools.js.map +0 -1
  37. package/dist-server/service/figure/figure-type.js.map +0 -1
  38. package/dist-server/service/figure/figure-write.js.map +0 -1
  39. package/dist-server/service/figure/figure.js.map +0 -1
  40. package/dist-server/service/figure/index.js.map +0 -1
  41. package/dist-server/service/figure-recipe/figure-recipe-resolver.js.map +0 -1
  42. package/dist-server/service/figure-recipe/figure-recipe-templates.js.map +0 -1
  43. package/dist-server/service/figure-recipe/figure-recipe-type.js.map +0 -1
  44. package/dist-server/service/figure-recipe/index.js.map +0 -1
  45. package/dist-server/service/index.js.map +0 -1
  46. package/dist-server/tsconfig.tsbuildinfo +0 -1
  47. package/scripts/build-templates.mts +0 -64
  48. package/scripts/figure-ai-scenarios-agent.cjs +0 -98
  49. package/scripts/rename-figures-to-full-names.mjs +0 -211
  50. package/scripts/templates.test.mts +0 -112
  51. package/server/index.ts +0 -46
  52. package/server/migrations/index.ts +0 -9
  53. package/server/routers/figure-mesh-router.ts +0 -63
  54. package/server/routers/figure-package-router.ts +0 -53
  55. package/server/routers/figure-thumbnail-router.ts +0 -159
  56. package/server/routes.ts +0 -30
  57. package/server/service/figure/catalog-db.test.ts +0 -162
  58. package/server/service/figure/event-subscriber.ts +0 -66
  59. package/server/service/figure/figure-ai-scenarios-run.ts +0 -127
  60. package/server/service/figure/figure-ai-scenarios.live.test.ts +0 -59
  61. package/server/service/figure/figure-ai-scenarios.test.ts +0 -109
  62. package/server/service/figure/figure-ai-scenarios.ts +0 -798
  63. package/server/service/figure/figure-blueprint-query.test.ts +0 -536
  64. package/server/service/figure/figure-catalog-seen-db.test.ts +0 -153
  65. package/server/service/figure/figure-categories.ts +0 -50
  66. package/server/service/figure/figure-category-db.test.ts +0 -127
  67. package/server/service/figure/figure-context.test.ts +0 -402
  68. package/server/service/figure/figure-context.ts +0 -510
  69. package/server/service/figure/figure-deprecation-db.test.ts +0 -218
  70. package/server/service/figure/figure-format.test.ts +0 -423
  71. package/server/service/figure/figure-format.ts +0 -783
  72. package/server/service/figure/figure-glb.test.ts +0 -112
  73. package/server/service/figure/figure-glb.ts +0 -251
  74. package/server/service/figure/figure-history.ts +0 -192
  75. package/server/service/figure/figure-inspect-db.test.ts +0 -131
  76. package/server/service/figure/figure-llm-provider.ts +0 -20
  77. package/server/service/figure/figure-llm-smoke.test.ts +0 -95
  78. package/server/service/figure/figure-mesh-db.test.ts +0 -246
  79. package/server/service/figure/figure-mesh-store.ts +0 -91
  80. package/server/service/figure/figure-mutation.ts +0 -656
  81. package/server/service/figure/figure-namespace-db.test.ts +0 -315
  82. package/server/service/figure/figure-namespace-entity.ts +0 -67
  83. package/server/service/figure/figure-namespace-resolver.ts +0 -54
  84. package/server/service/figure/figure-namespace.ts +0 -156
  85. package/server/service/figure/figure-package-export.ts +0 -136
  86. package/server/service/figure/figure-proposal-db.test.ts +0 -117
  87. package/server/service/figure/figure-proposal-record.ts +0 -38
  88. package/server/service/figure/figure-proposal.ts +0 -41
  89. package/server/service/figure/figure-propose-clips.test.ts +0 -69
  90. package/server/service/figure/figure-propose-steps.test.ts +0 -324
  91. package/server/service/figure/figure-propose-steps.ts +0 -354
  92. package/server/service/figure/figure-propose-type.ts +0 -46
  93. package/server/service/figure/figure-public-db.test.ts +0 -288
  94. package/server/service/figure/figure-public.ts +0 -60
  95. package/server/service/figure/figure-query.ts +0 -511
  96. package/server/service/figure/figure-release-check.test.ts +0 -63
  97. package/server/service/figure/figure-release-record-db.test.ts +0 -153
  98. package/server/service/figure/figure-release-size-db.test.ts +0 -156
  99. package/server/service/figure/figure-rename-db.test.ts +0 -237
  100. package/server/service/figure/figure-rename.test.ts +0 -117
  101. package/server/service/figure/figure-rename.ts +0 -143
  102. package/server/service/figure/figure-replaced-draft.ts +0 -99
  103. package/server/service/figure/figure-revert-db.test.ts +0 -163
  104. package/server/service/figure/figure-revert-race.pg.test.ts +0 -168
  105. package/server/service/figure/figure-revert.ts +0 -186
  106. package/server/service/figure/figure-subject.test.ts +0 -41
  107. package/server/service/figure/figure-subject.ts +0 -21
  108. package/server/service/figure/figure-thumbnail-db.test.ts +0 -279
  109. package/server/service/figure/figure-thumbnail-reader.ts +0 -20
  110. package/server/service/figure/figure-thumbnail-store.ts +0 -111
  111. package/server/service/figure/figure-thumbnail-upgrade.pg.test.ts +0 -93
  112. package/server/service/figure/figure-thumbnail-upgrade.ts +0 -70
  113. package/server/service/figure/figure-tool-doors.test.ts +0 -127
  114. package/server/service/figure/figure-tools-door-db.test.ts +0 -227
  115. package/server/service/figure/figure-tools.test.ts +0 -817
  116. package/server/service/figure/figure-tools.ts +0 -611
  117. package/server/service/figure/figure-type.ts +0 -241
  118. package/server/service/figure/figure-write.test.ts +0 -15
  119. package/server/service/figure/figure-write.ts +0 -131
  120. package/server/service/figure/figure.ts +0 -241
  121. package/server/service/figure/index.ts +0 -13
  122. package/server/service/figure-recipe/figure-recipe-resolver.ts +0 -38
  123. package/server/service/figure-recipe/figure-recipe-templates.test.ts +0 -47
  124. package/server/service/figure-recipe/figure-recipe-templates.ts +0 -70
  125. package/server/service/figure-recipe/figure-recipe-type.ts +0 -31
  126. package/server/service/figure-recipe/index.ts +0 -3
  127. package/server/service/index.ts +0 -34
  128. package/tsconfig.json +0 -14
@@ -1,112 +0,0 @@
1
- /**
2
- * Reading a GLB on upload (ADR-0129 decision 6): what a board can draw, and the numbers a mesh part carries.
3
- * The files are made here, from their JSON: glTF requires every POSITION accessor to state its min and max, which is all
4
- * the reader reads.
5
- */
6
- import { GlbRefusal, eulerOfRotation, readGlb } from './figure-glb'
7
-
8
- /** A binary glTF: the JSON chunk, padded to four bytes, and an empty binary chunk. */
9
- function glb(json: unknown, { version = 2 }: { version?: number } = {}): Uint8Array {
10
- let text = JSON.stringify(json)
11
- while (text.length % 4) text += ' '
12
- const body = new TextEncoder().encode(text)
13
- const out = new Uint8Array(12 + 8 + body.length + 8)
14
- const view = new DataView(out.buffer)
15
- view.setUint32(0, 0x46546c67, true)
16
- view.setUint32(4, version, true)
17
- view.setUint32(8, out.length, true)
18
- view.setUint32(12, body.length, true)
19
- view.setUint32(16, 0x4e4f534a, true)
20
- out.set(body, 20)
21
- view.setUint32(20 + body.length, 0, true)
22
- view.setUint32(24 + body.length, 0x004e4942, true)
23
- return out
24
- }
25
-
26
- /* A crane: a base (a 2 m × 0.5 m × 0.4 m box, its own origin at its centre) and a hoist below it, a 0.2 m cube with 12
27
- triangles in two primitives, turned 90° about Y and standing 1 m along X. */
28
- const quarterY = [0, Math.SQRT1_2, 0, Math.SQRT1_2]
29
- const crane = (over: Record<string, unknown> = {}) => ({
30
- asset: { version: '2.0' },
31
- scene: 0,
32
- scenes: [{ nodes: [0] }],
33
- nodes: [
34
- { name: 'base', mesh: 0, children: [1] },
35
- { name: 'hoist', mesh: 1, translation: [1, -0.5, 0], rotation: quarterY }
36
- ],
37
- meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }, { primitives: [{ attributes: { POSITION: 2 } }, { attributes: { POSITION: 2 } }] }],
38
- accessors: [
39
- { count: 24, min: [-1, -0.25, -0.2], max: [1, 0.25, 0.2] },
40
- { count: 36 },
41
- { count: 18, min: [-0.1, -0.1, -0.1], max: [0.3, 0.1, 0.1] }
42
- ],
43
- buffers: [{ byteLength: 0 }],
44
- ...over
45
- })
46
-
47
- describe('reading a GLB on upload', () => {
48
- it('counts the whole file: its bounds in mm, its triangles and its primitives', () => {
49
- const summary = readGlb(glb(crane()))
50
- expect(summary.triangles).toBe(12 + 6 + 6)
51
- expect(summary.primitives).toBe(3)
52
- expect(summary.unit).toBe('m')
53
- /* The hoist turned a quarter about Y reaches from 0.9 to 1.1 along X and from −0.3 to 0.1 along Z. */
54
- expect(summary.bounds).toEqual({ min: { x: -1000, y: -600, z: -300 }, max: { x: 1100, y: 250, z: 200 } })
55
- })
56
-
57
- it('lists each node in its own frame, and where it stands in the file', () => {
58
- const [base, hoist] = readGlb(glb(crane())).nodes
59
- expect(base).toMatchObject({ index: 0, name: 'base', parent: null, triangles: 24, primitives: 3, position: { x: 0, y: 0, z: 0 } })
60
- expect(base!.bounds).toEqual({ min: { x: -1000, y: -600, z: -300 }, max: { x: 1100, y: 250, z: 200 } })
61
- /* The hoist in its own frame is not turned, and is not re-centred: its origin is where the file put it. */
62
- expect(hoist).toMatchObject({ index: 1, name: 'hoist', parent: 0, triangles: 12, primitives: 2, position: { x: 1000, y: -500, z: 0 }, rotation: { x: 0, y: 90, z: 0 } })
63
- expect(hoist!.bounds).toEqual({ min: { x: -100, y: -100, z: -100 }, max: { x: 300, y: 100, z: 100 } })
64
- })
65
-
66
- it('offers no frame for a node that shears or mirrors, and no part for one without a mesh', () => {
67
- const sheared = readGlb(glb(crane({ nodes: [{ name: 'base', mesh: 0, children: [1], matrix: [1, 0, 0, 0, 0.5, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }, { name: 'hoist', mesh: 1 }] })))
68
- expect(sheared.nodes[0]!.refused).toBe('sheared')
69
- const mirrored = readGlb(glb(crane({ nodes: [{ name: 'base', mesh: 0, children: [1], scale: [-1, 1, 1] }, { name: 'hoist', mesh: 1 }] })))
70
- expect(mirrored.nodes[0]!.refused).toBe('sheared')
71
- const empty = readGlb(glb(crane({ nodes: [{ name: 'base', mesh: 0, children: [1] }, { name: 'hoist', mesh: 1 }, { name: 'marker' }] })))
72
- expect(empty.nodes[2]!.refused).toBe('no-mesh')
73
- })
74
-
75
- it('a strip and a fan are counted as they draw; lines and points draw no triangles', () => {
76
- const one = (mode: number, count: number) =>
77
- readGlb(glb(crane({ nodes: [{ mesh: 0 }], meshes: [{ primitives: [{ attributes: { POSITION: 0 }, mode }] }], accessors: [{ count, min: [0, 0, 0], max: [1, 1, 1] }] }))).triangles
78
- expect(one(5, 10)).toBe(8)
79
- expect(one(6, 10)).toBe(8)
80
- expect(one(1, 10)).toBe(0)
81
- })
82
-
83
- it('refuses what a board cannot draw as it is, by name', () => {
84
- const code = (bytes: Uint8Array) => {
85
- try {
86
- readGlb(bytes)
87
- } catch (e) {
88
- return e instanceof GlbRefusal ? e.code : String(e)
89
- }
90
- return 'read'
91
- }
92
- expect(code(new TextEncoder().encode('{"asset":{"version":"2.0"}}'))).toBe('GLB_NOT_BINARY')
93
- expect(code(glb(crane(), { version: 1 }))).toBe('GLB_VERSION')
94
- expect(code(glb(crane({ extensionsRequired: ['KHR_draco_mesh_compression'] })))).toBe('GLB_EXTENSION')
95
- expect(code(glb(crane({ extensionsRequired: ['EXT_meshopt_compression'] })))).toBe('read')
96
- expect(code(glb(crane({ buffers: [{ uri: 'crane.bin', byteLength: 10 }] })))).toBe('GLB_EXTERNAL')
97
- expect(code(glb(crane({ images: [{ uri: 'paint.png' }] })))).toBe('GLB_EXTERNAL')
98
- expect(code(glb(crane({ meshes: [], nodes: [{ name: 'empty' }] })))).toBe('GLB_NO_MESH')
99
- expect(code(glb(crane({ accessors: [{ count: 3 }, { count: 3 }, { count: 3 }] })))).toBe('GLB_UNREADABLE')
100
- const cut = glb(crane())
101
- expect(code(cut.subarray(0, cut.length - 4))).toBe('GLB_UNREADABLE')
102
- })
103
-
104
- it('turns a rotation into degrees in the order rigid@1 turns them', () => {
105
- const rx = (a: number) => [[1, 0, 0], [0, Math.cos(a), -Math.sin(a)], [0, Math.sin(a), Math.cos(a)]]
106
- const ry = (a: number) => [[Math.cos(a), 0, Math.sin(a)], [0, 1, 0], [-Math.sin(a), 0, Math.cos(a)]]
107
- const rz = (a: number) => [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], [0, 0, 1]]
108
- const m = (a: number[][], b: number[][]) => a.map((row, i) => b[0]!.map((_, k) => row.reduce((s, v, j) => s + v * b[j]![k]!, 0)))
109
- const d = Math.PI / 180
110
- expect(eulerOfRotation(m(m(rx(30 * d), ry(20 * d)), rz(-45 * d)))).toEqual({ x: 30, y: 20, z: -45 })
111
- })
112
- })
@@ -1,251 +0,0 @@
1
- /*
2
- * What a GLB file holds, read on upload (ADR-0129 decision 6): whether it is a glTF 2.0 binary the board can draw, and
3
- * the numbers a mesh part carries -- its bounds in mm, its triangles, its primitives -- for the whole file and for each
4
- * node of it. The kernel never reads the file (figure-model `mesh@1`, contract §13); these numbers come from here.
5
- *
6
- * Nothing is decoded but the JSON chunk. glTF requires every POSITION accessor to carry its min and max, so the bounds
7
- * are those corners carried through the node transforms; a compressed buffer (Meshopt) keeps them too.
8
- *
9
- * A node's frame is its place in the file: its world translation and rotation, in the file's root frame. A part made
10
- * from a node stands there (its position and rotation), turns about the node's origin, and is drawn with the node's
11
- * world scale kept in the drawing. A node whose world transform shears or mirrors has no such frame and is not offered.
12
- */
13
-
14
- import { FIGURE_MESH_CONTENT_TYPE, FIGURE_MESH_MAX_BYTES } from '@hatiolab/figure-model'
15
-
16
- /* The package contract's rule (figure-model): the same type and limit a board server holds an import to. */
17
- export const GLB_MIMETYPE = FIGURE_MESH_CONTENT_TYPE
18
- /** The largest file kept, in bytes. A board downloads it for every figure that draws it. */
19
- export const GLB_MAX_BYTES = FIGURE_MESH_MAX_BYTES
20
-
21
- /** The extensions a board can draw: Meshopt's decoder ships with the loader. Draco and KTX2 wait (ADR-0129 Q4). */
22
- const DRAWABLE_EXTENSIONS = new Set(['EXT_meshopt_compression', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform'])
23
-
24
- export type Box = { min: { x: number; y: number; z: number }; max: { x: number; y: number; z: number } }
25
-
26
- export interface GlbNode {
27
- /** Its place in the file's node list: what a mesh part names it by. */
28
- index: number
29
- name: string
30
- parent: number | null
31
- /** The node's subtree, in its own frame, in mm; none when it holds no mesh. */
32
- bounds: Box | null
33
- triangles: number
34
- primitives: number
35
- /** Where the node stands in the file's root frame: what a part made from it is placed at. */
36
- position: { x: number; y: number; z: number }
37
- rotation: { x: number; y: number; z: number }
38
- /** Why it cannot be a part, when it cannot. */
39
- refused?: 'no-mesh' | 'sheared'
40
- }
41
-
42
- export interface GlbSummary {
43
- /** The whole file in its root frame, in mm. */
44
- bounds: Box
45
- triangles: number
46
- primitives: number
47
- unit: 'm'
48
- nodes: GlbNode[]
49
- extensions: string[]
50
- }
51
-
52
- export class GlbRefusal extends Error {
53
- constructor(
54
- readonly code:
55
- | 'GLB_NOT_BINARY'
56
- | 'GLB_VERSION'
57
- | 'GLB_UNREADABLE'
58
- | 'GLB_EXTERNAL'
59
- | 'GLB_EXTENSION'
60
- | 'GLB_NO_MESH'
61
- | 'GLB_TOO_LARGE',
62
- message: string,
63
- /** What a screen says it with: the extensions it needs, the most bytes kept. */
64
- readonly params: Record<string, string | number> = {}
65
- ) {
66
- super(message)
67
- this.name = 'GlbRefusal'
68
- }
69
- }
70
-
71
- type M4 = number[] // column-major, as glTF writes it
72
- const IDENTITY: M4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
73
- const mul = (a: M4, b: M4): M4 => {
74
- const out = new Array(16).fill(0)
75
- for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) for (let k = 0; k < 4; k++) out[c * 4 + r] += a[k * 4 + r]! * b[c * 4 + k]!
76
- return out
77
- }
78
- const apply = (m: M4, p: [number, number, number]): [number, number, number] => [
79
- m[0]! * p[0] + m[4]! * p[1] + m[8]! * p[2] + m[12]!,
80
- m[1]! * p[0] + m[5]! * p[1] + m[9]! * p[2] + m[13]!,
81
- m[2]! * p[0] + m[6]! * p[1] + m[10]! * p[2] + m[14]!
82
- ]
83
- function local(node: any): M4 {
84
- if (Array.isArray(node.matrix) && node.matrix.length === 16) return node.matrix.map(Number)
85
- const [tx, ty, tz] = node.translation ?? [0, 0, 0]
86
- const [qx, qy, qz, qw] = node.rotation ?? [0, 0, 0, 1]
87
- const [sx, sy, sz] = node.scale ?? [1, 1, 1]
88
- const r = [
89
- 1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy + qz * qw), 2 * (qx * qz - qy * qw),
90
- 2 * (qx * qy - qz * qw), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz + qx * qw),
91
- 2 * (qx * qz + qy * qw), 2 * (qy * qz - qx * qw), 1 - 2 * (qx * qx + qy * qy)
92
- ]
93
- return [r[0]! * sx, r[1]! * sx, r[2]! * sx, 0, r[3]! * sy, r[4]! * sy, r[5]! * sy, 0, r[6]! * sz, r[7]! * sz, r[8]! * sz, 0, tx, ty, tz, 1]
94
- }
95
-
96
- /**
97
- * A world matrix as translation and rotation, the scale left in the drawing. Undefined when its axes are not square to
98
- * each other (a shear) or it mirrors: there is no frame to stand a part in.
99
- */
100
- function frameOf(m: M4): { rotation: number[][]; translation: [number, number, number]; inverse: M4 } | undefined {
101
- const cols = [0, 1, 2].map(c => [m[c * 4]!, m[c * 4 + 1]!, m[c * 4 + 2]!])
102
- const len = cols.map(c => Math.hypot(...c))
103
- if (len.some(l => !(l > 1e-12))) return undefined
104
- const unit = cols.map((c, i) => c.map(v => v / len[i]!))
105
- const dot = (a: number[], b: number[]) => a[0]! * b[0]! + a[1]! * b[1]! + a[2]! * b[2]!
106
- if (Math.abs(dot(unit[0]!, unit[1]!)) > 1e-6 || Math.abs(dot(unit[0]!, unit[2]!)) > 1e-6 || Math.abs(dot(unit[1]!, unit[2]!)) > 1e-6) return undefined
107
- const [a, b, c] = unit as [number[], number[], number[]]
108
- const det = a[0]! * (b[1]! * c[2]! - b[2]! * c[1]!) - b[0]! * (a[1]! * c[2]! - a[2]! * c[1]!) + c[0]! * (a[1]! * b[2]! - a[2]! * b[1]!)
109
- if (det < 0) return undefined
110
- /* rotation rows: R[r][c] = unit[c][r] */
111
- const rotation = [0, 1, 2].map(r => [0, 1, 2].map(col => unit[col]![r]!))
112
- const translation: [number, number, number] = [m[12]!, m[13]!, m[14]!]
113
- /* The inverse of the rigid part: Rᵀ and −Rᵀt. */
114
- const inv: M4 = [...IDENTITY]
115
- for (let r = 0; r < 3; r++) for (let col = 0; col < 3; col++) inv[col * 4 + r] = rotation[col]![r]!
116
- for (let r = 0; r < 3; r++) inv[12 + r] = -(rotation[0]![r]! * translation[0] + rotation[1]![r]! * translation[1] + rotation[2]![r]! * translation[2])
117
- return { rotation, translation, inverse: inv }
118
- }
119
-
120
- /** A rotation as degrees about X, Y and Z in the order `rigid@1` turns them (Rx · Ry · Rz). */
121
- export function eulerOfRotation(r: number[][]): { x: number; y: number; z: number } {
122
- const deg = (a: number) => {
123
- const d = Math.round(((a * 180) / Math.PI) * 1e6) / 1e6
124
- return d === 0 ? 0 : d
125
- }
126
- const sy = Math.max(-1, Math.min(1, r[0]![2]!))
127
- const y = Math.asin(sy)
128
- if (Math.abs(sy) < 1 - 1e-9) return { x: deg(Math.atan2(-r[1]![2]!, r[2]![2]!)), y: deg(y), z: deg(Math.atan2(-r[0]![1]!, r[0]![0]!)) }
129
- /* About Y by a quarter turn: X and Z turn about one axis and only their sum counts; Z is taken as 0. */
130
- return { x: deg(Math.atan2(r[2]![1]!, r[1]![1]!)), y: deg(y), z: 0 }
131
- }
132
-
133
- const TO_MM = 1000
134
- const empty = (): Box => ({ min: { x: Infinity, y: Infinity, z: Infinity }, max: { x: -Infinity, y: -Infinity, z: -Infinity } })
135
- const grow = (box: Box, p: [number, number, number]) => {
136
- box.min = { x: Math.min(box.min.x, p[0]), y: Math.min(box.min.y, p[1]), z: Math.min(box.min.z, p[2]) }
137
- box.max = { x: Math.max(box.max.x, p[0]), y: Math.max(box.max.y, p[1]), z: Math.max(box.max.z, p[2]) }
138
- }
139
- const round = (v: number) => {
140
- const r = Math.round(v * 1e6) / 1e6
141
- return r === 0 ? 0 : r
142
- }
143
- const inMm = (box: Box): Box => ({
144
- min: { x: round(box.min.x * TO_MM), y: round(box.min.y * TO_MM), z: round(box.min.z * TO_MM) },
145
- max: { x: round(box.max.x * TO_MM), y: round(box.max.y * TO_MM), z: round(box.max.z * TO_MM) }
146
- })
147
-
148
- /** Reads a GLB's JSON chunk, and refuses one a board cannot draw as it is. */
149
- function jsonOf(bytes: Uint8Array): any {
150
- if (bytes.length > GLB_MAX_BYTES) throw new GlbRefusal('GLB_TOO_LARGE', `the file is ${bytes.length} bytes; the most kept is ${GLB_MAX_BYTES}`, { max: Math.round(GLB_MAX_BYTES / 1024 / 1024) })
151
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
152
- if (bytes.length < 20 || view.getUint32(0, true) !== 0x46546c67) throw new GlbRefusal('GLB_NOT_BINARY', 'not a binary glTF (.glb) file')
153
- if (view.getUint32(4, true) !== 2) throw new GlbRefusal('GLB_VERSION', `glTF ${view.getUint32(4, true)}; only glTF 2.0 is read`)
154
- if (view.getUint32(8, true) !== bytes.length) throw new GlbRefusal('GLB_UNREADABLE', 'the file is cut short or has bytes past its end')
155
- const length = view.getUint32(12, true)
156
- if (view.getUint32(16, true) !== 0x4e4f534a || 20 + length > bytes.length) throw new GlbRefusal('GLB_UNREADABLE', 'its first chunk is not its JSON')
157
- try {
158
- return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + length)))
159
- } catch {
160
- throw new GlbRefusal('GLB_UNREADABLE', 'its JSON chunk is not JSON')
161
- }
162
- }
163
-
164
- export function readGlb(bytes: Uint8Array): GlbSummary {
165
- const gltf = jsonOf(bytes)
166
- if (String(gltf?.asset?.version ?? '').split('.')[0] !== '2') throw new GlbRefusal('GLB_VERSION', `glTF ${gltf?.asset?.version}; only glTF 2.0 is read`)
167
- const required: string[] = Array.isArray(gltf.extensionsRequired) ? gltf.extensionsRequired : []
168
- const undrawable = required.filter(e => !DRAWABLE_EXTENSIONS.has(e))
169
- if (undrawable.length) throw new GlbRefusal('GLB_EXTENSION', `a board cannot draw it yet: it needs ${undrawable.join(', ')}`, { extensions: undrawable.join(', ') })
170
- /* Self-contained: one buffer, the file's own; no file beside it. */
171
- if ((gltf.buffers ?? []).some((b: any) => b?.uri !== undefined)) throw new GlbRefusal('GLB_EXTERNAL', 'it reads a buffer from another file')
172
- if ((gltf.images ?? []).some((i: any) => i?.uri !== undefined && !String(i.uri).startsWith('data:')))
173
- throw new GlbRefusal('GLB_EXTERNAL', 'it reads a picture from another file')
174
-
175
- const nodes: any[] = Array.isArray(gltf.nodes) ? gltf.nodes : []
176
- const meshes: any[] = Array.isArray(gltf.meshes) ? gltf.meshes : []
177
- const accessors: any[] = Array.isArray(gltf.accessors) ? gltf.accessors : []
178
- const parent = new Array<number | null>(nodes.length).fill(null)
179
- nodes.forEach((n, i) => (Array.isArray(n?.children) ? n.children : []).forEach((c: number) => (parent[c] = i)))
180
-
181
- /* World matrices, from the roots of the scene shown (or every root, when none is named). */
182
- const world = new Array<M4 | undefined>(nodes.length)
183
- const scene = gltf.scenes?.[gltf.scene ?? 0]
184
- const roots: number[] = Array.isArray(scene?.nodes) ? scene.nodes : nodes.map((_, i) => i).filter(i => parent[i] === null)
185
- const visit = (i: number, above: M4) => {
186
- if (world[i]) throw new GlbRefusal('GLB_UNREADABLE', `node ${i} is reached twice: the nodes are not a tree`)
187
- world[i] = mul(above, local(nodes[i]))
188
- for (const c of nodes[i]?.children ?? []) visit(c, world[i]!)
189
- }
190
- roots.forEach(i => visit(i, IDENTITY))
191
-
192
- /* What one primitive costs and where it reaches, in its mesh's own space. */
193
- const primitive = (p: any) => {
194
- const position = accessors[p?.attributes?.POSITION]
195
- if (!position || !Array.isArray(position.min) || !Array.isArray(position.max))
196
- throw new GlbRefusal('GLB_UNREADABLE', 'a primitive has no POSITION with its min and max')
197
- const count = p.indices !== undefined ? Number(accessors[p.indices]?.count) : Number(position.count)
198
- const mode = p.mode ?? 4
199
- const triangles = mode === 4 ? Math.floor(count / 3) : mode === 5 || mode === 6 ? Math.max(count - 2, 0) : 0
200
- const [x0, y0, z0] = position.min.map(Number)
201
- const [x1, y1, z1] = position.max.map(Number)
202
- const corners: Array<[number, number, number]> = [x0, x1].flatMap(x => [y0, y1].flatMap(y => [z0, z1].map(z => [x, y, z] as [number, number, number])))
203
- return { triangles, corners }
204
- }
205
-
206
- const drawn = (i: number) => (nodes[i]?.mesh !== undefined ? meshes[nodes[i].mesh]?.primitives ?? [] : [])
207
- const subtree = (i: number): number[] => [i, ...(nodes[i]?.children ?? []).flatMap((c: number) => subtree(c))]
208
-
209
- const whole = empty()
210
- let triangles = 0,
211
- primitives = 0
212
- for (let i = 0; i < nodes.length; i++) {
213
- if (!world[i]) continue
214
- for (const p of drawn(i)) {
215
- const one = primitive(p)
216
- triangles += one.triangles
217
- primitives++
218
- for (const c of one.corners) grow(whole, apply(world[i]!, c))
219
- }
220
- }
221
- if (!primitives) throw new GlbRefusal('GLB_NO_MESH', 'it holds no mesh to draw')
222
-
223
- const listed: GlbNode[] = nodes.map((n, i) => {
224
- const frame = world[i] ? frameOf(world[i]!) : undefined
225
- const below = subtree(i).filter(k => world[k])
226
- const box = empty()
227
- let t = 0,
228
- p = 0
229
- for (const k of below)
230
- for (const prim of drawn(k)) {
231
- const one = primitive(prim)
232
- t += one.triangles
233
- p++
234
- if (frame) for (const c of one.corners) grow(box, apply(mul(frame.inverse, world[k]!), c))
235
- }
236
- const position = frame ? { x: round(frame.translation[0] * TO_MM), y: round(frame.translation[1] * TO_MM), z: round(frame.translation[2] * TO_MM) } : { x: 0, y: 0, z: 0 }
237
- return {
238
- index: i,
239
- name: typeof n?.name === 'string' ? n.name : `node ${i}`,
240
- parent: parent[i]!,
241
- bounds: p && frame ? inMm(box) : null,
242
- triangles: t,
243
- primitives: p,
244
- position,
245
- rotation: frame ? eulerOfRotation(frame.rotation) : { x: 0, y: 0, z: 0 },
246
- ...(!p ? { refused: 'no-mesh' as const } : !frame ? { refused: 'sheared' as const } : {})
247
- }
248
- })
249
-
250
- return { bounds: inMm(whole), triangles, primitives, unit: 'm', nodes: listed, extensions: Array.isArray(gltf.extensionsUsed) ? gltf.extensionsUsed : [] }
251
- }
@@ -1,192 +0,0 @@
1
- import { Field, ID, ObjectType, Float, Int } from 'type-graphql'
2
- import { GraphQLJSON } from 'graphql-scalars'
3
- import { Column, Entity, Index, ManyToOne, PrimaryGeneratedColumn, RelationId } from 'typeorm'
4
-
5
- import {
6
- HistoryActionColumn,
7
- HistoryActionType,
8
- HistoryEntityInterface,
9
- HistoryOriginalIdColumn
10
- } from '@operato/typeorm-history'
11
- import { User } from '@things-factory/auth-base'
12
- import { Domain, longTextColumn } from '@things-factory/shell'
13
-
14
- import { Figure } from './figure.js'
15
-
16
- /**
17
- * 발행된 버전 하나 — **발행할 때만 남는다.**
18
- *
19
- * 저작 중 저장은 여기 오지 않는다. 스냅샷을 뜨는 subscriber 가 `state === 'released'` 인 저장에만
20
- * 움직인다(`event-subscriber.ts`) — board 가 같은 규칙으로 돈다.
21
- *
22
- * ## 왜 통째로 베끼나
23
- *
24
- * 버전을 되세우려면 그때의 정본만으로는 모자란다. 이름·분류·그림·비용까지 함께 있어야 「그 버전이
25
- * 무엇이었나」를 보여 주고 되돌릴 수 있다. 파생값(점수·삼각형·묶음)도 같이 둔다 — 다시 계산하면
26
- * 형식이 바뀐 오늘의 값이 나오고, 그것은 그 버전의 값이 아니다.
27
- */
28
- @Entity()
29
- @Index('ix_figure_history_0', (history: FigureHistory) => [history.originalId, history.version], { unique: true })
30
- @ObjectType({ description: 'A released version of a figure — one row per release.' })
31
- export class FigureHistory implements HistoryEntityInterface<Figure> {
32
- @PrimaryGeneratedColumn('uuid')
33
- @Field(type => ID, { description: 'Unique identifier for this history record.' })
34
- readonly id: string
35
-
36
- @Column({ nullable: true, default: 1 })
37
- @Field(type => Int, { nullable: true, description: 'The published version number this record holds.' })
38
- version?: number = 1
39
-
40
- @ManyToOne(type => Domain)
41
- @Field(type => Domain, { nullable: true, description: 'The domain the figure belonged to.' })
42
- domain?: Domain
43
-
44
- @RelationId((history: FigureHistory) => history.domain)
45
- domainId?: string
46
-
47
- @Column({ nullable: true })
48
- @Field({ nullable: true, description: 'The stored identifier of the figure. It never changes.' })
49
- type?: string
50
-
51
- @Column({ nullable: true })
52
- @Field({ nullable: true, description: 'Namespace of the full name {namespace}/{type} at this version.' })
53
- namespace?: string
54
-
55
- @Column({ nullable: true })
56
- @Field({ nullable: true, description: 'The display name at this version.' })
57
- name?: string
58
-
59
- @Column({ nullable: true })
60
- @Field({ nullable: true, description: 'The description at this version.' })
61
- description?: string
62
-
63
- @Column('simple-json', { nullable: true, default: null })
64
- @Field(type => GraphQLJSON, { nullable: true, description: 'Display names by language at this version.' })
65
- names?: Record<string, string>
66
-
67
- @Column({ nullable: true })
68
- @Field({ nullable: true, description: 'The classification code at this version.' })
69
- category?: string
70
-
71
- @Column({ nullable: true })
72
- @Field({ nullable: true, description: 'The lifecycle state recorded with this version.' })
73
- state?: 'draft' | 'released'
74
-
75
- @Column({ nullable: true, ...longTextColumn() })
76
- @Field({ nullable: true, description: 'The figure asset JSON (figure-asset-1) at this version.' })
77
- source?: string
78
-
79
- @Column({ nullable: true, ...longTextColumn() })
80
- @Field({ nullable: true, description: 'The master-data field definition at this version.' })
81
- properties?: string
82
-
83
- @Column({ nullable: true, ...longTextColumn() })
84
- @Field({ nullable: true, description: 'The thumbnail as it looked at this version.' })
85
- thumbnail?: string
86
-
87
- /*
88
- * 그림의 내용 해시(SHA-256). 그림 자체는 attachment-base 가 갖고(refType `figure-thumbnail`, refBy 이 해시),
89
- * `/figure-thumbnail/:id` 가 권한을 본 뒤 내준다(ADR-0104 결정 6). `thumbnail` 칸은 옛 base64 가 남은 행을
90
- * 기동 때 옮기기 위한 칸이다 — 옮긴 뒤에는 비어 있고, 새 그림은 그 칸에 쓰지 않는다.
91
- */
92
- @Column({ nullable: true })
93
- @Field({ nullable: true, description: 'SHA-256 of the thumbnail picture; the picture is served by /figure-thumbnail/:id.' })
94
- thumbnailHash?: string
95
-
96
- /*
97
- * 그때의 비용이다. 오늘 다시 계산하면 오늘의 형식으로 나온다 — 그 버전을 설명하지 못한다.
98
- */
99
- @Column({ type: 'float', nullable: true })
100
- @Field(type => Float, { nullable: true, description: 'Reuse score as computed at this version.' })
101
- score?: number
102
-
103
- @Column({ nullable: true })
104
- @Field(type => Int, { nullable: true, description: 'Triangle count at this version.' })
105
- triangles?: number
106
-
107
- @Column({ nullable: true })
108
- @Field(type => Int, { nullable: true, description: 'Material group count at this version.' })
109
- groups?: number
110
-
111
- @Column({ nullable: true, ...longTextColumn() })
112
- @Field({ nullable: true, description: 'The note left when this version was released.' })
113
- comment?: string
114
-
115
- /*
116
- * 이 버전의 정본 형식(`figure-asset-1`)과, 직전 버전에 견준 변경(ADR-0104 결정 5). 발행할 때 한 번 정하고 다시
117
- * 계산하지 않는다 — 버전을 고정해 쓰는 쪽은 다음 버전으로 옮기기 전에 이것을 읽는다.
118
- */
119
- @Column({ nullable: true })
120
- @Field({ nullable: true, description: 'The asset format this version was written in (figure-asset-1).' })
121
- assetFormat?: string
122
-
123
- @Column({ nullable: true, ...longTextColumn() })
124
- @Field({
125
- nullable: true,
126
- description:
127
- 'What changed against the previous release, as JSON: [{ code, blocking, subject?, values, detail }]. [] for the first release. null when it was not compared: the previous release could not be read, or this release was made before releases recorded it (figure-service 10.1.109).'
128
- })
129
- changes?: string
130
-
131
- /*
132
- * 이 버전을 잰 커널의 버전(figure-model `FIGURE_KERNEL_VERSION`). 점수 · 묶음 · metrics 는 그 커널의 규칙으로 센 값이다 —
133
- * 규칙이 바뀌어도 발행된 값을 다시 세서 덮지 않고(ADR-0109 C1), 읽는 쪽은 이 칸으로 「남긴 값」과 「지금 규칙의 값」을
134
- * 가른다. 이 칸이 생기기 전에 발행된 버전은 비어 있다.
135
- */
136
- @Column({ nullable: true })
137
- @Field({
138
- nullable: true,
139
- description:
140
- 'The figure-model kernel version that measured this release (score, groups, metrics). null for releases made before releases recorded it.'
141
- })
142
- kernelVersion?: string
143
-
144
- @Column({ nullable: true, ...longTextColumn() })
145
- @Field({
146
- nullable: true,
147
- description:
148
- 'What this version measured once, as JSON (figure-model figureReleaseMetricsOf): { atLargest?: { size, triangles, groups }, linear?: { scalable, parts, probe }, origin?: { centred, off }, joints?: { schema, derivation, joints, unlisted } }. atLargest and linear only for a figure that takes its size from the instance. joints is the joint list a controller reads (schema 2, figure-model figureJointsOf), present when anything moves.'
149
- })
150
- metrics?: string
151
-
152
- @Column({ nullable: true, ...longTextColumn() })
153
- @Field({
154
- nullable: true,
155
- description: 'The plan from above at the authored size, as JSON (figure-model figureTopViewOf): { shapes: [{ id, color, outline, holes, top, transparent }], size }.'
156
- })
157
- topView?: string
158
-
159
- @Column({ nullable: true })
160
- @Field({ nullable: true, description: 'When the original figure was created.' })
161
- createdAt?: Date
162
-
163
- @Column({ nullable: true })
164
- @Field({ nullable: true, description: 'When the figure was saved at this version.' })
165
- updatedAt?: Date
166
-
167
- @ManyToOne(type => User, { nullable: true })
168
- @Field(type => User, { nullable: true, description: 'Who created the original figure.' })
169
- creator?: User
170
-
171
- @RelationId((history: FigureHistory) => history.creator)
172
- creatorId?: string
173
-
174
- @ManyToOne(type => User, { nullable: true })
175
- @Field(type => User, { nullable: true, description: 'Who released this version.' })
176
- updater?: User
177
-
178
- @RelationId((history: FigureHistory) => history.updater)
179
- updaterId?: string
180
-
181
- @Column({ nullable: true })
182
- @Field({ nullable: true, description: 'When the original figure was deleted, if it was.' })
183
- deletedAt?: Date
184
-
185
- @HistoryOriginalIdColumn()
186
- @Field({ description: 'The id of the figure this version belongs to.' })
187
- public originalId!: string
188
-
189
- @HistoryActionColumn({ nullable: false, type: 'varchar', length: 10 })
190
- @Field(type => String, { description: 'What produced this record (created · updated · deleted).' })
191
- public action!: HistoryActionType
192
- }