-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
244 lines (222 loc) · 7.99 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// deno-lint-ignore-file no-explicit-any
import { parse } from "jsr:@std/yaml";
import * as json from './jsontypes.ts'
import { Lexer, Parser } from "./tshv2/main.ts";
import ASTtoBlocks, { Environment } from "./asttoblocks.ts";
import * as zip from "jsr:@zip-js/zip-js";
import CryptoJS from "https://esm.sh/[email protected]";
import path from 'node:path'
// the t stands for tosh3
type TSound = any // TODO: finish this
type TCostume = {
format: 'svg' | string
path: string
}
type TSprite = {
stage?: boolean
name: string
costumes: Record<string, TCostume>
sounds: Record<string, TSound>
code: null | string
}
type TProject = {
sprites: Record<string, TSprite>
}
const dir: string = path.resolve(Deno.args[0] || Deno.cwd() || '.');
console.log(dir)
const decoder = new TextDecoder("utf-8");
const rawProjectConfig: string = decoder.decode(
Deno.readFileSync(
path.join(dir, 'project.prj.yaml')
)
)
const project: TProject = parse(rawProjectConfig) as TProject
console.debug(project)
const projectJson: {
targets: json.Sprite[],
meta: any,
$schema?: string,
extensions: string[],
extensionURLs: Record<string, string>
} = {
targets: [],
meta: {},
extensions: [],
extensionURLs: {},
}
function removeId(a: blockBlock): json.Block {
const b: json.Block & { id?: string } = a
delete b.id;
return b
}
export type blockBlock = ({ id: string } & json.Block)
export type varBlock = { id: string, data: [12, string, string] }
export type jsonBlock = blockBlock | varBlock
const assets: Map<string, string> = new Map();
const extensions: Set<[string, string]> = new Set();
let layer = -1;
for (const spriteName in project.sprites) {
layer++;
const sprite: TSprite = project.sprites[spriteName];
const jsonSprite: Partial<json.Sprite> = {};
jsonSprite.name = sprite.name
jsonSprite.isStage = sprite.stage ?? false
jsonSprite.lists = {}
jsonSprite.variables = {}
jsonSprite.broadcasts = {}
jsonSprite.costumes = []
if (sprite.code) {
const sourceCode = new TextDecoder().decode(Deno.readFileSync(path.join(dir, sprite.code)));
const lexer = new Lexer(sourceCode);
const tokens = lexer.tokenize();
const parser = new Parser(tokens);
let ast;
try {
ast = parser.parse();
} catch (error) {
console.error(error)
console.log('at', parser.position, tokens.map((a, i) => i == parser.position ? `${a.type}(${a.value}) <--` : `${a.type}(${a.value})`).join('\n'))
throw 'error during parsing'
}
if (Deno.args.includes('-a')) {
Deno.writeFileSync('ast.json', new TextEncoder().encode(JSON.stringify(ast, null, 4)))
}
const [blockaroonies, env]: [jsonBlock[], Environment] = await ASTtoBlocks(ast);
// console.log(ast, blockaroonies, env)
jsonSprite.variables = {
...Object.fromEntries(
[...env.variables.entries()].map(([v, n]) => [
n,
[
v,
0
]
])
)
}
jsonSprite.lists = {
...Object.fromEntries(
[...env.lists.entries()].map(([v, n]) => [
n[0],
[
v,
n[1]
]
])
)
}
const stage = projectJson.targets.find(t => t.isStage);
if (stage) {
stage.variables = {
...Object.fromEntries(
[...env.globalVariables.entries()].map(([v, n]) => [
n,
[
v,
0
]
])
),
...stage.variables
}
stage.lists = {
...Object.fromEntries(
[...env.globalLists.entries()].map(([v, n]) => [
n[0],
[
v,
n[1]
]
])
),
...stage.variables
}
}
env.extensions.forEach(ext => extensions.add(ext))
jsonSprite.blocks = Object.fromEntries(blockaroonies.map(b => [b.id, 'data' in b ? b.data : removeId(b)]))
} else {
jsonSprite.blocks = {}
}
jsonSprite.currentCostume = 0;
jsonSprite.sounds = [] // TODO: fix this
jsonSprite.volume = 100;
jsonSprite.layerOrder = layer
jsonSprite.isStage = sprite.stage ?? false
if (jsonSprite.isStage) {
jsonSprite.tempo = 60
jsonSprite.videoTransparency = 50
jsonSprite.videoState = 'on'
} else if (jsonSprite.isStage == false) {
jsonSprite.visible = true
jsonSprite.x = 0;
jsonSprite.y = 0;
jsonSprite.size = 100;
jsonSprite.direction = 90;
jsonSprite.draggable = false;
jsonSprite.rotationStyle = 'all around'
}
let completesprite: json.Sprite;
if (jsonSprite.isStage) {
completesprite = jsonSprite as json.Stage
} else if (jsonSprite.isStage == false) {
completesprite = jsonSprite as json.RealSprite
} else throw new Error()
for (const [name, asset] of Object.entries(sprite.costumes)) {
let [rotationCenterX, rotationCenterY] = [0, 0]
if (!assets.has(asset.path)) {
const assetData = new TextDecoder().decode(Deno.readFileSync(path.join(dir, asset.path)));
const match = [...assetData.matchAll(/<!--rotationCenter:(.*?):(.*?)-->/g)][0];
console.log(match ? match[1] : 'a')
if(match && match[1] && match[2]) {
[rotationCenterX, rotationCenterY] = [Number(match[1]), Number(match[2])]
}
const hash = CryptoJS.MD5(assetData).toString();
assets.set(asset.path, hash);
}
const ext = asset.path.match(/\.(.*?)$/g)?.[0]
jsonSprite.costumes.push({
assetId: assets.get(asset.path) ?? '',
dataFormat: asset.format, // TODO - figure out bitmap format
bitmapResolution: 1,
md5ext: assets.get(asset.path) as string + ext,
name,
rotationCenterX,
rotationCenterY,
})
}
projectJson.targets.push(completesprite)
}
projectJson.extensions = [...extensions].map(a => a[1])
projectJson.extensionURLs = Object.fromEntries([...extensions].map(([a, b]) => [b, a]))
projectJson.meta = {
agent: '',
semver: '3.0.0',
platform: {
name: 'backslash. (TurboWarp-compatible)',
url: 'https://github.com/WlodekM/scratch-text-coding-thingy'
}
}
//TODO - figure out what the SHIT is causing it to error
//@ts-expect-error: uh
const completeproject: json.Project & { $schema?: string } = {
$schema: "../schema/sb3_schema.json",
...projectJson
}
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(completeproject, null, 4)) // Since this now outputs an sb3, this is purely for debugging so we can indent
Deno.writeFileSync(path.join(dir, 'out.json'), data)
//SECTION - Write the project json and assets into a zip
const zipFileWriter = new zip.BlobWriter();
const zipWriter = new zip.ZipWriter(zipFileWriter);
await zipWriter.add("project.json", new zip.TextReader(JSON.stringify(completeproject)));
await zipWriter.add('assets/')
for (const [asset, uuid] of [...assets.entries()]) {
const file = Deno.readFileSync(path.join(dir, asset))
await zipWriter.add(`assets/${uuid}.svg`, new zip.BlobReader(new Blob([file]))) // ungodly conversion between a uint8array and reader
}
await zipWriter.close();
// Retrieves the Blob object containing the zip content into `zipFileBlob`. It
// is also returned by zipWriter.close() for more convenience.
const zipFileBlob = await zipFileWriter.getData();
Deno.writeFileSync(path.join(dir, 'project.sb3'), await zipFileBlob.bytes())
//!SECTION