Merge branch 'blender2.7'
[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         const char *error_prefix = "IndexBuf.__new__";
51         bool ok = true;
52
53         struct {
54                 GPUPrimType type_id;
55                 PyObject *seq;
56         } params;
57
58         uint verts_per_prim;
59         uint index_len;
60         GPUIndexBufBuilder builder;
61
62         static const char *_keywords[] = {"type", "seq", NULL};
63         static _PyArg_Parser _parser = {"$O&O:IndexBuf.__new__", _keywords, 0};
64         if (!_PyArg_ParseTupleAndKeywordsFast(
65                 args, kwds, &_parser,
66                 bpygpu_ParsePrimType, &params.type_id,
67                 &params.seq))
68         {
69                 return NULL;
70         }
71
72         verts_per_prim = GPU_indexbuf_primitive_len(params.type_id);
73         if (verts_per_prim == -1) {
74                 PyErr_Format(PyExc_ValueError,
75                              "The argument 'type' must be "
76                              "'POINTS', 'LINES', 'TRIS' or 'LINES_ADJ'");
77                 return NULL;
78         }
79
80         if (PyObject_CheckBuffer(params.seq)) {
81                 Py_buffer pybuffer;
82
83                 if (PyObject_GetBuffer(params.seq, &pybuffer, PyBUF_FORMAT | PyBUF_ND) == -1) {
84                         /* PyObject_GetBuffer already handles error messages. */
85                         return NULL;
86                 }
87
88                 if (pybuffer.ndim != 1 && pybuffer.shape[1] != verts_per_prim) {
89                         PyErr_Format(PyExc_ValueError,
90                                      "Each primitive must exactly %d indices",
91                                      verts_per_prim);
92                         return NULL;
93                 }
94
95                 if (pybuffer.itemsize != 4 ||
96                     PyC_StructFmt_type_is_float_any(PyC_StructFmt_type_from_str(pybuffer.format)))
97                 {
98                         PyErr_Format(PyExc_ValueError,
99                                      "Each index must be an 4-bytes integer value");
100                         return NULL;
101                 }
102
103                 index_len = pybuffer.shape[0];
104                 if (pybuffer.ndim != 1) {
105                         index_len *= pybuffer.shape[1];
106                 }
107
108                 /* The `vertex_len` parameter is only used for asserts in the Debug build. */
109                 /* Not very useful in python since scripts are often tested in Release build. */
110                 /* Use `INT_MAX` instead of the actual number of vertices. */
111                 GPU_indexbuf_init(
112                         &builder, params.type_id, index_len, INT_MAX);
113
114 #if 0
115                 uint *buf = pybuffer.buf;
116                 for (uint i = index_len; i--; buf++) {
117                         GPU_indexbuf_add_generic_vert(&builder, *buf);
118                 }
119 #else
120                 memcpy(builder.data, pybuffer.buf, index_len * sizeof(*builder.data));
121                 builder.index_len = index_len;
122 #endif
123                 PyBuffer_Release(&pybuffer);
124         }
125         else {
126                 PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
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                         int values[4];
152                         for (uint i = 0; i < seq_len; i++) {
153                                 PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
154                                 if (seq_fast_item == NULL) {
155                                         PyErr_Format(PyExc_TypeError,
156                                                      "%s: expected a sequence, got %s",
157                                                      error_prefix, Py_TYPE(seq_items[i])->tp_name);
158                                         ok = false;
159                                         goto finally;
160                                 }
161
162                                 ok = PyC_AsArray_FAST(
163                                         values, seq_fast_item, verts_per_prim,
164                                         &PyLong_Type, false, error_prefix) == 0;
165
166                                 if (ok) {
167                                         for (uint j = 0; j < verts_per_prim; j++) {
168                                                 GPU_indexbuf_add_generic_vert(&builder, values[j]);
169                                         }
170                                 }
171                                 Py_DECREF(seq_fast_item);
172                         }
173                 }
174
175                 if (PyErr_Occurred()) {
176                         ok = false;
177                 }
178
179 finally:
180
181                 Py_DECREF(seq_fast);
182         }
183
184         if (ok == false) {
185                 MEM_freeN(builder.data);
186                 return NULL;
187         }
188
189         return BPyGPUIndexBuf_CreatePyObject(GPU_indexbuf_build(&builder));
190 }
191
192 static void bpygpu_IndexBuf_dealloc(BPyGPUIndexBuf *self)
193 {
194         GPU_indexbuf_discard(self->elem);
195         Py_TYPE(self)->tp_free(self);
196 }
197
198 PyDoc_STRVAR(py_gpu_element_doc,
199 ".. class:: GPUIndexBuf(type, seq)\n"
200 "\n"
201 "   Contains an index buffer.\n"
202 "\n"
203 "   :param type: One of these primitive types: {\n"
204 "      `POINTS`,\n"
205 "      `LINES`,\n"
206 "      `TRIS`,\n"
207 "      `LINE_STRIP_ADJ` }\n"
208 "   :type type: `str`\n"
209 "   :param seq: Indices this index buffer will contain.\n"
210 "      Whether a 1D or 2D sequence is required depends on the type.\n"
211 "      Optionally the sequence can support the buffer protocol.\n"
212 "   :type seq: 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 /** \} */