SAIFIINDUSTRIES's picture
Add Repo: JulianKemmerer_PipelineC-Graphics
3459b20 verified
Raw
History Blame Contribute Delete
18.5 kB
/*
(C) 2021 Victor Suarez Rovere <suarezvictor@gmail.com>
LICENSE: GPL 3.0
This is a cflextypes demo for running unmodified PipelineC code in a CPU using a regular compiler.
To play: use UP key or the left mouse button
Compile & run:
$ clang++ -fopenmp=libiomp5 -I../../../include -O3 -ffast-math `sdl2-config --cflags --libs` simulator_main.cpp -o tr && ./tr
Currently doing 60FPS at 400x300 resolution. Faster speed is sometimes achieved by using native width registers that are not exact in regards to width as compared to the defined ones. For example, if a uint4_t is used, a uint8_t is allocated. To enable this, add -DNO_BIT_EXACT to the compiler parameters.
With parameter -DGATEWARE_VGA the video timing signals are generated by the HDL code instead of an optimized equivalent code, at the cost of about half the performance (and 4-bit color per channel).
There's no game nor render logic in this source, all that is defined by the HDL sources. Thus, they can be changed to implement any other interactive system with video output.
*/
//#define LINUX_FB "/dev/fb0"
//#define POWER_BENCH
//#define GATEWARE_VGA
//#define DUMP_FRAMES
#include <SDL2/SDL.h>
#define sqrt _sqrt //avoid library conflict
#ifndef _FRAME_WIDTH
#define FRAME_WIDTH 400
#define FRAME_HEIGHT 300
#endif
#define FRAME_FPS 60
int FRAME_WIDTH = _FRAME_WIDTH;
int FRAME_HEIGHT = _FRAME_HEIGHT;
#include "pipelinec_compat.h"
#include "float_type.h"
#ifndef CCOMPILE
#undef FP_DEBUG
#include "tr_pipelinec.cpp" //original source
#else
#include "fixed_type.h"
#include "tr_pipelinec.gen.c" //generated source
#endif
#undef float //just in case
#define FRAME_PITCH 4096
//struct pixel_t { uint8_t a, b, g, r; };
pixel_t pixelbuf[FRAME_PITCH*FRAME_PITCH];
//#include "pipelinec_compat.h"
#ifndef FRAME_WIDTH
#define FRAME_WIDTH FRAME_WIDTH
#define FRAME_HEIGHT FRAME_HEIGHT
#endif
#include "vga/vga_timing.h"
#warning integrate with crflexhdl graphics functions
unsigned buttons_pressed();
bool fb_init(unsigned hres, unsigned vres);
void fb_update();
bool fb_should_quit();
void fb_deinit();
void fb_save_texture(int frame);
inline void fb_setpixel_raw(pixel_t *p, uint8_t r, uint8_t g, uint8_t b) { p->a = 0xFF; p->b = b; p->g = g; p->r = r; }
inline void fb_setpixel(unsigned x, unsigned y, uint8_t r, uint8_t g, uint8_t b) { fb_setpixel_raw(&pixelbuf[y*FRAME_PITCH+x], r, g, b); }
inline uint64_t higres_ticks() { return SDL_GetPerformanceCounter(); }
inline uint64_t higres_ticks_freq() { return SDL_GetPerformanceFrequency(); }
unsigned frame = 0;
uint64_t t0;
double total_rendering_time = 0;
#ifdef POWER_BENCH
double total_energy = 0;
bool power_enabled = false;
#endif
#include <iostream>
void perf_render_dump();
void perf_clear();
void dump_stats()
{
float elapsed = (float)(higres_ticks()-t0)/higres_ticks_freq();
float fps = frame/elapsed;
printf("Resolution: %dx%d, FPS: %.1f\n", FRAME_WIDTH, FRAME_HEIGHT, fps);
#ifdef POWER_BENCH
if(power_enabled)
{
printf("Energy %.2fJ (Watt-second), Time %.2fs, Average power: %.2fW (%.2fW adjusted to %.1f FPS), Mpixel/Watt-second: %.2f\n",
total_energy, total_rendering_time,
total_energy / total_rendering_time,
(FRAME_FPS/fps) * total_energy / total_rendering_time,
float(FRAME_FPS),
1e-6*FRAME_WIDTH*FRAME_HEIGHT*frame/total_energy
);
}
#endif
}
#ifndef _DEBUG
//#define MOTION_BLUR // EXPERIMENTAL
#endif
#ifdef MOTION_BLUR
int current_blur_x, current_blur_y;
float blur_dist_a[FRAME_PITCH*FRAME_PITCH];
float blur_dist_curr[FRAME_PITCH*FRAME_PITCH];
void register_dist(float d)
{
int x = current_blur_x, y = current_blur_y;
blur_dist_a[y*FRAME_PITCH+x] = blur_dist_curr[y*FRAME_PITCH+x];
blur_dist_curr[y*FRAME_PITCH+x] = d;
}
#endif
inline void vga_register_outputs(vga_signals_t vga, pixel_t c)
{
#ifdef GATEWARE_VGA
if(vga.active)
fb_setpixel(vga.pos.x, vga.pos.y, c.r, c.g, c.b);
if(vga.start_of_frame)
{
if(fb_should_quit())
{
dump_stats();
exit(0);
}
fb_update();
++frame;
}
#endif
}
#ifdef FP_DEBUG
perfcount currentperf, fixedperf/*, colorperf, screen_coord_perf*/;
template<> perfcount *float_narrow::perf = &currentperf;
perfcount *fixed_perf = &fixedperf;
//template<> perfcount *fixed::perf = &fixedperf;
//template<> perfcount *color_type::perf = &colorperf;
//template<> perfcount *screen_coord_t::perf = &screen_coord_perf;
void perfcount::clear()
{
memset(this, 0, sizeof(*this));
}
void perfcount::dump()
{
/*if(mul)*/ printf("MUL: %d\n", mul);
if(add) printf("ADD: %d\n", add);
if(fmuladd) printf("FMULADD: %d\n", fmuladd);
if(sub) printf("SUB: %d\n", sub);
if(div) printf("DIV: %d\n", div);
if(unary_minus) printf("UNARY MINUS: %d\n", unary_minus);
if(cmp) printf("CMP: %d\n", cmp);
if(inttofp) printf("INT TO FP: %d\n", inttofp);
if(fptoint) printf("FP TO INT: %d\n", fptoint);
if(inttofix) printf("INT TO FIX: %d\n", inttofix);
if(fixtoint) printf("FIX TO INT: %d\n", fixtoint);
if(fptofix) printf("FP TO FIX: %d\n", fptofix);
if(fixtofp) printf("FIX TO FP: %d\n", fixtofp);
printf("\n");
}
#endif
/*
#ifndef SPIRV
#include "tr.c" //raytraced game or any other drawing program
#else
#include "spirv_compat.h"
#define main shader_main
#include "tr.gen.c" //code generated from SPIR-V
#undef main
#undef GATEWARE_VGA
*/
/*
inline pixel_t render_pixel(uint16_t i, uint16_t j, IN(Scene) scene)
{
float x = ((i<<1)-FRAME_WIDTH-1)/(float)(FRAME_HEIGHT<<1);
float y = -((j<<1)-FRAME_HEIGHT-1)/(float)(FRAME_HEIGHT<<1);
pixel_t pix; //ignores alpha
{
vec3 c = render_pixel_internal(x, y, scene, scene_colors(scene));
uint9_t r = float_shift(c.x, 8);
uint9_t g = float_shift(c.y, 8);
uint9_t b = float_shift(c.z, 8);
pix.r = (uint8_t) ((r & ~0xFF) ? (uint8_t)0xFF:(uint8_t)r);
pix.g = (uint8_t) ((g & ~0xFF) ? (uint8_t)0xFF:(uint8_t)g);
pix.b = (uint8_t) ((b & ~0xFF) ? (uint8_t)0xFF:(uint8_t)b);
}
return pix;
}
*/
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
int main()
{
if(!fb_init(FRAME_WIDTH, FRAME_HEIGHT))
return 1;
int outfd = -1;
{
int nbytes = 0;
if(ioctl(0, FIONREAD, &nbytes) == 0 && nbytes == 0)
{
printf("creating output file\n");
outfd = open("buttons-out.bin", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
if(outfd < 0)
{
perror("cannot open output file");
return 1;
}
}
}
#ifndef GATEWARE_VGA
state = full_update(state, true, false); //reset state
#endif
t0 = higres_ticks();
for(;;)
{
#ifdef GATEWARE_VGA
app();
#else
if(fb_should_quit())
break;
/*if(frame == 25)
--frame;
else*/
#if !defined(FP_DEBUG) && !defined(COLOR_DECOMP)
#pragma omp parallel for
#endif
for(int y = 0; y < FRAME_HEIGHT; ++y)
{
for(int x = 0; x < FRAME_WIDTH; ++x)
{
perf_clear();
#ifdef MOTION_BLUR
current_blur_x=x; current_blur_y=y;
#endif
#ifndef COLOR_DECOMP
pixel_t c = render_pixel(x, y);
#else
pixel_t c;
#if COLOR_DECOMP == 1
state.scene.current_color_channel = 0; //use red channel
c = render_pixel(x, y, c);
c.g = c.r;
c.b = c.r;
#else
for(int ch = 0; ch < 3; ++ch)
{
state.scene.current_color_channel = ch;
c = render_pixel(x, y, c);
}
#endif
#endif
perf_render_dump();
//while(frame == 26) { if(fb_should_quit()) exit(0); }
#ifdef MOTION_BLUR
static pixel_t pixelbuftmp[FRAME_PITCH*FRAME_PITCH];
{
pixel_t ct = pixelbuftmp[y*FRAME_PITCH+x];
//pixelbuftmp[y*FRAME_PITCH+x] = c; //no IIR
float distb = blur_dist_curr[y*FRAME_PITCH+x];
float dista = blur_dist_a[y*FRAME_PITCH+x];
float mm = distb;//FMAX(distb, dista);
if(mm >= /*0*/-1 && mm< 1)
{
float m = mm;///FMAX(distb,dista);//FABS(distb-dista);
#if 0
//float mix = .5;
c = pixel_t({ 0xFF,
uint8_t(float_select(m, c.b, ct.b)),
uint8_t(float_select(m, c.g, ct.g)),
uint8_t(float_select(m, c.r, ct.r)),
});
#else
c = pixel_t({ 0xFF,
uint8_t(m>0? m*255:0),//uint8_t(is_negative(m) ? 0 : m),
uint8_t(m<0 ? -m*255 : 0) ,//uint8_t(is_negative(m) ? -m : 0),
0,//c.r,
});
#endif
}
}
pixelbuftmp[y*FRAME_PITCH+x] = c; //IIR, FIXME avoid buffer
#endif
fb_setpixel(x, y, c.r, c.g, c.b);
}
}
#ifndef GATEWARE_VGA
uint8_t buttons = 0;
int nbytes;
if(ioctl(0, FIONREAD, &nbytes) == 0 && nbytes > 0)
read(0, &buttons, sizeof(buttons));
buttons |= buttons_pressed();
write(outfd, &buttons, sizeof(buttons));
state = full_update(state, false, buttons & 1);
#endif
fb_update();
#ifdef DUMP_FRAMES
fb_save_texture(frame);
#endif
++frame;
#ifdef POWER_BENCH
if(power_enabled && frame >= FRAME_FPS*30)
break;
#endif
if((frame % int(FRAME_FPS)) == 0)
dump_stats();
#endif
}
dump_stats();
close(outfd);
fb_deinit();
return 0;
}
#ifdef POWER_BENCH
#include "power.cpp"
#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
#endif
#ifdef LINUX_FB
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
int open_framebuffer(unsigned& w, unsigned& h, size_t& stride, unsigned& bpp, char *&fbp)
{
int fbfd = 0;
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
fbp = NULL;
w = h = stride = bpp = 0;
// Open the file for reading and writing
fbfd = open(LINUX_FB, O_RDWR);
if (!fbfd) {
printf("Error: cannot open framebuffer device.\n");
exit(1);
}
// Get fixed screen information
if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) {
printf("Error reading fixed information.\n");
exit(2);
}
// Get variable screen information
if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
printf("Error reading variable information.\n");
exit(3);
}
if(vinfo.bits_per_pixel != 32)
{
printf("Only 32 bpp supported.\n");
exit(4);
}
w = vinfo.xres;
h = vinfo.yres;
bpp = vinfo.bits_per_pixel;
stride = finfo.line_length;
// Figure out the size of the screen in bytes
size_t screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;
// Map the device to memory
fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED,
fbfd, 0);
if ((intptr_t)fbp == -1) {
printf("Error: failed to map framebuffer device to memory.\n");
exit(5);
}
//printf("The framebuffer device was mapped to memory successfully.\n");
return fbfd;
}
char *fbp;
size_t fb_stride;
unsigned fb_w, fb_h;
bool fb_init(unsigned hres, unsigned vres)
{
unsigned bpp;
int fbfd = open_framebuffer(fb_w, fb_h, fb_stride, bpp, fbp);
if(fbfd < 0)
return false;
#ifdef POWER_BENCH
power_enabled = power_init();
#endif
return true;
}
void display_frame()
{
//TODO: do a full memcpy if resolution matches
char *dst = fbp;
const pixel_t *src = pixelbuf;
size_t sz = FRAME_WIDTH*sizeof(pixel_t);
if(sz == fb_stride && fb_w == FRAME_PITCH && fb_h >= FRAME_HEIGHT)
{
memcpy(dst, src, fb_h*fb_stride);
return;
}
if(sz > fb_stride) sz = fb_stride;
for(int i=0; i < FRAME_HEIGHT; ++i)
{
memcpy(dst, src, sz);
dst += fb_stride;
src += FRAME_PITCH;
}
}
bool fb_should_quit()
{
return false; //TODO: read keyboard
}
void fb_deinit()
{
}
unsigned buttons_pressed()
{
return 0; //TODO: read keyboard
}
#else
SDL_Window* win = NULL;
SDL_Renderer* renderer = NULL;
SDL_Texture* texture = NULL;
bool fb_init(unsigned width, unsigned height)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
return false;
SDL_DisplayMode dm;
if (SDL_GetDesktopDisplayMode(0, &dm) != 0)
return false;
if(width == 0 || height == 0)
{
width = dm.w;
height = dm.h;
}
win = SDL_CreateWindow("Framebuffer", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN);
if (!win)
return false;
bool fullscreen = (dm.w == width && dm.h == height);
#ifdef POWER_BENCH
power_enabled = power_init();
//fullscreen = fullscreen && !power_enabled;
#endif
if(fullscreen)
SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN);
SDL_ShowCursor(SDL_DISABLE);
//fullscreen = true; //unncoment to limit FPS
renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE | (fullscreen ? SDL_RENDERER_PRESENTVSYNC: 0));
if (!renderer)
return false;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, width, height);
if (!texture)
return false;
return true;
}
bool fb_should_quit()
{
SDL_Event event;
if (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
if(event.key.keysym.sym != SDLK_ESCAPE)
break;
case SDL_QUIT:
return true;
}
}
return false;
}
void display_frame()
{
SDL_UpdateTexture(texture, NULL, pixelbuf, FRAME_PITCH*sizeof(pixel_t));
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
void fb_deinit()
{
SDL_SetWindowFullscreen(win, 0); //SDL_WINDOW_FULLSCREEN
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(win);
SDL_Quit();
}
unsigned buttons_pressed()
{
unsigned mpress = 0;
{ int x, y; mpress = SDL_GetMouseState(&x, &y); }
const uint8_t *st = SDL_GetKeyboardState(NULL);
return
(st[SDL_SCANCODE_UP] || (mpress & SDL_BUTTON_LMASK) ? 1 : 0) |
(st[SDL_SCANCODE_DOWN] || (mpress & SDL_BUTTON_RMASK) ? 2 : 0) |
(st[SDL_SCANCODE_W] ? 4 : 0) |
(st[SDL_SCANCODE_S] ? 8 : 0);
}
#endif
void fb_update()
{
//return; //uncomment to skip video output
display_frame();
static uint64_t t0 = higres_ticks();
static uint64_t tickf = higres_ticks_freq();
uint64_t t1 = higres_ticks();
uint64_t dticks = t1 - t0;
double dt = double(dticks) / tickf;
total_rendering_time += dt;
#ifdef POWER_BENCH
static std::condition_variable cv;
static std::mutex cv_m;
static std::atomic<int> i{0};
static auto t = std::chrono::system_clock::now();
std::unique_lock<std::mutex> lk(cv_m);
t += 1000000us/FRAME_FPS;
if(power_enabled)
{
static unsigned long e0 = get_package_energy();
static double unit = get_energy_unit();
unsigned long e1 = get_package_energy();
unsigned long energy = e1 - e0;
total_energy += energy*unit;
//printf("package energy: %f watts, FPS %g\n", energy*unit/dt, 1./dt);
cv.wait_until(lk, t, [](){return false;});
e0 = get_package_energy(); //skips energy for just waiting
//e0 = e1;
}
else
{
cv.wait_until(lk, t, [](){return false;});
}
#endif
t0 = t1;
}
void fb_save_texture(int frame)
{
char fname[20];
snprintf(fname, sizeof(fname), "frame%d.ppm", frame);
FILE *fp = fopen(fname, "wb");
//printf("File: %s (fd %p)\n", fname, fp);
fprintf(fp, "P6\n%d %d\n255\n", FRAME_WIDTH, FRAME_HEIGHT);
const pixel_t *pix = pixelbuf;
for(int y = 0; y < FRAME_HEIGHT; ++y)
{
for(int x = 0; x < FRAME_WIDTH; ++x)
{
uint8_t color[]={pix->r, pix->g, pix->b};
fwrite(color, 1, sizeof(color), fp);
++pix;
}
pix += FRAME_PITCH - FRAME_WIDTH;
}
fclose(fp);
printf("Saved frame %d\n", frame);
}
void perf_clear()
{
#ifdef FP_DEBUG
float_narrow::perf->clear();
//coord_type::perf->clear();
fixed_perf->clear();
//screen_coord_t::perf->clear();
//color_type::perf->clear();
#endif
}
void perf_render_dump()
{
#ifdef FP_DEBUG
static perfcount max;
if(float_narrow::perf->mul > max.mul)
{
max = *float_narrow::perf;
std::cout << "Rendering floating point operations:" << std::endl;
max.dump();
}/*
static perfcount fixedmax;
if(coord_type::perf->mul > fixedmax.mul)
{
fixedmax = *coord_type::perf;
std::cout << "Rendering fixed point operations" << std::endl;
fixedmax.dump();
}
*/
static perfcount fixedmax;
if(fixed_perf->mul > fixedmax.mul)
{
fixedmax = *fixed_perf;
std::cout << "Rendering fixed point operations" << std::endl;
fixedmax.dump();
}
/*
static perfcount screencoordmax;
if(screen_coord_t::perf->mul > screencoordmax.mul)
{
screencoordmax = *screen_coord_t::perf;
std::cout << "Rendering screencoord fixpoint operations" << std::endl;
screencoordmax.dump();
}
static perfcount colormax;
if(color_type::perf->mul > colormax.mul)
{
colormax = *color_type::perf;
std::cout << "Rendering color fixpoint operations" << std::endl;
colormax.dump();
}*/
#endif
}
void perf_gameplay_dump()
{
#ifdef FP_DEBUG
static perfcount max;
if(float_narrow::perf->mul > max.mul)
{
max = *float_narrow::perf;
std::cout << "Gameplay fp32 operations" << std::endl;
max.dump();
}
/*
static perfcount fixedmax;
if(coord_type::perf->mul > fixedmax.mul)
{
fixedmax = *coord_type::perf;
std::cout << "Gameplay fixed point operations" << std::endl;
fixedmax.dump();
}*/
static perfcount fixedmax;
if(fixed_perf->mul > fixedmax.mul)
{
fixedmax = *fixed_perf;
std::cout << "Gameplay fixed point operations" << std::endl;
fixedmax.dump();
}
/*
static perfcount colormax;
if(color_type::perf->mul > colormax.mul)
{
colormax = *color_type::perf;
std::cout << "Gameplay color fixpoint operations" << std::endl;
colormax.dump();
}
static perfcount screencoordmax;
if(screen_coord_t::perf->mul > screencoordmax.mul)
{
screencoordmax = *screen_coord_t::perf;
std::cout << "Gameplay screencoord fixpoint operations" << std::endl;
screencoordmax.dump();
}*/
#endif
}