Browse Source

Finished refactor.

angel 7 years ago
parent
commit
c93d8001c0

+ 4 - 0
include/buffer.h

@@ -12,6 +12,10 @@ struct Buffer{
         int mPitch;
         T *buffer;
 
+        T& operator()(size_t x, size_t y){
+            return buffer[y*mWidth + x];
+        }
+
         Buffer(int w, int h, T * array) 
         : mWidth(w), mHeight(h), mPixelCount(w*h),
                 mPitch(w*sizeof(T)), buffer(array) 

+ 5 - 7
include/camera.h

@@ -5,14 +5,12 @@
 #include "vector3.h"
 
 
-class Camera{
+struct Camera{
     public:
         Camera();
 
         void update();
 
-    private:
-
         //Position and direction of camera
         Vector3 position{0,0,8};
         Vector3 target;
@@ -21,10 +19,10 @@ class Camera{
         //Matrices and frustrum stuff
         Matrix4 viewMatrix;
         Matrix4 projectionMatrix;
-        float fov{75};
-        float near{1};
-        float far{100};
-        float aspectRatio{1};
+        int fov{75};
+        int near{1};
+        int far{100};
+        float aspectRatio{1.0};
 };
 
 #endif

+ 0 - 22
include/canvas.h

@@ -1,22 +0,0 @@
-#ifndef CANVAS_H
-#define CANVAS_H
-
-    #include "SDL.h"
-
-    struct Canvas{
-            Canvas(int w, int h, int px, int pi, Uint32 * buf1, float * buf2) 
-                : mWidth(w), mHeight(h), mPixelCount(px),
-                 mPitch(pi),mBuffer(buf1), mDBuffer(buf2) 
-            {}
-            int mWidth;
-            int mHeight;
-            int mPixelCount;
-            int mPitch;
-            //Represents the pixel data buffer
-            Uint32 *mBuffer; //FIX THIS AT SOME POINT  
-
-            //Represents the depth data buffer
-            float *mDBuffer;
-    };
-
-#endif

+ 15 - 6
include/displayManager.h

@@ -3,13 +3,19 @@
 
 #include "SDL.h"
 #include "buffer.h"
-#include "texture.h"
 
+
+//Manages all low level display and window SDL stuff
+//Currently set up to work using SDL2 hardware rendering
+//I tested software rendering and although it was faster for simple color passes
+//It was slower when I tried to implement alpha blending, so I decided to revert
+//Back to the hardware accelerated backend.
 class DisplayManager{
 
     public:
         const static int SCREEN_WIDTH  = 640; //640
         const static int SCREEN_HEIGHT = 480; //480
+        const static int SCREEN_PITCH  = SCREEN_HEIGHT*sizeof(Uint32);
 
         //Dummy Constructor / Destructor
         DisplayManager();
@@ -23,7 +29,7 @@ class DisplayManager{
         void clear();
 
         //Swaps the pixel buffer with the texture buffer and draws to screen
-        void draw(Buffer<Uint32> *pixelBuffer);
+        void swapBuffers(Buffer<Uint32> *pixelBuffer);
 
     private:
         bool startSDL();
@@ -31,10 +37,13 @@ class DisplayManager{
         bool createSDLRenderer();
         bool createScreenTexture();
 
-        Texture      screenTexture;
-        SDL_Surface  *surface;
-        SDL_Renderer *SDLRenderer;
-        SDL_Window   *mainWindow;
+        SDL_Texture  *mTexture;
+        SDL_Renderer *mSDLRenderer;
+        SDL_Window   *mWindow;
+
+        //These are only really needed for the texture copying operation
+        int           mTexturePitch;
+        void         *mTexturePixels;
 };
 
 #endif

+ 2 - 2
include/engine.h

@@ -3,7 +3,7 @@
 
 //Headers
 #include "displayManager.h"
-#include "softwareRenderer.h"
+#include "renderManager.h"
 #include "inputManager.h"
 #include "sceneManager.h"
 
@@ -26,7 +26,7 @@ class Engine{
 
     private:
         DisplayManager   gDisplayManager;
-        SoftwareRenderer gRenderer;
+        RenderManager    gRenderManager;
         InputManager     gInputManager;
         SceneManager     gSceneManager;
 };

+ 1 - 1
include/matrix.h

@@ -28,7 +28,7 @@ class Matrix4{
         Matrix4 static makeScaleMat(float scaleX, float scaleY, float scaleZ);
         Matrix4 static makeTranslateMat(float dx, float dy, float dz);
 
-        //Builds a matrix that rotates, scakes abd translates all in one
+        //Builds a matrix that rotates, scales and translates all in one
         Matrix4 static transformMatrix(TransformParameters transform);
 
         //Camera transformation matrix (the world from the camera's eyes)

+ 3 - 1
include/model.h

@@ -11,12 +11,14 @@ class Model{
     public:
         Model(std::string path); 
         void describeMesh();
+
         Mesh *getMesh();
+        
         void initPosition(TransformParameters initPos);
-
         void update();
 
     private:
+        
         void buildBoundaryBox();
         void buildMesh(std::string path);
         void loadVertices(std::ifstream &fileHandle);

+ 15 - 26
include/rasterizer.h

@@ -3,45 +3,34 @@
 
 #include "SDL.h"
 #include "buffer.h"
-#include "model.h"
+#include "vector3.h"
+#include "shader.h"
 
 class Rasterizer{
 
     public:
-        Rasterizer(Buffer<Uint32> *buffer) :mPixelBuffer(buffer){}
+        static void drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer, Buffer<float> *zBuffer, float intensity);
 
-        void drawTriangles(Vector3 &v1, Vector3 &v2, Vector3 &v3, float intensity);
+        static void drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer);
 
-        void drawWireFrame(Vector3 &v1, Vector3 &v2, Vector3 &v3);
+        static void testPattern(Buffer<Uint32> *pixelBuffer);
 
-        void testPattern();
+        static void makeCoolPattern(Buffer<Uint32> *pixelBuffer);
 
-        void makeCoolPattern();
+        static void drawLine(Vector3 &vertex1, Vector3 &vertex2, const Uint32 &color, Buffer<Uint32> *pixelBuffer);
 
     private:
+        Rasterizer(){};
+
+        //Setting this equal to the same pixel format our textures are in
         static const Uint32 PIXEL_FORMAT = SDL_PIXELFORMAT_RGBA8888;
-        
         static const SDL_PixelFormat* mappingFormat;
 
-        Uint32 getPixelColor(int x, int y);
-
-        void drawLine(Vector3 &vertex1, Vector3 &vertex2, Uint32 &color);
-
-        void setPixelColor( int x, int y, Uint32 color);
-
-        int convertCoordinates(int x, int y);
-
-        float getDepthBufferAtLocation(int x, int y);
-
-        void setDepthBufferAtLocation(int x, int y, float depth);
-
-        Buffer<Uint32> * mPixelBuffer;
-
-        Uint32 white = SDL_MapRGBA(mappingFormat, 0xFF,0xFF,0xFF,0xFF);
-        Uint32 red = SDL_MapRGBA(mappingFormat, 0xFF,0x00,0x00,0xFF);
-        Uint32 green = SDL_MapRGBA(mappingFormat, 0x00,0xFF,0x00,0xFF);
-        Uint32 blue = SDL_MapRGBA(mappingFormat, 0x00,0x00,0xFF,0xFF);
-
+        //Some basic colors
+        static const Uint32 white;
+        static const Uint32 red;
+        static const Uint32 green;
+        static const Uint32 blue; 
 };
 
 #endif

+ 39 - 0
include/renderManager.h

@@ -0,0 +1,39 @@
+#ifndef RENDERMANAGER_H
+#define RENDERMANAGER_H
+
+#include "displayManager.h"
+#include "sceneManager.h"
+#include "softwareRenderer.h"
+#include "mesh.h"
+#include <queue>
+
+//High level render operations that shouldn't be done by the
+//basic graphics lib.
+class RenderManager{
+
+    public:
+        //Dummy constructors / Destructors
+        RenderManager();
+        ~RenderManager();
+
+        //Gets scene and display info to 
+        bool startUp(DisplayManager &displayManager,SceneManager &sceneManager );
+        void shutDown();
+
+        //Performs all high level prep operations that the graphics library
+        //Needs to do before acting
+        void render();
+
+    private:
+        void buildRenderQueue();
+        bool initSoftwareRenderer();
+        
+        //This is a pointer to a pointer to allow for scene switching 
+        SceneManager   * sceneLocator;
+        DisplayManager * screen;
+        SoftwareRenderer renderInstance;
+        std::queue<Mesh*> renderQueue;        
+};
+
+
+#endif

+ 16 - 1
include/scene.h

@@ -4,6 +4,7 @@
 #include <string>
 #include "model.h"
 #include "camera.h"
+#include <vector>
 
 class Scene{
     public:
@@ -13,10 +14,24 @@ class Scene{
 
         //Updates all objects and cameras in scene
         void update();
+
+        std::vector<Model*>* getVisiblemodels();
+
+        Camera * getCurrentCamera();
     private:
         Camera mainCamera;
-        Model *sceneModel;
+
+        std::vector<Model*> modelsInScene;
+
+        //Contains the models that remain after frustrum culling
+        std::vector<Model*> visibleModels;
+        
+        //Initializes all modelsin the scene
         void loadSceneModels(std::string path);
+
+        //Cull objects that should not be visible and add the visible to the 
+        //visibleModels list for rendering TO DO 
+        void frustrumCulling();
 };
 
 #endif

+ 2 - 0
include/sceneManager.h

@@ -21,6 +21,8 @@ class SceneManager{
         // Update current scene
         void update();
 
+        Scene* getCurrentScene();
+
     private:
         bool loadScene();
         bool closeScene();

+ 37 - 0
include/shader.h

@@ -0,0 +1,37 @@
+#ifndef SHADER_H
+#define SHADER_H
+
+#include "vector3.h"
+#include "matrix.h"
+
+struct IShader {
+    virtual ~IShader() {};
+    virtual Vector3 vertex(Vector3 &vertex, Matrix4 &MVP) = 0;
+    virtual bool fragment(Vector3 &vertex) = 0;
+};
+
+struct FlatShader : public IShader {
+
+    virtual Vector3 vertex(Vector3 &vertex, Matrix4 &MVP){
+        return MVP.matMultVec(vertex);
+    }
+
+    virtual bool fragment(Vector3 &barCoordinates){
+        return false;
+    }
+
+};
+
+
+#endif
+
+//     //View matrix transform
+//     Vector3 v0 = viewMatrix.matMultVec((*vertices)[f.x-1]); //-1 because .obj file starts face count
+//     Vector3 v1 = viewMatrix.matMultVec((*vertices)[f.y-1]); // from 1. Should probably fix this 
+//     Vector3 v2 = viewMatrix.matMultVec((*vertices)[f.z-1]); // At some point
+
+
+//     // Projection matrix transformation
+//     v0 = projectionMatrix.matMultVec(v0);
+//     v1 = projectionMatrix.matMultVec(v1);
+//     v2 = projectionMatrix.matMultVec(v2);

+ 24 - 14
include/softwareRenderer.h

@@ -1,9 +1,10 @@
 #ifndef SRENDERER_H
 #define SRENDERER_H
 
-#include "displayManager.h"
 #include "rasterizer.h" 
 #include "buffer.h"
+#include "mesh.h"
+#include "camera.h"
 
 class SoftwareRenderer {
 
@@ -12,27 +13,36 @@ class SoftwareRenderer {
         SoftwareRenderer();
         ~SoftwareRenderer();
 
-        //Creates all buffers and initializes all sub-programs needed
-        //For rendering
-        bool startUp(DisplayManager &displayManager);  
+        //Creates all buffers and preps everything for for rendering
+        bool startUp(int w, int h);  
         void shutDown();      
 
-        //void render(Model *models, Matrix4 &mat);
-        void render();
+        //This could be expanded with more methods
+        // to draw different types of meshes or models
+        void drawTriangularMesh(Mesh * triMesh);
+
+        void clearBuffers();
+
+        Buffer<Uint32>* getRenderTarget();
+
+        void setCameraToRenderFrom(Camera * camera);
         
     private:
         //Buffer methods
-        bool createBuffers();
-        void clearBuffers();
+        bool createBuffers(int w, int h);
+
+        //Primitive building methods
+        void buildTri(Vector3 &f, Vector3 *trianglePrim, std::vector<Vector3> &verts);
+
+        //Culling methods
+        bool backFaceCulling(Vector3 *trianglePrim, float &intensity);
 
-        DisplayManager * screen;
-        Buffer<float> * zBuffer;
-        Buffer<Uint32> * pixelBuffer;
         
-        Rasterizer *raster;
+        //Pointer to the scene's target camera
+        Camera * mCamera;
 
-        //Culling
-        //bool frustrumCulling(Model *model, Matrix4 &viewMatrix);
+        Buffer<float> * zBuffer;
+        Buffer<Uint32> * pixelBuffer;
 };
 
 #endif

+ 0 - 37
include/texture.h

@@ -1,37 +0,0 @@
-#ifndef TEXTURE_H
-#define TEXTURE_H
-
-#include "SDL.h"
-
-//Needs another pass in the future, since it's so highly coupled with SDL
-//Okay for now but FIX THIS
-class Texture{
-
-    public:
-        Texture();
-
-        ~Texture();
-        
-        void free();
-
-        bool createBlank(SDL_Renderer * mainRenderer, int width, int height);
-
-        void update(Uint32 * pixels);
-
-        void renderToScreen(SDL_Renderer * mainRenderer);
-
-    private:
-        SDL_Texture* mTexture;
-
-        //Dimensions
-        int mWidth;
-        int mHeight;
-        int mPitch;
-
-        //Only used to lock and unlock pixels, not  the actual pixel
-        //values FIX THIS
-        void* mTrash;
-
-};
-
-#endif

+ 13 - 10
include/vector3.h

@@ -4,29 +4,32 @@
 #include <string>
 
 struct Vector3{
-    float x = 0;
-    float y = 0;
-    float z = 0;
+    float x;
+    float y;
+    float z;
 
+    
     Vector3(float x1, float y1, float z1) : x(x1), y(y1), z(z1)
     {}
 
-    Vector3(){};
+    Vector3(): x(0.0f), y(0.0f), z(0.0f)
+    {};
 
-    Vector3(std::string x1, std::string y1, std::string z1):
-        x(std::stof(x1)), y(std::stof(y1)), z(std::stof(z1))
-    {}
+
+    //Negate components of vector
+    Vector3 &operator-();
 
     Vector3 operator-(Vector3 &rhs);
 
-    Vector3&  normalized();
+    //Accessing components using array notation for looping
+    float &operator[](int i);
+
+    Vector3 &normalized();
 
     float length();
 
     Vector3 crossProduct(Vector3 &rhs);
 
-    Vector3 neg();
-
     float   dotProduct(Vector3 &rhs);
 
     void print();

+ 2 - 2
src/camera.cpp

@@ -4,7 +4,7 @@
 
 Camera::Camera(){
     viewMatrix = Matrix4::lookAt(position,target,up);
-    aspectRatio =  DisplayManager::SCREEN_WIDTH/DisplayManager::SCREEN_WIDTH;
+    aspectRatio =  DisplayManager::SCREEN_WIDTH/(float)DisplayManager::SCREEN_HEIGHT;
     projectionMatrix = Matrix4::makeProjectionMatrix(fov, aspectRatio, near,far);
 }
 
@@ -17,5 +17,5 @@ void Camera::update(){
     position.y = 0;
     position.z = camZ;
     viewMatrix = Matrix4::lookAt(position,target,up);
-    //viewMatrix = (Matrix4::makeTranslateMat(0,camX*0.25,0)*viewMatrix)
+    viewMatrix = (Matrix4::makeTranslateMat(0,camX*0.25,0)*viewMatrix);
 }

+ 38 - 38
src/displayManager.cpp

@@ -18,14 +18,14 @@ bool DisplayManager::startUp(){
             success = false;
         }
         else{
-            // if( !createSDLRenderer() ){
-            //     success = false;
-            // }
-            // else{
-            //     if( !createScreenTexture() ){
-            //         success = false;
-            //     }
-            // }
+            if( !createSDLRenderer() ){
+                success = false;
+            }
+            else{
+                if( !createScreenTexture() ){
+                    success = false;
+                }
+            }
 
         }
     }
@@ -33,15 +33,16 @@ bool DisplayManager::startUp(){
 }
 
 void DisplayManager::shutDown(){
-    // screenTexture.free();
+    mTexturePixels = nullptr;
   
-    // SDL_FreeSurface(surface);
+    SDL_DestroyTexture(mTexture);
+    mTexture = nullptr;
 
-    // SDL_DestroyRenderer(SDLRenderer);
-    // SDLRenderer = nullptr;
+    SDL_DestroyRenderer(mSDLRenderer);
+    mSDLRenderer = nullptr;
 
-    SDL_DestroyWindow(mainWindow);
-    mainWindow = nullptr;
+    SDL_DestroyWindow(mWindow);
+    mWindow = nullptr;
 
     SDL_Quit();
 }
@@ -55,9 +56,8 @@ bool DisplayManager::startSDL(){
 }
 
 bool DisplayManager::createWindow(){
-    mainWindow = SDL_CreateWindow( "SoftwareRenderer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
-    surface = SDL_GetWindowSurface(mainWindow);
-    if( mainWindow == nullptr){
+    mWindow = SDL_CreateWindow( "SoftwareRenderer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
+    if( mWindow == nullptr){
         printf("Could not create window. Error: %s\n", SDL_GetError() );
         return false;
     }
@@ -65,9 +65,8 @@ bool DisplayManager::createWindow(){
 }
 
 bool DisplayManager::createSDLRenderer(){
-    //SDLRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_PRESENTVSYNC);
-    SDLRenderer = SDL_CreateSoftwareRenderer(surface);
-    if(SDLRenderer == nullptr){
+    mSDLRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_PRESENTVSYNC);
+    if(mSDLRenderer == nullptr){
         printf("Could not create renderer context. Error: %s\n", SDL_GetError());
         return false;
     }
@@ -75,7 +74,9 @@ bool DisplayManager::createSDLRenderer(){
 }
 
 bool DisplayManager::createScreenTexture(){
-    if(! screenTexture.createBlank(SDLRenderer, SCREEN_WIDTH, SCREEN_HEIGHT)){
+    mTexture = SDL_CreateTexture(mSDLRenderer, SDL_PIXELFORMAT_RGBA8888,
+        SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT);
+    if(mTexture == NULL){
         printf("Could not create texture. Error: %s\n", SDL_GetError());
         return false;
     }
@@ -83,27 +84,26 @@ bool DisplayManager::createScreenTexture(){
 }
 
 void DisplayManager::clear(){
-    SDL_LockSurface(surface);
-    SDL_memset(surface->pixels,0 ,surface->h * surface->pitch);
-    SDL_UnlockSurface(surface);
-    //SDL_SetRenderDrawColor(SDLRenderer, 0x00, 0x00, 0x00, 0xFF);
-    //SDL_RenderClear(SDLRenderer);
-
+    SDL_SetRenderDrawColor(mSDLRenderer, 0x00, 0x00, 0x00, 0xFF);
+    SDL_RenderClear(mSDLRenderer);
 }
 
-void DisplayManager::draw(Buffer<Uint32> *pixels){
+void DisplayManager::swapBuffers(Buffer<Uint32> *pixels){
+    
+    //Lock texture for manipulation
+    SDL_LockTexture(mTexture, NULL, &mTexturePixels, &mTexturePitch );
     
-    // screenTexture.update(pixels->buffer);
+    //Copy pixels to texture memory PRETTY SLOW. FIX?
+    memcpy(mTexturePixels, pixels->buffer, SCREEN_HEIGHT*mTexturePitch);
 
-    // //Render texture to screen
-    // screenTexture.renderToScreen(SDLRenderer);
+    //Unlocking texture to apply pixel changes
+    SDL_UnlockTexture(mTexture);
+    mTexturePixels = nullptr;
 
-    // //Update screen to window
-    // SDL_RenderPresent( SDLRenderer );
+    //Setting blendmode for copy operation to renderer backbuffer
+    SDL_SetTextureBlendMode(mTexture, SDL_BLENDMODE_BLEND);
+    SDL_RenderCopy(mSDLRenderer, mTexture, NULL , NULL);
 
-    //Testing pure software rendering
-    SDL_LockSurface(surface);
-    memcpy(surface->pixels, pixels->buffer, pixels->mHeight*pixels->mPitch);
-    SDL_UnlockSurface(surface);
-    SDL_UpdateWindowSurface(mainWindow);
+    //Update screen to window
+    SDL_RenderPresent( mSDLRenderer );
 }

+ 16 - 11
src/engine.cpp

@@ -15,16 +15,18 @@ bool Engine::startUp(){
         printf("Failed to initialize window manager.\n");
     }
     else{
-        //Gets window and creates all buffers according to window size
-        if( !gRenderer.startUp(gDisplayManager) ){
+        //Loads default scene
+        if( !gSceneManager.startUp() ){
             success = false;
-            printf("Failed to initialize render manager.\n");
+            printf("Failed to initialize scene manager.\n");
         }
         else{
-            //Loads default scene
-            if( !gSceneManager.startUp() ){
+            //Initializes renderer and connects it to the window manager
+            //Also gets pointer to current scene
+            if( !gRenderManager.startUp(gDisplayManager,gSceneManager) ){
             success = false;
-            printf("Failed to initialize scene manager.\n");
+            printf("Failed to initialize render manager.\n");
+            
             }
             else{
                 if ( !gInputManager.startUp() ){
@@ -41,10 +43,13 @@ bool Engine::startUp(){
 void Engine::shutDown(){
     printf("Closing input manager.\n");
     gInputManager.shutDown();
+
+    printf("Closing renderer manager.\n");
+    gRenderManager.shutDown();
+    
     printf("Closing Scene manager.\n");
     gSceneManager.shutDown();
-    printf("Closing renderer manager.\n");
-    gRenderer.shutDown();
+    
     printf("Closing display manager.\n");
     gDisplayManager.shutDown();
 }
@@ -70,7 +75,7 @@ void Engine::run(){
         if( switchScene ){
             if( !gSceneManager.switchScene() ){
                 printf("Failed to switch scene! Quitting.\n");
-                continue;
+                break;
             }
             else switchScene = false;
         }
@@ -81,8 +86,8 @@ void Engine::run(){
         //Update all models and camera in the current scene
         gSceneManager.update();
 
-        //Enter rendering loop and render current scene
-        gRenderer.render();
+        //Update Rendering Queue and draw each item 
+        gRenderManager.render();
 
         end = SDL_GetTicks();
         printf("%2.1d: Loop elapsed time (ms):%d\n",count,end - start);

+ 2 - 2
src/model.cpp

@@ -51,7 +51,7 @@ void Model::loadFaces(std::ifstream &file){
         iss >> f;
         if(f == "f"){
             iss >> x >> y >> z;
-            Vector3 face(x,y,z);
+            Vector3 face(std::stof(x)-1,std::stof(y)-1,std::stof(z)-1);
             mMesh.faces.push_back(face);
         }
     }
@@ -68,7 +68,7 @@ void Model::loadVertices(std::ifstream &file){
         iss >> v;
         if(v == "v"){
             iss >> x >> y >> z;
-            Vector3 vertex(x,y,z);
+            Vector3 vertex(std::stof(x),std::stof(y),std::stof(z));
             mMesh.vertices.push_back(vertex);
         }
     }

+ 119 - 150
src/rasterizer.cpp

@@ -4,182 +4,151 @@
 #include <algorithm>
 
 const SDL_PixelFormat* Rasterizer::mappingFormat( SDL_AllocFormat(PIXEL_FORMAT));
-
-void Rasterizer::makeCoolPattern(){
-    Uint32 red = SDL_MapRGBA(mappingFormat, 0xFF,0x00,0x00,0xFF);
-    Uint32 green = SDL_MapRGBA(mappingFormat, 0x00,0xFF,0x00,0xFF);
-    Uint32 blue = SDL_MapRGBA(mappingFormat, 0x00,0x00,0xFF,0xFF);
-
-    for(int y = 0; y < mPixelBuffer->mHeight; ++y){
-        for(int x = 0; x < mPixelBuffer->mWidth; ++x){
-            Uint8 r = x*y % 256;
-            Uint8 g = y % 256;
-            Uint8 b = x % 256;
+const Uint32 Rasterizer::white(SDL_MapRGBA(mappingFormat, 0xFF,0xFF,0xFF,0xFF));
+const Uint32 Rasterizer::red(SDL_MapRGBA(mappingFormat, 0xFF,0x00,0x00,0xFF));
+const Uint32 Rasterizer::green(SDL_MapRGBA(mappingFormat, 0x00,0xFF,0x00,0xFF));
+const Uint32 Rasterizer::blue(SDL_MapRGBA(mappingFormat, 0x00,0x00,0xFF,0xFF));
+
+void Rasterizer::makeCoolPattern(Buffer<Uint32> *pixelBuffer){
+    for(int y = 0; y < pixelBuffer->mHeight; ++y){
+        for(int x = 0; x < pixelBuffer->mWidth; ++x){
+            Uint8 r = x*2 % 256;
+            Uint8 g = y/8 % 256;
+            Uint8 b = r*y % 256;
             Uint32 color = SDL_MapRGBA(mappingFormat, r,g,b,0xFF);
-            setPixelColor(x, y, color);
+            (*pixelBuffer)(x,y) = color;
         }
     }
 }
 
-void Rasterizer::testPattern(){
-    Uint32 red = SDL_MapRGBA(mappingFormat, 0xFF,0x00,0x00,0xFF);
-    Uint32 green = SDL_MapRGBA(mappingFormat, 0x00,0xFF,0x00,0xFF);
-    Uint32 blue = SDL_MapRGBA(mappingFormat, 0x00,0x00,0xFF,0xFF);
-    setPixelColor(600,200, red);
-    setPixelColor(400,200, green);
-    setPixelColor(200,200, blue);
+void Rasterizer::testPattern(Buffer<Uint32> *pixelBuffer){
+    (*pixelBuffer)(600,200) = red;
+    (*pixelBuffer)(400,200) = green;
+    (*pixelBuffer)(200,200) = blue;
+
+}
+
+void Rasterizer::drawLine(Vector3 &vertex1, Vector3 &vertex2,const Uint32 &color, Buffer<Uint32> *pixelBuffer ){
+    int x1 = (vertex1.x + 1 ) * pixelBuffer->mWidth * 0.5;
+    int y1 = (-vertex1.y + 1 ) * pixelBuffer->mHeight * 0.5;
+    int x2 = (vertex2.x +1 ) * pixelBuffer->mWidth  * 0.5;
+    int y2 = (-vertex2.y +1 ) * pixelBuffer->mHeight * 0.5;
+
+    //transpose line if it is too steep
+    bool steep = false;
+    if (std::abs(x1-x2) < std::abs(y1-y2) ){
+        std::swap(x1,y1);
+        std::swap(x2,y2);
+        steep = true;
+    }
+
+    //Redefine line so that it is left to right
+    if ( x1  > x2 ){
+        std::swap(x1,x2);
+        std::swap(y1,y2);
+    }
+    int dx = x2 - x1;
+    int dy = y2 - y1;
+    int derror2 = std::abs(dy)*2;
+    int error2 = 0;
+    int y = y1;
+
+    for(int x=x1; x <= x2 ; x++){
+        if(steep){
+                (*pixelBuffer)(y, x) = color;
+            }
+            else{
+                (*pixelBuffer)(x,y) = color;
+            }
+        error2 += derror2;
+        if (error2 > dx){
+            y += (y2 > y1  ? 1 : -1);
+            error2 -= dx*2;
+        }
 
+    }
+        
 }
 
+void Rasterizer::drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer){
+    drawLine(vertices[0], vertices[1], red, pixelBuffer);
+    drawLine(vertices[1], vertices[2], green, pixelBuffer);
+    drawLine(vertices[0], vertices[2], blue, pixelBuffer);
+}  
+
+
 //Draws triangles using edge detection and baricentric coordinates,
 //Also shades based on a light coming directly from the camera
-// void Rasterizer::drawTriangles(Vector3 &a, Vector3 &b, Vector3 &c, float intensity ){
-//     Uint32 color = SDL_MapRGBA(mappingFormat,
-//                 255*intensity,255*intensity,255*intensity,0xFF);
+void Rasterizer::drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer, Buffer<float> *zBuffer, float intensity){
+    Uint32 color = SDL_MapRGBA(mappingFormat,
+                255*intensity,255*intensity,255*intensity,0xFF);
 
-//     //Converting to screen space
-//     std::array<int, 3> xVerts;
-//     std::array<int, 3> yVerts;
-//     std::array<float, 3> zVerts;
-//     xVerts[0] = (a.x + 1 ) * mCanvas->mWidth * 0.5;
-//     yVerts[0] = (-a.y + 1 ) * mCanvas->mHeight * 0.5;
-//     zVerts[0] = (a.z);
+    //Converting to screen space
+    std::array<int, 3> xVerts;
+    std::array<int, 3> yVerts;
+    std::array<float, 3> zVerts;
+    xVerts[0] = (vertices[0].x + 1 ) * pixelBuffer->mWidth * 0.5;
+    yVerts[0] = (-vertices[0].y + 1 ) * pixelBuffer->mHeight * 0.5;
+    zVerts[0] = vertices[0].z;
 
-//     xVerts[1] = (b.x +1 ) * mCanvas->mWidth  * 0.5;
-//     yVerts[1] = (-b.y +1 ) * mCanvas->mHeight * 0.5;
-//     zVerts[1] = (b.z);
+    xVerts[1] = (vertices[1].x +1 ) * pixelBuffer->mWidth  * 0.5;
+    yVerts[1] = (-vertices[1].y +1 ) * pixelBuffer->mHeight * 0.5;
+    zVerts[1] = vertices[1].z;
 
-//     xVerts[2] = (c.x +1 ) * mCanvas->mWidth  * 0.5;
-//     yVerts[2] = (-c.y +1 ) * mCanvas->mHeight * 0.5;
-//     zVerts[2] = (c.z);
+    xVerts[2] = (vertices[2].x +1 ) * pixelBuffer->mWidth  * 0.5;
+    yVerts[2] = (-vertices[2].y +1 ) * pixelBuffer->mHeight * 0.5;
+    zVerts[2] = vertices[2].z;
 
 
-//     //Finding triangle bounding box
-//     int xMax = *std::max_element(xVerts.begin(),xVerts.end());
-//     int yMax = *std::max_element(yVerts.begin(),yVerts.end());
-//     int xMin = *std::min_element(xVerts.begin(),xVerts.end());
-//     int yMin = *std::min_element(yVerts.begin(),yVerts.end());
+    //Finding triangle bounding box
+    int xMax = *std::max_element(xVerts.begin(),xVerts.end());
+    int yMax = *std::max_element(yVerts.begin(),yVerts.end());
+    int xMin = *std::min_element(xVerts.begin(),xVerts.end());
+    int yMin = *std::min_element(yVerts.begin(),yVerts.end());
 
-//     //Find triangle area
-//     float area = std::abs((xVerts[2]-xVerts[0])*(yVerts[1]-yVerts[0]) 
-//                             - (xVerts[1]-xVerts[0])*(yVerts[2]-yVerts[0]));
+    //Find triangle area
+    float area = std::abs((xVerts[2]-xVerts[0])*(yVerts[1]-yVerts[0]) 
+                            - (xVerts[1]-xVerts[0])*(yVerts[2]-yVerts[0]));
 
-//     //Iterating the triangle bounding box
-//     //printf("Iterating through triangle bounding box\n");
-//     //printf("ymin: %d, ymax: %d, xmin: %d, xmax: %d\n",yMin, yMax, xMin, xMax);
-//     for(int y = yMin; y <= yMax; ++y){
-//         for(int x = xMin; x <= xMax; ++x){
-//             //Throw pixel away if not in screen
-//             if( x < 0 || x > mCanvas->mWidth || y < 0 || y > mCanvas->mHeight ) continue;
+    //Iterating the triangle bounding box
+    //printf("Iterating through triangle bounding box\n");
+    //printf("ymin: %d, ymax: %d, xmin: %d, xmax: %d\n",yMin, yMax, xMin, xMax);
+    for(int y = yMin; y <= yMax; ++y){
+        for(int x = xMin; x <= xMax; ++x){
+            //Throw pixel away if not in screen
+            if( x < 0 || x > pixelBuffer->mWidth || y < 0 || y > pixelBuffer->mHeight ) continue;
 
-//             float lambda0 = ((x-xVerts[0])*(yVerts[1]-yVerts[0]) 
-//                             - (xVerts[1]-xVerts[0])*(y-yVerts[0])) / area;
+            float lambda0 = ((x-xVerts[0])*(yVerts[1]-yVerts[0]) 
+                            - (xVerts[1]-xVerts[0])*(y-yVerts[0])) / area;
 
-//             float lambda1 = ((x-xVerts[1])*(yVerts[2]-yVerts[1]) 
-//                             - (xVerts[2]-xVerts[1])*(y-yVerts[1])) / area;
+            float lambda1 = ((x-xVerts[1])*(yVerts[2]-yVerts[1]) 
+                            - (xVerts[2]-xVerts[1])*(y-yVerts[1])) / area;
 
-//             float lambda2 = ((x-xVerts[2])*(yVerts[0]-yVerts[2]) 
-//                             - (xVerts[0]-xVerts[2])*(y-yVerts[2])) / area;
+            float lambda2 = ((x-xVerts[2])*(yVerts[0]-yVerts[2]) 
+                            - (xVerts[0]-xVerts[2])*(y-yVerts[2])) / area;
 
-//             //Throw pixel away if not in triangle
-//             if(lambda0 < 0 || lambda1 < 0 || lambda2 < 0) continue;
+            //Throw pixel away if not in triangle
+            if(lambda0 < 0 || lambda1 < 0 || lambda2 < 0) continue;
 
-//             float depth = lambda1*zVerts[0] + lambda2*zVerts[1] + lambda0*zVerts[2];
+            float depth = lambda1*zVerts[0] + lambda2*zVerts[1] + lambda0*zVerts[2];
 
-//             //If any of the edge functions are smaller than zero, discard the point
+            //If any of the edge functions are smaller than zero, discard the point
             
-//             if(getDepthBufferAtLocation(x,y) < depth){
-//                 float depthDiff = std::abs(depth - getDepthBufferAtLocation(x,y));
-//                 if(depth <= 1.0){
-//                     if(depthDiff < 0.1){
-//                     //printf("Bari: %f, %f, %f\n",lambda0,lambda1,lambda2);
-//                     //printf("Depth Buffer: %f\n",getDepthBufferAtLocation(x,y));
-//                     //printf("Pixel Depth: %f \n",depth);
-//                     setDepthBufferAtLocation(x,y,depth);
-//                     setPixelColor(x, y, color);
-
-//                     }
-//                     else{
-
-//                         setDepthBufferAtLocation(x,y,depth);
-//                         setPixelColor(x, y, color);
-//                     }
-//                 }
-                
-                
-                    
-//             } 
-
-//         }
-//     }
-
-// }  
-
-// void Rasterizer::drawWireFrame(Vector3 &v1, Vector3 &v2, Vector3 &v3 ){
-//     drawLine(v1, v2, red);
-//     drawLine(v2, v3, green);
-//     drawLine(v1, v3, blue);
-// }   
-
-// void Rasterizer::drawLine(Vector3 &vertex1, Vector3 &vertex2, Uint32 &color){
-//     int x1 = (vertex1.x + 1 ) * mCanvas->mWidth * 0.5;
-//     int y1 = (-vertex1.y + 1 ) * mCanvas->mHeight * 0.5;
-//     int x2 = (vertex2.x +1 ) * mCanvas->mWidth  * 0.5;
-//     int y2 = (-vertex2.y +1 ) * mCanvas->mHeight * 0.5;
-
-//     //transpose line if it is too steep
-//     bool steep = false;
-//     if (std::abs(x1-x2) < std::abs(y1-y2) ){
-//         std::swap(x1,y1);
-//         std::swap(x2,y2);
-//         steep = true;
-//     }
-
-//     //Redefine line so that it is left to right
-//     if ( x1  > x2 ){
-//         std::swap(x1,x2);
-//         std::swap(y1,y2);
-//     }
-//     int dx = x2 - x1;
-//     int dy = y2 - y1;
-//     int derror2 = std::abs(dy)*2;
-//     int error2 = 0;
-//     int y = y1;
-
-//     for(int x=x1; x <= x2 ; x++){
-//         if(steep){
-//                 setPixelColor(y, x, color);
-//             }
-//             else{
-//                 setPixelColor( x, y, color);
-//             }
-//         error2 += derror2;
-//         if (error2 > dx){
-//             y += (y2 > y1  ? 1 : -1);
-//             error2 -= dx*2;
-//         }
-
-//     }
-        
-// }
+            if((*zBuffer)(x,y) < depth){
+                if(depth <= 1.0){
+                        (*zBuffer)(x,y) = depth;
+                        (*pixelBuffer)(x,y) = color;
+                }   
+            } 
+
+        }
+    }
+
+}  
+
+ 
 
-void Rasterizer::setPixelColor(int x, int y, Uint32 color){
-        int arrayCoordinates = convertCoordinates(x,y); 
-        mPixelBuffer->buffer[arrayCoordinates] = color;
-    
-}
 
-int Rasterizer::convertCoordinates(int x, int y){
-    return ((y * mPixelBuffer->mWidth) + x);
-}
 
-float Rasterizer::getDepthBufferAtLocation(int x, int y){
-    int arrayCoordinates = convertCoordinates(x,y);
-    return mPixelBuffer->buffer[arrayCoordinates];
-}
 
-void Rasterizer::setDepthBufferAtLocation(int x, int y, float depth){
-    int arrayCoordinates = convertCoordinates(x,y);
-    mPixelBuffer->buffer[arrayCoordinates] = depth;
-}
 

+ 80 - 0
src/renderManager.cpp

@@ -0,0 +1,80 @@
+#include "renderManager.h"
+#include <vector>
+#include "model.h"
+
+RenderManager::RenderManager(){
+
+}
+
+RenderManager::~RenderManager(){
+
+}
+
+bool RenderManager::startUp(DisplayManager &displayManager,SceneManager &sceneManager ){
+    screen = &displayManager;
+    sceneLocator = &sceneManager;
+    if( !initSoftwareRenderer() ){
+        printf("Failed to initialize software Renderer!\n");
+        return false;
+    }
+    return true;
+}
+
+void RenderManager::shutDown(){
+    sceneLocator = nullptr;
+    screen = nullptr;
+    renderInstance.shutDown();
+}
+
+void RenderManager::render(){
+
+    //Clear screen and reset current buffers
+    screen->clear();
+    renderInstance.clearBuffers();
+
+    //Build a render Queue for drawing multiple models and assign camera
+    buildRenderQueue();
+
+    //Draw all meshes in the render queue so far we assume they are
+    //normal triangular meshes.
+    while( !renderQueue.empty() ){
+        renderInstance.drawTriangularMesh(renderQueue.front());
+        renderQueue.pop();
+    }
+
+    //Swapping pixel buffer with final rendered image with the
+    //display buffer
+    screen->swapBuffers(renderInstance.getRenderTarget());
+
+    //Set camera pointer to null just in case a scene change occurs
+    renderInstance.setCameraToRenderFrom(nullptr);
+}
+
+bool RenderManager::initSoftwareRenderer(){
+    int w = DisplayManager::SCREEN_WIDTH;
+    int h = DisplayManager::SCREEN_HEIGHT;
+    return renderInstance.startUp(w,h);
+}
+
+
+//Gets the list of visible models from the current scene and 
+//extracts a list of pointers to their meshes. Also
+void RenderManager::buildRenderQueue(){
+    
+    //Set renderer camera
+    Scene* currentScene = sceneLocator->getCurrentScene();
+    renderInstance.setCameraToRenderFrom(currentScene->getCurrentCamera());
+
+    std::vector<Model*>* visibleModels = currentScene->getVisiblemodels();
+    
+    //Builds render queue from visibleModels list
+    for (Model* model : *visibleModels ){
+        renderQueue.push(model->getMesh());
+    }
+}
+
+
+
+
+
+

+ 45 - 6
src/scene.cpp

@@ -5,20 +5,26 @@ Scene::Scene(std::string path){
 }
 
 Scene::~Scene(){
-    delete sceneModel;
+    for(Model *models : modelsInScene){
+        delete models;
+    }
 }
 
 void Scene::update(){
+    visibleModels.clear();
     mainCamera.update();
-    sceneModel->update();
+    for(Model *models : modelsInScene){
+        models->update();
+    }
+    frustrumCulling();
 }
 
 void Scene::loadSceneModels(std::string path){
     //In the future I want to read all o the models in the model folder
-    //And build them here.  For now I force it to be only one.
+    //And build them here.  For now only one
     std::string fullPath = "../models/";
     fullPath = fullPath + path;
-    sceneModel = new Model(fullPath);
+    modelsInScene.push_back(new Model(fullPath));
 
     //We also initialize the model position here position here
     TransformParameters initParameters;
@@ -26,7 +32,40 @@ void Scene::loadSceneModels(std::string path){
     initParameters.rotation = Vector3(0,0,0);
     initParameters.translation = Vector3(0, -1, 0);
 
-    sceneModel->initPosition(initParameters);
+    modelsInScene[0]->initPosition(initParameters);
 
     //sceneModel->describeMesh();
-}
+}
+
+void Scene::frustrumCulling(){
+    bool visible = true;
+    for(Model *model : modelsInScene){
+
+        //TO DO Visibility check against camera's frustrum planes
+
+        if (visible){
+            visibleModels.push_back(model);
+        }
+    }
+}
+
+std::vector<Model*>* Scene::getVisiblemodels(){
+    return &visibleModels;
+}
+
+Camera* Scene::getCurrentCamera(){
+    return &mainCamera;
+}
+
+// //If the frustrum culling returns true it means the model has been culled
+    // //Because no other models are in the scene we return
+    // // if (frustrumCulling(models, viewMatrix)){
+    // //     printf("Model culled!\n");
+    // //     return;
+    // // } 
+
+
+//     //stupid frustrum culling
+    //     //if(v1.x < -1 || v1.x > 1 || v1.y < -1 || v1.y > 1 || v1.z > 1 || v1.z < -1) continue;
+    //     //if(v2.x < -1 || v2.x > 1 || v2.y < -1 || v2.y > 1 || v2.z > 1 || v2.z < -1) continue;
+    //     //if(v3.x < -1 || v3.x > 1 || v3.y < -1 || v3.y > 1 || v3.z > 1 || v3.z < -1) continue;

+ 5 - 1
src/sceneManager.cpp

@@ -28,10 +28,14 @@ bool SceneManager::switchScene(){
 //for now just loads the teapot.obj
 bool SceneManager::loadScene(){
     bool success = true;
-    currentScene = new Scene("teapot.obj");
+    currentScene = new Scene("cow.obj");
     return success;
 }
 
 void SceneManager::update(){
     currentScene->update();
+}
+
+Scene* SceneManager::getCurrentScene(){
+    return currentScene;
 }

+ 0 - 0
src/shader.cpp


+ 61 - 79
src/softwareRenderer.cpp

@@ -1,4 +1,5 @@
 #include "softwareRenderer.h"
+#include "shader.h"
 
 SoftwareRenderer::SoftwareRenderer(){
 
@@ -8,21 +9,17 @@ SoftwareRenderer::~SoftwareRenderer(){
 
 }
 
-bool SoftwareRenderer::startUp(DisplayManager &displayManager){
-    screen = &displayManager;
-    if( !createBuffers() ){
+bool SoftwareRenderer::startUp(int w, int h){
+    if( !createBuffers(w, h) ){
         return false;
     }
-    //Create rasterizer to begin drawing
-    raster = new Rasterizer(pixelBuffer);
-    //createProjectionMatrix();
     return true;
 }
 
 void SoftwareRenderer::shutDown(){
+    mCamera = nullptr;
     delete zBuffer;
     delete pixelBuffer;
-    delete raster;
 }
 
 void SoftwareRenderer::clearBuffers(){
@@ -30,9 +27,7 @@ void SoftwareRenderer::clearBuffers(){
     pixelBuffer->clear();
 }
 
-bool SoftwareRenderer::createBuffers(){
-    int w = DisplayManager::SCREEN_WIDTH;
-    int h = DisplayManager::SCREEN_HEIGHT;
+bool SoftwareRenderer::createBuffers(int w, int h){
     int pixelCount = w*h;
     bool success = true;
 
@@ -51,74 +46,61 @@ bool SoftwareRenderer::createBuffers(){
     return success;
 }
 
-void SoftwareRenderer::render(){
-
-    //Clear screen and reset current buffers
-    screen->clear();
-    clearBuffers();
-
-    //Getting the meshes and faces 
-    // Mesh * modelMesh = models->getMesh();
-    // std::vector<Vector3> * faces = &modelMesh->faces;
-    // std::vector<Vector3> * vertices = &modelMesh->vertices;
-
-    // //If the frustrum culling returns true it means the model has been culled
-    // //Because no other models are in the scene we return
-    // // if (frustrumCulling(models, viewMatrix)){
-    // //     printf("Model culled!\n");
-    // //     return;
-    // // } 
-    // //Kind of a vertex shader I guess?
-    // for (Vector3 f : *faces ){
-
-    //     //View matrix transform
-    //     Vector3 v0 = viewMatrix.matMultVec((*vertices)[f.x-1]); //-1 because .obj file starts face count
-    //     Vector3 v1 = viewMatrix.matMultVec((*vertices)[f.y-1]); // from 1. Should probably fix this 
-    //     Vector3 v2 = viewMatrix.matMultVec((*vertices)[f.z-1]); // At some point
-
-    //     //Back face culling in view space
-    //     Vector3 N1 = v1 - v0;
-    //     Vector3 N2 = v2 - v0;
-    //     Vector3 N  = (N1.crossProduct(N2)).normalized();
-    //     Vector3 neg = (v0.neg()).normalized();
-    //     float intensity = N.dotProduct(neg);
-    //     if(intensity < 0.0) continue; //Exit if you can't even see it
-
-
-    //     //stupid frustrum culling
-    //     //if(v1.x < -1 || v1.x > 1 || v1.y < -1 || v1.y > 1 || v1.z > 1 || v1.z < -1) continue;
-    //     //if(v2.x < -1 || v2.x > 1 || v2.y < -1 || v2.y > 1 || v2.z > 1 || v2.z < -1) continue;
-    //     //if(v3.x < -1 || v3.x > 1 || v3.y < -1 || v3.y > 1 || v3.z > 1 || v3.z < -1) continue;
-
-    //     // Projection matrix transformation
-    //     v0 = projectionMatrix.matMultVec(v0);
-    //     v1 = projectionMatrix.matMultVec(v1);
-    //     v2 = projectionMatrix.matMultVec(v2);
-
-    //     //Rasterizing and shading in one
-    raster->makeCoolPattern();
-               
-    // }
-    //Apply the pixel changes and redraw
-    screen->draw(pixelBuffer);
+void SoftwareRenderer::drawTriangularMesh(Mesh* triMesh){
+
+    //Getting the vertices, faces 
+    std::vector<Vector3> * faces = &triMesh->faces;
+    std::vector<Vector3> * vertices = &triMesh->vertices;
+
+    //Array grouping vertices together into triangle
+    Vector3 trianglePrimitive[3];
+
+    //Initializing shader
+    FlatShader shader;
+
+    //Building ModelViewProjection matrix
+
+    Matrix4 MVP = (mCamera->projectionMatrix)*(mCamera->viewMatrix);
+
+    float intensity = 0;
+    int count = 0;
+    for (Vector3 &f : *faces ){
+        buildTri(f,trianglePrimitive, *vertices);
+        if (backFaceCulling(trianglePrimitive, intensity)) continue;
+        ++count;
+        for(int i = 0; i < 3; ++i){
+            trianglePrimitive[i] = shader.vertex(trianglePrimitive[i], MVP);
+        }
+        Rasterizer::drawTriangles(trianglePrimitive, shader, pixelBuffer, zBuffer, intensity);
+    }
+    printf("I rendered this: %d many faces.\n",count);
 }
 
-// bool SoftwareRenderer::frustrumCulling(Model *model, Matrix4 &viewMatrix){
-//     bool cull = false;
-//     Matrix4 viewProjectionMat = projectionMatrix*viewMatrix;
-//     return cull;
-// }
-
-// bool SoftwareRenderer::createCanvas(){
-//     int pixelCount = WindowManager::SCREEN_WIDTH * WindowManager::SCREEN_HEIGHT;
-//     int pitch      = WindowManager::SCREEN_WIDTH * sizeof(Uint32);
-//     mainCanvas = new Canvas(WindowManager::SCREEN_WIDTH,
-//                             WindowManager::SCREEN_HEIGHT,
-//                             pixelCount, pitch,
-//                             new Uint32[pixelCount], new float[pixelCount]);
-//     SDL_memset(mainCanvas->mBuffer, 0, mainCanvas->mPixelCount * sizeof(Uint32) );
-//     for(int i = 0; i < mainCanvas->mPixelCount;++i){
-//         mainCanvas->mDBuffer[i]  = 0.0f;
-//     }
-//     return mainCanvas != NULL;
-// }
+Buffer<Uint32>* SoftwareRenderer::getRenderTarget(){
+    return pixelBuffer;
+}
+
+void SoftwareRenderer::buildTri(Vector3 &f, Vector3 *trianglePrim, std::vector<Vector3> &verts){
+    for(int i = 0; i < 3; ++i){
+        trianglePrim[i] = verts[f[i]];
+    }
+}
+
+void SoftwareRenderer::setCameraToRenderFrom(Camera * camera){
+    mCamera = camera;
+}
+
+bool SoftwareRenderer::backFaceCulling(Vector3 *trianglePrim, float &intensity){
+        //Triangle surface normal 
+        //Should probably be calculated on load next time
+        Vector3 N1 = trianglePrim[1] - trianglePrim[0];
+        Vector3 N2 = trianglePrim[2] - trianglePrim[0];
+        Vector3 N  = (N1.crossProduct(N2)).normalized();
+
+        //View direction
+        Vector3 view_dir = trianglePrim[0] - mCamera->position ;
+        view_dir = view_dir.normalized();
+
+        intensity = N.dotProduct(view_dir);
+        return intensity >= 0.0;
+}

+ 0 - 50
src/texture.cpp

@@ -1,50 +0,0 @@
-#include "texture.h"
-
-
-Texture::Texture(){
-    mTexture = NULL;
-    mWidth   = 0;
-    mHeight  = 0;
-    mPitch   = 0;
-}
-
-Texture::~Texture(){
-    free();
-}
-
-void Texture::free(){
-    if(mTexture != NULL){
-        SDL_DestroyTexture (mTexture);
-        mWidth  = 0;
-        mHeight = 0;
-        mPitch  = 0; 
-        mTrash = nullptr;
-    }
-}
-
-bool Texture::createBlank(SDL_Renderer  *renderer, int width, int height ){
-    mWidth  = width;
-    mHeight = height;
-    mPitch  = width * sizeof(Uint32);
-    mTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
-        SDL_TEXTUREACCESS_STREAMING, mWidth, mHeight);
-
-    return mTexture != NULL;
-}
-
-void Texture::update(Uint32 * pixels){
-
-    //Lock texture for manipulation
-    SDL_LockTexture(mTexture, NULL, &mTrash, &mPitch );
-    //Copy pixels to texture
-    memcpy(mTrash, pixels, mHeight*mPitch);
-
-    //Update texture
-    SDL_UnlockTexture(mTexture);
-    mTrash = nullptr;
-}
-
-void Texture::renderToScreen(SDL_Renderer * renderer){
-    SDL_SetTextureBlendMode(mTexture, SDL_BLENDMODE_BLEND);
-    SDL_RenderCopy(renderer, mTexture, NULL , NULL);
-}

+ 19 - 5
src/vector.cpp

@@ -1,6 +1,13 @@
 #include "vector3.h"
 #include "math.h"
 
+Vector3 &Vector3::operator-(){
+    x = -x;
+    y = -y;
+    z = -z;
+    return *this;
+}
+
 Vector3 Vector3::operator-(Vector3 &rhs){
     return Vector3(this->x - rhs.x,
                    this->y - rhs.y,
@@ -8,6 +15,18 @@ Vector3 Vector3::operator-(Vector3 &rhs){
     );
 }
 
+float &Vector3::operator[](int i){
+    if( i == 0 ){
+        return x;
+    }
+    else if ( i == 1 ){
+        return y;
+    }
+    else if ( i == 2 ){
+        return z;
+    }
+}
+
 Vector3& Vector3::normalized(){
     float len = this->length();
     if(len > 0){
@@ -43,9 +62,4 @@ float Vector3::length(){
 
 void Vector3::print(){
     printf("Vec: %f\t%f\t%f\n",x,y,z);
-}
-
-Vector3 Vector3::neg(){
-        Vector3 negval(-this->x,-this->y,-this->z);
-    return negval;
 }