I can't get lighting to work in my program Shape turns black!?

//Here is both fragment and vertex shaders in one file

#shader vertex

#version 330 core

in vec3 position;
in vec3 normal;

uniform mat4 transform;

uniform mat4 range;

uniform mat4 rolook;

 

uniform vec3 lightph;


out vec3 fragph;
out vec3 Anormal;




void main()
{
    gl_Position = transform * vec4(position.x, position.y, position.z, 1.0);
    fragph = vec3(rolook * vec4(position.x, position.y, position.z, 1.0));
    Anormal = mat3(transpose(inverse(rolook))) * normal;
    

};

#shader fragment

#version 330 core

layout(location = 0) out vec4 color;

uniform vec4 Color_u;
uniform vec3 lightph;


in vec3 fragph;
in vec3 Anormal;

void main()
{

    float ambis = 0.1f;
    vec3 ambistren = ambis * Color_u;

    vec3 nor = normalize(Anormal);
    vec3 lightD = normalize(lightph - fragph);
    float diff = max(dot(nor, lightD), 0.0);
    vec3 diffus = diff * Color_u;
    color = Color_u;
};

You are drawing the default value of a vec4. You havn’t put anything into Color_u yet.

In main I linked it to a uniform value for coloring each object. Are you sure?

You initiated Color_u appropriately… yes, I’m ignorant. Since Color_u is not modified in the code you’ve sent, the output color ought to be what you initiated the uniform to.
You’ve not published the code with the error.

Oh really? So the issue is in my uniform. Sorry for not including everything Ill add what I can right now.

    int location = glGetUniformLocation(shader, "Color_u");

    if (location > -1) {
        glUniform4f(location, 0.8f, 0.0f, 0.0f, 1.0f);
    }
    //The code worked and the colors popped up before I tried to include some ambient and diffuse
    //I made a function that sets colors per object that uses Color_u as an outlet

    //Just a quick question, Is the shader working correctly to begin with?

I’m not skilled enough to evaluate the lighting of the shader … more than it does not influence the value you enter in your glUniform4f(…) … it ought to come out unchanged through color. Right?
Are you checking glError()?

I am not checking for errors no. I know I should.

I can send you my main. I feel like that’s the only option at this point??

Wouldn’t it be something like
GLuint e = glGetError()
with error-condition if e>0.

1 Like

@ theoldmcbeefus,
not to be picky, but do you expect me fo find an error in this code?:

do find out how to check for errors

void my_error(string s){
   GLenum enm =glGetError();
   if (enm!=GL_NO_ERROR){
        cout << "an errror ocurred at " << s << "\n";
    }
}

litter the function everywhere to narrow down where the error is made. Start at the draw-loop. If no error here, we’r lost.

Does all your drawing appear properly … except for the color?

as for the lighting-stuff you’ll probably have to use old-style openGL

I don’t think that those glEnable() are compatible with the profile you’ve chosen.

Ya I know it is a lot. But it would really help me out. I don’t know anyone who is learning OpenGL so I could really use any advice from anyone. Idk dude.

@CarstenT I think I got it using the error catching function. I am checking and I think I am trying to multiply Color_u a vec4 by vec3’s!! How can I convert them Color_u or the vec3’s to the same data type without effecting shader? Thanks so much by the way(:

Can you copy the code you talk about?
Sorry for whining about your code, but it still had multible external references.

You seem to have removed the code you sent. It error-tested the shaders with text-output on error. If you havn’t sent the error-log, there is no error in the shader. Color_u is a shader-variable.
You should look-up GLSL resources for what you can and cannot do in the shader.

I have asked some questions on the way. I still need answer.

nb on error-testing:
an error ‘lives’ until it’s read from glGetError(), and there may be more than one if memory serves me well. To test say the drawcall, you test before (and empty the error-buffer) and then after. Testing only after may point to an error anywhere. So, step backwards in your code-execution to find the first appearance.

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <glm.hpp>
#include <geometric.hpp>
#include <fwd.hpp>
#include <ext.hpp>
#include <matrix.hpp>
#include <exponential.hpp>
#include <common.hpp>
#include <packing.hpp>
#include <trigonometric.hpp>
#include <vector_relational.hpp>
#include <windows.ui.xaml.controls.primitives.h>

#include "gtx/transform.hpp"

using namespace std;



class endedquvb {                                                       



public:





    endedquvb(const void *data, unsigned int taken) {



        glGenBuffers(1, &bufferIDA);
        glBindBuffer(GL_ARRAY_BUFFER, bufferIDA);
        glBufferData(GL_ARRAY_BUFFER, taken, data, GL_STATIC_DRAW);
    }


    void Bindbufvb() {


        glBindBuffer(GL_ARRAY_BUFFER, bufferIDA);
    }
    void unbindbufvb() {


        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }




private:

    
    unsigned int bufferIDA;


};
class endedquib {



public:





    endedquib(const void* data, unsigned int caken) {



        glGenBuffers(1, &bufferIDI);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferIDI);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, caken * sizeof(unsigned int), data, GL_STATIC_DRAW);
    }


    void Bindbufib() {


        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferIDI);
    }
    void unbindbufib() {


        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }




private:


    unsigned int bufferIDI;


};




void acvaob(int loc, int sprok) {


    glVertexAttribPointer(0, loc, GL_FLOAT, GL_FALSE, sizeof(float) * sprok, 0);
    glEnableVertexAttribArray(0);


}


void dravao(unsigned int vao, int loc, float R, float G, float B, float A, int vertis) {

    if (loc > -1)
    {
        glUniform4f(loc, R, G, B, A);
    }
    glBindVertexArray(vao);
    glDrawElements(GL_TRIANGLES, vertis, GL_UNSIGNED_INT, nullptr);



}



void my_error() {

    GLenum enm = glGetError();

    if (enm != GL_NO_ERROR) {

        cout << "an errror ocurred";

    }

}

struct Shaderprogramsource
{
    std::string VertexSouce;
    std::string FragmentSource;
};

static Shaderprogramsource Parseshader(const std::string& filepath)
{
    std::ifstream stream(filepath);

    enum class Shadertype
    {
        VERTEX = 0,
        FRAGMENT = 1,
        NONE = 2
    };

    std::string line;
    std::stringstream ss[3];

    Shadertype type = Shadertype::NONE;

    while (getline(stream, line))
    {
        if (line.find("#shader") != std::string::npos)
        {
            if (line.find("vertex") != std::string::npos)
                type = Shadertype::VERTEX;

            else if (line.find("fragment") != std::string::npos)
                type = Shadertype::FRAGMENT;
        }
        else
        {
            ss[(int)type] << line << "\n";
        }
    }

    return Shaderprogramsource{ ss[0].str(), ss[1].str() };
}

static int CompileShader(unsigned int type, const std::string& Source)
{
    unsigned int id = glCreateShader(type);
    const char* src = Source.c_str();
    glShaderSource(id, 1, &src, nullptr);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);

    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

        char* message = (char*)alloca(length * sizeof(char));
        glGetShaderInfoLog(id, length, &length, message);

        std::cout << message;

        return 0;
    }

    return id;
}

static unsigned int CreateShader(
    const std::string& Vertexshader,
    const std::string& Fragmentshader)
{
    unsigned int program = glCreateProgram();
    unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader);
    unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader);

    glAttachShader(program, vertex);
    glAttachShader(program, fragment);

    glLinkProgram(program);
    glValidateProgram(program);

    return program;
}



int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);



    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'
    /////////////////////////////////////////////////TURNBACKTOBACKOFFCLASSD;';'


    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(800, 800, "Hello World", NULL, NULL);
    unsigned int indicesv2[] = {

    0, 1, 2,
    2, 3, 0


    };

    float verticesv2[] = { -0.1, -0.1, 1.0,
                            0.1, -0.1, 1.0,
                            0.1, 0.1, 1.0,
                           -0.1, 0.1, 1.0 };
    
    
    float verticesv3[] = {  0.1, -0.1, 1.2,
                            0.1, -0.1, 1.0,
                            0.1, 0.1, 1.0,
                            0.1, 0.1, 1.2 };
    unsigned int abuffar;
    unsigned int avbo;
    unsigned int avao;
    int cerry;
    cerry = 3;
    int barry;
    barry = 3;
    int height;
    int width;

    glfwGetFramebufferSize(window, &width, &height);
    glfwSetFramebufferSizeCallback(window, 0);




    






    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (GLEW_OK == glewInit())
    {
    }


    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);
    glEnable(GL_LIGHTING);
    glEnable(GL_COLOR_MATERIAL);


//ALLOFMYVARSINSBIGTUB;';'    
    //ALLOFMYVARSINSBIGTUB;';'
            //ALLOFMYVARSINSBIGTUB;';'
                //ALLOFMYVARSINSBIGTUB
                    //ALLOFMYVARSINSBIGTUB;';'
     //UDLRL;';'
    float lroundx;
    lroundx = 0.0f;
    float lroundxref;
    lroundxref = 0.0f;


    float lroundy;
    lroundy = 0.0f;
    //UDLRL;';'


    //MOV;';'
    float anothersmallstepforhumans;
    anothersmallstepforhumans = 0.0f;
    float lrm;
    lrm = 0.0f;


    bool wlksltkv;
    wlksltkv = false;
    bool deepress;
    deepress = false;
    float randus;
    randus = 0.0f;

    float aconmov;
    aconmov = 0.01f;
    float aconmovref;
    aconmovref = 0.01f;


    const float dar = 0.01f;
    


    //MOV;';'


    glm::vec3 thethe(dar, 0.0f, dar);
    glm::vec3 position(lrm, 0.0f, 0.0f);
    glm::vec3 UP(0.0f, 1.0f, 0.0f);
    glm::vec3 SIDE(1.0f, 0.0f, 0.0f);

    glm::vec3 Lp(0.2f, 0.1f, 0.2f);
    


//ENDINGALLOFMYVARSINSBIGTUB;';'
    //ENDINGALLOFMYVARSINSBIGTUB;';'
            //ENDINGALLOFMYVARSINSBIGTUB;';'
                //ENDINGALLOFMYVARSINSBIGTUB;';'
                    //ENDINGALLOFMYVARSINSBIGTUB;';'


    Shaderprogramsource source = Parseshader("res/shaders/fikit.Shader");





    unsigned int shader =
        CreateShader(source.VertexSouce, source.FragmentSource);

    unsigned int thepositions =
        CreateShader(source.VertexSouce, source.FragmentSource);

    cout << source.VertexSouce;
    my_error();
    



    endedquvb yepiss(verticesv2, sizeof(verticesv2));
    endedquib yepissi(indicesv2, 6);
    unsigned int vaocd;
    glGenVertexArrays(1, &vaocd);
    glBindVertexArray(vaocd);
    yepiss.Bindbufvb();
    yepissi.Bindbufib();
    acvaob(3, 3);


    endedquvb yepiss1(verticesv3, sizeof(verticesv3));
    endedquib yepissi1(indicesv2, 6);
    unsigned int vaocd1;
    glGenVertexArrays(1, &vaocd1);
    glBindVertexArray(vaocd1);
    yepiss1.Bindbufvb();
    yepissi1.Bindbufib();
    acvaob(3, 3);



////////////////////////////KEYINPUTSANDCONTROLLINGVARSYUIOP;';'
    ////////////////////////////KEYINPUTSANDCONTROLLINGVARSYUIOP;';'
            ////////////////////////////KEYINPUTSANDCONTROLLINGVARSYUIOP;';'
                ////////////////////////////KEYINPUTSANDCONTROLLINGVARSYUIOP;';'
                    ////////////////////////////KEYINPUTSANDCONTROLLINGVARSYUIOP;';'

    



    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        
        glClear(GL_COLOR_BUFFER_BIT);
        glClearColor(0.0f, 0.2f, 0.8f, 1.0f);
        glfwPollEvents();
        glUseProgram(shader);




    ////LOOKINGLEFTANDRIGHTUPNDOWNIANJ;';'
        ////LOOKINGLEFTANDRIGHTUPNDOWN;';'

        
        //UDLRkeys;';'
    
        
    if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) {
        lroundx += 0.034f;
    }
    else if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
        lroundx += -0.034f;
    }
        if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS && lroundy > -1.0f) {
            lroundy += -0.018f;
        }
        else if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS && lroundy < 0.5f) {
            lroundy += 0.018f;
        }
        //UDLRkeys;';'




    ////ENDINGLOOKINGLEFTANDRIGHTUPNDOWNIANJ;';'
        ////ENDINGLOOKINGLEFTANDRIGHTUPNDOWN;';'









    ////////////////////////////KEYINPUTENSINGNOU;';'
        ////////////////////////////KEYINPUTENSINGNOU;';'
                ////////////////////////////KEYINPUTENSINGNOU;';'
                    ////////////////////////////KEYINPUTENSINGNOU;';'
                         ////////////////////////////KEYINPUTENSINGNOU;';'











        ///////////////////////////////////////////////////MAKINGTHECAMERAASAPERFECTHINGBECASEILIKEITLIKETHATCAMER#CAMERACCCCCCCCCCCCCC;'
            ///////////////////////////////////////////////////MAKINGTHECAMERAASAPERFECTHINGBECASEILIKEITLIKETHATCAMER#CAMERACCCCCCCCCCCCCC;'
                    ///////////////////////////////////////////////////MAKINGTHECAMERAASAPERFECTHINGBECASEILIKEITLIKETHATCAMER#CAMERACCCCCCCCCCCCCC;'
                        ///////////////////////////////////////////////////MAKINGTHECAMERAASAPERFECTHINGBECASEILIKEITLIKETHATCAMER#CAMERACCCCCCCCCCCCCC;'
                                ///////////////////////////////////////////////////MAKINGTHECAMERAASAPERFECTHINGBECASEILIKEITLIKETHATCAMER#CAMERACCCCCCCCCCCCCC;'


            ////PERSPECTIVE;';'
        glm::mat4 therange(1.0f);
        therange = glm::perspective(glm::radians(95.0f), static_cast<float>(width) / height, 0.01f, 150.0f);
        //PERSPECTIVE;';'





        //XYLOOKING;';'
        glm::mat4 xlook(1.0f);
        glm::mat4 ylook(1.0f);
        glm::mat4 lrviews(1.0f);




        //XYLOOKING;';'





        //PVU;';'
        glm::vec4 viewdirection(0.0f, 0.0f, 1.0f, 0.0f);
        viewdirection = glm::rotate(lroundx, UP) * glm::vec4(viewdirection);
        ylook = glm::rotate(ylook, lroundy, SIDE);


        glm::vec3 siddir = glm::cross(glm::vec3(viewdirection), UP);
  
        
        //PVU;';'
        //TRANS;';'
        glm::mat4 trans1(1.0f);
        glm::mat4 trans2(1.0f);
        glm::mat4 trans3(1.0f);
        glm::mat4 translation(1.0f);
        //TRANS;';'



        trans1 = glm::translate(trans1, glm::vec3(randus, 0.0f, anothersmallstepforhumans));
        trans2 = glm::rotate(trans2, 0.0f, glm::vec3(0.0f, 0.0f, 1.0f));
        trans3 = glm::scale(trans3, glm::vec3(1.0f, 1.0f, 1.0f));
        translation = trans1 * trans2 * trans3;



        
        //LOOKT;';'
        glm::mat4 views(1.0f);
        views = glm::lookAt(position, position + glm::vec3(viewdirection), UP);
        //LOOKT;';'






        //ISSUEHEREGONARELABELSON;';'
        glm::vec3 loppik(0.0f, 0.0f, 0.0f);
        glm::vec3 levvik(0.0f, 0.0f, 0.0f);
        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
            position += glm::vec3(viewdirection) * thethe;
            aconmov += 0.01f;
        }
        else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
            position -= glm::vec3(viewdirection) * thethe;
            aconmov -= 0.01f;
        }
                        if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
                            position -= siddir * thethe;
                        }
                        else if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
                            position += siddir * thethe;
                        }
        views = glm::lookAt(position, position + glm::vec3(viewdirection), UP);
        //ISSUEHEREGONARELABELSON;';'

        

        //OFISHEMATRICS;';'
            //OFISHEMATRICS;';'
        glm::mat4 FinalCompilMat(1.0f);
        FinalCompilMat = { therange * ylook * views * translation };


            //OFISHEMATRICS;';'
        //OFISHEMATRICS;';'





        ////SENDINGUNIFORM;';'
        ////SENDINGUNIFORM;';'

        int range = glGetUniformLocation(shader, "range");
        glUniformMatrix4fv(range, 1, GL_FALSE, glm::value_ptr(therange));
        int Look = glGetUniformLocation(shader, "rolook");
        glUniformMatrix4fv(Look, 1, GL_FALSE, glm::value_ptr(translation));
        int TRans = glGetUniformLocation(shader, "transform");
        glUniformMatrix4fv(TRans, 1, GL_FALSE, glm::value_ptr(FinalCompilMat));
        int Lpos = glGetUniformLocation(shader, "lightph");
        glUniformMatrix4fv(Lpos, 1, GL_FALSE, glm::value_ptr(Lp));


        ////SENDINGUNIFORM;';'
        ////SENDINGUNIFORM;';'



    ///////////////////////////////////////////////////ENDINGCAMERA#CAM;'
        ///////////////////////////////////////////////////ENDINGCAMERA#CAM;'
                ///////////////////////////////////////////////////ENDINGCAMERA#CAM;'
                    ///////////////////////////////////////////////////ENDINGCAMERA#CAM;'
                        ///////////////////////////////////////////////////ENDINGCAMERA#CAM;'


        int location = glGetUniformLocation(shader, "Color_u");


        int thepositionsgetem = glGetUniformLocation(shader, "position.x");




        

        
        
        



        









        dravao(vaocd, location, 0.0f, 0.8f, 0.2f, 1.0f, 6);
        dravao(vaocd1, location, 0.0f, 0.8f, 0.2f, 1.0f, 6);

        glfwSwapBuffers(window);
        glClear(GL_DEPTH_BUFFER_BIT);
        glDisable(GL_NORMALIZE);
        glDisable(GL_LIGHTING);
        glDisable(GL_COLOR_MATERIAL);



        
    }


    glfwTerminate();
    return 0;
}

I am still having the error with surface normals but my colors are indeed going through though they appear darkened and not effected by my light position. Any ideas?

hi @theoldmcbeefus
I never understood that the output from the fragment-shader was indeed red albite darker than you would expect.

That means that there is no error in your code… sorry for making you jump high and low to fetch code then.

vec4(1.0, 0.0, 0.0, 1.0) would produce a bright red
vec4(0.8, 0.0, 0.0, 1.0) a slightly darker red

It makes sense that this is the color that passes through.
I’ve tried to tell you, that the color you set in Color_u

is never changed in the shader … you assign the value to the output color and it seems to appear a slightly dark red as expected.

It doesn’t work that way. Your profile does not allow hokus-pocus variables as lights and materials to kick in by just assigning values to them. You have to emulate the light-model through math and express it in the color you return from the shader. (I recognize your thinking from directX … this is a much more delicate/cumbersome situation).
I’ve not really sat up any sofisticated lighting-model, but there are numerous examples on how to emulate physical lighting using normals, lightposition etc.

have I hit the problem?

I’ve always understood this declaration as a vertex-attribute (write a color for each vertex). That you would use it for say vertex-positions and normals in the vertex-shader. But I won’t complaint if opengl doesn’t.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.