ddswrite.c 65.1 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * DDS GIMP plugin
 *
 * Copyright (C) 2004-2012 Shawn Kirst <skirst@gmail.com>,
 * with parts (C) 2003 Arne Reuter <homepage@arnereuter.de> where specified.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 51 Franklin Street, Fifth Floor
 * Boston, MA 02110-1301, USA.
 */
22

Jehan's avatar
Jehan committed
23 24
#include "config.h"

25 26 27 28 29 30 31 32 33 34 35
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <gtk/gtk.h>
#include <glib/gstdio.h>

#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>

Jehan's avatar
Jehan committed
36 37
#include <libgimp/stdplugins-intl.h>

38 39 40 41 42 43 44 45
#include "ddsplugin.h"
#include "dds.h"
#include "dxt.h"
#include "mipmap.h"
#include "endian.h"
#include "imath.h"
#include "color.h"

46 47 48 49 50 51 52 53
static gint save_dialog          (gint32     image_id,
                                  gint32     drawable);
static void save_dialog_response (GtkWidget *widget,
                                  gint       response_id,
                                  gpointer   data);
static int  write_image          (FILE      *fp,
                                  gint32     image_id,
                                  gint32     drawable_id);
54 55 56 57 58

static int runme = 0;

enum
{
59 60 61
  COMBO_VALUE,
  COMBO_STRING,
  COMBO_SENSITIVE
62 63 64 65
};

static const char *cubemap_face_names[4][6] =
{
66
    {
67 68 69
      "positive x", "negative x",
      "positive y", "negative y",
      "positive z", "negative z"
70 71
    },
    {
72 73 74
      "pos x", "neg x",
      "pos y", "neg y",
      "pos z", "neg z",
75 76
    },
    {
77 78 79
      "+x", "-x",
      "+y", "-y",
      "+z", "-z"
80 81
    },
    {
82 83 84
      "right", "left",
      "top", "bottom",
      "back", "front"
85
    }
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
};

static gint cubemap_faces[6];
static gint is_cubemap = 0;
static gint is_volume = 0;
static gint is_array = 0;
static gint is_mipmap_chain_valid = 0;

static GtkWidget *compress_opt;
static GtkWidget *format_opt;
static GtkWidget *mipmap_opt;
static GtkWidget *mipmap_filter_opt;
static GtkWidget *mipmap_wrap_opt;
static GtkWidget *srgb_chk;
static GtkWidget *gamma_chk;
static GtkWidget *gamma_spin;
static GtkWidget *pm_chk;
static GtkWidget *alpha_coverage_chk;
static GtkWidget *alpha_test_threshold_spin;

typedef struct string_value_s
{
108 109
  int value;
  char *string;
110 111 112 113
} string_value_t;

static string_value_t compression_strings[] =
{
114 115 116 117 118 119 120 121 122 123 124 125
    {DDS_COMPRESS_NONE,   "None"},
    {DDS_COMPRESS_BC1,    "BC1 / DXT1"},
    {DDS_COMPRESS_BC2,    "BC2 / DXT3"},
    {DDS_COMPRESS_BC3,    "BC3 / DXT5"},
    {DDS_COMPRESS_BC3N,   "BC3nm / DXT5nm"},
    {DDS_COMPRESS_BC4,    "BC4 / ATI1 (3Dc+)"},
    {DDS_COMPRESS_BC5,    "BC5 / ATI2 (3Dc)"},
    {DDS_COMPRESS_RXGB,   "RXGB (DXT5)"},
    {DDS_COMPRESS_AEXP,   "Alpha Exponent (DXT5)"},
    {DDS_COMPRESS_YCOCG,  "YCoCg (DXT5)"},
    {DDS_COMPRESS_YCOCGS, "YCoCg scaled (DXT5)"},
    {-1, 0}
126 127 128 129
};

static string_value_t format_strings[] =
{
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    {DDS_FORMAT_DEFAULT, "Default"},
    {DDS_FORMAT_RGB8,    "RGB8"},
    {DDS_FORMAT_RGBA8,   "RGBA8"},
    {DDS_FORMAT_BGR8,    "BGR8"},
    {DDS_FORMAT_ABGR8,   "ABGR8"},
    {DDS_FORMAT_R5G6B5,  "R5G6B5"},
    {DDS_FORMAT_RGBA4,   "RGBA4"},
    {DDS_FORMAT_RGB5A1,  "RGB5A1"},
    {DDS_FORMAT_RGB10A2, "RGB10A2"},
    {DDS_FORMAT_R3G3B2,  "R3G3B2"},
    {DDS_FORMAT_A8,      "A8"},
    {DDS_FORMAT_L8,      "L8"},
    {DDS_FORMAT_L8A8,    "L8A8"},
    {DDS_FORMAT_AEXP,    "AExp"},
    {DDS_FORMAT_YCOCG,   "YCoCg"},
    {-1, 0}
146 147 148 149
};

static string_value_t mipmap_strings[] =
{
150 151 152 153
    {DDS_MIPMAP_NONE,     "No mipmaps"},
    {DDS_MIPMAP_GENERATE, "Generate mipmaps"},
    {DDS_MIPMAP_EXISTING, "Use existing mipmaps"},
    {-1, 0}
154 155 156 157
};

static string_value_t mipmap_filter_strings[] =
{
158 159 160 161 162 163 164 165 166 167
    {DDS_MIPMAP_FILTER_DEFAULT,   "Default"},
    {DDS_MIPMAP_FILTER_NEAREST,   "Nearest"},
    {DDS_MIPMAP_FILTER_BOX,       "Box"},
    {DDS_MIPMAP_FILTER_TRIANGLE,  "Triangle"},
    {DDS_MIPMAP_FILTER_QUADRATIC, "Quadratic"},
    {DDS_MIPMAP_FILTER_BSPLINE,   "B-Spline"},
    {DDS_MIPMAP_FILTER_MITCHELL,  "Mitchell"},
    {DDS_MIPMAP_FILTER_LANCZOS,   "Lanczos"},
    {DDS_MIPMAP_FILTER_KAISER,    "Kaiser"},
    {-1, 0}
168 169 170 171
};

static string_value_t mipmap_wrap_strings[] =
{
172 173 174 175 176
    {DDS_MIPMAP_WRAP_DEFAULT, "Default"},
    {DDS_MIPMAP_WRAP_MIRROR,  "Mirror"},
    {DDS_MIPMAP_WRAP_REPEAT,  "Repeat"},
    {DDS_MIPMAP_WRAP_CLAMP,   "Clamp"},
    {-1, 0}
177 178 179 180
};

static string_value_t save_type_strings[] =
{
181 182 183 184 185
    {DDS_SAVE_SELECTED_LAYER, "Image / Selected layer"},
    {DDS_SAVE_CUBEMAP,        "As cube map"},
    {DDS_SAVE_VOLUMEMAP,      "As volume map"},
    {DDS_SAVE_ARRAY,          "As texture array"},
    {-1, 0}
186 187 188 189
};

static struct
{
190 191 192 193 194 195 196 197
  int          format;
  DXGI_FORMAT  dxgi_format;
  int          bpp;
  int          alpha;
  unsigned int rmask;
  unsigned int gmask;
  unsigned int bmask;
  unsigned int amask;
198 199
} format_info[] =
{
200 201 202 203 204 205 206 207 208 209 210 211 212 213
    {DDS_FORMAT_RGB8,    DXGI_FORMAT_UNKNOWN,           3, 0, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000},
    {DDS_FORMAT_RGBA8,   DXGI_FORMAT_B8G8R8A8_UNORM,    4, 1, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000},
    {DDS_FORMAT_BGR8,    DXGI_FORMAT_UNKNOWN,           3, 0, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000},
    {DDS_FORMAT_ABGR8,   DXGI_FORMAT_R8G8B8A8_UNORM,    4, 1, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000},
    {DDS_FORMAT_R5G6B5,  DXGI_FORMAT_B5G6R5_UNORM,      2, 0, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000},
    {DDS_FORMAT_RGBA4,   DXGI_FORMAT_B4G4R4A4_UNORM,    2, 1, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000},
    {DDS_FORMAT_RGB5A1,  DXGI_FORMAT_B5G5R5A1_UNORM,    2, 1, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000},
    {DDS_FORMAT_RGB10A2, DXGI_FORMAT_R10G10B10A2_UNORM, 4, 1, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000},
    {DDS_FORMAT_R3G3B2,  DXGI_FORMAT_UNKNOWN,           1, 0, 0x000000e0, 0x0000001c, 0x00000003, 0x00000000},
    {DDS_FORMAT_A8,      DXGI_FORMAT_A8_UNORM,          1, 0, 0x00000000, 0x00000000, 0x00000000, 0x000000ff},
    {DDS_FORMAT_L8,      DXGI_FORMAT_R8_UNORM,          1, 0, 0x000000ff, 0x000000ff, 0x000000ff, 0x00000000},
    {DDS_FORMAT_L8A8,    DXGI_FORMAT_UNKNOWN,           2, 1, 0x000000ff, 0x000000ff, 0x000000ff, 0x0000ff00},
    {DDS_FORMAT_AEXP,    DXGI_FORMAT_B8G8R8A8_UNORM,    4, 1, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000},
    {DDS_FORMAT_YCOCG,   DXGI_FORMAT_B8G8R8A8_UNORM,    4, 1, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000}
214 215
};

216 217 218
static int
check_mipmaps (gint32 image_id,
               int    savetype)
219
{
220 221 222 223 224 225 226 227 228 229 230 231
  gint *layers, num_layers;
  int i, j, w, h, mipw, miph, num_mipmaps, num_surfaces = 0;
  int min_surfaces = 1, max_surfaces = 1;
  int valid = 1;
  GimpImageType type;

  /* not handling volume maps for the moment... */
  if (savetype == DDS_SAVE_VOLUMEMAP)
    return (0);

  if (savetype == DDS_SAVE_CUBEMAP)
    {
232 233
      min_surfaces = 6;
      max_surfaces = 6;
234 235 236
    }
  else if (savetype == DDS_SAVE_ARRAY)
    {
237 238
      min_surfaces = 2;
      max_surfaces = INT_MAX;
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    }

  layers = gimp_image_get_layers (image_id, &num_layers);

  w = gimp_image_width (image_id);
  h = gimp_image_height (image_id);

  num_mipmaps = get_num_mipmaps (w, h);

  type = gimp_drawable_type (layers[0]);

  for (i = 0; i < num_layers; ++i)
    {
      if (type != gimp_drawable_type (layers[i]))
        return (0);

      if ((gimp_drawable_width (layers[i])  == w) &&
          (gimp_drawable_height (layers[i]) == h))
        ++num_surfaces;
    }

  if ((num_surfaces < min_surfaces) ||
261 262
      (num_surfaces > max_surfaces) ||
      (num_layers != (num_surfaces * num_mipmaps)))
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
    return (0);

  for (i = 0; valid && i < num_layers; i += num_mipmaps)
    {
      if ((gimp_drawable_width (layers[i])  != w) ||
          (gimp_drawable_height (layers[i]) != h))
        {
          valid = 0;
          break;
        }

      for (j = 1; j < num_mipmaps; ++j)
        {
          mipw = w >> j;
          miph = h >> j;
          if (mipw < 1) mipw = 1;
          if (miph < 1) miph = 1;
          if ((gimp_drawable_width (layers[i + j])  != mipw) ||
              (gimp_drawable_height (layers[i + j]) != miph))
            {
              valid = 0;
              break;
            }
        }
    }

  return (valid);
290 291
}

292 293
static int
check_cubemap (gint32 image_id)
294
{
295 296 297 298 299 300 301 302 303 304 305 306
  gint *layers, num_layers;
  int cubemap = 1, i, j, k, w, h;
  char *layer_name;
  GimpImageType type;

  layers = gimp_image_get_layers (image_id, &num_layers);

  if (num_layers < 6) return (0);

  /* check for a valid cubemap with mipmap layers */
  if (num_layers > 6)
    {
307
      /* check that mipmap layers are in order for a cubemap */
308 309 310
      if (!check_mipmaps (image_id, DDS_SAVE_CUBEMAP))
        return (0);

311
      /* invalidate cubemap faces */
312 313 314
      for (i = 0; i < 6; ++i)
        cubemap_faces[i] = -1;

315
      /* find the mipmap level 0 layers */
316 317 318 319 320 321 322
      w = gimp_image_width (image_id);
      h = gimp_image_height (image_id);

      for (i = 0; i < num_layers; ++i)
        {
          if ((gimp_drawable_width (layers[i])  != w) ||
              (gimp_drawable_height (layers[i]) != h))
323
            continue;
324 325 326

          layer_name = (char*)gimp_item_get_name (layers[i]);
          for (j = 0; j < 6; ++j)
327
            {
328 329 330 331 332 333 334 335 336 337 338
              for (k = 0; k < 4; ++k)
                {
                  if (strstr (layer_name, cubemap_face_names[k][j]))
                    {
                      if (cubemap_faces[j] == -1)
                        {
                          cubemap_faces[j] = layers[i];
                          break;
                        }
                    }
                }
339
            }
340 341
        }

342
      /* check for 6 valid faces */
343 344 345 346 347 348 349 350 351
      for (i = 0; i < 6; ++i)
        {
          if (cubemap_faces[i] == -1)
            {
              cubemap = 0;
              break;
            }
        }

352
      /* make sure they are all the same type */
353 354 355 356 357 358 359 360 361 362 363 364 365
      if (cubemap)
        {
          type = gimp_drawable_type (cubemap_faces[0]);
          for (i = 1; i < 6 && cubemap; ++i)
            {
              if (gimp_drawable_type (cubemap_faces[i]) != type)
                cubemap = 0;
            }
        }
    }

  if (num_layers == 6)
    {
366
      /* invalidate cubemap faces */
367 368 369 370 371 372 373
      for (i = 0; i < 6; ++i)
        cubemap_faces[i] = -1;

      for (i = 0; i < 6; ++i)
        {
          layer_name = (char*)gimp_item_get_name (layers[i]);
          for (j = 0; j < 6; ++j)
374
            {
375 376 377 378 379 380 381 382 383 384 385
              for (k = 0; k < 4; ++k)
                {
                  if (strstr (layer_name, cubemap_face_names[k][j]))
                    {
                      if (cubemap_faces[j] == -1)
                        {
                          cubemap_faces[j] = layers[i];
                          break;
                        }
                    }
                }
386
            }
387 388
        }

389
      /* check for 6 valid faces */
390 391 392 393 394 395 396 397 398
      for (i = 0; i < 6; ++i)
        {
          if (cubemap_faces[i] == -1)
            {
              cubemap = 0;
              break;
            }
        }

399
      /* make sure they are all the same size */
400 401 402 403 404 405 406 407 408 409 410 411 412
      if (cubemap)
        {
          w = gimp_drawable_width (cubemap_faces[0]);
          h = gimp_drawable_height (cubemap_faces[0]);

          for (i = 1; i < 6 && cubemap; ++i)
            {
              if ((gimp_drawable_width (cubemap_faces[i])  != w) ||
                  (gimp_drawable_height (cubemap_faces[i]) != h))
                cubemap = 0;
            }
        }

413
      /* make sure they are all the same type */
414 415 416 417 418 419 420 421 422 423 424 425
      if (cubemap)
        {
          type = gimp_drawable_type (cubemap_faces[0]);
          for (i = 1; i < 6 && cubemap; ++i)
            {
              if (gimp_drawable_type (cubemap_faces[i]) != type)
                cubemap = 0;
            }
        }
    }

  return (cubemap);
426 427
}

428 429
static int
check_volume (gint32 image_id)
430
{
431 432 433 434 435 436 437 438
  gint *layers, num_layers;
  int volume = 0, i, w, h;
  GimpImageType type;

  layers = gimp_image_get_layers (image_id, &num_layers);

  if (num_layers > 1)
    {
439
      volume = 1;
440

441
      /* make sure all layers are the same size */
442 443 444 445 446 447 448
      w = gimp_drawable_width (layers[0]);
      h = gimp_drawable_height (layers[0]);

      for (i = 1; i < num_layers && volume; ++i)
        {
          if ((gimp_drawable_width (layers[i])  != w) ||
              (gimp_drawable_height (layers[i]) != h))
449
            volume = 0;
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        }

      if (volume)
        {
          /* make sure all layers are the same type */
          type = gimp_drawable_type (layers[0]);
          for (i = 1; i < num_layers && volume; ++i)
            {
              if (gimp_drawable_type (layers[i]) != type)
                volume = 0;
            }
        }
    }

  return (volume);
465 466
}

467 468
static int
check_array (gint32 image_id)
469
{
470 471 472 473 474 475 476 477 478 479 480
  gint *layers, num_layers;
  int array = 0, i, w, h;
  GimpImageType type;

  if (check_mipmaps (image_id, DDS_SAVE_ARRAY))
    return (1);

  layers = gimp_image_get_layers (image_id, &num_layers);

  if (num_layers > 1)
    {
481
      array = 1;
482

483
      /* make sure all layers are the same size */
484 485 486 487 488 489 490
      w = gimp_drawable_width (layers[0]);
      h = gimp_drawable_height (layers[0]);

      for (i = 1; i < num_layers && array; ++i)
        {
          if ((gimp_drawable_width (layers[i])  != w) ||
              (gimp_drawable_height (layers[i]) != h))
491
            array = 0;
492 493 494 495 496 497 498
        }

      if (array)
        {
          /* make sure all layers are the same type */
          type = gimp_drawable_type (layers[0]);
          for (i = 1; i < num_layers; ++i)
499
            {
500 501 502 503 504
              if (gimp_drawable_type (layers[i]) != type)
                {
                  array = 0;
                  break;
                }
505
            }
506 507 508 509
        }
    }

  return (array);
510 511
}

512 513
static int
get_array_size (gint32 image_id)
514
{
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  gint *layers, num_layers;
  int i, w, h, elements = 0;

  layers = gimp_image_get_layers (image_id, &num_layers);

  w = gimp_image_width (image_id);
  h = gimp_image_height (image_id);

  for (i = 0; i < num_layers; ++i)
    {
      if ((gimp_drawable_width (layers[i]) == w) && (gimp_drawable_height (layers[i]) == h))
        ++elements;
    }

  return (elements);
530 531
}

532 533 534 535 536
GimpPDBStatusType
write_dds (gchar    *filename,
           gint32    image_id,
           gint32    drawable_id,
           gboolean  interactive_dds)
537
{
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
  FILE *fp;
  gchar *tmp;
  int rc = 0;

  is_mipmap_chain_valid = check_mipmaps (image_id, dds_write_vals.savetype);

  is_cubemap = check_cubemap (image_id);
  is_volume = check_volume (image_id);
  is_array = check_array (image_id);

  if (interactive_dds)
    {
      if (!is_mipmap_chain_valid &&
          dds_write_vals.mipmaps == DDS_MIPMAP_EXISTING)
        dds_write_vals.mipmaps = DDS_MIPMAP_NONE;

      if (!save_dialog (image_id, drawable_id))
        return (GIMP_PDB_CANCEL);
    }
  else
    {
      if (dds_write_vals.savetype == DDS_SAVE_CUBEMAP && !is_cubemap)
        {
          g_message ("DDS: Cannot save image as cube map");
          return (GIMP_PDB_EXECUTION_ERROR);
        }

      if (dds_write_vals.savetype == DDS_SAVE_VOLUMEMAP && !is_volume)
        {
          g_message ("DDS: Cannot save image as volume map");
          return (GIMP_PDB_EXECUTION_ERROR);
        }

      if (dds_write_vals.savetype == DDS_SAVE_VOLUMEMAP &&
          dds_write_vals.compression != DDS_COMPRESS_NONE)
        {
          g_message ("DDS: Cannot save volume map with compression");
          return (GIMP_PDB_EXECUTION_ERROR);
        }

      if (dds_write_vals.mipmaps == DDS_MIPMAP_EXISTING &&
          !is_mipmap_chain_valid)
        {
          g_message ("DDS: Cannot save with existing mipmaps as the mipmap chain is incomplete");
          return (GIMP_PDB_EXECUTION_ERROR);
        }
    }

  fp = g_fopen (filename, "wb");
  if (fp == 0)
    {
      g_message ("Error opening %s", filename);
      return (GIMP_PDB_EXECUTION_ERROR);
    }

  if (strrchr (filename, '/'))
    tmp = g_strdup_printf ("Saving %s:", strrchr (filename, '/') + 1);
  else
    tmp = g_strdup_printf ("Saving %s:", filename);
  gimp_progress_init (tmp);
  g_free (tmp);

  rc = write_image (fp, image_id, drawable_id);

  fclose (fp);

  return (rc ? GIMP_PDB_SUCCESS : GIMP_PDB_EXECUTION_ERROR);
605 606
}

607 608 609 610
static void
swap_rb (unsigned char *pixels,
         unsigned int   n,
         int            bpp)
611
{
612 613
  unsigned int i;
  unsigned char t;
614

615 616
  for (i = 0; i < n; ++i)
    {
617 618 619
      t = pixels[bpp * i + 0];
      pixels[bpp * i + 0] = pixels[bpp * i + 2];
      pixels[bpp * i + 2] = t;
620
    }
621 622
}

623 624 625 626 627 628
static void
alpha_exp (unsigned char *dst,
           int            r,
           int            g,
           int            b,
           int            a)
629
{
630
  float ar, ag, ab, aa;
631

632 633 634
  ar = (float)r / 255.0f;
  ag = (float)g / 255.0f;
  ab = (float)b / 255.0f;
635

636
  aa = MAX (ar, MAX (ag, ab));
637

638 639
  if (aa < 1e-04f)
    {
640 641 642 643 644
      dst[0] = b;
      dst[1] = g;
      dst[2] = r;
      dst[3] = 255;
      return;
645
    }
646

647 648 649
  ar /= aa;
  ag /= aa;
  ab /= aa;
650

651 652 653 654
  r = (int)floorf (255.0f * ar + 0.5f);
  g = (int)floorf (255.0f * ag + 0.5f);
  b = (int)floorf (255.0f * ab + 0.5f);
  a = (int)floorf (255.0f * aa + 0.5f);
655

656 657 658 659
  dst[0] = MAX (0, MIN (255, b));
  dst[1] = MAX (0, MIN (255, g));
  dst[2] = MAX (0, MIN (255, r));
  dst[3] = MAX (0, MIN (255, a));
660 661
}

662 663 664 665 666 667 668 669 670 671
static void
convert_pixels (unsigned char *dst,
                unsigned char *src,
                int            format,
                int            w,
                int            h,
                int            d,
                int            bpp,
                unsigned char *palette,
                int            mipmaps)
672
{
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
  unsigned int i, num_pixels;
  unsigned char r, g, b, a;

  if (d > 0)
    num_pixels = get_volume_mipmapped_size (w, h, d, 1, 0, mipmaps, DDS_COMPRESS_NONE);
  else
    num_pixels = get_mipmapped_size (w, h, 1, 0, mipmaps, DDS_COMPRESS_NONE);

  for (i = 0; i < num_pixels; ++i)
    {
      if (bpp == 1)
        {
          if (palette)
            {
              r = palette[3 * src[i] + 0];
              g = palette[3 * src[i] + 1];
              b = palette[3 * src[i] + 2];
            }
          else
692 693
            r = g = b = src[i];

694
          if (format == DDS_FORMAT_A8)
695
            a = src[i];
696
          else
697
            a = 255;
698 699 700 701 702 703 704 705 706 707 708 709 710
        }
      else if (bpp == 2)
        {
          r = g = b = src[2 * i];
          a = src[2 * i + 1];
        }
      else if (bpp == 3)
        {
          b = src[3 * i + 0];
          g = src[3 * i + 1];
          r = src[3 * i + 2];
          a = 255;
        }
711
      else
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
        {
          b = src[4 * i + 0];
          g = src[4 * i + 1];
          r = src[4 * i + 2];
          a = src[4 * i + 3];
        }

      switch (format)
        {
        case DDS_FORMAT_RGB8:
          dst[3 * i + 0] = b;
          dst[3 * i + 1] = g;
          dst[3 * i + 2] = r;
          break;
        case DDS_FORMAT_RGBA8:
          dst[4 * i + 0] = b;
          dst[4 * i + 1] = g;
          dst[4 * i + 2] = r;
          dst[4 * i + 3] = a;
          break;
        case DDS_FORMAT_BGR8:
          dst[3 * i + 0] = r;
          dst[3 * i + 1] = g;
          dst[3 * i + 2] = b;
          break;
        case DDS_FORMAT_ABGR8:
          dst[4 * i + 0] = r;
          dst[4 * i + 1] = g;
          dst[4 * i + 2] = b;
          dst[4 * i + 3] = a;
          break;
        case DDS_FORMAT_R5G6B5:
          PUTL16(&dst[2 * i], pack_r5g6b5(r, g, b));
          break;
        case DDS_FORMAT_RGBA4:
          PUTL16(&dst[2 * i], pack_rgba4(r, g, b, a));
          break;
        case DDS_FORMAT_RGB5A1:
          PUTL16(&dst[2 * i], pack_rgb5a1(r, g, b, a));
          break;
        case DDS_FORMAT_RGB10A2:
          PUTL32(&dst[4 * i], pack_rgb10a2(r, g, b, a));
          break;
        case DDS_FORMAT_R3G3B2:
          dst[i] = pack_r3g3b2(r, g, b);
          break;
        case DDS_FORMAT_A8:
          dst[i] = a;
          break;
        case DDS_FORMAT_L8:
          dst[i] = rgb_to_luminance (r, g, b);
          break;
        case DDS_FORMAT_L8A8:
          dst[2 * i + 0] = rgb_to_luminance (r, g, b);
          dst[2 * i + 1] = a;
          break;
        case DDS_FORMAT_YCOCG:
          dst[4 * i] = a;
          RGB_to_YCoCg (&dst[4 * i], r, g, b);
          break;
        case DDS_FORMAT_AEXP:
          alpha_exp (&dst[4 * i], r, g, b, a);
          break;
        default:
          break;
        }
    }
779 780
}

781 782 783 784 785 786 787
static void
get_mipmap_chain (unsigned char *dst,
                  int            w,
                  int            h,
                  int            bpp,
                  gint32         image_id,
                  gint           drawable_id)
788
{
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  gint *layers, num_layers;
  GeglBuffer *buffer;
  const Babl *format = 0;
  int i, idx = 0, offset, mipw, miph;

  if (bpp == 1)
    format = babl_format ("Y' u8");
  else if (bpp == 2)
    format = babl_format ("Y'A u8");
  else if (bpp == 3)
    format = babl_format ("R'G'B' u8");
  else
    format = babl_format ("R'G'B'A u8");

  layers = gimp_image_get_layers (image_id, &num_layers);

  for (i = 0; i < num_layers; ++i)
    {
      if (layers[i] == drawable_id)
        {
          idx = i;
          break;
        }
    }

  if (i == num_layers) return;

  offset = 0;

  while (get_next_mipmap_dimensions (&mipw, &miph, w, h))
    {
      buffer = gimp_drawable_get_buffer (layers[++idx]);

      if ((gegl_buffer_get_width (buffer)  != mipw) ||
          (gegl_buffer_get_height (buffer) != miph))
        {
          g_object_unref (buffer);
          return;
        }

      gegl_buffer_get (buffer, GEGL_RECTANGLE (0, 0, mipw, miph), 1.0, format,
                       dst + offset, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
      g_object_unref (buffer);
832 833

      /* we need BGRX or BGRA */
834 835
      if (bpp >= 3)
        swap_rb (dst + offset, mipw * miph, bpp);
836 837 838 839

      offset += (mipw * miph * bpp);
      w = mipw;
      h = miph;
840
    }
841 842
}

843 844 845 846 847 848 849 850 851
static void
write_layer (FILE   *fp,
             gint32  image_id,
             gint32  drawable_id,
             int     w,
             int     h,
             int     bpp,
             int     fmtbpp,
             int     mipmaps)
852
{
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
  GeglBuffer *buffer;
  const Babl *format = 0;
  GimpImageBaseType basetype;
  GimpImageType type;
  unsigned char *src, *dst, *fmtdst, *tmp;
  unsigned char *palette = NULL;
  int i, c, x, y, size, fmtsize, offset, colors;
  int compression = dds_write_vals.compression;
  int flags = 0;

  basetype = gimp_image_base_type (image_id);
  type = gimp_drawable_type (drawable_id);

  buffer = gimp_drawable_get_buffer (drawable_id);

  src = g_malloc (w * h * bpp);

  if (bpp == 1)
    format = babl_format ("Y' u8");
  else if (bpp == 2)
    format = babl_format ("Y'A u8");
  else if (bpp == 3)
    format = babl_format ("R'G'B' u8");
  else
    format = babl_format ("R'G'B'A u8");

  gegl_buffer_get (buffer, GEGL_RECTANGLE (0, 0, w, h), 1.0, format, src,
880 881
                   GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);

882 883 884
  if (basetype == GIMP_INDEXED)
    {
      palette = gimp_image_get_colormap (image_id, &colors);
885

886 887 888 889
      if (type == GIMP_INDEXEDA_IMAGE)
        {
          tmp = g_malloc (w * h);
          for (i = 0; i < w * h; ++i)
890
            tmp[i] = src[2 * i];
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
          g_free (src);
          src = tmp;
          bpp = 1;
        }
    }

  /* we want and assume BGRA ordered pixels for bpp >= 3 from here and
     onwards */
  if (bpp >= 3)
    swap_rb (src, w * h, bpp);

  if (compression == DDS_COMPRESS_BC3N)
    {
      if (bpp != 4)
        {
          fmtsize = w * h * 4;
          fmtdst = g_malloc (fmtsize);
          convert_pixels (fmtdst, src, DDS_FORMAT_RGBA8, w, h, 0, bpp,
                          palette, 1);
          g_free (src);
          src = fmtdst;
          bpp = 4;
        }

      for (y = 0; y < h; ++y)
        {
          for (x = 0; x < w; ++x)
            {
              /* set alpha to red (x) */
              src[y * (w * 4) + (x * 4) + 3] =
                src[y * (w * 4) + (x * 4) + 2];
              /* set red to 1 */
              src[y * (w * 4) + (x * 4) + 2] = 255;
            }
        }
    }

  /* RXGB (Doom3) */
  if (compression == DDS_COMPRESS_RXGB)
    {
      if (bpp != 4)
        {
          fmtsize = w * h * 4;
          fmtdst = g_malloc (fmtsize);
          convert_pixels (fmtdst, src, DDS_FORMAT_RGBA8, w, h, 0, bpp,
                          palette, 1);
          g_free (src);
          src = fmtdst;
          bpp = 4;
        }

      for (y = 0; y < h; ++y)
        {
          for (x = 0; x < w; ++x)
            {
              /* swap red and alpha */
              c = src[y * (w * 4) + (x * 4) + 3];
              src[y * (w * 4) + (x * 4) + 3] =
                src[y * (w * 4) + (x * 4) + 2];
              src[y * (w * 4) + (x * 4) + 2] = c;
            }
        }
    }

  if (compression == DDS_COMPRESS_YCOCG ||
956
      compression == DDS_COMPRESS_YCOCGS) /* convert to YCoCG */
957
    {
958
      fmtsize = w * h * 4;
959 960 961 962
      fmtdst = g_malloc (fmtsize);
      convert_pixels (fmtdst, src, DDS_FORMAT_YCOCG, w, h, 0, bpp,
                      palette, 1);
      g_free (src);
963 964
      src = fmtdst;
      bpp = 4;
965
    }
966

967 968
  if (compression == DDS_COMPRESS_AEXP)
    {
969
      fmtsize = w * h * 4;
970 971 972 973
      fmtdst = g_malloc (fmtsize);
      convert_pixels (fmtdst, src, DDS_FORMAT_AEXP, w, h, 0, bpp,
                      palette, 1);
      g_free (src);
974 975
      src = fmtdst;
      bpp = 4;
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    }

  if (compression == DDS_COMPRESS_NONE)
    {
      if (mipmaps > 1)
        {
          /* pre-convert indexed images to RGB for better quality mipmaps
             if a pixel format conversion is requested */
          if (dds_write_vals.format > DDS_FORMAT_DEFAULT && basetype == GIMP_INDEXED)
            {
              fmtsize = get_mipmapped_size (w, h, 3, 0, mipmaps, DDS_COMPRESS_NONE);
              fmtdst = g_malloc (fmtsize);
              convert_pixels (fmtdst, src, DDS_FORMAT_RGB8, w, h, 0, bpp,
                              palette, 1);
              g_free (src);
              src = fmtdst;
              bpp = 3;
              palette = NULL;
            }

          size = get_mipmapped_size (w, h, bpp, 0, mipmaps, DDS_COMPRESS_NONE);
          dst = g_malloc (size);
          if (dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE)
            {
              generate_mipmaps (dst, src, w, h, bpp, palette != NULL,
                                mipmaps,
                                dds_write_vals.mipmap_filter,
                                dds_write_vals.mipmap_wrap,
                                dds_write_vals.gamma_correct + dds_write_vals.srgb,
                                dds_write_vals.gamma,
                                dds_write_vals.preserve_alpha_coverage,
                                dds_write_vals.alpha_test_threshold);
            }
          else
            {
              memcpy (dst, src, w * h * bpp);
              get_mipmap_chain (dst + (w * h * bpp), w, h, bpp, image_id, drawable_id);
            }

          if (dds_write_vals.format > DDS_FORMAT_DEFAULT)
            {
              fmtsize = get_mipmapped_size (w, h, fmtbpp, 0, mipmaps,
                                            DDS_COMPRESS_NONE);
              fmtdst = g_malloc (fmtsize);

              convert_pixels (fmtdst, dst, dds_write_vals.format, w, h, 0, bpp,
                              palette, mipmaps);

              g_free (dst);
              dst = fmtdst;
              bpp = fmtbpp;
            }

          offset = 0;

          for (i = 0; i < mipmaps; ++i)
            {
              size = get_mipmapped_size (w, h, bpp, i, 1, DDS_COMPRESS_NONE);
              fwrite (dst + offset, 1, size, fp);
              offset += size;
            }

          g_free (dst);
        }
1040
      else
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        {
          if (dds_write_vals.format > DDS_FORMAT_DEFAULT)
            {
              fmtdst = g_malloc (h * w * fmtbpp);
              convert_pixels (fmtdst, src, dds_write_vals.format, w, h, 0, bpp,
                              palette, 1);
              g_free (src);
              src = fmtdst;
              bpp = fmtbpp;
            }

          fwrite (src, 1, h * w * bpp, fp);
        }
    }
  else
    {
      size = get_mipmapped_size (w, h, bpp, 0, mipmaps, compression);

      dst = g_malloc (size);

      if (basetype == GIMP_INDEXED)
        {
          fmtsize = get_mipmapped_size (w, h, 3, 0, mipmaps,
                                        DDS_COMPRESS_NONE);
          fmtdst = g_malloc (fmtsize);
          convert_pixels (fmtdst, src, DDS_FORMAT_RGB8, w, h, 0, bpp,
                          palette, mipmaps);
          g_free (src);
          src = fmtdst;
          bpp = 3;
        }

      if (mipmaps > 1)
        {
          fmtsize = get_mipmapped_size (w, h, bpp, 0, mipmaps,
                                        DDS_COMPRESS_NONE);
          fmtdst = g_malloc (fmtsize);
          if (dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE)
            {
              generate_mipmaps (fmtdst, src, w, h, bpp, 0, mipmaps,
                                dds_write_vals.mipmap_filter,
                                dds_write_vals.mipmap_wrap,
                                dds_write_vals.gamma_correct + dds_write_vals.srgb,
                                dds_write_vals.gamma,
                                dds_write_vals.preserve_alpha_coverage,
                                dds_write_vals.alpha_test_threshold);
            }
          else
            {
              memcpy (fmtdst, src, w * h * bpp);
              get_mipmap_chain (fmtdst + (w * h * bpp), w, h, bpp, image_id, drawable_id);
            }

          g_free (src);
          src = fmtdst;
        }
1097 1098

      flags = 0;
1099
      if (dds_write_vals.perceptual_metric) flags |= DXT_PERCEPTUAL;
1100

1101
      dxt_compress (dst, src, compression, w, h, bpp, mipmaps, flags);
1102

1103
      fwrite (dst, 1, size, fp);
1104

1105 1106
      g_free (dst);
    }
1107

1108
  g_free (src);
1109

1110
  g_object_unref (buffer);
1111 1112
}

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
static void
write_volume_mipmaps (FILE   *fp,
                      gint32  image_id,
                      gint32 *layers,
                      int     w,
                      int     h,
                      int     d,
                      int     bpp,
                      int     fmtbpp,
                      int     mipmaps)
1123
{
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  int i, size, offset, colors;
  unsigned char *src, *dst, *tmp, *fmtdst;
  unsigned char *palette = 0;
  GeglBuffer *buffer;
  const Babl *format;
  GimpImageBaseType type;

  type = gimp_image_base_type (image_id);

  if (dds_write_vals.compression != DDS_COMPRESS_NONE) return;

  src = g_malloc (w * h * bpp * d);

  if (bpp == 1)
    format = babl_format ("Y' u8");
  else if (bpp == 2)
    format = babl_format ("Y'A u8");
  else if (bpp == 3)
    format = babl_format ("R'G'B' u8");
  else
    format = babl_format ("R'G'B'A u8");

  if (gimp_image_base_type (image_id) == GIMP_INDEXED)
    palette = gimp_image_get_colormap (image_id, &colors);

  offset = 0;
  for (i = 0; i < d; ++i)
    {
      buffer = gimp_drawable_get_buffer (layers[i]);
      gegl_buffer_get (buffer, GEGL_RECTANGLE (0, 0, w, h), 1.0, format,
                       src + offset, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
1155
      offset += (w * h * bpp);
1156 1157 1158 1159 1160 1161 1162 1163 1164
      g_object_unref (buffer);
    }

  if (gimp_drawable_type (layers[0]) == GIMP_INDEXEDA_IMAGE)
    {
      tmp = g_malloc (w * h * d);
      for (i = 0; i < w * h * d; ++i)
        tmp[i] = src[2 * i];
      g_free (src);
1165 1166
      src = tmp;
      bpp = 1;
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    }

  /* we want and assume BGRA ordered pixels for bpp >= 3 from here and
     onwards */
  if (bpp >= 3)
    swap_rb (src, w * h * d, bpp);

  /* pre-convert indexed images to RGB for better mipmaps if a
     pixel format conversion is requested */
  if (dds_write_vals.format > DDS_FORMAT_DEFAULT && type == GIMP_INDEXED)
    {
      size = get_volume_mipmapped_size (w, h, d, 3, 0, mipmaps,
                                        DDS_COMPRESS_NONE);
      dst = g_malloc (size);
      convert_pixels (dst, src, DDS_FORMAT_RGB8, w, h, d, bpp, palette, 1);
      g_free (src);
1183 1184 1185
      src = dst;
      bpp = 3;
      palette = NULL;
1186
    }
1187

1188
  size = get_volume_mipmapped_size (w, h, d, bpp, 0, mipmaps,
1189 1190
                                    dds_write_vals.compression);

1191
  dst = g_malloc (size);
1192

1193
  offset = get_volume_mipmapped_size (w, h, d, bpp, 0, 1,
1194 1195
                                      dds_write_vals.compression);

1196
  generate_volume_mipmaps (dst, src, w, h, d, bpp,
1197 1198 1199 1200 1201 1202
                           palette != NULL, mipmaps,
                           dds_write_vals.mipmap_filter,
                           dds_write_vals.mipmap_wrap,
                           dds_write_vals.gamma_correct + dds_write_vals.srgb,
                           dds_write_vals.gamma);

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  if (dds_write_vals.format > DDS_FORMAT_DEFAULT)
    {
      size = get_volume_mipmapped_size (w, h, d, fmtbpp, 0, mipmaps,
                                        dds_write_vals.compression);
      offset = get_volume_mipmapped_size (w, h, d, fmtbpp, 0, 1,
                                          dds_write_vals.compression);
      fmtdst = g_malloc (size);

      convert_pixels (fmtdst, dst, dds_write_vals.format, w, h, d, bpp,
                      palette, mipmaps);
      g_free (dst);
1214
      dst = fmtdst;
1215
    }
1216

1217
  fwrite (dst + offset, 1, size, fp);
1218

1219 1220
  g_free (src);
  g_free (dst);
1221 1222
}

1223 1224 1225 1226
static int
write_image (FILE   *fp,
             gint32  image_id,
             gint32  drawable_id)
1227
{
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  GimpImageType drawable_type;
  GimpImageBaseType basetype;
  int i, w, h, bpp = 0, fmtbpp = 0, has_alpha = 0;
  int num_mipmaps;
  unsigned char hdr[DDS_HEADERSIZE], hdr10[DDS_HEADERSIZE_DX10];
  unsigned int flags = 0, pflags = 0, caps = 0, caps2 = 0, size = 0;
  unsigned int rmask = 0, gmask = 0, bmask = 0, amask = 0;
  unsigned int fourcc = 0;
  DXGI_FORMAT dxgi_format = DXGI_FORMAT_UNKNOWN;
  gint32 num_layers, *layers;
  guchar *cmap;
  gint colors;
  unsigned char zero[4] = {0, 0, 0, 0};
  int is_dx10 = 0, array_size = 1;

  layers = gimp_image_get_layers (image_id, &num_layers);

  if (dds_write_vals.mipmaps == DDS_MIPMAP_EXISTING)
    drawable_id = layers[0];

  if (dds_write_vals.savetype == DDS_SAVE_SELECTED_LAYER)
    {
      w = gimp_drawable_width (drawable_id);
      h = gimp_drawable_height (drawable_id);
    }
  else
    {
      w = gimp_image_width (image_id);
      h = gimp_image_height (image_id);
    }

  basetype = gimp_image_base_type (image_id);
  drawable_type = gimp_drawable_type (drawable_id);

  switch (drawable_type)
    {
    case GIMP_RGB_IMAGE:      bpp = 3; break;
    case GIMP_RGBA_IMAGE:     bpp = 4; break;
    case GIMP_GRAY_IMAGE:     bpp = 1; break;
    case GIMP_GRAYA_IMAGE:    bpp = 2; break;
    case GIMP_INDEXED_IMAGE:  bpp = 1; break;
    case GIMP_INDEXEDA_IMAGE: bpp = 2; break;
    default:
                              break;
    }

  if (dds_write_vals.format > DDS_FORMAT_DEFAULT)
    {
      for (i = 0; ; ++i)
        {
          if (format_info[i].format == dds_write_vals.format)
            {
              fmtbpp = format_info[i].bpp;
              has_alpha = format_info[i].alpha;
              rmask = format_info[i].rmask;
              gmask = format_info[i].gmask;
              bmask = format_info[i].bmask;
              amask = format_info[i].amask;
              dxgi_format = format_info[i].dxgi_format;
              break;
            }
        }
    }
  else if (bpp == 1)
    {
      if (basetype == GIMP_INDEXED)
        {
          fmtbpp = 1;
          has_alpha = 0;
          rmask = bmask = gmask = amask = 0;
        }
1299
      else
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        {
          fmtbpp = 1;
          has_alpha = 0;
          rmask = 0x000000ff;
          gmask = bmask = amask = 0;
          dxgi_format = DXGI_FORMAT_R8_UNORM;
        }
    }
  else if (bpp == 2)
    {
      if (basetype == GIMP_INDEXED)
        {
          fmtbpp = 1;
          has_alpha = 0;
          rmask = gmask = bmask = amask = 0;
        }
1316
      else
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
        {
          fmtbpp = 2;
          has_alpha = 1;
          rmask = 0x000000ff;
          gmask = 0x000000ff;
          bmask = 0x000000ff;
          amask = 0x0000ff00;
        }
    }
  else if (bpp == 3)
    {
1328 1329 1330 1331 1332
      fmtbpp = 3;
      rmask = 0x00ff0000;
      gmask = 0x0000ff00;
      bmask = 0x000000ff;
      amask = 0x00000000;
1333 1334 1335
    }
  else
    {
1336 1337 1338 1339 1340 1341 1342
      fmtbpp = 4;
      has_alpha = 1;
      rmask = 0x00ff0000;
      gmask = 0x0000ff00;
      bmask = 0x000000ff;
      amask = 0xff000000;
      dxgi_format = DXGI_FORMAT_B8G8R8A8_UNORM;
1343
    }
1344

1345
  memset (hdr, 0, DDS_HEADERSIZE);
1346

1347 1348 1349 1350 1351
  PUTL32(hdr,       FOURCC ('D','D','S',' '));
  PUTL32(hdr + 4,   124);
  PUTL32(hdr + 12,  h);
  PUTL32(hdr + 16,  w);
  PUTL32(hdr + 76,  32);
1352

1353 1354
  if (dds_write_vals.compression == DDS_COMPRESS_NONE)
    {
1355 1356 1357 1358 1359
      PUTL32(hdr + 88,  fmtbpp << 3);
      PUTL32(hdr + 92,  rmask);
      PUTL32(hdr + 96,  gmask);
      PUTL32(hdr + 100, bmask);
      PUTL32(hdr + 104, amask);
1360
    }
1361

1362 1363 1364 1365 1366 1367 1368
  /*
     put some information in the reserved area to identify the origin
     of the image
     */
  PUTL32(hdr + 32, FOURCC ('G','I','M','P'));
  PUTL32(hdr + 36, FOURCC ('-','D','D','S'));
  PUTL32(hdr + 40, DDS_PLUGIN_VERSION);
1369

1370
  flags = DDSD_CAPS | DDSD_PIXELFORMAT | DDSD_WIDTH | DDSD_HEIGHT;
1371

1372 1373 1374
  caps = DDSCAPS_TEXTURE;
  if (dds_write_vals.mipmaps)
    {
1375 1376
      flags |= DDSD_MIPMAPCOUNT;
      caps |= (DDSCAPS_COMPLEX | DDSCAPS_MIPMAP);
1377 1378 1379 1380
      num_mipmaps = get_num_mipmaps (w, h);
    }
  else
    num_mipmaps = 1;
1381

1382 1383
  if ((dds_write_vals.savetype == DDS_SAVE_CUBEMAP) && is_cubemap)
    {
1384 1385
      caps |= DDSCAPS_COMPLEX;
      caps2 |= (DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_ALL_FACES);
1386 1387 1388
    }
  else if ((dds_write_vals.savetype == DDS_SAVE_VOLUMEMAP) && is_volume)
    {
1389 1390 1391 1392
      PUTL32(hdr + 24, num_layers); /* depth */
      flags |= DDSD_DEPTH;
      caps |= DDSCAPS_COMPLEX;
      caps2 |= DDSCAPS2_VOLUME;
1393
    }
1394

1395 1396 1397
  PUTL32(hdr + 28,  num_mipmaps);
  PUTL32(hdr + 108, caps);
  PUTL32(hdr + 112, caps2);
1398

1399 1400
  if (dds_write_vals.compression == DDS_COMPRESS_NONE)
    {
1401 1402
      flags |= DDSD_PITCH;

1403 1404 1405
      if (dds_write_vals.format > DDS_FORMAT_DEFAULT)
        {
          if (dds_write_vals.format == DDS_FORMAT_A8)
1406
            pflags |= DDPF_ALPHA;
1407 1408 1409 1410 1411 1412 1413 1414 1415
          else
            {
              if (((fmtbpp == 1) || (dds_write_vals.format == DDS_FORMAT_L8A8)) &&
                  (dds_write_vals.format != DDS_FORMAT_R3G3B2))
                pflags |= DDPF_LUMINANCE;
              else
                pflags |= DDPF_RGB;
            }
        }
1416
      else
1417 1418 1419 1420 1421 1422 1423 1424 1425
        {
          if (bpp == 1)
            {
              if (basetype == GIMP_INDEXED)
                pflags |= DDPF_PALETTEINDEXED8;
              else
                pflags |= DDPF_LUMINANCE;
            }
          else if ((bpp == 2) && (basetype == GIMP_INDEXED))
1426
            pflags |= DDPF_PALETTEINDEXED8;
1427
          else
1428
            pflags |= DDPF_RGB;
1429
        }
1430

1431
      if (has_alpha) pflags |= DDPF_ALPHAPIXELS;
1432 1433 1434 1435 1436 1437

      PUTL32(hdr + 8,  flags);
      PUTL32(hdr + 20, w * fmtbpp); /* pitch */
      PUTL32(hdr + 80, pflags);

      /*
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
         write extra fourcc info - this is special to GIMP DDS. When the image
         is read by the plugin, we can detect the added information to decode
         the pixels
         */
      if (dds_write_vals.format == DDS_FORMAT_AEXP)
        {
          PUTL32(hdr + 44, FOURCC ('A','E','X','P'));
        }
      else if (dds_write_vals.format == DDS_FORMAT_YCOCG)
        {
          PUTL32(hdr + 44, FOURCC ('Y','C','G','1'));
        }
    }
  else
    {
1453 1454 1455
      flags |= DDSD_LINEARSIZE;
      pflags = DDPF_FOURCC;

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
      switch (dds_write_vals.compression)
        {
        case DDS_COMPRESS_BC1:
          fourcc = FOURCC ('D','X','T','1');
          dxgi_format = DXGI_FORMAT_BC1_UNORM;
          break;
        case DDS_COMPRESS_BC2:
          fourcc = FOURCC ('D','X','T','3');
          dxgi_format = DXGI_FORMAT_BC2_UNORM;
          break;
        case DDS_COMPRESS_BC3:
        case DDS_COMPRESS_BC3N:
        case DDS_COMPRESS_YCOCG:
        case DDS_COMPRESS_YCOCGS:
        case DDS_COMPRESS_AEXP:
          fourcc = FOURCC ('D','X','T','5');
          dxgi_format = DXGI_FORMAT_BC3_UNORM;
          break;
        case DDS_COMPRESS_RXGB:
          fourcc = FOURCC ('R','X','G','B');
          dxgi_format = DXGI_FORMAT_BC3_UNORM;
          break;
        case DDS_COMPRESS_BC4:
          fourcc = FOURCC ('A','T','I','1');
          dxgi_format = DXGI_FORMAT_BC4_UNORM;
          //is_dx10 = 1;
          break;
        case DDS_COMPRESS_BC5:
          fourcc = FOURCC ('A','T','I','2');
          dxgi_format = DXGI_FORMAT_BC5_UNORM;
          //is_dx10 = 1;
          break;
        }

      if ((dds_write_vals.compression == DDS_COMPRESS_BC3N) ||
          (dds_write_vals.compression == DDS_COMPRESS_RXGB))
        pflags |= DDPF_NORMAL;
1493 1494 1495 1496 1497 1498

      PUTL32(hdr + 8,  flags);
      PUTL32(hdr + 80, pflags);
      PUTL32(hdr + 84, fourcc);

      size = ((w + 3) >> 2) * ((h + 3) >> 2);
1499 1500 1501
      if ((dds_write_vals.compression == DDS_COMPRESS_BC1) ||
          (dds_write_vals.compression == DDS_COMPRESS_BC4))
        size *= 8;
1502
      else
1503
        size *= 16;
1504 1505 1506 1507

      PUTL32(hdr + 20, size); /* linear size */

      /*
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
         write extra fourcc info - this is special to GIMP DDS. When the image
         is read by the plugin, we can detect the added information to decode
         the pixels
         */
      if (dds_write_vals.compression == DDS_COMPRESS_AEXP)
        {
          PUTL32(hdr + 44, FOURCC ('A','E','X','P'));
        }
      else if (dds_write_vals.compression == DDS_COMPRESS_YCOCG)
        {
          PUTL32(hdr + 44, FOURCC ('Y','C','G','1'));
        }
      else if (dds_write_vals.compression == DDS_COMPRESS_YCOCGS)
        {
          PUTL32(hdr + 44, FOURCC ('Y','C','G','2'));
        }
    }

  /* texture arrays require a DX10 header */
  if (dds_write_vals.savetype == DDS_SAVE_ARRAY)
    is_dx10 = 1;

  if (is_dx10)
    {
      array_size = (dds_write_vals.savetype == DDS_SAVE_SELECTED_LAYER) ? 1 : get_array_size (image_id);
1533 1534 1535 1536 1537 1538 1539 1540 1541

      PUTL32(hdr10 +  0, dxgi_format);
      PUTL32(hdr10 +  4, D3D10_RESOURCE_DIMENSION_TEXTURE2D);
      PUTL32(hdr10 +  8, 0);
      PUTL32(hdr10 + 12, array_size);
      PUTL32(hdr10 + 16, 0);

      /* update main header accordingly */
      PUTL32(hdr + 80, pflags | DDPF_FOURCC);
1542 1543
      PUTL32(hdr + 84, FOURCC ('D','X','1','0'));
    }
1544

1545
  fwrite (hdr, DDS_HEADERSIZE, 1, fp);
1546

1547 1548
  if (is_dx10)
    fwrite (hdr10, DDS_HEADERSIZE_DX10, 1, fp);
1549

1550 1551
  /* write palette for indexed images */
  if ((basetype == GIMP_INDEXED) &&
1552 1553
      (dds_write_vals.format == DDS_FORMAT_DEFAULT) &&
      (dds_write_vals.compression == DDS_COMPRESS_NONE))
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
    {
      cmap = gimp_image_get_colormap (image_id, &colors);
      for (i = 0; i < colors; ++i)
        {
          fwrite (&cmap[3 * i], 1, 3, fp);
          if (i == dds_write_vals.transindex)
            fputc (0, fp);
          else
            fputc (255, fp);
        }
      for (; i < 256; ++i)
        fwrite (zero, 1, 4, fp);
    }

  if (dds_write_vals.savetype == DDS_SAVE_CUBEMAP)
    {
      for (i = 0; i < 6; ++i)
        {
          write_layer (fp, image_id, cubemap_faces[i], w, h, bpp, fmtbpp,
                       num_mipmaps);
          gimp_progress_update ((float)(i + 1) / 6.0);
        }
    }
  else if (dds_write_vals.savetype == DDS_SAVE_VOLUMEMAP)
    {
      for (i = 0; i < num_layers; ++i)
        {
          write_layer (fp, image_id, layers[i], w, h, bpp, fmtbpp, 1);
          gimp_progress_update ((float)i / (float)num_layers);
        }

      if (num_mipmaps > 1)
        write_volume_mipmaps (fp, image_id, layers, w, h, num_layers,
1587
                              bpp, fmtbpp, num_mipmaps);
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
    }
  else if (dds_write_vals.savetype == DDS_SAVE_ARRAY)
    {
      for (i = 0; i < num_layers; ++i)
        {
          if ((gimp_drawable_width (layers[i]) == w) && (gimp_drawable_height (layers[i]) == h))
            write_layer (fp, image_id, layers[i], w, h, bpp, fmtbpp, num_mipmaps);

          gimp_progress_update ((float)i / (float)num_layers);
        }
    }
  else
    {
      write_layer (fp, image_id, drawable_id, w, h, bpp, fmtbpp, num_mipmaps);
    }

  gimp_progress_update (1.0);

  return (1);
1607 1608
}

1609 1610 1611
static GtkWidget *
string_value_combo_new (string_value_t *strings,
                        int             active_value)
1612
{
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
  GtkWidget *opt;
  GtkCellRenderer *renderer;
  GtkListStore *store;
  GtkTreeIter iter;
  int i, active = 0;

  store = gtk_list_store_new (3, G_TYPE_INT, G_TYPE_STRING, G_TYPE_BOOLEAN);
  for (i = 0; strings[i].string; ++i)
    {
      if (strings[i].value == active_value) active = i;
      gtk_list_store_append (store, &iter);
      gtk_list_store_set (store, &iter,
                          0, strings[i].value,
                          1, strings[i].string,
                          2, 1,
                          -1);
    }

  renderer = gtk_cell_renderer_text_new ();

  opt = gtk_combo_box_new_with_model (GTK_TREE_MODEL (store));
  gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (opt), renderer, 1);
  gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (opt), renderer,
1636 1637 1638 1639
                                  "text", COMBO_STRING,
                                  "sensitive", COMBO_SENSITIVE,
                                  NULL);

1640
  gtk_combo_box_set_active (GTK_COMBO_BOX (opt), active);
1641

1642
  g_object_unref (store);
1643

1644
  return (opt);
1645 1646
}

1647 1648 1649
static void
string_value_combo_selected (GtkWidget *widget,
                             gpointer   data)
1650
{
1651 1652 1653
  int value;
  GtkTreeIter iter;
  GtkTreeModel *model;
1654

1655 1656 1657
  model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget));
  gtk_combo_box_get_active_iter (GTK_COMBO_BOX (widget), &iter);
  gtk_tree_model_get (model, &iter, COMBO_VALUE, &value, -1);
1658

1659
  *((int *)data) = value;
1660 1661
}

1662 1663 1664 1665
static void
string_value_combo_set_item_sensitive (GtkWidget *widget,
                                       int        value,
                                       int        sensitive)
1666
{
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
  GtkTreeIter iter;
  GtkTreeModel *model;
  int val;

  model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget));
  gtk_tree_model_get_iter_first (model, &iter);
  do
    {
      gtk_tree_model_get (model, &iter, COMBO_VALUE, &val, -1);
      if (val == value)
        {
          gtk_list_store_set (GTK_LIST_STORE (model), &iter,
                              COMBO_SENSITIVE, sensitive, -1);
          break;
        }
    } while (gtk_tree_model_iter_next (model, &iter));
1683 1684
}

1685 1686 1687
static void
string_value_combo_set_active (GtkWidget *widget,
                               int        value)
1688
{
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
  GtkTreeIter iter;
  GtkTreeModel *model;
  int val;

  model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget));
  gtk_tree_model_get_iter_first (model, &iter);
  do
    {
      gtk_tree_model_get (model, &iter, COMBO_VALUE, &val, -1);
      if (val == value)
        {
          gtk_combo_box_set_active_iter (GTK_COMBO_BOX (widget), &iter);
          break;
        }
    } while (gtk_tree_model_iter_next (model, &iter));
1704 1705
}

1706 1707 1708 1709
static void
save_dialog_response (GtkWidget *widget,
                      gint       response_id,
                      gpointer   data)
1710
{
1711 1712 1713 1714 1715 1716 1717 1718
  switch (response_id)
    {
    case GTK_RESPONSE_OK:
      runme = 1;
    default:
      gtk_widget_destroy (widget);
      break;
    }
1719 1720
}

1721 1722 1723
static void
compression_selected (GtkWidget *widget,
                      gpointer   data)
1724
{
1725 1726 1727 1728 1729
  GtkTreeIter iter;
  GtkTreeModel *model;
  model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget));
  gtk_combo_box_get_active_iter (GTK_COMBO_BOX (widget), &iter);
  gtk_tree_model_get (model, &iter, COMBO_VALUE,
1730 1731
                      &dds_write_vals.compression, -1);

1732 1733
  gtk_widget_set_sensitive (format_opt, dds_write_vals.compression == DDS_COMPRESS_NONE);
  gtk_widget_set_sensitive (pm_chk, dds_write_vals.compression != DDS_COMPRESS_NONE);
1734 1735
}

1736 1737 1738
static void
savetype_selected (GtkWidget *widget,
                   gpointer   data)
1739
{
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
  gint32 image_id = *((gint32 *)data);

  dds_write_vals.savetype = gtk_combo_box_get_active (GTK_COMBO_BOX (widget));

  switch (dds_write_vals.savetype)
    {
    case DDS_SAVE_SELECTED_LAYER:
    case DDS_SAVE_CUBEMAP:
    case DDS_SAVE_ARRAY:
      gtk_widget_set_sensitive (compress_opt, 1);
      break;
    case DDS_SAVE_VOLUMEMAP:
      dds_write_vals.compression = DDS_COMPRESS_NONE;
      gtk_combo_box_set_active (GTK_COMBO_BOX (compress_opt),
                                DDS_COMPRESS_NONE);
      gtk_widget_set_sensitive (compress_opt, 0);
      break;
    }

  string_value_combo_set_item_sensitive (mipmap_opt, DDS_MIPMAP_EXISTING,
                                         check_mipmaps (image_id, dds_write_vals.savetype));
1761 1762
}

1763 1764 1765
static void
mipmaps_selected (GtkWidget *widget,
                  gpointer   data)
1766
{
1767 1768 1769 1770 1771
  GtkTreeIter iter;
  GtkTreeModel *model;
  model = gtk_combo_box_get_model (GTK_COMBO_BOX (widget));
  gtk_combo_box_get_active_iter (GTK_COMBO_BOX (widget), &iter);
  gtk_tree_model_get (model, &iter, COMBO_VALUE,
1772 1773
                      &dds_write_vals.mipmaps, -1);

1774 1775 1776 1777 1778
  gtk_widget_set_sensitive (mipmap_filter_opt, dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE);
  gtk_widget_set_sensitive (mipmap_wrap_opt, dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE);
  gtk_widget_set_sensitive (gamma_chk, dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE);
  gtk_widget_set_sensitive (srgb_chk, (dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE) && dds_write_vals.gamma_correct);
  gtk_widget_set_sensitive (gamma_spin, (dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE) &&
1779
                            dds_write_vals.gamma_correct && !dds_write_vals.srgb);
1780 1781
  gtk_widget_set_sensitive (alpha_coverage_chk, dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE);
  gtk_widget_set_sensitive (alpha_test_threshold_spin, (dds_write_vals.mipmaps == DDS_MIPMAP_GENERATE) &&
1782 1783 1784
                            dds_write_vals.preserve_alpha_coverage);
}

1785 1786 1787
static void
toggle_clicked (GtkWidget *widget,
                gpointer   data)
1788
{
1789 1790
  int *flag = (int *)data;
  (*flag) = !(*flag);
1791 1792
}

1793 1794 1795
static void
transindex_clicked (GtkWidget *widget,
                    gpointer   data)
1796
{
1797
  GtkWidget *spin = GTK_WIDGET (g_object_get_data (G_OBJECT (widget), "spin"));
1798

1799 1800
  if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)))
    {
1801
      dds_write_vals.transindex = 0;
1802 1803 1804 1805 1806 1807
      gtk_widget_set_sensitive (spin, 1);
      gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin), 0);
    }
  else
    {
      gtk_widget_set_sensitive (spin, 0);
1808
      dds_write_vals.transindex = -1;
1809
    }
1810 1811
}

1812 1813 1814
static void
transindex_changed (GtkWidget *widget,
                    gpointer   data)
1815
{
1816
  dds_write_vals.transindex = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (widget));
1817 1818
}

1819 1820 1821
static void
adv_opt_expanded (GtkWidget *widget,
                  gpointer   data)
1822
{
1823
  dds_write_vals.show_adv_opt = !gtk_expander_get_expanded (GTK_EXPANDER (widget));
1824 1825
}

1826 1827 1828
static void
gamma_correct_clicked (GtkWidget *widget,
                       gpointer   data)
1829
{