I've been writing, deleting and rewriting OpenGL programs in C++ but usage of shaders confuse me. I don't know how it should be structured.

Scenario A: (In a world we have a sun, the sun should shine upon everything in the world and on a lake or there would be fog which should only be visible from outside the building but not inside)

So far, I am thinking that I would write a global sun structure in C++ then pass its value to all shaders, then in all used shaders I would write the same lighting functions over and over again.

So I would be repeating codes... How would you construct your shader program in such scenario? And Should I write a shader for each model?


1 Answer 1


I would write the same lighting functions over and over again


A shader pipeline is a series of actions:

  • Inputs from CPU (or GPU, in some cases; optional)
  • Vertex Shader
  • Geometry Shader (optional)
  • Fragment Shader
  • Retrieve buffers to CPU (optional)

^ At no stage is there any repetition in this sequence.

If you're saying that you need to do the same thing from different places... well, let's say you have two higher level lighting functions called "outdoor lighting" vs. "indoor lighting"; if there are parts of their code that are the same, then you factor these out into separate sub-functions, that you call from different places in your higher-level lighting functions. Most of these smaller functions will be very small, < 10 lines, performing some elementary action.

It's basic Refactoring 101.

  • \$\begingroup\$ I really don'y known why, based on the information i've got right now, I would do as I described but let me clarify my question a bit more, "Should I write a shader for each model"? \$\endgroup\$
    – user133668
    Commented Mar 2, 2020 at 19:32

You must log in to answer this question.