From 31e778c913c6bd8478f32c3e50ac5b6d90928526 Mon Sep 17 00:00:00 2001 From: Erwin Coumans Date: Wed, 9 Oct 2019 22:26:20 -0400 Subject: [PATCH] avoid crashes in TinyRenderer --- examples/TinyRenderer/TinyRenderer.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/examples/TinyRenderer/TinyRenderer.cpp b/examples/TinyRenderer/TinyRenderer.cpp index f98362d96..2880eb254 100644 --- a/examples/TinyRenderer/TinyRenderer.cpp +++ b/examples/TinyRenderer/TinyRenderer.cpp @@ -156,8 +156,11 @@ struct Shader : public IShader float index_x = b3Max(float(0.0), b3Min(float(m_width - 1), p[0])); float index_y = b3Max(float(0.0), b3Min(float(m_height - 1), p[1])); int idx = int(index_x) + int(index_y) * m_width; // index in the shadowbuffer array - float shadow = 0.8 + 0.2 * (m_shadowBuffer->at(idx) < -depth + 0.05); // magic coeff to avoid z-fighting - + float shadow = 1.0; + if (m_shadowBuffer && idx >=0 && idx size()) + { + shadow = 0.8 + 0.2 * (m_shadowBuffer->at(idx) < -depth + 0.05); // magic coeff to avoid z-fighting + } Vec3f bn = (varying_nrm * bar).normalize(); Vec2f uv = varying_uv * bar; @@ -174,7 +177,13 @@ struct Shader : public IShader for (int i = 0; i < 3; ++i) { - color[i] = b3Min(int(m_ambient_coefficient * color[i] + shadow * (m_diffuse_coefficient * diffuse + m_specular_coefficient * specular) * color[i] * m_light_color[i]), 255); + int orgColor = 0; + float floatColor = (m_ambient_coefficient * color[i] + shadow * (m_diffuse_coefficient * diffuse + m_specular_coefficient * specular) * color[i] * m_light_color[i]); + if (floatColor==floatColor) + { + orgColor=int(floatColor); + } + color[i] = b3Min(orgColor, 255); } return false;