aa687ecaff50da13b0f06a2facc600c142bdb908
[blender.git] / source / blender / python / gpu / gpu_py_batch.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  * Copyright 2015, Blender Foundation.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/gpu/gpu_py_batch.c
24  *  \ingroup bpygpu
25  *
26  * This file defines the offscreen functionalities of the 'gpu' module
27  * used for off-screen OpenGL rendering.
28  *
29  * - Use ``bpygpu_`` for local API.
30  * - Use ``BPyGPU`` for public API.
31  */
32
33 #include <Python.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_utildefines.h"
38
39 #include "BKE_global.h"
40
41 #include "GPU_batch.h"
42
43 #include "../mathutils/mathutils.h"
44
45 #include "../generic/py_capi_utils.h"
46
47 #include "gpu_py.h"
48 #include "gpu_py_shader.h"
49 #include "gpu_py_vertex_buffer.h"
50 #include "gpu_py_element.h"
51 #include "gpu_py_batch.h" /* own include */
52
53
54 /* -------------------------------------------------------------------- */
55 /** \name Utility Functions
56  * \{ */
57
58 static bool bpygpu_batch_is_program_or_error(BPyGPUBatch *self)
59 {
60         if (!glIsProgram(self->batch->program)) {
61                 PyErr_SetString(
62                         PyExc_RuntimeError,
63                         "batch does not have any program assigned to it");
64                 return false;
65         }
66         return true;
67 }
68
69 /** \} */
70
71
72 /* -------------------------------------------------------------------- */
73 /** \name GPUBatch Type
74  * \{ */
75
76 static PyObject *bpygpu_Batch_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
77 {
78         const char *exc_str_missing_arg = "GPUBatch.__new__() missing required argument '%s' (pos %d)";
79
80         struct {
81                 GPUPrimType type_id;
82                 BPyGPUVertBuf *py_vertbuf;
83                 BPyGPUIndexBuf *py_indexbuf;
84         } params = {GPU_PRIM_NONE, NULL, NULL};
85
86         static const char *_keywords[] = {"type", "buf", "elem", NULL};
87         static _PyArg_Parser _parser = {"|$O&O!O!:GPUBatch.__new__", _keywords, 0};
88         if (!bpygpu_is_initialized() ||
89             !_PyArg_ParseTupleAndKeywordsFast(
90                 args, kwds, &_parser,
91                 bpygpu_ParsePrimType, &params.type_id,
92                 &BPyGPUVertBuf_Type, &params.py_vertbuf,
93                 &BPyGPUIndexBuf_Type, &params.py_indexbuf))
94         {
95                 return NULL;
96         }
97
98         if (params.type_id == GPU_PRIM_NONE) {
99                 PyErr_Format(PyExc_TypeError,
100                              exc_str_missing_arg, _keywords[0], 1);
101                 return NULL;
102         }
103
104         if (params.py_vertbuf == NULL) {
105                 PyErr_Format(PyExc_TypeError,
106                              exc_str_missing_arg, _keywords[1], 2);
107                 return NULL;
108         }
109
110         GPUBatch *batch = GPU_batch_create(
111                 params.type_id,
112                 params.py_vertbuf->buf,
113                 params.py_indexbuf ? params.py_indexbuf->elem : NULL);
114
115         BPyGPUBatch *ret = (BPyGPUBatch *)BPyGPUBatch_CreatePyObject(batch);
116
117 #ifdef USE_GPU_PY_REFERENCES
118         ret->references = PyList_New(params.py_indexbuf ? 2 : 1);
119         PyList_SET_ITEM(ret->references, 0, (PyObject *)params.py_vertbuf);
120         Py_INCREF(params.py_vertbuf);
121
122         if (params.py_indexbuf != NULL) {
123                 PyList_SET_ITEM(ret->references, 1, (PyObject *)params.py_indexbuf);
124                 Py_INCREF(params.py_indexbuf);
125         }
126
127         PyObject_GC_Track(ret);
128 #endif
129
130         return (PyObject *)ret;
131 }
132
133 PyDoc_STRVAR(bpygpu_Batch_vertbuf_add_doc,
134 ".. method:: vertbuf_add(buf)\n"
135 "\n"
136 "   Add another vertex buffer to the Batch.\n"
137 "   It is not possible to add more vertices to the batch using this method.\n"
138 "   Instead it can be used to add more attributes to the existing vertices.\n"
139 "   A good use case would be when you have a separate vertex buffer for vertex positions and vertex normals.\n"
140 "   Current a batch can have at most " STRINGIFY(GPU_BATCH_VBO_MAX_LEN) " vertex buffers.\n"
141 "\n"
142 "   :param buf: The vertex buffer that will be added to the batch.\n"
143 "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
144 );
145 static PyObject *bpygpu_Batch_vertbuf_add(BPyGPUBatch *self, BPyGPUVertBuf *py_buf)
146 {
147         if (!BPyGPUVertBuf_Check(py_buf)) {
148                 PyErr_Format(PyExc_TypeError,
149                              "Expected a GPUVertBuf, got %s",
150                              Py_TYPE(py_buf)->tp_name);
151                 return NULL;
152         }
153
154         if (self->batch->verts[0]->vertex_len != py_buf->buf->vertex_len) {
155                 PyErr_Format(PyExc_TypeError,
156                              "Expected %d length, got %d",
157                              self->batch->verts[0]->vertex_len, py_buf->buf->vertex_len);
158                 return NULL;
159         }
160
161         if (self->batch->verts[GPU_BATCH_VBO_MAX_LEN - 1] != NULL) {
162                 PyErr_SetString(
163                         PyExc_RuntimeError,
164                         "Maximum number of vertex buffers exceeded: " STRINGIFY(GPU_BATCH_VBO_MAX_LEN));
165                 return NULL;
166         }
167
168 #ifdef USE_GPU_PY_REFERENCES
169         /* Hold user */
170         PyList_Append(self->references, (PyObject *)py_buf);
171 #endif
172
173         GPU_batch_vertbuf_add(self->batch, py_buf->buf);
174         Py_RETURN_NONE;
175 }
176
177 PyDoc_STRVAR(bpygpu_Batch_program_set_doc,
178 ".. method:: program_set(program)\n"
179 "\n"
180 "   Assign a shader to this batch that will be used for drawing when not overwritten later.\n"
181 "   Note: This method has to be called in the draw context that the batch will be drawn in.\n"
182 "   This function does not need to be called when you always set the shader when calling `batch.draw`.\n"
183 "\n"
184 "   :param program: The program/shader the batch will use in future draw calls.\n"
185 "   :type program: :class:`gpu.types.GPUShader`\n"
186 );
187 static PyObject *bpygpu_Batch_program_set(BPyGPUBatch *self, BPyGPUShader *py_shader)
188 {
189         if (!BPyGPUShader_Check(py_shader)) {
190                 PyErr_Format(PyExc_TypeError,
191                              "Expected a GPUShader, got %s",
192                              Py_TYPE(py_shader)->tp_name);
193                 return NULL;
194         }
195
196         GPUShader *shader = py_shader->shader;
197         GPU_batch_program_set(
198                 self->batch,
199                 GPU_shader_get_program(shader),
200                 GPU_shader_get_interface(shader));
201
202 #ifdef USE_GPU_PY_REFERENCES
203         /* Remove existing user (if any), hold new user. */
204         int i = PyList_GET_SIZE(self->references);
205         while (--i != -1) {
206                 PyObject *py_shader_test = PyList_GET_ITEM(self->references, i);
207                 if (BPyGPUShader_Check(py_shader_test)) {
208                         PyList_SET_ITEM(self->references, i, (PyObject *)py_shader);
209                         Py_INCREF(py_shader);
210                         Py_DECREF(py_shader_test);
211                         /* Only ever reference one shader. */
212                         break;
213                 }
214         }
215         if (i != -1) {
216                 PyList_Append(self->references, (PyObject *)py_shader);
217         }
218 #endif
219
220         Py_RETURN_NONE;
221 }
222
223 PyDoc_STRVAR(bpygpu_Batch_draw_doc,
224 ".. method:: draw(program=None)\n"
225 "\n"
226 "   Run the drawing program with the parameters assigned to the batch.\n"
227 "\n"
228 "   :param program: Program that performs the drawing operations.\n"
229 "      If ``None`` is passed, the last program setted to this batch will run.\n"
230 "   :type program: :class:`gpu.types.GPUShader`\n"
231 );
232 static PyObject *bpygpu_Batch_draw(BPyGPUBatch *self, PyObject *args)
233 {
234         BPyGPUShader *py_program = NULL;
235
236         if (!PyArg_ParseTuple(
237                 args, "|O!:GPUBatch.draw",
238                 &BPyGPUShader_Type, &py_program))
239         {
240                 return NULL;
241         }
242         else if (py_program == NULL) {
243                 if (!bpygpu_batch_is_program_or_error(self)) {
244                         return NULL;
245                 }
246         }
247         else if (self->batch->program != GPU_shader_get_program(py_program->shader)) {
248                 GPU_batch_program_set(
249                         self->batch,
250                         GPU_shader_get_program(py_program->shader),
251                         GPU_shader_get_interface(py_program->shader));
252         }
253
254         GPU_batch_draw(self->batch);
255         Py_RETURN_NONE;
256 }
257
258 static PyObject *bpygpu_Batch_program_use_begin(BPyGPUBatch *self)
259 {
260         if (!bpygpu_batch_is_program_or_error(self)) {
261                 return NULL;
262         }
263         GPU_batch_program_use_begin(self->batch);
264         Py_RETURN_NONE;
265 }
266
267 static PyObject *bpygpu_Batch_program_use_end(BPyGPUBatch *self)
268 {
269         if (!bpygpu_batch_is_program_or_error(self)) {
270                 return NULL;
271         }
272         GPU_batch_program_use_end(self->batch);
273         Py_RETURN_NONE;
274 }
275
276 static struct PyMethodDef bpygpu_Batch_methods[] = {
277         {"vertbuf_add", (PyCFunction)bpygpu_Batch_vertbuf_add,
278          METH_O, bpygpu_Batch_vertbuf_add_doc},
279         {"program_set", (PyCFunction)bpygpu_Batch_program_set,
280          METH_O, bpygpu_Batch_program_set_doc},
281         {"draw", (PyCFunction) bpygpu_Batch_draw,
282          METH_VARARGS, bpygpu_Batch_draw_doc},
283         {"_program_use_begin", (PyCFunction)bpygpu_Batch_program_use_begin,
284          METH_NOARGS, ""},
285         {"_program_use_end", (PyCFunction)bpygpu_Batch_program_use_end,
286          METH_NOARGS, ""},
287         {NULL, NULL, 0, NULL}
288 };
289
290 #ifdef USE_GPU_PY_REFERENCES
291
292 static int bpygpu_Batch_traverse(BPyGPUBatch *self, visitproc visit, void *arg)
293 {
294         Py_VISIT(self->references);
295         return 0;
296 }
297
298 static int bpygpu_Batch_clear(BPyGPUBatch *self)
299 {
300         Py_CLEAR(self->references);
301         return 0;
302 }
303
304 #endif
305
306 static void bpygpu_Batch_dealloc(BPyGPUBatch *self)
307 {
308         GPU_batch_discard(self->batch);
309
310 #ifdef USE_GPU_PY_REFERENCES
311         if (self->references) {
312                 PyObject_GC_UnTrack(self);
313                 bpygpu_Batch_clear(self);
314                 Py_XDECREF(self->references);
315         }
316 #endif
317
318         Py_TYPE(self)->tp_free(self);
319 }
320
321 PyDoc_STRVAR(py_gpu_batch_doc,
322 ".. class:: GPUBatch(type, buf, elem=None)\n"
323 "\n"
324 "   Reusable container for drawable geometry.\n"
325 "\n"
326 "   :arg type: One of these primitive types: {\n"
327 "       `POINTS`,\n"
328 "       `LINES`,\n"
329 "       `TRIS`,\n"
330 "       `LINE_STRIP`,\n"
331 "       `LINE_LOOP`,\n"
332 "       `TRI_STRIP`,\n"
333 "       `TRI_FAN`,\n"
334 "       `LINES_ADJ`,\n"
335 "       `TRIS_ADJ`,\n"
336 "       `LINE_STRIP_ADJ` }\n"
337 "   :type type: `str`\n"
338 "   :arg buf: Vertex buffer containing all or some of the attributes required for drawing.\n"
339 "   :type buf: :class:`gpu.types.GPUVertBuf`\n"
340 "   :arg elem: An optional index buffer.\n"
341 "   :type elem: :class:`gpu.types.GPUIndexBuf`\n"
342 );
343 PyTypeObject BPyGPUBatch_Type = {
344         PyVarObject_HEAD_INIT(NULL, 0)
345         .tp_name = "GPUBatch",
346         .tp_basicsize = sizeof(BPyGPUBatch),
347         .tp_dealloc = (destructor)bpygpu_Batch_dealloc,
348 #ifdef USE_GPU_PY_REFERENCES
349         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
350         .tp_doc = py_gpu_batch_doc,
351         .tp_traverse = (traverseproc)bpygpu_Batch_traverse,
352         .tp_clear = (inquiry)bpygpu_Batch_clear,
353 #else
354         .tp_flags = Py_TPFLAGS_DEFAULT,
355 #endif
356         .tp_methods = bpygpu_Batch_methods,
357         .tp_new = bpygpu_Batch_new,
358 };
359
360 /** \} */
361
362
363 /* -------------------------------------------------------------------- */
364 /** \name Public API
365 * \{ */
366
367 PyObject *BPyGPUBatch_CreatePyObject(GPUBatch *batch)
368 {
369         BPyGPUBatch *self;
370
371 #ifdef USE_GPU_PY_REFERENCES
372         self = (BPyGPUBatch *)_PyObject_GC_New(&BPyGPUBatch_Type);
373         self->references = NULL;
374 #else
375         self = PyObject_New(BPyGPUBatch, &BPyGPUBatch_Type);
376 #endif
377
378         self->batch = batch;
379
380         return (PyObject *)self;
381 }
382
383 /** \} */
384
385 #undef BPY_GPU_BATCH_CHECK_OBJ