source: trunk/src/shader.cpp @ 659

Last change on this file since 659 was 659, checked in by sam, 10 years ago

Try to factor all the recent GLSL stuff in the new Shader class.

File size: 2.3 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cmath>
16#include <cstdio>
17
18#ifdef WIN32
19#   define WIN32_LEAN_AND_MEAN
20#   include <windows.h>
21#endif
22#if defined __APPLE__ && defined __MACH__
23#   include <OpenGL/gl.h>
24#else
25#   define GL_GLEXT_PROTOTYPES
26#   include <GL/gl.h>
27#endif
28
29#include "core.h"
30
31/*
32 * Shader implementation class
33 */
34
35class ShaderData
36{
37    friend class Shader;
38
39private:
40    GLuint prog_id, vert_id, frag_id;
41};
42
43/*
44 * Public Shader class
45 */
46
47Shader::Shader(char const *vert, char const *frag)
48  : data(new ShaderData())
49{
50    char buf[4096];
51    GLsizei len;
52
53    data->vert_id = glCreateShader(GL_VERTEX_SHADER);
54    glShaderSource(data->vert_id, 1, &vert, NULL);
55    glCompileShader(data->vert_id);
56
57    glGetShaderInfoLog(data->vert_id, sizeof(buf), &len, buf);
58    if (len > 0)
59        fprintf(stderr, "ERROR: failed to compile vertex shader: %s", buf);
60
61    data->frag_id = glCreateShader(GL_FRAGMENT_SHADER);
62    glShaderSource(data->frag_id, 1, &frag, NULL);
63    glCompileShader(data->frag_id);
64
65    glGetShaderInfoLog(data->frag_id, sizeof(buf), &len, buf);
66    if (len > 0)
67        fprintf(stderr, "ERROR: failed to compile fragment shader: %s", buf);
68
69    data->prog_id = glCreateProgram();
70    glAttachShader(data->prog_id, data->vert_id);
71    glAttachShader(data->prog_id, data->frag_id);
72
73    glLinkProgram(data->prog_id);
74    glValidateProgram(data->prog_id);
75}
76
77int Shader::GetAttribLocation(char const *attr) const
78{
79    return glGetAttribLocation(data->prog_id, attr);   
80}
81
82int Shader::GetUniformLocation(char const *uni) const
83{
84    return glGetUniformLocation(data->prog_id, uni);
85}
86
87void Shader::Bind() const
88{
89    glUseProgram(data->prog_id);
90}
91
92Shader::~Shader()
93{
94    glDetachShader(data->prog_id, data->vert_id);
95    glDetachShader(data->prog_id, data->frag_id);
96    glDeleteShader(data->vert_id);
97    glDeleteShader(data->frag_id);
98    glDeleteProgram(data->prog_id);
99    delete data;
100}
101
Note: See TracBrowser for help on using the repository browser.