buffer.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #ifndef BUFFER_H
  2. #define BUFFER_H
  3. // ===============================
  4. // AUTHOR : Angel Ortiz (angelo12 AT vt DOT edu)
  5. // CREATE DATE : 2018-07-10
  6. // PURPOSE : Buffer template used as render targets for the software renderer
  7. // ===============================
  8. #include "SDL.h"
  9. #include <type_traits>
  10. //Templated struct to emulate GPU buffers such as
  11. //the frame buffer and the ZBuffer
  12. //Also keeps track of a bunch of useful data about itself
  13. template<class T>
  14. struct Buffer{
  15. int mWidth, mHeight, mPixelCount, mPitch, mOrigin;
  16. T *buffer;
  17. //The buffer is actually just a simple 1D array which we access using an equation
  18. //Notice how it's not the usual (y*width + x) equation that you see for most quasi 2D arrays
  19. //This is because the origin is at the lower left (instead of upper left) and y moves upwards
  20. T& operator()(size_t x, size_t y){
  21. return buffer[mOrigin + -y*mWidth + x];
  22. }
  23. Buffer(int w, int h, T * array)
  24. : mWidth(w), mHeight(h), mPixelCount(w*h), mPitch(w*sizeof(T)),
  25. mOrigin(mHeight*mWidth - mWidth), buffer(array){}
  26. ~Buffer(){delete [] buffer;}
  27. //Cannot use memset to clear a float since the binary
  28. //Representation is more complex. We just iterate through the whole
  29. //thing and explicitely set it to zero instead
  30. void clear(){
  31. if(std::is_same<T,float>::value){
  32. for(int i = 0; i < mPixelCount;++i){
  33. buffer[i] = 0.0f;
  34. }
  35. }
  36. else{
  37. //Set to a 15% white color to make it nicer looking.
  38. memset(buffer,0xD, mPitch*mHeight);
  39. }
  40. }
  41. };
  42. #endif