我正在尝试仅使用 gldrawpixels() (和 glfw)编写我自己的光栅化器。我不能使用 opengl 3 或 4 的东西,因为我的笔记本电脑只有 intelgraphics。我想让我的代码跨平台,所以没有 windows.h。我不能使用 pixeltoaster,因为它不是基于 mingw 构建的。当我运行我的程序时它崩溃了,为什么?我不知道哪个函数导致错误。
这是我的代码:
我的 main.cpp:
#include "main.h"
GLFWwindow* window;
unsigned int x ,y,size;
float* pixeldata;
// init
bool init()
{
bool init_val;
if(!glfwInit() )
{
std::cout << "GLFW failed to initialize \n";
init_val = false;
glfwTerminate();
return init_val;
}
init_val = true;
return init_val;
}
//creat window and allocate memory for pixelbuffer
int createwindow(int width, int height, char* window_name, int fullscreen)
{
x = width;
y = height;
size = x*y;
pixeldata = new float[size*3];
std::cout << size;
if (fullscreen == 1)
{
window = glfwCreateWindow( width, height, window_name ,glfwGetPrimaryMonitor(),NULL );
}
else
{
window = glfwCreateWindow( width, height, window_name ,NULL,NULL );
}
if(!window)
{
std::cout << "failed to open window! \n";
glfwTerminate();
return -1;
}
else
{
glfwMakeContextCurrent(window);
}
}
//places pixel on screen, doesn't work properly
void setpixel(unsigned int xloc,unsigned int yloc)
{
unsigned int pixloc;
pixloc = xloc * yloc;
if(pixloc > size)
{
std::cout << "TOO FAR!";
glfwWindowShouldClose(window);
glfwTerminate();
}
else
{
pixeldata[pixloc*3] = 10;
}
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(x, y, GL_RGB, GL_FLOAT, pixeldata);
}
int main()
{
init();
createwindow(760, 360,"window", 0);
drawline(10,10, 380,180);
while (!glfwWindowShouldClose(window))
{
render();
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
}
我的 main.h:
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
//GL libs
#include <GL/glfw.h>
#include <GLM/glm.hpp>
// STD libs
#include <iostream>
#include <string>
#include <fstream>
#include <thread>
#include <cmath>
//shared functions
//main.cpp
void setpixel(unsigned int xloc, unsigned int yloc);
//draw.cpp
void drawline( unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1 );
我的draw.cpp:
#include "main.h"
//does not work, should draw a line
void drawline( unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1 )
{
int dx = x1 - x0;
int dy = y1 - y0;
int a = dy/dx;
int x2 = x0, y2 = y0;
int b = (a*x2) - y2;
b *= -1;
for (int i = x0; x0 <= x1; i++)
{
y2 = a*x2 + b;
setpixel(i,y2);
}
}
我忘了说,这是一个爱好项目。