Skip to content

bindings/cpp/raster3d.cpp

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

Source files · Download raster3d.cpp

#include "raster3d.hpp"
#include <algorithm>

namespace gaspardos
{
    namespace graphics
    {
        static const float Pi = 3.14159265358979323846f;

        static bool finite(float value)
        {
            return value == value && value > -1e20f && value < 1e20f;
        }

        static bool dimension(float value)
        {
            return finite(value) && value > 0 && value <= 10000;
        }

        static Vec3 subtract(const Vec3& a, const Vec3& b)
        {
            return Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
        }

        static Vec3 interpolate(const Vec3& a, const Vec3& b, float t)
        {
            return Vec3(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t);
        }

        static uint32_t shade(uint32_t color, const Vec3& a, const Vec3& b, const Vec3& c)
        {
            Vec3  u = subtract(b, a), v = subtract(c, a);
            float us = std::max(std::fabs(u.x), std::max(std::fabs(u.y), std::fabs(u.z)));
            float vs = std::max(std::fabs(v.x), std::max(std::fabs(v.y), std::fabs(v.z)));
            if (us > 0)
            {
                u.x /= us;
                u.y /= us;
                u.z /= us;
            }
            if (vs > 0)
            {
                v.x /= vs;
                v.y /= vs;
                v.z /= vs;
            }
            Vec3  n(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x);
            float length = std::sqrt(n.x * n.x + n.y * n.y + n.z * n.z);
            float light =
                length > 1e-8f
                    ? .25f + .75f * std::fabs((n.x * .3f - n.y * .4f - n.z * .8660254f) / length)
                    : .25f;
            uint32_t result = 0;
            for (unsigned shift = 0; shift < 24; shift += 8)
                result |= static_cast<uint32_t>(((color >> shift) & 255) * std::min(1.f, light))
                          << shift;
            return result;
        }

        Mesh Shapes3D::cube(float size)
        {
            return box(size, size, size);
        }

        Mesh Shapes3D::box(float w, float h, float d)
        {
            Mesh mesh;
            if (!dimension(w) || !dimension(h) || !dimension(d))
                return mesh;
            for (unsigned i = 0; i < 8; ++i)
                mesh.vertices.push_back(Vec3(
                    (i & 1 ? .5f : -.5f) * w, (i & 2 ? .5f : -.5f) * h, (i & 4 ? .5f : -.5f) * d));
            const unsigned faces[6][4] = { { 0, 2, 3, 1 }, { 4, 5, 7, 6 }, { 0, 4, 6, 2 },
                                           { 1, 3, 7, 5 }, { 0, 1, 5, 4 }, { 2, 6, 7, 3 } };
            const uint32_t colors[6]   = { 0x004080ff, 0x00ffb060, 0x0060d080,
                                           0x00e080d0, 0x0080d0f0, 0x00d0b060 };
            for (unsigned i = 0; i < 6; ++i)
            {
                mesh.triangles.push_back(
                    Triangle(faces[i][0], faces[i][1], faces[i][2], colors[i]));
                mesh.triangles.push_back(
                    Triangle(faces[i][0], faces[i][2], faces[i][3], colors[i]));
            }
            return mesh;
        }

        Mesh Shapes3D::pyramid(float base, float height)
        {
            Mesh mesh;
            if (!dimension(base) || !dimension(height))
                return mesh;
            float b = base * .5f, h = height * .5f;
            mesh.vertices.push_back(Vec3(-b, -h, -b));
            mesh.vertices.push_back(Vec3(b, -h, -b));
            mesh.vertices.push_back(Vec3(b, -h, b));
            mesh.vertices.push_back(Vec3(-b, -h, b));
            mesh.vertices.push_back(Vec3(0, h, 0));
            mesh.triangles.push_back(Triangle(0, 2, 1, 0x0080b0e0));
            mesh.triangles.push_back(Triangle(0, 3, 2, 0x0080b0e0));
            for (unsigned i = 0; i < 4; ++i)
                mesh.triangles.push_back(Triangle(i, (i + 1) % 4, 4, 0x0060a0ff + i * 0x180000));
            return mesh;
        }

        Mesh Shapes3D::plane(float width, float depth)
        {
            Mesh mesh;
            if (!dimension(width) || !dimension(depth))
                return mesh;
            mesh.vertices.push_back(Vec3(-width * .5f, 0, -depth * .5f));
            mesh.vertices.push_back(Vec3(width * .5f, 0, -depth * .5f));
            mesh.vertices.push_back(Vec3(width * .5f, 0, depth * .5f));
            mesh.vertices.push_back(Vec3(-width * .5f, 0, depth * .5f));
            mesh.triangles.push_back(Triangle(0, 1, 2, 0x00a0d080));
            mesh.triangles.push_back(Triangle(0, 2, 3, 0x00a0d080));
            return mesh;
        }

        Mesh Shapes3D::sphere(float radius, unsigned slices, unsigned stacks)
        {
            Mesh mesh;
            if (!dimension(radius) || slices < 3 || slices > 64 || stacks < 2 || stacks > 32)
                return mesh;
            for (unsigned y = 0; y <= stacks; ++y)
            {
                float phi = Pi * y / stacks;
                for (unsigned x = 0; x < slices; ++x)
                {
                    float theta = 2 * Pi * x / slices;
                    mesh.vertices.push_back(Vec3(radius * std::sin(phi) * std::cos(theta),
                                                 radius * std::cos(phi),
                                                 radius * std::sin(phi) * std::sin(theta)));
                }
            }
            for (unsigned y = 0; y < stacks; ++y)
                for (unsigned x = 0; x < slices; ++x)
                {
                    unsigned a = y * slices + x, b = y * slices + (x + 1) % slices, c = a + slices,
                             d = b + slices;
                    if (y)
                        mesh.triangles.push_back(Triangle(a, c, b, 0x00e0b060));
                    if (y + 1 < stacks)
                        mesh.triangles.push_back(Triangle(b, c, d, 0x00e0b060));
                }
            return mesh;
        }

        Mesh Shapes3D::cylinder(float radius, float height, unsigned slices)
        {
            Mesh mesh;
            if (!dimension(radius) || !dimension(height) || slices < 3 || slices > 64)
                return mesh;
            for (unsigned y = 0; y < 2; ++y)
                for (unsigned x = 0; x < slices; ++x)
                {
                    float theta = 2 * Pi * x / slices;
                    mesh.vertices.push_back(Vec3(radius * std::cos(theta),
                                                 (y ? .5f : -.5f) * height,
                                                 radius * std::sin(theta)));
                }
            mesh.vertices.push_back(Vec3(0, -height * .5f, 0));
            mesh.vertices.push_back(Vec3(0, height * .5f, 0));
            for (unsigned x = 0; x < slices; ++x)
            {
                unsigned n = (x + 1) % slices;
                mesh.triangles.push_back(Triangle(x, n, x + slices, 0x0080d0a0));
                mesh.triangles.push_back(Triangle(n, n + slices, x + slices, 0x0080d0a0));
                mesh.triangles.push_back(Triangle(slices * 2, n, x, 0x00e0c080));
                mesh.triangles.push_back(
                    Triangle(slices * 2 + 1, x + slices, n + slices, 0x00e0c080));
            }
            return mesh;
        }

        Rasterizer3D::Rasterizer3D(Framebuffer& target) : target_(target), near_(.1f), focal_(0)
        {
            clear();
        }

        void Rasterizer3D::clear(uint32_t color)
        {
            target_.clear(color);
            depth_.assign(static_cast<std::size_t>(target_.width()) * target_.height(), 0.f);
            focal_ = target_.height() * .8660254f;
        }

        Vec3 Rasterizer3D::transform(const Vec3& v, const Pose& p) const
        {
            float sx = std::sin(p.rotation.x), cx = std::cos(p.rotation.x),
                  sy = std::sin(p.rotation.y), cy = std::cos(p.rotation.y),
                  sz = std::sin(p.rotation.z), cz = std::cos(p.rotation.z);
            Vec3 a(v.x, v.y * cx - v.z * sx, v.y * sx + v.z * cx);
            Vec3 b(a.x * cy + a.z * sy, a.y, -a.x * sy + a.z * cy);
            return Vec3(b.x * cz - b.y * sz + p.translation.x,
                        b.x * sz + b.y * cz + p.translation.y,
                        b.z + p.translation.z);
        }

        Rasterizer3D::Point Rasterizer3D::project(const Vec3& v) const
        {
            Point result = { target_.width() * .5f + v.x * focal_ / v.z,
                             target_.height() * .5f - v.y * focal_ / v.z,
                             1.f / v.z };
            return result;
        }

        void Rasterizer3D::sample(int x, int y, float z, uint32_t color, bool overlay)
        {
            if (x < 0 || y < 0 || static_cast<unsigned>(x) >= target_.width()
                || static_cast<unsigned>(y) >= target_.height() || !finite(z))
                return;
            std::size_t pos = static_cast<std::size_t>(y) * target_.width() + x;
            if (z >= depth_[pos] * (overlay ? .985f : 1.f))
            {
                target_.pixel(x, y, color);
                if (!overlay)
                    depth_[pos] = z;
            }
        }

        void Rasterizer3D::projectedTriangle(const Point& a,
                                             const Point& b,
                                             const Point& c,
                                             uint32_t     color)
        {
            if (!finite(a.x) || !finite(a.y) || !finite(b.x) || !finite(b.y) || !finite(c.x)
                || !finite(c.y))
                return;
            float area = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
            if (!finite(area) || std::fabs(area) < 1e-6f)
                return;
            float minx = std::min(a.x, std::min(b.x, c.x)),
                  maxx = std::max(a.x, std::max(b.x, c.x));
            float miny = std::min(a.y, std::min(b.y, c.y)),
                  maxy = std::max(a.y, std::max(b.y, c.y));
            if (maxx < 0 || maxy < 0 || minx >= target_.width() || miny >= target_.height())
                return;
            int x0 = static_cast<int>(std::max(0.f, minx)),
                x1 = static_cast<int>(std::min(float(target_.width() - 1), maxx));
            int y0 = static_cast<int>(std::max(0.f, miny)),
                y1 = static_cast<int>(std::min(float(target_.height() - 1), maxy));
            for (int y = y0; y <= y1; ++y)
                for (int x = x0; x <= x1; ++x)
                {
                    float px = x + .5f, py = y + .5f;
                    float wa = ((b.x - px) * (c.y - py) - (b.y - py) * (c.x - px)) / area;
                    float wb = ((c.x - px) * (a.y - py) - (c.y - py) * (a.x - px)) / area;
                    float wc = 1.f - wa - wb;
                    if (wa >= -1e-6f && wb >= -1e-6f && wc >= -1e-6f)
                        sample(x,
                               y,
                               wa * a.inverseZ + wb * b.inverseZ + wc * c.inverseZ,
                               color,
                               false);
                }
        }

        void Rasterizer3D::triangle(const Vec3& a, const Vec3& b, const Vec3& c, uint32_t color)
        {
            Vec3     input[3] = { a, b, c }, clipped[4];
            unsigned count    = 0;
            for (unsigned i = 0; i < 3; ++i)
            {
                const Vec3& p = input[i];
                const Vec3& q = input[(i + 1) % 3];
                if (p.z >= near_)
                    clipped[count++] = p;
                if ((p.z >= near_) != (q.z >= near_))
                    clipped[count++] = interpolate(p, q, (near_ - p.z) / (q.z - p.z));
            }
            for (unsigned i = 1; i + 1 < count; ++i)
                projectedTriangle(
                    project(clipped[0]), project(clipped[i]), project(clipped[i + 1]), color);
        }

        void Rasterizer3D::edge(const Vec3& va, const Vec3& vb, uint32_t color)
        {
            Vec3 a = va, b = vb;
            if (a.z < near_ && b.z < near_)
                return;
            if (a.z < near_)
                a = interpolate(a, b, (near_ - a.z) / (b.z - a.z));
            if (b.z < near_)
                b = interpolate(b, a, (near_ - b.z) / (a.z - b.z));
            Point p = project(a), q = project(b);
            float dx = q.x - p.x, dy = q.y - p.y;
            if (!finite(dx) || !finite(dy))
                return;
            // Clip the line in screen space before converting to integer steps.
            float first = 0, last = 1;
            float weights[4]   = { -dx, dx, -dy, dy };
            float distances[4] = {
                p.x, float(target_.width() - 1) - p.x, p.y, float(target_.height() - 1) - p.y
            };
            for (unsigned i = 0; i < 4; ++i)
            {
                if (std::fabs(weights[i]) < 1e-10f)
                {
                    if (distances[i] < 0)
                        return;
                }
                else
                {
                    float t = distances[i] / weights[i];
                    if (weights[i] < 0)
                        first = std::max(first, t);
                    else
                        last = std::min(last, t);
                }
            }
            if (first > last)
                return;
            float span = std::max(std::fabs(dx * (last - first)), std::fabs(dy * (last - first)));
            unsigned steps = static_cast<unsigned>(std::min(2048.f, span)) + 1;
            for (unsigned i = 0; i <= steps; ++i)
            {
                float t = first + (last - first) * i / steps;
                sample(static_cast<int>(p.x + dx * t),
                       static_cast<int>(p.y + dy * t),
                       p.inverseZ + (q.inverseZ - p.inverseZ) * t,
                       color,
                       true);
            }
        }

        void Rasterizer3D::marker(const Vec3& v, uint32_t color)
        {
            if (v.z < near_ || target_.width() < 9 || target_.height() < 9)
                return;
            Point p = project(v);
            if (!finite(p.x) || !finite(p.y) || p.x < 4 || p.y < 4 || p.x >= target_.width() - 4
                || p.y >= target_.height() - 4)
                return;
            int x = static_cast<int>(p.x), y = static_cast<int>(p.y);
            // Hollow radius-four circle: center and inner pixels stay untouched.
            for (int dy = -4; dy <= 4; ++dy)
                for (int dx = -4; dx <= 4; ++dx)
                    if (dx * dx + dy * dy >= 10 && dx * dx + dy * dy <= 18)
                        sample(x + dx, y + dy, p.inverseZ, color, true);
        }

        void Rasterizer3D::draw(const Mesh& mesh,
                                const Pose& pose,
                                bool        wireframe,
                                bool        hollowVertices)
        {
            if (!target_.width() || !target_.height()
                || depth_.size() != static_cast<std::size_t>(target_.width()) * target_.height())
                return;
            std::vector<Vec3> points;
            for (std::size_t i = 0; i < mesh.vertices.size(); ++i)
            {
                Vec3 p = transform(mesh.vertices[i], pose);
                if (!finite(p.x) || !finite(p.y) || !finite(p.z))
                    return;
                points.push_back(p);
            }
            for (std::size_t i = 0; i < mesh.triangles.size(); ++i)
            {
                const Triangle& t = mesh.triangles[i];
                if (t.a >= points.size() || t.b >= points.size() || t.c >= points.size())
                    continue;
                if (!wireframe)
                    triangle(points[t.a],
                             points[t.b],
                             points[t.c],
                             shade(t.color, points[t.a], points[t.b], points[t.c]));
            }
            if (wireframe)
                for (std::size_t i = 0; i < mesh.triangles.size(); ++i)
                {
                    const Triangle& t = mesh.triangles[i];
                    if (t.a >= points.size() || t.b >= points.size() || t.c >= points.size())
                        continue;
                    edge(points[t.a], points[t.b], t.color);
                    edge(points[t.b], points[t.c], t.color);
                    edge(points[t.c], points[t.a], t.color);
                }
            if (hollowVertices)
                for (std::size_t i = 0; i < points.size(); ++i)
                    marker(points[i], 0x00ffffff);
        }
    }  // namespace graphics
}  // namespace gaspardos