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_api.h"
40 #include "gpu_py_element.h" /* own include */
41
42
43 /* -------------------------------------------------------------------- */
44 /** \name IndexBuf Type
45  * \{ */
46
47 static PyObject *bpygpu_IndexBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
48 {
49         BPYGPU_IS_INIT_OR_ERROR_OBJ;
50
51         const char *error_prefix = "IndexBuf.__new__";
52         bool ok = true;
53
54         struct {
55                 GPUPrimType type_id;
56                 PyObject *seq;
57         } params;
58
59         uint verts_per_prim;
60         uint index_len;
61         GPUIndexBufBuilder builder;
62
63         static const char *_keywords[] = {"type", "seq", NULL};
64         static _PyArg_Parser _parser = {"$O&O:IndexBuf.__new__", _keywords, 0};
65         if (!_PyArg_ParseTupleAndKeywordsFast(
66                 args, kwds, &_parser,
67                 bpygpu_ParsePrimType, &params.type_id,
68                 &params.seq))
69         {
70                 return NULL;
71         }
72
73         verts_per_prim = GPU_indexbuf_primitive_len(params.type_id);
74         if (verts_per_prim == -1) {
75                 PyErr_Format(PyExc_ValueError,
76                              "The argument 'type' must be "
77                              "'POINTS', 'LINES', 'TRIS' or 'LINES_ADJ'");
78                 return NULL;
79         }
80
81         if (PyObject_CheckBuffer(params.seq)) {
82                 Py_buffer pybuffer;
83
84                 if (PyObject_GetBuffer(params.seq, &pybuffer, PyBUF_FORMAT | PyBUF_ND) == -1) {
85                         /* PyObject_GetBuffer already handles error messages. */
86                         return NULL;
87                 }
88
89                 if (pybuffer.ndim != 1 && pybuffer.shape[1] != verts_per_prim) {
90                         PyErr_Format(PyExc_ValueError,
91                                      "Each primitive must exactly %d indices",
92                                      verts_per_prim);
93                         return NULL;
94                 }
95
96                 if (pybuffer.itemsize != 4 ||
97                     PyC_StructFmt_type_is_float_any(PyC_StructFmt_type_from_str(pybuffer.format)))
98                 {
99                         PyErr_Format(PyExc_ValueError,
100                                      "Each index must be an 4-bytes integer value");
101                         return NULL;
102                 }
103
104                 index_len = pybuffer.shape[0];
105                 if (pybuffer.ndim != 1) {
106                         index_len *= pybuffer.shape[1];
107                 }
108
109                 /* The `vertex_len` parameter is only used for asserts in the Debug build. */
110                 /* Not very useful in python since scripts are often tested in Release build. */
111                 /* Use `INT_MAX` instead of the actual number of vertices. */
112                 GPU_indexbuf_init(
113                         &builder, params.type_id, index_len, INT_MAX);
114
115 #if 0
116                 uint *buf = pybuffer.buf;
117                 for (uint i = index_len; i--; buf++) {
118                         GPU_indexbuf_add_generic_vert(&builder, *buf);
119                 }
120 #else
121                 memcpy(builder.data, pybuffer.buf, index_len * sizeof(*builder.data));
122                 builder.index_len = index_len;
123 #endif
124                 PyBuffer_Release(&pybuffer);
125         }
126         else {
127                 PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
128
129                 if (seq_fast == NULL) {
130                         return false;
131                 }
132
133                 const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
134
135                 PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
136
137                 index_len = seq_len * verts_per_prim;
138
139                 /* The `vertex_len` parameter is only used for asserts in the Debug build. */
140                 /* Not very useful in python since scripts are often tested in Release build. */
141                 /* Use `INT_MAX` instead of the actual number of vertices. */
142                 GPU_indexbuf_init(
143                         &builder, params.type_id, index_len, INT_MAX);
144
145                 if (verts_per_prim == 1) {
146                         for (uint i = 0; i < seq_len; i++) {
147                                 GPU_indexbuf_add_generic_vert(
148                                         &builder, PyC_Long_AsU32(seq_items[i]));
149                         }
150                 }
151                 else {
152                         int values[4];
153                         for (uint i = 0; i < seq_len; i++) {
154                                 PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
155                                 if (seq_fast_item == NULL) {
156                                         PyErr_Format(PyExc_TypeError,
157                                                      "%s: expected a sequence, got %s",
158                                                      error_prefix, Py_TYPE(seq_items[i])->tp_name);
159                                         ok = false;
160                                         goto finally;
161                                 }
162
163                                 ok = PyC_AsArray_FAST(
164                                         values, seq_fast_item, verts_per_prim,
165                                         &PyLong_Type, false, error_prefix) == 0;
166
167                                 if (ok) {
168                                         for (uint j = 0; j < verts_per_prim; j++) {
169                                                 GPU_indexbuf_add_generic_vert(&builder, values[j]);
170                                         }
171                                 }
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
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 ".. class:: GPUIndexBuf(type, seq)\n"
201 "\n"
202 "   Contains an index buffer.\n"
203 "\n"
204 "   :param type: One of these primitive types: {\n"
205 "      `POINTS`,\n"
206 "      `LINES`,\n"
207 "      `TRIS`,\n"
208 "      `LINE_STRIP_ADJ` }\n"
209 "   :type type: `str`\n"
210 "   :param seq: Indices this index buffer will contain.\n"
211 "      Whether a 1D or 2D sequence is required depends on the type.\n"
212 "      Optionally the sequence can support the buffer protocol.\n"
213 "   :type seq: 1D or 2D sequence\n"
214 );
215 PyTypeObject BPyGPUIndexBuf_Type = {
216         PyVarObject_HEAD_INIT(NULL, 0)
217         .tp_name = "GPUIndexBuf",
218         .tp_basicsize = sizeof(BPyGPUIndexBuf),
219         .tp_dealloc = (destructor)bpygpu_IndexBuf_dealloc,
220         .tp_flags = Py_TPFLAGS_DEFAULT,
221         .tp_doc = py_gpu_element_doc,
222         .tp_new = bpygpu_IndexBuf_new,
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 /** \} */