This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
196 lines (190 loc) · 4.98 KB
/
main.ts
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import {
BitDepth,
ColorType,
decode as decodePNG,
encode as encodePNG,
} from "https://deno.land/x/pngs@0.1.1/mod.ts";
// @deno-types="https://cdn.esm.sh/v58/@types/yargs@17.0.8/index.d.ts"
import yargs from "https://deno.land/x/yargs@v17.3.1-deno/deno.ts";
import type { Image, Pixel } from "./mod.ts";
import {
defaultPalette,
LuoguPainter,
PaintBoardError,
parseTokens,
} from "./mod.ts";
import { pluralize, throttleAsync } from "./util.ts";
declare global {
interface NumberConstructor {
isInteger(value: unknown): value is number;
}
}
const {
"png": pngFile,
"x": x,
"y": y,
"tokens": tokensFile,
"randomize": randomize,
"cooldown": cooldown,
"preview": preview,
"board-url": boardURL,
"paint-url": paintURL,
"socket": socket,
} = yargs(Deno.args)
.usage("Usage: luogu-painter [options] <png> <x> <y>")
.version(false)
.option("tokens", {
alias: "s",
description: "file to read tokens from",
type: "string",
})
.option("randomize", {
alias: "r",
description: "randomize the order of pixels",
type: "boolean",
})
.option("cooldown", {
alias: "t",
description: "milliseconds to wait after drawing each pixel",
type: "number",
})
.option("preview", {
alias: "p",
description: "file to store a preview to",
type: "string",
})
.option("board-url", {
type: "string",
hidden: true,
})
.option("paint-url", {
type: "string",
hidden: true,
})
.option("socket", {
type: "string",
hidden: true,
})
.option("help", {
alias: "h",
description: "show this help message",
type: "boolean",
})
.command("$0 <png> <x> <y>", false, (yargs) =>
yargs
.positional("png", {
description: "image to draw",
type: "string",
normalize: true,
})
.positional("x", {
description: "x coordinate in pixels",
type: "number",
})
.positional("y", {
description: "y coordinate in pixels",
type: "number",
}))
.fail((msg, err) => {
if (err) {
throw err;
}
console.error(msg);
console.error("Try --help for more information.");
Deno.exit(2);
})
.strict()
.parseSync();
if (typeof pngFile !== "string") {
throw new TypeError("png is not a string.");
}
if (!Number.isInteger(x)) {
throw new TypeError("x is not an integer.");
}
if (!Number.isInteger(y)) {
throw new TypeError("y is not an integer.");
}
const { width, height, data } = await Deno.readFile(pngFile).then((data) => {
const { width, height, image, colorType, bitDepth } = decodePNG(data);
if (colorType !== ColorType.RGBA) {
throw new Error(`Unsupported color type ${colorType}`);
}
if (bitDepth !== BitDepth.Eight) {
throw new Error(`Unsupported bit depth ${bitDepth}`);
}
return { width, height, data: image };
});
const tokens = tokensFile === undefined
? []
: parseTokens(await Deno.readTextFile(tokensFile));
if (tokens.length === 0) {
console.log("No tokens; starting in watch mode");
} else {
console.log(`Using ${pluralize(tokens.length, "token", "tokens")}`);
}
const painter = new LuoguPainter({
image: { x, y, width, height, data },
tokens,
randomize,
cooldown,
boardURL,
paintURL,
socket,
});
let boardCache: Image;
let pixelsCache: Pixel[];
const savePreview = throttleAsync(60000, async (path: string) => {
console.log("Saving preview");
try {
const { data, width, height } = boardCache;
const previewData = new Uint8Array(data);
for (const { x, y, color } of pixelsCache) {
previewData[y * width + x] = color;
}
const png = encodePNG(previewData, width, height, {
palette: defaultPalette,
color: ColorType.Indexed,
});
const tempPath = await Deno.makeTempFile();
await Deno.writeFile(tempPath, png);
await Deno.rename(tempPath, path);
} catch (e: unknown) {
console.error("Failed to save preview:", e);
}
});
let lastCount = -1;
function update(count: number): void {
if (count !== lastCount) {
lastCount = count;
console.log(`${pluralize(count, "pixel", "pixels")} remaining`);
}
if (preview !== undefined) {
savePreview(preview);
}
}
painter.addEventListener("load", (event) => {
const { board, pixels, remaining } = event.detail;
boardCache = board;
pixelsCache = pixels;
console.log(`Board loaded (${board.width}x${board.height})`);
console.log(`${pluralize(pixels.length, "pixel", "pixels")} in total`);
update(remaining);
});
painter.addEventListener("update", (event) => {
const { pixel: { x, y, color }, remaining } = event.detail;
const { data, width } = boardCache;
data[y * width + x] = color;
update(remaining);
});
painter.addEventListener("paint", (event) => {
const { x, y, color } = event.detail;
console.log(`(${x}, ${y}) ← ${color}`);
});
painter.addEventListener("error", (event) => {
const error = event.detail;
if (error instanceof PaintBoardError) {
console.error(`${error.token}: ${error.message}`);
} else {
console.error("Network error:", error);
}
});