nedoPC.org

Electronics hobbyists community established in 2002
Atom Feed | View unanswered posts | View active topics It is currently 28 Mar 2024 08:14



Reply to topic  [ 32 posts ]  Go to page 1, 2, 3  Next
XORLib - игровая либа для старой школы ;) 
Author Message
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
По итогам экспериментов с PIC32 решил вот начать писать опенсорцную игровую либу для PIC32 и DOS PC под лицензией MIT:

https://gitlab.com/shaos/xorlib

Wiki-документация (буду потихоньку заполнять):

https://gitlab.com/shaos/xorlib/wikis/home

Заголовочный файл со всеми константами и функциям:
Code:
/*

XORLib - old school game library licensed under the MIT License
===============================================================

See for more info: http://www.xorlib.com

*/

#ifndef _XORLIB_H_
#define _XORLIB_H_

#define XORLIB_VERSION 0x0002 /* v0.2 */

/* Available external macros:

   PIC32NTSC - for PIC32MX with 8 MHz crystal and NTSC timings (black and white modes)
   PIC32NTSCQ - for PIC32MX with 14.31818 MHz crystal (with possible color burst mode)
   PIC32PAL - for PIC32MX with 8 MHz crystal and PAL timings (black and white modes)
   PIC32VGA - experimental mode for PIC32MX connected to VGA monitor (future)
   DOS32 - for 32-bit DOS
   DOS16 - for 16-bit DOS
   TERM - emulation of some basic functions through terminal (ncurses)

   DECODEGIF - compiled with GIF decoder (xdec_gif.c)
   DECODEJPG - compiled with JPEG decoder (xdec_jpg.c)
*/

/* NTSC compatible video modes - 320 bits per line */
#define XOMODE_320x200_MONO    0 /* Black and white 320x200 */
#define XOMODE_160x100_GRAY5   1 /* Pseudo mode on top of mode 0 with 5 shades of gray */
/* NTSC compatible video modes - 640 bits per line */
#define XOMODE_640x200_MONO    2 /* Black and white 640x200 */
#define XOMODE_213x200_GRAY4   3 /* Pseudo mode on top of mode 2 with 4 shades of gray */
#define XOMODE_160x200_COL15   4 /* Color burst mode over 640x200 with 15 unique colors (4 pallets) */
#define XOMODE_160x100_COL120  5 /* Pseudo mode on top of mode 4 with about 120 unique dithered colors */
/* NTSC compatible video modes with additional hardware - 640 bits per line */
#define XOMODE_320x200_COL4    6 /* CGA-like mode with configurable 4-color palette */
#define XOMODE_160x200_COL16   7 /* Color mode with standard 16-color palette */
/* NTSC compatible video modes with additional hardware - 1280 bits per line */
#define XOMODE_320x200_COL16   8 /* EGA-like mode with standard 16-color palette */
#define XOMODE_160x200_COL256  9 /* Predefined 256-color RGB-palette (including 64 shades of gray) */
/* NTSC compatible video modes with additional hardware - 2560 bits per line */
#define XOMODE_640x200_COL16  10 /* EGA-like mode with standard 16-color palette */
#define XOMODE_320x200_COL256 11 /* Predefined 256-color RGB-palette (including 64 shades of gray) */
/* VGA compatible video modes (just a placeholder for future) */
#define XOMODE_640x350_COL16  12 /* EGA-like mode with standard 16-color palette */
#define XOMODE_640x480_COL16  13 /* VGA-like mode with standard 16-color palette */
#define XOMODE_800x600_COL16  14 /* SVGA-like mode with standard 16-color palette */
#define XOMODE_ENHANCED_VGA   15 /* Placeholder for other VGA modes */

/* Standard colors (directly supported only in modes >=7 and simulated in mode 5) */
#define XOCOLOR_BLACK           0
#define XOCOLOR_BLUE            1
#define XOCOLOR_GREEN           2
#define XOCOLOR_CYAN            3
#define XOCOLOR_RED             4
#define XOCOLOR_MAGENTA         5
#define XOCOLOR_BROWN           6
#define XOCOLOR_WHITE           7
#define XOCOLOR_GRAY            8
#define XOCOLOR_BRIGHT_BLUE     9
#define XOCOLOR_BRIGHT_GREEN   10
#define XOCOLOR_BRIGHT_CYAN    11
#define XOCOLOR_BRIGHT_RED     12
#define XOCOLOR_BRIGHT_MAGENTA 13
#define XOCOLOR_BRIGHT_YELLOW  14
#define XOCOLOR_BRIGHT_WHITE   15

#define XOCOLOR_INVERT         -1

/* Configuration flags (bits 0..15 for supported graphics modes) */
#define XOCONFIG_BIGENDIAN 0x00010000 /* bit 16 */
#define XOCONFIG_32BITINT  0x00020000 /* bit 17 */
#define XOCONFIG_NTSCTV    0x00040000 /* bit 18 */
#define XOCONFIG_PALTV     0x00080000 /* bit 19 */
#define XOCONFIG_NETWORK   0x00100000 /* bit 20 */
#define XOCONFIG_KEYBOARD  0x00200000 /* bit 21 */
#define XOCONFIG_MOUSE     0x00400000 /* bit 22 */
#define XOCONFIG_SDCARD    0x00800000 /* bit 23 */
#define XOCONFIG_CDROM     0x01000000 /* bit 24 */

/* Control bits */
#define XOCONTROL_LEFT1  0x0001 /* bit 0 */
#define XOCONTROL_RIGHT1 0x0002 /* bit 1 */
#define XOCONTROL_UP1    0x0004 /* bit 2 */
#define XOCONTROL_DOWN1  0x0008 /* bit 3 */
#define XOCONTROL_LEFT2  0x0010 /* bit 4 */
#define XOCONTROL_RIGHT2 0x0020 /* bit 5 */
#define XOCONTROL_UP2    0x0040 /* bit 6 */
#define XOCONTROL_DOWN2  0x0080 /* bit 7 */

/* Some control aliases */
#define XOCONTROL_FIRE   XOCONTROL_LEFT2
#define XOCONTROL_X      XOCONTROL_UP2
#define XOCONTROL_Y      XOCONTROL_LEFT2
#define XOCONTROL_A      XOCONTROL_RIGHT2
#define XOCONTROL_B      XOCONTROL_DOWN2
#define XOCONTROL_UP     XOCONTROL_UP1
#define XOCONTROL_LEFT   XOCONTROL_LEFT1
#define XOCONTROL_RIGHT  XOCONTROL_RIGHT1
#define XOCONTROL_DOWN   XOCONTROL_DOWN1

/* Optional control bits */
#define XOCONTROL_LSHOULDER 0x0100 /* bit 8 */
#define XOCONTROL_RSHOULDER 0x0200 /* bit 9 */
#define XOCONTROL_KEYREADY  0x1000 /* bit 12 - keyboard buffer is not empty */

struct xoimage
{
 short width, height;     /* width and height of the image in pixels */
 unsigned char pitch;     /* pitch in bytes (to calculate vertical offset) */
 signed char bpp;         /* bits per pixel (negative for grayscale) */
 unsigned char *data;     /* pointer to the image data */
 unsigned char *mask;     /* optional pointer to the mask */
};

/* Some macros */
#define VIDEOSCREEN (struct xoimage*)0
#define TEXTNORMAL xotextattr(XOCOLOR_BRIGHT_WHITE,XOCOLOR_BLACK)
#define TEXTINVERT xotextattr(XOCOLOR_BLACK,XOCOLOR_BRIGHT_WHITE)

#ifdef __cplusplus
extern "C" {
#endif

/* System functions */

unsigned long xoconfig(void);                   /* return configuration bits (see above) */
unsigned long xocontrols(void);                 /* return state of controls (see above) */
unsigned long xoframes(void);                   /* return frames counter */
unsigned long xoseconds(void);                  /* return seconds counter */
int xocurline(void);                            /* return current line of the frame (0 is 1st line of the video) */
void xowaitretrace(void);                       /* wait for vertical retrace interval */
void xodelay(int ms);                           /* delay in milliseconds */
int xokeyboard(int *scancode);                  /* return ASCII code from keyboard */
int xomouse(int *px, int *py);                  /* return mouse state (bit 0 - left button, bit 1 - right button) */

/* Graphics functions */

int xoinit(short m);                                    /* set graphics mode -> 0 if failed */
int xopalette(short p);                                 /* set predefined palette (for color modes) -> 0 if invalid id */
int xomode(void);                                       /* get graphics mode -> -1 if not yet set */
int xowidth(void);                                      /* return width of the screen */
int xoheight(void);                                     /* return height of the screen */
int xocls(void);                                        /* clear the screen */
int xopixel(short x, short y, char c);                  /* draw a pixel (-1 means inversion) -> 0 if invalid args */
int xoget(short x, short y);                            /* get state of the pixel (actual value) -> -1 if not supported */
int xoline(short x1, short y1, short x2, short y2, char c); /* draw a line with a color (-1 means inversion) */
int xorect(short x, short y, short w, short h, char c); /* draw a rectangular with a color (-1 means inversion) */
int xobar(short x, short y, short w, short h, char c);  /* draw a solid rectangular with a color (-1 means inversion) */
int xocircle(short x, short y, short r, char c);        /* draw a circle with a color (-1 means inversion) */
int xoellipse(short x, short y, short rx, short ry, char c); /* draw an oval with a color (-1 means inversion) */
int xoarc(short x, short y, short rx, short ry, short a1, short a2, char c); /* draw an arc of oval (-1 means inversion) */
int xopie(short x, short y, short rx, short ry, short a1, short a2, char c); /* draw a solid piece of oval (-1 means inversion) */
int xofill(short x, short y, char c);                   /* fill a region with a color (inversion is not applicable) */
int xopoly(char c, short n, short *a);                  /* draw a polygon from array {x,y, x,y, etc. } */
int xotextattr(char i, char p);                         /* set text color attributes (ink, paper) */
int xochar(unsigned char x, unsigned char y, char c);   /* print character using text location */
int xostring(unsigned char x, unsigned char y, char* s);/* print string using text location */
int xoprintf(char* s, ...);                             /* print string to current position with a possible scroll */
int xouserchar(char c, unsigned char* p);               /* add user character with code 0...31 using 8 bytes -> 0 if error */
int xotextwidth(void);                                  /* return text screen width */
int xotextheight(void);                                 /* return text screen height */
int xogray5(int i);                                     /* 5 shades of gray function (0,1,2,3,4) returns ASCII code */
int xoswitchscreens(void);                              /* switch primary and secondary screens (in case of double buffering) */
int xouseprimary(void);                                 /* use primary screen (default) */
int xousesecondary(void);                               /* use secondary screen (in case of double buffering) */
unsigned char* xodirectline(short y);                   /* return pointer to video line for direct access */
unsigned char* xoprevline(unsigned char *p);            /* return pointer to the previous video line for direct access */
unsigned char* xonextline(unsigned char *p);            /* return pointer to the next video line for direct access */
int xocopy(struct xoimage* d, struct xoimage* s);       /* copy one image into another with mask if presented */
int xorcopy(struct xoimage* d, struct xoimage* s);      /* copy one image into another with xor -> 0 if not supported */
int xopcopy(struct xoimage* d, struct xoimage* s, short x, short y, short w, short h); /* partial copy without mask */
int xopcopyk(struct xoimage* d, struct xoimage* s, short x, short y, short w, short h, char c); /* partial copy with a key color */
int xocopytxt(struct xoimage* d, const char* s, short x, short y); /* render text to image coordinates x,y */
int xocopyxbm(struct xoimage* d, const unsigned char* s, short w, short h);  /* copy image from XBM */
int xocopyeta(struct xoimage* d, const unsigned char* s, short f, short *t); /* copy image from ETA frame */
int xocopymyg(struct xoimage* d, const unsigned char* s, short f, short *t); /* copy image from MYG frame */
int xocopygif(struct xoimage* d, const unsigned char* s, short f, short *t); /* copy image from GIF frame (if GIF decoder is enabled) */
int xocopyjpg(struct xoimage* d, const unsigned char* s); /* copy image from JPEG (if JPEG decoder is enabled) */

#ifdef __cplusplus
}
#endif

#endif

_________________
:dj: https://mastodon.social/@Shaos


04 Apr 2015 19:46
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Для декодера JPEG подтянул "публикдомайную" целочисленную либу picojpeg:

https://code.google.com/p/picojpeg/

а для декода GIF-ов (в том числе анимированных) - либу libnsgif, которая распостраняется под лиценизей MIT:

http://www.netsurf-browser.org/projects/libnsgif/

_________________
:dj: https://mastodon.social/@Shaos


04 Apr 2015 19:54
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Научил libnsgif декодить GIF не только в 32-битные пикселы, но и в 8-битные, 4-битные, 2-битные и 1-битные ;)
Пока правда ограничение есть - по ширине картинка должна умещаться в 32-битных целых числах, т.е.
- при декоде в 8-битный буфер, ширина оригинальной картинки должна быть кратна 4 пикселам;
- при декоде в 4-битный буфер, ширина оригинальной картинки должна быть кратна 8 пикселам;
- при декоде в 2-битный буфер, ширина оригинальной картинки должна быть кратна 16 пикселам;
- при декоде в 1-битный буфер, ширина оригинальной картинки должна быть кратна 32 пикселам.
Возможно позже уберу это ограничение...

P.S. Также в первом посте топика поправил описание графических режимов в соответствии с последними результатами экспериментов

_________________
:dj: https://mastodon.social/@Shaos


06 Apr 2015 15:43
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Благодаря блогу опасных прототипов попал на 3 первых места в поисковиках по запросу "xorlib" ;)

P.S. nedopc.org чегой-то плохо стал индексироваться поисковиками...

_________________
:dj: https://mastodon.social/@Shaos


13 Apr 2015 07:55
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Сегодня в список функций запланированных к реализации добавилось копирование из MYG-формата (MYG = MY Graphics):
Code:
int xocopymyg(struct xoimage* d, unsigned char* s, int f); /* copy image from MYG frame */

Этот формат представления 16-цветных и 256-цветных картинок я придумал на 5 курсе универа в 1995 году, когда делал всякие практические лабы по хаосу и фракталам на 386DX компах - формат использовал RLE и сжимал лучше PCX, а на некоторых картинках даже лучше GIF, плюс давал возможность делать анимацию (надо чтоли на ютюб выложить эти лабы - было прикольно для того времени)...

P.S. Выложил видео программки тех времён (май 1995) с хаотично сгенерённой луной :dj:


https://youtu.be/1-XwFXB843A

_________________
:dj: https://mastodon.social/@Shaos


14 Apr 2015 20:58
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Начал потихоньку городить XORLib wiki:

github.com/shaos/xorlib/wiki

P.S. Туда сейчас перекидывает xorlib.com

_________________
:dj: https://mastodon.social/@Shaos


16 Apr 2015 18:45
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Версия v0.2 теперь работает и на PC с CGA, правда с 32-битным процом ;)

P.S. Вот батник для сборки XORLib-приложений для PC с помощью OpenWatcom-1.9:
Code:
SET WATCOM=C:\SYSTEM\WATCOM19
SET INCLUDE=%WATCOM%\H
SET WATBIN=%WATCOM%\BINW
SET PATH=%WATBIN%;%PATH%
%WATBIN%\wpp386 /onatx /oh /oi+ /ei /3 /fp3 /dDOS32 %1.c xorlib.c nedofont.c
%WATBIN%\wlink system pmodew option stack=64k file %1,xorlib,nedofont name %1

_________________
:dj: https://mastodon.social/@Shaos


24 Apr 2015 19:21
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
А не портировать ли мне XORLib ещё и вот сюда?

https://www.pjrc.com/store/teensy31.html

Тут тоже 256К флеша, 64К озу и куча ио...

_________________
:dj: https://mastodon.social/@Shaos


16 May 2015 18:59
Profile WWW
Senior

Joined: 23 Feb 2015 15:37
Posts: 151
Location: OMS
Reply with quote
Quote:
#define XOMODE_320x200_COL256 11 /* Predefined 256-color RGB-palette (including 64 shades of gray) */
/* VGA compatible video modes (just a placeholder for future) */
#define XOMODE_640x350_COL16 12 /* EGA-like mode with standard 16-color palette */
#define XOMODE_640x480_COL16 13 /* VGA-like mode with standard 16-color palette */
#define XOMODE_800x600_COL16 14 /* SVGA-like mode with standard 16-color palette */
#define XOMODE_ENHANCED_VGA 15 /* Placeholder for other VGA modes */


Т.е. если я правильно понял, то 256 цветов уже можно? :)
Да такая библиотечка нужна везде, портируй! :rotate:


26 Jun 2015 04:13
Profile
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Odin P. Morgan wrote:
Quote:
#define XOMODE_320x200_COL256 11 /* Predefined 256-color RGB-palette (including 64 shades of gray) */
/* VGA compatible video modes (just a placeholder for future) */
#define XOMODE_640x350_COL16 12 /* EGA-like mode with standard 16-color palette */
#define XOMODE_640x480_COL16 13 /* VGA-like mode with standard 16-color palette */
#define XOMODE_800x600_COL16 14 /* SVGA-like mode with standard 16-color palette */
#define XOMODE_ENHANCED_VGA 15 /* Placeholder for other VGA modes */


Т.е. если я правильно понял, то 256 цветов уже можно? :)
Да такая библиотечка нужна везде, портируй! :rotate:


только в версии для PC можно - на PIC32 пока нельзя...

_________________
:dj: https://mastodon.social/@Shaos


26 Jun 2015 14:38
Profile WWW
Senior

Joined: 23 Feb 2015 15:37
Posts: 151
Location: OMS
Reply with quote
Попробую найти в продаже PIC32, и попробую накатать смещения палитры.


28 Jun 2015 08:04
Profile
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Shaos wrote:
Сегодня в список функций запланированных к реализации добавилось копирование из MYG-формата (MYG = MY Graphics):
Code:
int xocopymyg(struct xoimage* d, unsigned char* s, int f); /* copy image from MYG frame */

Этот формат представления 16-цветных и 256-цветных картинок я придумал на 5 курсе универа в 1995 году, когда делал всякие практические лабы по хаосу и фракталам на 386DX компах - формат использовал RLE и сжимал лучше PCX, а на некоторых картинках даже лучше GIF, плюс давал возможность делать анимацию (надо чтоли на ютюб выложить эти лабы - было прикольно для того времени)...

P.S. Выложил видео программки тех времён (май 1995) с хаотично сгенерённой луной :dj:


https://youtu.be/1-XwFXB843A


Приближающуюся Луну отсюда задействовал в своей "супердеме", перекодировав в новый формат v57 :)



https://youtu.be/xI5DuTKPWsA?t=4m (линк сразу перематывает к нужному месту)

_________________
:dj: https://mastodon.social/@Shaos


19 Nov 2016 19:26
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Забыл сюда написать, что в 2018 году я частично портировал XORLib на TFT экран:


https://www.youtube.com/watch?v=V4lDQX5Ax-U

Там хитрость есть, что при следующем вызове xodirectline заполненная в предыдущий раз строка (как массив байтов) переводится в TFT-шные пикселы

P.S. Писал про это в другом топике: http://www.nedopc.org/forum/viewtopic.php?p=148480#p148480

_________________
:dj: https://mastodon.social/@Shaos


04 Oct 2022 21:50
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Вобщем я вот чего думаю - вместо того чтобы экспериментировать на реальном железе, наблюдая в реальности во что может превратиться та или иная последовательность пикселов:



Image


надо написать софт для ПЦ, который будет имитировать "обманувшийся" телек NTSC по входной ч/б картинке - это вроде бы должно быть не сложно:

Attachment:
NTSC_vectorograph.png
NTSC_vectorograph.png [ 139.51 KiB | Viewed 26177 times ]
https://people.ece.cornell.edu/land/courses/ece5760/video/gvworks/GV%27s%20works%20%20NTSC%20demystified%20-%20Color%20Encoding%20-%20Part%202.htm

чтобы можно было программно получить такое:

Attachment:
1k06_cga_composite_fringing_artifacts.png
1k06_cga_composite_fringing_artifacts.png [ 16.97 KiB | Viewed 26173 times ]
https://int10h.org/blog/2015/04/cga-in-1024-colors-new-mode-illustrated/

для этого надо превратить последовательность пикселов в аналоговый сигнал и пользуясь опорным сигналом "color burst" вычислить амплитуду и фазу получающихся цветных пикселов (я что-то такое уже вычислял в конце 90х, когда строил цифровую противоаварийную автоматику для сургутской ГРЭС-2 - там по входящим замерам напряжения и тока в линии надо было в реальном времени считать амплитуды и фазы, а тут ещё постоянную составляющую считать надо для яркости).

_________________
:dj: https://mastodon.social/@Shaos


11 Jan 2023 01:27
Profile WWW
Admin
User avatar

Joined: 08 Jan 2003 23:22
Posts: 22409
Location: Silicon Valley
Reply with quote
Суть алгоритма демодуляции цвета вот на этой картинке показана (я именно так считал фазы и амплитуды напряжения и тока в линии 500 кВ в конце 90х):

Attachment:
chromademod.jpg
chromademod.jpg [ 9.8 KiB | Viewed 26129 times ]

http://www.ifp.illinois.edu/~yuhuang/ntscdecoding.htm

Для получения сигнала цветности пропускаем входной сигнал через фильтр высокой частоты (по хорошему полосовой). А теперь как по картинке выше - берём опорный сигнал с частотой 3.57954 МГц - прямой и повёрнутый на 90 градусов (т.е. COS и SIN), на которые умножается сигнал цветности и каждый из двух полученных сигналов пропускается через фильтр низкой частоты - в результате получаем координаты цветового вектора (V и U), переводя которые в полярные координаты получаем фазу (угол цвета) и амплитуду (интенсивность цвета как в цветовом диске выше).

А для выделения сигнал яркости просто пропускаем входной сигнал через фильтр низкой частоты (с частотой среза меньше 3.5 МГц) - вот и вся нехитрая математика.

Естественно оперировать мы будем последовательностями отсчётов, которые на самом деле не будут идти в реальном времени (т.е. не с частотой дискретизации 14.31818 МГц) и фильтровать мы их будем цифровыми фильтрами в течение некоторого времени, которое будет тем короче, чем более производительный компьютер будет использоваться...

P.S. Я такой фокус с косинусами и синусами оказывается уже проделывал в апреле 2020 года тут на форуме - только я использовал этот фокус для выделения частот (вместо полосового фильтра).

_________________
:dj: https://mastodon.social/@Shaos


11 Jan 2023 21:26
Profile WWW
Display posts from previous:  Sort by  
Reply to topic   [ 32 posts ]  Go to page 1, 2, 3  Next

Who is online

Users browsing this forum: imsushka and 14 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Powered by phpBB® Forum Software © phpBB Group
Designed by ST Software.