/* util.c Copyright (C) 2026 Pierre Sarrazin This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "util.h" #include "pmode4game.h" /* cardgame library */ word timer; byte numVSyncsBeforeScreenFlip = 0; //BOOL enableTraces; static interrupt void irqService(void) { asm { tst $ff03 ; do nothing if 63.5 us interrupt bpl @done ; 60 Hz interrupt: lda $ff02 ; reset PIA0, port B interrupt flag ; Decrement numVSyncsBeforeScreenFlip if not already zero. ; ; Useful to get stats on IRQs per flip. See also showGraphicsPage(). ; tst :enableTraces ; beq @noTraces ; lda #'I' ; sta $FF42 ; write to Becker port, to server that collects these chars ; lda #10 ; sta $FF42 ;@noTraces ; tst _numVSyncsBeforeScreenFlip beq @flipDecDone dec _numVSyncsBeforeScreenFlip @flipDecDone ldd _timer addd #1 std _timer @done } } void setupIRQService(void) { asm { ldx $FFF8 ; 6809 IRQ vector address lda #$7E ; JMP instruction sta ,x leay irqService ; new routine sty 1,x } } void coldBoot(void) { disableInterrupts(); memset16((void *) VIDRAM, 0x8080, 512 / 2); // clear 32x16 screen at location used by Basic // Copy a small routine to low RAM, then jump to the routine, which: // - goes back to RAM-ROM mode to bring back Basic (CLR >$FFDE); // - pokes 0 at 113 (CLR >$0071); // - jumps at 40999 to cold boot Basic (JMP >$A027). // memcpy(0, "\x7F\xFF\xDE" "\x7F\x00\x71" "\x7E\xA0\x27", 9); asm { jmp >0 } } __gcccall asm void setCoCo12ColorSet(byte colorSet) { asm { lda $FF22 tstb ; B contains colorSet (re: __gcccall) bne @colorSet1 anda #$F7 bra @store @colorSet1 ora #$08 @store sta $FF22 } } __gcccall void asm setCoCo3ColorSet(byte colorSet) { // Palette slots 0..3 for color set 0: black, dark green, middle green, light green. // Palette slots 0..3 for color set 1: black, blue, orange, white. // asm { tstb ; B contains colorSet, b/c __gcccall bne @colorSet1 ; Color set 0: ldd #$0002 ; black, dark green ldx #$1412 ; middle green, light green bra @store @colorSet1 ldd #$000B ; black, blue ldx #$34FF ; orange, white @store std PALETREG stx PALETREG+2 } } word rnd(word lowerLimit, word upperLimit) { return (word) rand() % (upperLimit - lowerLimit + 1) + lowerLimit; } #if 0 asm sword makeEven(sword n) { /* Original C code: if (n >= 0) return n & 0xFFFE; return -((-n) & 0xFFFE); */ asm { ldd 2,s ; load 'n', changes N and Z, resets V blt @negative andb #$FE bra @done @negative coma comb addd #1 andb #$FE coma comb addd #1 @done } } __gcccall byte ceilDiv(byte num, byte den) { return (num + den - 1) / den; } #endif __gcccall asm sword signExtendYPos(byte screenRow) { #if 0 /* Original C code. */ if (screenRow < ROWS_PER_SCREEN) return (sword) screenRow; return (sbyte) screenRow; // -64..-1 #else asm { ; screenRow is received in B. cmpb #ROWS_PER_SCREEN bhs @negative ; B is 0..191; return this value as a word. clra bra @returnInX @negative ; B is -64..-1; sign extend this value to return it as a word. sex @returnInX tfr d,x ; a __gcccall function returns a word in X } #endif } static const struct { sword c, s; } cosSin256thsTable[16] = { /* 0 0.0 deg */ { 256, 0 }, /* 1 22.5 deg */ { 237, 98 }, /* 2 45.0 deg */ { 181, 181 }, /* 3 67.5 deg */ { 98, 237 }, /* 4 90.0 deg */ { 0, 256 }, /* 5 112.5 deg */ { -98, 237 }, /* 6 135.0 deg */ { -181, 181 }, /* 7 157.5 deg */ { -237, 98 }, /* 8 180.0 deg */ { -256, 0 }, /* 9 202.5 deg */ { -237, -98 }, /* 10 225.0 deg */ { -181, -181 }, /* 11 247.5 deg */ { -98, -237 }, /* 12 270.0 deg */ { 0, -256 }, /* 13 292.5 deg */ { 98, -237 }, /* 14 315.0 deg */ { 181, -181 }, /* 15 337.5 deg */ { 237, -98 }, }; // angle: 0..15. // Returns (256 * cos(a * 22.5 deg), 256 * sin(a * 22.5 deg)). // void cosSin256ths(byte angle, sword *cosine, sword *sine) { assert(angle < ARRAY_SIZE(cosSin256thsTable)); *cosine = cosSin256thsTable[angle].c; *sine = cosSin256thsTable[angle].s; } sword cos256ths(byte angle) { assert(angle < ARRAY_SIZE(cosSin256thsTable)); return cosSin256thsTable[angle].c; } sword mul256thsToByte(sword a256, sword b256) { signed long product = (signed long) a256 * (signed long) b256; if (product >= 0) // to round to nearest multiple of 2**16: product += 0x8000u; else product -= 0x8000u; return * (sword *) &product; // product / 2**16; assumes big endian } #if 0 void addToDecimalDigit(byte valueToAdd, sbyte digitIndex, byte digitArray[SCORE_WIDTH]) { byte *digitInArray = digitArray + digitIndex; for (;;) { byte sum = valueToAdd + *digitInArray; // result in 0..18 if (sum < 10) // if no carry { *digitInArray = sum; return; } *digitInArray-- = sum - 10; if (digitIndex == 0) return; // out of digits in array --digitIndex; valueToAdd = 1; // next iteration will add carry to previous digit } } #endif static byte leftMargin, logicalLineLength; void setWrappedPrinting(byte _leftMargin, byte _logicalLineLength) { leftMargin = _leftMargin; logicalLineLength = _logicalLineLength; } // Prints the given character, while also managing a boolean that // is used to invert the leftmost column of the next character // to be printed. This boolean is true at the closing of a ^...^ // sequence that inverts the characters between the carets. // // ch: Character to write. No character gets written if ch is '\0'. // static __gcccall void putcharAndMung(char ch, BOOL *nextCharToHaveLeftColumnInverted) { if (*nextCharToHaveLeftColumnInverted) setColorInversionMask(0b11000000); if (ch) putchar(ch); if (*nextCharToHaveLeftColumnInverted) { setColorInversionMask(0); *nextCharToHaveLeftColumnInverted = FALSE; } } void printWrapped(const char *text) { assert(logicalLineLength > 0); // setWrappedPrinting() must have been called const byte logicalLineEnd = leftMargin + logicalLineLength; byte hPos, vPos; getCursor(&hPos, &vPos); // call to cardgame library if (hPos < leftMargin) { moveCursor(leftMargin, vPos); hPos = leftMargin; } byte separator = !!isspace(text[0]); // 1 means next word must be preceded by a space BOOL invColorEnabled = FALSE; BOOL nextCharToHaveLeftColumnInverted = FALSE; for (const char *p = text; ; ) { // Skip white space, but do newlines. while (isspace(*p)) { if (*p == '\n') { putcharAndMung('\0', &nextCharToHaveLeftColumnInverted); moveCursor(leftMargin, textPosY + 1); hPos = leftMargin; separator = 0; } ++p; } // Find end of current word. const char *wordStart = p; while (*p && !isspace(*p)) ++p; // If not enough space for word on current line, newline. size_t wordLen = p - wordStart; if (wordLen == 0) break; // end of 'text' // If current word would go over limit, newline before. if (hPos + separator + wordLen > logicalLineEnd) { putcharAndMung('\0', &nextCharToHaveLeftColumnInverted); moveCursor(leftMargin, textPosY + 1); hPos = leftMargin; separator = 0; } else if (separator) { putcharAndMung(' ', &nextCharToHaveLeftColumnInverted); ++hPos; } // Print the word at (wordStart, wordLen), with support // for color inversion. Advance hPos. // for (byte j = 0; j < wordLen; ++j) { char ch = wordStart[j]; if (ch == INVERTED_COLOR_TOGGLE_CHAR) { invColorEnabled = !invColorEnabled; enableInvertedColorText(invColorEnabled); if (!invColorEnabled) { // This boolean is used to patch the rendering of the // character that follows a sequence of inverted characters. // With this patch, we ensure that the rightmost column of // the last inverted character is white instead of black. // nextCharToHaveLeftColumnInverted = TRUE; } } else { putcharAndMung(ch, &nextCharToHaveLeftColumnInverted); ++hPos; } } if (hPos != logicalLineEnd) separator = 1; } } void copyDoubleRowBitmap(byte *screenPtr, const uint32_t bitmapRows[][8], byte numRows) { for (byte row = 0; row < numRows; ++row) { memcpy(screenPtr, bitmapRows[row], BYTES_PER_ROW); screenPtr += BYTES_PER_ROW; memcpy(screenPtr, bitmapRows[row], BYTES_PER_ROW); screenPtr += BYTES_PER_ROW; } } void xorRegion(byte *screenPtr, byte numRows, byte xorArg) { size_t numBytes = (size_t) numRows * BYTES_PER_ROW; for (size_t i = 0; i < numBytes; ++i) screenPtr[i] ^= xorArg; } void enableSound(void) { // Based on Color Basic code at $9A2B. byte *pia0 = (byte *) 0xFF00; pia0[1] &= 0xF7; pia0[3] &= 0xF7; byte *pia1 = (byte *) 0xFF20; pia1[3] |= 0x08; } void playSoundSample(const void *sampleArray, const void *sampleArrayEnd, word delayLength) { asm { ldx :sampleArray // // Assuming that the playing rate is 4000 Hz, as an example. // The following sampling loop must write out a 6-bit sample 4000 times per second. // The CoCo 6809 CPU, for example, executes 894886 cycles per second. // Each iteration must last 894886 / 4000 cycles (about 224). // Each iteration lasts 5+4+6+N*(3+3)+6+3 cycles (see asm code below), // where N is the number of iterations of the between-samples delay loop. // We have 6*N + 24 = 224, so N is about 33. // Total formula: N = (224 - 24) / 6 = (894886 / 4000 - 24) / 6 // = (cpuCyclesPerSecond / playBackFrequencyInHz - 24) / 6 // This number can be computed by Player_getSamplePlayDelayLength(). // @samplingLoop lda ,x+ ; (5 cycles) sta $FF20 ; (4) Write to PIA1 ldd :delayLength ; (6) @delayLoop subd #1 ; (3) bhi @delayLoop ; (3) cmpx :sampleArrayEnd ; (6) blo @samplingLoop ; (3) } } #if 0 __gcccall void asm memzero(char *dest, byte numBytes) { asm { ; X is dest b/c of __gcccall tstb ; B is numBytes b/c of __gcccall beq @done clra @loop sta ,x+ decb bne @loop @done } } #endif static word randomWord = 0; // 0..$3FFF static byte numTaystesLeft = 0; byte generateRandomTayste(void) { if (numTaystesLeft == 0) { randomWord = (word) rand() % 0x3FFF; // keep 14 low bits numTaystesLeft = 7; } byte direction = (byte) (randomWord & 3); randomWord >>= 2; --numTaystesLeft; return direction; } int8_t approxAtan2Signed8(int8_t y, int8_t x) { //printf("approxAtan2Signed8(%d,%d)\n", y, x); assert(y >= -127 && y <= 127); assert(x >= -127 && x <= 127); if (y == 0) { if (x == 0) return 0; return x < 0 ? -128 : 0; } if (x == 0) return y < 0 ? 64 : -64; // Convert to y axis that points up. // y = -y; uint8_t abs_y = (uint8_t) (y < 0 ? -y : y); uint8_t abs_x = (uint8_t) (x < 0 ? -x : x); int16_t angle; // Linear approximation ratio scaled to 32 (to fit comfortably in 16-bit). // Octant N, where N is in 1..8, goes from 45(N-1) to 45N degrees. // if (abs_x >= abs_y) { // Octants 1, 4, 5, 8: ratio = (32 * abs_y) / abs_x. angle = (int16_t) (((uint16_t) abs_y * 32u) / abs_x); } else { // Octants 2, 3, 6, 7. Invert across 45-deg. diagonal. angle = 64 - (int16_t) (((uint16_t) abs_x * 32u) / abs_y); } // Mirror to correct quadrant based on original signs of x and y. // if (x < 0) angle = 128 - angle; if (y < 0) angle = -angle; if (angle == 128) // 128 does not fit a signed byte angle = -128; BOOL angleValid = (angle >= -128 && angle <= 127); //if (!angleValid) // printf("x=%d, y=%d, angle=%d\n", x, y, angle); assert(angleValid); return (int8_t) angle; } BOOL computeAngleIfNotTooFar(byte shooterX, byte shooterY, byte shooterOrientation, byte targetX, byte targetY, word maxDistance, word maxDistanceSquared, int8_t *angleInBrads) { //printf("# computeAngleIfNotTooFar(%u, %u, %u, %u, %u)\n", // shooterX, shooterY, shooterOrientation, targetX, targetY); // Compute the distance between the two sprites. // sword dx = (sword) targetX - (sword) shooterX; word dxAbs = (word) abs(dx); if (dxAbs >= maxDistance) return FALSE; // too far horizontally, avoid calculating distance sword dy = (sword) targetY - (sword) shooterY; // positive x axis points down word dyAbs = (word) abs(dy); if (dyAbs >= maxDistance) return FALSE; // too far vertically, avoid calculating distance word sqDist = dxAbs * dxAbs + dyAbs * dyAbs; // not expecting overflow b/c large dx, dy values already excluded if (sqDist >= maxDistanceSquared) return FALSE; // too far //printf("# computeAngleIfNotTooFar: dx=%d, dy=%d, sqDist=%u\n", dx, dy, sqDist); // Check if the shooter is pointing in direction of the target. // bitmapIndex is in 0..15. // The nose of the plane points in a direction given by an angle that is bitmapIndex * 22.5 degrees. // (Standard trig circle assumed, with 0 deg to the right, and +90 up.) // The direction from the shooter to the target is given by the couple (dx, -dy) (standard Cartesian plane). // (The minus sign is because the y axis used by Sprite points down.) // The angle of the shooter-to-target arrow is atan(-dy / dx). // int8_t bradsToTarget = approxAtan2Signed8((sbyte) dy, (sbyte) dx); // angle in binary radians: -128..127 //printf("# computeAngleIfNotTooFar: bradsToTarget=%d\n", bradsToTarget); byte noseBrads = shooterOrientation << 4; // convert 0..15 to brads (0..255) //printf("# computeAngleIfNotTooFar: noseBrads=%u\n", noseBrads); *angleInBrads = bradsToTarget - (int8_t) noseBrads; //printf("# computeAngleIfNotTooFar: angleInBrads=%d\n", *angleInBrads); return TRUE; } #if DEBUG /* Useful for debugging. */ void beckPrintStr(const char *s) { for (; *s; ++s) beckputchar(*s); } void beckPrintInt(int n) { char tmp[16]; itoa10(n, tmp); beckPrintStr(tmp); } void beckPrintLineNo(int lineNo) { beckputchar('['); beckputchar('L'); beckPrintInt(lineNo); beckputchar(']'); beckputchar('\n'); } void beckPrintInts(int a, int b) { beckPrintInt(a); beckputchar(';'); beckPrintInt(b); beckputchar('\n'); } asm void beckerPortConsoleOutHook(void) { asm { sta $FF42 } } void beckPrintf(const char *fmt, ...) { ConsoleOutHook oldHook = setConsoleOutHook(beckerPortConsoleOutHook); va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); setConsoleOutHook(oldHook); } void printDecimalArray(const byte array[], byte numDigits) { for ( ; numDigits--; ++array) putchar('0' + *array); } void breakpoint(void) { printf("*** STOPPED AT BREAKPOINT ***\n"); while (! isKeyPressed(KEY_PROBE_1, KEY_BIT_1)) ; while (isKeyPressed(KEY_PROBE_1, KEY_BIT_1)) ; } #endif /* DEBUG */