Cleanup: remove redundant, invalid info from headers
[blender.git] / source / blender / python / gpu / gpu_py_vertex_buffer.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file blender/python/gpu/gpu_py_vertex_buffer.c
18  *  \ingroup bpygpu
19  *
20  * - Use ``bpygpu_`` for local API.
21  * - Use ``BPyGPU`` for public API.
22  */
23
24 #include <Python.h>
25
26 #include "GPU_vertex_buffer.h"
27
28 #include "BLI_math.h"
29
30 #include "MEM_guardedalloc.h"
31
32 #include "../generic/py_capi_utils.h"
33 #include "../generic/python_utildefines.h"
34
35 #include "gpu_py_vertex_format.h"
36 #include "gpu_py_vertex_buffer.h" /* own include */
37
38 /* -------------------------------------------------------------------- */
39 /** \name Utility Functions
40  * \{ */
41
42 #define PY_AS_NATIVE_SWITCH(attr) \
43         switch (attr->comp_type) { \
44                 case GPU_COMP_I8:  { PY_AS_NATIVE(int8_t,   PyC_Long_AsI8); break; } \
45                 case GPU_COMP_U8:  { PY_AS_NATIVE(uint8_t,  PyC_Long_AsU8); break; } \
46                 case GPU_COMP_I16: { PY_AS_NATIVE(int16_t,  PyC_Long_AsI16); break; } \
47                 case GPU_COMP_U16: { PY_AS_NATIVE(uint16_t, PyC_Long_AsU16); break; } \
48                 case GPU_COMP_I32: { PY_AS_NATIVE(int32_t,  PyC_Long_AsI32); break; } \
49                 case GPU_COMP_U32: { PY_AS_NATIVE(uint32_t, PyC_Long_AsU32); break; } \
50                 case GPU_COMP_F32: { PY_AS_NATIVE(float, PyFloat_AsDouble); break; } \
51                 default: \
52                         BLI_assert(0); \
53         } ((void)0)
54
55 /* No error checking, callers must run PyErr_Occurred */
56 static void fill_format_elem(void *data_dst_void, PyObject *py_src, const GPUVertAttr *attr)
57 {
58 #define PY_AS_NATIVE(ty_dst, py_as_native) \
59 { \
60         ty_dst *data_dst = data_dst_void; \
61         *data_dst = py_as_native(py_src); \
62 } ((void)0)
63
64         PY_AS_NATIVE_SWITCH(attr);
65
66 #undef PY_AS_NATIVE
67 }
68
69 /* No error checking, callers must run PyErr_Occurred */
70 static void fill_format_sequence(void *data_dst_void, PyObject *py_seq_fast, const GPUVertAttr *attr)
71 {
72         const uint len = attr->comp_len;
73         PyObject **value_fast_items = PySequence_Fast_ITEMS(py_seq_fast);
74
75 /**
76  * Args are constants, so range checks will be optimized out if they're nop's.
77  */
78 #define PY_AS_NATIVE(ty_dst, py_as_native) \
79         ty_dst *data_dst = data_dst_void; \
80         for (uint i = 0; i < len; i++) { \
81                 data_dst[i] = py_as_native(value_fast_items[i]); \
82         } ((void)0)
83
84         PY_AS_NATIVE_SWITCH(attr);
85
86 #undef PY_AS_NATIVE
87 }
88
89 #undef PY_AS_NATIVE_SWITCH
90 #undef WARN_TYPE_LIMIT_PUSH
91 #undef WARN_TYPE_LIMIT_POP
92
93 static bool bpygpu_vertbuf_fill_impl(
94         GPUVertBuf *vbo,
95         uint data_id, PyObject *seq, const char *error_prefix)
96 {
97         const char *exc_str_size_mismatch = "Expected a %s of size %d, got %u";
98
99         bool ok = true;
100         const GPUVertAttr *attr = &vbo->format.attrs[data_id];
101
102         if (PyObject_CheckBuffer(seq)) {
103                 Py_buffer pybuffer;
104
105                 if (PyObject_GetBuffer(seq, &pybuffer, PyBUF_STRIDES | PyBUF_ND) == -1) {
106                         /* PyObject_GetBuffer raise a PyExc_BufferError */
107                         return false;
108                 }
109
110                 uint comp_len = pybuffer.ndim == 1 ? 1 : (uint)pybuffer.shape[1];
111
112                 if (pybuffer.shape[0] != vbo->vertex_len) {
113                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
114                                      "sequence", vbo->vertex_len, pybuffer.shape[0]);
115                         ok = false;
116                 }
117                 else if (comp_len != attr->comp_len) {
118                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
119                                     "component", attr->comp_len, comp_len);
120                         ok = false;
121                 }
122                 else {
123                         GPU_vertbuf_attr_fill_stride(vbo, data_id, pybuffer.strides[0], pybuffer.buf);
124                 }
125
126                 PyBuffer_Release(&pybuffer);
127         }
128         else {
129                 GPUVertBufRaw data_step;
130                 GPU_vertbuf_attr_get_raw_data(vbo, data_id, &data_step);
131
132                 PyObject *seq_fast = PySequence_Fast(seq, "Vertex buffer fill");
133                 if (seq_fast == NULL) {
134                         return false;
135                 }
136
137                 const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
138
139                 if (seq_len != vbo->vertex_len) {
140                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
141                                      "sequence", vbo->vertex_len, seq_len);
142                 }
143
144                 PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
145
146                 if (attr->comp_len == 1) {
147                         for (uint i = 0; i < seq_len; i++) {
148                                 uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
149                                 PyObject *item = seq_items[i];
150                                 fill_format_elem(data, item, attr);
151                         }
152                 }
153                 else {
154                         for (uint i = 0; i < seq_len; i++) {
155                                 uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
156                                 PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
157
158                                 if (seq_fast_item == NULL) {
159                                         ok = false;
160                                         goto finally;
161                                 }
162                                 if (PySequence_Fast_GET_SIZE(seq_fast_item) != attr->comp_len) {
163                                         PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
164                                                      "sequence", attr->comp_len, PySequence_Fast_GET_SIZE(seq_fast_item));
165                                         ok = false;
166                                         Py_DECREF(seq_fast_item);
167                                         goto finally;
168                                 }
169
170                                 /* May trigger error, check below */
171                                 fill_format_sequence(data, seq_fast_item, attr);
172                                 Py_DECREF(seq_fast_item);
173                         }
174                 }
175
176                 if (PyErr_Occurred()) {
177                         ok = false;
178                 }
179
180 finally:
181
182                 Py_DECREF(seq_fast);
183         }
184         return ok;
185 }
186
187 static int bpygpu_attr_fill(GPUVertBuf *buf, int id, PyObject *py_seq_data, const char *error_prefix)
188 {
189         if (id < 0 || id >= buf->format.attr_len) {
190                 PyErr_Format(PyExc_ValueError,
191                              "Format id %d out of range",
192                              id);
193                 return 0;
194         }
195
196         if (buf->data == NULL) {
197                 PyErr_SetString(PyExc_ValueError,
198                                 "Can't fill, static buffer already in use");
199                 return 0;
200         }
201
202         if (!bpygpu_vertbuf_fill_impl(buf, (uint)id, py_seq_data, error_prefix)) {
203                 return 0;
204         }
205
206         return 1;
207 }
208
209
210 /** \} */
211
212
213 /* -------------------------------------------------------------------- */
214 /** \name VertBuf Type
215  * \{ */
216
217 static PyObject *bpygpu_VertBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
218 {
219         struct {
220                 PyObject *py_fmt;
221                 uint len;
222         } params;
223
224         static const char *_keywords[] = {"format", "len", NULL};
225         static _PyArg_Parser _parser = {"O!I:GPUVertBuf.__new__", _keywords, 0};
226         if (!_PyArg_ParseTupleAndKeywordsFast(
227                 args, kwds, &_parser,
228                 &BPyGPUVertFormat_Type, &params.py_fmt,
229                 &params.len))
230         {
231                 return NULL;
232         }
233
234         const GPUVertFormat *fmt = &((BPyGPUVertFormat *)params.py_fmt)->fmt;
235         GPUVertBuf *vbo = GPU_vertbuf_create_with_format(fmt);
236
237         GPU_vertbuf_data_alloc(vbo, params.len);
238
239         return BPyGPUVertBuf_CreatePyObject(vbo);
240 }
241
242 PyDoc_STRVAR(bpygpu_VertBuf_attr_fill_doc,
243 ".. method:: attr_fill(id, data)\n"
244 "\n"
245 "   Insert data into the buffer for a single attribute.\n"
246 "\n"
247 "   :param id: Either the name or the id of the attribute.\n"
248 "   :type id: int or str\n"
249 "   :param data: Sequence of data that should be stored in the buffer\n"
250 "   :type data: sequence of values or tuples\n"
251 );
252 static PyObject *bpygpu_VertBuf_attr_fill(BPyGPUVertBuf *self, PyObject *args, PyObject *kwds)
253 {
254         PyObject *data;
255         PyObject *identifier;
256
257         static const char *_keywords[] = {"id", "data", NULL};
258         static _PyArg_Parser _parser = {"OO:attr_fill", _keywords, 0};
259         if (!_PyArg_ParseTupleAndKeywordsFast(
260                 args, kwds, &_parser,
261                 &identifier, &data))
262         {
263                 return NULL;
264         }
265
266         int id;
267
268         if (PyLong_Check(identifier)) {
269                 id = PyLong_AsLong(identifier);
270         }
271         else if (PyUnicode_Check(identifier)) {
272                 const char *name = PyUnicode_AsUTF8(identifier);
273                 id = GPU_vertformat_attr_id_get(&self->buf->format, name);
274                 if (id == -1) {
275                         PyErr_SetString(PyExc_ValueError,
276                                         "Unknown attribute name");
277                         return NULL;
278                 }
279         }
280         else {
281                 PyErr_SetString(PyExc_TypeError,
282                                 "expected int or str type as identifier");
283                 return NULL;
284         }
285
286
287         if (!bpygpu_attr_fill(self->buf, id, data, "GPUVertBuf.attr_fill")) {
288                 return NULL;
289         }
290
291         Py_RETURN_NONE;
292 }
293
294
295 static struct PyMethodDef bpygpu_VertBuf_methods[] = {
296         {"attr_fill", (PyCFunction) bpygpu_VertBuf_attr_fill,
297          METH_VARARGS | METH_KEYWORDS, bpygpu_VertBuf_attr_fill_doc},
298         {NULL, NULL, 0, NULL}
299 };
300
301 static void bpygpu_VertBuf_dealloc(BPyGPUVertBuf *self)
302 {
303         GPU_vertbuf_discard(self->buf);
304         Py_TYPE(self)->tp_free(self);
305 }
306
307 PyDoc_STRVAR(py_gpu_vertex_buffer_doc,
308 ".. class:: GPUVertBuf(len, format)\n"
309 "\n"
310 "   Contains a VBO.\n"
311 "\n"
312 "   :param len: Amount of vertices that will fit into this buffer.\n"
313 "   :type type: `int`\n"
314 "   :param format: Vertex format.\n"
315 "   :type buf: :class:`gpu.types.GPUVertFormat`\n"
316 );
317 PyTypeObject BPyGPUVertBuf_Type = {
318         PyVarObject_HEAD_INIT(NULL, 0)
319         .tp_name = "GPUVertBuf",
320         .tp_basicsize = sizeof(BPyGPUVertBuf),
321         .tp_dealloc = (destructor)bpygpu_VertBuf_dealloc,
322         .tp_flags = Py_TPFLAGS_DEFAULT,
323         .tp_doc = py_gpu_vertex_buffer_doc,
324         .tp_methods = bpygpu_VertBuf_methods,
325         .tp_new = bpygpu_VertBuf_new,
326 };
327
328 /** \} */
329
330
331 /* -------------------------------------------------------------------- */
332 /** \name Public API
333  * \{ */
334
335 PyObject *BPyGPUVertBuf_CreatePyObject(GPUVertBuf *buf)
336 {
337         BPyGPUVertBuf *self;
338
339         self = PyObject_New(BPyGPUVertBuf, &BPyGPUVertBuf_Type);
340         self->buf = buf;
341
342         return (PyObject *)self;
343 }
344
345 /** \} */