Merge branch 'master' into blender2.8
[blender.git] / source / blender / python / gpu / gpu_py_element.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/python/gpu/gpu_py_element.c
22  *  \ingroup bpygpu
23  *
24  * - Use ``bpygpu_`` for local API.
25  * - Use ``BPyGPU`` for public API.
26  */
27
28 #include <Python.h>
29
30 #include "GPU_element.h"
31
32 #include "BLI_math.h"
33
34 #include "MEM_guardedalloc.h"
35
36 #include "../generic/py_capi_utils.h"
37 #include "../generic/python_utildefines.h"
38
39 #include "gpu_py_primitive.h"
40 #include "gpu_py_element.h" /* own include */
41
42
43 /* -------------------------------------------------------------------- */
44
45 /** \name IndexBuf Type
46  * \{ */
47
48 static PyObject *bpygpu_IndexBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
49 {
50         bool ok = true;
51
52         struct {
53                 GPUPrimType type_id;
54                 PyObject *seq;
55         } params;
56
57         uint verts_per_prim;
58         uint index_len;
59         GPUIndexBufBuilder builder;
60
61         static const char *_keywords[] = {"type", "seq", NULL};
62         static _PyArg_Parser _parser = {"$O&O:IndexBuf.__new__", _keywords, 0};
63         if (!_PyArg_ParseTupleAndKeywordsFast(
64                 args, kwds, &_parser,
65                 bpygpu_ParsePrimType, &params.type_id,
66                 &params.seq))
67         {
68                 return NULL;
69         }
70
71         verts_per_prim = GPU_indexbuf_primitive_len(params.type_id);
72         if (verts_per_prim == -1) {
73                 PyErr_Format(PyExc_ValueError,
74                              "The argument 'type' must be "
75                              "'POINTS', 'LINES', 'TRIS' or 'LINES_ADJ'");
76                 return NULL;
77         }
78
79         if (PyObject_CheckBuffer(params.seq)) {
80                 Py_buffer pybuffer;
81
82                 if (PyObject_GetBuffer(params.seq, &pybuffer, PyBUF_FORMAT | PyBUF_ND) == -1) {
83                         /* PyObject_GetBuffer already handles error messages. */
84                         return NULL;
85                 }
86
87                 if (pybuffer.ndim != 1 && pybuffer.shape[1] != verts_per_prim) {
88                         PyErr_Format(PyExc_ValueError,
89                                      "Each primitive must exactly %d indices",
90                                      verts_per_prim);
91                         return NULL;
92                 }
93
94                 if (pybuffer.itemsize != 4 ||
95                     PyC_StructFmt_type_is_float_any(PyC_StructFmt_type_from_str(pybuffer.format)))
96                 {
97                         PyErr_Format(PyExc_ValueError,
98                                      "Each index must be an 4-bytes integer value");
99                         return NULL;
100                 }
101
102                 index_len = pybuffer.shape[0];
103                 if (pybuffer.ndim != 1) {
104                         index_len *= pybuffer.shape[1];
105                 }
106
107                 /* The `vertex_len` parameter is only used for asserts in the Debug build. */
108                 /* Not very useful in python since scripts are often tested in Release build. */
109                 /* Use `INT_MAX` instead of the actual number of vertices. */
110                 GPU_indexbuf_init(
111                         &builder, params.type_id, index_len, INT_MAX);
112
113 #if 0
114                 uint *buf = pybuffer.buf;
115                 for (uint i = index_len; i--; buf++) {
116                         GPU_indexbuf_add_generic_vert(&builder, *buf);
117                 }
118 #else
119                 memcpy(builder.data, pybuffer.buf, index_len * sizeof(builder.data));
120                 builder.index_len = index_len;
121 #endif
122                 PyBuffer_Release(&pybuffer);
123         }
124         else {
125                 PyObject *seq_fast = PySequence_Fast(
126                         params.seq, "Index Buffer Initialization");
127
128                 if (seq_fast == NULL) {
129                         return false;
130                 }
131
132                 const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
133
134                 PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
135
136                 index_len = seq_len * verts_per_prim;
137
138                 /* The `vertex_len` parameter is only used for asserts in the Debug build. */
139                 /* Not very useful in python since scripts are often tested in Release build. */
140                 /* Use `INT_MAX` instead of the actual number of vertices. */
141                 GPU_indexbuf_init(
142                         &builder, params.type_id, index_len, INT_MAX);
143
144                 if (verts_per_prim == 1) {
145                         for (uint i = 0; i < seq_len; i++) {
146                                 GPU_indexbuf_add_generic_vert(
147                                         &builder, PyC_Long_AsU32(seq_items[i]));
148                         }
149                 }
150                 else {
151                         for (uint i = 0; i < seq_len; i++) {
152                                 PyObject *item = seq_items[i];
153                                 if (!PyTuple_CheckExact(item)) {
154                                         PyErr_Format(PyExc_ValueError,
155                                                      "expected a tuple, got %s",
156                                                      Py_TYPE(item)->tp_name);
157                                         ok = false;
158                                         goto finally;
159                                 }
160                                 if (PyTuple_GET_SIZE(item) != verts_per_prim) {
161                                         PyErr_Format(PyExc_ValueError,
162                                                      "Expected a Tuple of size %d, got %d",
163                                                      PyTuple_GET_SIZE(item));
164                                         ok = false;
165                                         goto finally;
166                                 }
167
168                                 for (uint j = 0; j < verts_per_prim; j++) {
169                                         GPU_indexbuf_add_generic_vert(
170                                                 &builder,
171                                                 PyC_Long_AsU32(PyTuple_GET_ITEM(item, j)));
172                                 }
173                         }
174                 }
175
176                 if (PyErr_Occurred()) {
177                         ok = false;
178                 }
179
180 finally:
181
182                 Py_DECREF(seq_fast);
183         }
184
185         if (ok == false) {
186                 MEM_freeN(builder.data);
187                 return NULL;
188         }
189
190         return BPyGPUIndexBuf_CreatePyObject(GPU_indexbuf_build(&builder));
191 }
192
193 static void bpygpu_IndexBuf_dealloc(BPyGPUIndexBuf *self)
194 {
195         GPU_indexbuf_discard(self->elem);
196         Py_TYPE(self)->tp_free(self);
197 }
198
199 PyDoc_STRVAR(py_gpu_element_doc,
200 "GPUIndexBuf(type, seq)\n"
201 "\n"
202 "Contains a VBO."
203 "\n"
204 "   :param prim_type:\n"
205 "      One of these primitive types: {\n"
206 "      'POINTS',\n"
207 "      'LINES',\n"
208 "      'TRIS',\n"
209 "      'LINE_STRIP_ADJ'}\n"
210 "   :type type: `str`\n"
211 "   :param seq: Sequence of integers.\n"
212 "   :type buf: `Any 1D or 2D Sequence`\n"
213 );
214 PyTypeObject BPyGPUIndexBuf_Type = {
215         PyVarObject_HEAD_INIT(NULL, 0)
216         .tp_name = "GPUIndexBuf",
217         .tp_basicsize = sizeof(BPyGPUIndexBuf),
218         .tp_dealloc = (destructor)bpygpu_IndexBuf_dealloc,
219         .tp_flags = Py_TPFLAGS_DEFAULT,
220         .tp_doc = py_gpu_element_doc,
221         .tp_new = bpygpu_IndexBuf_new,
222 };
223
224 /** \} */
225
226
227 /* -------------------------------------------------------------------- */
228
229 /** \name Public API
230  * \{ */
231
232 PyObject *BPyGPUIndexBuf_CreatePyObject(GPUIndexBuf *elem)
233 {
234         BPyGPUIndexBuf *self;
235
236         self = PyObject_New(BPyGPUIndexBuf, &BPyGPUIndexBuf_Type);
237         self->elem = elem;
238
239         return (PyObject *)self;
240 }
241
242 /** \} */