Read me About Demoscene? Links Contact

½-page - second try :-)

So, here is my second try at using shaders in less than a half page of code. My first try used both SDL and GLEW which could be considered “cheating”.

Second time around I use “raw” Win32 API and OpenGL to make everything work. Everything in 36 lines.

#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include "glext.h"
#include <string>
#include <fstream>
#include <iterator>
#define F(x,y) ((x)wglGetProcAddress(y))
unsigned int CompileSrc(const char *src, GLenum dest) {
	unsigned int s = F(PFNGLCREATESHADERPROC,"glCreateShader")(dest);
	F(PFNGLSHADERSOURCEPROC,"glCreateShader")(s, 1, &src, NULL);
	F(PFNGLCOMPILESHADERPROC,"glCompileShader")(s);
	return s; }
int main(int argc, char **argv) {
	static PIXELFORMATDESCRIPTOR pfd;
	pfd.dwFlags = PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;	
	pfd.cAlphaBits = 8;
	pfd.cColorBits = 24;
	HDC hDC = GetDC( CreateWindow("edit", 0, WS_POPUP|WS_VISIBLE, 0,0,1024,768,0,0,GetModuleHandle(NULL),0) );
	SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
	wglMakeCurrent(hDC, wglCreateContext(hDC));
	unsigned int sp = F(PFNGLCREATEPROGRAMPROC,"glCreateProgram")();
	F(PFNGLATTACHSHADERPROC,"glAttachShader")(sp, CompileSrc(std::string((std::istreambuf_iterator<char>( std::ifstream("shader.fs") )), std::istreambuf_iterator<char>()).c_str(), GL_FRAGMENT_SHADER));
	F(PFNGLATTACHSHADERPROC,"glAttachShader")(sp, CompileSrc(std::string((std::istreambuf_iterator<char>( std::ifstream("shader.vs") )), std::istreambuf_iterator<char>()).c_str(), GL_VERTEX_SHADER));
	F(PFNGLLINKPROGRAMPROC,"glLinkProgram")(sp);
	F(PFNGLUSEPROGRAMPROC,"glUseProgram")(sp);
	while (!GetAsyncKeyState(VK_ESCAPE))
	{
		glViewport(0,0,1024,768);				
		glMatrixMode(GL_PROJECTION);				
		glLoadIdentity();							
		glOrtho(-1,1,1,-1,0.1f, 100.0f);
		glRectf(-1,1,1,-1);
		SwapBuffers(hDC);	
	}
	return 0;}