Skip to content

bindings/cpp/raster3d.hpp

C++98 API source. Preserve the bindings/cpp/ layout when downloading multiple files.

Source files · Download raster3d.hpp

#ifndef GASPARDOS_RASTER3D_HPP
#define GASPARDOS_RASTER3D_HPP
#include "framebuffer.hpp"
#include <cmath>

namespace gaspardos
{
    namespace graphics
    {
        struct Vec3
        {
            float x, y, z;

            Vec3(float px = 0, float py = 0, float pz = 0) : x(px), y(py), z(pz)
            {
            }
        };

        struct Triangle
        {
            unsigned a, b, c;
            uint32_t color;

            Triangle(unsigned pa, unsigned pb, unsigned pc, uint32_t value)
                : a(pa), b(pb), c(pc), color(value)
            {
            }
        };

        struct Mesh
        {
            std::vector<Vec3>     vertices;
            std::vector<Triangle> triangles;
        };

        struct Pose
        {
            Vec3 rotation, translation;

            Pose() : translation(0, 0, 4)
            {
            }
        };

        class Shapes3D
        {
        public:
            static Mesh cube(float size = 2);
            static Mesh box(float width, float height, float depth);
            static Mesh pyramid(float base = 2, float height = 2);
            static Mesh plane(float width = 3, float depth = 3);
            static Mesh sphere(float radius = 1, unsigned slices = 16, unsigned stacks = 8);
            static Mesh cylinder(float radius = 1, float height = 2, unsigned slices = 16);
        };

        class Rasterizer3D
        {
            struct Point
            {
                float x, y, inverseZ;
            };

            Framebuffer&       target_;
            std::vector<float> depth_;
            float              near_, focal_;
            Rasterizer3D(const Rasterizer3D&);
            Rasterizer3D& operator=(const Rasterizer3D&);
            Vec3          transform(const Vec3& v, const Pose& pose) const;
            Point         project(const Vec3& v) const;
            void          triangle(const Vec3& a, const Vec3& b, const Vec3& c, uint32_t color);
            void projectedTriangle(const Point& a, const Point& b, const Point& c, uint32_t color);
            void edge(const Vec3& a, const Vec3& b, uint32_t color);
            void marker(const Vec3& v, uint32_t color);
            void sample(int x, int y, float inverseZ, uint32_t color, bool overlay);

        public:
            explicit Rasterizer3D(Framebuffer& target);
            void clear(uint32_t color = 0x00201810);
            // Angles in radians. +Z is forward; clipped at z=0.1.
            void draw(const Mesh& mesh,
                      const Pose& pose           = Pose(),
                      bool        wireframe      = false,
                      bool        hollowVertices = true);
        };
    }  // namespace graphics
}  // namespace gaspardos
#endif