forked from JohnEarnest/Octo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
octo
executable file
·219 lines (204 loc) · 6.58 KB
/
octo
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
#!/usr/bin/env node
// simple piped commandline octo compiler
"use strict";
const compiler = require('./js/compiler')
const decompiler = require('./js/decompiler')
const sharing = require('./js/sharing')
const fs = require('fs')
const path = require('path')
const defaults = {
tickrate:20,
fillColor:"#FFCC00",
fillColor2:"#FF6600",
blendColor:"#662200",
backgroundColor:"#996600",
buzzColor:"#FFAA00",
quietColor:"#000000",
shiftQuirks:false,
loadStoreQuirks:false,
vfOrderQuirks:false,
clipQuirks:false,
jumpQuirks:false,
logicQuirks:false,
vBlankQuirks:false,
screenRotation:0,
maxSize:3584,
touchInputMode:'none',
fontStyle:'octo',
displayScale:'6',
}
/**
*
* Utilities:
*
**/
const zeroes = '00000000'
global.maskFormat = mask => options.numericMask ? numericFormat(mask) : binaryFormat(mask)
global.numericFormat = num => options.numericFormat=='dec'?decimalFormat(num):
options.numericFormat=='bin'?binaryFormat(num): hexFormat(num)
global.decimalFormat = num => num.toString(10)
global.hexFormat = num => {
const hex=num.toString(16).toUpperCase()
return '0x'+zeroPad(hex.length,2)+hex
}
global.binaryFormat = num => {
const bin=num.toString(2)
return '0b'+zeroPad(bin.length,8)+bin
}
function zeroPad(strLen, byteLength) {
const dif=strLen%byteLength
return dif==0 ? '' : zeroes.substr(0, byteLength-dif);
}
function extractFlag(name) {
const index=process.argv.indexOf(name)
if (index==-1) return false
process.argv.splice(index,1)
return true
}
function extractParameter(name) {
const index=process.argv.indexOf(name)
if (index==-1) return null
const val=process.argv[index+1]
process.argv.splice(index,2)
return val
}
function readTextFile(path) {
// files from some systems might include a byte-order mark (BOM):
return fs.readFileSync(path, { encoding:'utf8' }).replace(/\uFEFF/g, '')
}
/**
*
* Operations:
*
**/
function compile(sourceCode) {
let comp;
try {
comp = new compiler.Compiler(sourceCode)
comp.go()
let len=comp.rom.length
while(comp.rom[len-1]===0) len-=1
return comp.rom.slice(0,len)
}
catch(err) {
let line=1, pos=1
if (comp.pos!=null) {
for(let x=0; x<comp.pos[1]-1; x++){
pos++;
if (sourceCode.charAt(x) == '\n') pos=1, line++
}
}
console.error("(%d:%d) %s", line, pos, err)
process.exit(1)
}
}
function compileFile(src, dst, options) {
const programText=readTextFile(src)
const programRom=compile(programText)
const programBinary=Buffer.from(programRom)
if (/\.gif$/i.test(dst)) {
const label=dst+'\n'+(new Date().toISOString().replace('T','\n'))
const payload={
created: new Date().toISOString(),
program: programText,
options: options,
}
fs.writeFileSync(dst, Buffer.from(sharing.buildCartridge(label,payload,null)), { encoding:'binary' })
}
if (/\.html$/i.test(dst)) {
const MAGIC_STRING = '<!-- Standalone Generated By Octo (octo-ide.com) -->\n'
let page = MAGIC_STRING + `<script>data=${JSON.stringify({
program: programText,
options: options,
rom: programRom,
})}</script>\n`;
([
{u:'./js/emulator.js', f:x=>`<script>${x}</script>\n`},
{u:'./js/shared.js', f:x=>`<script>${x}</script>\n`},
{u:'./js/input.js', f:x=>`<script>${x}</script>\n`},
{u:'standalone.html',f:x=>x},
]).forEach(x => page += x.f(readTextFile(path.resolve(__dirname, x.u))))
fs.writeFileSync(dst, page)
}
else if (dst) fs.writeFileSync(dst, programBinary, { encoding:'binary' })
else process.stdout.write(programBinary)
return programBinary
}
function decompileFile(src, dst, options) {
const buff=fs.readFileSync(src)
decompiler.analyze(buff, options)
const programText=decompiler.formatProgram(buff.length)
if (dst) fs.writeFileSync(dst, programText)
else console.log(programText)
return programText;
}
function roundTripDecompile(src, dst, options) {
let decompiledText=decompileFile(src, dst, options)
const startBinary=fs.readFileSync(src)
if (decompiledText=='') {
decompiler.analyze(startBinary,options)
decompiledText=decompiler.formatProgram(startBinary.length)
}
const endBinary=compile(decompiledText)
let mismatch=false
for(var x=0; x<Math.max(startBinary.length,endBinary.length); x++) {
const mishere=startBinary[x]!=endBinary[x]
if (!mishere) continue
if (!mismatch) console.error('round trip mismatch!')
mismatch |= mishere
console.error('%s: original: %s output: %s',
hexFormat(x + 0x200),
hexFormat(startBinary[x]),
hexFormat(endBinary[x])
)
}
if (startBinary.length!=endBinary.length) {
console.error('binary sizes do not match!')
mismatch=true
}
if (mismatch) process.exit(1)
}
function decodeCart(src,dst) {
try {
const cartBytes = fs.readFileSync(src)
const cartData = sharing.parseCartridge(cartBytes)
console.log('Successfully decoded Octo Cartridge...')
console.log('---------------------------------------------')
console.log('payload: '+cartData.program.length+' characters')
console.log('creation date: ', cartData.created || 'UNKNOWN')
console.log('sharing key: ', cartData.key || 'UNKNOWN')
console.log('options: ', JSON.stringify(cartData.options, null, '\t'))
if (dst) {
fs.writeFileSync(dst, cartData.program)
console.log('\nwrote payload to '+dst)
}
}
catch(e) {
console.log('Unable to decode Octo Cartridge from GIF file!')
console.log(e)
}
}
/**
*
* Top Level:
*
**/
const decompileFlag = extractFlag("--decompile")
const roundTripFlag = extractFlag("--roundtrip")
const optionsFile = extractParameter("--options")
if (process.argv.length <3 || process.argv.length>4) {
console.log("usage: octo [--decompile] [--options <file.json>] <source> [<destination>]")
console.log(" if <source> has a .gif extension, unpack an existing octo cartridge into source code.")
console.log(" if <destination> has a .gif extension, create an octo cartridge file.")
console.log(" if <destination> has an .html extension, create a standalone HTML5 build.")
console.log(" if the specified options file does not exist, a new template will be created.")
process.exit(1)
}
if (optionsFile&&!fs.existsSync(optionsFile)) fs.writeFileSync(optionsFile,JSON.stringify(defaults,null,'\t'))
const sourceFile = process.argv[2]
const destFile = process.argv[3]
const options = optionsFile ? JSON.parse(readTextFile(optionsFile)) : {}
if (decompileFlag&&roundTripFlag) roundTripDecompile(sourceFile, destFile, options)
else if (decompileFlag) decompileFile (sourceFile, destFile, options)
else if (/\.gif$/i.test(sourceFile)) decodeCart (sourceFile, destFile)
else compileFile (sourceFile, destFile, options)