init repo

This commit is contained in:
RomanRom2 committed 2025-01-28 19:17:01 +03:00
commit 90e6151613
3260 files changed
+3745062

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
{
"extends": "google",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"no-tabs": "off",
"no-var": "off"
},
"env": {
"browser": true
}
}
+4
View File
@@ -0,0 +1,4 @@
*~
.tags
node_modules
roms
+22
View File
@@ -0,0 +1,22 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
},
{
"name": "Launch index.html (disable sourcemaps)",
"type": "chrome",
"request": "launch",
"sourceMaps": false,
"file": "${workspaceFolder}/src/index.html"
}
]
}
+25
View File
@@ -0,0 +1,25 @@
BSD 2-Clause License
Copyright (c) 2018, Philip Thomas
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+27
View File
@@ -0,0 +1,27 @@
Gigatron Simulator
==================
The simulator loads the ROM using an `XmlHttpRequest`, so the application must be served up over HTTP.
The `package.json` can install an HTTP server, just do:
npm install
Pick and download a [`*.rom`](https://github.com/kervinck/gigatron-rom/) file into the `src/` directory and rename it as `gigatron.rom`
Direct links:
[`ROM v1`](https://github.com/kervinck/gigatron-rom/raw/master/ROMv1.rom)
[`ROM v2`](https://github.com/kervinck/gigatron-rom/raw/master/ROMv2.rom)
[`ROM v3`](https://github.com/kervinck/gigatron-rom/raw/master/ROMv3.rom)
Start the HTTP server
npm start
Point your browser at [localhost:8000/src](localhost:8000/src).
Use the cursor keys for the D-pad.
## GT1 Files
GT1 files can be loaded by dropping a `.gt1` file onto the VGA display from File Explorer or Finder.
+5
View File
@@ -0,0 +1,5 @@
{
"name": "gigatron",
"version": "1.0.0",
"lockfileVersion": 1
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "gigatron",
"version": "1.0.0",
"description": "Gigatron Emulator",
"main": "index.js",
"scripts": {
"start": "http-server -p 8000 -c-1",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Phil Thomas",
"license": "SEE LICENSE IN LICENSE",
"devDependencies": {},
"dependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/PhilThomas/gigatron.git"
},
"bugs": {
"url": "https://github.com/PhilThomas/gigatron/issues"
},
"homepage": "https://github.com/PhilThomas/gigatron#readme"
}
+4
View File
@@ -0,0 +1,4 @@
*.rom
*.asm
*.gt1
+115
View File
@@ -0,0 +1,115 @@
const SAMPLES_PER_SECOND = 44100;
var AudioContext = window.AudioContext || window.webkitAudioContext;
/** Audio output */
export class Audio {
/**
* Create an Audio.
* @param {Gigatron} cpu - The CPU
*/
constructor(cpu) {
this.cpu = cpu;
let context = this.context = new AudioContext();
this.mute = false;
this.volume = 0.33;
this.cycle = 0;
this.bias = 0;
this.alpha = 0.99;
this.scheduled = 0;
this.full = false;
let numSamples = Math.floor(SAMPLES_PER_SECOND / 100);
this.buffers = [];
for (let i = 0; i < 8; i++) {
let buffer = context.createBuffer(1,
numSamples,
SAMPLES_PER_SECOND);
this.buffers.push(buffer);
}
this.headBufferIndex = 0;
this.tailBufferIndex = 0;
this.duration = this.buffers[0].duration;
this.tailTime = 0; // time at which tail buffer will start
this.headTime = this.duration; // time at which head buffer will end
this.channelData = this.buffers[0].getChannelData(0);
this.sampleIndex = 0;
}
/** drain completed head buffers */
drain() {
let currentTime = this.context.currentTime;
let headTime = this.headTime;
let headBufferIndex = this.headBufferIndex;
let scheduled = this.scheduled;
let numBuffers = this.buffers.length;
while (scheduled > 0 && headTime < currentTime) {
headBufferIndex = (headBufferIndex == numBuffers - 1) ? 0 :
(headBufferIndex + 1);
headTime += this.duration;
scheduled--;
}
this.headTime = headTime;
this.scheduled = scheduled;
this.full = scheduled == numBuffers;
}
/** flush current tail buffer */
_flushChannelData() {
let context = this.context;
let currentTime = context.currentTime;
let tailBufferIndex = this.tailBufferIndex;
let buffer = this.buffers[tailBufferIndex];
let scheduled = this.scheduled;
let numBuffers = this.buffers.length;
/* if the tail can't keep ahead of realtime, jump it to now */
if (this.tailTime < currentTime) {
// console.log('audio skip');
this.tailTime = currentTime;
this.headTime = currentTime + this.duration;
this.headBufferIndex = tailBufferIndex;
scheduled = 0;
}
if (!this.mute) {
let source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(this.tailTime);
}
scheduled++;
this.tailTime += this.duration;
tailBufferIndex = (tailBufferIndex == numBuffers - 1) ? 0 :
(tailBufferIndex + 1);
this.channelData = this.buffers[tailBufferIndex].getChannelData(0);
this.sampleIndex = 0;
this.tailBufferIndex = tailBufferIndex;
this.scheduled = scheduled;
this.full = scheduled == numBuffers;
}
/** advance simulation by one tick */
tick() {
this.cycle += SAMPLES_PER_SECOND;
if (this.cycle >= this.cpu.hz) {
this.cycle -= this.cpu.hz;
let sample = (this.cpu.outx >> 4) / 8;
this.bias = (this.alpha * this.bias) + ((1 - this.alpha) * sample);
sample = (sample - this.bias) * this.volume;
this.channelData[this.sampleIndex++] = sample;
if (this.sampleIndex == this.channelData.length) {
this._flushChannelData();
}
}
}
}
@@ -0,0 +1,31 @@
/** Blinkenlights on outx register */
export class BlinkenLights {
/** Create a new BlinkenLights
* @param {Gigatron} cpu
*/
constructor(cpu) {
this.cpu = cpu;
this.outx = cpu.outx & 0x0f;
this.timer = null;
for (let i = 0; i < 4; i++) {
$(`.led-${i}`).addClass(
`led-${(this.outx & (1<<i)) ? 'on' : 'off'}`);
}
}
/** advance simulation by one tick */
tick() {
let outx = this.cpu.outx & 0x0f;
let changed = this.outx ^ outx;
if (changed) {
for (let i = 0; i < 4; i++) {
if (changed & (1 << i)) {
$(`.led-${i}`).toggleClass('led-on led-off');
}
}
this.outx = outx;
}
}
}
+207
View File
@@ -0,0 +1,207 @@
import {
toHex,
} from './utils.js';
/** Gigatron Disassembler */
export class Disassembler {
/**
* The result of disassembly
* @typedef {Object} Parts
* @property {string} mnemonic
* @property {string[]} operands
*/
/** disassemble instruction
* @param {number} instruction
* @return {Parts}
*/
disassemble(instruction) {
let op = (instruction >> 13) & 7;
let mode = (instruction >> 10) & 7;
let bus = (instruction >> 8) & 3;
let d = (instruction >> 0) & 0xff;
switch (op) {
case 0:
return this._decodeAlu(mode, bus, d, 'ld');
case 1:
return this._decodeAlu(mode, bus, d, 'anda');
case 2:
return this._decodeAlu(mode, bus, d, 'ora');
case 3:
return this._decodeAlu(mode, bus, d, 'xora');
case 4:
return this._decodeAlu(mode, bus, d, 'adda');
case 5:
return this._decodeAlu(mode, bus, d, 'suba');
case 6:
return this._decodeStore(mode, bus, d);
case 7:
return this._decodeBranch(mode, bus, d);
}
}
/** decode a ram address
* @param {number} mode
* @param {number} d
* @return {string}
*/
_decodeAddr(mode, d) {
switch (mode) {
case 0:
case 4:
case 5:
case 6:
return '$' + toHex(d, 2);
case 1:
return 'x';
case 2:
return 'y,' + '$' + toHex(d, 2);
case 3:
return 'y,x';
case 7:
return 'y,x++';
}
}
/** decode an alu op
* @param {number} mode
* @param {number} bus
* @param {number} d
* @param {number} mnemonic
* @return {Parts}
*/
_decodeAlu(mode, bus, d, mnemonic) {
let operands = [];
switch (bus) {
case 0:
operands.push('$' + toHex(d, 2));
break;
case 1:
operands.push('[' + this._decodeAddr(mode, d) + ']');
break;
case 2:
operands.push('ac');
break;
case 3:
operands.push('in');
break;
}
switch (mode) {
case 4:
operands.push('x');
break;
case 5:
operands.push('y');
break;
case 6:
case 7:
operands.push('out');
break;
}
return {
mnemonic: mnemonic,
operands: operands,
};
}
/** decode a store op
* @param {number} mode
* @param {number} bus
* @param {number} d
* @return {Parts}
*/
_decodeStore(mode, bus, d) {
let operands = [];
switch (bus) {
case 0:
operands.push('$' + toHex(d, 2));
break;
case 1:
operands.push('$??');
break;
case 3:
operands.push('in');
break;
}
operands.push('[' + this._decodeAddr(mode, d) + ']');
switch (mode) {
case 4:
operands.push('x');
break;
case 5:
operands.push('y');
break;
}
return {
mnemonic: 'st',
operands: operands,
};
}
/** decode a branch op
* @param {number} mode
* @param {number} bus
* @param {number} d
* @return {Parts}
*/
_decodeBranch(mode, bus, d) {
let operands = [];
let mnemonic;
switch (mode) {
case 0:
mnemonic = 'jmp';
operands.push('y');
break;
case 1:
mnemonic = 'bgt';
break;
case 2:
mnemonic = 'bge';
break;
case 3:
mnemonic = 'bne';
break;
case 4:
mnemonic = 'beq';
break;
case 5:
mnemonic = 'blt';
break;
case 6:
mnemonic = 'ble';
break;
case 7:
mnemonic = 'bra';
break;
}
switch (bus) {
case 0:
operands.push('$' + toHex(d, 2));
break;
case 1:
operands.push('[$' + toHex(d, 2) + ']');
break;
case 2:
operands.push('ac');
break;
case 3:
operands.push('in');
break;
}
return {
mnemonic: mnemonic,
operands: operands,
};
}
}
+155
View File
@@ -0,0 +1,155 @@
export const BUTTON_A = 0x80;
export const BUTTON_B = 0x40;
export const BUTTON_SELECT = 0x20;
export const BUTTON_START = 0x10;
export const BUTTON_UP = 0x08;
export const BUTTON_DOWN = 0x04;
export const BUTTON_LEFT = 0x02;
export const BUTTON_RIGHT = 0x01;
/** map from controller button name to inReg bit */
const buttonMap = {
a: BUTTON_A,
b: BUTTON_B,
select: BUTTON_SELECT,
start: BUTTON_START,
up: BUTTON_UP,
down: BUTTON_DOWN,
left: BUTTON_LEFT,
right: BUTTON_RIGHT,
};
const axisThreshold = 0.5;
/** map from standard gamepad button index to inReg bit */
const gamepadButtonMap = {
0: buttonMap.a,
1: buttonMap.b,
6: buttonMap.b,
7: buttonMap.a,
8: buttonMap.select,
9: buttonMap.start,
12: buttonMap.up,
13: buttonMap.down,
14: buttonMap.left,
15: buttonMap.right,
};
/** map from standard gamepad axis index to negative and positive inReg bits */
const gamepadAxisMap = {
0: [buttonMap.left, buttonMap.right],
1: [buttonMap.up, buttonMap.down],
};
/** Gamepad device */
export class Gamepad {
/** Create a Gamepad
* @param {Gigatron} cpu - The cpu to control
* @param {Object.<string,string[]>} keys - Map from controller button
* name to list of keys
*/
constructor(cpu, keys) {
this.cpu = cpu;
this.enabled = false;
this.pressed = 0;
this.keyMap = {};
/* build map from keyboard key to controller button name */
for (let button of Object.keys(keys)) {
for (let key of keys[button]) {
this.keyMap[key] = buttonMap[button];
}
}
/* build map of ASCII codes that the Gigatron understands as well */
this.asciiMap = {
'Tab': 9,
'Enter': 10,
'Escape': 27,
'Esc': 27,
'Delete': 127,
'Backspace': 127,
};
for (let ascii=32; ascii<127; ascii++) {
this.asciiMap[String.fromCharCode(ascii)] = ascii;
}
for (let fnKey=1; fnKey<=12; fnKey++) {
this.asciiMap['F' + fnKey] = 0xc0 + fnKey;
}
}
/** start handling key events */
start() {
$(document)
.on('keydown', (event) => {
let bit = this.keyMap[event.key];
if (bit) {
this.pressed |= bit;
event.preventDefault();
} else {
let ascii = this.asciiMap[event.key];
if (ascii) {
if (event.ctrlKey) {
// Control codes (e.g. Ctrl-C for ETX or BREAK)
if (ascii == 63 /*'?'*/) ascii = 127;
else if (ascii == 32 /*' '*/) ascii = 0;
else ascii &= 31;
}
this.pressed = ascii ^ 0xff; /// will be inverted again in tick()
event.preventDefault();
}
}
})
.on('keyup', (event) => {
let bit = this.keyMap[event.key];
if (bit) {
this.pressed &= ~bit;
} else {
this.pressed = 0;
}
event.preventDefault();
});
this.enabled = true;
}
/** stop handling key events */
stop() {
$(document).off('keydown keyup');
this.enabled = false;
}
/** check gamepads */
tick() {
let pressed = this.pressed;
if (navigator.getGamepads) {
let gamepads = navigator.getGamepads();
for (let gamepad of gamepads) {
if (gamepad) {
// check the axes
for (let axisIndex of Object.keys(gamepadAxisMap)) {
let axis = gamepad.axes[axisIndex];
let bits = gamepadAxisMap[axisIndex];
if (axis < -axisThreshold) {
pressed |= bits[0];
} else if (axis > axisThreshold) {
pressed |= bits[1];
}
}
// check the buttons
for (let buttonIndex of Object.keys(gamepadButtonMap)) {
let bit = gamepadButtonMap[buttonIndex];
if (gamepad.buttons[buttonIndex].pressed) {
pressed |= bit;
}
}
}
}
}
if (this.enabled) {
this.cpu.inReg = pressed ^ 0xff; // active low
}
}
}
+263
View File
@@ -0,0 +1,263 @@
/**
* @return {Uint8} a random Uint8
* */
function randomUint8() {
return Math.floor(Math.random() * 256);
}
/** Gigatron processor */
export class Gigatron {
/** Create a Gigatron
* @param {Object} options
*/
constructor(options) {
this.hz = options.hz || 6250000;
this.rom = new Uint16Array(1 << (options.romAddressWidth || 16));
this.romMask = this.rom.length - 1;
this.ram = new Uint8Array(1 << (options.ramAddressWidth || 15));
this.ramMask = this.ram.length - 1;
this.reset();
// randomize ram
for (let i = 0; i < this.ram.length; i++) {
this.ram[i] = randomUint8();
}
}
/** reset registers to power-on state */
reset() {
this.pc = 0;
this.nextpc = (this.pc + 1) & this.romMask;
this.ac = 0;
this.x = 0;
this.y = 0;
this.out = 0;
this.outx = 0;
this.inReg = 0xff; // active low!
}
/** advance simulation by one tick */
tick() {
let pc = this.pc;
this.pc = this.nextpc;
this.nextpc = (this.pc + 1) & this.romMask;
let ir = this.rom[pc];
let op = (ir >> 13) & 0x0007;
let mode = (ir >> 10) & 0x0007;
let bus = (ir >> 8) & 0x0003;
let d = (ir >> 0) & 0x00ff;
switch (op) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
this.aluOp(op, mode, bus, d);
break;
case 6:
this.storeOp(mode, bus, d);
break;
case 7:
this.branchOp(mode, bus, d);
break;
}
}
/** perform an alu op
* @param {number} op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
aluOp(op, mode, bus, d) {
let b;
switch (bus) {
case 0:
b = d;
break;
case 1:
let addr = this.addr(mode, d) & this.ramMask;
b = this.ram[addr];
break;
case 2:
b = this.ac;
break;
case 3:
b = this.inReg;
break;
}
switch (op) {
case 1:
b = this.ac & b;
break;
case 2:
b = this.ac | b;
break;
case 3:
b = this.ac ^ b;
break;
case 4:
b = (this.ac + b) & 0xff;
break;
case 5:
b = (this.ac - b) & 0xff;
break;
}
switch (mode) {
case 0:
case 1:
case 2:
case 3:
this.ac = b;
break;
case 4:
this.x = b;
break;
case 5:
this.y = b;
break;
case 6:
case 7:
let rising = ~this.out & b;
this.out = b;
// rising edge of out[6] registers outx from ac
if (rising & 0x40) {
this.outx = this.ac;
}
break;
}
}
/** perform a store op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
storeOp(mode, bus, d) {
let b;
switch (bus) {
case 0:
b = d;
break;
case 1:
b = 0;
console.error('UNDEFINED BEHAVIOR!');
break;
case 2:
b = this.ac;
break;
case 3:
b = this.inReg;
break;
}
let addr = this.addr(mode, d) & this.ramMask;
this.ram[addr] = b;
switch (mode) {
case 4: // XXX not clear whether x++ mode takes priority
this.x = b;
break;
case 5:
this.y = b;
break;
}
}
/** perform a branch op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
branchOp(mode, bus, d) {
const ZERO = 0x80;
let c;
let ac = this.ac ^ ZERO;
let base = this.pc & 0xff00;
switch (mode) {
case 0: // jmp
c = true;
base = this.y << 8;
break;
case 1: // bgt
c = ac > ZERO;
break;
case 2: // blt
c = ac < ZERO;
break;
case 3: // bne
c = ac != ZERO;
break;
case 4: // beq
c = ac == ZERO;
break;
case 5: // bge
c = ac >= ZERO;
break;
case 6: // ble
c = ac <= ZERO;
break;
case 7: // bra
c = true;
break;
}
if (c) {
let b = this.offset(bus, d);
this.nextpc = base | b;
}
}
/** calculate a ram address
* @param {number} mode
* @param {number} d
* @return {number} the address
*/
addr(mode, d) {
switch (mode) {
case 0:
case 4:
case 5:
case 6:
return d;
case 1:
return this.x;
case 2:
return (this.y << 8) | d;
case 3:
return (this.y << 8) | this.x;
case 7:
let addr = (this.y << 8) | this.x;
this.x = (this.x + 1) & 0xff;
return addr;
}
}
/** calculate a branch page offset
* @param {number} bus
* @param {number} d
* @return {number} page offset
*/
offset(bus, d) {
switch (bus) {
case 0:
return d;
case 1:
// RAM always has at least 1 page, so no need to mask address
return this.ram[d];
case 2:
return this.ac;
case 3:
return this.inReg;
}
}
}
+251
View File
@@ -0,0 +1,251 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=640, initial-scale=0.5">
<title>Gigatron</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.1.0/slate/bootstrap.min.css" integrity="sha384-A0hm/Pn0Gvk8w7szlEuTOZrIyQCCBNXQF9ccseoCI36nWRfMEAapo5UJ56zLPvPw" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css" integrity="sha256-BJ/G+e+y7bQdrYkS2RBTyNfBHpA9IuGaPmf9htub5MQ=" crossorigin="anonymous" />
<script type="module" src="./main.js"></script>
<style>
kbd {
background-color: black;
}
#vga-canvas {
background-color: black;
}
.gamepad-btn.pressed {
fill: #00f;
fill-opacity: 0.5;
}
.gamepad-btn:hover {
stroke: gray;
stroke-width: 5;
}
.led.led-on {
--led-lamp-fill: url(#led-lamp-on);
--led-hilight-fill: url(#led-hilight-on);
}
.led.led-off {
--led-lamp-fill: url(#led-lamp-off);
--led-hilight-fill: url(#led-hilight-off);
}
</style>
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col">
<div class="mx-auto" style="width:640px;">
<!-- LOGO -->
<!--
<a href="https://gigatron.io">
<img src="https://gigatron.io/wp-content/uploads/2018/02/cropped-logo2.png" width="350" height="70">
</a>
<hr>
-->
<!-- BLINKENLIGHTS -->
<svg xmlns="http://www.w3.org/2000/svg" xlink:xmlns="http://www.w3.org/1999/xlink" width="80" height="24">
<defs>
<linearGradient id="led-lamp-on" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#e00"/>
<stop offset="100%" stop-color="#e22"/>
</linearGradient>
<linearGradient id="led-lamp-off" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#800"/>
<stop offset="100%" stop-color="#822"/>
</linearGradient>
<linearGradient id="led-hilight-on" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#e88"/>
<stop offset="100%" stop-color="#e00"/>
</linearGradient>
<linearGradient id="led-hilight-off" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#888"/>
<stop offset="100%" stop-color="#800"/>
</linearGradient>
<g id="led">
<circle cx="0" cy="0" r="8" fill="var(--led-lamp-fill)"/>
<ellipse cx="0" cy="-3.25" rx="5" ry="4" fill="var(--led-hilight-fill)"/>
</g>
</defs>
<use class="led led-0" xlink:href="#led" x="10" y="12"/>
<use class="led led-1" xlink:href="#led" x="30" y="12"/>
<use class="led led-2" xlink:href="#led" x="50" y="12"/>
<use class="led led-3" xlink:href="#led" x="70" y="12"/>
</svg>
<!-- VGA -->
<canvas id="vga-canvas" class="border border-white rounded p-1" width="640" height="480"></canvas>
<hr>
<div class="row">
<div>
<!-- GAMEPAD -->
<svg class="gamepad" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 630 250" width="400" height="150">
<defs>
<radialGradient id="button-gradient" fx="0.8" fy="0.8">
<stop offset="5%" stop-color="gray"/>
<stop offset="100%" stop-color="black"/>
</radialGradient>
</defs>
<g>
<rect x="0" y="0" width="630" height="250" rx="15" ry="15" stroke="#802020" stroke-width="5" fill="#82332f"/>
<path d="m 15,30 a 15,15 0 0 1 15,-15 h 180 a 15,15 0 0 1 15,15 v 60 a 15,15 0 0 0 15,15 h 360 a 15,15 0 0 1 15,15 v 100 a 15,15 0 0 1 -15,15 h -570 a 15,15 0 0 1 -15,-15 z" stroke="#f0d0d0" fill="#f7f1db"/>
<line x1="15" y1="200" x2="615" y2="200" stroke-width="4" stroke="black"/>
<line x1="15" y1="208" x2="615" y2="208" stroke-width="4" stroke="black"/>
</g>
<g transform="translate(102,150)">
<!-- <rect id="dpad" x="-80" y="-80" width="160" height="160" fill="none"/> -->
<path d="m-24,-68 a4,4 0 0,1 4,-4 h40 a4,4 0 0,1 4,4 v40 a4,4 0 0,0 4,4 h40 a4,4 0 0,1 4,4 v40 a4,4 0 0,1 -4,4 h-40 a4,4 0 0,0 -4,4 v40 a 4,4 0 0,1 -4,4 h-40 a4,4 0 0,1 -4,-4 v-40 a4,4 0 0,0 -4,-4 h-40 a4,4 0 0,1 -4,-4 v-40 a4,4 0 0,1 4,-4 h40 a4,4 0 0,0 4,-4 z" stroke="#82332f" stroke-width="5" fill="black"/>
<circle cx="0" cy="0" r="10" fill="url(#button-gradient)"/>
<g transform="translate(-48,0) rotate(0)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-left" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(48,0) rotate(180)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-right" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(0,-48) rotate(90)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-up" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(0,48) rotate(270)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-down" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
</g>
<g transform="translate(300,190)">
<rect x="-100" y="-30" width="200" height="60" rx="30" ry="30" stroke="#82332f" stroke-width="8" fill="#954540"/>
<g transform="translate(-45)">
<text x="0" y="-40" font-family="sans-serif" font-size="16" text-anchor="middle" fill="black">SELECT</text>
<rect x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill="#222"/>
<rect class="gamepad-btn gamepad-btn-select" x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill-opacity="0"/>
</g>
<g transform="translate(45)">
<text x="0" y="-40" font-family="sans-serif" font-size="16" text-anchor="middle" fill="black">START</text>
<rect x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill="#222"/>
<rect class="gamepad-btn gamepad-btn-start" x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill-opacity="0"/>
</g>
</g>
<g transform="translate(510,200)">
<g transform="translate(-50)">
<circle cx="0" cy="0" r="15" fill="black"/>
<text x="0" y="6" font-family="sans-serif" font-size="18" font-weight="bold" text-anchor="middle" fill="#f7f1db">A</text>
</g>
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle class="gamepad-btn gamepad-btn-a" cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(450,135)">
<g transform="translate(-50)">
<circle cx="0" cy="0" r="15" fill="black"/>
<text x="0" y="6" font-family="sans-serif" font-size="18" font-weight="bold" text-anchor="middle" fill="#f7f1db">B</text>
</g>
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle class="gamepad-btn gamepad-btn-b" cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(570,135)">
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(510,70)">
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
</svg>
</div>
<div class="col">
<!-- VOLUME -->
<div class="form-row">
<div class="col-sm-10">
<input id="volume-slider" type="range" class="custom-range"> Volume <label for="volume-slider"></label>
</div>
<div class="col">
<span id="unmute" class="btn btn-sm btn-danger oi oi-volume-off d-none" style="width:30px;" data-toggle="tooltip" title="Unmute"></span>
<span id="mute" class="btn btn-sm btn-success oi oi-volume-high" style="width:30px;" data-toggle="tooltip" title="Mute"></span>
</div>
</div>
<p>
<!-- FILE LOADER -->
<form>
<div class="form-group">
<div class="custom-file">
<input id="load-file-input" type="file" class="form-control custom-file-input" accept=".gt1,.gt1x">
<label class="custom-file-label" for="load-file-input">Load GT1 file</label>
</div>
</div>
</form>
</div>
</div>
<hr>
<!-- KEYMAP -->
Keyboard shortcuts:
<p>
<dl class="row">
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[A] button</span></dt>
<dd class="col-sm-4"><kbd>Delete/End key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[B] button</span></dt>
<dd class="col-sm-4"><kbd>Insert/Home key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[Select] button</span></dt>
<dd class="col-sm-4"><kbd>PageDown key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[Start] button</span></dt>
<dd class="col-sm-4"><kbd>PageUp key</kbd></dd>
</dl>
</div>
</div>
</div>
</div>
<div id="error-modal" class="modal fade" role="alert">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4>Error</h4>
<button type="button" class="close" data-dismiss="modal"><span class="oi oi-x"></span></button>
</div>
<div id="error-modal-body" class="modal-body">
</div>
</div>
</div>
</div>
</body>
</html>
+334
View File
@@ -0,0 +1,334 @@
import {
HSYNC,
VSYNC,
} from './vga.js';
import {
BUTTON_DOWN,
BUTTON_A,
} from './gamepad.js';
const {
Observable,
Subject,
concat,
defer,
range,
} = rxjs;
const {
concatMap,
concatAll,
finalize,
} = rxjs.operators;
const MAX_PAYLOAD_SIZE = 60;
const START_OF_FRAME = 'L'.charCodeAt(0);
const INIT_CHECKSUM = 'g'.charCodeAt(0);
/** Repeat an Observable count times
* @param {number} count
* @param {Observable} observable
* @return {Observable}
*/
function replicate(count, observable) {
// return concat(...new Array(count).fill(observable));
let go = (observer) => {
if (count-- > 0) {
observable.subscribe({
next: (value) => observer.next(value),
error: (err) => observer.error(err),
complete: () => go(observer),
});
} else {
observer.complete();
}
};
return Observable.create(go);
}
/** Loader */
export class Loader {
/** Create a new Loader
* @param {Gigatron} cpu
*/
constructor(cpu) {
this.cpu = cpu;
this.strobes = new Subject();
}
/** load a gt1 file
* @param {File} file
* @return {Observable}
*/
load(file) {
return this.readFile(file).pipe(
concatMap((buffer) => {
let data = new DataView(buffer);
return concat(
this.startLoader(),
defer(() => {
// Send one frame with false checksum to force
// a checksum resync at the receiver
this.checksum = 0;
return this.sendFrame(0xff, 0);
}),
defer(() => {
// Setup checksum properly
this.checksum = INIT_CHECKSUM;
return this.sendSegments(data);
}));
}),
finalize(() => {
// Set the input register back to quiesced state
this.cpu.inReg = 0xff;
}));
}
/** read a file returning a Promise
* @param {File} file
* @return {Observable}
*/
readFile(file) {
return Observable.create((observer) => {
let reader = new FileReader();
reader.onload = (event) => {
observer.next(reader.result);
observer.complete();
};
reader.onerror = (event) => {
observer.error(new Error('FileReader error'));
};
reader.readAsArrayBuffer(file);
});
}
/** start the loader on the gigatron
* @return {Observable}
*/
startLoader() {
return concat(
defer(() => {
this.cpu.reset();
return replicate(100, this.atPosedge(VSYNC));
}),
replicate(5, this.pressButton(BUTTON_DOWN, 1, 1)),
this.pressButton(BUTTON_A, 1, 60)
);
}
/** simulate a button press
* @param {number} bit
* @param {number} downTime
* @param {number} upTime
* @return {Observable}
*/
pressButton(bit, downTime, upTime) {
return concat(
defer(() => {
this.cpu.inReg = bit ^ 0xff;
return replicate(downTime, this.atPosedge(VSYNC));
}),
defer(() => {
this.cpu.inReg = 0xff;
return replicate(upTime, this.atPosedge(VSYNC));
})
);
}
/** load sections from data until busy
* @param {DataView} data
* @return {Observable<Observable<T>>}
*/
sendSegments(data) {
return Observable.create((observer) => {
let offset = 0;
while (offset < data.byteLength) {
if (data.getUint8(offset) == 0 && offset != 0) {
// start address segment
offset += 1;
let startAddr = data.getUint16(offset);
offset += 2;
if (startAddr != 0) {
observer.next(this.sendStartCommand(startAddr));
}
break;
} else {
// data segment
let addr = data.getUint16(offset);
offset += 2;
let size = data.getUint8(offset);
offset += 1;
if (size == 0) {
size = 256;
}
let payload = new DataView(
data.buffer,
data.byteOffset + offset,
size);
observer.next(this.sendDataSegment(addr, payload));
offset += size;
}
}
if (offset > data.byteLength) {
observer.error(new Error('Last segment exceeds file size'));
}
observer.complete();
}).pipe(concatAll());
}
/** send a start command
* @param {number} addr
* @return {Observable}
*/
sendStartCommand(addr) {
return this.sendFrame(START_OF_FRAME, addr);
}
/** send a data block
* @param {number} addr
* @param {DataView} data
* @return {Observable}
*/
sendDataSegment(addr, data) {
return Observable.create((observer) => {
let buffer = data.buffer;
let size = data.byteLength;
let offset = data.byteOffset;
let bytesInPage = 256 - (addr & 255);
if (size > bytesInPage) {
observer.error(new Error('Segment crosses page boundary'));
} else {
while (size != 0) {
let n = Math.min(size, MAX_PAYLOAD_SIZE);
let payload = new DataView(buffer, offset, n);
observer.next(this.sendFrame(
START_OF_FRAME, addr, payload));
addr += n;
offset += n;
size -= n;
}
observer.complete();
}
}).pipe(concatAll());
}
/** send the payload frame
* @param {number} firstByte
* @param {number} addr
* @param {DataView} payload
* @return {Observable}
*/
sendFrame(firstByte, addr, payload) {
return concat(
this.atNegedge(VSYNC),
// account for 2 cycles delay in 74HCT595 and ?
this.atPosedge(HSYNC),
this.atPosedge(HSYNC),
this.sendDataBits(firstByte, 8),
defer(() => {
this.checksum = (this.checksum + (firstByte << 6)) & 0xff;
return this.sendDataBits(payload ? payload.byteLength : 0, 6);
}),
this.sendDataBits(addr & 0xff, 8),
this.sendDataBits(addr >> 8, 8),
this.sendDataBytes(payload),
defer(() => {
this.checksum = (-this.checksum) & 0xff;
return this.sendBits(this.checksum, 8);
}));
}
/** send bytes from payload
* @param {Uint8Array} payload
* @return {Observable}
*/
sendDataBytes(payload) {
return range(0, MAX_PAYLOAD_SIZE).pipe(
concatMap((offset) => {
let byte = (payload && offset < payload.byteLength) ?
payload.getUint8(offset) : 0;
return this.sendDataBits(byte, 8);
}));
}
/** send bits and add to checksum
* @param {number} value - byte containing bits to send (msb first)
* @param {number} n - number of bits to send
* @return {Observable}
*/
sendDataBits(value, n) {
return defer(() => {
this.checksum = (this.checksum + value) & 0xff;
return this.sendBits(value, n);
});
}
/** shift one bit into inReg
* @param {number} bit
*/
shiftBit(bit) {
this.cpu.inReg = ((this.cpu.inReg << 1) & 0xff) | (bit ? 1 : 0);
}
/** send bits
* @param {number} value - byte containing bits to send (msb first)
* @param {number} n - number of bits to send
* @return {Observable}
*/
sendBits(value, n) {
return range(0, n).pipe(
concatMap((i) => {
this.shiftBit(value & (1 << (n - i - 1)));
return this.atPosedge(HSYNC);
}));
}
/** wait for negedge of signal
* @param {number} mask
* @return {Observable}
*/
atNegedge(mask) {
return Observable.create((observer) => {
let prev = this.cpu.out;
let subscription = this.strobes.subscribe((curr) => {
if (prev & ~curr & mask) {
observer.complete();
subscription.unsubscribe();
} else {
prev = curr;
}
});
});
}
/** wait for posedge of signal
* @param {number} mask
* @return {Observable}
*/
atPosedge(mask) {
return Observable.create((observer) => {
let prev = this.cpu.out;
let subscription = this.strobes.subscribe((curr) => {
if (~prev & curr & mask) {
observer.complete();
subscription.unsubscribe();
} else {
prev = curr;
}
});
});
}
/** advance one tick */
tick() {
if ((this.out ^ this.cpu.out) & (HSYNC | VSYNC)) {
this.out = this.cpu.out;
this.strobes.next(this.out);
}
}
}
+320
View File
@@ -0,0 +1,320 @@
import {
Vga,
} from './vga.js';
import {
BlinkenLights,
} from './blinkenlights.js';
import {
Gigatron,
} from './gigatron.js';
import {
Gamepad,
} from './gamepad.js';
import {
Audio,
} from './audio.js';
import {
Loader,
} from './loader.js';
const {
finalize,
} = rxjs.operators;
const HZ = 6250000;
const romUrl = 'gigatron.rom';
$(function() {
$('[data-toggle="tooltip"]').tooltip();
let muteButton = $('#mute');
let unmuteButton = $('#unmute');
let volumeSlider = $('#volume-slider');
let vgaCanvas = $('#vga-canvas');
let loadFileInput = $('#load-file-input');
/** Trigger a keydown/keyup event in response to a mousedown/mouseup event
* @param {JQuery} $button
* @param {string} key
*/
function bindKeyToButton($button, key) {
$button
.on('mousedown', (event) => {
event.preventDefault();
document.dispatchEvent(new KeyboardEvent('keydown', {
'key': key,
}));
$button.addClass('pressed');
})
.on('mouseenter', (event) => {
event.preventDefault();
if (event.originalEvent.buttons & 1) {
document.dispatchEvent(new KeyboardEvent('keydown', {
'key': key,
}));
$button.addClass('pressed');
}
})
.on('mouseup mouseleave', (event) => {
event.preventDefault();
document.dispatchEvent(new KeyboardEvent('keyup', {
'key': key,
}));
$button.removeClass('pressed');
});
}
bindKeyToButton($('.gamepad-btn-a'), 'Delete');
bindKeyToButton($('.gamepad-btn-b'), 'Insert');
bindKeyToButton($('.gamepad-btn-start'), 'PageUp');
bindKeyToButton($('.gamepad-btn-select'), 'PageDown');
bindKeyToButton($('.gamepad-btn-up'), 'ArrowUp');
bindKeyToButton($('.gamepad-btn-down'), 'ArrowDown');
bindKeyToButton($('.gamepad-btn-left'), 'ArrowLeft');
bindKeyToButton($('.gamepad-btn-right'), 'ArrowRight');
// jQuery targets of current touches indexed by touch identifier
let $touchTargets = {};
// track touches within the fc30 and map them to mouse events
$('.gamepad')
.on('touchstart', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $currTarget = $(document.elementFromPoint(
touch.clientX, touch.clientY))
.filter('.gamepad-btn');
$touchTargets[touch.identifier] = $currTarget;
$currTarget.trigger('mousedown');
if ($currTarget.length > 0 && navigator.vibrate) {
navigator.vibrate(20);
}
}
})
.on('touchmove', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $prevTarget = $touchTargets[touch.identifier];
let $currTarget = $(document.elementFromPoint(
touch.clientX, touch.clientY))
.filter('.gamepad-btn');
if ($prevTarget.get(0) != $currTarget.get(0)) {
$prevTarget.trigger('mouseup');
$touchTargets[touch.identifier] = $currTarget;
$currTarget.trigger('mousedown');
if ($currTarget.length > 0 && navigator.vibrate) {
navigator.vibrate(20);
}
}
}
})
.on('touchend touchcancel', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $prevTarget = $touchTargets[touch.identifier];
$prevTarget.trigger('mouseup');
delete $touchTargets[touch.identifier];
}
});
/** display the error modal with the given message
* @param {JQuery} body
*/
function showError(body) {
$('#error-modal-body')
.empty()
.append(body);
$('#error-modal').modal();
}
let cpu = new Gigatron({
hz: HZ,
romAddressWidth: 16,
ramAddressWidth: 15,
});
let vga = new Vga(vgaCanvas.get(0), cpu, {
horizontal: {
frontPorch: 16,
pulse: 96,
backPorch: 48,
visible: 640,
},
vertical: {
frontPorch: 6,
pulse: 8,
backPorch: 27,
visible: 480,
},
});
let blinkenLights = new BlinkenLights(cpu);
let audio = new Audio(cpu);
let gamepad = new Gamepad(cpu, {
up: ['ArrowUp'],
down: ['ArrowDown'],
left: ['ArrowLeft'],
right: ['ArrowRight'],
select: ['PageDown'],
start: ['PageUp'],
a: ['Delete', 'Backspace', 'End'],
b: ['Insert', 'Home'],
});
let loader = new Loader(cpu);
muteButton.click(function() {
audio.mute = true;
$([muteButton, unmuteButton]).toggleClass('d-none');
});
unmuteButton.click(function() {
audio.mute = false;
$([muteButton, unmuteButton]).toggleClass('d-none');
});
volumeSlider.val(100 * audio.volume);
volumeSlider.on('input', function(event) {
let target = event.target;
target.labels[0].textContent = target.value + '%';
audio.volume = target.value / 100;
});
volumeSlider.trigger('input');
let timer;
/** load a GT1 file
* @param {File} file
*/
function loadGt1(file) {
gamepad.stop();
loader.load(file)
.pipe(finalize(() => {
gamepad.start();
}))
.subscribe({
error: (error) => showError($(`\
<p>\
Could not load GT1 from <code>${file.name}</code>\
</p>\
<hr>\
<p class="alert alert-danger">\
<span class="oi oi-warning"></span> ${error.message}\
</p>`)),
});
}
loadFileInput
.on('click', (event) => {
loadFileInput.closest('form').get(0).reset();
})
.on('change', (event) => {
let target = event.target;
if (target.files.length != 0) {
let file = target.files[0];
loadGt1(file);
}
});
$(document)
.on('dragenter', (event) => {
event.preventDefault();
event.stopPropagation();
let dataTransfer = event.originalEvent.dataTransfer;
dataTransfer.dropEffect = 'link';
})
.on('dragover', (event) => {
event.preventDefault();
event.stopPropagation();
})
.on('drop', (event) => {
let dataTransfer = event.originalEvent.dataTransfer;
if (dataTransfer) {
let files = dataTransfer.files;
if (files.length != 0) {
event.preventDefault();
event.stopPropagation();
loadGt1(files[0]);
}
}
});
/** start the simulation loop */
function startRunLoop() {
gamepad.start();
timer = setInterval(() => {
/* advance the simulation until the audio queue is full,
* or 10ms of simulated time has passed.
*/
let cycles = cpu.hz / 100;
audio.drain();
while (cycles-- >= 0 && !audio.full) {
cpu.tick();
vga.tick();
audio.tick();
loader.tick();
}
blinkenLights.tick(); // don't need realtime update
gamepad.tick();
}, audio.duration);
audio.context.resume();
// Chrome suspends the AudioContext on reload
// and doesn't allow it to be resumed unless there
// is user interaction
if (audio.context.state === 'suspended') {
vga.ctx.fillStyle = 'white';
vga.ctx.textAlign = 'center';
vga.ctx.textBaseline = 'middle';
vga.ctx.font = '4em sans-serif';
vga.ctx.fillText('Click to start', 320, 240);
vgaCanvas.on('click', (event) => {
audio.context.resume();
vgaCanvas.off('click');
});
}
}
/** stop the simulation loop */
function stopRunLoop() { // eslint-disable-line
clearTimeout(timer);
gamepad.stop();
}
/** load the ROM image
* @param {string} url
*/
function loadRom(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
req.onload = (event) => {
if (req.status != 200) {
showError($(`\
<p>\
Could not load ROM from <code>${url}</code>\
</p>\
<hr>\
<p class="alert alert-danger">\
<span class="oi oi-warning"></span> ${req.statusText}\
</p>`));
} else {
let dataView = new DataView(req.response);
let wordCount = dataView.byteLength >> 1;
// convert to host endianess
for (let wordIndex = 0; wordIndex < wordCount; wordIndex++) {
cpu.rom[wordIndex] = dataView.getUint16(2 * wordIndex);
}
startRunLoop();
}
};
req.send(null);
}
loadRom(romUrl);
});
+56
View File
@@ -0,0 +1,56 @@
import {
toHex,
} from './utils.js';
/** determine if a character code is printable
* @param {number} code - Character code to test
* @return {boolean}
*/
function isprint(code) {
return code >= 0x20 && code < 0x7f;
}
/** A view of RAM */
export class RamView {
/** Create a new RamView
* @param {HTMLTextAreaElement} textarea
* @param {Uint8Array} memory
*/
constructor(textarea, memory) {
this.textarea = textarea;
this.memory = memory;
this.address = 0;
this.bytesPerRow = 16;
this.render();
}
/** fill the textarea with dump of ram */
render() {
let rows = [];
let address = this.address;
let memory = this.memory;
// it seems fast enough to just dump the entire contents
// of memory into the textarea!!
while (address < memory.length) {
let cols = [];
let chars = [];
cols.push(' ' + toHex(address, 4) + ':');
for (let col = 0; col < this.bytesPerRow; col++) {
if (address < memory.length) {
let char = String.fromCharCode(memory[address]);
cols.push(' ' + toHex(memory[address], 2));
chars.push(isprint(char.charCodeAt(0)) ? char : '.');
address++;
} else {
cols.push(' ');
}
}
cols.push(' |');
cols = cols.concat(chars);
cols.push('|');
rows.push(cols.join(''));
}
this.textarea.value = rows.join('\n');
}
}
+50
View File
@@ -0,0 +1,50 @@
import {
rpad,
toHex,
} from './utils.js';
/** A view of ROM */
export class RomView {
/** Create a new RomView
* @param {HTMLDivElement} view
* @param {Uint16Array} rom
*/
constructor(view, rom) {
this.view = view;
this.rom = rom;
this.disassembler = new Disassembler();
this.scroller = new Scroller(view, {
createRow: (index) => this._createRow(index),
numRows: rom.length,
});
this.hilights = {};
}
/** create a row for the scroller
* @param {number} index
* @return {HTMLElement}
*/
_createRow(index) {
if (index < 0 || index >= this.rom.length) {
return null;
}
let instruction = this.rom[index];
let decode = this.disassembler.disassemble(instruction);
return $('<div>')
.addClass(this.hilights[index] || '')
.html(toHex(index, 4) + '&nbsp;' +
toHex(instruction, 4) + '&nbsp;&nbsp;' +
rpad(decode.mnemonic, 4, '&nbsp;') + '&nbsp;' +
decode.operands.join(','));
}
/** redraw the view at the given start address
* @param {number} startAddress
*/
render(startAddress) {
let top = Math.floor(startAddress - this.scroller.numVisibleRows / 2);
this.scroller.scrollTop(top);
}
}
+67
View File
@@ -0,0 +1,67 @@
/** A class to manage scrolling a dynamically generated list */
export class Scroller {
/** Create a new Scroller
* @param {HTMLElement} container
* @param {{createRow: function, numRows: number}} options
*/
constructor(container, options) {
this.container = container;
this.createRow = options.createRow;
this.numRows = options.numRows;
this.numVisibleRows = 0;
this.scrollIndex = 0;
container.on('wheel', (event) => this.onwheel(event));
}
/** redraw the rows */
render() {
let container = this.container;
container.empty();
let height = container.height();
let index = this.scrollIndex;
this.numVisibleRows = 0;
while (height > 0) {
let row = this.createRow(index);
if (row == null) {
break;
}
container.append(row);
height -= row.height();
index++;
this.numVisibleRows++;
}
if (height < 0) {
this.numVisibleRows--;
}
}
/** set the index of the topmost visible row
* @param {number} index
*/
scrollTop(index) {
this.scrollIndex = Math.max(0,
Math.min(this.numRows - this.numVisibleRows,
index));
this.render();
}
/** respond to wheel events
* @param {Event} event
*/
onwheel(event) {
event.preventDefault();
let magnitude = (event.altKey && event.shiftKey) ? 0x1000 :
event.altKey ? 0x0100 :
event.shiftKey ? 0x0010 :
0x0001;
let delta = Math.sign(event.originalEvent.deltaY) * magnitude;
this.scrollTop(this.scrollIndex + delta);
}
}
+36
View File
@@ -0,0 +1,36 @@
/** right pad a string
* @param {string} value - The value to pad
* @param {number} width - The width to pad to
* @param {string} [pad=' '] - The pad string
* @return {string} The padded string
*/
export function rpad(value, width, pad) {
pad = pad || ' ';
if (value.length < width) {
value = value + pad.repeat(width - value.length);
}
return value;
}
/** left pad a string
* @param {string} value - The value to pad
* @param {number} width - The width to pad to
* @param {string} [pad=' '] - The pad string
* @return {string} The padded string
*/
export function lpad(value, width, pad) {
pad = pad || ' ';
if (value.length < width) {
value = pad.repeat(width - value.length) + value;
}
return value;
}
/** convert a number to a zero-padded hex string
* @param {number} value - The number to convert to hex
* @param {number} width - The width of the result
* @return {string} The padded hex string
*/
export function toHex(value, width) {
return lpad(value.toString(16), width, '0');
}
+83
View File
@@ -0,0 +1,83 @@
export const VSYNC = 0x80;
export const HSYNC = 0x40;
/** Vga */
export class Vga {
/** Create a new Vga
* @param {HTMLCanvasElement} canvas
* @param {Gigatron} cpu
* @param {Object} options
*/
constructor(canvas, cpu, options) {
this.canvas = canvas;
this.canvas.width = options.horizontal.visible;
this.canvas.height = options.vertical.visible;
this.ctx = canvas.getContext('2d', {
alpha: false,
});
this.imageData = this.ctx.getImageData(
0, 0,
canvas.width, canvas.height);
this.pixels = this.imageData.data;
this.cpu = cpu;
this.row = 0;
this.minRow = options.vertical.backPorch + options.vertical.pulse;
this.maxRow = this.minRow + options.vertical.visible;
this.col = 0;
this.minCol = options.horizontal.backPorch + options.horizontal.pulse;
this.maxCol = this.minCol + options.horizontal.visible;
this.pixel = 0;
this.out = 0;
// turn all pixels black with full alpha
for (let i = 0; i < this.pixels.length; i++) {
this.pixels[i] = (i % 4) == 3 ? 255 : 0;
}
this.render();
}
/** draw the pixels into the canvas */
render() {
this.ctx.putImageData(this.imageData, 0, 0);
}
/** advance simulation by one tick */
tick() {
let out = this.cpu.out;
let falling = this.out & ~out;
if (falling & VSYNC) {
this.row = -1; // After 4 more CPU cycles HSYNC increments row to 0
this.pixel = 0;
this.render();
}
if (falling & HSYNC) {
this.col = 0;
this.row++;
}
// Chrome optimizer put this before the falling calculation
// if it follows immediately after it, so it got moved down here
this.out = out;
if ((this.row >= this.minRow && this.row < this.maxRow) &&
(this.col >= this.minCol && this.col < this.maxCol)) {
let pixels = this.pixels;
let pixel = this.pixel;
let r = (out ) & 3;
let g = (out >> 2) & 3;
let b = (out >> 4) & 3;
for (let i = 0; i < 4; i++) {
pixels[pixel++] = 85 * r;
pixels[pixel++] = 85 * g;
pixels[pixel++] = 85 * b;
pixel++;
}
this.pixel = pixel;
}
this.col += 4;
}
}