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)
286 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
288 openAppleDown = false;
289 closedAppleDown = false;
300 SwitchLC(); // Make sure MMU is in sane state
301 memset(ram, 0, 0x10000);
302 memset(ram2, 0, 0x10000);
306 #ifdef CPU_CLOCK_CHECKING
308 uint32_t totalCPU = 0;
309 uint64_t lastClock = 0;
314 int main(int /*argc*/, char * /*argv*/[])
316 InitLog("./apple2.log");
318 srand(time(NULL)); // Initialize RNG
321 memset(ram, 0, 0x10000);
322 memset(rom, 0, 0x10000);
323 memset(ram2, 0, 0x10000);
328 // Set up V65C02 execution context
329 memset(&mainCPU, 0, sizeof(V65C02REGS));
330 mainCPU.RdMem = AppleReadMem;
331 mainCPU.WrMem = AppleWriteMem;
332 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
334 // alternateCharset = true;
335 // if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
336 if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
338 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
342 //Load up disk image from config file (for now)...
343 floppyDrive.LoadImage(settings.diskImagePath1, 0);
344 floppyDrive.LoadImage(settings.diskImagePath2, 1);
345 // floppyDrive.LoadImage("./disks/temp.nib", 1); // Load temp .nib file into second drive...
347 WriteLog("About to initialize video...\n");
351 std::cout << "Aborting!" << std::endl;
355 GUI::Init(sdlRenderer);
357 // Have to do this *after* video init but *before* sound init...!
358 //Shouldn't be necessary since we're not doing emulation in the ISR...
359 if (settings.autoStateSaving)
361 // Load last state from file...
362 if (!LoadApple2State(settings.autoStatePath))
363 WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
366 WriteLog("About to initialize audio...\n");
368 SetupBlurTable(); // Set up the color TV emulation blur table
369 running = true; // Set running status...
370 InitializeEventList(); // Clear the event list before we use it...
371 SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
372 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 s intervals
373 startTicks = SDL_GetTicks();
375 #ifdef THREADED_65C02
376 cpuCond = SDL_CreateCond();
377 mainSem = SDL_CreateSemaphore(1);
378 cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
379 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
380 // SDL_sem * mainMutex = SDL_CreateMutex();
383 WriteLog("Entering main loop...\n");
387 double timeToNextEvent = GetTimeToNextEvent();
388 #ifndef THREADED_65C02
389 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
391 //We MUST remove a frame's worth of time in order for the CPU to function... !!! FIX !!!
392 //(Fix so that this is not a requirement!)
393 //Fixed, but mainCPU.clock is destroyed in the bargain. Oh well.
394 // mainCPU.clock -= USEC_TO_M6502_CYCLES(timeToNextEvent);
396 #ifdef CPU_CLOCK_CHECKING
397 #ifndef THREADED_65C02
398 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
404 #ifdef THREADED_65C02
405 WriteLog("Main: cpuFinished = true;\n");
407 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
408 //What to do? How do you know when the CPU is sleeping???
409 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
410 //Nope, use a semaphore...
411 WriteLog("Main: SDL_SemWait(mainSem);\n");
412 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
415 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
416 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
417 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
418 SDL_WaitThread(cpuThread, NULL);
419 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
420 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
421 SDL_DestroyCond(cpuCond);
423 SDL_DestroySemaphore(mainSem);
425 if (settings.autoStateSaving)
427 // Save state here...
428 SaveApple2State(settings.autoStatePath);
430 floppyDrive.SaveImage(0);
431 floppyDrive.SaveImage(1);
447 -----------------------
448 space $A0 $A0 $A0 $A0 No xlation
449 RETURN $8D $8D $8D $8D No xlation
450 0 $B0 $B0 $B0 $B0 Need to screen shift+0 (?)
451 1! $B1 $B1 $A1 $A1 No xlation
452 2" $B2 $B2 $A2 $A2 No xlation
453 3# $B3 $B3 $A3 $A3 No xlation
454 4$ $B4 $B4 $A4 $A4 No xlation
455 5% $B5 $B5 $A5 $A5 No xlation
456 6& $B6 $B6 $A6 $A6 No xlation
457 7' $B7 $B7 $A7 $A7 No xlation
458 8( $B8 $B8 $A8 $A8 No xlation
459 9) $B9 $B9 $A9 $A9 No xlation
460 :* $BA $BA $AA $AA No xlation
461 ;+ $BB $BB $AB $AB No xlation
462 ,< $AC $AC $BC $BC No xlation
463 -= $AD $AD $BD $BD No xlation
464 .> $AE $AE $BE $BE No xlation
465 /? $AF $AF $BF $BF No xlation
478 M $CD $8D $DD $9D -> ODD
479 N^ $CE $8E $DE $9E -> ODD
481 P@ $D0 $90 $C0 $80 Need to xlate CTL+SHFT+P & SHFT+P (?)
494 ESC $9B $9B $9B $9B No xlation
497 //static uint64_t lastCPUCycles = 0;
498 static uint32_t frameCount = 0;
499 static void FrameCallback(void)
503 while (SDL_PollEvent(&event))
507 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
510 //Need to do some key translation here, and screen out non-apple keys as well...
511 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
512 // everything else done separately. this is slightly easier. :-P)
513 // if (event.key.keysym.sym == SDLK_TAB) // Prelim key screening...
514 if (event.edit.text[0] == '\t') // Prelim key screening...
517 lastKeyPressed = event.edit.text[0];
520 //kludge: should have a caps lock thingy here...
521 //or all uppercase for ][+...
522 // if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
523 // lastKeyPressed &= 0xDF; // Convert to upper case...
528 // Use ALT+Q to exit, as well as the usual window decoration method
529 if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
532 // CTRL+RESET key emulation (mapped to CTRL+`)
533 // This doesn't work...
534 // if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
535 // if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
536 if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
538 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
539 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
540 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
544 if (event.key.keysym.sym == SDLK_RIGHT)
545 lastKeyPressed = 0x15, keyDown = true;
546 else if (event.key.keysym.sym == SDLK_LEFT)
547 lastKeyPressed = 0x08, keyDown = true;
548 else if (event.key.keysym.sym == SDLK_UP)
549 lastKeyPressed = 0x0B, keyDown = true;
550 else if (event.key.keysym.sym == SDLK_DOWN)
551 lastKeyPressed = 0x0A, keyDown = true;
552 else if (event.key.keysym.sym == SDLK_RETURN)
553 lastKeyPressed = 0x0D, keyDown = true;
554 else if (event.key.keysym.sym == SDLK_ESCAPE)
555 lastKeyPressed = 0x1B, keyDown = true;
556 else if (event.key.keysym.sym == SDLK_BACKSPACE)
557 lastKeyPressed = 0x7F, keyDown = true;
559 // Fix CTRL+key combo...
560 if (event.key.keysym.mod & KMOD_CTRL)
562 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
564 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
566 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
572 // Fix SHIFT+key combo...
573 if (event.key.keysym.mod & KMOD_SHIFT)
575 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
577 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
579 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
582 else if (event.key.keysym.sym == SDLK_1)
584 lastKeyPressed = '!';
588 else if (event.key.keysym.sym == SDLK_2)
590 lastKeyPressed = '@';
594 else if (event.key.keysym.sym == SDLK_3)
596 lastKeyPressed = '#';
600 else if (event.key.keysym.sym == SDLK_3)
602 lastKeyPressed = '#';
606 else if (event.key.keysym.sym == SDLK_4)
608 lastKeyPressed = '$';
612 else if (event.key.keysym.sym == SDLK_5)
614 lastKeyPressed = '%';
618 else if (event.key.keysym.sym == SDLK_6)
620 lastKeyPressed = '^';
624 else if (event.key.keysym.sym == SDLK_7)
626 lastKeyPressed = '&';
630 else if (event.key.keysym.sym == SDLK_8)
632 lastKeyPressed = '*';
636 else if (event.key.keysym.sym == SDLK_9)
638 lastKeyPressed = '(';
642 else if (event.key.keysym.sym == SDLK_0)
644 lastKeyPressed = ')';
648 else if (event.key.keysym.sym == SDLK_MINUS)
650 lastKeyPressed = '_';
654 else if (event.key.keysym.sym == SDLK_EQUALS)
656 lastKeyPressed = '+';
660 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
662 lastKeyPressed = '{';
666 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
668 lastKeyPressed = '}';
672 else if (event.key.keysym.sym == SDLK_BACKSLASH)
674 lastKeyPressed = '|';
678 else if (event.key.keysym.sym == SDLK_SEMICOLON)
680 lastKeyPressed = ':';
684 else if (event.key.keysym.sym == SDLK_QUOTE)
686 lastKeyPressed = '"';
690 else if (event.key.keysym.sym == SDLK_COMMA)
692 lastKeyPressed = '<';
696 else if (event.key.keysym.sym == SDLK_PERIOD)
698 lastKeyPressed = '>';
702 else if (event.key.keysym.sym == SDLK_SLASH)
704 lastKeyPressed = '?';
708 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
710 lastKeyPressed = '~';
718 if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
720 lastKeyPressed = event.key.keysym.sym;
723 // Check for Caps Lock key...
724 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
725 lastKeyPressed -= 0x20;
730 if (event.key.keysym.sym == SDLK_PAUSE)
732 pauseMode = !pauseMode;
737 SpawnMessage("*** PAUSED ***");
742 SpawnMessage("*** RESUME ***");
746 // Paddle buttons 0 & 1
747 if (event.key.keysym.sym == SDLK_INSERT)
748 openAppleDown = true;
749 if (event.key.keysym.sym == SDLK_PAGEUP)
750 closedAppleDown = true;
752 if (event.key.keysym.sym == SDLK_F11)
753 dumpDis = !dumpDis; // Toggle the disassembly process
755 /*else if (event.key.keysym.sym == SDLK_F9)
757 floppyDrive.CreateBlankImage(0);
758 // SpawnMessage("Image cleared...");
760 /*else if (event.key.keysym.sym == SDLK_F10)
762 floppyDrive.SwapImages();
763 // SpawnMessage("Image swapped...");
766 if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
768 else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
770 else if (event.key.keysym.sym == SDLK_F5)
773 char volStr[19] = "[****************]";
774 // volStr[GetVolume()] = 0;
775 for(int i=GetVolume(); i<16; i++)
777 SpawnMessage("Volume: %s", volStr);
779 else if (event.key.keysym.sym == SDLK_F6)
782 char volStr[19] = "[****************]";
783 // volStr[GetVolume()] = 0;
784 for(int i=GetVolume(); i<16; i++)
786 SpawnMessage("Volume: %s", volStr);
788 else if (event.key.keysym.sym == SDLK_F12)
790 if (!fullscreenDebounce)
793 fullscreenDebounce = true;
797 if (event.key.keysym.sym == SDLK_CAPSLOCK)
799 if (!capsLockDebounce)
801 capsLock = !capsLock;
802 capsLockDebounce = true;
808 if (event.key.keysym.sym == SDLK_F12)
809 fullscreenDebounce = false;
810 if (event.key.keysym.sym == SDLK_CAPSLOCK)
811 capsLockDebounce = false;
813 // Paddle buttons 0 & 1
814 if (event.key.keysym.sym == SDLK_INSERT)
815 openAppleDown = false;
816 if (event.key.keysym.sym == SDLK_PAGEUP)
817 closedAppleDown = false;
819 // if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
823 case SDL_MOUSEBUTTONDOWN:
824 GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
826 case SDL_MOUSEBUTTONUP:
827 GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
829 case SDL_MOUSEMOTION:
830 GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
832 case SDL_WINDOWEVENT:
833 if (event.window.event == SDL_WINDOWEVENT_LEAVE)
834 GUI::MouseMove(0, 0, 0);
842 // Handle power request from the GUI
843 if (powerStateChangeRequested)
845 if (GUI::powerOnState)
855 //NOPE SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
856 // ResetApple2State();
859 powerStateChangeRequested = false;
862 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
868 RenderScreenBuffer();
869 GUI::Render(sdlRenderer);
870 SDL_RenderPresent(sdlRenderer);
871 SetCallbackTime(FrameCallback, 16666.66666667);
873 #ifdef CPU_CLOCK_CHECKING
874 //We know it's stopped, so we can get away with this...
878 uint64_t clock = GetCurrentV65C02Clock();
879 //totalCPU += (uint32_t)(clock - lastClock);
881 printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
887 //Instead of this, we should yield remaining time to other processes... !!! FIX !!! [DONE]
890 //Actually, slows things down too much...
892 // while (SDL_GetTicks() - startTicks < 16); // Wait for next frame...
894 // This is the problem: If you set the interval to 16, it runs faster than
895 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
896 // have it do 16 for one frame, then 17 for two others. Then it should average
897 // out to 1/60s per frame every 3 frames.
898 frameCount = (frameCount + 1) % 3;
899 uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
901 while (SDL_GetTicks() - startTicks < waitFrameTime)
902 SDL_Delay(1); // Wait for next frame...
904 startTicks = SDL_GetTicks();
906 uint64_t cpuCycles = GetCurrentV65C02Clock();
907 uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
908 WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
909 lastCPUCycles = cpuCycles;
912 //let's wait, then signal...
913 //works longer, but then still falls behind...
914 #ifdef THREADED_65C02
916 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
921 static void BlinkTimer(void)
924 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 sec intervals
929 Next problem is this: How to have events occur and synchronize with the rest
932 o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
933 remainder CPU cycles over...)
935 One way would be to use a fractional accumulator, then subtract 1 every
936 time it overflows. Like so:
942 Execute6808(&soundCPU, time);
943 overflow += 0.289115646;