1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      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
     244
     245
     246
     247
     248
     249
     250
     251
     252
     253
     254
     255
     256
     257
     258
     259
     260
     261
     262
     263
     264
     265
     266
     267
     268
     269
     270
     271
     272
     273
     274
     275
     276
     277
     278
     279
     280
     281
     282
     283
     284
     285
     286
     287
     288
     289
     290
     291
     292
     293
     294
     295
     296
     297
     298
     299
     300
     301
     302
     303
     304
     305
     306
     307
     308
     309
     310
     311
     312
     313
     314
     315
     316
     317
     318
     319
     320
     321
     322
     323
     324
     325
     326
     327
     328
     329
     330
     331
     332
     333
     334
     335
     336
     337
     338
     339
     340
     341
     342
     343
     344
     345
     346
     347
     348
     349
     350
     351
     352
     353
     354
     355
     356
     357
     358
     359
     360
     361
     362
     363
     364
     365
     366
     367
     368
     369
     370
     371
     372
     373
     374
     375
     376
     377
     378
     379
     380
     381
     382
     383
     384
     385
     386
     387
     388
     389
     390
     391
     392
     393
     394
     395
     396
     397
     398
     399
     400
     401
     402
     403
     404
     405
     406
     407
     408
     409
     410
     411
     412
     413
     414
     415
     416
     417
     418
     419
     420
     421
     422
     423
     424
     425
     426
     427
     428
     429
     430
     431
     432
     433
     434
     435
     436
     437
     438
     439
     440
     441
     442
     443
     444
     445
     446
     447
     448
     449
     450
     451
     452
     453
     454
     455
     456
     457
     458
     459
     460
     461
     462
     463
     464
     465
     466
     467
     468
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <gdk-pixbuf/gdk-pixbuf.h>

/*
   Compile with

   g++ -std=c++11 -Wall `pkg-config --cflags --libs gdk-pixbuf-2.0` mandelbrot_1.cpp
*/


template<typename Real, typename Color>
struct Parameters
{
    Real                center_x;
    Real                center_y;
    Real                horizontal_diameter;

    // in pixels:
    unsigned int        width;
    unsigned int        height;

    // parameter for the mandelbrot function:
    unsigned int        maxiterations;
    Real                color_shift;
    Real                color_progression;
    std::list<Color>    palette;

    // derived values
    Real                resolution;
    Real                xmin;
    Real                xmax;
    Real                vertical_diameter;
    Real                ymin;
    Real                ymax;
};

// ----------------------------------------------------------------------------
void
usage(const char* cmdname)
{
    std::cerr << "Usage: " << cmdname << " (-RGB|-HSV) filename"
              << std::endl;
    exit(1);
}


// ----------------------------------------------------------------------------

struct RGBColor
{
    RGBColor()
        : red(0), green(0), blue(0)
    {
    }

    RGBColor(unsigned red, unsigned green, unsigned blue)
        : red(red/255.0), green(green/255.0), blue(blue/255.0)
    {
    }

    RGBColor(float red, float green, float blue)
        : red(red), green(green), blue(blue)
    {
    }

    RGBColor
    get_rgb() const 
    {
      return *this;
    }

    RGBColor interpolate(const RGBColor& other, float t)
    {
        return RGBColor((red   + (other.red   - red) * t),
                        (green + (other.green - green) * t),
                        (blue  + (other.blue  - blue) * t));
    }

    bool
    operator==(const RGBColor& other)
    {
        return std::fabs(red - other.red)     < DBL_EPSILON &&
               std::fabs(green - other.green) < DBL_EPSILON &&
               std::fabs(blue - other.blue)   < DBL_EPSILON;
    }

    bool
    operator!=(const RGBColor& other)
    {
        return !(*this == other);
    }

    float red;
    float green;
    float blue;
};

std::ostream &
operator<<(std::ostream& out, const RGBColor &color)
{
    return out << "(" << color.red << ", " << color.green <<
                  ", " << color.blue << ")";
}
// ----------------------------------------------------------------------------
/* based on the code by Nan C. Schaller at
   http://www.cs.rit.edu/~ncs/color/t_convert.html */

RGBColor
HSVtoRGB(float h, float s, float v)
{
    RGBColor result;
    if (s == 0) {
        // achromatic (grey)
        return RGBColor(v, v, v);
    }
    h /= 60;
    int i = std::floor(h);
    float f = h - i;
    float p = v * (1 - s);
    float q = v * (1 - s * f);
    float t = v * (1 - s * (1 - f));

    switch (i) {
        case 0:  return RGBColor(v, t, p);
        case 1:  return RGBColor(q, v, p);
        case 2:  return RGBColor(p, v, t);
        case 3:  return RGBColor(p, q, v);
        case 4:  return RGBColor(t, p, v);
        defaultreturn RGBColor(v, p, q);
    }
}
// ----------------------------------------------------------------------------

struct HSVColor
{
    HSVColor()
        : hue(0), saturation(0), value(0)
    {
    }

    HSVColor(float hue, float saturation, float value)
        : hue(hue), saturation(saturation), value(value)
    {
    }

    RGBColor
    get_rgb() const
    {
        return HSVtoRGB(hue, saturation, value);
    }

    HSVColor
    interpolate(const HSVColor& other, float t)
    {
        return HSVColor(other.hue<=hue
                        ? std::fmod(hue+(360+other.hue-hue)*t, 360)
                        : hue + (other.hue - hue) * t,
                        saturation + (other.saturation - saturation) * t,
                        value + (other.value-value)*t);
    }

    float hue;
    float saturation;
    float value;
};

std::ostream &
operator<<(std::ostream& out, const HSVColor& color)
{
    return out << "(" << color.hue << ", " << color.saturation <<
                  ", " << color.value << ")";
}


// ----------------------------------------------------------------------------

template<typename Real, typename Color>
class Colorizer
{
    public:
        using color_type = Color;

        Colorizer()
            : color_shift(0), color_progression(0), colors{Color()}
        {
        }

        template<typename Iterator>
        Colorizer(Real color_shift, Real color_progression,
                  Iterator it1, Iterator it2)
            : color_shift(color_shift), color_progression(color_progression),
              colors(it1, it2)
        {
            assert(colors.size() > 0);
        }

        Color
        operator()(unsigned int maxiterations, unsigned int iterations, Real t)
        {
            double value = std::log(iterations+t)/std::log(Real(maxiterations));
            double index = std::fmod(color_shift + value*color_progression,
                                     colors.size());
            unsigned int i    = std::floor(index); double remainder = index - i;
            unsigned int next = (i + 1) % colors.size();
            return colors[index].interpolate(colors[next], remainder);
        }

    private:
        Real color_shift;
        Real color_progression;
        std::vector<Color> colors;
};

// ----------------------------------------------------------------------------

/* Algorithm based on pseudo-code at
   https://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring
*/
template<typename Real, typename Colorizer>
typename Colorizer::color_type
mandelbrot(Real c_x, Real c_y, unsigned int maxiterations, Colorizer colorizer)
{
    using Color = typename Colorizer::color_type;

    constexpr Real bailout  = 2;
    constexpr Real bailout2 = bailout * bailout;

    Real x = 0;
    Real y = 0;

    for (unsigned int iteration=0; iteration<maxiterations; ++iteration) {
        Real x_square = x * x;
        Real y_square = y * y;
        Real distance2 = x_square + y_square;

        if (distance2 >= bailout2) {
            return colorizer(maxiterations, iteration, 0);
        }

        Real next_x = x_square - y_square + c_x;
        Real next_y = 2*x*y + c_y;

        x = next_x;
        y = next_y;
    }
    return Color(); // black
}

// ----------------------------------------------------------------------------

void
set_default_palette(std::list<RGBColor> &palette)
{
    palette = {
        RGBColor(),
        RGBColor(255u,255u,255u)
    };
}

void
set_default_palette(std::list<HSVColor> &palette)
{
    palette = {
        HSVColor(00.90.9),
    };
}

// ----------------------------------------------------------------------------

template<typename Options>
void
usage(const char* cmdname, const Options& options)
{
    std::cerr << "Usage: " << cmdname
              << " (-RGB|-HSV) {option} filename"
              << std::endl;
    std::cerr << "Supported options:" << std::endl;
    for (auto pair: options) {
        std::cerr << "   -" << pair.first << "    "
                  << pair.second.description << std::endl;
    }
    exit(1);
}

// ----------------------------------------------------------------------------

template <typename T>
bool
read_val(int& argc, char**& argv, char*& argp, void* param)
{
    T* value = (T*) param;
    if (argc == 0) {
        return false;
    }
    if (!argp || !*argp) {
        if (argc == 1) {
            return false;
        }
        --argc;
        ++argv;
        argp = *argv;
    }
    std::string         s(argp);
    std::istringstream  is(s);

    T tmpval;
    if (!(is >> tmpval)) {
        return false;
    }
    argp += is.tellg();
    *value = tmpval;
    return true;
}

// ----------------------------------------------------------------------------

template<typename Real, typename Color>
void
process_options(const char* cmdname, int &argc, char** &argv,
                Parameters<Real, Color> &p)
{

    struct Option {
        const char* description;
        void*       param;
        bool        (*input)(int& argc, char**& argv, char*& argp, void* param);
    };

    std::map<char, Option> options = {
    {'x', {"center (real part)", &p.center_x, read_val<Real>}},
    {'y', {"center (imaginary part)", &p.center_y, read_val<Real>}},
    {'d', {"horizontal diameter", &p.horizontal_diameter, read_val<Real>}},
    {'w', {"width in pixels", &p.width, read_val<unsigned int>}},
    {'h', {"height in pixels", &p.height, read_val<unsigned int>}},
    {'m', {"maximal iterations", &p.maxiterations, read_val<unsigned int>}},
    {'s', {"color shift", &p.color_shift, read_val<Real>}},
    {'p', {"color progression", &p.color_progression, read_val<Real>}},
    };

    while (argc > 0)
    {
        if (strcmp(*argv, "--") == 0) {
            /* explicit end of options */
            --argc;
            ++argv;
            break;
        }
        if (argv[0][0] != '-') {
            /* not an option */
            break;
        }
        char* argp = *argv + 1;
        char optch = *argp++;
        auto optit = options.find(optch);
        if (optit == options.end()) {
            std::cerr << cmdname << ": no such option: '-"
                      << optch << "'" << std::endl;
            usage(cmdname, options);
        }

        bool ok = optit->second.input(argc, argv, argp, optit->second.param);
        if (!ok) {
            std::cerr << cmdname << ": invalid option value for '-"
                      << optch << "'" << std::endl;
            usage(cmdname, options);
        }

        ++argv; --argc;
    }
    /* compute derived parameters */
    p.resolution        = p.width / p.horizontal_diameter;
    p.xmin              = p.center_x - p.horizontal_diameter / 2;
    p.xmax              = p.center_x + p.horizontal_diameter / 2;
    p.vertical_diameter = p.height / p.resolution;
    p.ymin              = p.center_y - p.vertical_diameter / 2;
    p.ymax              = p.center_y + p.vertical_diameter / 2;
}


// ----------------------------------------------------------------------------

template<typename Real, typename Color>
bool
do_main(const char* cmdname, int argc, char** argv)
{
    Parameters<Real, Color> p = {
        .center_x            = -0.7,
        .center_y            = 0,
        .horizontal_diameter = 3.0769,
        .width               = 512,
        .height              = 480,
        .maxiterations       = 1000,
        .color_shift         = 0,
        .color_progression   = 3
    };
    set_default_palette(p.palette);

    // allow command line options to overwrite default values
    process_options<Real>(cmdname, argc, argv, p);

    if (argc != 1) {
        usage(cmdname);
    }
    std::string filename(*argv++); --argc;

    std::cout << "file name =   " << filename << std::endl;

    GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8,
                                       p.width, p.height);

    int n_channels     = gdk_pixbuf_get_n_channels(pixbuf);
    int rowstride      = gdk_pixbuf_get_rowstride(pixbuf);
    guchar* pixels     = gdk_pixbuf_get_pixels(pixbuf);

    if (!pixels) return false;

    Colorizer<Real, Color> colorizer(p.color_shift, p.color_progression,
                                     p.palette.begin(), p.palette.end());

    for (unsigned int i = 0; i < p.height; ++i) {
        for (unsigned int j = 0; j < p.width; ++j) {
            guchar* pp = pixels + i * rowstride + j * n_channels;
            Real x     = p.xmin + j/p.resolution;
            Real y     = p.ymax - i/p.resolution;
            RGBColor c = mandelbrot(x, y, p.maxiterations, colorizer).get_rgb();

            pp[0] = c.red   * 255;
            pp[1] = c.green * 255;
            pp[2] = c.blue  * 255;
        }
    }

    return gdk_pixbuf_save(pixbuf, filename.c_str(), "jpeg",
                           nullptr"quality""100"nullptr) != FALSE;
}

#ifndef REAL
#define REAL double
#endif

int
main(int argc, char** argv)
{
    const char* cmdname = *argv++; --argc;

    if (argc == 0) {
        usage(cmdname);
    }

    const char* color_space = *argv++; --argc;

    if (strcmp(color_space, "-RGB") == 0) {
        do_main<REAL, RGBColor>(cmdname, argc, argv);
    } else if (strcmp(color_space, "-HSV") == 0) {
        do_main<REAL, HSVColor>(cmdname, argc, argv);
    } else {
        usage(cmdname);
    }
}