buffer.h 1.7 KB

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