I am trying to modify the framebuffer on Linux. I am running the program through a virtual terminal (tty). I cannot seem to modify the pixel I want. Here is my code:
#include <stdio.h>
unsigned char buffer[4 * 1366 * 768];
const int framewidth = 1366;
void placepixel(int x, int y, int r, int g, int b, int a){
buffer[(framewidth * y) + x] = b;
buffer[(framewidth * y) + x+1] = g;
buffer[(framewidth * y) + x+2] = r;
buffer[(framewidth * y) + x+3] = a;
}
void placepixelbynum(int i, int r, int g, int b, int a){
buffer[i] = b;
buffer[i+1] = g;
buffer[i+2] = r;
buffer[i+3] = a;
}
int main(){
for(int i = 0; i < 4 * 1366 * 768; i+=4){
placepixelbynum(i, 50,50,50,0);
}
FILE *write_ptr;
write_ptr = fopen("/dev/fb0","wb");
int x, y, z, xr, yr, zr;
while(true){
for(int i = 0; i < 128; i++){
placepixel(128+i,128,255,0,0,0);
}
fwrite(buffer,sizeof(buffer),1,write_ptr);
}
return 0;
}
When I run this, the screen turns gray (as expected), but places the line not where I expected. (I want it to start at 128x128 and end at 256x128), but it is near the right end of the screen.
The problem appears it would seem, from a failure to account for 4 bytes of buffer-space for each pixel. Consider the following desk-check
pixel(0,0)
(framewidth*y) + x + 0 -> 0
(framewidth*y) + x + 1 -> 1
(framewidth*y) + x + 2 -> 2
(framewidth*y) + x + 3 -> 3
pixel(1,0)
(framewidth*y) + x + 0 -> 1
(framewidth*y) + x + 1 -> 2
(framewidth*y) + x + 2 -> 3
(framewidth*y) + x + 3 -> 4
I suspect you'll have slightly more success with something like this:
void placePixel(int x, int y, int r, int g, int b, int a)
{
int index = 4 * ((frameWidth*y) + x)
buffer[index+0] = r;
buffer[index+1] = g;
buffer[index+2] = b;
buffer[index+3] = a;
}