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

+146
View File
@@ -0,0 +1,146 @@
%!
<< /PageSize [842 595] >> setpagedevice
gsave
% Find out if the device space is rotated compared to user space.
% This turns out to be important!
% We assume if we have a non-zero in index one, then we're rotated by 90 degrees
6 array currentmatrix 1 get 0 ne dup
{ 160 } { 120 } ifelse /YDivisions exch def
{ 120 } { 160 } ifelse /XDivisions exch def
0 0 itransform % Device origin
480 add exch 640 add exch % rough grid size
transform % to device space
round cvi YDivisions idiv
dup /DeviceHPitch exch def
YDivisions mul /DeviceGridHeight exch def
round cvi XDivisions idiv
dup /DeviceVPitch exch def
XDivisions mul /DeviceGridWidth exch def
DeviceGridWidth DeviceGridHeight itransform 0 0 itransform
exch 3 1 roll
sub /UserGridHeight exch def
sub /UserGridWidth exch def
842 UserGridWidth sub 2 div
595 UserGridHeight sub 2 div
2 copy
/UserGridBottomLeftY exch def
/UserGridBottomLeftX exch def
transform
round cvi /DeviceGridBottomLeftY exch def
round cvi /DeviceGridBottomLeftX exch def
[ 1 0 0 1 DeviceGridBottomLeftX DeviceGridBottomLeftY ] setmatrix
0 setlinewidth
% Should return something like [[2Pitch/5 Pitch/5 Pitch/5 Pitch/5] Pitch/5]
% Element 0 (Representing the corners) is made to be bigger, and the other values are made to fit
% I think this will do something broadly sensible for grid pitches > 2 device units
% The intent is something like + - + - + with the corners intersecting the lines coming the other way
% but it will fall back to + + if there's no space for a middle stroke, and will just dash lines otherwise.
/MakeDashPattern {
[ exch abs dup % ([ pitch pitch)
[ exch % Bring line pitch (gap to fill) to top of stack. We'll keep it at the top as we go
dup 5 div ceiling cvi 2 mul % corners - if pitch is =< 2, this will be weird
dup neg % ( [ pitch [ pitch corners -corners )
3 2 roll add % Bring gap to fill to the top, and update ( [ pitch [ corners gap)
% Gap may be =<0
dup 0 gt { % if
% Leave a copy of the gap, in case we aren't able to split it
dup % ( ... corners biggap biggap)
% If gap is bigish we'll definitely want a centre stroke even if it's an even number
% so we reserve up to a third of the gap before dividing by two to get space width.
dup dup 3 div floor cvi sub 2 idiv % (... corners biggap biggap space)
dup 0 le { % if
% If we can't split the gap, use the whole gap as space
pop pop
} { % else
% Make a second copy of the space
dup % ( ... corners biggap biggap space space)
% Bring the gap to the top, and update, the new value is the centre stroke width
dup -2 mul 4 3 roll add % (... corners biggap space space centre)
dup 0 eq { % if
% Failed to split
pop pop pop % (... corners biggap)
} { % else
% Manipulate stack so that the extra gap goes away, and centre is in the right place
exch 4 3 roll % (... corners space centre space biggap)
pop % (... corners space centre space)
} ifelse
} ifelse
} { % else
pop
} ifelse
] %( [ pitch [spacing] )
exch 5 div ceiling cvi ]
} def
/HMinorTickDash DeviceVPitch MakeDashPattern def
/VMinorTickDash DeviceHPitch MakeDashPattern def
% Draw horizontal ticks
1 1 YDivisions 1 sub { % for
dup 8 mod 0 eq { [] 0 } { HMinorTickDash 0 get HMinorTickDash 1 get } ifelse setdash
DeviceHPitch mul 0 exch moveto
DeviceGridWidth 0 rlineto stroke
} for
% Draw vertical ticks
1 1 XDivisions 1 sub { % for
dup 8 mod 0 eq { [] 0 } { VMinorTickDash 0 get VMinorTickDash 1 get } ifelse setdash
DeviceVPitch mul 0 moveto
0 DeviceGridHeight rlineto stroke
} for
grestore
1 setlinewidth 0 setgray
1 setlinejoin
UserGridBottomLeftX UserGridBottomLeftY translate
0.5 0.5 moveto
0 UserGridHeight 1 add rlineto
UserGridWidth 1 add 0 rlineto
0 -1 UserGridHeight sub rlineto
closepath stroke
/UserPixelHeight UserGridHeight 120 div def
/UserPixelWidth UserGridWidth 160 div def
/Courier findfont
6 scalefont
setfont
0 8 112 {
dup -24 exch % x
UserGridHeight exch 1 add UserPixelHeight mul sub
moveto
8 add ($00xx) dup 3 2 roll
16 2 string cvrs
dup length 3 exch sub exch putinterval
show
} for
-10
0 8 152 {
2 copy UserPixelWidth mul exch moveto
($xx00) dup 3 2 roll
16 2 string cvrs
dup length 5 exch sub exch putinterval
show
} for
pop
showpage
+7
View File
@@ -0,0 +1,7 @@
[flake8]
ignore = E203, E266, E501, W503, E231, E731
# line length is intentionally set to 80 here because black uses Bugbear
# See https://github.com/psf/black/blob/master/README.md#line-length for more details
max-line-length = 80
select = B,C,E,F,W,T4,B9
+7
View File
@@ -0,0 +1,7 @@
/.venv/
/.vscode/
/out/*.rom
/.pytest_cache/
/.hypothesis/
/.pypy-venv/
/.ipynb_checkpoints/
+5
View File
@@ -0,0 +1,5 @@
[settings]
profile=black
line_length=70
sections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,GIGATRON,LOCALFOLDER
known_gigatron=asm,gtemu
@@ -0,0 +1,754 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "7be713cc",
"metadata": {},
"outputs": [],
"source": [
"import benchmark\n",
"from benchmark import Emulator\n",
"from benchmark import _read_word as read_word\n",
"from benchmark import RAM"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "f58fdb10",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "812c9947",
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "4c59a0ce",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"WindowsPath('C:/Users/peter.russell/Documents/Personal/multiply/Contrib/psr/multiply/mandelbrot/Mandelbrot.gcl')"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"benchmark.MY_MANDELBROT"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "74cc8de7",
"metadata": {},
"outputs": [],
"source": [
"my_symbols = benchmark._load(benchmark.MY_MANDELBROT)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "452bbd78",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Boot reached SYS_RESET_88 in 1006781 cycles (0.16108496s)\n",
"Boot reached SYS_Exec_88 (Reset) in 1006825 cycles (0.161092s)\n",
"Boot reached SYS_Exec_88 (Main) in 2037968 cycles (0.32607488s)\n",
"Program was ready to begin exectution after 3752667 cycles (0.60042672s)\n"
]
}
],
"source": [
"cycles = benchmark._run_to_main_start()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "c80561c7",
"metadata": {},
"outputs": [],
"source": [
"cycles += benchmark._run_to_function_entry(my_symbols, 'CalcSet')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a1d3e5bc",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"58"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pen_address = my_symbols['Pen']\n",
"pen_address"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "4585f488",
"metadata": {},
"outputs": [],
"source": [
"def get_current_coordinate():\n",
" \"\"\"Return the current screen coordinate based on the Pen variable\"\"\"\n",
" memory_address = read_word(pen_address, signed=False)\n",
" offset_in_screen_ram = memory_address - 0x800\n",
" page, offset_in_page = divmod(offset_in_screen_ram, 0x100)\n",
" return offset_in_page, page"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "ea8d8c2d",
"metadata": {},
"outputs": [],
"source": [
"RAM[pen_address:pen_address + 2] = 1,9"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "65ad01fc",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(1, 1)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_current_coordinate()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "96ce801d",
"metadata": {},
"outputs": [],
"source": [
"per_pixel_timings = np.zeros((160, 120), dtype='uint32')"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "e76bb8b2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'06ae'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"target_vcpu_instruction = Emulator.vLR\n",
"f\"{target_vcpu_instruction:04x}\""
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "8702c06c",
"metadata": {},
"outputs": [],
"source": [
"import asm\n",
"call_and_a_bit = asm.symbol('CALL') + 1\n",
"Emulator.breakpoints.add(call_and_a_bit)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "053e54a2",
"metadata": {},
"outputs": [],
"source": [
"def in_call_instruction():\n",
" return Emulator.next_instruction == call_and_a_bit\n",
"\n",
"def calling_function_of_interest(function_variable):\n",
" return Emulator.AC == function_variable"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "20a3a0f0",
"metadata": {},
"outputs": [],
"source": [
"calc_pixel = my_symbols['CalcPixel']\n",
"total_time_in_calc_pixel = 0\n",
"count = 0\n",
"cycles += Emulator.run_vcpu_to(target_vcpu_instruction)\n",
"while in_call_instruction():# and count < 120:\n",
" if not calling_function_of_interest(calc_pixel):\n",
" cycles += Emulator.run_vcpu_to(target_vcpu_instruction)\n",
" continue\n",
" cycles += Emulator.step_vcpu() # Complete CALL\n",
" \n",
" # We are now at the start of a call to calc_pixel\n",
" return_point = Emulator.vLR\n",
" coords = get_current_coordinate()\n",
" cost_of_calc_pixel = Emulator.run_vcpu_to(return_point)\n",
" # Ignore breakpoint inside function\n",
" while in_call_instruction():\n",
" cost_of_calc_pixel += Emulator.run_vcpu_to(return_point)\n",
" per_pixel_timings[coords] = cost_of_calc_pixel\n",
" total_time_in_calc_pixel += cost_of_calc_pixel\n",
" cycles += cost_of_calc_pixel\n",
" count += 1\n",
" cycles += Emulator.run_vcpu_to(target_vcpu_instruction)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "0b1e7e7f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb1da0f00>"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1h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gRp7ZGJtriAhlPeE3J5GrfCY+T2iLbG1EGcqFzPAxr/eY+jdETO+yRXa1DU0kOY20eTZhMrQYlvV/eyU5TsY5amJlwnOh7fHxEkl+D0VStGLE+PBfw0YWvPs26tAk/Qv7JMjtjQl3mnc/ibSVlyT3LkeKLCv7sRGJ1b+RIIwJn8EWQZTB7B/YoCTiakNl7j8RJGlbwgnFdeE1neGSvn+hUi2RbjSUsaPPMVSslGqGnUHc6ByGE4aoU9qk5NLDo1VJFK/aTet7TPSod9ZL1Z8JKD/QdMr489Ku2XguY+x8VijV2PK+cgIF5yVi04y2LfufjvmAWiaHKptTdcBNYnYQQSxpx+enLdgpJ6ny3fmrGuGT8l23ecilnVuOnTD8b1KJ2rIjyjR04kA9pr1i9Ssf6ciS4z5kA/h6ZV88cpT1SXS82n4rW0RRBhIM/lbqUPBBjot8mb4PLUurFsL4ZkjUUdJoWy5xO2Zt/7vL+RNeJ5fMPlqmbfkIcSVZ1RlxpoSTVad9s6PucdJYqgppW3q3Ib1xosUE4yWcmKyfvHVTcY1brYSotuIVTzhJQJNm9HhLbByLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(per_pixel_timings.T) # Transpose so that the first index is the x-axis."
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "952145ae",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"total_time_in_calc_pixel: 81.65%\n"
]
}
],
"source": [
"print(f\"total_time_in_calc_pixel: {total_time_in_calc_pixel / cycles * 100:.4}%\")"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "a4b8dfeb",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.colors as colors"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "69528c0b",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28caec2d280>"
]
},
"execution_count": 20,
"metad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cWsJ+8RqCpX5sIrijFm7lpa/SoN12yX5a3lzALlo0207sixDEW74yR3Rw+LGi5E685NEeujpfisOIGeW12yiu3YKvxHkj9jVKBvBQ6AscvYGZym1bme7gdJGqGhYs4Jaqaql6WCygCEleANsAoYIa1KW/uKBNKw6HUFAae+gEkBdC1B6173lVdUnHQq9auaV85yuCW0KdAXI9dqXqVCkvBHnWe6A1FJu9jKqaBivXQdyrbm6pJphKbWaNIKHg1DHCvfAxnQjZ4GiAjFhNKcQsm4aFvvhREEDXZn+fxot9jq3cq2lZHDeqokb1MyHJOB5UUFNvnghOjre1ChKnz9P3z9MtIhBRIduokLVqs+PeCRgZAqB+3GiuKOZRC5T/3SoTXlHQqYMkqroJSYY4X/IsiVnWpOnvwbSK9qz0HU09sqkJCBHUKWsyocW0hihpTWwJrOY5Cv2m5JZybpw/voskfMN5lK+lbc+u8te/73vT/0yUPHv1XoVQUq9KhR6mswFgSL3ewOTaEugCVpcnAyeCrQNCYRIKEBuMgekY1Y0aobLoxlYFLaHc72Brj2ZX1OXc00gdq91DH9jYgDwwee4IYeRQn616JFMzqJOxk23QyNh2GVDuN/BjJ84ZfRGrmy1ggGZbjWVxbJaXlLyMHUqD5VkHP1LVsQaKBSevt1vKgo2oydbLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(per_pixel_timings.T, norm=colors.LogNorm()) "
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "1539f776",
"metadata": {},
"outputs": [],
"source": [
"from gtemu import RAM\n",
"import _gtemu\n",
"\n",
"screen = np.frombuffer(_gtemu.ffi.buffer(RAM), dtype='uint8', offset=0x800).reshape((120, 256))"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "e88da693",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb1369328>"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"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GMpLETJpHj09TuXUn0Wg3heNQ2pUi8OkV7ywiaK7EmFqjcO0riZB4/EaY1EiZ6cJLmvpWE5tto5QbVnf0kD85ir87iWTqhMzeUHxfKSEOjsTZB/NVJmjvHMesOgZmiivHReZzBJHY6QOTYNPUDK94Y441DICF4qRfj0wX8WJDWmIpxc+9KgoUORq5GZfeA8mNlFjdiED7Zi/Fldb001is/WjvGVa4nVYzvmuuZJlq9Q21b5m1zHTs4RXP3+NvmOn58Dndy+h37DC/jncE7VZP/vSEDBpoZhICJHM5APg8DGbR6C2nb+GP9iEoVLZlAxsJQLCGHM4hZH2E7+MNZyOUhk0J4PjSa+KNZRKOJFovi96egUEQOZtGKFfxqTR0vlhB9KaRpQKWCP5xF63ZB15EjWeVHfx9aq4PsdNWYShUtlUQmokt+3AQ6HfzRW36oxThqDfzRrOqWkOBlE4Tnunh9MQCssjq3YN5GWjq+ESI038UbSqO3XRDgDaUJzXfx4yGkgGBejQlUHISUeJm4splNIDxJoGrjjWYJLXTxe3X78HwXbySDWXdAgjPaRyelER5KYidN2mmd0Fg/nZSO5oYwIyadlEZktI92NoDUIDCapZPSsIbi+AGtdzxLu8/ADwgQaTopDWc4RbvfwokIgr0xxmAEzZF0UhrR0SzLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(screen)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "034c9362",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"cycles: 2708024662\n",
"realtime: 433.28s\n",
"realtime: 7:13\n"
]
}
],
"source": [
"print(f\"cycles: {cycles}\")\n",
"print(f\"realtime: {cycles * benchmark.CLOCK_PERIOD:.5}s\")\n",
"mins, secs = divmod(round(cycles * benchmark.CLOCK_PERIOD), 60)\n",
"print(f\"realtime: {mins}:{secs}\")\n",
"my_cycles, my_total_time_in_calc_pixel = cycles, total_time_in_calc_pixel\n",
"my_timings = per_pixel_timings"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "8fa9dc45",
"metadata": {},
"outputs": [],
"source": [
"original_symbols = symbols = benchmark._load(benchmark.ORIGINAL_MANDELBROT)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "67484620",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Boot reached SYS_RESET_88 in 1006781 cycles (0.16108496s)\n",
"Boot reached SYS_Exec_88 (Reset) in 1006825 cycles (0.161092s)\n",
"Boot reached SYS_Exec_88 (Main) in 2037968 cycles (0.32607488s)\n",
"Program was ready to begin exectution after 3961067 cycles (0.63377072s)\n"
]
}
],
"source": [
"cycles = benchmark._run_to_main_start()"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "56492aa2",
"metadata": {},
"outputs": [],
"source": [
"cycles += benchmark._run_to_function_entry(symbols, 'CalcSet')"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "2c796727",
"metadata": {},
"outputs": [],
"source": [
"pen_address = symbols['Pen']\n",
"\n",
"def get_current_coordinate():\n",
" \"\"\"Return the current screen coordinate based on the Pen variable\"\"\"\n",
" memory_address = read_word(pen_address, signed=False)\n",
" offset_in_screen_ram = memory_address - 0x800\n",
" page, offset_in_page = divmod(offset_in_screen_ram, 0x100)\n",
" return offset_in_page, page\n",
"\n",
"call_and_a_bit = asm.symbol('CALL') + 1\n",
"Emulator.breakpoints.add(call_and_a_bit)\n",
"\n",
"per_pixel_timings = original_per_pixel_timings = np.zeros((160, 120), dtype='uint32')\n",
"\n",
"calc_pixel = symbols['CalcPixel']\n",
"total_time_in_calc_pixel = 0\n",
"count = 0\n",
"cycles += Emulator.run_vcpu_to(target_vcpu_instruction)\n",
"while in_call_instruction():# and count < 120:\n",
" if not calling_function_of_interest(calc_pixel):\n",
" cycles += Emulator.run_vcpu_to(target_vcpu_instruction)\n",
" continue\n",
" cycles += Emulator.step_vcpu() # Complete CALL\n",
" \n",
" # We are now at the start of a call to calc_pixel\n",
" return_point = Emulator.vLR\n",
" coords = get_current_coordinate()\n",
" cost_of_calc_pixel = Emulator.run_vcpu_to(return_point)\n",
" # Ignore breakpoint inside function\n",
" while in_call_instruction():\n",
" cost_of_calc_pixel += Emulator.run_vcpu_to(return_point)\n",
" per_pixel_timings[coords] = cost_of_calc_pixel\n",
" total_time_in_calc_pixel += cost_of_calc_pixel\n",
" cycles += cost_of_calc_pixel\n",
" count += 1\n",
" cycles += Emulator.run_vcpu_to(target_vcpu_instruction)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "07cc45af",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"cycles: 7,439,242,573\n",
"realtime: 1,190.28s\n",
"realtime: 19:50\n",
"total_time_in_calc_pixel: 90.24%\n"
]
}
],
"source": [
"print(f\"cycles: {cycles:,}\")\n",
"print(f\"realtime: {cycles * benchmark.CLOCK_PERIOD:,.6}s\")\n",
"mins, secs = divmod(round(cycles * benchmark.CLOCK_PERIOD), 60)\n",
"print(f\"realtime: {mins}:{secs}\")\n",
"print(f\"total_time_in_calc_pixel: {total_time_in_calc_pixel / cycles * 100:.4}%\")"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "2857f063",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb314cbf0>"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1hAAAAO3RFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMGIxLCBodHRwczovL21hdHBsb3RsaWIub3JnLwiMSToAAAAJcEhZcwAACxMAAAsTAQCanBgAAJM+SURBVHic7b13vCxZWe/9fVZVdfeOJ85JM2dyYoYwAzMwgJLDiEgwXVCCChfMihG9vtfrTcpVUTGgGFERUC4ygFwBicoEYGZIk/PMyfnss1N3Va31/lFV3dW1V6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9uCknHiuvl+sIIorPghzoLPtj+c4MHG42iYkGC6gedrCOmj6BhXYTwHbyEV6Ek+eonFEQS9YJLtHIrgulGgJxtpTyMn0COp/d1USJsf0ub7S2vNRVpnss0mLKsGdbLIowjl0YMquhvGV1BWQR3TOou08BxUaxpW26qi9ttoQSr99T/NfqW1uHbZtlkhUUVo2LQrS7+Brme6T2gQX+POdzCew9K2JmIM7qIDsbwxDRfdcDjyxEnam4VN94Y0j0cZPEbFdCFYKTwG0TBFgbII2vT+MjhOsSmefY6zHxNb+6Rd1T6DIE9bHeAY42VXJUIvLfzS5PH0vwRVhGNeoYphBJ1Nm63iA63zsNu+jkoLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(per_pixel_timings.T)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "09ed8c22",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb04b5670>"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1hAAAAO3RFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMGIxLCBodHRwczovL21hdHBsb3RsaWIub3JnLwiMSToAAAAJcEhZcwAACxMAAAsTAQCanBgAAQAASURBVHic7P13uC3ZVR+K/sacFVbY6aTuPqdzS92tnFBC5CCwEVjXgLgYgcHmWY8LxgRhEMafr/18Sfc9G3N5OAhsTDSYa3wNiCSChEABZRqp1VKr1a0Op/ucPufsuEJVzTnuH2OmqlVr7306aTf3zO/b3957rao5Z1XNGnOE3/gNYmZcaVfalXalXWnLm/pMT+BKu9KutCvtqLcrgvJKu9KutCvtgHZFUF5pV9qVdqUd0K4IyivtSrvSrrQD2hVBeaVdaVfalXZAuyIor7Qr7Uq70g5oT4qgJKK/QUR3EdHdRP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2IOe2PK3LRzpzZzLt7QfBQljnz1kF9dvecb9Npbs4UR1kKRnNvIqa4ogDVwXAANA14a1vml2iENBqJoNzZDTCgMC9ncvNkurgJJFhJnjjXgg/aaAUaDeUapjMxs8O1FjC3XgfroDY+wEINByhNWNDstGK0tTlWBHbaAZD4FOcmaj+Line truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(per_pixel_timings.T, norm=colors.LogNorm()) "
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "916934b2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 36342, 52676, 36282, ..., 36282, 45689, 69408],\n",
" [ 64887, 61950, 37950, ..., 58515, 44276, 37094],\n",
" [ 52794, 37150, 45059, ..., 38626, 56319, 37950],\n",
" ...,\n",
" [ 79083, 109721, 99374, ..., 101203, 103278, 101889],\n",
" [112865, 89096, 102853, ..., 97863, 97882, 91509],\n",
" [ 82959, 107653, 90359, ..., 106833, 90513, 104433]], dtype=int64)"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"time_saved_per_pixel = original_per_pixel_timings.astype('int64') - my_timings\n",
"time_saved_per_pixel"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "8f3b91a7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb1ffe2f8>"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1hAAAAO3RFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMGIxLCBodHRwczovL21hdHBsb3RsaWIub3JnLwiMSToAAAAJcEhZcwAACxMAAAsTAQCanBgAAG08SURBVHic7b13tGTZXd/7+Z1Q6ca+nW7n7gma0WhGYTRKCAuUQAKMbBAsgm3Zlq1lY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wUb4V+OvAO0TkMf/zLcCPA+8WkWeBd/n/pyiDYTKwSUScGrdbbScgUdUWhQje6htd7TAKP5hc+S/gnpkmBxub1DSLpco2SwtbVKp2X139n0FurgCynDhx19PqSkMelXlYeYJ8Q0LpOEql1J+T3DXvLFvvrYTueu48sZHhsJO+PEkNpKRllc2qd1CEveNp0IbUXgEoLd2THKyM6WGSXW/+zjXlCqIp9JqD6wjK0hBNIbqL6ArTdHjrwRc4aK6jicsd9aucOH6N3798H89vHaDr8Al3kiiP8dr+xr9p0ncYkiNPUrmg/jS7cpiGJPNIN72YtJZrGWGRJYx5UDD/5CxhvF0R3T+ycHkGY6RxKPvShdvN00bevIMi9t1KZpLh7546xFOrlw+v0jAtXrqyhHK8esRncGK4aJpC010Mw0FnZ7OLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(time_saved_per_pixel.T, norm=colors.TwoSlopeNorm(vcenter=0))"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "5ab0127c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb18eb478>"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1hAAAAO3RFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMGIxLCBodHRwczovL21hdHBsb3RsaWIub3JnLwiMSToAAAAJcEhZcwAACxMAAAsTAQCanBgAAQAASURBVHic7P15tG7bdRcG/uZau/ma853mtq/Ve5IsWXIn28gWXWjKDS5wbHoTUnShhocrwxQBEsDAIMlIGJiEphKqQsoUqYJhCscEAgbTGFw2YGMLyZaNW1nS03vS6293uq/be681648551prf+fce2VsmSu4a4x7zznft5u1115rrtn85m8SM+Nxe9wet8ftcbt/c/+2O/C4PW6P2+P2qLfHgvJxe9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5VHXEwl8r5cgVcr8HKVIvFcV6AYVeNCDsr0DPaiVZlGI2YnyWLE2PHNpnk9oEmwQnxvFIogkfqVJAARxVRtVEvp4tj8D1AHfeF0B3LEGBZ0kj7RoBpWI8LOb0TYRHPIr4YUlPHbmM08dRUAMiYWuXdBgzpqOldLcXkMMy++1JX4LGPjUC0HuD5imOV7mzYGhpimGlG253GdBKjCRPu3HhBr1eiXvfo0cwCoDAxBkQbQ98EqHEdjs7ua2UxKPU7Xxv3eZxKuRONrMmftzlwgPvt8uRLlRYQdxIpgoDrrxZc9tYBe1oartbiLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(time_saved_per_pixel.T, norm=colors.LogNorm())"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "8bba2aed",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x28cb22f2560>"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAUoAAAD7CAYAAAAMyN1hAAAAO3RFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMGIxLCBodHRwczovL21hdHBsb3RsaWIub3JnLwiMSToAAAAJcEhZcwAACxMAAAsTAQCanBgAABh+SURBVHic7d17eFT1ncfx93dmciHcknAJgYBETFG0ViwC4vbylHbX2xa3dV2sa9GypU9rq7a2rrbP09322e3W1q3abbXLFltwWW3LWrW21QVqd9eqKCiK3CPhEq4RA3KRkJl89485dAOEHMhczgz5vJ4nT2bOOZnz4cfkk3OZmWPujoiInFgs6gAiIoVORSkiEkJFKSISQkUpIhJCRSkiEkJFKSISIidFaWaXmtlaM2s0sztysQ4RkXyxbL+O0sziwDrgI0Az8BJwrbuvyuqKRETyJJGDx5wINLr7BgAzewSYBpywKEutzMvpm4MoIiInZx+tb7r7kK7m5aIoRwB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c5REPJbhIHU6RaW6OOUzS0RSkiEiKjLUoz+yLwN4ADK4AbgVrgEWAQsAy43t2z99lcInLK3rlqItveF8PLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(time_saved_per_pixel.T < 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "48db7521",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "PyPy3 (Multiply)",
"language": "python",
"name": "pypy3-multiply"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+133
View File
@@ -0,0 +1,133 @@
# Multiplication Routines
This directory includes two implementations of byte by byte multiplication
in native code. It's pretty fast, but comes at the cost of a very large
(two pages) lookup table.
The algorithm used is [Quarter square multiplication](https://en.wikipedia.org/wiki/Multiplication_algorithm#Quarter_square_multiplication)
with some caveats: multiplying two 8-bit values would require a four page
lookup table, and I couldn't find a way to implement that.
However it was possible to implement a two-page table sufficient for
multiplying 7-bit numbers.
This is then extended by other means.
This code has not been tested on real hardware,
and it uses instructions that do not seem to be used elsewhere
(bne ac and bge ac). gtemu.c and asm.py seem happy with them,
so I do expect them to work.
The purpose of this code is threefold:
* Just for fun. I read about the algorithm and wanted to see how hard it was to implement, and if it turned out to be fast.
* As a demonstration of an approach to native Gigatron programming. I've tried to make the code relatively easy to read, more below.
* As a testbed and demonstration of py-gtemu
## What's here
There are two implementations, and a Mandelbrot demo.
### The proof of concept
The first implementation,
and the one you should read if you want to understand the code is src/multiplication.asm.py.
This is a file that contains nothing but the multiplication routine.
It was where I developed the code.
If loaded on a Gigatron it would do nothing at all,
it is exercised only by the tests in test/test_multiplication.asm.py
If you want to understand how it works,
I suggest reading the commits that affected those files,
rather than reading it all in one go.
It should break the implementation into logical chunks:
first looking up the low-byte of a quarter square,
then looking up the high-byte,
then implementing the full routine for 7-bit numbers,
then extending it to 8-bit numbers.
As the code got bigger the whole file became harder to understand,
but I tried to keep the diffs readable.
### The SYS function
The second implementation is the same thing, but with some optimisations,
and implemented as a SYS function.
This is built in to a modified version of the ROMv5a.asm.py script.
It can be found in sys/ROM.asm.py.
Again, the diffs are probably the best way to view the code,
as there is naturally a lot of unrelated code in there.
The reason that this had to be written in,
and not a seperate .py file,
is that I need code in the page after the shift table.
The major differences between the two versions are that in the SYS function:
* I neglected comments
* I store the lookup table inverted, because
* I do the subtraction step before the addition. This makes things a bit faster
* I do the 7-bit multiplication first instead of last.
This means that the control flow splits but does not merge again,
which is better for SYS functions.
* The cycle counting is done "Marcel style" with each instruction being numbered.
The sys function takes 120 cycles,
or 92 if both bytes are known to be <128,
i.e. they have the top bit clear.
I haven't used a slot to allow for the code moving,
but just started in the middle of the lookup table.
This saves some cycles, and this is just a demo.
The SYS function takes the two bytes in sysArgs0 and sysArgs1,
and returns a 16-bit product in vAC.
Neither parameter is modified,
to make it easy to reuse them on subsequent calls,
but sysArgs2-5 are trampled.
### Mandelbrot
In order to see how performant the SYS function is,
I modified Mandelbrot.gcl to make use of it.
The answer is quite a lot faster than the vCPU shift-and-add implementation,
but not as much as I might have hoped.
In the default graphics mode it completes in under 8 minutes to render the first view,
going by the clock on the screen.
This takes something like 17 minutes using Marcel's code.
I suspect that there is scope for improvement,
either by avoiding calling the SYS function with zero as a parameter,
or rearranging code to minimise stalls.
I'd like to do some profiling to see where time is being spent.
## How to run it
### To run the Mandelbrot demo
Assuming you are in this directory,
you can add ../../../Core to your Python module search path (e.g. set PYTHONPATH) and run
python3 ./sys/ROM.asm.py "Reset=../../../Core/Reset_v5.gcl" "Main=mandelbrot/Mandelbrot.gcl" "Boot=../../../Apps/CardTest/CardBoot.gcl"
(convert slashes as appropriate on your platform)
This should generate a ROM.rom and ROM.lst file, which you can run in your preferred emulator
### To run the tests
As above you need the Core directory on the search path, and you will also need:
* py-gtemu (follow the instructions in Contrib/psr/py-gtemu)
* pytest
* hypothesis
With these available you can just run pytest from this directory
You can see my approach to this
(creating a virtualenv, with a .pth file for Core, and installing dependencies)
in psakefile.ps1.
## Future work
I'd like to do the following
* Do more acurate benchmarking of Mandelbrot
* Move the code for loading Mandelbrot.gcl in the test to py-gtemu
* Do some profiling of MulShift8, and see if it can be sped up
* See if using PyPy helps make any of the above faster
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
import copy
import pathlib
from importlib import reload
from unittest.mock import patch
import gcl0x as gcl
import asm
from gtemu import RAM, Emulator
ROOT = (pathlib.Path(__file__).parent).resolve()
REPO_ROOT = (ROOT / ".." / ".." / "..").resolve()
SCRIPT = ROOT / "sys" / "ROM.asm.py"
RESET = REPO_ROOT / "Core" / "Reset_v5.gcl"
BOOT = REPO_ROOT / "Apps" / "CardTest" / "CardBoot.gcl"
ORIGINAL_MANDELBROT = REPO_ROOT / "Apps" / "Mandelbrot" / "Mandelbrot_v1.gcl"
MY_MANDELBROT = ROOT / "mandelbrot" / "Mandelbrot.gcl"
CLOCK_FREQUENCY = 6.250e06 # Hz
CLOCK_PERIOD = 1 / CLOCK_FREQUENCY
for file in [SCRIPT, RESET, BOOT, ORIGINAL_MANDELBROT, MY_MANDELBROT]:
assert file.exists(), f"File does not exist: {file}"
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": "__main__"}
with SCRIPT.open("rb") as file:
compiled_script = compile(file.read(), SCRIPT, "exec")
script_argv = [str(SCRIPT.name), f"Reset={RESET}", f"Boot={BOOT}"]
def get_symbol_table(gcl_file):
"""Compile and discard gcl, and return the symbol table
Requires the rom script to already have been run in so that the
"""
# Execute the hacked ROM script, to define all of the required variables
reload(asm)
asm.define("Main", 0x0000) # Must be defined to something
with patch("sys.argv", script_argv), patch("asm.writeRomFiles"), patch(
"asm.enableListing"
), patch("asm.disableListing"), patch("asm.print"), patch("gcl0x.print"):
exec(compiled_script, copy.copy(script_globals))
asm.align(1)
asm.zpReset(asm.symbol("userVars"))
program = gcl.Program("Mandelbrot", forRom=False)
program.org(asm.symbol("userCode"))
with gcl_file.open("r", encoding="utf-8") as fp:
for line in fp.readlines():
with patch("gcl0x.print"):
program.line(line)
with patch("gcl0x.print"):
program.end()
asm.end()
return program.vars
def compile_and_load_rom(main_gcl):
reload(asm)
with patch("sys.argv", script_argv + [f"Main={main_gcl}"]), patch(
"asm.writeRomFiles"
), patch("asm.enableListing"), patch("asm.disableListing"), patch(
"asm.print"
), patch(
"gcl0x.print"
):
exec(compiled_script, copy.copy(script_globals))
Emulator.reset() # To reset PC etc. should really be part of load_rom_from_asm_module
Emulator.load_rom_from_asm_module()
def _read_word(address, *, signed):
return int.from_bytes(RAM[address : address + 2], "little", signed=signed)
def _load(gcl_file):
symbols = get_symbol_table(gcl_file)
compile_and_load_rom(gcl_file)
return symbols
def _run_to_main_start():
cycles = Emulator.run_to("SYS_Reset_88", max_instructions=10_000_000)
print(f"Boot reached SYS_RESET_88 in {cycles} cycles ({cycles * CLOCK_PERIOD}s)")
cycles += Emulator.run_to("SYS_Exec_88")
assert _read_word(asm.symbol("sysArgs0"), signed=False) == asm.symbol("Reset")
print(
f"Boot reached SYS_Exec_88 (Reset) in {cycles} cycles ({cycles * CLOCK_PERIOD}s)"
)
cycles += Emulator.run_to("SYS_Exec_88", max_instructions=10_000_000)
assert _read_word(asm.symbol("sysArgs0"), signed=False) == asm.symbol("Main")
print(
f"Boot reached SYS_Exec_88 (Main) in {cycles} cycles ({cycles * CLOCK_PERIOD}s)"
)
cycles += Emulator.run_vcpu_to(0x200)
print(
f"Program was ready to begin exectution after {cycles} cycles ({cycles * CLOCK_PERIOD}s)"
)
return cycles
def _run_to_function_entry(symbols, function):
# Can't run to CALL, as it's included in DEF
target_instruction = asm.symbol("CALL") + 1
cycles = Emulator.run_to(target_instruction, max_instructions=1_000_000)
if Emulator.next_instruction != target_instruction:
# Must have hit a breakpoint, just return and hope the caller knows what to do
return cycles
# May be calling the wrong function
while Emulator.AC != symbols[function]:
cycles += Emulator.run_to(target_instruction, max_instructions=1_000_000)
if Emulator.next_instruction != target_instruction:
return cycles
# Allow CALL to run, so that we return when to enter the function
cycles += Emulator.step_vcpu()
return cycles
def _complete_function():
return Emulator.run_vcpu_to(Emulator.vLR)
def benchmark(name, gcl_file):
symbols = _load(gcl_file)
message = f"Running {name}"
print(message)
print("=" * len(message))
cycles = _run_to_main_start()
cycles += _run_to_function_entry(symbols, "CalcSet")
print(
f"Program initialisation was complete after {cycles} cycles ({cycles * CLOCK_PERIOD}s)"
)
cycles += _complete_function()
print(f"CalcSet was complete after {cycles} cycles ({cycles * CLOCK_PERIOD}s)")
print()
if __name__ == "__main__":
for name, gcl_file in [
("Original", ORIGINAL_MANDELBROT),
("Modified", MY_MANDELBROT),
]:
benchmark(name, gcl_file)
@@ -0,0 +1,356 @@
{-----------------------------------------------------------------------+
| |
| Mandelbrot fractal |
| |
+-----------------------------------------------------------------------}
gcl0x
{
Plot the Mandelbrot set
Originally by Marcel. This version is adapted to use SYS_MultiplyBytes_120
In order to make the multiplication as fast as possible we use 8 fraction
bits instead of 7.
}
{ multiply-shift ((A*B)>>8) }
{
Uses Karatsuba's algorithm, which only computes three partial products,
the product of the two high-bytes, the product of the two low-bytes, and
a product that turns out to be (in our case)
high-of-A * low-of-B
+ low-of-A * high-of-B
- high-of-A * high-of-B
- low-of-A * low-of-B
In other words, we can produce
high-of-A * low-of-B + low-of-A * high-of-B
(the sum of the two partial products we didn't calculate)
by adding on the products we do. Nice.
The setup to find the multiplicands needed is a bit fiddly,
and would be slow in vCPU, so we use a SYS function to do it.
This leaves sysFn pointing to SYS_MultiplyBytes_120, so the whole thing is easy.
}
[def
{Extract sign and absolute values}
0 sign=
{0}A- [if>0 A= 1 sign=]
0 B- [if>0 B= sign 1^ sign=]
{ Karatsuba multiplication }
\SYS_KaratsubaPrepare_54 _sysFn=
A _sysArgs0=
B 54!!
[if=0 120!! C=
else 120!! C= 0 C- C=]
{ Find product of low bytes }
<A, \sysArgs0.
<B, \sysArgs1.
120!! \sysArgs5: C+ C=
{ multiply high-byte of A by high-byte of B, left-shift by 8 and add to C }
>A, \sysArgs0.
>B, \sysArgs1.
98!! \sysArgs7. C+ _sysArgs6+ C=
{Apply sign to return value }
sign [if<>0 0 C- else C]
ret
] MulShift8=
{-----------------------------------------------------------------------+
|}\vLR>++ ret{ RAM page 3 |
+-----------------------------------------------------------------------}
$0300:
[def {CalcSet}
push
$800 Pen= {Start of video}
120 Height= 160 Width= len=
LastPixel= {Anything well-defined}
0 DY=
Step DX=
[do
{Draw white pixel while busy here}
63 Pen.
{Update clock}
UpdateClock!
\SYS_MultiplyBytes_120 \sysFn:
LastPixel [if=0
{Check if we are inside one of the main bulbs for
a quick bailout (Wikipedia)
(x+1)^2 + y^2 < 1/16}
Y0 A= B= MulShift8! YY=
256 X0+ A= B= MulShift8! YY+ 16- [if<0 0
else
{q*(q + x - 1/4) < 1/4*y^2, where q = (x - 1/4)^2 + y^2}
X0 64- A= B= MulShift8! YY+ {q}
A= X0+ 64- B= MulShift8! tmp=
tmp+ tmp= tmp+ tmp= {*4} YY- [if<0 0
else
{Otherwise run the escape time algorithm}
CalcPixel!
]
]
else
{No shortcut}
CalcPixel!
]
LastPixel= Pen. {Plot pixel}
len 1- [if<=0
{Turn right}
DY tmp= DX DY= 0 tmp- DX=
{Length of next segment, either horizontal or vertical}
DX [if<>0 Width 1- Width= else Height 1- Height=]
]
{Break when reaching a zero-length segment}
len= if>0
{Step in the fractal plane}
X0 DX+ X0=
Y0 DY+ Y0=
{Matching step in video frame}
DX [if<0 Pen 1- Pen=]
DX [if>0 Pen 1+ Pen=]
DY [if<0 -$100 Pen+ Pen=]
DY [if>0 $100 Pen+ Pen=]
loop]
{60 \soundTimer. {For debugging}}
GrayOut!
pop ret
] CalcSet=
{-----------------------------------------------------------------------+
|}\vLR>++ ret{ RAM page 4 |
+-----------------------------------------------------------------------}
$0400:
[def {GrayOut}
push
$800 Pen=
120 Height= 160 Width= len=
1 DX= 0 DY=
[do
\SYS_LSRW1_48 \sysFn:
0 Level=
32 [do
i=
Pen, 63& i- [if>=0 Pen. i 21& [if<>0 1 else 2] Level+ Level=]
i 48!! {ShiftRight}
if>0loop]
{Level in 0..9}
Pen. {Paint it black}
Level [if<>0
{Level in 1..9}
{Ordered dithering}
Pen>, 1& i= i+ i= {2 * bit 0 of y}
Pen 1& i+ i= {+ bit 0 of x}
[def 0# 2# {Bayer matrix (Wikipedia)}
3# 1#]
i+ peek Level+ 1- Level=
{Level in 0..11}
{Map intensity level to actual gray color (multiple of 1+4+16)}
[do Level 3- if>=0 Level= Pen, 21+ Pen. loop]
]
{Advance to next pixel}
len 1- [if<=0
{Turn right}
DY tmp= DX DY= 0 tmp- DX=
{Length of next segment, either horizontal or vertical}
DX [if<>0 Width 1- Width= else Height 1- Height=]
]
{Break when reaching a zero-length segment}
len= if>0
{Matching step in video frame}
DX [if<0 Pen 1- Pen=]
DX [if>0 Pen 1+ Pen=]
DY [if<0 -$100 Pen+ Pen=]
DY [if>0 $100 Pen+ Pen=]
{Update clock}
UpdateClock!
loop]
pop ret
] GrayOut=
$201a Separator= {High: separator character, Low: XOR when blinking}
{-----------------------------------------------------------------------+
|}\vLR>++ ret{ RAM page 5 |
+-----------------------------------------------------------------------}
$0500:
{Update 24-hour clock}
[def
\frameCount,
LastFrame- 255& Elapsed=
60- [if<0
\buttonState, 128& [if<>0 ret]
15 {Yellow}
else
63 {White}]
Color=
{1 second has elapsed, or button A was pressed}
push
Clock0 Elapsed+ Clock0=
LastFrame Elapsed+ LastFrame=
-3599 Clock0+ [if>=0
Clock0=
1 AddMinutes!
]
{Change separator between on/off ($3a/$20)}
Separator>, Separator^ Separator>.
{Check if user is adjusting the time}
\buttonState, 119^ {A+Up} [if=0 Clock0= +1 else
12^ {A+Down} [if=0 Clock0= -1 else
6^ {A+Left} [if=0 Clock0= -60 else
3^ {A+Right} [if=0 Clock0= +60 else 0]]]]
[if<>0
AddMinutes! {Adjust minutes/hours clock}
0 Clock0= {Reset seconds/subseconds clock}
$3a00 Separator= {Stop blinking once adjusted}
]
\buttonState, 15| \buttonState. {Reset arrow presses, but not the others}
{Convert to HH:MM:SS and draw on screen}
$445c Pos=
Clock1 Value= 600 NextDigit! {10-hour digit}
60 NextDigit! { 1-hour digit}
Separator>, PrintChar! {Colon or space}
10 NextDigit! {10-minute digit}
1 NextDigit! { 1-minute digit}
pop ret
] UpdateClock=
[def {PrintChar}
32- i= \font32up fontData= {All of '0'-'9' and ':' are in the first page}
i 2<< i+ {Multiply by 5}
fontData+ fontData= {Add to page address to reach bitmap data}
$800 Pos+ q= {Where to stop the inner drawing loop}
{Draw 5 vertical slices: 5 using font data}
0 \sysArgs0. {Black}
Color \sysArgs1.
Pos \sysArgs4:
6+ Pos=
\SYS_VDrawBits_134 \sysFn:
$fb i= [do
fontData 0? fontData<++ \sysArgs2. 134!!
\sysArgs4<++
i<++ i if<>0loop]
ret
] PrintChar=
{-----------------------------------------------------------------------+
|}\vLR>++ ret{ RAM page 6 |
+-----------------------------------------------------------------------}
$0600:
[def {NextDigit -- Value Radix}
push
Radix=
$30 Digit=
Value Radix- [if>=0
[do Value= Digit<++ Radix- if>=0loop]
]
Digit PrintChar!
pop ret
] NextDigit=
[def {AddMinutes}
Clock1+ Clock1=
[if<0 1440 Clock1+ Clock1=]
-1440 Clock1+ [if>=0 Clock1=]
ret
] AddMinutes=
{ Calculate color for (X0,Y0) using the escape time algorithm }
[def {CalcPixel}
push
0 X= XX= Y= YY= i=
[do
i 1+ i= 64^ if<>0 {Break after completing 63 iterations}
{Mandelbrot function: z' := z^2 + c}
X A= Y Y+ B= MulShift8! Y0+ Y= {Y = 2*X*Y + Y0}
XX YY- X0+ X= {X = X^2 - Y^2 + X0}
{Calculate squares}
{X}A= B= MulShift8! XX=
Y A= B= MulShift8! YY=
-$400 XX+ YY+
if<=0loop {else} i {Also break when X^2 + Y^2 > 4}
]
pop ret
] CalcPixel=
{ Main }
0 Clock0= Clock1= {Frames and minutes}
Digit=
\frameCount, LastFrame=
[do
-360 Y0= -640 X0= 6 Step= CalcSet! {Global 1127.446 seconds}
-296 Y0= -196 X0= 2 Step= CalcSet! {Zoom1 2125.648 seconds}
-120 Y0= -512 X0= 2 Step= CalcSet! {Zoom2 2050.341 seconds}
-640 Y0= -720 X0= 18 Step= CalcSet! {Wide 356.482 seconds}
0 Y0= -200 X0= 2 Step= CalcSet! {Zoom3 2337.633 seconds}
-120 Y0= 0 X0= 2 Step= CalcSet! {Zoom4 1409.569 seconds}
loop]
{ Benchmark settings:
+ $1c10 p= {Start of video}
+ 96 Height= 128 Width= len=
+ i 1+ i= 27^ if<>0 {Break after completing 26 iterations}
+ -144 Y0= -256 X0= 3 Step= CalcSet! {Global 736.586 seconds}
}
{-----------------------------------------------------------------------+
| End |
+-----------------------------------------------------------------------}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,209 @@
* source: C:\Users\peter.russell\Documents\Personal\multiply\Contrib\psr\multiply\src\half-square.asm.py
address
| encoding
| | instruction
| | | operands
| | | |
V V V V
0000 dc00 st $00,[y,x++] ;[x++] <- ⌊$0²/2⌋
0001 dc00 st $00,[y,x++] ;[x++] <- ⌊$1²/2⌋
0002 dc02 st $02,[y,x++] ;[x++] <- ⌊$2²/2⌋
0003 dc04 st $04,[y,x++] ;[x++] <- ⌊$3²/2⌋
0004 dc08 st $08,[y,x++] ;[x++] <- ⌊$4²/2⌋
0005 dc0c st $0c,[y,x++] ;[x++] <- ⌊$5²/2⌋
0006 dc12 st $12,[y,x++] ;[x++] <- ⌊$6²/2⌋
0007 dc18 st $18,[y,x++] ;[x++] <- ⌊$7²/2⌋
0008 dc20 st $20,[y,x++] ;[x++] <- ⌊$8²/2⌋
0009 dc28 st $28,[y,x++] ;[x++] <- ⌊$9²/2⌋
000a dc32 st $32,[y,x++] ;[x++] <- ⌊$a²/2⌋
000b dc3c st $3c,[y,x++] ;[x++] <- ⌊$b²/2⌋
000c dc48 st $48,[y,x++] ;[x++] <- ⌊$c²/2⌋
000d dc54 st $54,[y,x++] ;[x++] <- ⌊$d²/2⌋
000e dc62 st $62,[y,x++] ;[x++] <- ⌊$e²/2⌋
000f dc70 st $70,[y,x++] ;[x++] <- ⌊$f²/2⌋
0010 0001 ld $01 ;Right-shift by four lookup for $1x
start: 0011 0104 ld [$04] ;(A)
0012 200f anda $0f
0013 c201 st [$01] ;[$01] <- A-low.
0014 6104 xora [$04] ;(A)
0015 ee00 bne ac ;ac >>= 4
0016 fc18 bra .multiply.1
0017 0000 ld $00
.multiply.1: 0018 c206 st [$06] ;[$06] <- A-high.
0019 0105 ld [$05] ;(B)
001a 20f0 anda $f0
001b ee00 bne ac ;ac >>= 4
001c fc21 bra .multiply.2
001d 0000 ld $00
001e 0200 nop ;2 fillers
001f 0200 nop
0020 0002 ld $02 ;Right-shift by four lookup for $2x
.multiply.2: 0021 c203 st [$03] ;[$03] <- B-high.
0022 1400 ld $00,y
0023 1007 ld $07,x
0024 a106 suba [$06] ;(A-high)
0025 fe00 bra ac ;[$07] <- ⌊(A-high - B-high)²/2⌋; x <- 8
0026 fc27 bra .multiply.3
.multiply.3: 0027 0103 ld [$03] ;(B-high)
0028 2106 anda [$06] ;(A-high)
0029 2001 anda $01
002a a107 suba [$07] ;(⌊(A-high - B-high)²/2⌋)
002b c202 st [$02] ;[$02] <- high-byte total.
002c 0101 ld [$01] ;(A-low)
002d a103 suba [$03] ;(B-high)
002e fe00 bra ac ;[$08] <- ⌊(A-low - B-high)²/2⌋; x <- 9
002f fc31 bra .multiply.4
0030 0003 ld $03 ;Right-shift by four lookup for $3x
.multiply.4: 0031 0103 ld [$03] ;(B-high)
0032 fd03 bra [$03] ;[$09] <- ⌊B-high²/2⌋; x <- 10
0033 fc34 bra .multiply.5
.multiply.5: 0034 fd01 bra [$01] ;[$0a] <- ⌊A-low²/2⌋; x <- 11
0035 fc41 bra .multiply.6
0036 0200 nop ;10 fillers
0037 0200 nop
0038 0200 nop
* 10 times
0040 0004 ld $04 ;Right-shift by four lookup for $4x
.multiply.6: 0041 2104 anda [$04] ;(A)
0042 2001 anda $01
0043 810a adda [$0a] ;(⌊A-low²/2⌋)
0044 8109 adda [$09] ;(⌊B-high²/2⌋)
0045 a108 suba [$08] ;(⌊(A-low - B-high)²/2⌋)
0046 c203 st [$03] ;[$03] <- A-low * B-high.
0047 200f anda $0f
0048 c207 st [$07] ;[$07] <- low(A-low * B-high).
0049 6103 xora [$03] ;(A-low * B-high)
004a ee00 bne ac ;ac >>= 4
004b fc51 bra .multiply.7
004c 0000 ld $00
004d 0200 nop ;3 fillers
004e 0200 nop
004f 0200 nop
0050 0005 ld $05 ;Right-shift by four lookup for $5x
.multiply.7: 0051 8109 adda [$09] ;(⌊B-high²/2⌋)
0052 8102 adda [$02] ;(high-byte total)
0053 c202 st [$02] ;Update high-byte total
0054 1008 ld $08,x
0055 0105 ld [$05] ;(B)
0056 200f anda $0f
0057 c203 st [$03] ;[$03] <- B-low.
0058 a106 suba [$06] ;(A-high)
0059 fe00 bra ac ;[$08] <- ⌊(B-low - A-high)²/2⌋; x <- 9
005a fc61 bra .multiply.8
005b 0200 nop ;5 fillers
005c 0200 nop
005d 0200 nop
* 5 times
0060 0006 ld $06 ;Right-shift by four lookup for $6x
.multiply.8: 0061 fd03 bra [$03] ;[$09] <- ⌊B-low²/2⌋; x <- 10
0062 fc63 bra .multiply.9
.multiply.9: 0063 0106 ld [$06] ;(A-high)
0064 1006 ld $06,x
0065 fd06 bra [$06] ;[$06] <- ⌊A-high²/2⌋; x <- 7
0066 fc71 bra .multiply.10
0067 0200 nop ;9 fillers
0068 0200 nop
0069 0200 nop
* 9 times
0070 0007 ld $07 ;Right-shift by four lookup for $7x
.multiply.10: 0071 2105 anda [$05] ;(B)
0072 2001 anda $01
0073 8109 adda [$09] ;(⌊B-low²/2⌋)
0074 8106 adda [$06] ;(⌊A-high²/2⌋)
0075 a108 suba [$08] ;(⌊(B-low - A-high)²/2⌋)
0076 c203 st [$03] ;[$03] <- B-low * A-high.
0077 200f anda $0f
0078 c208 st [$08] ;[$08] <- low(B-low * A-high).
0079 6103 xora [$03] ;(B-low * A-high)
007a ee00 bne ac ;ac >>= 4
007b fc81 bra .multiply.11
007c 0000 ld $00
007d 0200 nop ;3 fillers
007e 0200 nop
007f 0200 nop
0080 0008 ld $08 ;Right-shift by four lookup for $8x
.multiply.11: 0081 8106 adda [$06] ;(⌊A-high²/2⌋)
0082 8102 adda [$02] ;(high-byte total)
0083 c202 st [$02] ;Update high-byte total
0084 1006 ld $06,x
0085 0105 ld [$05] ;(B)
0086 200f anda $0f
0087 a101 suba [$01] ;(A-low)
0088 fe00 bra ac ;[$06] <- ⌊(B-low - A-low)²/2⌋; x <- 7
0089 fc91 bra .multiply.12
008a 0200 nop ;6 fillers
008b 0200 nop
008c 0200 nop
* 6 times
0090 0009 ld $09 ;Right-shift by four lookup for $9x
.multiply.12: 0091 0101 ld [$01] ;(A-low)
0092 2105 anda [$05] ;(B)
0093 2001 anda $01
0094 8109 adda [$09] ;(⌊B-low²/2⌋)
0095 810a adda [$0a] ;(⌊A-low²/2⌋)
0096 a106 suba [$06] ;(⌊(B-low - A-low)²/2⌋)
0097 c203 st [$03] ;[$03] <- A-low * B-low.
0098 200f anda $0f
0099 c201 st [$01] ;[$01] <- result low nibble.
009a 6103 xora [$03] ;(A-low * B-low)
009b ee00 bne ac ;ac >>= 4
009c fca1 bra .multiply.13
009d 0000 ld $00
009e 0200 nop ;2 fillers
009f 0200 nop
00a0 000a ld $0a ;Right-shift by four lookup for $ax
.multiply.13: 00a1 8107 adda [$07] ;(low(A-low * B-high))
00a2 8108 adda [$08] ;(low(B-low * A-high))
00a3 c203 st [$03] ;[$03] <- temp.
00a4 8200 adda ac
00a5 8200 adda ac
00a6 8200 adda ac
00a7 8200 adda ac
00a8 4101 ora [$01] ;(result low nibble)
00a9 c201 st [$01] ;[$01] <- low(result).
00aa 0103 ld [$03] ;(temp)
00ab 20f0 anda $f0
00ac ee00 bne ac ;ac >>= 4
00ad fcb1 bra .multiply.14
00ae 0000 ld $00
00af 0200 nop ;filler
00b0 000b ld $0b ;Right-shift by four lookup for $bx
.multiply.14: 00b1 8102 adda [$02] ;(high-byte total)
00b2 c202 st [$02] ;[$02] <- high(result).
end: 00b3 0200 nop
00b4 0200 nop ;12 fillers
00b5 0200 nop
00b6 0200 nop
* 12 times
00c0 000c ld $0c ;Right-shift by four lookup for $cx
00c1 0200 nop ;15 fillers
00c2 0200 nop
00c3 0200 nop
* 15 times
00d0 000d ld $0d ;Right-shift by four lookup for $dx
00d1 0200 nop ;15 fillers
00d2 0200 nop
00d3 0200 nop
* 15 times
00e0 000e ld $0e ;Right-shift by four lookup for $ex
00e1 0200 nop ;15 fillers
00e2 0200 nop
00e3 0200 nop
* 15 times
00f0 000f ld $0f ;Right-shift by four lookup for $fx
00f1 dc70 st $70,[y,x++] ;[x++] <- ⌊($-f)²/2⌋
00f2 dc62 st $62,[y,x++] ;[x++] <- ⌊($-e)²/2⌋
00f3 dc54 st $54,[y,x++] ;[x++] <- ⌊($-d)²/2⌋
00f4 dc48 st $48,[y,x++] ;[x++] <- ⌊($-c)²/2⌋
00f5 dc3c st $3c,[y,x++] ;[x++] <- ⌊($-b)²/2⌋
00f6 dc32 st $32,[y,x++] ;[x++] <- ⌊($-a)²/2⌋
00f7 dc28 st $28,[y,x++] ;[x++] <- ⌊($-9)²/2⌋
00f8 dc20 st $20,[y,x++] ;[x++] <- ⌊($-8)²/2⌋
00f9 dc18 st $18,[y,x++] ;[x++] <- ⌊($-7)²/2⌋
00fa dc12 st $12,[y,x++] ;[x++] <- ⌊($-6)²/2⌋
00fb dc0c st $0c,[y,x++] ;[x++] <- ⌊($-5)²/2⌋
00fc dc08 st $08,[y,x++] ;[x++] <- ⌊($-4)²/2⌋
00fd dc04 st $04,[y,x++] ;[x++] <- ⌊($-3)²/2⌋
00fe dc02 st $02,[y,x++] ;[x++] <- ⌊($-2)²/2⌋
00ff dc00 st $00,[y,x++] ;[x++] <- ⌊($-1)²/2⌋
0100
File diff suppressed because it is too large. Load diff
+150
View File
@@ -0,0 +1,150 @@
$ErrorActionPreference = 'Stop';
# Path of the root of the repository
$REPO_ROOT_PATH = Join-Path $PSScriptRoot '..\..\..' -Resolve
# Python search path for modules
$VENV_DIR = Join-Path $PSScriptRoot '.venv'
$SCRIPT_DIR = Join-Path $VENV_DIR 'Scripts'
$SRC_DIR = Join-Path $PSScriptRoot 'src'
$SYS_DIR = Join-Path $PSScriptRoot 'sys'
$OUT_DIR = Join-Path $PSScriptRoot 'out'
$TEST_DIR = Join-Path $PSScriptRoot 'test'
$dirExcludes = '.venv', '.pytest_cache', 'sys', '.pypy-venv'
function findFilesToFormat() {
$filesToFormat = @(Get-ChildItem -Exclude $dirExcludes -Directory | ForEach-Object { Get-ChildItem -path $_ -Recurse -Filter '*.py' })
$filesToFormat += @(Get-ChildItem -Filter '*.py')
return @($filesToFormat | ForEach-Object { $_.FullName })
}
$PACKAGES = 'ipython', 'pytest', 'hypothesis', 'flake8', 'isort', 'black'
task default -depends isort, Blacken, Flake8, Test, Listing
function executeScript($script, $params) {
$scriptPath = Join-Path $SCRIPT_DIR -ChildPath $script
try {
get-item $scriptPath -ErrorAction Stop > $null
}
catch {
Invoke-Task Packages
}
exec { & "$scriptPath" @($params) } -errorMessage "Error when executing ${script}"
}
task isort {
executeScript 'isort.exe' (findFilesToFormat)
}
task Blacken {
executeScript 'black.exe' (findFilesToFormat)
}
task Flake8 {
$filesToFormat = findFilesToFormat
if ($filesToFormat.Count -gt 0) {
executeScript 'flake8.exe' $filesToFormat
}
}
task Virtualenv {
try {
get-item "$VENV_DIR" -ErrorAction Stop > $null
}
catch {
exec { python3 -m venv "$VENV_DIR" } -workingDirectory $PSScriptRoot
executeScript 'python.exe' @('-m', 'pip', 'install', '--upgrade', 'pip', 'setuptools', 'wheel')
# We always want core in the repo root to be on the search path
$pthFile = (Join-Path (Join-Path (Join-Path $VENV_DIR 'Lib') 'site-packages') 'gigatron-core.pth')
New-Item $pthFile > $null
"$(join-path $REPO_ROOT_PATH 'Core')" | Set-Content -Encoding 'ASCII' $pthFile
}
}
task Upgrade-Packages {
executeScript 'pip.exe' (('install', '--upgrade') + $PACKAGES)
Push-Location (Join-Path $PSScriptRoot '..\..\psr\py-gtemu')
try {
Remove-Item 'dist' -Recurse -ErrorAction SilentlyContinue
executeScript 'python.exe' @('setup.py', 'bdist_wheel')
$wheel = Get-ChildItem 'dist' '*.whl'
executeScript 'pip.exe' @('install', '--force-reinstall', $wheel.FullName)
}
finally {
Pop-Location
}
}
task Packages -depends VirtualEnv {
# In case we're not already here
Push-Location $PSScriptRoot
try {
Push-Location '..\..\psr\py-gtemu'
try {
$wheel = Get-ChildItem 'dist' '*.whl' -ErrorAction SilentlyContinue
if (!$wheel) {
executeScript 'python.exe' @('setup.py', 'bdist_wheel')
}
$wheel = Get-ChildItem 'dist' '*.whl' -ErrorAction SilentlyContinue
executeScript 'pip.exe' @('install', $wheel.FullName)
}
finally {
Pop-Location
}
}
finally {
Pop-Location
}
Pop-Location
executeScript 'pip.exe' (@(, 'install') + $PACKAGES)
}
task Test {
if (Test-Path $TEST_DIR) {
executeScript 'pytest.exe'
}
}
task Listing {
try {
$output = Get-Item $OUT_DIR -ErrorAction Stop
}
catch {
$output = New-Item $OUT_DIR -Type Directory
}
Push-Location $output
try {
$SRC_DIR, $SYS_DIR | Get-ChildItem -Filter '*.asm.py' -ErrorAction SilentlyContinue | ForEach-Object {
executeScript 'python.exe' @(, $_.FullName)
}
}
finally {
Pop-Location
}
}
task Clean {
get-item $OUT_DIR -ErrorAction SilentlyContinue | Remove-Item -Recurse
exec { git clean '-fXd' }
}
task PreCommit {
# Save any unknown / unstaged files
exec { git stash push '-kum' "Unstaged changes, for precommit testing" }
Push-Location $PSScriptRoot
try {
exec { git clean '-fdxe' '.venv' '-e' '.pytest_cache' '-e' '.pypy-venv' }
Invoke-Task default -ErrorAction Stop
# Check for any unstaged changes resulting
# we should be committing everything - including .lst files
exec { git 'update-index' '--refresh' '-q' }
$gitStatusOutput = @(exec { git 'status' '--porcelain=v1' '-uall' })
$modifiedFiles = @($gitStatusOutput -match '^.[^ ]')
Assert ($modifiedFiles.Count -eq 0) -failureMessage "Unstaged files were modified"
exec { git stash pop }
}
finally {
Pop-Location
}
}
@@ -0,0 +1,328 @@
"""Implementation of multiplication that uses the following identity:
a * b = (a² + b² - (a-b)²)/2
We use this to implement multiplication of nibbles, and from that multiplication of bytes.
We make use of a lookup table of ⌊n²/2⌋ for n in the range [-15,15],
and calculate (⌊a²/2⌋ + ⌊b²/2⌋ - ⌊(a-b)²/2⌋ + (a & b & 1)) - The a & b & 1 term compensates
for the fact that (⌊a²/2⌋ + ⌊b²/2⌋ - ⌊(a-b)²/2⌋) is off by one when both a and b are odd.
We also have a right-shift by four table.
Memory is used as follows:
(0x1,0x2) = Result (would be vAC in a real sys function)
(0x3) = very brief temporary storage (would be vTmp)
(0x4, 0x5) = A, B - Operands, would be sysArgs[0:2] - untouched.
(0x6..) = Variables. Would be sysArgs[2:] - but we try to leave the last value untouched.
"""
import sys
from itertools import chain, count
import asm
from asm import (
AC,
C,
X,
Xpp,
Y,
adda,
align,
anda,
bne,
bra,
define,
end,
fillers,
label,
ld,
ora,
pc,
st,
suba,
writeRomFiles,
xora,
)
DEBUG = False # Set to True to get debugging output
# I'm keen to avoid using too many variables.
# The comments that this outputs should help me keep things clean
class VariableTracker:
def __init__(self, size=12, initial_x=6):
self._x = initial_x
self._current_bindings = ["unused"] * size
@staticmethod
def _comment_next_instruction(message):
# Hack to add a comment on the next instruction, not the previous.
address = max(0, asm._romSize)
line_comments = asm._comments.setdefault(address, [])
line_comments.append(f";{message}")
def define(self, name, address, *, suppress_comment=False):
assert self._current_bindings[address] in ("dead", "unused")
self._current_bindings[address] = name
if not suppress_comment:
self._comment_next_instruction(f"[${address:02x}] <- {name}.")
if DEBUG:
print(self)
return address
def __repr__(self) -> str:
return f"{self._current_bindings} x={self._x}"
def reset_x(self, new_x):
self._x = new_x
return new_x
def define_from_x_postincrement(self, name, *, suppress_comment=False):
assert self._current_bindings[self._x] in ("dead", "unused"), self
self._current_bindings[self._x] = name
if not suppress_comment:
C(f"[${self._x:02x}] <- {name}; x <- {self._x + 1}")
self._x += 1
if DEBUG:
print(self)
def read(self, name, *, suppress_comment=False):
if not suppress_comment:
self._comment_next_instruction(f"({name})")
return self._current_bindings.index(name)
def update(self, name, *, suppress_comment=False):
if not suppress_comment:
self._comment_next_instruction(f"Update {name}")
return self._current_bindings.index(name)
def kill(self, name, *, suppress_comment=False):
address = self._current_bindings.index(name)
self._current_bindings[address] = "dead"
if not suppress_comment:
self._comment_next_instruction(f"({name})")
return address
def get_name(self, address):
return self._current_bindings[address]
def assert_x(self, n):
assert self._x == n, f"Assert x: have {self._x}, but wanted {n}. {self}"
## Lookup tables are woven through the code, and we need to avoid them.
_emit_half_square = lambda i: st(i, [Y, Xpp])
class LookupTableManager:
half_square_table = [
(i, _emit_half_square, i**2 // 2, f"[x++] <- ⌊${i:x}²/2⌋")
for i in range(0x10)
]
half_square_table_inverted = [
(i & 0xFF, _emit_half_square, (i**2 // 2), f"[x++] <- ⌊(${i:x})²/2⌋")
for i in range(-1, -0x10, -1)
]
right_shift_table = [
(i * 16, ld, i, f"Right-shift by four lookup for ${i:x}x")
for i in range(1, 0x10)
]
def __init__(self):
all_entries = chain(
self.half_square_table,
self.half_square_table_inverted,
self.right_shift_table,
)
self.table_entries = iter(sorted(all_entries))
self.next_entry = next(self.table_entries)
def emit_next_entry(self):
address, emit, value, comment = self.next_entry
assert address >= (
pc() & 0xFF
), f"Next address ({address:x}) is before the current PC ({pc() & 0xff:x}) - we missed it!"
fillers(until=address)
while address == pc() & 0xFF:
emit(value)
C(comment)
address, emit, value, comment = next(self.table_entries)
self.next_entry = address, emit, value, comment
def finish_tables(self):
address, emit, value, comment = self.next_entry
assert address >= (
pc() & 0xFF
), f"Next address ({address:x}) is before the current PC ({pc() & 0xff:x}) - we missed it!"
fillers(until=address)
emit(value)
C(comment)
for address, emit, value, comment in self.table_entries:
fillers(until=address)
emit(value)
C(comment)
vars = VariableTracker()
labels = (f".multiply.{i}" for i in count(1))
tables = LookupTableManager()
def right_shift(*, emit_next_table_entry=False):
next_label = next(labels)
bne(AC)
C("ac >>= 4")
bra(next_label)
ld(0) # A nop, in this case
if emit_next_table_entry:
tables.emit_next_entry()
label(next_label)
def lookup_and_store_half_square(
src, operand_name=None, *, kill=False, emit_next_table_entry=False
):
assert (src is not AC) or (operand_name is not None)
operand_name = operand_name or src
target_name = (
f"⌊{operand_name}²/2⌋" if " " not in operand_name else f"⌊({operand_name})²/2⌋"
)
if src is AC:
bra(AC)
elif kill:
bra([vars.kill(src, suppress_comment=True)])
else:
bra([vars.read(src, suppress_comment=True)])
vars.define_from_x_postincrement(target_name)
next_label = next(labels)
bra(next_label)
if emit_next_table_entry:
tables.emit_next_entry()
label(next_label)
### Code starts here
define("A", vars.define("A", 0x4, suppress_comment=True))
define("B", vars.define("B", 0x5, suppress_comment=True))
align(0x100)
tables.emit_next_entry()
label("start")
ld([vars.read("A")])
anda(0x0F)
st([vars.define("A-low", 0x1)])
xora([vars.read("A")])
right_shift()
st([vars.define("A-high", 0x6)])
ld([vars.read("B")])
anda(0xF0)
right_shift(emit_next_table_entry=True)
st([vars.define("B-high", 0x3)])
# Start product of high-nibbles
ld(0, Y)
ld(vars.reset_x(0x07), X)
suba([vars.read("A-high")])
lookup_and_store_half_square(AC, "A-high - B-high")
ld([vars.read("B-high")])
anda([vars.read("A-high")])
anda(0x01)
suba([vars.kill("⌊(A-high - B-high)²/2⌋")])
st([vars.define("high-byte total", 0x02)])
# A-low * B-high
ld([vars.read("A-low")])
suba([vars.read("B-high")])
lookup_and_store_half_square(AC, "A-low - B-high", emit_next_table_entry=True)
ld([vars.read("B-high")])
lookup_and_store_half_square("B-high", kill=True)
lookup_and_store_half_square("A-low", emit_next_table_entry=True)
anda([vars.read("A")])
anda(0x01)
adda([vars.read("⌊A-low²/2⌋")])
adda([vars.read("⌊B-high²/2⌋")])
suba([vars.kill("⌊(A-low - B-high)²/2⌋")])
st([vars.define("A-low * B-high", 0x03)])
anda(0x0F)
st([vars.define("low(A-low * B-high)", 0x07)])
xora([vars.kill("A-low * B-high")])
right_shift(emit_next_table_entry=True)
adda([vars.kill("⌊B-high²/2⌋")])
adda([vars.read("high-byte total")])
st([vars.update("high-byte total")])
ld(vars.reset_x(0x8), X)
ld([vars.read("B")])
anda(0x0F)
st([vars.define("B-low", 0x03)])
suba([vars.read("A-high")])
print(vars)
lookup_and_store_half_square(
AC, operand_name="B-low - A-high", emit_next_table_entry=True
)
lookup_and_store_half_square("B-low", kill=True)
ld([vars.read("A-high")])
ld(vars.reset_x(0x6), X)
lookup_and_store_half_square("A-high", kill=True, emit_next_table_entry=True)
anda([vars.read("B")])
anda(0x01)
adda([vars.read("⌊B-low²/2⌋")])
adda([vars.read("⌊A-high²/2⌋")])
suba([vars.kill("⌊(B-low - A-high)²/2⌋")])
st([vars.define("B-low * A-high", 0x03)])
anda(0x0F)
st([vars.define("low(B-low * A-high)", 0x08)])
xora([vars.kill("B-low * A-high")])
right_shift(emit_next_table_entry=True)
adda([vars.kill("⌊A-high²/2⌋")])
adda([vars.read("high-byte total")])
st([vars.update("high-byte total")])
# Product of low-nibbles
ld(vars.reset_x(6), X)
ld([vars.read("B")])
anda(0x0F) # Because we lost B-low
suba([vars.read("A-low")])
lookup_and_store_half_square(
AC, operand_name="B-low - A-low", emit_next_table_entry=True
)
ld([vars.kill("A-low")])
anda([vars.read("B")])
anda(0x01)
adda([vars.kill("⌊B-low²/2⌋")])
adda([vars.kill("⌊A-low²/2⌋")])
suba([vars.kill("⌊(B-low - A-low)²/2⌋")])
st([vars.define("A-low * B-low", 0x3)])
print(vars)
# Final sum - 23 cycles
anda(0xF)
st([vars.define("result low nibble", 0x01)])
xora([vars.kill("A-low * B-low")])
right_shift(emit_next_table_entry=True)
adda([vars.kill("low(A-low * B-high)")])
adda([vars.kill("low(B-low * A-high)")])
st([vars.define("temp", 0x3)])
adda(AC)
adda(AC)
adda(AC)
adda(AC)
ora([vars.kill("result low nibble")])
st([vars.define("low(result)", 0x01)])
ld([vars.kill("temp")])
anda(0xF0)
right_shift(emit_next_table_entry=True)
adda([vars.kill("high-byte total")])
st([vars.define("high(result)", 0x2)])
label("end")
ld(AC, AC)
tables.finish_tables()
end()
define("result", 0x01)
if __name__ == "__main__":
writeRomFiles(sys.argv[0])
@@ -0,0 +1,381 @@
import math
import sys
from asm import (
AC,
C,
X,
Y,
adda,
align,
anda,
bge,
blt,
bne,
bra,
disableListing,
enableListing,
end,
fillers,
hi,
jmp,
label,
ld,
lo,
nop,
ora,
pc,
st,
suba,
writeRomFiles,
xora,
zpByte,
)
if __name__ == "__main__":
enableListing()
# Inputs
a, b = zpByte(), zpByte()
# Output
result = zpByte(2)
# Used for storage
tmp = zpByte()
# Used for the continuation address after lookup.
continuation = zpByte()
# Used for the action to take with the high byte.
high_byte_action = zpByte()
# The following code implements a lookup table of floored quarter squares,
# for values up to 255.
# This is supposed to enable a fast multiplication for 7-bit numbers.
# First the high-bytes.
# The table is shifted down by 32 places, as the first 32 high-bytes are all zero
# This allows us to have code later in the page which we can branch back to.
align(0x100, size=0x100)
label("Quarter-squares lookup table")
for i in range(32, 256):
val = math.floor(i**2 / 4)
ld(hi(val))
C(f"${val:04x} = {val} = floor({i} ** 2 / 4); ${val:04x} >> 8 = ${val >> 8:02x}")
# We jump back here after looking up the low-byte of the result.
label("low-byte return point")
ld(hi("multiply 7x7"), Y)
jmp(Y, [continuation])
ld(hi(pc()), Y) # Make it easy to get back here!
cost_of_low_byte_return = 3
label("table entry.possibly-negative")
# AC is negative, if b > a. Find absolute value
blt(pc() + 3) # 1
bra(pc() + 3) # 2
suba(1) # 3; if >= 0
xora(0xFF) # 3; if < 0
adda(1) # 4
cost_of_absolute = 4
label("table entry")
# Calculate an index into the high-byte table.
# This is basically a matter of subtracting 32, and jumping in if the result >= 0.
# But values greater than 160 have the sign-bit set after subtraction,
# despite being >32.
# We test for the sign bit and jump after subtraction even if 'negative' in these cases.
st([tmp]) # 1
blt(pc() + 5) # 2
suba(32) # 3
bge(AC) # 4
bra([high_byte_action]) # 5
ld(0) # 6
bra(AC) # 4
bra([high_byte_action]) # 5
cost_of_high_byte_table_entry = 6
# Some space here for other code?
fillers(until=251)
# We jump back here after looking up the high-byte of the result.
# Counting is in reverse
label("high-byte action.invert-and-add")
xora(0xFF) # 4
label("high-byte action.add")
adda([result + 1]) # 3
label("high-byte action.store")
st([result + 1]) # 2
ld([tmp]) # 1
assert pc() & 0xFF == 0xFF, pc()
cost_of_high_byte_invert_and_add = 4
cost_of_high_byte_add = 3
cost_of_high_byte_store = 2
label("low-byte table entry")
# With the index in the accumulator, and the current page in the Y register,
# We jump to the right entry in the low-byte table, replace AC with the result,
# and jump back out to 'low-byte return point' defined above,
# using the double-jump trick.
# This exploits the fact the following is the last instruction on the page,
# and the high byte of the PC has already incremented,
# so the bne will take us to an address in the next page.
# We use the Y register to return to the current page.
# The table has two zeros at the start, meaning that we can replace the first
# with the jump back.
bne(AC) # 1
align(0x100, size=0x100)
jmp(Y, "low-byte return point") # 2
ld(0) # 3
cost_of_low_byte_table_entry = 3
C("0 = floor(0 ** 2 / 4) and floor(1 ** 2 / 4)")
for i in range(2, 256):
val = math.floor(i**2 / 4)
ld(val)
C(f"${val:04x} = {val} = floor({i} ** 2 / 4)")
# Code copied from the main ROM. This provides a lookup table for right-shifts
align(0x100, size=0x100)
label("shiftTable")
shiftTable = pc()
for ix in range(255):
for n in range(1, 9): # Find first zero
if ~ix & (1 << (n - 1)):
break
pattern = ["x" if i < n else "1" if ix & (1 << i) else "0" for i in range(8)]
ld(ix >> n)
C("0b%s >> %d" % ("".join(reversed(pattern)), n))
assert pc() & 255 == 255
bra([continuation]) # Jumps back into next page
align(0x100, size=0x100)
nop() #
label("multiply 7x7")
# The formula is floor(((a + b) ** 2) / 4) - floor(((a - b) ** 2) / 4)
ld(".after-first-lookup") # 1
st([continuation])
ld(hi("Quarter-squares lookup table"), Y)
ld("high-byte action.store")
st([high_byte_action]) # 5
ld([a])
jmp(Y, "table entry") # 7
adda([b]) # 8
cost_to_first_lookup = 8
cost_after_first_lookup = (
cost_to_first_lookup
+ cost_of_high_byte_table_entry
+ cost_of_high_byte_store
+ cost_of_low_byte_table_entry
+ cost_of_low_byte_return
)
label(".after-first-lookup")
# On return we have the low-byte in the accumulator
# We can safely add one to it without causing an overflow,
# because 255 does not appear in the low-byte table.
# This is part of the following subtraction.
adda(1) # 1
st([result])
ld(".after-second-lookup")
st([continuation])
ld("high-byte action.invert-and-add") # 5
st([high_byte_action])
ld([a])
jmp(Y, "table entry.possibly-negative") # 8
suba([b]) # 9
cost_between_lookups = 9
cost_after_second_lookup = (
cost_after_first_lookup
+ cost_between_lookups
+ cost_of_absolute
+ cost_of_high_byte_table_entry
+ cost_of_high_byte_invert_and_add
+ cost_of_low_byte_table_entry
+ cost_of_low_byte_return
)
label(".after-second-lookup")
xora(0xFF) # 1
# We need to add this to the result
# But we may have a carry
adda([result])
st([tmp])
blt(pc() + 4) # 5
suba([result]) # 6
bra(pc() + 4) # 7
ora([result]) # 8
bra(pc() + 2) # 7
anda([result]) # 8
anda(0b1000_0000, X) # 9
ld([tmp])
st([result]) # 10
ld([X])
adda([result + 1])
st([result + 1]) # 13
cost_of_final_add = 13
cost_of_7bit_multiply = cost_after_second_lookup + cost_of_final_add
C(f"Total cost: {cost_of_7bit_multiply} cycles")
label("done")
nop()
label("multiply 8x8")
# Extend the 7bit x 7bit multiplication to 8bit x 8bit
#
# The logic goes as follows.
# Let A and B be the low seven bits of a and b, e.g.
# A = a₆2⁶ + a₅2⁵ + a₄2⁴ + a₃2³ + a₂2² + a₁2¹ + a₀2⁰
# B = b₆2⁶ + b₅2⁵ + b₄2⁴ + b₃2³ + b₂2² + b₁2¹ + b₀2⁰
# Then we could think of 8bit x 8bit multiply as
# (a₇2⁷ + A)(b₇2⁷ + B)
# Multiplying out the brackets gives
# a₇2⁷b₇2⁷ + a₇2⁷B + b₇2⁷A + AB
# (and AB is the result we already know how to calculate)
# Simplifying a bit, we get
# a₇b₇2¹⁴ + 2⁷(a₇B + b₇A) + AB
# Since a₇ and b₇ are one or zero, multiplying by them is like an if.
# We can consider four cases,
# if a₇ is 1 and b₇ is 1:
# 2¹⁴ + 2⁷(B + A) + AB
# if a₇ is 1 and b₇ is 0:
# 2⁷B + AB
# if a₇ is 0 and b₇ is 1:
# 2⁷A + AB
# if a₇ is 0 and b₇ is 0:
# AB
# Multiplication by 2⁷(=128) is a left-shift by seven, which
# can be broken down as moving the LSB of the low-byte to the
# MSB of the low-byte, and setting all of the other bits to zero,
# The other bits of the low byte can be right-shifted by one,
# and moved to the high byte.
# Test which of the branches we are on.
ld([a]) # 1
xora([b])
blt(".one MSB set") # 3
ld([a]) # 4
# Both MSBs equal
bge("multiply 7x7") # 5
anda(0b0111_1111) # 6
cost_of_8bit_multiply__both_msbs_low = cost_of_7bit_multiply + 6
# Both MSBs set
st([a]) # 7; a = A
ld(".after right-shift")
st([continuation])
ld(2**14 >> 8) # 10; Write the high-byte for later addition.
st([result + 1])
ld([b])
anda(0b0111_1111)
st([b]) # b = B
adda([a]) # 15
cost_of_both_msbs_set = 15
label(". << 7")
st([tmp]) # 1
anda(0b0000_0001) # Clear all but the bottom bit
adda(0b0111_1111) # Carries bottom bit to top bit
anda(0b1000_0000) # Clears all but the top bit
st([result]) # 5
ld([tmp])
anda(0b1111_1110) # Calculate index to right-shift-table
ld(hi("shiftTable"), Y)
jmp(Y, AC) # 9
bra(0xFF) # 10
# 11 ld (a + b) >> 1
# 12 bra [continuation]
# 12 nop
cost_of_right_shift = 13
cost_after_right_shift = cost_of_both_msbs_set + cost_of_right_shift
label(".one MSB set")
bge(".b has msb set") # 5
ld(0b0111_1111) # 6
# a has msb set
anda([a]) # 7
st([a])
ld(lo(".after right-shift") + 1)
st([continuation]) # 10
bra(". << 7") # 11
ld([b]) # 12
label(".b has msb set")
anda([b]) # 7
st([b])
ld(lo(".after right-shift") + 1)
st([continuation]) # 10
bra(". << 7") # 11
ld([a]) # 12
cost_of_one_msb_set = 12
one_msb_cost_saving = cost_of_both_msbs_set - cost_of_one_msb_set + 1
label(".after right-shift")
adda([result + 1]) # 1
st([result + 1])
ld(".after-first-lookup-8bit")
st([continuation])
ld(hi("Quarter-squares lookup table"), Y) # 5
ld("high-byte action.add")
st([high_byte_action])
ld([a])
jmp(Y, "table entry") # 9
adda([b]) # 10
cost_of_after_right_shift = 10
cost_after_first_lookup__8bit = (
cost_after_right_shift
+ cost_of_after_right_shift
+ cost_of_high_byte_table_entry
+ cost_of_high_byte_add
+ cost_of_low_byte_table_entry
+ cost_of_low_byte_return
)
label(".after-first-lookup-8bit")
# On return we have the low-byte in the accumulator
# We already either have 0 or 128 in the low byte of the result.
# Adding will cause an overflow into the high byte iff both
# have the MSB set, in which case the result will definitely
# not have the MSB set.
adda([result]) # 1
blt(pc() + 3) # 2
bra(pc() + 3) # 3
ld([result], X) # 4; May be a carry
ld(0, X) # 4; Definitely no carry
# We can safely add one to the result without causing a further overflow,
# because 255 does not appear in the low-byte table.
# This is part of the subtraction.
adda(1) # 5
st([result])
# Do the carry
ld([X])
adda([result + 1])
st([result + 1])
ld(".after-second-lookup") # 10
st([continuation])
ld("high-byte action.invert-and-add")
st([high_byte_action])
ld([a])
jmp(Y, "table entry.possibly-negative") # 15
suba([b]) # 16
cost_between_lookups__8bit = 16
cost_after_second_lookup__8bit = (
cost_after_first_lookup__8bit
+ cost_between_lookups__8bit
+ cost_of_absolute
+ cost_of_high_byte_table_entry
+ cost_of_high_byte_invert_and_add
+ cost_of_low_byte_table_entry
+ cost_of_low_byte_return
)
cost_of_8bit_multiply = cost_after_second_lookup__8bit + cost_of_final_add
no_msb_cost_saving = cost_of_8bit_multiply - cost_of_8bit_multiply__both_msbs_low
C(f"Worst case cost: {cost_of_8bit_multiply}")
C(f"Saving when both values < 128: {no_msb_cost_saving}")
C(f"Saving when only one value < 128: {one_msb_cost_saving}")
end()
if __name__ == "__main__":
disableListing()
writeRomFiles(sys.argv[0])
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,47 @@
import os.path
import pathlib
from importlib import reload
from types import SimpleNamespace
from hypothesis import given
from hypothesis import strategies as st
import asm
from gtemu import RAM, Emulator
SRC_DIR = (pathlib.Path(__file__).parent / ".." / "src").resolve()
SCRIPT = SRC_DIR / "half-square.asm.py"
def setup_module():
global vars
"""Load the Emulator from the multiplication script"""
reload(asm)
name, _ = os.path.splitext(os.path.basename(SCRIPT))
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": name}
with SCRIPT.open("rb") as file:
exec(compile(file.read(), SCRIPT, "exec"), script_globals)
Emulator.load_rom_from_asm_module()
vars = SimpleNamespace(**script_globals)
_bytes = st.integers(min_value=0, max_value=255)
@given(a=_bytes, b=_bytes)
def test_multiplication_8(a, b):
"""Multiplication of two eight-bit integers should work"""
Emulator.reset()
RAM[asm.symbol("A")] = a
RAM[asm.symbol("B")] = b
Emulator.next_instruction = "start"
cycles = Emulator.run_to("end")
result = int.from_bytes(
RAM[asm.symbol("result") : asm.symbol("result") + 2],
"little",
signed=False,
)
assert a * b == result
assert 119 == cycles
@@ -0,0 +1,106 @@
"""Tests for the implementation of SYS_KaratsubaPrepare_54"""
import os.path
import pathlib
from importlib import reload
from types import SimpleNamespace
from hypothesis import given
from hypothesis import strategies as st
import asm
from gtemu import RAM, Emulator
MAX_CYCLES = 54
SYS_DIR = (pathlib.Path(__file__).parent / ".." / "sys").resolve()
SCRIPT = SYS_DIR / "ROM.asm.py"
def setup_module():
global vars
"""Load the Emulator from the ROM script"""
reload(asm)
name, _ = os.path.splitext(os.path.basename(SCRIPT))
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": name}
with SCRIPT.open("rb") as file:
exec(compile(file.read(), SCRIPT, "exec"), script_globals)
Emulator.load_rom_from_asm_module()
vars = SimpleNamespace(**script_globals)
def setup_function():
RAM[vars.sysFn : vars.sysFn + 2] = asm.symbol("SYS_KaratsubaPrepare_54").to_bytes(
2, "little"
)
RAM[vars.vTicks] = 75
Emulator.next_instruction = "SYS"
Emulator.AC = 270 - max(14, MAX_CYCLES // 2)
def _sign_extend(byte_):
if byte_ & 0x80:
return ~0xFF | byte_
return byte_
_unsigned_words = st.integers(min_value=0, max_value=1 << 16 - 1)
@given(a=_unsigned_words, b=_unsigned_words)
def test_karatsuba_prepare(a, b):
setup_function() # Because Hypothesis calls us repeatedly, and the function under test changes sysFn etc.
RAM[vars.sysArgs : vars.sysArgs + 2] = a.to_bytes(2, "little", signed=False)
RAM[vars.vAC : vars.vAC + 2] = b.to_bytes(2, "little", signed=False)
cycles = 10 # 9 Cycles from previous next, plus one, because, I dunno, but you do.
cycles += Emulator.run_to("NEXT")
assert abs((a & 0xFF) - (a >> 8)) == RAM[vars.sysArgs + 0]
assert abs((b >> 8) - (b & 0xFF)) == RAM[vars.sysArgs + 1]
assert ((a >> 8) > (a & 0xFF)) ^ ((b & 0xFF) > (b >> 8)) == RAM[vars.vAC]
assert int.from_bytes(
RAM[vars.sysFn : vars.sysFn + 2], "little", signed=False
) == asm.symbol("SYS_MultiplyBytes_120")
assert RAM[vars.vAC] == RAM[vars.vAC + 1]
assert cycles == MAX_CYCLES
assert cycles == _sign_extend(Emulator.AC) * -2
def test_timing_both_overflow():
"""Follow the routine through, checking the timing comments
This follows the case where both subtractions result in a negative number:
the high byte of vAC is bigger than the low, and
the low byte of sysArgs[0:2] is bigger than the high.
"""
RAM[vars.sysArgs : vars.sysArgs + 2] = 0x00FF.to_bytes(2, "little", signed=False)
RAM[vars.vAC : vars.vAC + 2] = 0xFF00.to_bytes(2, "little", signed=False)
# fmt: off
cycles = 9 # On entry to SYS, 9 cycles have already elapsed
cycles += Emulator.run_to("SYS_KaratsubaPrepare_54"); assert 14 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sysKaratsubaPrepare#18"); assert 17 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sysKaratsubaPrepare#21"); assert 20 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sysKaratsubaPrepare#35"); assert 34 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("REENTER"); assert 51 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("NEXT"); assert 53 == cycles # noqa: E702, E241, E272
# fmt: on
def test_timing_neither_overflow():
"""Follow the routine through, checking the timing comments
This follows the case where both subtractions result in a positive number:
the low byte of vAC is bigger than the high, and
the high byte of sysArgs[0:2] is bigger than the low.
"""
RAM[vars.sysArgs : vars.sysArgs + 2] = 0xFF00.to_bytes(2, "little", signed=False)
RAM[vars.vAC : vars.vAC + 2] = 0x00FF.to_bytes(2, "little", signed=False)
# fmt: off
cycles = 9 # On entry to SYS, 9 cycles have already elapsed
cycles += Emulator.run_to("SYS_KaratsubaPrepare_54"); assert 14 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sysKaratsubaPrepare#21"); assert 20 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sysKaratsubaPrepare#35"); assert 34 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("REENTER"); assert 51 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("NEXT"); assert 53 == cycles # noqa: E702, E241, E272
# fmt: on
@@ -0,0 +1,101 @@
import os.path
import pathlib
from importlib import reload
from types import SimpleNamespace
import gcl0x as gcl
from hypothesis import given
from hypothesis import strategies as st
import asm
from gtemu import RAM, Emulator
ROOT = (pathlib.Path(__file__).parent / "..").resolve()
SCRIPT = ROOT / "sys" / "ROM.asm.py"
GCL = ROOT / "mandelbrot" / "Mandelbrot.gcl"
def setup_module():
global vars, symbol_table, execution_address
"""Load the Emulator from the ROM script and Mandelbrot
"""
reload(asm)
name, _ = os.path.splitext(os.path.basename(SCRIPT))
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": name}
with SCRIPT.open("rb") as file:
exec(compile(file.read(), SCRIPT, "exec"), script_globals)
Emulator.load_rom_from_asm_module()
vars = SimpleNamespace(**script_globals)
# This sequence of calls is roughly taken from compilegcl.py
old_rom_size = asm._romSize
program = gcl.Program("Mandelbrot", forRom=False)
user_code = asm.symbol("userCode")
user_vars = asm.symbol("userVars")
program.org(user_code)
asm.align(1)
asm.zpReset(user_vars)
with GCL.open("r", encoding="utf-8") as fp:
for line in fp.readlines():
program.line(line)
program.end()
asm.end()
# Copy the resulting data straight into RAM, in the appropriate blocks
data = asm.getRom1()[old_rom_size:]
index, more_data = 0, bool(data)
while more_data:
start_address = int.from_bytes(data[index : index + 2], "big", signed=False)
index += 2
size = data[index] or 256
index += 1
chunk = data[index : index + size]
index += size
RAM[start_address : start_address + len(chunk)] = chunk
more_data = data[index]
execution_address = program.execute
symbol_table = program.vars
def _prepare_for_vcpu_execution_at(execution_address):
Emulator.AC = 127
Emulator.next_instruction = "ENTER"
RAM[vars.vReturn] = vars.videoZ & 0xFF
RAM[vars.vCpuSelect] = Emulator.next_instruction >> 8
Emulator.vLR = execution_address
Emulator.vPC = execution_address & 0xFF00 | (execution_address - 2) & 0xFF
def _call_vcpu_function(variable):
return_point = Emulator.vPC & 0xFF00 | (Emulator.vPC + 2) & 0xFF
Emulator.AC = symbol_table[variable]
Emulator.next_instruction = "CALL"
Emulator.step_vcpu() # Execute CALL
Emulator.run_vcpu_to(return_point)
def _write_word(address, value, *, signed):
RAM[address : address + 2] = value.to_bytes(2, "little", signed=signed)
def _read_word(address, *, signed):
return int.from_bytes(RAM[address : address + 2], "little", signed=signed)
_signed_ints_with_12bit_range = st.integers(
min_value=-(1 << 11), max_value=(1 << 11) - 1
)
@given(a=_signed_ints_with_12bit_range, b=_signed_ints_with_12bit_range)
def test_MulShift8(a, b):
_prepare_for_vcpu_execution_at(execution_address)
Emulator.run_vcpu_to(0x300) # Run the first page, so the variable is defined
_write_word(vars.sysFn, asm.symbol("SYS_MultiplyBytes_120"), signed=False)
_write_word(symbol_table["A"], a, signed=True)
_write_word(symbol_table["B"], b, signed=True)
_call_vcpu_function("MulShift8")
assert int(a * b / 256) == _read_word(vars.vAC, signed=True)
@@ -0,0 +1,141 @@
import math
import os.path
import pathlib
from importlib import reload
from types import SimpleNamespace
from hypothesis import given
from hypothesis import strategies as st
import asm
from gtemu import RAM, Emulator
SRC_DIR = (pathlib.Path(__file__).parent / ".." / "src").resolve()
SCRIPT = SRC_DIR / "quarter-square.asm.py"
def setup_module():
global vars
"""Load the Emulator from the multiplication script"""
reload(asm)
name, _ = os.path.splitext(os.path.basename(SCRIPT))
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": name}
with SCRIPT.open("rb") as file:
exec(compile(file.read(), SCRIPT, "exec"), script_globals)
Emulator.load_rom_from_asm_module()
vars = SimpleNamespace(**script_globals)
_bytes = st.integers(min_value=0, max_value=255)
@given(value=_bytes)
def test_low_byte_lookup(value):
"""Lookup of the low-byte of a quarter square should work"""
Emulator.Y = asm.symbol("Quarter-squares lookup table") >> 8
Emulator.AC = value
Emulator.next_instruction = "low-byte table entry"
cycles = Emulator.run_to("low-byte return point")
assert int(math.floor((value**2) / 4)) & 0xFF == Emulator.AC
assert vars.cost_of_low_byte_table_entry == cycles
@given(value=_bytes)
def test_high_byte_lookup(value):
"""Lookup of the high-byte of a quarter square should work"""
RAM[vars.high_byte_action] = asm.symbol("high-byte action.store")
Emulator.AC = value
Emulator.Y = asm.symbol("Quarter-squares lookup table") >> 8
Emulator.next_instruction = "table entry"
cycles = Emulator.run_to("high-byte action.store")
assert int(math.floor((value**2) / 4)) >> 8 == Emulator.AC
assert vars.cost_of_high_byte_table_entry == cycles
_seven_bit_integers = st.integers(min_value=0, max_value=127)
@given(a=_seven_bit_integers, b=_seven_bit_integers)
def test_both_byte_lookup(a, b):
"""Lookup of both bytes of a quarter square should work
The multiplication routine actually adds 1 to the result,
so storing it, so check for that.
"""
RAM[vars.a] = a
RAM[vars.b] = b
Emulator.next_instruction = "multiply 7x7"
expected = int(math.floor(((a + b) ** 2) / 4)) + 1
cycles = Emulator.run_to(asm.symbol(".after-first-lookup") + 2)
assert expected == int.from_bytes(
RAM[vars.result : vars.result + 2], "little", signed=False
)
assert cycles == vars.cost_after_first_lookup + 2
assert asm.symbol("Quarter-squares lookup table") >> 8 == Emulator.Y
@given(
a=_seven_bit_integers,
b=_seven_bit_integers,
previous_value=st.integers(min_value=0, max_value=65025),
)
def test_subtract_quarter_square(a, b, previous_value):
"""to done should subtract the"""
RAM[vars.a] = a
RAM[vars.b] = b
RAM[vars.result : vars.result + 2] = (previous_value + 1).to_bytes(
2, "little", signed=False
)
Emulator.Y = asm.symbol("Quarter-squares lookup table") >> 8
Emulator.next_instruction = asm.symbol(".after-first-lookup") + 2
expected = (previous_value - math.floor((a - b) ** 2 / 4)) & 0xFFFF
cycles = Emulator.run_to(asm.symbol("done"))
assert expected == int.from_bytes(
RAM[vars.result : vars.result + 2], "little", signed=False
)
assert asm.symbol("Quarter-squares lookup table") >> 8 == Emulator.Y
assert vars.cost_of_7bit_multiply - vars.cost_after_first_lookup - 2 == cycles
@given(a=_seven_bit_integers, b=_seven_bit_integers)
def test_multiplication_7(a, b):
"""Multiplication of two seven-bit integers should work"""
RAM[vars.a] = a
RAM[vars.b] = b
Emulator.next_instruction = "multiply 7x7"
cycles = Emulator.run_to("done")
result = int.from_bytes(RAM[vars.result : vars.result + 2], "little", signed=False)
assert a * b == result
assert vars.cost_of_7bit_multiply == cycles
@given(a=_bytes, b=_bytes)
def test_multiplication_8(a, b):
"""Multiplication of two eight-bit integers should work"""
Emulator.reset()
RAM[vars.a] = a
RAM[vars.b] = b
Emulator.next_instruction = "multiply 8x8"
expected_saving = (
vars.no_msb_cost_saving
if a < 128 and b < 128
else vars.one_msb_cost_saving
if a < 128 or b < 128
else 0
)
cycles = Emulator.run_to("done")
result = int.from_bytes(RAM[vars.result : vars.result + 2], "little", signed=False)
assert a * b == result
assert vars.cost_of_8bit_multiply - expected_saving == cycles
@@ -0,0 +1,111 @@
"""Tests for the implementation of SYS_MultiplyBytes_126"""
import os.path
import pathlib
from importlib import reload
from types import SimpleNamespace
from hypothesis import given
from hypothesis import strategies as st
import asm
from gtemu import RAM, Emulator
MAX_CYCLES = 120
SYS_DIR = (pathlib.Path(__file__).parent / ".." / "sys").resolve()
SCRIPT = SYS_DIR / "ROM.asm.py"
def setup_module():
global vars
"""Load the Emulator from the ROM script"""
reload(asm)
name, _ = os.path.splitext(os.path.basename(SCRIPT))
script_globals = {"__file__": str(SCRIPT.absolute()), "__name__": name}
with SCRIPT.open("rb") as file:
exec(compile(file.read(), SCRIPT, "exec"), script_globals)
Emulator.load_rom_from_asm_module()
vars = SimpleNamespace(**script_globals)
def setup_function():
RAM[vars.sysFn : vars.sysFn + 2] = asm.symbol("SYS_MultiplyBytes_120").to_bytes(
2, "little"
)
RAM[vars.vTicks] = 75
Emulator.next_instruction = "SYS"
Emulator.AC = 270 - max(14, MAX_CYCLES // 2)
def test_timing_both_lt_128():
"""Follow the routine through, checking the timing comments
This follows the case where both values are less than 128
I'm just trying to check that the comments are correct!
"""
RAM[vars.sysArgs : vars.sysArgs + 2] = 3, 5
# fmt: off
cycles = 9 # On entry to SYS, 9 cycles have already elapsed
cycles += Emulator.run_to("SYS_MultiplyBytes_120"); assert 14 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.tableEntry"); assert 29 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.high-byte-action.store-inverted"); assert 35 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.tableExit"); assert 40 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes#44"); assert 43 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.tableEntry"); assert 51 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.high-byte-action.restore-and-add"); assert 57 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.tableExit"); assert 64 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes#68"); assert 67 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("NEXTY"); assert 90 == cycles # noqa: E702, E241, E272
# fmt: on
def test_timing_neither_lt_128():
"""Follow the routine through, checking the timing comments
This follows the case where neither value is less than 128
"""
RAM[vars.sysArgs : vars.sysArgs + 2] = 172, 160
# fmt: off
cycles = 9 # On entry to SYS, 9 cycles have already elapsed
cycles += Emulator.run_to("sys_MultiplyBytes#68"); assert 67 == cycles # noqa: E702, E241, E272, E221
cycles += Emulator.run_to("sys_MultiplyBytes#92"); assert 91 == cycles # noqa: E702, E241, E272, E221
cycles += Emulator.run_to("sys_MultiplyBytes#114"); assert 113 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("NEXTY"); assert 118 == cycles # noqa: E702, E241, E272
# fmt: on
def test_timing_one_lt_128():
"""Follow the routine through, checking the timing comments
This follows the case where one value is less than 128
"""
RAM[vars.sysArgs : vars.sysArgs + 2] = 3, 160
# fmt: off
cycles = 9 # On entry to SYS, 9 cycles have already elapsed
cycles += Emulator.run_to("sys_MultiplyBytes#68"); assert 67 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes.oneMsbSetCase"); assert 85 == cycles # noqa: E702, E241, E272
cycles += Emulator.run_to("sys_MultiplyBytes#92"); assert 91 == cycles # noqa: E702, E241, E272
# fmt: on
def _sign_extend(byte_):
if byte_ & 0x80:
return ~0xFF | byte_
return byte_
_bytes = st.integers(min_value=0, max_value=255)
@given(a=_bytes, b=_bytes)
def test_multiply_bytes(a, b):
setup_function()
RAM[vars.sysArgs : vars.sysArgs + 2] = a, b
cycles = 10 # Because Next is marked as zero
cycles += Emulator.run_to("NEXT")
assert cycles <= MAX_CYCLES
assert cycles == _sign_extend(Emulator.AC) * -2
assert a * b == Emulator.vAC
+7
View File
@@ -0,0 +1,7 @@
[flake8]
ignore = E203, E266, E501, W503, E231, E731
# line length is intentionally set to 80 here because black uses Bugbear
# See https://github.com/psf/black/blob/master/README.md#line-length for more details
max-line-length = 80
select = B,C,E,F,W,T4,B9
+14
View File
@@ -0,0 +1,14 @@
/.venv/
/_gtemu.c
_gtemu*.pyd
/Release/
/roms/
/*.exe
/*.obj
.vscode
/install-test/
/build/
/py_gtemu.egg-info/
/dist/
/.eggs/
/.pypy-venv/
+89
View File
@@ -0,0 +1,89 @@
# py-gtemu: A Python extension, wrapping gtemu.c for testing and debugging
gtemu is a module which exposes the Gigatron emulator in gtemu.c to Python. It is meant to be useful for testing and debugging Gigatron software written using a Python-based toolchain. It has grown out my effort to make a native Forth implementation for the Gigatron. It uses an extension module (_gtemu) which is built using cffi, and provides a high-level API on top of that.
## Core functionality
The main entry-point to the module is an object called `Emulator`. This is a singleton - there is only meant to be one instance of this. This is because the C source uses static arrays for the RAM and ROM, and so we can't have multiple emulators at the same time. Perhaps this should be changed in future, but I quite like that I'm using the unmodified C source, even if it was never meant to be used like this.
`Emulator` provides low-level methods to single-step, run for a number of cycles, run up to a certain address, to set and get the next execution address, and get and set any of the registers (these are properties, so `Emulator.AC` etc.). There are also objects in the module ROM and RAM which expose the data.
There are also higher-level methods which make certain assumptions about the software in the ROM, these include running up to the next horizontal and vertical blank period, emulating sending a byte of data in through the game controller port for one frame only, and reading serial output sent with SYS_SendSerial_v3_80.
The Emulator also has some support for the vCPU: you can single-step, run up to a certain address, get and set any of the (virtual) registers. This could probably be much improved.
The Emulator object has a flag called _print. When this is set to True, many methods will print a representation of the relevant emulator state on completion. This is useful for debugging. The string that they print is always accessible through the `Emulator.state` and `Emulator.vcpu_state` properties.
Look at the source in gtemu.py for a list of the available methods.
### Unit testing Gigatron code
The main usecase is to enable unit-testing of Gigatron code for a better development cycle. I use pytest for unit testing, often with Hypothesis for test case generation, but those details are not vital.
This usually follows a normal Arrange, Act, Assert process, where the arrange phase sets up the emulator state, the act phase runs the emulator, and the assert phase verifies that whatever the code was meant to do has been done, usually by reading the RAM and registers.
The following is output from pytest when a test fails. The Gigatron program under test is an echo function, that writes to, and then reads from a ring buffer. You can see that it has a bug.
```
def test_write():
assert _read_bytes(5) == b"READY"
for b in b"Hello":
Emulator.send_byte(b)
> assert _read_bytes(5) == b"Hello"
E AssertionError: assert b'\x00Hell' == b'Hello'
E At index 0 diff: b'\x00' != b'H'
E Use -v to get the full diff
tests\test_io.py:40: AssertionError
```
For a more complete example of usage,
see the tests in Contrib/psr/multiply,
which demonstrates use in native and vCPU code.
You can look at my Forth for more - although in Forth I've written a lot of wrappers, so the use may not be so obvious.
### Debugging Gigatron code
This module is not (yet) a fully fledged debugger. If that is what you need, perhaps at67's tools might be a better fit.
However when hitting a failing test, its very useful to drop into pdb, set `Emulator._print = True` and run `Emulator.step()` or other methods repeatedly (pdb repeats the last command if you just press enter). This gives a very debugger like experience.
## API stability
The interface has been driven solely by my needs, and I make no promises not to change it in future. Sorry! However if you're using this module in your tests, and they are available publicly, let me know and I'll endeavour not to break your tests, or perhaps provide pull-requests to update them.
## Build / Installation
In order to build the module you need to have Python 3.6 or later, the headers for your Python, a C compiler and the C library headers. The build also depends on a Python package called CFFI, but *I think* you shouldn't need to do anything about that.
On Debian or Ubuntu, running `apt-get install build-essential python3-dev python3-pip python3-venv` should get you what you need.
On Windows I think it's sufficient to install Python from Python.org or the Microsoft Store and the Visual Studio Build Tools from the Visual Studio Installer. I believe that this is free. If you already have Visual Studio installed, you don't need to install the build tools.
On other platforms, I'm afraid you're on your own.
As always when working with external dependencies with Python it is very strongly advisable to use an isolated Python environment to avoid messing up your Python installation, particularly on Linux distributions where it is a core part of your operating system.
Once you have these dependencies in place, you should be to run `python setup.py install` from within this directory to install the modules. Don't use pip to install it (at least not from source); because we assume that this directory is part of a full Gigatron source tree - i.e. gtemu.c is in ../../../Docs/, pip's current policy of copying the source tree doesn't work for us.
The extension module assumes that asm.py is on the module search path, as it uses this for disassembly (and referencing symbols - but that only works under special circumstances).
For development of py-gtemu itself you will need to install cffi with pip, and to run the tests pytest as well. Check psakefile.ps1 to see how I manage this - even if you don't use psake to build, it should give the right idea.
Note: The tests don't currently pass!
## Development
This was spun out from the Forth project when I needed to add the ability to test routines that perform serial IO. The code I added to read the serial output was complicated enough that I was sure it would have bugs, and I couldn't really debug both the system under test and the test harness at the same time. That explains why that is the only area with anything like test coverage.
My idea was to have various GCL programs which could be built in to complete ROM images by making them the Main entry point, as I have with echo.gcl. psakefile.ps1 contains code to generate a ROM from each .gcl file in the scripts directory, and the tests can then load these.
## Future developments
The following might be worth doing in future:
* Finish the Echo tests.
* A Makefile for Linux / macOS development.
* The ability to capture and restore emulator state for better fixtures
* Make a full PDB style debugger, using the cmd module. This should be pretty easy.
* A pytest plugin.
* Some Hypothesis integration: I currently use pytest fixtures, but Hypothesis warns that they're not compatible. Actually the 'incompatible' behaviour is perfectly fine for me, but it would be possible to do better.
+2
View File
@@ -0,0 +1,2 @@
# This file is purely present to make the pytest command
# recognise that this directory should be on the import path
+709
View File
@@ -0,0 +1,709 @@
"""Python wrapper for the gtemu emulator
"""
import itertools
from contextlib import contextmanager
import asm
import _gtemu
__all__ = ["Emulator", "RAM", "ROM"]
_BLANK_RAM = bytearray([0 for _ in range(1 << 15)])
def _make_state_field_accessor(name):
"""Return a descriptor that accesses the fields of the state"""
def _getter(self):
state = self._state
return getattr(state, name)
def _setter(self, value):
state = self._state
setattr(state, name, value)
return property(
_getter,
_setter,
doc=f"Get or set the current state of the {name} register",
)
def _make_zero_page_accessor(
name, address, *, width=2, byteorder="little", signed=False
):
"""Return a descriptor that accesses zero-page memory"""
def _getter(self):
return int.from_bytes(
RAM[address : address + width], byteorder=byteorder, signed=signed
)
def _setter(self, value):
RAM[address : address + width] = value.to_bytes(
width, byteorder=byteorder, signed=signed
)
return property(
_getter, _setter, doc=f"Get or set the current state of the {name} register"
)
def _to_address(address_or_symbol):
"""Convert a value that may be an address or a symbol, to an address
Labels are the most likely symbols we encounter"""
from_symbol = asm.symbol(address_or_symbol)
if from_symbol is not None:
address = from_symbol
else:
try:
address = int(address_or_symbol)
except (TypeError, ValueError):
raise ValueError(
f"{address_or_symbol:r} is not a valid address or symbol"
)
if not (0 <= address < (1 << 16)):
raise ValueError(f"{address:x} is out of range for an address")
return address
# When stepping the vCPU where must we stop.
# TODO: We should probably be loading these from asm.py
_STEP_VCPU_BREAKPOINTS = frozenset(
[
0x02FF, # ENTER
0x0301, # NEXT
]
)
# Maximum latency between vCPU instructions if nothing goes wrong.
# TODO: Find the right value, needs to work if we're in slow (rendering all four lines) mode.
_STEP_VCPU_MAX_CYCLES = 1000 # It should be possible to calculate a more precise value
class _Emulator:
"""Provides programatic control over the Gigatron Emulator"""
def __init__(self):
self.reset()
def load_rom_file(self, path):
with open(path, "rb") as fp:
fp.readinto(_gtemu.ffi.buffer(ROM))
def load_rom_from_asm_module(self):
"""Populates the ROM from the contents of the asm module
This requires that an assembly script has already been executed.
"""
def gen_rom_data():
for opcode, operand in zip(asm._rom0, asm._rom1):
yield opcode
yield operand
rom_data = bytearray(gen_rom_data())
_gtemu.ffi.buffer(ROM)[0 : len(rom_data)] = rom_data
def reset(self):
self._state = _gtemu.ffi.new("CpuState *")[0]
self._last_pc = None
self._print = False
self._vga_x = 0
self._vga_y = 0
self._xout = 0
self.breakpoints = set()
_gtemu.ffi.buffer(RAM)[:] = _BLANK_RAM
# Needed for bit shuffling
_gtemu.ffi.buffer(RAM)[0b1000_0000] = b"\x01"
PC = _make_state_field_accessor("PC")
IR = _make_state_field_accessor("IR")
D = _make_state_field_accessor("D")
AC = _make_state_field_accessor("AC")
X = _make_state_field_accessor("X")
Y = _make_state_field_accessor("Y")
OUT = _make_state_field_accessor("OUT")
@property
def XOUT(self):
"""State of the eXtended OUTput register
This is set from AC when the hsync signal is low
"""
return self._xout
@property
def hsync(self):
"""Return the state of the HSYNC signal.
True is high, and False is low, but remember this is an active low signal"""
return bool(self.OUT & _HSYNC)
@property
def vsync(self):
"""Return the state of the VSYNC value.
True is high, and False is low, but remember this is an active low signal"""
return bool(self.OUT & _VSYNC)
@property
def next_instruction(self):
"""Get the address of the next instruction to execute"""
return self._last_pc
@next_instruction.setter
def next_instruction(self, address):
"""Set program execution to proceed from `address`
This sets the PC to address + 1, having loaded the instruction at address,
as if we had just executed address - 1.
"""
# To start from an address, we need to fill the pipeline with the instruction at address
# and set PC to address + 1.
address = _to_address(address)
self.PC = address + 1
self.IR = _gtemu.lib.ROM[address][0]
self.D = _gtemu.lib.ROM[address][1]
self._last_pc = address
@property
def state(self):
"""Return a string representation of the current state"""
registers = [
("PC", 2),
("IR", 1),
("D", 1),
("AC", 1),
("X", 1),
("Y", 1),
("OUT", 1),
("XOUT", 1),
]
heading = " ".join(
[r.rjust(w * 2 + 1) for r, w in registers] + ["Loaded instruction"]
)
separator = " ".join(
["-" * (2 * w + 1) for _, w in registers] + ["------------------"]
)
values = " ".join(
[("${:0%dx}" % (w * 2,)).format(getattr(self, r)) for r, w in registers]
+ [asm.disassemble(self.IR, self.D)]
)
return "\n".join([heading, separator, values])
def _step(self):
"""Run a single step of the interpreter"""
# Store the current PC, so that we can return it as next_instruction
# This is needed because of the pipeline
self._last_pc = self.PC
old_state = self._state
self._state = new_state = _gtemu.lib.cpuCycle(self._state)
# Detect changes in the vertical and horizontal sync signals
hsync_edge = (new_state.OUT & _HSYNC) - (old_state.OUT & _HSYNC)
vsync_edge = (new_state.OUT & _VSYNC) - (old_state.OUT & _VSYNC)
# TODO: It might be nice to detect timing errors - but it's tricky because the ROM
# doesn't go straight into standard timings.
# We keep these values in order to support run_to_vsync and run_to_hsync
self._vga_x += 1
if vsync_edge < 0:
self._vga_y = -36
if hsync_edge > 0:
self._vga_x = 0
self._vga_y += 1
self._xout = self.AC
def step(self):
self._step()
if self._print:
print(self.state)
def _run_for(self, instructions):
for i in range(instructions):
self._step()
if self._last_pc in self.breakpoints:
return i + 1
return instructions
def run_for(self, instructions):
"""Run the emulator for a fixed number of cycles
Will stop at breakpoints if they are hit,
but always executes at least one cycle
Returns the number of cycles executed.
"""
try:
self._run_for(instructions)
finally:
if self._print:
print(self.state)
def _run_to_breakpoint(self, max_instructions):
cycles = self._run_for(max_instructions)
if self._last_pc not in self.breakpoints:
raise ValueError("timeout")
return cycles
def run_to(self, address, max_instructions=1000):
"""Run the emulator until it is about to execute the instruction at `address`
Due to the pipeline, this means that for the previous instruction PC was `address`,
and therefore we have loaded the instruction.
Will stop at breakpoints if they are hit,
but always executes at least one cycle
"""
address = _to_address(address)
iterator = (
range(max_instructions)
if max_instructions is not None
else itertools.count()
)
try:
for i, _ in enumerate(iterator):
self._step()
if self._last_pc == address or self._last_pc in self.breakpoints:
return i + 1
raise ValueError(
"Did not hit address in %d instructions" % (max_instructions,)
)
finally:
if self._print:
print(self.state)
def run_to_hblank(self):
"""Run the emulator until we get to the next horizontal blank period
This is the "front-porch" period which follows the visible pixels
and preceeds the hsync signal going low
If we are already in the hblank period, we advance to the following one
"""
# Counting from the rising edge of HSYNC, there are
# (48 / 4) back porch pixels
# + (640 / 4) visible pixels
# Before we blank
hblank_start = 48 / 4 + 640 / 4 # = 172
# Skip through current blank
while self._vga_x > hblank_start:
self._step()
while self._vga_x < hblank_start:
self._step()
if self._print:
print(self.state)
def run_to_vblank(self):
"""Run the emulator until we get to the next vertical blank period
This is the "front-porch" period which follows the visible lines
and preceeds the vsync signal going low
If we are already in the vblank period, we advance to the following one
"""
# Our counter starts from -36, following the code in gtemu.c, and so
# we can just need to wait until we hit line 480
# If we are currently in a vertical blank interval, advance through it.
# the caller wants the next one
while self._vga_y > 480:
self._step()
while self._vga_y < 480:
self._step()
if self._print:
print(self.state)
@contextmanager
def additional_breakpoints(self, *additional_breakpoints):
"""Returns a context manager which will add breakpoints on entry and restore them on completion
Additional_breakpoints can be a single collection or multiple arguments.
Note, this swaps out and restores the breakpoint set on exit.
To prevent breakpoints being added and lost when the context expires, a frozenset is used.
"""
# This approach is basically meant to optimise for the vCPU step usecase
existing_breakpoints = self.breakpoints
try:
additional_breakpoints = frozenset(*additional_breakpoints)
except TypeError:
additional_breakpoints = frozenset(additional_breakpoints)
self.breakpoints = (
additional_breakpoints | existing_breakpoints
if existing_breakpoints
else additional_breakpoints
)
try:
yield
finally:
self.breakpoints = existing_breakpoints
# vCPU related methods
vPC = _make_zero_page_accessor("vPC", 0x16)
vAC = _make_zero_page_accessor("vAC", 0x18)
vLR = _make_zero_page_accessor("vLR", 0x1A)
vSP = _make_zero_page_accessor("vSP", 0x1C, width=1)
@property
def vcpu_state(self):
registers = [
("vPC", 2),
("vAC", 2),
("vLR", 2),
("vSP", 1),
]
heading = " ".join(
[r.rjust(w * 2 + 1) for r, w in registers] + ["Next instruction"]
)
separator = " ".join(
["-" * (2 * w + 1) for _, w in registers] + ["----------------"]
)
values = " ".join(
[("${:0%dx}" % (w * 2,)).format(getattr(self, r)) for r, w in registers]
+ [_disassemble_vcpu_next()]
)
return "\n".join([heading, separator, values])
def step_vcpu(self):
"""Run the emulator up to NEXT or ENTER.
Returns the number of machine instructions exectuted.
Does stop at breakpoints if they are set.
The method name is slightly misleading.
It will always complete the currently executing instruction if there is one,
but it doesn't follow that it leaves us in a state where we're about to execute the next one.
We might instead be about to return to the display loop,
or the next instruction might be a SYS function which doesn't have time to execute.
It might therefore take several call to see a change in vPC.
"""
try:
with self.additional_breakpoints(_STEP_VCPU_BREAKPOINTS):
return self._run_to_breakpoint(_STEP_VCPU_MAX_CYCLES)
finally:
if self._print:
print(self.vcpu_state)
def run_vcpu_to(self, address, *, always_run_some_code=True):
"""Run the emulator until we are at NEXT or ENTER, before vPC is advanced to address.
Returns the number of machine instructions exectuted.
Does stop at breakpoints if they are set.
This will always run some code if always_run_some_code is True (the default),
even if the vPC is already in the desired state,
to allow repeated calls in a loop.
See the docstring for step_vcpu for further caveats.
"""
# Before we run the instruction at 0x200, vPC should be 0x2fe,
# Because only the low byte is incremented
target_vpc = address & 0xFF00 | (address - 2) & 0xFF
cycles = 0
try:
with self.additional_breakpoints(_STEP_VCPU_BREAKPOINTS):
while always_run_some_code and self.vPC == target_vpc:
cycles += self._run_to_breakpoint(_STEP_VCPU_MAX_CYCLES)
if self._last_pc not in _STEP_VCPU_BREAKPOINTS:
return cycles
while self.vPC != target_vpc:
cycles += self._run_to_breakpoint(_STEP_VCPU_MAX_CYCLES)
if self._last_pc not in _STEP_VCPU_BREAKPOINTS:
return cycles
return cycles
finally:
if self._print:
print(self.vcpu_state)
def send_byte(self, value):
"""Send a byte through the input port"""
# While communication to the Gigatron is serial,
# it's captured by a shift register, and is presented as a byte
# so for our purposes we can just write the byte.
#
# The shift register is read once per vertical refresh
# so wait until vsync goes low, write the value and hold it
# through the rising edge round to the next falling edge
while self.OUT & _VSYNC:
self._step()
_IN[0] = value
while not (self.OUT & _VSYNC):
self._step()
while self.OUT & _VSYNC:
self._step()
_IN[0] = 0xFF # Restore to the initial value
def read_serial(self, *, bits):
"""Read a single serial value through the output port
Returns the value read and the number of bits that were read
"""
# Conversely, from an architectural point of view, the Gigatron has a single 8-bit
# output port, which is written as a byte. However this drives multiple output devices.
# Primarily the display, of course, but the /HSYNC signal also clocks the XOUT register
# (which copies the value of the accumulator) for the LEDS and sound
# and also the game controller port.
# The way in which serial output works is actually modulating the duration of the
# /VSYNC pulse, which can be counted in terms of /HSYNC pulses.
# 8 is the default length and so can be interpretted as no data transmission,
# but it is shortened to 7 for a zero bit, and stretched to 9 for a 1.
# This code is kinda complicated
def generate_outputs():
"""Step the emulator yielding OUT"""
while True:
yield self.OUT
self._step()
# create two generators yielding just the vsync and hsync bits.
# The place value doesn't matter because we're going to edge-detect
# and only look at sign.
_outs1, _outs2 = itertools.tee(generate_outputs())
vsyncs, hsyncs = (o & _VSYNC for o in _outs1), (o & _HSYNC for o in _outs2)
def detect_edges(gen):
"""Yield positive numbers for rising edges, and negative for falling"""
# Pairwise iteration
a, b = itertools.tee(gen)
next(b, None)
for prev, curr in zip(a, b):
yield curr - prev
def debug_detect_edges_short(edges):
"""Useful routine to use when debugging the code below"""
for value in edges:
if value < 0:
print("v", end="")
elif value > 0:
print("^", end="")
yield value
def debug_detect_edges(edges):
"""Useful routine to use when debugging the code below"""
state = "X"
for i, value in enumerate(edges):
if i % 6400 == 0:
print("\n", self.state)
print("\n", self.vcpu_state)
elif i % 80 == 0:
print()
if value == 0:
print(state, end="")
elif value < 0:
state = "_"
print("\\", end="")
else:
state = "‾"
print("/", end="")
yield value
# vsync_edges, hsync_edges = (
# debug_detect_edges_short(detect_edges(vsyncs)),
# debug_detect_edges(detect_edges(hsyncs)),
# )
vsync_edges, hsync_edges = detect_edges(vsyncs), detect_edges(hsyncs)
def do_line_counting(vsync_edges, hsync_edges):
"""Yield count of lines in each negative vsync pulse"""
pairs = zip(vsync_edges, hsync_edges)
while True:
# Advance to falling edge
i = itertools.dropwhile(lambda pair: pair[0] >= 0, pairs)
# .. and continue until we see a rising edge
i = itertools.takewhile(lambda pair: pair[0] <= 0, i)
# count falling HSYNC edges within this window
yield sum(1 for _, h_edge in i if h_edge < 0)
lines_per_vsync = do_line_counting(vsync_edges, hsync_edges)
def debug_counting(lines_per_vsync):
"""useful routine when debugging the code below"""
for frame, hsync_edges in enumerate(lines_per_vsync):
print(f"Frame {frame} has {hsync_edges} line vsync pulse")
yield hsync_edges
# lines_per_vsync = debug_counting(lines_per_vsync)
# Skip frames with 8 line VSYNC signals
lines_per_vsync = itertools.dropwhile(lambda count: count == 8, lines_per_vsync)
# and continue until we return to 8
lines_per_vsync = itertools.takewhile(lambda count: count != 8, lines_per_vsync)
# Data is sent in little-endian order.
# So a 1 in the first frame represents 1
# and a 1 in the second frame represents 2
result = 0
for bit_number, lines in enumerate(lines_per_vsync):
assert lines in (7, 9), f"Unexpected VSYNC length {lines}"
if lines == 7:
value = 0
if lines == 9:
value = 1 << bit_number
result |= value
if bit_number == bits - 1:
break
else:
# We did not see the expected number of bits in the transmission
raise AssertionError(f"Only saw {bit_number} bits in the transmission")
return result
_VSYNC = 0b1000_0000
_HSYNC = 0b0100_0000
# This is effectively a pointer to the IN global variable, which can be
# Updated through list assignment.
_IN = _gtemu.ffi.addressof(_gtemu.lib, "IN")
RAM = _gtemu.lib.RAM
ROM = _gtemu.lib.ROM
Emulator = _Emulator()
# Little vCPU disassembler copied from gt1dump.py
def _disassemble_vcpu_next():
"""Return the string disassembly of the next instruction"""
# The next vPC is not Emulator.vPC + 2 - it doesn't carry into the high byte
next_vpc = Emulator.vPC & 0xFF00 | ((Emulator.vPC + 2 & 0xFF))
opcode = RAM[next_vpc]
# If we don't know a mnemonic, just use hex - no operands
mnemonic, number_of_operands = _OPCODES.get(opcode, (f"${opcode:02x}", 0))
asm_parts = [mnemonic]
operands = bytearray(RAM[next_vpc + 1 : next_vpc + 1 + number_of_operands])
while operands:
# Poor man's switch statement
if mnemonic in _ZP_MODE_OPCODES:
operand = operands.pop(0)
decoding = _ZERO_PAGE_SYMBOLS.get(operand, f"${operand:02x}")
asm_parts.append(decoding)
continue
if mnemonic == "Bcc":
operand = operands.pop(0)
if operand in _BCC_CODES:
asm_parts = [f"B{_BCC_CODES[operand]}"]
# Fall through
if mnemonic in {"Bcc", "BRA", "DEF"}:
# Next operand is a target within a page
operand = operands.pop(0)
target = next_vpc & 0xFF00 | (operand + 2) & 0xFF
asm_parts.append(f"${target:04x}")
continue
if mnemonic == "SYS":
operand = operands.pop(0)
if operand != 128:
max_cycles = 28 - 2 * ((operand ^ 128) - 128)
asm_parts.append(str(max_cycles))
else:
asm_parts = ["HALT"]
continue
# Else...
# Treat any remaining bytes as a single operand
operand = int.from_bytes(operands, "little", signed=False)
asm_parts.append(f"${operand:02x}" if len(operands) == 1 else f"${operand:04x}")
break
return " ".join(asm_parts)
_OPCODES = {
0x11: ("LDWI", 2),
0x1A: ("LD", 1),
0x1F: ("CMPHS", 1),
0x21: ("LDW", 1),
0x2B: ("STW", 1),
0x35: ("Bcc", 2),
0x59: ("LDI", 1),
0x5E: ("ST", 1),
0x63: ("POP", 0),
0x75: ("PUSH", 0),
0x7F: ("LUP", 1),
0x82: ("ANDI", 1),
0x85: ("CALLI", 2),
0x88: ("ORI", 1),
0x8C: ("XORI", 1),
0x90: ("BRA", 1),
0x93: ("INC", 1),
0x97: ("CMPHU", 1),
0x99: ("ADDW", 1),
0xAD: ("PEEK", 0),
0xB4: ("SYS", 1),
0xB8: ("SUBW", 1),
0xCD: ("DEF", 1),
0xCF: ("CALL", 1),
0xDF: ("ALLOC", 1),
0xE3: ("ADDI", 1),
0xE6: ("SUBI", 1),
0xE9: ("LSLW", 0),
0xEC: ("STLW", 1),
0xEE: ("LDLW", 1),
0xF0: ("POKE", 1),
0xF3: ("DOKE", 1),
0xF6: ("DEEK", 0),
0xF8: ("ANDW", 1),
0xFA: ("ORW", 1),
0xFC: ("XORW", 1),
0xFF: ("RET", 0),
}
_BCC_CODES = {
0x3F: "EQ",
0x4D: "GT",
0x50: "LT",
0x53: "GE",
0x56: "LE",
0x72: "NE",
}
_ZERO_PAGE_SYMBOLS = {
0x00: "zeroConst",
0x01: "memSize",
0x06: "entropy",
0x09: "videoY",
0x0E: "frameCount",
0x0F: "serialRaw",
0x11: "buttonState",
0x14: "xoutMask",
0x16: "vPC",
0x17: "vPC+1",
0x18: "vAC",
0x19: "vAC+1",
0x1A: "vLR",
0x1B: "vLR+1",
0x1C: "vSP",
0x21: "romType",
0x22: "sysFn",
0x23: "sysFn+1",
0x24: "sysArgs+0",
0x25: "sysArgs+1",
0x26: "sysArgs+2",
0x27: "sysArgs+3",
0x28: "sysArgs+4",
0x29: "sysArgs+5",
0x2A: "sysArgs+6",
0x2B: "sysArgs+7",
0x2C: "soundTimer",
0x2E: "ledState_v2",
0x2F: "ledTempo",
0x80: "oneConst",
}
# Opcodes that address page zero
_ZP_MODE_OPCODES = {
"LD",
"LDW",
"STW",
"ST",
"INC",
"ADDW",
"SUBW",
"CALL",
"POKE",
"DOKE",
"ANDW",
"ORW",
"XORW",
"CMPHS",
"CMPHU",
}
@@ -0,0 +1,49 @@
"""CFFI Build script - Tells CFFI how to build the _gtemu extension
Defines the functions and structures that need to be useable from Python
using C syntax, and says where to find the C file that also be compiled and
linked.
"""
import pathlib
from cffi import FFI
# Paths to files elsewhere in the repository
REPO_ROOT = (pathlib.Path(__file__).parent / ".." / ".." / "..").resolve()
GTEMU_C = REPO_ROOT / "Docs" / "gtemu.c"
ffibuilder = FFI()
# These definitions become most of the the API of the extension.
# They're parsed by CFFI, but are in C syntax.
# They're copied from gtemu.c, but in a more typical usage
# they'd be taken from a manpage or other documentation.
ffibuilder.cdef(
"""\
typedef struct { // TTL state that the CPU controls
uint16_t PC;
uint8_t IR, D, AC, X, Y, OUT, undef;
} CpuState;
"""
)
ffibuilder.cdef("extern uint8_t ROM[1<<16][2], RAM[1<<15], IN;")
ffibuilder.cdef("CpuState cpuCycle(const CpuState S);")
ffibuilder.set_source(
"_gtemu", # name of the output C extension
# The same code as above, but this time for including in the generated C.
# More typically this would be a single line that includes a header.
"""\
typedef struct { // TTL state that the CPU controls
uint16_t PC;
uint8_t IR, D, AC, X, Y, OUT, undef;
} CpuState;
CpuState cpuCycle(const CpuState S);
extern uint8_t ROM[1<<16][2], RAM[1<<15], IN;
""",
sources=[str(GTEMU_C)],
libraries=[],
)
if __name__ == "__main__":
ffibuilder.compile(verbose=True)
+105
View File
@@ -0,0 +1,105 @@
$ErrorActionPreference = 'Stop';
# Path of the root of the repository
$REPO_ROOT_PATH = Join-Path $PSScriptRoot '..\..\..' -Resolve
# Python search path for modules
$VENV_DIR = Join-Path $PSScriptRoot '.venv'
$SCRIPT_DIR = Join-Path $VENV_DIR 'Scripts'
$dirExcludes = '.venv', '.pytest_cache', 'install-test', '.pypy-venv', 'build', 'dist'
$filesToFormat = @(get-childitem -Exclude $dirExcludes -Directory | ForEach-Object { get-childitem -path $_ -Recurse -Include '*.py' })
$filesToFormat += @(get-childitem -Name '*.py')
$PACKAGES = 'cffi', 'ipython', 'pytest', 'hypothesis', 'flake8', 'isort', 'black'
task default -depends isort, Blacken, Flake8, Extension, Test
function executeScript($script, $params) {
$scriptPath = Join-Path $SCRIPT_DIR -ChildPath $script
try {
get-item $scriptPath -ErrorAction Stop > $null
}
catch {
Invoke-Task Packages
}
& "$scriptPath" @($params)
if ($LASTEXITCODE -ne 0 ) {
throw "$script failed";
}
}
task isort {
executeScript 'isort.exe' $filesToFormat
}
task Blacken {
executeScript 'black.exe' $filesToFormat
}
task Flake8 {
executeScript 'flake8.exe' ('gtemu.py', 'gtemu_extension_build.py', 'tests')
}
task Virtualenv {
try {
get-item "$VENV_DIR" -ErrorAction Stop > $null
}
catch {
python3 -m venv "$VENV_DIR"
& "$SCRIPT_DIR\python" @('-m', 'pip', 'install', '--upgrade', 'pip')
}
}
task Upgrade-Packages {
executeScript 'pip.exe' (('install', '--upgrade') + $PACKAGES)
}
task Packages -depends VirtualEnv {
executeScript 'pip.exe' (@(, 'install') + $PACKAGES)
}
task Extension {
executeScript python.exe .\gtemu_extension_build.py
if ($LASTEXITCODE -ne 0 ) {
throw "Extension failed"
}
}
task RomFiles {
$testScripts = @(Get-ChildItem -Path 'test-scripts' -Filter '*.gcl' -Recurse )
try {
Push-Location 'roms'
Remove-Item '*.rom', '*.lst'
}
catch {
New-Item 'roms' -Type Directory | Push-Location
}
Copy-Item (Join-Path $REPO_ROOT_PATH 'interface.json')
try {
$testScripts | ForEach-Object {
executeScript python.exe ((Join-Path (Join-Path $REPO_ROOT_PATH 'Core') 'ROMv4.asm.py'), "Reset=$($_.FullName)")
if ($LASTEXITCODE -ne 0 ) {
throw "Failed to generate ROM from $($_.FullName)";
}
Rename-Item ROMv4.rom "$($_.Basename).rom"
Rename-Item ROMv4.lst "$($_.Basename).lst"
}
}
finally {
Pop-Location
}
}
task Test -depends RomFiles {
$oldPythonPath = $env:PYTHONPATH
$env:PYTHONPATH = Join-Path $REPO_ROOT_PATH 'Core'
try {
executeScript 'pytest'
}
finally {
$env:PYTHONPATH = $oldPythonPath
}
}
+17
View File
@@ -0,0 +1,17 @@
import pathlib
from setuptools import setup
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / "README.md").read_text(encoding="utf-8")
setup(
name="py-gtemu",
version="0.1a20210930",
setup_requires=["cffi>=1.0.0"],
cffi_modules=["gtemu_extension_build.py:ffibuilder"],
install_requires=["cffi>=1.0.0"],
python_requires=">=3.6, <4",
py_modules=["gtemu"],
)
@@ -0,0 +1,84 @@
{
Echo Test
---------
When this program is loaded as the Reset script for the Gigatron
then all that the Gigatron will do is read input from the serial port
and echo it back out again using SYS_SendSerial1_v3_80.
It maintains a circular buffer of size 128, which is initialised with the bytes
'READY'.
It is intended to support testing of the gtemu.py sending and recieving code.
Logic copied from https://www.snellman.net/blog/archive/2016-12-13-ring-buffers/
I think this is right - I'm really using 8-bit unsigned counters, but combining with
a second byte to make an array index (the array is at a page boundary)
}
gcl0x
{ Change into default video mode - Needs to happen on system boot }
\SYS_SetMode_v2_80 _sysFn=
1 80!! {Mode 1 -> "ABC-"}
{ Convert vAC into a valid index, zeroing the MSB of the low-byte }
$ff7f Mask=
{ vAC is non-zero if there is anything in the buffer }
[def ReadPointer WritePointer^ ret] NonEmpty=
{ Number of bytes in the buffer }
[def WritePointer ReadPointer- ret] Size=
{ vAC is zero if the buffer is full }
[def push Size! $80^ pop ret] NonFull=
{ Add byte to buffer if it is not full. If it is full overwrite last byte written with $00 to show an overflow }
[def push
data=
NonFull! [ if=0
$00 data=
else
<WritePointer++ { Increment low-byte of WritePointer }
]
WritePointer Mask& address= { Mask WritePointer and store in address }
data address. { Load original value and store through newly calculated pointer}
pop ret
] Push=
{ Write all available bytes out of the output port }
[ def push
[ do
NonEmpty! [ if=0 pop ret ] { return straight away with 0 exit if there's nothing to send }
{ Technically we can send up to 31 bytes in a go }
{ However we need to watch the wrap around }
{ and anyway, we're not really trying to test SYS_SendSerial1_v3_80 }
ReadPointer Mask& \sysArgs0: { Pointer to read from }
1 \sysArgs2. { Starting at bit one }
8 \sysArgs3. { Transmit 8 bits }
\SYS_SendSerial1_v3_80 _sysFn=
80!!
[ if=0 <ReadPointer++ loop ]
]
pop ret { We return 0 if we transmitted everything successfully, non-zero otherwise }
] WriteOut=
\InitialReadPointer ReadPointer=
\InitialWritePointer WritePointer=
[ do
[ do
\serialRaw, data= { Read serial data }
$ff _serialRaw= { Reset to the sentinal value }
{ Is there a byte? }
data $ff^ [if<>0 { yes } data Push! loop ] ]
WriteOut!
loop ]
*=$300
{ Ring Buffer }
_InitialReadPointer=*
`READY
_InitialWritePointer=*
+40
View File
@@ -0,0 +1,40 @@
"""Tests for reading and writing using the serial port"""
import pathlib
from gtemu import Emulator
_ROM_FILE = pathlib.Path(__file__).parent / ".." / "roms" / "echo.rom"
# _ROM_FILE = pathlib.Path(__file__).parent /'..'/ '..'/ '..'/'..'/'ROMv4.rom'
def setup_module():
Emulator.load_rom_file(_ROM_FILE)
def setup_function():
Emulator.reset()
def test_read_initial_state():
# The following are not necessary, but it was very helpful in debugging
Emulator.run_to(0x2FF, max_instructions=10_000_000) # Entry of vCPU
Emulator.run_vcpu_to(0x200) # Pass through loading sequence
buffer = bytearray()
for _ in range(5):
value = Emulator.read_serial(bits=8)
buffer.append(value)
assert buffer == b"READY"
def _read_bytes(n):
buffer = bytearray()
for _ in range(n):
buffer.append(Emulator.read_serial(bits=8))
return bytes(buffer)
def test_write():
assert _read_bytes(5) == b"READY"
for b in b"Hello":
Emulator.send_byte(b)
assert _read_bytes(5) == b"Hello"