Debian Codegraph @

doc/tests/binary_fixture.ts

raw
1 type Numeric = number | bigint;
2
3 export class BinaryWriter {
4 private bytes: number[] = [];
5
6 private add(size: number, write: (view: DataView) => void): this {
7 const buffer = new ArrayBuffer(size);
8 write(new DataView(buffer));
9 this.bytes.push(...new Uint8Array(buffer));
10 return this;
11 }
12
13 u8(value: number): this { this.bytes.push(value); return this; }
14 u32(value: number): this { return this.add(4, (view) => view.setUint32(0, value, true)); }
15 i32(value: number): this { return this.add(4, (view) => view.setInt32(0, value, true)); }
16 u64(value: Numeric): this { return this.add(8, (view) => view.setBigUint64(0, BigInt(value), true)); }
17 f64(value: number): this { return this.add(8, (view) => view.setFloat64(0, value, true)); }
18 string(value: string): this { this.bytes.push(...new TextEncoder().encode(value), 0); return this; }
19 file(name: string): File { return new File([new Uint8Array(this.bytes)], name); }
20 }
21
22 function rigid(writer: BinaryWriter, translation: [number, number, number]): void {
23 writer.f64(1).f64(0).f64(0).f64(0).f64(translation[0]).f64(translation[1]).f64(translation[2]);
24 }
25
26 export function cameraFile(cameraId = 1): File {
27 return new BinaryWriter()
28 .u64(1).u32(cameraId).i32(0).u64(640).u64(480)
29 .f64(500).f64(320).f64(240)
30 .file("cameras.bin");
31 }
32
33 export function imageFile(imageId = 2, cameraId = 1, pointId = 42n): File {
34 const writer = new BinaryWriter().u64(1).u32(imageId);
35 rigid(writer, [4, 5, 6]);
36 return writer.u32(cameraId).string("images/frame.jpg").u64(1)
37 .f64(330).f64(220).u64(pointId)
38 .file("images.bin");
39 }
40
41 export function pointFile(imageId = 2, pointId = 42n, trackLength = 1): File {
42 const writer = new BinaryWriter().u64(1).u64(pointId)
43 .f64(1).f64(2).f64(3).u8(10).u8(20).u8(30).f64(0.25)
44 .u64(trackLength);
45 for (let i = 0; i < trackLength; ++i) writer.u32(imageId).u32(0);
46 return writer.file("points3D.bin");
47 }
48
49 export function modernRigFiles(cameraId = 2, imageId = 2): [File, File] {
50 const rigs = new BinaryWriter().u64(1).u32(7).u32(2)
51 .i32(0).u32(1)
52 .i32(0).u32(cameraId).u8(1);
53 rigid(rigs, [1, 0, 0]);
54 const frames = new BinaryWriter().u64(1).u32(9).u32(7);
55 rigid(frames, [0, 2, 0]);
56 frames.u32(1).i32(0).u32(cameraId).u64(imageId);
57 return [rigs.file("rigs.bin"), frames.file("frames.bin")];
58 }