This repository has been archived on 2023-10-09. You can view files and clone it, but cannot push or open issues or pull requests.
Files
blender-archive/source/blender/python/gpu/gpu_py_offscreen.c

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

498 lines
16 KiB
C
Raw Normal View History

/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright 2015, Blender Foundation.
*/
/** \file
* \ingroup bpygpu
*
* This file defines the offscreen functionalities of the 'gpu' module
* used for off-screen OpenGL rendering.
*
* - Use `bpygpu_` for local API.
* - Use `BPyGPU` for public API.
*/
#include <Python.h>
#include "MEM_guardedalloc.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "BKE_global.h"
#include "BKE_lib_id.h"
#include "BKE_scene.h"
2018-09-06 10:47:10 +10:00
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "DNA_view3d_types.h"
#include "GPU_context.h"
#include "GPU_framebuffer.h"
#include "GPU_texture.h"
#include "GPU_viewport.h"
#include "ED_view3d.h"
#include "ED_view3d_offscreen.h"
#include "../mathutils/mathutils.h"
#include "../generic/py_capi_utils.h"
#include "gpu_py.h"
#include "gpu_py_texture.h"
#include "gpu_py_offscreen.h" /* own include */
/* Define the free method to avoid breakage. */
#define BPYGPU_USE_GPUOBJ_FREE_METHOD
2019-03-19 15:17:46 +11:00
/* -------------------------------------------------------------------- */
/** \name GPUOffScreen Common Utilities
* \{ */
static int pygpu_offscreen_valid_check(BPyGPUOffScreen *py_ofs)
{
if (UNLIKELY(py_ofs->ofs == NULL)) {
PyErr_SetString(PyExc_ReferenceError,
#ifdef BPYGPU_USE_GPUOBJ_FREE_METHOD
"GPU offscreen was freed, no further access is valid"
#else
"GPU offscreen: internal error"
#endif
);
return -1;
}
return 0;
}
#define BPY_GPU_OFFSCREEN_CHECK_OBJ(bpygpu) \
{ \
if (UNLIKELY(pygpu_offscreen_valid_check(bpygpu) == -1)) { \
return NULL; \
} \
} \
((void)0)
/** \} */
/* -------------------------------------------------------------------- */
/** \name Stack (Context Manager)
*
* Safer alternative to ensure balanced push/pop calls.
*
* \{ */
typedef struct {
PyObject_HEAD /* Required Python macro. */
BPyGPUOffScreen *py_offscreen;
int level;
bool is_explicitly_bound; /* Bound by "bind" method. */
} OffScreenStackContext;
static void pygpu_offscreen_stack_context__tp_dealloc(OffScreenStackContext *self)
{
2021-03-08 14:40:57 +11:00
Py_DECREF(self->py_offscreen);
PyObject_DEL(self);
}
static PyObject *pygpu_offscreen_stack_context_enter(OffScreenStackContext *self)
{
2021-03-08 14:40:57 +11:00
BPY_GPU_OFFSCREEN_CHECK_OBJ(self->py_offscreen);
if (!self->is_explicitly_bound) {
if (self->level != -1) {
PyErr_SetString(PyExc_RuntimeError, "Already in use");
return NULL;
}
2021-03-08 14:40:57 +11:00
GPU_offscreen_bind(self->py_offscreen->ofs, true);
self->level = GPU_framebuffer_stack_level_get();
}
Py_RETURN_NONE;
}
static PyObject *pygpu_offscreen_stack_context_exit(OffScreenStackContext *self,
PyObject *UNUSED(args))
{
2021-03-08 14:40:57 +11:00
BPY_GPU_OFFSCREEN_CHECK_OBJ(self->py_offscreen);
if (self->level == -1) {
PyErr_SetString(PyExc_RuntimeError, "Not yet in use\n");
return NULL;
}
const int level = GPU_framebuffer_stack_level_get();
if (level != self->level) {
PyErr_Format(
PyExc_RuntimeError, "Level of bind mismatch, expected %d, got %d\n", self->level, level);
}
2021-03-08 14:40:57 +11:00
GPU_offscreen_unbind(self->py_offscreen->ofs, true);
Py_RETURN_NONE;
}
static PyMethodDef pygpu_offscreen_stack_context__tp_methods[] = {
{"__enter__", (PyCFunction)pygpu_offscreen_stack_context_enter, METH_NOARGS},
{"__exit__", (PyCFunction)pygpu_offscreen_stack_context_exit, METH_VARARGS},
{NULL},
};
static PyTypeObject PyGPUOffscreenStackContext_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUFrameBufferStackContext",
.tp_basicsize = sizeof(OffScreenStackContext),
.tp_dealloc = (destructor)pygpu_offscreen_stack_context__tp_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_methods = pygpu_offscreen_stack_context__tp_methods,
};
PyDoc_STRVAR(pygpu_offscreen_bind_doc,
".. function:: bind()\n"
"\n"
" Context manager to ensure balanced bind calls, even in the case of an error.\n");
static PyObject *pygpu_offscreen_bind(BPyGPUOffScreen *self)
{
OffScreenStackContext *ret = PyObject_New(OffScreenStackContext,
&PyGPUOffscreenStackContext_Type);
2021-03-08 14:40:57 +11:00
ret->py_offscreen = self;
ret->level = -1;
ret->is_explicitly_bound = false;
Py_INCREF(self);
pygpu_offscreen_stack_context_enter(ret);
ret->is_explicitly_bound = true;
return (PyObject *)ret;
}
PyDoc_STRVAR(pygpu_offscreen_unbind_doc,
".. method:: unbind(restore=True)\n"
"\n"
" Unbind the offscreen object.\n"
"\n"
" :arg restore: Restore the OpenGL state, can only be used when the state has been "
"saved before.\n"
" :type restore: bool\n");
static PyObject *pygpu_offscreen_unbind(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
{
bool restore = true;
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
static const char *_keywords[] = {"restore", NULL};
PyAPI: use keyword only arguments Use keyword only arguments for the following functions. - addon_utils.module_bl_info 2nd arg `info_basis`. - addon_utils.modules 1st `module_cache`, 2nd arg `refresh`. - addon_utils.modules_refresh 1st arg `module_cache`. - bl_app_template_utils.activate 1nd arg `template_id`. - bl_app_template_utils.import_from_id 2nd arg `ignore_not_found`. - bl_app_template_utils.import_from_path 2nd arg `ignore_not_found`. - bl_keymap_utils.keymap_from_toolbar.generate 2nd & 3rd args `use_fallback_keys` & `use_reset`. - bl_keymap_utils.platform_helpers.keyconfig_data_oskey_from_ctrl 2nd arg `filter_fn`. - bl_ui_utils.bug_report_url.url_prefill_from_blender 1st arg `addon_info`. - bmesh.types.BMFace.copy 1st & 2nd args `verts`, `edges`. - bmesh.types.BMesh.calc_volume 1st arg `signed`. - bmesh.types.BMesh.from_mesh 2nd..4th args `face_normals`, `use_shape_key`, `shape_key_index`. - bmesh.types.BMesh.from_object 3rd & 4th args `cage`, `face_normals`. - bmesh.types.BMesh.transform 2nd arg `filter`. - bmesh.types.BMesh.update_edit_mesh 2nd & 3rd args `loop_triangles`, `destructive`. - bmesh.types.{BMVertSeq,BMEdgeSeq,BMFaceSeq}.sort 1st & 2nd arg `key`, `reverse`. - bmesh.utils.face_split 4th..6th args `coords`, `use_exist`, `example`. - bpy.data.libraries.load 2nd..4th args `link`, `relative`, `assets_only`. - bpy.data.user_map 1st..3rd args `subset`, `key_types, `value_types`. - bpy.msgbus.subscribe_rna 5th arg `options`. - bpy.path.abspath 2nd & 3rd args `start` & `library`. - bpy.path.clean_name 2nd arg `replace`. - bpy.path.ensure_ext 3rd arg `case_sensitive`. - bpy.path.module_names 2nd arg `recursive`. - bpy.path.relpath 2nd arg `start`. - bpy.types.EditBone.transform 2nd & 3rd arg `scale`, `roll`. - bpy.types.Operator.as_keywords 1st arg `ignore`. - bpy.types.Struct.{keyframe_insert,keyframe_delete} 2nd..5th args `index`, `frame`, `group`, `options`. - bpy.types.WindowManager.popup_menu 2nd & 3rd arg `title`, `icon`. - bpy.types.WindowManager.popup_menu_pie 3rd & 4th arg `title`, `icon`. - bpy.utils.app_template_paths 1st arg `subdir`. - bpy.utils.app_template_paths 1st arg `subdir`. - bpy.utils.blend_paths 1st..3rd args `absolute`, `packed`, `local`. - bpy.utils.execfile 2nd arg `mod`. - bpy.utils.keyconfig_set 2nd arg `report`. - bpy.utils.load_scripts 1st & 2nd `reload_scripts` & `refresh_scripts`. - bpy.utils.preset_find 3rd & 4th args `display_name`, `ext`. - bpy.utils.resource_path 2nd & 3rd arg `major`, `minor`. - bpy.utils.script_paths 1st..4th args `subdir`, `user_pref`, `check_all`, `use_user`. - bpy.utils.smpte_from_frame 2nd & 3rd args `fps`, `fps_base`. - bpy.utils.smpte_from_seconds 2nd & 3rd args `fps`, `fps_base`. - bpy.utils.system_resource 2nd arg `subdir`. - bpy.utils.time_from_frame 2nd & 3rd args `fps`, `fps_base`. - bpy.utils.time_to_frame 2nd & 3rd args `fps`, `fps_base`. - bpy.utils.units.to_string 4th..6th `precision`, `split_unit`, `compatible_unit`. - bpy.utils.units.to_value 4th arg `str_ref_unit`. - bpy.utils.user_resource 2nd & 3rd args `subdir`, `create` - bpy_extras.view3d_utils.location_3d_to_region_2d 4th arg `default`. - bpy_extras.view3d_utils.region_2d_to_origin_3d 4th arg `clamp`. - gpu.offscreen.unbind 1st arg `restore`. - gpu_extras.batch.batch_for_shader 4th arg `indices`. - gpu_extras.batch.presets.draw_circle_2d 4th arg `segments`. - gpu_extras.presets.draw_circle_2d 4th arg `segments`. - imbuf.types.ImBuf.resize 2nd arg `resize`. - imbuf.write 2nd arg `filepath`. - mathutils.kdtree.KDTree.find 2nd arg `filter`. - nodeitems_utils.NodeCategory 3rd & 4th arg `descriptions`, `items`. - nodeitems_utils.NodeItem 2nd..4th args `label`, `settings`, `poll`. - nodeitems_utils.NodeItemCustom 1st & 2nd arg `poll`, `draw`. - rna_prop_ui.draw 5th arg `use_edit`. - rna_prop_ui.rna_idprop_ui_get 2nd arg `create`. - rna_prop_ui.rna_idprop_ui_prop_clear 3rd arg `remove`. - rna_prop_ui.rna_idprop_ui_prop_get 3rd arg `create`. - rna_xml.xml2rna 2nd arg `root_rna`. - rna_xml.xml_file_write 4th arg `skip_typemap`.
2021-06-08 18:03:14 +10:00
static _PyArg_Parser _parser = {"|$O&:unbind", _keywords, 0};
if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, PyC_ParseBool, &restore)) {
return NULL;
}
GPU_offscreen_unbind(self->ofs, restore);
GPU_apply_state();
Py_RETURN_NONE;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name GPUOffscreen Type
* \{ */
static PyObject *pygpu_offscreen__tp_new(PyTypeObject *UNUSED(self),
PyObject *args,
PyObject *kwds)
{
BPYGPU_IS_INIT_OR_ERROR_OBJ;
GPUOffScreen *ofs = NULL;
int width, height;
char err_out[256];
static const char *_keywords[] = {"width", "height", NULL};
static _PyArg_Parser _parser = {"ii:GPUOffScreen.__new__", _keywords, 0};
if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, &width, &height)) {
return NULL;
}
if (GPU_context_active_get()) {
ofs = GPU_offscreen_create(width, height, true, GPU_RGBA8, err_out);
}
else {
STRNCPY(err_out, "No active GPU context found");
}
if (ofs == NULL) {
PyErr_Format(PyExc_RuntimeError,
"gpu.offscreen.new(...) failed with '%s'",
err_out[0] ? err_out : "unknown error");
return NULL;
}
return BPyGPUOffScreen_CreatePyObject(ofs);
}
PyDoc_STRVAR(pygpu_offscreen_width_doc, "Width of the texture.\n\n:type: `int`");
static PyObject *pygpu_offscreen_width_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
return PyLong_FromLong(GPU_offscreen_width(self->ofs));
}
PyDoc_STRVAR(pygpu_offscreen_height_doc, "Height of the texture.\n\n:type: `int`");
static PyObject *pygpu_offscreen_height_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
return PyLong_FromLong(GPU_offscreen_height(self->ofs));
}
PyDoc_STRVAR(pygpu_offscreen_color_texture_doc,
2018-11-13 14:55:15 +01:00
"OpenGL bindcode for the color texture.\n\n:type: `int`");
static PyObject *pygpu_offscreen_color_texture_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
GPUTexture *texture = GPU_offscreen_color_texture(self->ofs);
return PyLong_FromLong(GPU_texture_opengl_bindcode(texture));
}
PyDoc_STRVAR(pygpu_offscreen_texture_color_doc,
"The color texture attached.\n"
"\n"
":type: :class:`gpu.types.GPUTexture`");
static PyObject *pygpu_offscreen_texture_color_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
GPUTexture *texture = GPU_offscreen_color_texture(self->ofs);
2021-04-30 11:00:57 -03:00
return BPyGPUTexture_CreatePyObject(texture, true);
}
PyDoc_STRVAR(
pygpu_offscreen_draw_view3d_doc,
2021-08-04 19:24:19 -04:00
".. method:: draw_view3d(scene, view_layer, view3d, region, view_matrix, projection_matrix, "
"do_color_management=False)\n"
"\n"
" Draw the 3d viewport in the offscreen object.\n"
"\n"
2018-11-13 14:55:15 +01:00
" :arg scene: Scene to draw.\n"
" :type scene: :class:`bpy.types.Scene`\n"
2018-11-13 14:55:15 +01:00
" :arg view_layer: View layer to draw.\n"
" :type view_layer: :class:`bpy.types.ViewLayer`\n"
2018-11-13 14:55:15 +01:00
" :arg view3d: 3D View to get the drawing settings from.\n"
" :type view3d: :class:`bpy.types.SpaceView3D`\n"
2018-11-13 14:55:15 +01:00
" :arg region: Region of the 3D View (required as temporary draw target).\n"
" :type region: :class:`bpy.types.Region`\n"
2018-11-13 14:55:15 +01:00
" :arg view_matrix: View Matrix (e.g. ``camera.matrix_world.inverted()``).\n"
" :type view_matrix: :class:`mathutils.Matrix`\n"
2018-11-13 14:55:15 +01:00
" :arg projection_matrix: Projection Matrix (e.g. ``camera.calc_matrix_camera(...)``).\n"
" :type projection_matrix: :class:`mathutils.Matrix`\n"
" :arg do_color_management: Color manage the output.\n"
" :type do_color_management: bool\n");
static PyObject *pygpu_offscreen_draw_view3d(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
{
MatrixObject *py_mat_view, *py_mat_projection;
PyObject *py_scene, *py_view_layer, *py_region, *py_view3d;
struct Depsgraph *depsgraph;
struct Scene *scene;
struct ViewLayer *view_layer;
View3D *v3d;
ARegion *region;
bool do_color_management = false;
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
2021-08-04 19:24:19 -04:00
static const char *_keywords[] = {"scene",
"view_layer",
"view3d",
"region",
"view_matrix",
"projection_matrix",
"do_color_management",
NULL};
static _PyArg_Parser _parser = {"OOOOO&O&|$O&:draw_view3d", _keywords, 0};
if (!_PyArg_ParseTupleAndKeywordsFast(args,
kwds,
&_parser,
&py_scene,
&py_view_layer,
&py_view3d,
&py_region,
Matrix_Parse4x4,
&py_mat_view,
Matrix_Parse4x4,
&py_mat_projection,
2021-08-04 19:24:19 -04:00
PyC_ParseBool,
&do_color_management) ||
(!(scene = PyC_RNA_AsPointer(py_scene, "Scene")) ||
!(view_layer = PyC_RNA_AsPointer(py_view_layer, "ViewLayer")) ||
!(v3d = PyC_RNA_AsPointer(py_view3d, "SpaceView3D")) ||
!(region = PyC_RNA_AsPointer(py_region, "Region")))) {
return NULL;
}
BLI_assert(BKE_id_is_in_global_main(&scene->id));
depsgraph = BKE_scene_ensure_depsgraph(G_MAIN, scene, view_layer);
/* Disable 'bgl' state since it interfere with off-screen drawing, see: T84402. */
const bool is_bgl = GPU_bgl_get();
if (is_bgl) {
GPU_bgl_end();
}
GPU_offscreen_bind(self->ofs, true);
/* Cache the #GPUViewport so the frame-buffers and associated textures are
* not reallocated each time, see: T89204 */
if (!self->viewport) {
self->viewport = GPU_viewport_create();
}
else {
GPU_viewport_tag_update(self->viewport);
}
ED_view3d_draw_offscreen(depsgraph,
scene,
v3d->shading.type,
v3d,
region,
GPU_offscreen_width(self->ofs),
GPU_offscreen_height(self->ofs),
2021-03-04 16:57:30 +11:00
(const float(*)[4])py_mat_view->matrix,
(const float(*)[4])py_mat_projection->matrix,
true,
true,
"",
do_color_management,
true,
self->ofs,
self->viewport);
GPU_offscreen_unbind(self->ofs, true);
if (is_bgl) {
GPU_bgl_start();
}
Py_RETURN_NONE;
}
#ifdef BPYGPU_USE_GPUOBJ_FREE_METHOD
PyDoc_STRVAR(pygpu_offscreen_free_doc,
2018-11-13 14:55:15 +01:00
".. method:: free()\n"
"\n"
2018-11-13 14:55:15 +01:00
" Free the offscreen object.\n"
" The framebuffer, texture and render objects will no longer be accessible.\n");
static PyObject *pygpu_offscreen_free(BPyGPUOffScreen *self)
{
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
if (self->viewport) {
GPU_viewport_free(self->viewport);
self->viewport = NULL;
}
GPU_offscreen_free(self->ofs);
self->ofs = NULL;
Py_RETURN_NONE;
}
#endif
static void BPyGPUOffScreen__tp_dealloc(BPyGPUOffScreen *self)
{
if (self->viewport) {
GPU_viewport_free(self->viewport);
}
if (self->ofs) {
GPU_offscreen_free(self->ofs);
}
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyGetSetDef pygpu_offscreen__tp_getseters[] = {
{"color_texture",
(getter)pygpu_offscreen_color_texture_get,
(setter)NULL,
pygpu_offscreen_color_texture_doc,
NULL},
{"texture_color",
(getter)pygpu_offscreen_texture_color_get,
(setter)NULL,
pygpu_offscreen_texture_color_doc,
NULL},
{"width", (getter)pygpu_offscreen_width_get, (setter)NULL, pygpu_offscreen_width_doc, NULL},
{"height", (getter)pygpu_offscreen_height_get, (setter)NULL, pygpu_offscreen_height_doc, NULL},
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static struct PyMethodDef pygpu_offscreen__tp_methods[] = {
{"bind", (PyCFunction)pygpu_offscreen_bind, METH_NOARGS, pygpu_offscreen_bind_doc},
{"unbind",
(PyCFunction)pygpu_offscreen_unbind,
METH_VARARGS | METH_KEYWORDS,
pygpu_offscreen_unbind_doc},
{"draw_view3d",
(PyCFunction)pygpu_offscreen_draw_view3d,
METH_VARARGS | METH_KEYWORDS,
pygpu_offscreen_draw_view3d_doc},
#ifdef BPYGPU_USE_GPUOBJ_FREE_METHOD
{"free", (PyCFunction)pygpu_offscreen_free, METH_NOARGS, pygpu_offscreen_free_doc},
#endif
{NULL, NULL, 0, NULL},
};
PyDoc_STRVAR(pygpu_offscreen__tp_doc,
".. class:: GPUOffScreen(width, height)\n"
"\n"
" This object gives access to off screen buffers.\n"
"\n"
2018-11-13 14:55:15 +01:00
" :arg width: Horizontal dimension of the buffer.\n"
" :type width: int\n"
2018-11-13 14:55:15 +01:00
" :arg height: Vertical dimension of the buffer.\n"
" :type height: int\n");
PyTypeObject BPyGPUOffScreen_Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUOffScreen",
.tp_basicsize = sizeof(BPyGPUOffScreen),
.tp_dealloc = (destructor)BPyGPUOffScreen__tp_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = pygpu_offscreen__tp_doc,
.tp_methods = pygpu_offscreen__tp_methods,
.tp_getset = pygpu_offscreen__tp_getseters,
.tp_new = pygpu_offscreen__tp_new,
};
/** \} */
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUOffScreen_CreatePyObject(GPUOffScreen *ofs)
{
BPyGPUOffScreen *self;
self = PyObject_New(BPyGPUOffScreen, &BPyGPUOffScreen_Type);
self->ofs = ofs;
self->viewport = NULL;
return (PyObject *)self;
}
/** \} */
#undef BPY_GPU_OFFSCREEN_CHECK_OBJ