2725b55a5da00da9605d2ba8c6dc8aa9ea25121d
[blender.git] / source / blender / python / gpu / gpu_py_offscreen.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_offscreen.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 #include "BKE_library.h"
41 #include "BKE_scene.h"
42
43 #include "DNA_screen_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_view3d_types.h"
46
47 #include "GPU_framebuffer.h"
48 #include "GPU_texture.h"
49
50 #include "../editors/include/ED_view3d.h"
51
52 #include "../mathutils/mathutils.h"
53
54 #include "../generic/py_capi_utils.h"
55
56 #include "gpu_py.h"
57 #include "gpu_py_offscreen.h" /* own include */
58
59
60  /* -------------------------------------------------------------------- */
61
62  /** \name GPUOffScreen Common Utilities
63   * \{ */
64
65 static int bpygpu_offscreen_valid_check(BPyGPUOffScreen *bpygpu_ofs)
66 {
67         if (UNLIKELY(bpygpu_ofs->ofs == NULL)) {
68                 PyErr_SetString(PyExc_ReferenceError, "GPU offscreen was freed, no further access is valid");
69                 return -1;
70         }
71         return 0;
72 }
73
74 #define BPY_GPU_OFFSCREEN_CHECK_OBJ(bpygpu) { \
75         if (UNLIKELY(bpygpu_offscreen_valid_check(bpygpu) == -1)) { \
76                 return NULL; \
77         } \
78 } ((void)0)
79
80 /** \} */
81
82
83 /* -------------------------------------------------------------------- */
84
85 /** \name GPUOffscreen Type
86  * \{ */
87
88
89 static PyObject *bpygpu_offscreen_new(PyTypeObject *UNUSED(self), PyObject *args, PyObject *kwds)
90 {
91         GPUOffScreen *ofs;
92         int width, height, samples = 0;
93         char err_out[256];
94
95         static const char *_keywords[] = {"width", "height", "samples", NULL};
96         static _PyArg_Parser _parser = {"ii|i:GPUOffScreen.__new__", _keywords, 0};
97         if (!bpygpu_is_initialized() ||
98             !_PyArg_ParseTupleAndKeywordsFast(
99                 args, kwds, &_parser,
100                 &width, &height, &samples))
101         {
102                 return NULL;
103         }
104
105         ofs = GPU_offscreen_create(width, height, samples, true, false, err_out);
106
107         if (ofs == NULL) {
108                 PyErr_Format(PyExc_RuntimeError,
109                              "gpu.offscreen.new(...) failed with '%s'",
110                              err_out[0] ? err_out : "unknown error");
111                 return NULL;
112         }
113
114         return BPyGPUOffScreen_CreatePyObject(ofs);
115 }
116
117 PyDoc_STRVAR(bpygpu_offscreen_width_doc, "Width of the texture.\n\n:type: `int`");
118 static PyObject *bpygpu_offscreen_width_get(BPyGPUOffScreen *self, void *UNUSED(type))
119 {
120         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
121         return PyLong_FromLong(GPU_offscreen_width(self->ofs));
122 }
123
124 PyDoc_STRVAR(bpygpu_offscreen_height_doc, "Height of the texture.\n\n:type: `int`");
125 static PyObject *bpygpu_offscreen_height_get(BPyGPUOffScreen *self, void *UNUSED(type))
126 {
127         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
128         return PyLong_FromLong(GPU_offscreen_height(self->ofs));
129 }
130
131 PyDoc_STRVAR(bpygpu_offscreen_color_texture_doc, "OpenGL bindcode for the color texture.\n\n:type: `int`");
132 static PyObject *bpygpu_offscreen_color_texture_get(BPyGPUOffScreen *self, void *UNUSED(type))
133 {
134         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
135         GPUTexture *texture = GPU_offscreen_color_texture(self->ofs);
136         return PyLong_FromLong(GPU_texture_opengl_bindcode(texture));
137 }
138
139 PyDoc_STRVAR(bpygpu_offscreen_bind_doc,
140 ".. method:: bind(save=True)\n"
141 "\n"
142 "   Bind the offscreen object.\n"
143 "   To make sure that the offscreen gets unbind whether an exception occurs or not, pack it into a `with` statement.\n"
144 "\n"
145 "   :arg save: Save the current OpenGL state, so that it can be restored when unbinding.\n"
146 "   :type save: `bool`\n"
147 );
148 static PyObject *bpygpu_offscreen_bind(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
149 {
150         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
151         bool save = true;
152
153         static const char *_keywords[] = {"save", NULL};
154         static _PyArg_Parser _parser = {"|O&:bind", _keywords, 0};
155         if (!_PyArg_ParseTupleAndKeywordsFast(
156                 args, kwds, &_parser,
157                 PyC_ParseBool, &save))
158         {
159                 return NULL;
160         }
161
162         GPU_offscreen_bind(self->ofs, save);
163
164         self->is_saved = save;
165         Py_INCREF(self);
166
167         return (PyObject *)self;
168 }
169
170 PyDoc_STRVAR(bpygpu_offscreen_unbind_doc,
171 ".. method:: unbind(restore=True)\n"
172 "\n"
173 "   Unbind the offscreen object.\n"
174 "\n"
175 "   :arg restore: Restore the OpenGL state, can only be used when the state has been saved before.\n"
176 "   :type restore: `bool`\n"
177 );
178 static PyObject *bpygpu_offscreen_unbind(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
179 {
180         bool restore = true;
181
182         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
183
184         static const char *_keywords[] = {"restore", NULL};
185         static _PyArg_Parser _parser = {"|O&:unbind", _keywords, 0};
186         if (!_PyArg_ParseTupleAndKeywordsFast(
187                 args, kwds, &_parser,
188                 PyC_ParseBool, &restore))
189         {
190                 return NULL;
191         }
192
193         GPU_offscreen_unbind(self->ofs, restore);
194         Py_RETURN_NONE;
195 }
196
197 PyDoc_STRVAR(bpygpu_offscreen_draw_view3d_doc,
198 ".. method:: draw_view3d(scene, view3d, region, view_matrix, projection_matrix)\n"
199 "\n"
200 "   Draw the 3d viewport in the offscreen object.\n"
201 "\n"
202 "   :arg scene: Scene to draw.\n"
203 "   :type scene: :class:`bpy.types.Scene`\n"
204 "   :arg view_layer: View layer to draw.\n"
205 "   :type view_layer: :class:`bpy.types.ViewLayer`\n"
206 "   :arg view3d: 3D View to get the drawing settings from.\n"
207 "   :type view3d: :class:`bpy.types.SpaceView3D`\n"
208 "   :arg region: Region of the 3D View (required as temporary draw target).\n"
209 "   :type region: :class:`bpy.types.Region`\n"
210 "   :arg view_matrix: View Matrix (e.g. ``camera.matrix_world.inverted()``).\n"
211 "   :type view_matrix: :class:`mathutils.Matrix`\n"
212 "   :arg projection_matrix: Projection Matrix (e.g. ``camera.calc_matrix_camera(...)``).\n"
213 "   :type projection_matrix: :class:`mathutils.Matrix`\n"
214 );
215 static PyObject *bpygpu_offscreen_draw_view3d(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
216 {
217         MatrixObject *py_mat_view, *py_mat_projection;
218         PyObject *py_scene, *py_view_layer, *py_region, *py_view3d;
219
220         struct Depsgraph *depsgraph;
221         struct Scene *scene;
222         struct ViewLayer *view_layer;
223         View3D *v3d;
224         ARegion *ar;
225         struct RV3DMatrixStore *rv3d_mats;
226
227         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
228
229         static const char *_keywords[] = {
230                 "scene", "view_layer", "view3d", "region",
231                 "view_matrix", "projection_matrix", NULL};
232
233         static _PyArg_Parser _parser = {"OOOOO&O&:draw_view3d", _keywords, 0};
234         if (!_PyArg_ParseTupleAndKeywordsFast(
235                 args, kwds, &_parser,
236                 &py_scene, &py_view_layer, &py_view3d, &py_region,
237                 Matrix_Parse4x4, &py_mat_view,
238                 Matrix_Parse4x4, &py_mat_projection) ||
239             (!(scene      = PyC_RNA_AsPointer(py_scene, "Scene")) ||
240              !(view_layer = PyC_RNA_AsPointer(py_view_layer, "ViewLayer")) ||
241              !(v3d        = PyC_RNA_AsPointer(py_view3d, "SpaceView3D")) ||
242              !(ar         = PyC_RNA_AsPointer(py_region, "Region"))))
243         {
244                 return NULL;
245         }
246
247         BLI_assert(BKE_id_is_in_global_main(&scene->id));
248
249         depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
250
251         rv3d_mats = ED_view3d_mats_rv3d_backup(ar->regiondata);
252
253         GPU_offscreen_bind(self->ofs, true);
254
255         ED_view3d_draw_offscreen(depsgraph,
256                                  scene,
257                                  v3d->shading.type,
258                                  v3d,
259                                  ar,
260                                  GPU_offscreen_width(self->ofs),
261                                  GPU_offscreen_height(self->ofs),
262                                  (float(*)[4])py_mat_view->matrix,
263                                  (float(*)[4])py_mat_projection->matrix,
264                                  false,
265                                  true,
266                                  "",
267                                  NULL,
268                                  self->ofs,
269                                  NULL);
270
271         GPU_offscreen_unbind(self->ofs, true);
272
273         ED_view3d_mats_rv3d_restore(ar->regiondata, rv3d_mats);
274         MEM_freeN(rv3d_mats);
275
276         Py_RETURN_NONE;
277 }
278
279 PyDoc_STRVAR(bpygpu_offscreen_free_doc,
280 ".. method:: free()\n"
281 "\n"
282 "   Free the offscreen object.\n"
283 "   The framebuffer, texture and render objects will no longer be accessible.\n"
284 );
285 static PyObject *bpygpu_offscreen_free(BPyGPUOffScreen *self)
286 {
287         BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
288
289         GPU_offscreen_free(self->ofs);
290         self->ofs = NULL;
291         Py_RETURN_NONE;
292 }
293
294 static PyObject *bpygpu_offscreen_bind_context_enter(BPyGPUOffScreen *UNUSED(self))
295 {
296         Py_RETURN_NONE;
297 }
298
299 static PyObject *bpygpu_offscreen_bind_context_exit(BPyGPUOffScreen *self, PyObject *UNUSED(args))
300 {
301         GPU_offscreen_unbind(self->ofs, self->is_saved);
302         Py_RETURN_NONE;
303 }
304
305 static void BPyGPUOffScreen__tp_dealloc(BPyGPUOffScreen *self)
306 {
307         if (self->ofs)
308                 GPU_offscreen_free(self->ofs);
309         Py_TYPE(self)->tp_free((PyObject *)self);
310 }
311
312 static PyGetSetDef bpygpu_offscreen_getseters[] = {
313         {(char *)"color_texture", (getter)bpygpu_offscreen_color_texture_get, (setter)NULL, bpygpu_offscreen_color_texture_doc, NULL},
314         {(char *)"width", (getter)bpygpu_offscreen_width_get, (setter)NULL, bpygpu_offscreen_width_doc, NULL},
315         {(char *)"height", (getter)bpygpu_offscreen_height_get, (setter)NULL, bpygpu_offscreen_height_doc, NULL},
316         {NULL, NULL, NULL, NULL, NULL}  /* Sentinel */
317 };
318
319 static struct PyMethodDef bpygpu_offscreen_methods[] = {
320         {"bind", (PyCFunction)bpygpu_offscreen_bind, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_bind_doc},
321         {"unbind", (PyCFunction)bpygpu_offscreen_unbind, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_unbind_doc},
322         {"draw_view3d", (PyCFunction)bpygpu_offscreen_draw_view3d, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_draw_view3d_doc},
323         {"free", (PyCFunction)bpygpu_offscreen_free, METH_NOARGS, bpygpu_offscreen_free_doc},
324         {"__enter__", (PyCFunction)bpygpu_offscreen_bind_context_enter, METH_NOARGS},
325         {"__exit__",  (PyCFunction)bpygpu_offscreen_bind_context_exit,  METH_VARARGS},
326         {NULL, NULL, 0, NULL}
327 };
328
329 PyDoc_STRVAR(bpygpu_offscreen_doc,
330 ".. class:: GPUOffScreen(width, height, samples=0)\n"
331 "\n"
332 "   This object gives access to off screen buffers.\n"
333 "\n"
334 "   :arg width: Horizontal dimension of the buffer.\n"
335 "   :type width: `int`\n"
336 "   :arg height: Vertical dimension of the buffer.\n"
337 "   :type height: `int`\n"
338 "   :arg samples: OpenGL samples to use for MSAA or zero to disable.\n"
339 "   :type samples: `int`\n"
340 );
341 PyTypeObject BPyGPUOffScreen_Type = {
342         PyVarObject_HEAD_INIT(NULL, 0)
343         .tp_name = "GPUOffScreen",
344         .tp_basicsize = sizeof(BPyGPUOffScreen),
345         .tp_dealloc = (destructor)BPyGPUOffScreen__tp_dealloc,
346         .tp_flags = Py_TPFLAGS_DEFAULT,
347         .tp_doc = bpygpu_offscreen_doc,
348         .tp_methods = bpygpu_offscreen_methods,
349         .tp_getset = bpygpu_offscreen_getseters,
350         .tp_new = bpygpu_offscreen_new,
351 };
352
353 /** \} */
354
355
356 /* -------------------------------------------------------------------- */
357
358 /** \name Public API
359  * \{ */
360
361 PyObject *BPyGPUOffScreen_CreatePyObject(GPUOffScreen *ofs)
362 {
363         BPyGPUOffScreen *self;
364
365         self = PyObject_New(BPyGPUOffScreen, &BPyGPUOffScreen_Type);
366         self->ofs = ofs;
367
368         return (PyObject *)self;
369 }
370
371 /** \} */
372
373 #undef BPY_GPU_OFFSCREEN_CHECK_OBJ