noise-simplex.c 8.98 KB
Newer Older
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
/* This file is an image processing operation for GEGL
 *
 * GEGL is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * GEGL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with GEGL; if not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright 2014 Dimitris Papavasiliou <dpapavas@google.com>
 */

/* This plug-in generates noise textures originally presented by Ken
 * Perlin during a SIGGRAPH 2002 course and further explained in the
 * paper "Simplex noise demystified" by Stefan Gustavson.
 *
 * Comments and improvements for this code are welcome.
 */

#include "config.h"
#include <glib/gi18n-lib.h>

29
#ifdef GEGL_PROPERTIES
30

31 32 33 34 35 36 37 38 39 40
property_double (scale, _("Scale"), 1.0)
    description (_("The scale of the noise function"))
    value_range (0.0, 20.0)

property_int    (iterations, _("Iterations"), 1)
    description (_("The number of noise octaves."))
    value_range (1, 20)

property_seed   (seed, _("Random seed"), rand)
    description (_("The random seed for the noise function"))
41 42 43

#else

44 45
#define GEGL_OP_POINT_RENDER
#define GEGL_OP_C_FILE       "noise-simplex.c"
46

47
#include "gegl-op.h"
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
#include <gegl-buffer-cl-iterator.h>
#include <gegl-debug.h>
#include <math.h>

#include "opencl/noise-simplex.cl.h"

typedef struct
{
  guint seed;
} Context;

static GeglClRunData *cl_data = NULL;

static inline gdouble
dot_2(gdouble *p,
      gdouble *q)
{
  return p[0] * q[0] + p[1] * q[1];
}

static inline void
philox (guint    s,
        guint    t,
        guint    k,
        gdouble *h)
{
  guint64 p;
  gint    i;

  /* For details regarding this hash function consult:

     Salmon, J.K.; Moraes, M.A.; Dror, R.O.; Shaw, D.E., "Parallel
     random numbers: As easy as 1, 2, 3," High Performance Computing,
     Networking, Storage and Analysis (SC), 2011 International
     Conference for , vol., no., pp.1,12, 12-18 Nov. 2011 */\

  for (i = 0 ; i < 3 ; i += 1)
    {
      p = s * (guint64)0xcd9e8d57;

      s = ((guint)(p >> 32)) ^ t ^ k;
      t = (guint)p;

      k += 0x9e3779b9;
    }

  h[0] = s / 2147483648.0 - 1.0;
  h[1] = t / 2147483648.0 - 1.0;
}

static gdouble
noise2 (gdouble  x,
        gdouble  y,
        Context *context)
{
  gdouble s, t, n;
  gdouble g[3][2], u[3][2];
  gint i, j, di, k;

  /* Skew the input point and find the lowest corner of the containing
     simplex. */

  s = (x + y) * (sqrt(3) - 1) / 2;
  i = (gint)floor(x + s);
  j = (gint)floor(y + s);

  /* Calculate the (unskewed) distance between the input point and all
     simplex corners. */

  s = (i + j) * (3 - sqrt(3)) / 6;
  u[0][0] = x - i + s;
  u[0][1] = y - j + s;

  di = (u[0][0] >= u[0][1]);

  u[1][0] = u[0][0] - di + (3 - sqrt(3)) / 6;
  u[1][1] = u[0][1] - !di + (3 - sqrt(3)) / 6;

  u[2][0] = u[0][0] - 1 + (3 - sqrt(3)) / 3;
  u[2][1] = u[0][1] - 1 + (3 - sqrt(3)) / 3;

  /* Calculate gradients for each corner vertex. */

  philox(i, j, context->seed, g[0]);
  philox(i + di, j + !di, context->seed, g[1]);
  philox(i + 1, j + 1, context->seed, g[2]);

  /* Finally accumulate the contribution of each vertex to the current
   * pixel. */

  for (k = 0, n = 0 ; k < 3 ; k += 1)
    {
      t = 0.5 - dot_2(u[k], u[k]);

      if (t > 0)
        {
          t *= t;
          n += t * t * dot_2(g[k], u[k]);
        }
    }

  /* Normalize result to lie in [-1, 1]. */

  return 70 * n;
}

static void
prepare (GeglOperation *operation)
{
  gegl_operation_set_format (operation, "output", babl_format ("Y float"));
}

static GeglRectangle
get_bounding_box (GeglOperation *operation)
{
  return gegl_rectangle_infinite_plane ();
}

static gboolean
cl_process (GeglOperation       *operation,
            cl_mem               out_tex,
            const GeglRectangle *roi)
{
171
  GeglProperties   *o      = GEGL_PROPERTIES (operation);
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
  const size_t  gbl_size[] = {roi->width, roi->height};
  size_t        work_group_size;
  cl_uint       cl_iterations   = o->iterations;
  cl_int        cl_err          = 0;
  cl_int        cl_x_0          = roi->x;
  cl_int        cl_y_0          = roi->y;
  cl_float      cl_scale        = o->scale / 50.0;
  cl_uint       cl_seed         = o->seed;

  if (!cl_data)
    {
      const char *kernel_name[] = {"kernel_noise", NULL};
      cl_data = gegl_cl_compile_and_build (noise_simplex_cl_source,
                                           kernel_name);

      if (!cl_data)
        return TRUE;
    }

  cl_err = gegl_cl_set_kernel_args (cl_data->kernel[0],
                                    sizeof(cl_mem), &out_tex,
                                    sizeof(cl_int), &cl_x_0,
                                    sizeof(cl_int), &cl_y_0,
                                    sizeof(cl_uint), &cl_iterations,
                                    sizeof(cl_float), &cl_scale,
                                    sizeof(cl_uint), &cl_seed,
                                    NULL);
  CL_CHECK;

  cl_err = gegl_clGetKernelWorkGroupInfo (cl_data->kernel[0],
                                          gegl_cl_get_device (),
                                          CL_KERNEL_WORK_GROUP_SIZE,
                                          sizeof (size_t), &work_group_size,
                                          NULL);
  CL_CHECK;

  cl_err = gegl_clEnqueueNDRangeKernel (gegl_cl_get_command_queue (),
                                        cl_data->kernel[0], 2,
                                        NULL, gbl_size, NULL,
                                        0, NULL, NULL);
  CL_CHECK;

  cl_err = gegl_clFinish (gegl_cl_get_command_queue ());
  CL_CHECK;

  return FALSE;

error:
  return TRUE;
}

static gboolean
c_process (GeglOperation       *operation,
           void                *out_buf,
           glong                n_pixels,
           const GeglRectangle *roi,
           gint                 level)
{
230
  GeglProperties *o = GEGL_PROPERTIES (operation);
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
  Context     context;
  gfloat     *pixel;
  gint        s, t;

  context.seed = o->seed;

  for (t = 0, pixel = out_buf ; t < roi->height ; t += 1)
    {
      for (s = 0 ; s < roi->width ; s += 1, pixel += 1)
        {
          gint    i;
          gdouble c, d;

          /* Pile up noise octaves onto the output value. */

          for (i = 0, c = 1, d = o->scale / 50.0, *pixel = 0;
               i < o->iterations;
               c *= 2, d *= 2, i += 1)
            {
              *pixel += noise2 ((double) (s + roi->x) * d,
                                (double) (t + roi->y) * d,
                                &context) / c;
            }
        }
    }

  return TRUE;
}

static gboolean
process (GeglOperation       *operation,
         GeglBuffer          *out_buf,
         const GeglRectangle *roi,
         gint                 level)
{
  GeglBufferIterator *iter;
  const Babl         *out_format = gegl_operation_get_format (operation,
                                                              "output");

  g_assert(babl_format_get_n_components (out_format) == 1 &&
           babl_format_get_type (out_format, 0) == babl_type ("float"));

  if (gegl_operation_use_opencl (operation))
    {
      GeglBufferClIterator *cl_iter;
      gboolean              err;

      GEGL_NOTE (GEGL_DEBUG_OPENCL, "GEGL_OPERATION_POINT_RENDER: %s", GEGL_OPERATION_GET_CLASS (operation)->name);

      cl_iter = gegl_buffer_cl_iterator_new (out_buf, roi, out_format, GEGL_CL_BUFFER_WRITE);

      while (gegl_buffer_cl_iterator_next (cl_iter, &err) && !err)
        {
          err = cl_process (operation, cl_iter->tex[0], cl_iter->roi);

          if (err)
            {
              gegl_buffer_cl_iterator_stop (cl_iter);
              break;
            }
        }

      if (err)
        GEGL_NOTE (GEGL_DEBUG_OPENCL, "Error: %s", GEGL_OPERATION_GET_CLASS (operation)->name);
      else
        return TRUE;
    }

  iter = gegl_buffer_iterator_new (out_buf, roi, level, out_format,
                                   GEGL_BUFFER_WRITE, GEGL_ABYSS_NONE);

  while (gegl_buffer_iterator_next (iter))
    c_process (operation, iter->data[0], iter->length, &iter->roi[0], level);

  return  TRUE;
}

static void
309
gegl_op_class_init (GeglOpClass *klass)
310 311 312 313 314 315 316 317 318 319 320 321 322
{
  GeglOperationClass       *operation_class;
  GeglOperationSourceClass *source_class;

  operation_class = GEGL_OPERATION_CLASS (klass);
  source_class = GEGL_OPERATION_SOURCE_CLASS (klass);

  source_class->process = process;
  operation_class->get_bounding_box = get_bounding_box;
  operation_class->prepare = prepare;
  operation_class->opencl_support = TRUE;

  gegl_operation_class_set_keys (operation_class,
323 324 325
    "name",               "gegl:simplex-noise",
    "categories",         "render",
    "position-dependent", "true",
326 327 328 329 330
    "description", _("Generates a solid noise texture."),
    NULL);
}

#endif