2 // Apple 2 SDL Portable Apple Emulator
5 // © 2014 Underground Software
7 // Loosely based on AppleWin by Tom Charlesworth which was based on AppleWin by
8 // Oliver Schmidt which was based on AppleWin by Michael O'Brien. :-) Parts are
9 // also derived from ApplePC. Too bad it was closed source--it could have been
10 // *the* premier Apple II emulator out there.
12 // JLH = James Hammons <jlhamm@acm.org>
15 // --- ---------- ------------------------------------------------------------
16 // JLH 11/12/2005 Initial port to SDL
17 // JLH 11/18/2005 Wired up graphic soft switches
18 // JLH 12/02/2005 Setup timer subsystem for more accurate time keeping
19 // JLH 12/12/2005 Added preliminary state saving support
20 // JLH 09/24/2013 Added //e support
25 // - Port to SDL [DONE]
27 // - Weed out unneeded functions [DONE]
29 // - 128K IIe related stuff [DONE]
30 // - State loading/saving
48 #include "applevideo.h"
56 // Debug and misc. defines
58 #define THREADED_65C02
59 #define CPU_THREAD_OVERFLOW_COMPENSATION
61 //#define CPU_CLOCK_CHECKING
62 //#define THREAD_DEBUGGING
63 #define SOFT_SWITCH_DEBUGGING
67 uint8_t ram[0x10000], rom[0x10000]; // RAM & ROM spaces
68 uint8_t ram2[0x10000]; // Auxillary RAM
69 //uint8_t diskRom[0x100]; // Disk ROM space
70 V65C02REGS mainCPU; // v65C02 execution context
71 uint8_t appleType = APPLE_TYPE_IIE;
72 FloppyDrive floppyDrive;
73 //bool powerOnState = true; // Virtual power switch
74 bool powerStateChangeRequested = false;
78 uint8_t lastKeyPressed = 0;
80 bool openAppleDown = false;
81 bool closedAppleDown = false;
82 bool store80Mode = false;
84 bool slotCXROM = false;
85 bool slotC3ROM = false;
91 // Language card state (ROM read, no write)
92 uint8_t lcState = 0x02;
94 static bool running = true; // Machine running state flag...
95 static uint32_t startTicks;
96 static bool pauseMode = false;
97 static bool fullscreenDebounce = false;
98 static bool capsLock = false;
99 static bool capsLockDebounce = false;
101 // Local functions (technically, they're global...)
103 bool LoadImg(char * filename, uint8_t * ram, int size);
104 static void SaveApple2State(const char * filename);
105 static bool LoadApple2State(const char * filename);
106 static void ResetApple2State(void);
108 // Local timer callback functions
110 static void FrameCallback(void);
111 static void BlinkTimer(void);
113 #ifdef THREADED_65C02
114 // Test of threaded execution of 6502
115 static SDL_Thread * cpuThread = NULL;
116 //static SDL_mutex * cpuMutex = NULL;
117 static SDL_cond * cpuCond = NULL;
118 static SDL_sem * mainSem = NULL;
119 static bool cpuFinished = false;
120 static bool cpuSleep = false;
122 // NB: Apple //e Manual sez 6502 is running @ 1,022,727 Hz
124 // Let's try a thread...
126 Here's how it works: Execute 1 frame's worth, then sleep.
127 Other stuff wakes it up
129 int CPUThreadFunc(void * data)
131 // Mutex must be locked for conditional to work...
132 // Also, must be created in the thread that uses it...
133 SDL_mutex * cpuMutex = SDL_CreateMutex();
135 // decrement mainSem...
136 //SDL_SemWait(mainSem);
137 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
138 float overflow = 0.0;
144 SDL_CondWait(cpuCond, cpuMutex);
146 // decrement mainSem...
147 #ifdef THREAD_DEBUGGING
148 WriteLog("CPU: SDL_SemWait(mainSem);\n");
150 SDL_SemWait(mainSem);
152 // There are exactly 800 slices of 21.333 cycles per frame, so it works out
155 uint32_t cycles = 17066;
156 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
157 // ODD! It's closer *without* this overflow compensation. ??? WHY ???
158 overflow += 0.666666667;
167 #ifdef THREAD_DEBUGGING
168 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
170 Execute65C02(&mainCPU, cycles); // how much? 1 frame (after 1 s, off by 40 cycles) not any more--it's off by as much as 240 now!
172 // Adjust the sound routine's last cycle toggled time base
173 // Also, since we're finished executing, .clock is now valid
174 #ifdef THREAD_DEBUGGING
175 WriteLog("CPU: AdjustLastToggleCycles(mainCPU.clock);\n");
177 AdjustLastToggleCycles(mainCPU.clock);
179 #ifdef THREAD_DEBUGGING
180 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
182 for(int i=0; i<800; i++)
184 uint32_t cycles = 21;
185 overflow += 0.333333334;
193 Execute65C02(&mainCPU, cycles);
194 WriteSampleToBuffer();
196 // Dunno if this is correct (seems to be close enough)...
197 vbl = (i < 670 ? true : false);
201 #ifdef THREAD_DEBUGGING
202 WriteLog("CPU: SDL_mutexP(cpuMutex);\n");
204 SDL_mutexP(cpuMutex);
205 // increment mainSem...
206 #ifdef THREAD_DEBUGGING
207 WriteLog("CPU: SDL_SemPost(mainSem);\n");
209 SDL_SemPost(mainSem);
210 #ifdef THREAD_DEBUGGING
211 WriteLog("CPU: SDL_CondWait(cpuCond, cpuMutex);\n");
213 SDL_CondWait(cpuCond, cpuMutex);
215 #ifdef THREAD_DEBUGGING
216 WriteLog("CPU: SDL_mutexV(cpuMutex);\n");
218 SDL_mutexV(cpuMutex);
220 while (!cpuFinished);
222 SDL_DestroyMutex(cpuMutex);
231 // Request a change in the power state of the emulated Apple
233 void SetPowerState(void)
235 // powerOnState = state;
236 // pauseMode = !state;
240 //printf("Turning on...\n");
241 // Transitioning from OFF to ON
242 // mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
247 //printf("Turning off...\n");
251 powerStateChangeRequested = true;
257 // Load a file into RAM/ROM image space
259 bool LoadImg(char * filename, uint8_t * ram, int size)
261 FILE * fp = fopen(filename, "rb");
266 fread(ram, 1, size, fp);
273 static void SaveApple2State(const char * filename)
278 static bool LoadApple2State(const char * filename)
284 static void ResetApple2State(void)
287 openAppleDown = false;
288 closedAppleDown = false;
299 // SwitchLC(); // Make sure MMU is in sane state
300 //NOPE, does nothing SetupAddressMap();
303 // Without this, you can wedge the system :-/
304 memset(ram, 0, 0x10000);
305 // memset(ram2, 0, 0x10000);
306 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
310 #ifdef CPU_CLOCK_CHECKING
312 uint32_t totalCPU = 0;
313 uint64_t lastClock = 0;
318 int main(int /*argc*/, char * /*argv*/[])
320 InitLog("./apple2.log");
322 srand(time(NULL)); // Initialize RNG
325 memset(ram, 0, 0x10000);
326 memset(rom, 0, 0x10000);
327 memset(ram2, 0, 0x10000);
333 // Set up V65C02 execution context
334 memset(&mainCPU, 0, sizeof(V65C02REGS));
335 mainCPU.RdMem = AppleReadMem;
336 mainCPU.WrMem = AppleWriteMem;
337 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
339 // alternateCharset = true;
340 // if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
341 if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
343 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
347 //Load up disk image from config file (for now)...
348 floppyDrive.LoadImage(settings.diskImagePath1, 0);
349 floppyDrive.LoadImage(settings.diskImagePath2, 1);
350 // floppyDrive.LoadImage("./disks/temp.nib", 1); // Load temp .nib file into second drive...
352 WriteLog("About to initialize video...\n");
356 std::cout << "Aborting!" << std::endl;
360 GUI::Init(sdlRenderer);
362 // Have to do this *after* video init but *before* sound init...!
363 //Shouldn't be necessary since we're not doing emulation in the ISR...
364 if (settings.autoStateSaving)
366 // Load last state from file...
367 if (!LoadApple2State(settings.autoStatePath))
368 WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
371 WriteLog("About to initialize audio...\n");
373 SetupBlurTable(); // Set up the color TV emulation blur table
374 running = true; // Set running status...
375 InitializeEventList(); // Clear the event list before we use it...
376 SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
377 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 s intervals
378 startTicks = SDL_GetTicks();
380 #ifdef THREADED_65C02
381 cpuCond = SDL_CreateCond();
382 mainSem = SDL_CreateSemaphore(1);
383 cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
384 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
385 // SDL_sem * mainMutex = SDL_CreateMutex();
388 WriteLog("Entering main loop...\n");
392 double timeToNextEvent = GetTimeToNextEvent();
393 #ifndef THREADED_65C02
394 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
397 #ifdef CPU_CLOCK_CHECKING
398 #ifndef THREADED_65C02
399 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
405 #ifdef THREADED_65C02
406 WriteLog("Main: cpuFinished = true;\n");
408 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
409 //What to do? How do you know when the CPU is sleeping???
410 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
411 //Nope, use a semaphore...
412 WriteLog("Main: SDL_SemWait(mainSem);\n");
413 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
416 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
417 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
418 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
419 SDL_WaitThread(cpuThread, NULL);
420 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
421 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
422 SDL_DestroyCond(cpuCond);
424 SDL_DestroySemaphore(mainSem);
426 if (settings.autoStateSaving)
428 // Save state here...
429 SaveApple2State(settings.autoStatePath);
431 floppyDrive.SaveImage(0);
432 floppyDrive.SaveImage(1);
448 -----------------------
449 space $A0 $A0 $A0 $A0 No xlation
450 RETURN $8D $8D $8D $8D No xlation
451 0 $B0 $B0 $B0 $B0 Need to screen shift+0 (?)
452 1! $B1 $B1 $A1 $A1 No xlation
453 2" $B2 $B2 $A2 $A2 No xlation
454 3# $B3 $B3 $A3 $A3 No xlation
455 4$ $B4 $B4 $A4 $A4 No xlation
456 5% $B5 $B5 $A5 $A5 No xlation
457 6& $B6 $B6 $A6 $A6 No xlation
458 7' $B7 $B7 $A7 $A7 No xlation
459 8( $B8 $B8 $A8 $A8 No xlation
460 9) $B9 $B9 $A9 $A9 No xlation
461 :* $BA $BA $AA $AA No xlation
462 ;+ $BB $BB $AB $AB No xlation
463 ,< $AC $AC $BC $BC No xlation
464 -= $AD $AD $BD $BD No xlation
465 .> $AE $AE $BE $BE No xlation
466 /? $AF $AF $BF $BF No xlation
479 M $CD $8D $DD $9D -> ODD
480 N^ $CE $8E $DE $9E -> ODD
482 P@ $D0 $90 $C0 $80 Need to xlate CTL+SHFT+P & SHFT+P (?)
495 ESC $9B $9B $9B $9B No xlation
498 //static uint64_t lastCPUCycles = 0;
499 static uint32_t frameCount = 0;
500 static void FrameCallback(void)
504 while (SDL_PollEvent(&event))
508 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
511 //Need to do some key translation here, and screen out non-apple keys as well...
512 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
513 // everything else done separately. this is slightly easier. :-P)
514 // if (event.key.keysym.sym == SDLK_TAB) // Prelim key screening...
515 if (event.edit.text[0] == '\t') // Prelim key screening...
518 lastKeyPressed = event.edit.text[0];
521 //kludge: should have a caps lock thingy here...
522 //or all uppercase for ][+...
523 // if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
524 // lastKeyPressed &= 0xDF; // Convert to upper case...
529 // Use ALT+Q to exit, as well as the usual window decoration method
530 if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
533 // CTRL+RESET key emulation (mapped to CTRL+`)
534 // This doesn't work...
535 // if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
536 // if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
537 if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
539 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
540 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
541 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
545 if (event.key.keysym.sym == SDLK_RIGHT)
546 lastKeyPressed = 0x15, keyDown = true;
547 else if (event.key.keysym.sym == SDLK_LEFT)
548 lastKeyPressed = 0x08, keyDown = true;
549 else if (event.key.keysym.sym == SDLK_UP)
550 lastKeyPressed = 0x0B, keyDown = true;
551 else if (event.key.keysym.sym == SDLK_DOWN)
552 lastKeyPressed = 0x0A, keyDown = true;
553 else if (event.key.keysym.sym == SDLK_RETURN)
554 lastKeyPressed = 0x0D, keyDown = true;
555 else if (event.key.keysym.sym == SDLK_ESCAPE)
556 lastKeyPressed = 0x1B, keyDown = true;
557 else if (event.key.keysym.sym == SDLK_BACKSPACE)
558 lastKeyPressed = 0x7F, keyDown = true;
560 // Fix CTRL+key combo...
561 if (event.key.keysym.mod & KMOD_CTRL)
563 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
565 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
567 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
573 // Fix SHIFT+key combo...
574 if (event.key.keysym.mod & KMOD_SHIFT)
576 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
578 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
580 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
583 else if (event.key.keysym.sym == SDLK_1)
585 lastKeyPressed = '!';
589 else if (event.key.keysym.sym == SDLK_2)
591 lastKeyPressed = '@';
595 else if (event.key.keysym.sym == SDLK_3)
597 lastKeyPressed = '#';
601 else if (event.key.keysym.sym == SDLK_3)
603 lastKeyPressed = '#';
607 else if (event.key.keysym.sym == SDLK_4)
609 lastKeyPressed = '$';
613 else if (event.key.keysym.sym == SDLK_5)
615 lastKeyPressed = '%';
619 else if (event.key.keysym.sym == SDLK_6)
621 lastKeyPressed = '^';
625 else if (event.key.keysym.sym == SDLK_7)
627 lastKeyPressed = '&';
631 else if (event.key.keysym.sym == SDLK_8)
633 lastKeyPressed = '*';
637 else if (event.key.keysym.sym == SDLK_9)
639 lastKeyPressed = '(';
643 else if (event.key.keysym.sym == SDLK_0)
645 lastKeyPressed = ')';
649 else if (event.key.keysym.sym == SDLK_MINUS)
651 lastKeyPressed = '_';
655 else if (event.key.keysym.sym == SDLK_EQUALS)
657 lastKeyPressed = '+';
661 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
663 lastKeyPressed = '{';
667 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
669 lastKeyPressed = '}';
673 else if (event.key.keysym.sym == SDLK_BACKSLASH)
675 lastKeyPressed = '|';
679 else if (event.key.keysym.sym == SDLK_SEMICOLON)
681 lastKeyPressed = ':';
685 else if (event.key.keysym.sym == SDLK_QUOTE)
687 lastKeyPressed = '"';
691 else if (event.key.keysym.sym == SDLK_COMMA)
693 lastKeyPressed = '<';
697 else if (event.key.keysym.sym == SDLK_PERIOD)
699 lastKeyPressed = '>';
703 else if (event.key.keysym.sym == SDLK_SLASH)
705 lastKeyPressed = '?';
709 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
711 lastKeyPressed = '~';
719 if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
721 lastKeyPressed = event.key.keysym.sym;
724 // Check for Caps Lock key...
725 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
726 lastKeyPressed -= 0x20;
731 if (event.key.keysym.sym == SDLK_PAUSE)
733 pauseMode = !pauseMode;
738 SpawnMessage("*** PAUSED ***");
743 SpawnMessage("*** RESUME ***");
747 // Paddle buttons 0 & 1
748 if (event.key.keysym.sym == SDLK_INSERT)
749 openAppleDown = true;
750 if (event.key.keysym.sym == SDLK_PAGEUP)
751 closedAppleDown = true;
753 if (event.key.keysym.sym == SDLK_F11)
754 dumpDis = !dumpDis; // Toggle the disassembly process
756 /*else if (event.key.keysym.sym == SDLK_F9)
758 floppyDrive.CreateBlankImage(0);
759 // SpawnMessage("Image cleared...");
761 /*else if (event.key.keysym.sym == SDLK_F10)
763 floppyDrive.SwapImages();
764 // SpawnMessage("Image swapped...");
767 if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
769 else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
771 else if (event.key.keysym.sym == SDLK_F5)
774 char volStr[19] = "[****************]";
775 // volStr[GetVolume()] = 0;
776 for(int i=GetVolume(); i<16; i++)
778 SpawnMessage("Volume: %s", volStr);
780 else if (event.key.keysym.sym == SDLK_F6)
783 char volStr[19] = "[****************]";
784 // volStr[GetVolume()] = 0;
785 for(int i=GetVolume(); i<16; i++)
787 SpawnMessage("Volume: %s", volStr);
789 else if (event.key.keysym.sym == SDLK_F12)
791 if (!fullscreenDebounce)
794 fullscreenDebounce = true;
798 if (event.key.keysym.sym == SDLK_CAPSLOCK)
800 if (!capsLockDebounce)
802 capsLock = !capsLock;
803 capsLockDebounce = true;
809 if (event.key.keysym.sym == SDLK_F12)
810 fullscreenDebounce = false;
811 if (event.key.keysym.sym == SDLK_CAPSLOCK)
812 capsLockDebounce = false;
814 // Paddle buttons 0 & 1
815 if (event.key.keysym.sym == SDLK_INSERT)
816 openAppleDown = false;
817 if (event.key.keysym.sym == SDLK_PAGEUP)
818 closedAppleDown = false;
820 // if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
824 case SDL_MOUSEBUTTONDOWN:
825 GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
827 case SDL_MOUSEBUTTONUP:
828 GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
830 case SDL_MOUSEMOTION:
831 GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
833 case SDL_WINDOWEVENT:
834 if (event.window.event == SDL_WINDOWEVENT_LEAVE)
835 GUI::MouseMove(0, 0, 0);
843 // Handle power request from the GUI
844 if (powerStateChangeRequested)
846 if (GUI::powerOnState)
856 //NOPE SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
857 // ResetApple2State();
860 powerStateChangeRequested = false;
863 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
869 RenderScreenBuffer();
870 GUI::Render(sdlRenderer);
871 SDL_RenderPresent(sdlRenderer);
872 SetCallbackTime(FrameCallback, 16666.66666667);
874 #ifdef CPU_CLOCK_CHECKING
875 //We know it's stopped, so we can get away with this...
879 uint64_t clock = GetCurrentV65C02Clock();
880 //totalCPU += (uint32_t)(clock - lastClock);
882 printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
889 // This is the problem: If you set the interval to 16, it runs faster than
890 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
891 // have it do 16 for one frame, then 17 for two others. Then it should average
892 // out to 1/60s per frame every 3 frames.
893 frameCount = (frameCount + 1) % 3;
894 uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
896 // Wait for next frame...
897 while (SDL_GetTicks() - startTicks < waitFrameTime)
900 startTicks = SDL_GetTicks();
902 uint64_t cpuCycles = GetCurrentV65C02Clock();
903 uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
904 WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
905 lastCPUCycles = cpuCycles;
908 //let's wait, then signal...
909 //works longer, but then still falls behind...
910 #ifdef THREADED_65C02
912 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
917 static void BlinkTimer(void)
920 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 sec intervals
925 Next problem is this: How to have events occur and synchronize with the rest
928 o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
929 remainder CPU cycles over...)
931 One way would be to use a fractional accumulator, then subtract 1 every
932 time it overflows. Like so:
938 Execute6808(&soundCPU, time);
939 overflow += 0.289115646;