Blender V5.3
python.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
5#include <Python.h>
6
7#include "blender/CCL_api.h"
8
9#include "blender/device.h"
10#include "blender/session.h"
11#include "blender/sync.h"
12#include "blender/util.h"
13
14#include "session/denoising.h"
15#include "session/merge.h"
16
17#include "util/colorspace.h"
18#include "util/debug.h"
19#include "util/guiding.h"
20#include "util/image_maketx.h"
21#include "util/image_metadata.h"
22#include "util/log.h"
24#include "util/path.h"
25#include "util/string.h"
26#include "util/task.h"
27#include "util/types.h"
28
29#include "GPU_state.hh"
30
31#include "DNA_screen_types.h"
32
33#include "scene/osl.h"
34
35#ifdef WITH_METAL
36# include "device/metal/device.h"
37#endif
38
40
41namespace {
42
43/* Flag describing whether debug flags were synchronized from scene. */
44bool debug_flags_set = false;
45
46void *pylong_as_voidptr_typesafe(PyObject *object)
47{
48 if (object == Py_None) {
49 return nullptr;
50 }
51 return PyLong_AsVoidPtr(object);
52}
53
54PyObject *pyunicode_from_string(const char *str)
55{
56 /* Ignore errors if device API returns invalid UTF8 strings. */
57 return PyUnicode_DecodeUTF8(str, strlen(str), "ignore");
58}
59
60/* Synchronize debug flags from a given Blender scene.
61 * Return truth when device list needs invalidation.
62 */
64{
65 DebugFlagsRef flags = DebugFlags();
66 blender::PointerRNA scene_rna_ptr = RNA_id_pointer_create(&b_scene.id);
67 blender::PointerRNA cscene = RNA_pointer_get(&scene_rna_ptr, "cycles");
68 /* Synchronize CPU flags. */
69 flags.cpu.avx2 = get_boolean(cscene, "debug_use_cpu_avx2");
70 flags.cpu.sse42 = get_boolean(cscene, "debug_use_cpu_sse42");
71 flags.cpu.bvh_layout = (BVHLayout)get_enum(cscene, "debug_bvh_layout");
72 /* Synchronize CUDA flags. */
73 flags.cuda.adaptive_compile = get_boolean(cscene, "debug_use_cuda_adaptive_compile");
74 flags.hip.adaptive_compile = get_boolean(cscene, "debug_use_hip_adaptive_compile");
75 flags.metal.adaptive_compile = get_boolean(cscene, "debug_use_metal_adaptive_compile");
76 /* Synchronize OptiX flags. */
77 flags.optix.use_debug = get_boolean(cscene, "debug_use_optix_debug");
78 /* Synchronize Texture Cache flags. */
79 flags.texture_cache.use_eviction = get_boolean(cscene, "debug_use_texture_cache_eviction");
80 flags.texture_cache.preserve_unused = get_int(cscene, "debug_texture_cache_preserve_unused");
81}
82
83/* Reset debug flags to default values.
84 * Return truth when device list needs invalidation.
85 */
87{
88 DebugFlagsRef flags = DebugFlags();
89 flags.reset();
90}
91
92} /* namespace */
93
94static const char *PyC_UnicodeAsBytes(PyObject *py_str, PyObject **coerce)
95{
96 const char *result = PyUnicode_AsUTF8(py_str);
97 if (result) {
98 /* 99% of the time this is enough but we better support non unicode
99 * chars since blender doesn't limit this.
100 */
101 return result;
102 }
103 PyErr_Clear();
104 if (PyBytes_Check(py_str)) {
105 return PyBytes_AS_STRING(py_str);
106 }
107
108 *coerce = PyUnicode_EncodeFSDefault(py_str);
109 if (*coerce) {
110 return PyBytes_AS_STRING(*coerce);
111 }
112 /* Clear the error, so Cycles can be at least used without
113 * GPU and OSL support,
114 */
115 PyErr_Clear();
116 return "";
117}
118
119static PyObject *init_func(PyObject * /*self*/, PyObject *args)
120{
121 PyObject *path;
122 PyObject *user_path;
123 int headless;
124
125 if (!PyArg_ParseTuple(args,
126 "O" /* `path` */
127 "O" /* `user_path` */
128 "i" /* `headless` */,
129 &path,
130 &user_path,
131 &headless))
132 {
133 return nullptr;
134 }
135
136 PyObject *path_coerce = nullptr;
137 PyObject *user_path_coerce = nullptr;
138 path_init(PyC_UnicodeAsBytes(path, &path_coerce),
139 PyC_UnicodeAsBytes(user_path, &user_path_coerce));
140 Py_XDECREF(path_coerce);
141 Py_XDECREF(user_path_coerce);
142
143 BlenderSession::headless = headless;
144
145 Py_RETURN_NONE;
146}
147
148static PyObject *exit_func(PyObject * /*self*/, PyObject * /*args*/)
149{
150#ifdef WITH_METAL
152#endif
153
158 Py_RETURN_NONE;
159}
160
161static PyObject *create_func(PyObject * /*self*/, PyObject *args)
162{
163 PyObject *pyengine;
164 PyObject *pypreferences;
165 PyObject *pydata;
166 PyObject *pyscreen;
167 PyObject *pyregion;
168 PyObject *pyv3d;
169 PyObject *pyrv3d;
170 int preview_osl;
171
172 if (!PyArg_ParseTuple(args,
173 "O" /* `engine` */
174 "O" /* `preferences` */
175 "O" /* `data` */
176 "O" /* `screen` */
177 "O" /* `region` */
178 "O" /* `v3d` */
179 "O" /* `rv3d` */
180 "i" /* `preview_osl` */,
181 &pyengine,
182 &pypreferences,
183 &pydata,
184 &pyscreen,
185 &pyregion,
186 &pyv3d,
187 &pyrv3d,
188 &preview_osl))
189 {
190 return nullptr;
191 }
192
193 /* RNA */
194 blender::ID *bScreen = (blender::ID *)PyLong_AsVoidPtr(pyscreen);
195
196 blender::RenderEngine *engine = static_cast<blender::RenderEngine *>(PyLong_AsVoidPtr(pyengine));
197 blender::UserDef *preferences = static_cast<blender::UserDef *>(PyLong_AsVoidPtr(pypreferences));
198 blender::Main *data = static_cast<blender::Main *>(PyLong_AsVoidPtr(pydata));
199 blender::View3D *v3d = static_cast<blender::View3D *>(pylong_as_voidptr_typesafe(pyv3d));
200 blender::ARegion *region = static_cast<blender::ARegion *>(pylong_as_voidptr_typesafe(pyregion));
201
202 /* create session */
203 BlenderSession *session;
204
205 if (region) {
206 blender::RegionView3D *rv3d = static_cast<blender::RegionView3D *>(region->regiondata);
207 /* interactive viewport session */
208 const int width = region->winx;
209 const int height = region->winy;
210
211 session = new BlenderSession(*engine,
212 *preferences,
213 *data,
214 blender::id_cast<blender::bScreen *>(bScreen),
215 v3d,
216 rv3d,
217 width,
218 height);
219 }
220 else {
221 /* offline session or preview render */
222 session = new BlenderSession(*engine, *preferences, *data, preview_osl);
223 }
224
225 return PyLong_FromVoidPtr(session);
226}
227
228static PyObject *free_func(PyObject * /*self*/, PyObject *value)
229{
230 delete (BlenderSession *)PyLong_AsVoidPtr(value);
231
232 Py_RETURN_NONE;
233}
234
235static PyObject *render_func(PyObject * /*self*/, PyObject *args)
236{
237 PyObject *pysession;
238 PyObject *pydepsgraph;
239
240 if (!PyArg_ParseTuple(args,
241 "O" /* `session` */
242 "O" /* `depsgraph` */,
243 &pysession,
244 &pydepsgraph))
245 {
246 return nullptr;
247 }
248
249 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
250 blender::Depsgraph *b_depsgraph = static_cast<blender::Depsgraph *>(
251 PyLong_AsVoidPtr(pydepsgraph));
252
253 /* Allow Blender to execute other Python scripts. */
254 Py_BEGIN_ALLOW_THREADS;
255 session->render(*b_depsgraph);
256 Py_END_ALLOW_THREADS;
257
258 Py_RETURN_NONE;
259}
260
261static PyObject *render_frame_finish_func(PyObject * /*self*/, PyObject *args)
262{
263 PyObject *pysession;
264
265 if (!PyArg_ParseTuple(args, "O" /* `session` */, &pysession)) {
266 return nullptr;
267 }
268
269 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
270
271 /* Allow Blender to execute other Python scripts. */
272 Py_BEGIN_ALLOW_THREADS;
273 session->render_frame_finish();
274 Py_END_ALLOW_THREADS;
275
276 Py_RETURN_NONE;
277}
278
279static PyObject *draw_func(PyObject * /*self*/, PyObject *args)
280{
281 PyObject *py_session;
282 PyObject *py_graph;
283 PyObject *py_screen;
284 PyObject *py_space_image;
285
286 if (!PyArg_ParseTuple(args,
287 "O" /* `session` */
288 "O" /* `graph` */
289 "O" /* `screen` */
290 "O" /* `space_image` */,
291 &py_session,
292 &py_graph,
293 &py_screen,
294 &py_space_image))
295 {
296 return nullptr;
297 }
298
299 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(py_session);
300
301 blender::ID *b_screen = (blender::ID *)PyLong_AsVoidPtr(py_screen);
302
303 blender::SpaceImage *b_space_image = static_cast<blender::SpaceImage *>(
304 pylong_as_voidptr_typesafe(py_space_image));
305
306 /* Release GIL, this is required because draw() can indirectly cause
307 * a Python render_stats handler to be run, which can deadlock otherwise. */
308 Py_BEGIN_ALLOW_THREADS;
309 session->draw(blender::id_cast<blender::bScreen &>(*b_screen), *b_space_image);
310 Py_END_ALLOW_THREADS;
311
312 Py_RETURN_NONE;
313}
314
315/* pixel_array and result passed as pointers */
316static PyObject *bake_func(PyObject * /*self*/, PyObject *args)
317{
318 PyObject *pysession;
319 PyObject *pydepsgraph;
320 PyObject *pyobject;
321 const char *pass_type;
322 int pass_filter;
323 int width;
324 int height;
325
326 if (!PyArg_ParseTuple(args,
327 "O" /* `session` */
328 "O" /* `depsgraph` */
329 "O" /* `object` */
330 "s" /* `pass_type` */
331 "i" /* `pass_filter` */
332 "i" /* `width` */
333 "i" /* `height` */,
334 &pysession,
335 &pydepsgraph,
336 &pyobject,
337 &pass_type,
338 &pass_filter,
339 &width,
340 &height))
341 {
342 return nullptr;
343 }
344
345 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
346
347 blender::Depsgraph *b_depsgraph = static_cast<blender::Depsgraph *>(
348 PyLong_AsVoidPtr(pydepsgraph));
349 blender::Object *b_object = static_cast<blender::Object *>(PyLong_AsVoidPtr(pyobject));
350
351 Py_BEGIN_ALLOW_THREADS;
352 session->bake(*b_depsgraph, *b_object, pass_type, pass_filter, width, height);
353 Py_END_ALLOW_THREADS;
354
355 Py_RETURN_NONE;
356}
357
358static PyObject *view_draw_func(PyObject * /*self*/, PyObject *args)
359{
360 PyObject *pysession;
361 PyObject *pygraph;
362 PyObject *pyv3d;
363 PyObject *pyrv3d;
364
365 if (!PyArg_ParseTuple(args,
366 "O" /* `session` */
367 "O" /* `graph` */
368 "O" /* `v3d` */
369 "O" /* `rv3d` */,
370 &pysession,
371 &pygraph,
372 &pyv3d,
373 &pyrv3d))
374 {
375 return nullptr;
376 }
377
378 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
379
380 if (PyLong_AsVoidPtr(pyrv3d)) {
381 /* 3d view drawing */
382 int viewport[4];
384
385 Py_BEGIN_ALLOW_THREADS;
386 session->view_draw(viewport[2], viewport[3]);
387 Py_END_ALLOW_THREADS;
388 }
389
390 Py_RETURN_NONE;
391}
392
393static PyObject *view_pause_func(PyObject * /*self*/, PyObject *args)
394{
395 PyObject *pysession;
396 int pause;
397
398 if (!PyArg_ParseTuple(args, "Op", &pysession, &pause)) {
399 return nullptr;
400 }
401
402 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
403 Py_BEGIN_ALLOW_THREADS;
404 session->view_pause(pause);
405 Py_END_ALLOW_THREADS;
406
407 Py_RETURN_NONE;
408}
409
410static PyObject *reset_func(PyObject * /*self*/, PyObject *args)
411{
412 PyObject *pysession;
413 PyObject *pydata;
414 PyObject *pydepsgraph;
415
416 if (!PyArg_ParseTuple(args,
417 "O" /* `session` */
418 "O" /* `data` */
419 "O" /* `depsgraph` */,
420 &pysession,
421 &pydata,
422 &pydepsgraph))
423 {
424 return nullptr;
425 }
426
427 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
428
429 blender::Main *b_data = static_cast<blender::Main *>(PyLong_AsVoidPtr(pydata));
430 blender::Depsgraph *b_depsgraph = static_cast<blender::Depsgraph *>(
431 PyLong_AsVoidPtr(pydepsgraph));
432
433 Py_BEGIN_ALLOW_THREADS;
434 session->reset_session(*b_data, *b_depsgraph);
435 Py_END_ALLOW_THREADS;
436
437 Py_RETURN_NONE;
438}
439
440static PyObject *sync_func(PyObject * /*self*/, PyObject *args)
441{
442 PyObject *pysession;
443 PyObject *pydepsgraph;
444
445 if (!PyArg_ParseTuple(args,
446 "O" /* `session` */
447 "O" /* `depsgraph` */,
448 &pysession,
449 &pydepsgraph))
450 {
451 return nullptr;
452 }
453
454 BlenderSession *session = (BlenderSession *)PyLong_AsVoidPtr(pysession);
455
456 blender::Depsgraph *b_depsgraph = static_cast<blender::Depsgraph *>(
457 PyLong_AsVoidPtr(pydepsgraph));
458
459 Py_BEGIN_ALLOW_THREADS;
460 session->synchronize(*b_depsgraph);
461 Py_END_ALLOW_THREADS;
462
463 Py_RETURN_NONE;
464}
465
466static PyObject *available_devices_func(PyObject * /*self*/, PyObject *args)
467{
468 const char *type_name;
469 if (!PyArg_ParseTuple(args, "s" /* `type_name` */, &type_name)) {
470 return nullptr;
471 }
472
473 const DeviceType type = Device::type_from_string(type_name);
474 /* "NONE" is defined by the add-on, see: `CyclesPreferences.get_device_types`. */
475 if ((type == DEVICE_NONE) && (strcmp(type_name, "NONE") != 0)) {
476 PyErr_Format(PyExc_ValueError, "Device \"%s\" not known.", type_name);
477 return nullptr;
478 }
479
480 uint mask = (type == DEVICE_NONE) ? DEVICE_MASK_ALL : DEVICE_MASK(type);
482
484 PyObject *ret = PyTuple_New(devices.size());
485
486 for (size_t i = 0; i < devices.size(); i++) {
487 const DeviceInfo &device = devices[i];
488 const string type_name = Device::string_from_type(device.type);
489 PyObject *device_tuple = PyTuple_New(10);
490 PyTuple_SET_ITEM(device_tuple, 0, pyunicode_from_string(device.description.c_str()));
491 PyTuple_SET_ITEM(device_tuple, 1, pyunicode_from_string(type_name.c_str()));
492 PyTuple_SET_ITEM(device_tuple, 2, pyunicode_from_string(device.id.c_str()));
493 PyTuple_SET_ITEM(device_tuple, 3, PyBool_FromLong(device.has_peer_memory));
494 PyTuple_SET_ITEM(device_tuple, 4, PyBool_FromLong(device.use_hardware_raytracing));
495 PyTuple_SET_ITEM(
496 device_tuple, 5, PyBool_FromLong(device.denoisers & DENOISER_OPENIMAGEDENOISE));
497 PyTuple_SET_ITEM(device_tuple, 6, PyBool_FromLong(device.denoisers & DENOISER_OPTIX));
498 PyTuple_SET_ITEM(device_tuple, 7, PyBool_FromLong(device.has_execution_optimization));
499 PyTuple_SET_ITEM(device_tuple, 8, PyBool_FromLong(device.meets_driver_requirement));
500 PyTuple_SET_ITEM(device_tuple, 9, PyBool_FromLong(device.denoisers & DENOISER_DLSS));
501 PyTuple_SET_ITEM(ret, i, device_tuple);
502 }
503
504 return ret;
505}
506
507#ifdef WITH_OSL
508
509static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args)
510{
511 const char *inputfile = nullptr;
512 const char *outputfile = nullptr;
513
514 if (!PyArg_ParseTuple(args,
515 "s" /* `inputfile` */
516 "s" /* `outputfile` */,
517 &inputfile,
518 &outputfile))
519 {
520 return nullptr;
521 }
522
523 /* return */
524 if (!OSLManager::osl_compile(inputfile, outputfile)) {
525 Py_RETURN_FALSE;
526 }
527
528 Py_RETURN_TRUE;
529}
530#endif
531
532static PyObject *system_info_func(PyObject * /*self*/, PyObject * /*value*/)
533{
534 const string system_info = Device::device_capabilities();
535 return pyunicode_from_string(system_info.c_str());
536}
537
538static bool image_parse_filepaths(PyObject *pyfilepaths, vector<string> &filepaths)
539{
540 if (PyUnicode_Check(pyfilepaths)) {
541 const char *filepath = PyUnicode_AsUTF8(pyfilepaths);
542 filepaths.push_back(filepath);
543 return true;
544 }
545
546 PyObject *sequence = PySequence_Fast(pyfilepaths,
547 "File paths must be a string or sequence of strings");
548 if (sequence == nullptr) {
549 return false;
550 }
551
552 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) {
553 PyObject *item = PySequence_Fast_GET_ITEM(sequence, i);
554 const char *filepath = PyUnicode_AsUTF8(item);
555 if (filepath == nullptr) {
556 PyErr_SetString(PyExc_ValueError, "File paths must be a string or sequence of strings.");
557 Py_DECREF(sequence);
558 return false;
559 }
560 filepaths.push_back(filepath);
561 }
562 Py_DECREF(sequence);
563
564 return true;
565}
566
567static PyObject *denoise_func(PyObject * /*self*/, PyObject *args, PyObject *keywords)
568{
569 static const char *keyword_list[] = {
570 "preferences", "scene", "view_layer", "input", "output", nullptr};
571 PyObject *pypreferences;
572 PyObject *pyscene;
573 PyObject *pyviewlayer;
574 PyObject *pyinput;
575 PyObject *pyoutput = nullptr;
576
577 if (!PyArg_ParseTupleAndKeywords(args,
578 keywords,
579 "O" /* `preferences` */
580 "O" /* `scene` */
581 "O" /* `view_layer` */
582 "O" /* `input` */
583 "|" /* Optional arguments. */
584 "O" /* `output` */,
585 (char **)keyword_list,
586 &pypreferences,
587 &pyscene,
588 &pyviewlayer,
589 &pyinput,
590 &pyoutput))
591 {
592 return nullptr;
593 }
594
595 /* Get device specification from preferences and scene. */
596 blender::UserDef *b_preferences = static_cast<blender::UserDef *>(
597 PyLong_AsVoidPtr(pypreferences));
598 blender::Scene *b_scene = static_cast<blender::Scene *>(PyLong_AsVoidPtr(pyscene));
599
600 DeviceInfo preferences_device;
601 const DeviceInfo pathtrace_device = blender_device_info(
602 *b_preferences, *b_scene, true, true, preferences_device);
603
604 /* Get denoising parameters from view layer. */
605 blender::ViewLayer *b_view_layer = static_cast<blender::ViewLayer *>(
606 PyLong_AsVoidPtr(pyviewlayer));
607
609 *b_scene, b_view_layer, true, preferences_device);
610 params.use = true;
611
612 /* Parse file paths list. */
613 vector<string> input;
615
616 if (!image_parse_filepaths(pyinput, input)) {
617 return nullptr;
618 }
619
620 if (pyoutput) {
621 if (!image_parse_filepaths(pyoutput, output)) {
622 return nullptr;
623 }
624 }
625 else {
626 output = input;
627 }
628
629 if (input.empty()) {
630 PyErr_SetString(PyExc_ValueError, "No input file paths specified.");
631 return nullptr;
632 }
633 if (input.size() != output.size()) {
634 PyErr_SetString(PyExc_ValueError, "Number of input and output file paths does not match.");
635 return nullptr;
636 }
637
638 /* Create denoiser. */
639 /* We are using preference device here, because path trace device will be identical to it unless
640 * scene is setting CPU render or command line override render device. But both of this options
641 * are for render, not for denoising. */
642 DenoiserPipeline denoiser(preferences_device, params);
643 denoiser.input = input;
644 denoiser.output = output;
645
646 /* Run denoiser. */
647 if (!denoiser.run()) {
648 PyErr_SetString(PyExc_ValueError, denoiser.error.c_str());
649 return nullptr;
650 }
651
652 Py_RETURN_NONE;
653}
654
655static PyObject *merge_func(PyObject * /*self*/, PyObject *args, PyObject *keywords)
656{
657 static const char *keyword_list[] = {"input", "output", nullptr};
658 PyObject *pyinput;
659 PyObject *pyoutput = nullptr;
660
661 if (!PyArg_ParseTupleAndKeywords(args,
662 keywords,
663 "O" /* `input` */
664 "O" /* `output` */,
665 (char **)keyword_list,
666 &pyinput,
667 &pyoutput))
668 {
669 return nullptr;
670 }
671
672 /* Parse input list. */
673 vector<string> input;
674 if (!image_parse_filepaths(pyinput, input)) {
675 return nullptr;
676 }
677
678 /* Parse output string. */
679 if (!PyUnicode_Check(pyoutput)) {
680 PyErr_SetString(PyExc_ValueError, "Output must be a string.");
681 return nullptr;
682 }
683 const string output = PyUnicode_AsUTF8(pyoutput);
684
685 /* Merge. */
686 ImageMerger merger;
687 merger.input = input;
688 merger.output = output;
689
690 if (!merger.run()) {
691 PyErr_SetString(PyExc_ValueError, merger.error.c_str());
692 return nullptr;
693 }
694
695 Py_RETURN_NONE;
696}
697
698static PyObject *debug_flags_update_func(PyObject * /*self*/, PyObject *args)
699{
700 PyObject *pyscene;
701 if (!PyArg_ParseTuple(args, "O" /* `scene` */, &pyscene)) {
702 return nullptr;
703 }
704
705 blender::Scene *b_scene = static_cast<blender::Scene *>(PyLong_AsVoidPtr(pyscene));
706
707 debug_flags_sync_from_scene(*b_scene);
708
709 debug_flags_set = true;
710
711 Py_RETURN_NONE;
712}
713
714static PyObject *debug_flags_reset_func(PyObject * /*self*/, PyObject * /*args*/)
715{
716 debug_flags_reset();
717 if (debug_flags_set) {
718 debug_flags_set = false;
719 }
720 Py_RETURN_NONE;
721}
722
723static PyObject *enable_print_stats_func(PyObject * /*self*/, PyObject * /*args*/)
724{
726 Py_RETURN_NONE;
727}
728
729static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/)
730{
731 const vector<DeviceType> device_types = Device::available_types();
732 bool has_cuda = false;
733 bool has_optix = false;
734 bool has_hip = false;
735 bool has_metal = false;
736 bool has_oneapi = false;
737 bool has_hiprt = false;
738 for (const DeviceType device_type : device_types) {
739 has_cuda |= (device_type == DEVICE_CUDA);
740 has_optix |= (device_type == DEVICE_OPTIX);
741 has_hip |= (device_type == DEVICE_HIP);
742 has_metal |= (device_type == DEVICE_METAL);
743 has_oneapi |= (device_type == DEVICE_ONEAPI);
744 has_hiprt |= (device_type == DEVICE_HIPRT);
745 }
746 PyObject *list = PyTuple_New(6);
747 PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda));
748 PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_optix));
749 PyTuple_SET_ITEM(list, 2, PyBool_FromLong(has_hip));
750 PyTuple_SET_ITEM(list, 3, PyBool_FromLong(has_metal));
751 PyTuple_SET_ITEM(list, 4, PyBool_FromLong(has_oneapi));
752 PyTuple_SET_ITEM(list, 5, PyBool_FromLong(has_hiprt));
753 return list;
754}
755
756static PyObject *set_device_override_func(PyObject * /*self*/, PyObject *arg)
757{
758 PyObject *override_string = PyObject_Str(arg);
759 string override = PyUnicode_AsUTF8(override_string);
760 Py_DECREF(override_string);
761
762 bool include_cpu = false;
763 const string cpu_suffix = "+CPU";
764 if (string_endswith(override, cpu_suffix)) {
765 include_cpu = true;
766 override = override.substr(0, override.length() - cpu_suffix.length());
767 }
768
769 if (override == "CPU") {
771 }
772 else if (override == "CUDA") {
774 }
775 else if (override == "OPTIX") {
777 }
778 else if (override == "HIP") {
780 }
781 else if (override == "METAL") {
783 }
784 else if (override == "ONEAPI") {
786 }
787 else {
788 LOG_ERROR << override << " is not a valid Cycles device.";
789 Py_RETURN_FALSE;
790 }
791
792 if (include_cpu) {
795 }
796
797 Py_RETURN_TRUE;
798}
799
800static PyObject *maketx_func(PyObject * /*self*/, PyObject *args, PyObject *keywords)
801{
802 static const char *keyword_list[] = {
803 "filepath", "colorspace", "alpha_type", "cache_dir", nullptr};
804
805 const char *filepath = nullptr;
806 const char *colorspace = "auto";
807 const char *alpha_type_str = "auto";
808 const char *cache_dir = "";
809
810 if (!PyArg_ParseTupleAndKeywords(args,
811 keywords,
812 "s" /* `filepath` */
813 "|" /* Optional arguments. */
814 "s" /* `colorspace` */
815 "s" /* `alpha_type` */
816 "s" /* `cache_dir` */,
817 (char **)keyword_list,
818 &filepath,
819 &colorspace,
820 &alpha_type_str,
821 &cache_dir))
822 {
823 return nullptr;
824 }
825
826 /* Alpha type. */
827 ImageAlphaType alpha_type;
828 if (strcmp(alpha_type_str, "straight") == 0) {
829 alpha_type = IMAGE_ALPHA_UNASSOCIATED;
830 }
831 else if (strcmp(alpha_type_str, "premultiplied") == 0) {
832 alpha_type = IMAGE_ALPHA_ASSOCIATED;
833 }
834 else if (strcmp(alpha_type_str, "channel_packed") == 0) {
835 alpha_type = IMAGE_ALPHA_CHANNEL_PACKED;
836 }
837 else if (strcmp(alpha_type_str, "none") == 0) {
838 alpha_type = IMAGE_ALPHA_IGNORE;
839 }
840 else if (strcmp(alpha_type_str, "auto") == 0) {
841 alpha_type = IMAGE_ALPHA_AUTO;
842 }
843 else {
844 PyErr_Format(PyExc_ValueError, "Unknown alpha type: %s", alpha_type_str);
845 return nullptr;
846 }
847
848 /* Colorspace. */
849 const ustring colorspace_ustring = (strcmp(colorspace, "auto") == 0) ? u_colorspace_auto :
850 ustring(colorspace);
851
852 /* Resolve output path, and check if tx file is already up to date. */
853 string out_filepath;
854 ccl::ImageMetaData out_metadata;
855 const bool up_to_date = resolve_tx(filepath,
856 cache_dir,
857 colorspace_ustring,
858 alpha_type,
860 out_filepath,
861 out_metadata);
862
863 if (out_filepath.empty()) {
864 LOG_ERROR << "Source image not found: " << filepath;
865 PyErr_Format(PyExc_RuntimeError, "Source image not found");
866 return nullptr;
867 }
868
869 /* Generate tx file if needed. */
870 if (!up_to_date) {
871 bool ok;
872 Py_BEGIN_ALLOW_THREADS;
873 ok = make_tx(filepath, out_filepath, colorspace_ustring, alpha_type, IMAGE_FORMAT_PLAIN);
874 Py_END_ALLOW_THREADS;
875
876 if (!ok) {
877 LOG_ERROR << "Failed to generate tx file";
878 PyErr_Format(PyExc_RuntimeError, "Failed to generate tx file");
879 return nullptr;
880 }
881 }
882
883 return pyunicode_from_string(out_filepath.c_str());
884}
885
886#ifdef __GNUC__
887# ifdef __clang__
888# pragma clang diagnostic push
889# pragma clang diagnostic ignored "-Wcast-function-type"
890# else
891# pragma GCC diagnostic push
892# pragma GCC diagnostic ignored "-Wcast-function-type"
893# endif
894#endif
895
896static PyMethodDef methods[] = {
897 {"init", init_func, METH_VARARGS, ""},
898 {"exit", exit_func, METH_VARARGS, ""},
899 {"create", create_func, METH_VARARGS, ""},
900 {"free", free_func, METH_O, ""},
901 {"render", render_func, METH_VARARGS, ""},
902 {"render_frame_finish", render_frame_finish_func, METH_VARARGS, ""},
903 {"draw", draw_func, METH_VARARGS, ""},
904 {"bake", bake_func, METH_VARARGS, ""},
905 {"view_draw", view_draw_func, METH_VARARGS, ""},
906 {"view_pause", view_pause_func, METH_VARARGS, ""},
907 {"sync", sync_func, METH_VARARGS, ""},
908 {"reset", reset_func, METH_VARARGS, ""},
909#ifdef WITH_OSL
910 {"osl_compile", osl_compile_func, METH_VARARGS, ""},
911#endif
912 {"available_devices", available_devices_func, METH_VARARGS, ""},
913 {"system_info", system_info_func, METH_NOARGS, ""},
914
915 /* Standalone denoising */
916 {"denoise", (PyCFunction)denoise_func, METH_VARARGS | METH_KEYWORDS, ""},
917 {"merge", (PyCFunction)merge_func, METH_VARARGS | METH_KEYWORDS, ""},
918
919 /* Debugging routines */
920 {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""},
921 {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""},
922
923 /* Statistics. */
924 {"enable_print_stats", enable_print_stats_func, METH_NOARGS, ""},
925
926 /* Compute Device selection */
927 {"get_device_types", get_device_types_func, METH_VARARGS, ""},
928 {"set_device_override", set_device_override_func, METH_O, ""},
929
930 /* Texture cache */
931 {"maketx", (PyCFunction)maketx_func, METH_VARARGS | METH_KEYWORDS, ""},
932
933 {nullptr, nullptr, 0, nullptr},
934};
935
936#ifdef __GNUC__
937# ifdef __clang__
938# pragma clang diagnostic pop
939# else
940# pragma GCC diagnostic pop
941# endif
942#endif
943
944static struct PyModuleDef module = {
945 /*m_base*/ PyModuleDef_HEAD_INIT,
946 /*m_name*/ "_cycles",
947 /*m_doc*/ "Blender cycles render integration",
948 /*m_size*/ -1,
949 /*m_methods*/ methods,
950 /*m_slots*/ nullptr,
951 /*m_traverse*/ nullptr,
952 /*m_clear*/ nullptr,
953 /*m_free*/ nullptr,
954};
955
957
959{
960 PyObject *mod = PyModule_Create(&ccl::module);
961
962#ifdef WITH_OSL
963 /* TODO(sergey): This gives us library we've been linking against.
964 * In theory with dynamic OSL library it might not be
965 * accurate, but there's nothing in OSL API which we
966 * might use to get version in runtime.
967 */
968 const int curversion = OSL_LIBRARY_VERSION_CODE;
969 PyModule_AddObjectRef(mod, "with_osl", Py_True);
970 PyModule_AddObject(
971 mod,
972 "osl_version",
973 Py_BuildValue("(iii)", curversion / 10000, (curversion / 100) % 100, curversion % 100));
974 PyModule_AddObject(
975 mod,
976 "osl_version_string",
977 PyUnicode_FromFormat(
978 "%2d, %2d, %2d", curversion / 10000, (curversion / 100) % 100, curversion % 100));
979#else
980 PyModule_AddObjectRef(mod, "with_osl", Py_False);
981 PyModule_AddStringConstant(mod, "osl_version", "unknown");
982 PyModule_AddStringConstant(mod, "osl_version_string", "unknown");
983#endif
984
985 if (ccl::guiding_supported()) {
986 PyModule_AddObjectRef(mod, "with_path_guiding", Py_True);
987 }
988 else {
989 PyModule_AddObjectRef(mod, "with_path_guiding", Py_False);
990 }
991
992#ifdef WITH_EMBREE
993 PyModule_AddObjectRef(mod, "with_embree", Py_True);
994#else /* WITH_EMBREE */
995 PyModule_AddObjectRef(mod, "with_embree", Py_False);
996#endif /* WITH_EMBREE */
997
998#ifdef WITH_EMBREE_GPU
999 PyModule_AddObjectRef(mod, "with_embree_gpu", Py_True);
1000#else /* WITH_EMBREE_GPU */
1001 PyModule_AddObjectRef(mod, "with_embree_gpu", Py_False);
1002#endif /* WITH_EMBREE_GPU */
1003
1004 if (ccl::openimagedenoise_supported()) {
1005 PyModule_AddObjectRef(mod, "with_openimagedenoise", Py_True);
1006 }
1007 else {
1008 PyModule_AddObjectRef(mod, "with_openimagedenoise", Py_False);
1009 }
1010
1011#ifdef WITH_DLSS
1012 PyModule_AddObjectRef(mod, "with_dlss", Py_True);
1013#else
1014 PyModule_AddObjectRef(mod, "with_dlss", Py_False);
1015#endif
1016
1017#ifdef WITH_CYCLES_DEBUG
1018 PyModule_AddObjectRef(mod, "with_debug", Py_True);
1019#else /* WITH_CYCLES_DEBUG */
1020 PyModule_AddObjectRef(mod, "with_debug", Py_False);
1021#endif /* WITH_CYCLES_DEBUG */
1022
1023 return (void *)mod;
1024}
DeviceInfo blender_device_info(blender::UserDef &b_preferences, blender::Scene &b_scene, bool background, bool preview, DeviceInfo &preferences_device)
#define output
static bool headless
static bool print_render_stats
void draw(blender::bScreen &b_screen, blender::SpaceImage &space_image)
void synchronize(blender::Depsgraph &b_depsgraph)
void view_pause(const bool pause)
void render(blender::Depsgraph &b_depsgraph)
void bake(blender::Depsgraph &b_depsgraph_, blender::Object &b_object, const string &bake_type, const int bake_filter, const int bake_width, const int bake_height)
void reset_session(blender::Main &b_data, blender::Depsgraph &b_depsgraph)
void view_draw(const int w, const int h)
BlenderSession(blender::RenderEngine &b_engine, blender::UserDef &b_userpref, blender::Main &b_data, bool preview_osl)
static DeviceTypeMask device_override
static DenoiseParams get_denoise_params(blender::Scene &b_scene, blender::ViewLayer *b_view_layer, bool background, const DeviceInfo &denoise_device)
Definition sync.cpp:1143
static void free_memory()
CPU cpu
Definition debug.h:143
void reset()
Definition debug.cpp:119
OptiX optix
Definition debug.h:149
CUDA cuda
Definition debug.h:146
HIP hip
Definition debug.h:152
TextureCache texture_cache
Definition debug.h:158
Metal metal
Definition debug.h:155
NODE_DECLARE bool use
Definition denoise.h:70
vector< string > input
Definition denoising.h:39
vector< string > output
Definition denoising.h:43
bool has_execution_optimization
bool meets_driver_requirement
DenoiserTypeMask denoisers
bool has_peer_memory
DeviceType type
string description
bool use_hardware_raytracing
static void free_memory()
static DeviceType type_from_string(const char *name)
static string device_capabilities(const uint device_type_mask=DEVICE_MASK_ALL)
static vector< DeviceType > available_types()
static string string_from_type(DeviceType type)
static vector< DeviceInfo > available_devices(const uint device_type_mask=DEVICE_MASK_ALL)
bool run()
Definition merge.cpp:572
string output
Definition merge.h:25
vector< string > input
Definition merge.h:23
string error
Definition merge.h:20
static void free_memory()
Definition osl.cpp:1679
static void free_memory()
Definition task.cpp:91
CCL_NAMESPACE_BEGIN ustring u_colorspace_auto
DebugFlags & DebugFlagsRef
Definition debug.h:168
@ DENOISER_OPTIX
Definition denoise.h:12
@ DENOISER_OPENIMAGEDENOISE
Definition denoise.h:13
@ DENOISER_DLSS
Definition denoise.h:14
#define CCL_NAMESPACE_END
#define DEVICE_MASK(type)
DeviceTypeMask
@ DEVICE_MASK_OPTIX
@ DEVICE_MASK_CPU
@ DEVICE_MASK_HIP
@ DEVICE_MASK_ALL
@ DEVICE_MASK_CUDA
@ DEVICE_MASK_METAL
@ DEVICE_MASK_ONEAPI
DeviceType
@ DEVICE_NONE
@ DEVICE_METAL
@ DEVICE_CUDA
@ DEVICE_HIPRT
@ DEVICE_OPTIX
@ DEVICE_HIP
@ DEVICE_ONEAPI
void device_metal_exit()
#define str(s)
VecBase< float, D > constexpr mod(VecOp< float, D >, VecOp< float, D >) RET
float length(VecOp< float, D >) RET
bool resolve_tx(const string &filepath, const string &texture_cache_path, ustring colorspace, const ImageAlphaType alpha_type, const ImageFormatType format_type, string &out_filepath, ImageMetaData &out_metadata)
bool make_tx(const string &filepath, const string &out_filepath, ustring colorspace, const ImageAlphaType alpha_type, const ImageFormatType format_type)
#define LOG_ERROR
Definition log.h:101
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
void debug_flags_reset()
Definition python.cpp:86
void debug_flags_sync_from_scene(blender::Scene &b_scene)
Definition python.cpp:63
void * pylong_as_voidptr_typesafe(PyObject *object)
Definition python.cpp:46
PyObject * pyunicode_from_string(const char *str)
Definition python.cpp:54
void GPU_viewport_size_get_i(int coords[4])
Definition gpu_state.cc:267
void * CCL_python_module_init()
Definition python.cpp:958
KernelBVHLayout BVHLayout
Definition params.h:22
void path_init(const string &path, const string &user_path)
Definition path.cpp:355
static PyObject * init_func(PyObject *, PyObject *args)
Definition python.cpp:119
static PyObject * merge_func(PyObject *, PyObject *args, PyObject *keywords)
Definition python.cpp:655
static PyObject * sync_func(PyObject *, PyObject *args)
Definition python.cpp:440
static PyObject * denoise_func(PyObject *, PyObject *args, PyObject *keywords)
Definition python.cpp:567
static PyObject * system_info_func(PyObject *, PyObject *)
Definition python.cpp:532
static PyObject * set_device_override_func(PyObject *, PyObject *arg)
Definition python.cpp:756
static PyObject * free_func(PyObject *, PyObject *value)
Definition python.cpp:228
static PyObject * view_pause_func(PyObject *, PyObject *args)
Definition python.cpp:393
static struct PyModuleDef module
Definition python.cpp:944
static bool image_parse_filepaths(PyObject *pyfilepaths, vector< string > &filepaths)
Definition python.cpp:538
static PyMethodDef methods[]
Definition python.cpp:896
static PyObject * available_devices_func(PyObject *, PyObject *args)
Definition python.cpp:466
static PyObject * maketx_func(PyObject *, PyObject *args, PyObject *keywords)
Definition python.cpp:800
static PyObject * bake_func(PyObject *, PyObject *args)
Definition python.cpp:316
static PyObject * reset_func(PyObject *, PyObject *args)
Definition python.cpp:410
static PyObject * view_draw_func(PyObject *, PyObject *args)
Definition python.cpp:358
static PyObject * enable_print_stats_func(PyObject *, PyObject *)
Definition python.cpp:723
static PyObject * debug_flags_reset_func(PyObject *, PyObject *)
Definition python.cpp:714
static PyObject * render_func(PyObject *, PyObject *args)
Definition python.cpp:235
static PyObject * debug_flags_update_func(PyObject *, PyObject *args)
Definition python.cpp:698
static PyObject * draw_func(PyObject *, PyObject *args)
Definition python.cpp:279
static PyObject * get_device_types_func(PyObject *, PyObject *)
Definition python.cpp:729
static const char * PyC_UnicodeAsBytes(PyObject *py_str, PyObject **coerce)
Definition python.cpp:94
static PyObject * render_frame_finish_func(PyObject *, PyObject *args)
Definition python.cpp:261
static PyObject * create_func(PyObject *, PyObject *args)
Definition python.cpp:161
static PyObject * exit_func(PyObject *, PyObject *)
Definition python.cpp:148
bool string_endswith(const string_view s, const string_view end)
Definition string.cpp:122
BVHLayout bvh_layout
Definition debug.h:47
bool adaptive_compile
Definition debug.h:59
bool adaptive_compile
Definition debug.h:73
bool adaptive_compile
Definition debug.h:96
ImageAlphaType
Definition types_image.h:61
@ IMAGE_ALPHA_ASSOCIATED
Definition types_image.h:63
@ IMAGE_ALPHA_CHANNEL_PACKED
Definition types_image.h:64
@ IMAGE_ALPHA_AUTO
Definition types_image.h:66
@ IMAGE_ALPHA_IGNORE
Definition types_image.h:65
@ IMAGE_ALPHA_UNASSOCIATED
Definition types_image.h:62
@ IMAGE_FORMAT_PLAIN
Definition types_image.h:73