Welcome to mirror list, hosted at ThFree Co, Russian Federation.

imbuf_py_api.c « generic « python « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6a7f899488b7aef307d530dd35f569aec8bb324a (plain)
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
 * 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; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/** \file
 * \ingroup pygen
 *
 * This file defines the 'imbuf' image manipulation module.
 */

#include <Python.h>

#include "BLI_utildefines.h"
#include "BLI_string.h"
#include "BLI_rect.h"

#include "py_capi_utils.h"

#include "python_utildefines.h"

#include "imbuf_py_api.h" /* own include */

#include "../../imbuf/IMB_imbuf.h"
#include "../../imbuf/IMB_imbuf_types.h"

/* File IO */
#include <fcntl.h>
#include <errno.h>
#include "BLI_fileops.h"

static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf);

/* -------------------------------------------------------------------- */
/** \name Type & Utilities
 * \{ */

typedef struct Py_ImBuf {
  PyObject_VAR_HEAD
      /* can be NULL */
      ImBuf *ibuf;
} Py_ImBuf;

static int py_imbuf_valid_check(Py_ImBuf *self)
{
  if (LIKELY(self->ibuf)) {
    return 0;
  }
  else {
    PyErr_Format(
        PyExc_ReferenceError, "ImBuf data of type %.200s has been freed", Py_TYPE(self)->tp_name);
    return -1;
  }
}

#define PY_IMBUF_CHECK_OBJ(obj) \
  if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { \
    return NULL; \
  } \
  ((void)0)
#define PY_IMBUF_CHECK_INT(obj) \
  if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { \
    return -1; \
  } \
  ((void)0)

/** \} */

/* -------------------------------------------------------------------- */
/** \name Methods
 * \{ */

PyDoc_STRVAR(py_imbuf_resize_doc,
             ".. method:: resize(size, method='FAST')\n"
             "\n"
             "   Resize the image.\n"
             "\n"
             "   :arg size: New size.\n"
             "   :type size: pair of ints\n"
             "   :arg method: Method of resizing ('FAST', 'BILINEAR')\n"
             "   :type method: str\n");
static PyObject *py_imbuf_resize(Py_ImBuf *self, PyObject *args, PyObject *kw)
{
  PY_IMBUF_CHECK_OBJ(self);

  uint size[2];

  enum { FAST, BILINEAR };
  const struct PyC_StringEnumItems method_items[] = {
      {FAST, "FAST"},
      {BILINEAR, "BILINEAR"},
      {0, NULL},
  };
  struct PyC_StringEnum method = {method_items, FAST};

  static const char *_keywords[] = {"size", "method", NULL};
  static _PyArg_Parser _parser = {"(II)|O&:resize", _keywords, 0};
  if (!_PyArg_ParseTupleAndKeywordsFast(
          args, kw, &_parser, &size[0], &size[1], PyC_ParseStringEnum, &method)) {
    return NULL;
  }
  if (method.value_found == FAST) {
    IMB_scalefastImBuf(self->ibuf, UNPACK2(size));
  }
  else if (method.value_found == BILINEAR) {
    IMB_scaleImBuf(self->ibuf, UNPACK2(size));
  }
  else {
    BLI_assert(0);
  }
  Py_RETURN_NONE;
}

PyDoc_STRVAR(py_imbuf_crop_doc,
             ".. method:: crop(min, max)\n"
             "\n"
             "   Crop the image.\n"
             "\n"
             "   :arg min: X, Y minimum.\n"
             "   :type min: pair of ints\n"
             "   :arg max: X, Y maximum.\n"
             "   :type max: pair of ints\n");
static PyObject *py_imbuf_crop(Py_ImBuf *self, PyObject *args, PyObject *kw)
{
  PY_IMBUF_CHECK_OBJ(self);

  rcti crop;

  static const char *_keywords[] = {"min", "max", NULL};
  static _PyArg_Parser _parser = {"(II)(II):crop", _keywords, 0};
  if (!_PyArg_ParseTupleAndKeywordsFast(
          args, kw, &_parser, &crop.xmin, &crop.ymin, &crop.xmax, &crop.ymax)) {
    return NULL;
  }

  if (/* X range. */
      (!(crop.xmin >= 0 && crop.xmax < self->ibuf->x)) ||
      /* Y range. */
      (!(crop.ymin >= 0 && crop.ymax < self->ibuf->y)) ||
      /* X order. */
      (!(crop.xmin <= crop.xmax)) ||
      /* Y order. */
      (!(crop.ymin <= crop.ymax))) {
    PyErr_SetString(PyExc_ValueError, "ImBuf crop min/max not in range");
    return NULL;
  }
  IMB_rect_crop(self->ibuf, &crop);
  Py_RETURN_NONE;
}

PyDoc_STRVAR(py_imbuf_copy_doc,
             ".. method:: copy()\n"
             "\n"
             "   :return: A copy of the image.\n"
             "   :rtype: :class:`ImBuf`\n");
static PyObject *py_imbuf_copy(Py_ImBuf *self)
{
  PY_IMBUF_CHECK_OBJ(self);
  return Py_ImBuf_CreatePyObject(self->ibuf);
}

static PyObject *py_imbuf_deepcopy(Py_ImBuf *self, PyObject *args)
{
  if (!PyC_CheckArgs_DeepCopy(args)) {
    return NULL;
  }
  return py_imbuf_copy(self);
}

PyDoc_STRVAR(py_imbuf_free_doc,
             ".. method:: free()\n"
             "\n"
             "   Clear image data immediately (causing an error on re-use).\n");
static PyObject *py_imbuf_free(Py_ImBuf *self)
{
  if (self->ibuf) {
    IMB_freeImBuf(self->ibuf);
    self->ibuf = NULL;
  }
  Py_RETURN_NONE;
}

static struct PyMethodDef Py_ImBuf_methods[] = {
    {"resize", (PyCFunction)py_imbuf_resize, METH_VARARGS | METH_KEYWORDS, py_imbuf_resize_doc},
    {"crop", (PyCFunction)py_imbuf_crop, METH_VARARGS | METH_KEYWORDS, (char *)py_imbuf_crop_doc},
    {"free", (PyCFunction)py_imbuf_free, METH_NOARGS, py_imbuf_free_doc},
    {"copy", (PyCFunction)py_imbuf_copy, METH_NOARGS, py_imbuf_copy_doc},
    {"__copy__", (PyCFunction)py_imbuf_copy, METH_NOARGS, py_imbuf_copy_doc},
    {"__deepcopy__", (PyCFunction)py_imbuf_deepcopy, METH_VARARGS, py_imbuf_copy_doc},
    {NULL, NULL, 0, NULL},
};

/** \} */

/* -------------------------------------------------------------------- */
/** \name Attributes
 * \{ */

PyDoc_STRVAR(py_imbuf_size_doc, "size of the image in pixels.\n\n:type: pair of ints");
static PyObject *py_imbuf_size_get(Py_ImBuf *self, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_OBJ(self);
  ImBuf *ibuf = self->ibuf;
  return PyC_Tuple_Pack_I32(ibuf->x, ibuf->y);
}

PyDoc_STRVAR(py_imbuf_ppm_doc, "pixels per meter.\n\n:type: pair of floats");
static PyObject *py_imbuf_ppm_get(Py_ImBuf *self, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_OBJ(self);
  ImBuf *ibuf = self->ibuf;
  return PyC_Tuple_Pack_F64(ibuf->ppm[0], ibuf->ppm[1]);
}

static int py_imbuf_ppm_set(Py_ImBuf *self, PyObject *value, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_INT(self);
  double ppm[2];

  if (PyC_AsArray(ppm, value, 2, &PyFloat_Type, true, "ppm") == -1) {
    return -1;
  }

  if (ppm[0] <= 0.0 || ppm[1] <= 0.0) {
    PyErr_SetString(PyExc_ValueError, "invalid ppm value");
    return -1;
  }

  ImBuf *ibuf = self->ibuf;
  ibuf->ppm[0] = ppm[0];
  ibuf->ppm[1] = ppm[1];
  return 0;
}

PyDoc_STRVAR(py_imbuf_filepath_doc, "filepath associated with this image.\n\n:type: string");
static PyObject *py_imbuf_filepath_get(Py_ImBuf *self, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_OBJ(self);
  ImBuf *ibuf = self->ibuf;
  return PyC_UnicodeFromByte(ibuf->name);
}

static int py_imbuf_filepath_set(Py_ImBuf *self, PyObject *value, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_INT(self);

  if (!PyUnicode_Check(value)) {
    PyErr_SetString(PyExc_TypeError, "expected a string!");
    return -1;
  }

  ImBuf *ibuf = self->ibuf;
  Py_ssize_t value_str_len_max = sizeof(ibuf->name);
  Py_ssize_t value_str_len;
  const char *value_str = _PyUnicode_AsStringAndSize(value, &value_str_len);
  if (value_str_len >= value_str_len_max) {
    PyErr_Format(PyExc_TypeError, "filepath length over %zd", value_str_len_max - 1);
    return -1;
  }
  memcpy(ibuf->name, value_str, value_str_len + 1);
  return 0;
}

PyDoc_STRVAR(py_imbuf_planes_doc, "Number of bits associated with this image.\n\n:type: int");
static PyObject *py_imbuf_planes_get(Py_ImBuf *self, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_OBJ(self);
  ImBuf *imbuf = self->ibuf;
  return PyLong_FromLong(imbuf->planes);
}

PyDoc_STRVAR(py_imbuf_channels_doc, "Number of bit-planes.\n\n:type: int");
static PyObject *py_imbuf_channels_get(Py_ImBuf *self, void *UNUSED(closure))
{
  PY_IMBUF_CHECK_OBJ(self);
  ImBuf *imbuf = self->ibuf;
  return PyLong_FromLong(imbuf->channels);
}

static PyGetSetDef Py_ImBuf_getseters[] = {
    {(char *)"size", (getter)py_imbuf_size_get, (setter)NULL, (char *)py_imbuf_size_doc, NULL},
    {(char *)"ppm",
     (getter)py_imbuf_ppm_get,
     (setter)py_imbuf_ppm_set,
     (char *)py_imbuf_ppm_doc,
     NULL},
    {(char *)"filepath",
     (getter)py_imbuf_filepath_get,
     (setter)py_imbuf_filepath_set,
     (char *)py_imbuf_filepath_doc,
     NULL},
    {(char *)"planes", (getter)py_imbuf_planes_get, NULL, (char *)py_imbuf_planes_doc, NULL},
    {(char *)"channels", (getter)py_imbuf_channels_get, NULL, (char *)py_imbuf_channels_doc, NULL},
    {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};

/** \} */

/* -------------------------------------------------------------------- */
/** \name Type & Implementation
 * \{ */

static void py_imbuf_dealloc(Py_ImBuf *self)
{
  ImBuf *ibuf = self->ibuf;
  if (ibuf != NULL) {
    IMB_freeImBuf(self->ibuf);
    self->ibuf = NULL;
  }
  PyObject_DEL(self);
}

static PyObject *py_imbuf_repr(Py_ImBuf *self)
{
  const ImBuf *ibuf = self->ibuf;
  if (ibuf != NULL) {
    return PyUnicode_FromFormat(
        "<imbuf: address=%p, filepath='%s', size=(%d, %d)>", ibuf, ibuf->name, ibuf->x, ibuf->y);
  }
  else {
    return PyUnicode_FromString("<imbuf: address=0x0>");
  }
}

static Py_hash_t py_imbuf_hash(Py_ImBuf *self)
{
  return _Py_HashPointer(self->ibuf);
}

PyTypeObject Py_ImBuf_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    /*  For printing, in format "<module>.<name>" */
    "ImBuf",          /* tp_name */
    sizeof(Py_ImBuf), /* int tp_basicsize; */
    0,                /* tp_itemsize;  For allocation */

    /* Methods to implement standard operations */

    (destructor)py_imbuf_dealloc, /* destructor tp_dealloc; */
    NULL,                         /* printfunc tp_print; */
    NULL,                         /* getattrfunc tp_getattr; */
    NULL,                         /* setattrfunc tp_setattr; */
    NULL,                         /* cmpfunc tp_compare; */
    (reprfunc)py_imbuf_repr,      /* reprfunc tp_repr; */

    /* Method suites for standard classes */

    NULL, /* PyNumberMethods *tp_as_number; */
    NULL, /* PySequenceMethods *tp_as_sequence; */
    NULL, /* PyMappingMethods *tp_as_mapping; */

    /* More standard operations (here for binary compatibility) */

    (hashfunc)py_imbuf_hash, /* hashfunc tp_hash; */
    NULL,                    /* ternaryfunc tp_call; */
    NULL,                    /* reprfunc tp_str; */
    NULL,                    /* getattrofunc tp_getattro; */
    NULL,                    /* setattrofunc tp_setattro; */

    /* Functions to access object as input/output buffer */
    NULL, /* PyBufferProcs *tp_as_buffer; */

    /*** Flags to define presence of optional/expanded features ***/
    Py_TPFLAGS_DEFAULT, /* long tp_flags; */

    NULL, /*  char *tp_doc;  Documentation string */
    /*** Assigned meaning in release 2.0 ***/
    /* call function for all accessible objects */
    NULL, /* traverseproc tp_traverse; */

    /* delete references to contained objects */
    NULL, /* inquiry tp_clear; */

    /***  Assigned meaning in release 2.1 ***/
    /*** rich comparisons ***/
    NULL, /* richcmpfunc tp_richcompare; */

    /***  weak reference enabler ***/
    0, /* long tp_weaklistoffset; */

    /*** Added in release 2.2 ***/
    /*   Iterators */
    NULL, /* getiterfunc tp_iter; */
    NULL, /* iternextfunc tp_iternext; */
    /*** Attribute descriptor and subclassing stuff ***/
    Py_ImBuf_methods,   /* struct PyMethodDef *tp_methods; */
    NULL,               /* struct PyMemberDef *tp_members; */
    Py_ImBuf_getseters, /* struct PyGetSetDef *tp_getset; */
};

static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf)
{
  Py_ImBuf *self = PyObject_New(Py_ImBuf, &Py_ImBuf_Type);
  self->ibuf = ibuf;
  return (PyObject *)self;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Module Functions
 * \{ */

PyDoc_STRVAR(M_imbuf_new_doc,
             ".. function:: new(size)\n"
             "\n"
             "   Load a new image.\n"
             "\n"
             "   :arg size: The size of the image in pixels.\n"
             "   :type size: pair of ints\n"
             "   :return: the newly loaded image.\n"
             "   :rtype: :class:`ImBuf`\n");
static PyObject *M_imbuf_new(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
  int size[2];
  static const char *_keywords[] = {"size", NULL};
  static _PyArg_Parser _parser = {"(ii)|i:new", _keywords, 0};
  if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &size[0], &size[1])) {
    return NULL;
  }

  /* TODO, make options */
  uchar planes = 4;
  uint flags = IB_rect;

  ImBuf *ibuf = IMB_allocImBuf(UNPACK2(size), planes, flags);
  if (ibuf == NULL) {
    PyErr_Format(PyExc_ValueError, "new: Unable to create image (%d, %d)", UNPACK2(size));
    return NULL;
  }
  return Py_ImBuf_CreatePyObject(ibuf);
}

PyDoc_STRVAR(M_imbuf_load_doc,
             ".. function:: load(filepath)\n"
             "\n"
             "   Load an image from a file.\n"
             "\n"
             "   :arg filepath: the filepath of the image.\n"
             "   :type filepath: string\n"
             "   :return: the newly loaded image.\n"
             "   :rtype: :class:`ImBuf`\n");
static PyObject *M_imbuf_load(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
  const char *filepath;

  static const char *_keywords[] = {"filepath", NULL};
  static _PyArg_Parser _parser = {"s:load", _keywords, 0};
  if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &filepath)) {
    return NULL;
  }

  const int file = BLI_open(filepath, O_BINARY | O_RDONLY, 0);
  if (file == -1) {
    PyErr_Format(PyExc_IOError, "load: %s, failed to open file '%s'", strerror(errno), filepath);
    return NULL;
  }

  ImBuf *ibuf = IMB_loadifffile(file, filepath, IB_rect, NULL, filepath);

  close(file);

  if (ibuf == NULL) {
    PyErr_Format(
        PyExc_ValueError, "load: Unable to recognize image format for file '%s'", filepath);
    return NULL;
  }

  BLI_strncpy(ibuf->name, filepath, sizeof(ibuf->name));

  return Py_ImBuf_CreatePyObject(ibuf);
}

PyDoc_STRVAR(M_imbuf_write_doc,
             ".. function:: write(image, filepath)\n"
             "\n"
             "   Write an image.\n"
             "\n"
             "   :arg image: the image to write.\n"
             "   :type image: :class:`ImBuf`\n"
             "   :arg filepath: the filepath of the image.\n"
             "   :type filepath: string\n");
static PyObject *M_imbuf_write(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
  Py_ImBuf *py_imb;
  const char *filepath = NULL;

  static const char *_keywords[] = {"image", "filepath", NULL};
  static _PyArg_Parser _parser = {"O!|s:write", _keywords, 0};
  if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &Py_ImBuf_Type, &py_imb, &filepath)) {
    return NULL;
  }

  if (filepath == NULL) {
    filepath = py_imb->ibuf->name;
  }

  bool ok = IMB_saveiff(py_imb->ibuf, filepath, IB_rect);
  if (ok == false) {
    PyErr_Format(
        PyExc_IOError, "write: Unable to write image file (%s) '%s'", strerror(errno), filepath);
    return NULL;
  }

  Py_RETURN_NONE;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Module Definition
 * \{ */

static PyMethodDef IMB_methods[] = {
    {"new", (PyCFunction)M_imbuf_new, METH_VARARGS | METH_KEYWORDS, M_imbuf_new_doc},
    {"load", (PyCFunction)M_imbuf_load, METH_VARARGS | METH_KEYWORDS, M_imbuf_load_doc},
    {"write", (PyCFunction)M_imbuf_write, METH_VARARGS | METH_KEYWORDS, M_imbuf_write_doc},
    {NULL, NULL, 0, NULL},
};

PyDoc_STRVAR(IMB_doc, "This module provides access to Blender's image manipulation API.");
static struct PyModuleDef IMB_module_def = {
    PyModuleDef_HEAD_INIT,
    "imbuf",     /* m_name */
    IMB_doc,     /* m_doc */
    0,           /* m_size */
    IMB_methods, /* m_methods */
    NULL,        /* m_reload */
    NULL,        /* m_traverse */
    NULL,        /* m_clear */
    NULL,        /* m_free */
};

PyObject *BPyInit_imbuf(void)
{
  PyObject *submodule;

  submodule = PyModule_Create(&IMB_module_def);

  PyType_Ready(&Py_ImBuf_Type);

  return submodule;
}

/** \} */