FracGen.cpp 10 KB
Newer Older
Jehferson Mello's avatar
Jehferson Mello committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include "FracGen.hpp"

#include <iostream>
#include <cfloat>
#include <functional>
#include <atomic>
#include <vector>

#include <tbb/parallel_for.h>
#include <tbb/blocked_range2d.h>

//static Vec3f boxMaxes;
//static Vec3f boxMins;


using  estimatorFunction = std::function<float(Vec3f)>;


/******************************************************************************
 *
 * Tweakable parameters
 *
 ******************************************************************************/

25 26
static constexpr const size_t maxRaySteps      = 7500;
static constexpr const float  collisionMinDist = 0.00055f;
27 28
static constexpr const float  cameraX          =  0.0f;
static constexpr const float  cameraY          =  0.0f;
29
static constexpr const float  cameraZ          = -3.8f;
30 31 32
static constexpr const float  targetX          =  0.0f;
static constexpr const float  targetY          =  0.0f;
static constexpr const float  targetZ          =  0.0f;
Jehferson Mello's avatar
Jehferson Mello committed
33 34 35

// coulouring parameters

36 37 38
static constexpr const float hueFactor   = -10.0f;
static constexpr const int   hueOffset   = 195;
static constexpr const float valueFactor = 62;
Jehferson Mello's avatar
Jehferson Mello committed
39 40
static constexpr const float valueRange  = 1.0f;
static constexpr const float valueClamp  = 0.9f;
41
static constexpr const float satValue    = 0.7f;
Jehferson Mello's avatar
Jehferson Mello committed
42 43 44 45
static constexpr const float bgValue     = 0.05f;
static constexpr const float bgAlpha     = 1.0f;

// Mandelbox constants
46 47 48 49
static constexpr const float  fixedRadiusSq = 2.2f;
static constexpr const float  minRadiusSq   = 0.8f;
static constexpr const float  foldingLimit  = 1.45;
static constexpr const float  boxScale      = -3.5f;
Jehferson Mello's avatar
Jehferson Mello committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
static constexpr const size_t boxIterations = 30;


/******************************************************************************
 *
 * Distance estimator functions and helpers
 *
 ******************************************************************************/



void sphereFold(Vec3f& z, float& dz)
{
    float r2 = z.sqMod();
    if ( r2 < minRadiusSq)
    {
        // linear inner scaling
        float temp = (fixedRadiusSq/minRadiusSq);
        z *= temp;
        dz *= temp;
    }
    else if(r2<fixedRadiusSq)
    {
        // this is the actual sphere inversion
        float temp =(fixedRadiusSq/r2);
        z *= temp;
        dz*= temp;
    }
}

void boxFold(Vec3f& z)
{
    z = z.clamp(-foldingLimit, foldingLimit)* 2.0f - z;
}

float boxDist(const Vec3f& p)
{
    /**
     * Distance estimator for a mandelbox
     *
     * Distance estimator adapted from
     * https://http://blog.hvidtfeldts.net/index.php/2011/11/distance-estimated-3d-fractals-vi-the-mandelbox/
     */
    const Vec3f& offset = p;
    float dr = boxScale;
    Vec3f z{p};
    for (size_t n = 0; n < boxIterations; n++)
    {
        boxFold(z);       // Reflect
        sphereFold(z,dr);    // Sphere Inversion

        z = z * boxScale + offset;  // Scale & Translate
        dr = dr * std::abs(boxScale) + 1.0f;


    }
    float r = z.mod();
    return r/std::abs(dr);
}


float bulbDist(const Vec3f& p)
{

    /**
     * Distance estimator for a mandelbulb
     *
     * Distance estimator adapted from
     * https://www.iquilezles.org/www/articles/mandelbulb/mandelbulb.htm
     * https://www.shadertoy.com/view/ltfSWn
     */

    Vec3f w = p;
    float m = w.sqMod();

    //vec4 trap = vec4(abs(w),m);
    float dz = 3.0f;


    for( int i=0; i<4; i++ )
    {
#if 1
        float m2 = m*m;
        float m4 = m2*m2;
        dz = 8.0f*sqrt(m4*m2*m)*dz + 1.0f;

        float x = w.X(); float x2 = x*x; float x4 = x2*x2;
        float y = w.Y(); float y2 = y*y; float y4 = y2*y2;
        float z = w.Z(); float z2 = z*z; float z4 = z2*z2;

        float k3 = x2 + z2;
        float k2 = 1/sqrt( k3*k3*k3*k3*k3*k3*k3 );
        float k1 = x4 + y4 + z4 - 6.0f*y2*z2 - 6.0f*x2*y2 + 2.0f*z2*x2;
        float k4 = x2 - y2 + z2;

        w.setX(p.X() +  64.0f*x*y*z*(x2-z2)*k4*(x4-6.0f*x2*z2+z4)*k1*k2);
        w.setY(p.Y() + -16.0f*y2*k3*k4*k4 + k1*k1);
        w.setZ(p.Z() +  -8.0f*y*k4*(x4*x4 - 28.0f*x4*x2*z2 + 70.0f*x4*z4 - 28.0f*x2*z2*z4 + z4*z4)*k1*k2);
#else
        dz = 8.0*pow(sqrt(m),7.0)*dz + 1.0;
        //dz = 8.0*pow(m,3.5)*dz + 1.0;

        float r = w.mod();
        float b = 8.0*acos( w.Y()/r);
        float a = 8.0*atan2( w.X(), w.Z() );
        w = p + Vec3f( sin(b)*sin(a), cos(b), sin(b)*cos(a) ) * pow(r,8.0);
#endif

       // trap = min( trap, vec4(abs(w),m) );

        m = w.sqMod();
        if( m > 256.0f )
            break;
    }

    return 0.25f*log(m)*sqrt(m)/dz;
}

float sphereDist(Vec3f p)
{
    float radius = 2.f;
    return p.mod() - radius;
}

/******************************************************************************
 *
 * Coulouring functions and helpers
 *
 ******************************************************************************/

RGBA HSVtoRGB(int H, float S, float V)
{

    /**
     * adapted from
     * https://gist.github.com/kuathadianto/200148f53616cbd226d993b400214a7f
     */

    RGBA output;
    float C = S * V;
    float X = C * (1 - std::abs(std::fmod(H / 60.0, 2) - 1));
    float m = V - C;
    float Rs, Gs, Bs;

    if(H >= 0 && H < 60)
    {
        Rs = C;
        Gs = X;
        Bs = 0;
    }
    else if(H >= 60 && H < 120)
    {
        Rs = X;
        Gs = C;
        Bs = 0;
    }
    else if(H >= 120 && H < 180)
    {
        Rs = 0;
        Gs = C;
        Bs = X;
    }
    else if(H >= 180 && H < 240)
    {
        Rs = 0;
        Gs = X;
        Bs = C;
    }
    else if(H >= 240 && H < 300)
    {
        Rs = X;
        Gs = 0;
        Bs = C;
    }
    else {
        Rs = C;
        Gs = 0;
        Bs = X;
    }

    output.setR(Rs + m);
    output.setG(Gs + m);
    output.setB(Bs + m);
    output.setA( 1.0f );

    return output;
}

RGBA getColour(const Vec4f& steps)
{
    RGBA colour;

    Vec3f position(steps.X(),steps.Y(),steps.Z());

244
    static const RGBA background(bgValue,bgValue,bgValue,bgAlpha);
Jehferson Mello's avatar
Jehferson Mello committed
245

246
    if(steps.W() >= maxRaySteps)
Jehferson Mello's avatar
Jehferson Mello committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    {
        return background;
    }

//        This is a good place to float check your bounds if you need to

//        boxMins.setX(std::min(boxMins.X(),position.X()));
//        boxMins.setY(std::min(boxMins.Y(),position.Y()));
//        boxMins.setZ(std::min(boxMins.Z(),position.Z()));

//        boxMaxes.setX(std::max(boxMaxes.X(),position.X()));
//        boxMaxes.setY(std::max(boxMaxes.Y(),position.Y()));
//        boxMaxes.setZ(std::max(boxMaxes.Z(),position.Z()));

    float saturation = satValue;
262 263 264
    float hueVal = (position.Z() * hueFactor) + hueOffset;
    int hue = static_cast<int>( trunc(fmod(hueVal, 360.0f) ) );
    hue = hue < 0 ? 360 + hue: hue;
Jehferson Mello's avatar
Jehferson Mello committed
265 266 267 268 269
    float value = valueRange*(1.0f - std::min(steps.W()*valueFactor/maxRaySteps, valueClamp));

    colour = HSVtoRGB(hue, saturation, value);

//    Simplest colouring, based only on steps (roughly distance from camera)
270
    //colour = RGBA(value,value,value,1.0f);
Jehferson Mello's avatar
Jehferson Mello committed
271 272 273 274 275 276 277 278 279 280

    return colour;
}

/******************************************************************************
 *
 * Ray marching functions and helpers
 *
 ******************************************************************************/

281
Vec4f trace(const Camera<float>& cam,size_t x, size_t y, const estimatorFunction& f)
Jehferson Mello's avatar
Jehferson Mello committed
282 283 284 285 286 287 288 289 290
{
    /**
     * This function taken from
     * http://blog.hvidtfeldts.net/index.php/2011/06/distance-estimated-3d-fractals-part-i/
     */

    float totalDistance = 0.0f;
    unsigned int steps;

291
    Vec3f pixelPosition = cam.ScreenTopLeft() + (cam.ScreenRight() * static_cast<float>(x)) + (cam.ScreenUp() * static_cast<float>(y));
Jehferson Mello's avatar
Jehferson Mello committed
292

293
    Vec3f rayDir = pixelPosition - cam.Pos();
Jehferson Mello's avatar
Jehferson Mello committed
294 295 296 297 298
    rayDir.normalise();

    Vec3f p;
    for (steps=0; steps < maxRaySteps; steps++)
    {
299
        p = cam.Pos() + (rayDir * totalDistance);
Jehferson Mello's avatar
Jehferson Mello committed
300 301 302 303 304 305 306 307 308
        float distance = f(p);
        totalDistance += distance;
        if (distance < collisionMinDist) break;
    }
    //return both the steps and the actual position in space for colouring purposes
    return Vec4f{p,static_cast<float>(steps)};
}

void traceRegion(colourVec& data,
309
                 const Camera<float>& cam,
Jehferson Mello's avatar
Jehferson Mello committed
310 311 312 313 314 315 316
                 const estimatorFunction& f,
                 const tbb::blocked_range2d<size_t,size_t>& range)
{
    for(size_t h = range.rows().begin(); h < range.rows().end(); h++)
    {
        for(size_t w = range.cols().begin(); w < range.cols().end(); w++ )
        {
317
            data[(h*cam.ScreenWidth())+w] = getColour(trace(cam, w, h, f));
Jehferson Mello's avatar
Jehferson Mello committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        }
    }
}

/******************************************************************************
 *
 * Thread spawning section
 *
 ******************************************************************************/

bool FracGen::Generate(int width, int height)
{

    bool finishedGeneration = false;
    int heightStep = bench ? height : 10;

    estimatorFunction bulb(bulbDist);
    estimatorFunction box(boxDist);
    estimatorFunction sphere(sphereDist);

338 339
    auto tbbTrace = [this, f = box](const tbb::blocked_range2d<size_t,size_t>& range)
            {traceRegion(*(this->outBuffer), *(this->cam), f, range); };
Jehferson Mello's avatar
Jehferson Mello committed
340 341 342 343


    // Minor optimization in TBB: Since we can define the range here, we don't need to check bounds in
    // traceRegion. This is very similar to how SYCL and OpenCL do things
344
    tbb::blocked_range2d<size_t,size_t> range(lastHeight, std::min(lastHeight+heightStep, static_cast<size_t>(height)), 0, width);
Jehferson Mello's avatar
Jehferson Mello committed
345 346
    tbb::parallel_for(range, tbbTrace);

347
    lastHeight+= heightStep;
Jehferson Mello's avatar
Jehferson Mello committed
348 349 350 351 352 353
    /*
     * TBB doesn't seem to like the way of doing things where I know how
     * many tasks there are and am collecting the return from them.
     * At least not in the initial tutorials and beginner documentation
     */

354
    if (lastHeight >=static_cast<size_t>(height) )
Jehferson Mello's avatar
Jehferson Mello committed
355
    {
356
        lastHeight = 0;
Jehferson Mello's avatar
Jehferson Mello committed
357 358 359 360 361 362 363 364
        finishedGeneration = true;
    }

    return finishedGeneration;
}

FracGen::FracGen(bool benching, size_t width, size_t height)
    : bench{benching}
365
    , lastHeight{0}
Jehferson Mello's avatar
Jehferson Mello committed
366 367
{
    outBuffer = std::make_shared< colourVec >(width*height);
368
    cam = std::make_shared<Camera<float> >(Vec3f{cameraX, cameraY, cameraZ},Vec3f{targetX,targetY,targetZ}, width, height, 0.1f, 45);
Jehferson Mello's avatar
Jehferson Mello committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382

    static bool once = false;
    if(!bench || !once)
    {
      std::cout << "Running on TBB "<< TBB_VERSION_MAJOR <<"."<< TBB_VERSION_MINOR << std::endl;
      once = true;
    }
}

FracGen::~FracGen()
{}