Cycles: add animation denoising Python operator.
[blender.git] / intern / cycles / blender / blender_python.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <Python.h>
18
19 #include "blender/CCL_api.h"
20
21 #include "blender/blender_device.h"
22 #include "blender/blender_sync.h"
23 #include "blender/blender_session.h"
24
25 #include "render/denoising.h"
26
27 #include "util/util_debug.h"
28 #include "util/util_foreach.h"
29 #include "util/util_logging.h"
30 #include "util/util_md5.h"
31 #include "util/util_opengl.h"
32 #include "util/util_path.h"
33 #include "util/util_string.h"
34 #include "util/util_types.h"
35
36 #ifdef WITH_OSL
37 #include "render/osl.h"
38
39 #include <OSL/oslquery.h>
40 #include <OSL/oslconfig.h>
41 #endif
42
43 CCL_NAMESPACE_BEGIN
44
45 namespace {
46
47 /* Flag describing whether debug flags were synchronized from scene. */
48 bool debug_flags_set = false;
49
50 void *pylong_as_voidptr_typesafe(PyObject *object)
51 {
52         if(object == Py_None)
53                 return NULL;
54         return PyLong_AsVoidPtr(object);
55 }
56
57 /* Synchronize debug flags from a given Blender scene.
58  * Return truth when device list needs invalidation.
59  */
60 bool debug_flags_sync_from_scene(BL::Scene b_scene)
61 {
62         DebugFlagsRef flags = DebugFlags();
63         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
64         /* Backup some settings for comparison. */
65         DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;
66         DebugFlags::OpenCL::KernelType opencl_kernel_type = flags.opencl.kernel_type;
67         /* Synchronize shared flags. */
68         flags.viewport_static_bvh = get_enum(cscene, "debug_bvh_type");
69         /* Synchronize CPU flags. */
70         flags.cpu.avx2 = get_boolean(cscene, "debug_use_cpu_avx2");
71         flags.cpu.avx = get_boolean(cscene, "debug_use_cpu_avx");
72         flags.cpu.sse41 = get_boolean(cscene, "debug_use_cpu_sse41");
73         flags.cpu.sse3 = get_boolean(cscene, "debug_use_cpu_sse3");
74         flags.cpu.sse2 = get_boolean(cscene, "debug_use_cpu_sse2");
75         flags.cpu.bvh_layout = (BVHLayout)get_enum(cscene, "debug_bvh_layout");
76         flags.cpu.split_kernel = get_boolean(cscene, "debug_use_cpu_split_kernel");
77         /* Synchronize CUDA flags. */
78         flags.cuda.adaptive_compile = get_boolean(cscene, "debug_use_cuda_adaptive_compile");
79         flags.cuda.split_kernel = get_boolean(cscene, "debug_use_cuda_split_kernel");
80         /* Synchronize OpenCL kernel type. */
81         switch(get_enum(cscene, "debug_opencl_kernel_type")) {
82                 case 0:
83                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;
84                         break;
85                 case 1:
86                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_MEGA;
87                         break;
88                 case 2:
89                         flags.opencl.kernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;
90                         break;
91         }
92         /* Synchronize OpenCL device type. */
93         switch(get_enum(cscene, "debug_opencl_device_type")) {
94                 case 0:
95                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;
96                         break;
97                 case 1:
98                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ALL;
99                         break;
100                 case 2:
101                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_DEFAULT;
102                         break;
103                 case 3:
104                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_CPU;
105                         break;
106                 case 4:
107                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_GPU;
108                         break;
109                 case 5:
110                         flags.opencl.device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;
111                         break;
112         }
113         /* Synchronize other OpenCL flags. */
114         flags.opencl.debug = get_boolean(cscene, "debug_use_opencl_debug");
115         flags.opencl.mem_limit = ((size_t)get_int(cscene, "debug_opencl_mem_limit"))*1024*1024;
116         flags.opencl.single_program = get_boolean(cscene, "debug_opencl_kernel_single_program");
117         return flags.opencl.device_type != opencl_device_type ||
118                flags.opencl.kernel_type != opencl_kernel_type;
119 }
120
121 /* Reset debug flags to default values.
122  * Return truth when device list needs invalidation.
123  */
124 bool debug_flags_reset()
125 {
126         DebugFlagsRef flags = DebugFlags();
127         /* Backup some settings for comparison. */
128         DebugFlags::OpenCL::DeviceType opencl_device_type = flags.opencl.device_type;
129         DebugFlags::OpenCL::KernelType opencl_kernel_type = flags.opencl.kernel_type;
130         flags.reset();
131         return flags.opencl.device_type != opencl_device_type ||
132                flags.opencl.kernel_type != opencl_kernel_type;
133 }
134
135 }  /* namespace */
136
137 void python_thread_state_save(void **python_thread_state)
138 {
139         *python_thread_state = (void*)PyEval_SaveThread();
140 }
141
142 void python_thread_state_restore(void **python_thread_state)
143 {
144         PyEval_RestoreThread((PyThreadState*)*python_thread_state);
145         *python_thread_state = NULL;
146 }
147
148 static const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
149 {
150         const char *result = _PyUnicode_AsString(py_str);
151         if(result) {
152                 /* 99% of the time this is enough but we better support non unicode
153                  * chars since blender doesnt limit this.
154                  */
155                 return result;
156         }
157         else {
158                 PyErr_Clear();
159                 if(PyBytes_Check(py_str)) {
160                         return PyBytes_AS_STRING(py_str);
161                 }
162                 else if((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
163                         return PyBytes_AS_STRING(*coerce);
164                 }
165                 else {
166                         /* Clear the error, so Cycles can be at leadt used without
167                          * GPU and OSL support,
168                          */
169                         PyErr_Clear();
170                         return "";
171                 }
172         }
173 }
174
175 static PyObject *init_func(PyObject * /*self*/, PyObject *args)
176 {
177         PyObject *path, *user_path;
178         int headless;
179
180         if(!PyArg_ParseTuple(args, "OOi", &path, &user_path, &headless)) {
181                 return NULL;
182         }
183
184         PyObject *path_coerce = NULL, *user_path_coerce = NULL;
185         path_init(PyC_UnicodeAsByte(path, &path_coerce),
186                   PyC_UnicodeAsByte(user_path, &user_path_coerce));
187         Py_XDECREF(path_coerce);
188         Py_XDECREF(user_path_coerce);
189
190         BlenderSession::headless = headless;
191
192         VLOG(2) << "Debug flags initialized to:\n"
193                 << DebugFlags();
194
195         Py_RETURN_NONE;
196 }
197
198
199 static PyObject *exit_func(PyObject * /*self*/, PyObject * /*args*/)
200 {
201         ShaderManager::free_memory();
202         TaskScheduler::free_memory();
203         Device::free_memory();
204         Py_RETURN_NONE;
205 }
206
207 static PyObject *create_func(PyObject * /*self*/, PyObject *args)
208 {
209         PyObject *pyengine, *pyuserpref, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d;
210         int preview_osl;
211
212         if(!PyArg_ParseTuple(args, "OOOOOOOi", &pyengine, &pyuserpref, &pydata, &pyscene,
213                              &pyregion, &pyv3d, &pyrv3d, &preview_osl))
214         {
215                 return NULL;
216         }
217
218         /* RNA */
219         PointerRNA engineptr;
220         RNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr);
221         BL::RenderEngine engine(engineptr);
222
223         PointerRNA userprefptr;
224         RNA_pointer_create(NULL, &RNA_UserPreferences, (void*)PyLong_AsVoidPtr(pyuserpref), &userprefptr);
225         BL::UserPreferences userpref(userprefptr);
226
227         PointerRNA dataptr;
228         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
229         BL::BlendData data(dataptr);
230
231         PointerRNA sceneptr;
232         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
233         BL::Scene scene(sceneptr);
234
235         PointerRNA regionptr;
236         RNA_pointer_create(NULL, &RNA_Region, pylong_as_voidptr_typesafe(pyregion), &regionptr);
237         BL::Region region(regionptr);
238
239         PointerRNA v3dptr;
240         RNA_pointer_create(NULL, &RNA_SpaceView3D, pylong_as_voidptr_typesafe(pyv3d), &v3dptr);
241         BL::SpaceView3D v3d(v3dptr);
242
243         PointerRNA rv3dptr;
244         RNA_pointer_create(NULL, &RNA_RegionView3D, pylong_as_voidptr_typesafe(pyrv3d), &rv3dptr);
245         BL::RegionView3D rv3d(rv3dptr);
246
247         /* create session */
248         BlenderSession *session;
249
250         if(rv3d) {
251                 /* interactive viewport session */
252                 int width = region.width();
253                 int height = region.height();
254
255                 session = new BlenderSession(engine, userpref, data, scene, v3d, rv3d, width, height);
256         }
257         else {
258                 /* override some settings for preview */
259                 if(engine.is_preview()) {
260                         PointerRNA cscene = RNA_pointer_get(&sceneptr, "cycles");
261
262                         RNA_boolean_set(&cscene, "shading_system", preview_osl);
263                         RNA_boolean_set(&cscene, "use_progressive_refine", true);
264                 }
265
266                 /* offline session or preview render */
267                 session = new BlenderSession(engine, userpref, data, scene);
268         }
269
270         python_thread_state_save(&session->python_thread_state);
271
272         session->create();
273
274         python_thread_state_restore(&session->python_thread_state);
275
276         return PyLong_FromVoidPtr(session);
277 }
278
279 static PyObject *free_func(PyObject * /*self*/, PyObject *value)
280 {
281         delete (BlenderSession*)PyLong_AsVoidPtr(value);
282
283         Py_RETURN_NONE;
284 }
285
286 static PyObject *render_func(PyObject * /*self*/, PyObject *value)
287 {
288         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
289
290         python_thread_state_save(&session->python_thread_state);
291
292         session->render();
293
294         python_thread_state_restore(&session->python_thread_state);
295
296         Py_RETURN_NONE;
297 }
298
299 /* pixel_array and result passed as pointers */
300 static PyObject *bake_func(PyObject * /*self*/, PyObject *args)
301 {
302         PyObject *pysession, *pyobject;
303         PyObject *pypixel_array, *pyresult;
304         const char *pass_type;
305         int num_pixels, depth, object_id, pass_filter;
306
307         if(!PyArg_ParseTuple(args, "OOsiiOiiO", &pysession, &pyobject, &pass_type, &pass_filter, &object_id, &pypixel_array, &num_pixels, &depth, &pyresult))
308                 return NULL;
309
310         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
311
312         PointerRNA objectptr;
313         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyobject), &objectptr);
314         BL::Object b_object(objectptr);
315
316         void *b_result = PyLong_AsVoidPtr(pyresult);
317
318         PointerRNA bakepixelptr;
319         RNA_pointer_create(NULL, &RNA_BakePixel, PyLong_AsVoidPtr(pypixel_array), &bakepixelptr);
320         BL::BakePixel b_bake_pixel(bakepixelptr);
321
322         python_thread_state_save(&session->python_thread_state);
323
324         session->bake(b_object, pass_type, pass_filter, object_id, b_bake_pixel, (size_t)num_pixels, depth, (float *)b_result);
325
326         python_thread_state_restore(&session->python_thread_state);
327
328         Py_RETURN_NONE;
329 }
330
331 static PyObject *draw_func(PyObject * /*self*/, PyObject *args)
332 {
333         PyObject *pysession, *pyv3d, *pyrv3d;
334
335         if(!PyArg_ParseTuple(args, "OOO", &pysession, &pyv3d, &pyrv3d))
336                 return NULL;
337
338         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
339
340         if(PyLong_AsVoidPtr(pyrv3d)) {
341                 /* 3d view drawing */
342                 int viewport[4];
343                 glGetIntegerv(GL_VIEWPORT, viewport);
344
345                 session->draw(viewport[2], viewport[3]);
346         }
347
348         Py_RETURN_NONE;
349 }
350
351 static PyObject *reset_func(PyObject * /*self*/, PyObject *args)
352 {
353         PyObject *pysession, *pydata, *pyscene;
354
355         if(!PyArg_ParseTuple(args, "OOO", &pysession, &pydata, &pyscene))
356                 return NULL;
357
358         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);
359
360         PointerRNA dataptr;
361         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
362         BL::BlendData b_data(dataptr);
363
364         PointerRNA sceneptr;
365         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
366         BL::Scene b_scene(sceneptr);
367
368         python_thread_state_save(&session->python_thread_state);
369
370         session->reset_session(b_data, b_scene);
371
372         python_thread_state_restore(&session->python_thread_state);
373
374         Py_RETURN_NONE;
375 }
376
377 static PyObject *sync_func(PyObject * /*self*/, PyObject *value)
378 {
379         BlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(value);
380
381         python_thread_state_save(&session->python_thread_state);
382
383         session->synchronize();
384
385         python_thread_state_restore(&session->python_thread_state);
386
387         Py_RETURN_NONE;
388 }
389
390 static PyObject *available_devices_func(PyObject * /*self*/, PyObject * args)
391 {
392         const char *type_name;
393         if(!PyArg_ParseTuple(args, "s", &type_name)) {
394                 return NULL;
395         }
396
397         DeviceType type = Device::type_from_string(type_name);
398         uint mask = (type == DEVICE_NONE) ? DEVICE_MASK_ALL : DEVICE_MASK(type);
399         mask |= DEVICE_MASK_CPU;
400
401         vector<DeviceInfo> devices = Device::available_devices(mask);
402         PyObject *ret = PyTuple_New(devices.size());
403
404         for(size_t i = 0; i < devices.size(); i++) {
405                 DeviceInfo& device = devices[i];
406                 string type_name = Device::string_from_type(device.type);
407                 PyObject *device_tuple = PyTuple_New(3);
408                 PyTuple_SET_ITEM(device_tuple, 0, PyUnicode_FromString(device.description.c_str()));
409                 PyTuple_SET_ITEM(device_tuple, 1, PyUnicode_FromString(type_name.c_str()));
410                 PyTuple_SET_ITEM(device_tuple, 2, PyUnicode_FromString(device.id.c_str()));
411                 PyTuple_SET_ITEM(ret, i, device_tuple);
412         }
413
414         return ret;
415 }
416
417 #ifdef WITH_OSL
418
419 static PyObject *osl_update_node_func(PyObject * /*self*/, PyObject *args)
420 {
421         PyObject *pydata, *pynodegroup, *pynode;
422         const char *filepath = NULL;
423
424         if(!PyArg_ParseTuple(args, "OOOs", &pydata, &pynodegroup, &pynode, &filepath))
425                 return NULL;
426
427         /* RNA */
428         PointerRNA dataptr;
429         RNA_main_pointer_create((Main*)PyLong_AsVoidPtr(pydata), &dataptr);
430         BL::BlendData b_data(dataptr);
431
432         PointerRNA nodeptr;
433         RNA_pointer_create((ID*)PyLong_AsVoidPtr(pynodegroup), &RNA_ShaderNodeScript, (void*)PyLong_AsVoidPtr(pynode), &nodeptr);
434         BL::ShaderNodeScript b_node(nodeptr);
435
436         /* update bytecode hash */
437         string bytecode = b_node.bytecode();
438
439         if(!bytecode.empty()) {
440                 MD5Hash md5;
441                 md5.append((const uint8_t*)bytecode.c_str(), bytecode.size());
442                 b_node.bytecode_hash(md5.get_hex().c_str());
443         }
444         else
445                 b_node.bytecode_hash("");
446
447         /* query from file path */
448         OSL::OSLQuery query;
449
450         if(!OSLShaderManager::osl_query(query, filepath))
451                 Py_RETURN_FALSE;
452
453         /* add new sockets from parameters */
454         set<void*> used_sockets;
455
456         for(int i = 0; i < query.nparams(); i++) {
457                 const OSL::OSLQuery::Parameter *param = query.getparam(i);
458
459                 /* skip unsupported types */
460                 if(param->varlenarray || param->isstruct || param->type.arraylen > 1)
461                         continue;
462
463                 /* determine socket type */
464                 string socket_type;
465                 BL::NodeSocket::type_enum data_type = BL::NodeSocket::type_VALUE;
466                 float4 default_float4 = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
467                 float default_float = 0.0f;
468                 int default_int = 0;
469                 string default_string = "";
470
471                 if(param->isclosure) {
472                         socket_type = "NodeSocketShader";
473                         data_type = BL::NodeSocket::type_SHADER;
474                 }
475                 else if(param->type.vecsemantics == TypeDesc::COLOR) {
476                         socket_type = "NodeSocketColor";
477                         data_type = BL::NodeSocket::type_RGBA;
478
479                         if(param->validdefault) {
480                                 default_float4[0] = param->fdefault[0];
481                                 default_float4[1] = param->fdefault[1];
482                                 default_float4[2] = param->fdefault[2];
483                         }
484                 }
485                 else if(param->type.vecsemantics == TypeDesc::POINT ||
486                         param->type.vecsemantics == TypeDesc::VECTOR ||
487                         param->type.vecsemantics == TypeDesc::NORMAL)
488                 {
489                         socket_type = "NodeSocketVector";
490                         data_type = BL::NodeSocket::type_VECTOR;
491
492                         if(param->validdefault) {
493                                 default_float4[0] = param->fdefault[0];
494                                 default_float4[1] = param->fdefault[1];
495                                 default_float4[2] = param->fdefault[2];
496                         }
497                 }
498                 else if(param->type.aggregate == TypeDesc::SCALAR) {
499                         if(param->type.basetype == TypeDesc::INT) {
500                                 socket_type = "NodeSocketInt";
501                                 data_type = BL::NodeSocket::type_INT;
502                                 if(param->validdefault)
503                                         default_int = param->idefault[0];
504                         }
505                         else if(param->type.basetype == TypeDesc::FLOAT) {
506                                 socket_type = "NodeSocketFloat";
507                                 data_type = BL::NodeSocket::type_VALUE;
508                                 if(param->validdefault)
509                                         default_float = param->fdefault[0];
510                         }
511                         else if(param->type.basetype == TypeDesc::STRING) {
512                                 socket_type = "NodeSocketString";
513                                 data_type = BL::NodeSocket::type_STRING;
514                                 if(param->validdefault)
515                                         default_string = param->sdefault[0].string();
516                         }
517                         else
518                                 continue;
519                 }
520                 else
521                         continue;
522
523                 /* find socket socket */
524                 BL::NodeSocket b_sock(PointerRNA_NULL);
525                 if(param->isoutput) {
526                         b_sock = b_node.outputs[param->name.string()];
527                         /* remove if type no longer matches */
528                         if(b_sock && b_sock.bl_idname() != socket_type) {
529                                 b_node.outputs.remove(b_data, b_sock);
530                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
531                         }
532                 }
533                 else {
534                         b_sock = b_node.inputs[param->name.string()];
535                         /* remove if type no longer matches */
536                         if(b_sock && b_sock.bl_idname() != socket_type) {
537                                 b_node.inputs.remove(b_data, b_sock);
538                                 b_sock = BL::NodeSocket(PointerRNA_NULL);
539                         }
540                 }
541
542                 if(!b_sock) {
543                         /* create new socket */
544                         if(param->isoutput)
545                                 b_sock = b_node.outputs.create(b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str());
546                         else
547                                 b_sock = b_node.inputs.create(b_data, socket_type.c_str(), param->name.c_str(), param->name.c_str());
548
549                         /* set default value */
550                         if(data_type == BL::NodeSocket::type_VALUE) {
551                                 set_float(b_sock.ptr, "default_value", default_float);
552                         }
553                         else if(data_type == BL::NodeSocket::type_INT) {
554                                 set_int(b_sock.ptr, "default_value", default_int);
555                         }
556                         else if(data_type == BL::NodeSocket::type_RGBA) {
557                                 set_float4(b_sock.ptr, "default_value", default_float4);
558                         }
559                         else if(data_type == BL::NodeSocket::type_VECTOR) {
560                                 set_float3(b_sock.ptr, "default_value", float4_to_float3(default_float4));
561                         }
562                         else if(data_type == BL::NodeSocket::type_STRING) {
563                                 set_string(b_sock.ptr, "default_value", default_string);
564                         }
565                 }
566
567                 used_sockets.insert(b_sock.ptr.data);
568         }
569
570         /* remove unused parameters */
571         bool removed;
572
573         do {
574                 BL::Node::inputs_iterator b_input;
575                 BL::Node::outputs_iterator b_output;
576
577                 removed = false;
578
579                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
580                         if(used_sockets.find(b_input->ptr.data) == used_sockets.end()) {
581                                 b_node.inputs.remove(b_data, *b_input);
582                                 removed = true;
583                                 break;
584                         }
585                 }
586
587                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
588                         if(used_sockets.find(b_output->ptr.data) == used_sockets.end()) {
589                                 b_node.outputs.remove(b_data, *b_output);
590                                 removed = true;
591                                 break;
592                         }
593                 }
594         } while(removed);
595
596         Py_RETURN_TRUE;
597 }
598
599 static PyObject *osl_compile_func(PyObject * /*self*/, PyObject *args)
600 {
601         const char *inputfile = NULL, *outputfile = NULL;
602
603         if(!PyArg_ParseTuple(args, "ss", &inputfile, &outputfile))
604                 return NULL;
605
606         /* return */
607         if(!OSLShaderManager::osl_compile(inputfile, outputfile))
608                 Py_RETURN_FALSE;
609
610         Py_RETURN_TRUE;
611 }
612 #endif
613
614 static PyObject *system_info_func(PyObject * /*self*/, PyObject * /*value*/)
615 {
616         string system_info = Device::device_capabilities();
617         return PyUnicode_FromString(system_info.c_str());
618 }
619
620 #ifdef WITH_OPENCL
621 static PyObject *opencl_disable_func(PyObject * /*self*/, PyObject * /*value*/)
622 {
623         VLOG(2) << "Disabling OpenCL platform.";
624         DebugFlags().opencl.device_type = DebugFlags::OpenCL::DEVICE_NONE;
625         Py_RETURN_NONE;
626 }
627 #endif
628
629 static bool denoise_parse_filepaths(PyObject *pyfilepaths, vector<string>& filepaths)
630 {
631
632         if(PyUnicode_Check(pyfilepaths)) {
633                 const char *filepath = PyUnicode_AsUTF8(pyfilepaths);
634                 filepaths.push_back(filepath);
635                 return true;
636         }
637
638         PyObject *sequence = PySequence_Fast(pyfilepaths, "File paths must be a string or sequence of strings");
639         if(sequence == NULL) {
640                 return false;
641         }
642
643         for(Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(sequence); i++) {
644                 PyObject *item = PySequence_Fast_GET_ITEM(sequence, i);
645                 const char *filepath = PyUnicode_AsUTF8(item);
646                 if(filepath == NULL) {
647                         PyErr_SetString(PyExc_ValueError, "File paths must be a string or sequence of strings.");
648                         Py_DECREF(sequence);
649                         return false;
650                 }
651                 filepaths.push_back(filepath);
652         }
653         Py_DECREF(sequence);
654
655         return true;
656 }
657
658 static PyObject *denoise_func(PyObject * /*self*/, PyObject *args, PyObject *keywords)
659 {
660         static const char *keyword_list[] = {"preferences", "scene", "view_layer",
661                                              "input", "output",
662                                              "tile_size", "samples", NULL};
663         PyObject *pypreferences, *pyscene, *pyrenderlayer;
664         PyObject *pyinput, *pyoutput = NULL;
665         int tile_size = 0, samples = 0;
666
667         if (!PyArg_ParseTupleAndKeywords(args, keywords, "OOOO|Oii", (char**)keyword_list,
668                                          &pypreferences, &pyscene, &pyrenderlayer,
669                                                                          &pyinput, &pyoutput,
670                                          &tile_size, &samples)) {
671                 return NULL;
672         }
673
674         /* Get device specification from preferences and scene. */
675         PointerRNA preferencesptr;
676         RNA_pointer_create(NULL, &RNA_UserPreferences, (void*)PyLong_AsVoidPtr(pypreferences), &preferencesptr);
677         BL::UserPreferences b_preferences(preferencesptr);
678
679         PointerRNA sceneptr;
680         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
681         BL::Scene b_scene(sceneptr);
682
683         DeviceInfo device = blender_device_info(b_preferences, b_scene, true);
684
685         /* Get denoising parameters from view layer. */
686         PointerRNA renderlayerptr;
687         RNA_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &RNA_SceneRenderLayer, PyLong_AsVoidPtr(pyrenderlayer), &renderlayerptr);
688         PointerRNA crenderlayer = RNA_pointer_get(&renderlayerptr, "cycles");
689
690         DenoiseParams params;
691         params.radius = get_int(crenderlayer, "denoising_radius");
692         params.strength = get_float(crenderlayer, "denoising_strength");
693         params.feature_strength = get_float(crenderlayer, "denoising_feature_strength");
694         params.relative_pca = get_boolean(crenderlayer, "denoising_relative_pca");
695         params.neighbor_frames = get_int(crenderlayer, "denoising_neighbor_frames");
696
697         /* Parse file paths list. */
698         vector<string> input, output;
699
700         if(!denoise_parse_filepaths(pyinput, input)) {
701                 return NULL;
702         }
703
704         if(pyoutput) {
705                 if(!denoise_parse_filepaths(pyoutput, output)) {
706                         return NULL;
707                 }
708         }
709         else {
710                 output = input;
711         }
712
713         if(input.empty()) {
714                 PyErr_SetString(PyExc_ValueError, "No input file paths specified.");
715                 return NULL;
716         }
717         if(input.size() != output.size()) {
718                 PyErr_SetString(PyExc_ValueError, "Number of input and output file paths does not match.");
719                 return NULL;
720         }
721
722         /* Create denoiser. */
723         Denoiser denoiser(device);
724         denoiser.params = params;
725         denoiser.input = input;
726         denoiser.output = output;
727
728         if (tile_size > 0) {
729                 denoiser.tile_size = make_int2(tile_size, tile_size);
730         }
731         if (samples > 0) {
732                 denoiser.samples_override = samples;
733         }
734
735         /* Run denoiser. */
736         if(!denoiser.run()) {
737                 PyErr_SetString(PyExc_ValueError, denoiser.error.c_str());
738                 return NULL;
739         }
740
741         Py_RETURN_NONE;
742 }
743
744 static PyObject *debug_flags_update_func(PyObject * /*self*/, PyObject *args)
745 {
746         PyObject *pyscene;
747         if(!PyArg_ParseTuple(args, "O", &pyscene)) {
748                 return NULL;
749         }
750
751         PointerRNA sceneptr;
752         RNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);
753         BL::Scene b_scene(sceneptr);
754
755         if(debug_flags_sync_from_scene(b_scene)) {
756                 VLOG(2) << "Tagging device list for update.";
757                 Device::tag_update();
758         }
759
760         VLOG(2) << "Debug flags set to:\n"
761                 << DebugFlags();
762
763         debug_flags_set = true;
764
765         Py_RETURN_NONE;
766 }
767
768 static PyObject *debug_flags_reset_func(PyObject * /*self*/, PyObject * /*args*/)
769 {
770         if(debug_flags_reset()) {
771                 VLOG(2) << "Tagging device list for update.";
772                 Device::tag_update();
773         }
774         if(debug_flags_set) {
775                 VLOG(2) << "Debug flags reset to:\n"
776                         << DebugFlags();
777                 debug_flags_set = false;
778         }
779         Py_RETURN_NONE;
780 }
781
782 static PyObject *set_resumable_chunk_func(PyObject * /*self*/, PyObject *args)
783 {
784         int num_resumable_chunks, current_resumable_chunk;
785         if(!PyArg_ParseTuple(args, "ii",
786                              &num_resumable_chunks,
787                              &current_resumable_chunk)) {
788                 Py_RETURN_NONE;
789         }
790
791         if(num_resumable_chunks <= 0) {
792                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
793                 abort();
794                 Py_RETURN_NONE;
795         }
796         if(current_resumable_chunk < 1 ||
797            current_resumable_chunk > num_resumable_chunks)
798         {
799                 fprintf(stderr, "Cycles: Bad value for current resumable chunk number.\n");
800                 abort();
801                 Py_RETURN_NONE;
802         }
803
804         VLOG(1) << "Initialized resumable render: "
805                 << "num_resumable_chunks=" << num_resumable_chunks << ", "
806                 << "current_resumable_chunk=" << current_resumable_chunk;
807         BlenderSession::num_resumable_chunks = num_resumable_chunks;
808         BlenderSession::current_resumable_chunk = current_resumable_chunk;
809
810         printf("Cycles: Will render chunk %d of %d\n",
811                current_resumable_chunk,
812                num_resumable_chunks);
813
814         Py_RETURN_NONE;
815 }
816
817 static PyObject *set_resumable_chunk_range_func(PyObject * /*self*/, PyObject *args)
818 {
819         int num_chunks, start_chunk, end_chunk;
820         if(!PyArg_ParseTuple(args, "iii",
821                              &num_chunks,
822                              &start_chunk,
823                              &end_chunk)) {
824                 Py_RETURN_NONE;
825         }
826
827         if(num_chunks <= 0) {
828                 fprintf(stderr, "Cycles: Bad value for number of resumable chunks.\n");
829                 abort();
830                 Py_RETURN_NONE;
831         }
832         if(start_chunk < 1 || start_chunk > num_chunks) {
833                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
834                 abort();
835                 Py_RETURN_NONE;
836         }
837         if(end_chunk < 1 || end_chunk > num_chunks) {
838                 fprintf(stderr, "Cycles: Bad value for start chunk number.\n");
839                 abort();
840                 Py_RETURN_NONE;
841         }
842         if(start_chunk > end_chunk) {
843                 fprintf(stderr, "Cycles: End chunk should be higher than start one.\n");
844                 abort();
845                 Py_RETURN_NONE;
846         }
847
848         VLOG(1) << "Initialized resumable render: "
849                 << "num_resumable_chunks=" << num_chunks << ", "
850                 << "start_resumable_chunk=" << start_chunk
851                 << "end_resumable_chunk=" << end_chunk;
852         BlenderSession::num_resumable_chunks = num_chunks;
853         BlenderSession::start_resumable_chunk = start_chunk;
854         BlenderSession::end_resumable_chunk = end_chunk;
855
856         printf("Cycles: Will render chunks %d to %d of %d\n",
857                start_chunk,
858                end_chunk,
859                num_chunks);
860
861         Py_RETURN_NONE;
862 }
863
864 static PyObject *enable_print_stats_func(PyObject * /*self*/, PyObject * /*args*/)
865 {
866         BlenderSession::print_render_stats = true;
867         Py_RETURN_NONE;
868 }
869
870 static PyObject *get_device_types_func(PyObject * /*self*/, PyObject * /*args*/)
871 {
872         vector<DeviceType> device_types = Device::available_types();
873         bool has_cuda = false, has_opencl = false;
874         foreach(DeviceType device_type, device_types) {
875                 has_cuda   |= (device_type == DEVICE_CUDA);
876                 has_opencl |= (device_type == DEVICE_OPENCL);
877         }
878         PyObject *list = PyTuple_New(2);
879         PyTuple_SET_ITEM(list, 0, PyBool_FromLong(has_cuda));
880         PyTuple_SET_ITEM(list, 1, PyBool_FromLong(has_opencl));
881         return list;
882 }
883
884 static PyMethodDef methods[] = {
885         {"init", init_func, METH_VARARGS, ""},
886         {"exit", exit_func, METH_VARARGS, ""},
887         {"create", create_func, METH_VARARGS, ""},
888         {"free", free_func, METH_O, ""},
889         {"render", render_func, METH_O, ""},
890         {"bake", bake_func, METH_VARARGS, ""},
891         {"draw", draw_func, METH_VARARGS, ""},
892         {"sync", sync_func, METH_O, ""},
893         {"reset", reset_func, METH_VARARGS, ""},
894 #ifdef WITH_OSL
895         {"osl_update_node", osl_update_node_func, METH_VARARGS, ""},
896         {"osl_compile", osl_compile_func, METH_VARARGS, ""},
897 #endif
898         {"available_devices", available_devices_func, METH_VARARGS, ""},
899         {"system_info", system_info_func, METH_NOARGS, ""},
900 #ifdef WITH_OPENCL
901         {"opencl_disable", opencl_disable_func, METH_NOARGS, ""},
902 #endif
903
904         /* Standalone denoising */
905         {"denoise", (PyCFunction)denoise_func, METH_VARARGS|METH_KEYWORDS, ""},
906
907         /* Debugging routines */
908         {"debug_flags_update", debug_flags_update_func, METH_VARARGS, ""},
909         {"debug_flags_reset", debug_flags_reset_func, METH_NOARGS, ""},
910
911         /* Statistics. */
912         {"enable_print_stats", enable_print_stats_func, METH_NOARGS, ""},
913
914         /* Resumable render */
915         {"set_resumable_chunk", set_resumable_chunk_func, METH_VARARGS, ""},
916         {"set_resumable_chunk_range", set_resumable_chunk_range_func, METH_VARARGS, ""},
917
918         /* Compute Device selection */
919         {"get_device_types", get_device_types_func, METH_VARARGS, ""},
920
921         {NULL, NULL, 0, NULL},
922 };
923
924 static struct PyModuleDef module = {
925         PyModuleDef_HEAD_INIT,
926         "_cycles",
927         "Blender cycles render integration",
928         -1,
929         methods,
930         NULL, NULL, NULL, NULL
931 };
932
933 CCL_NAMESPACE_END
934
935 void *CCL_python_module_init()
936 {
937         PyObject *mod = PyModule_Create(&ccl::module);
938
939 #ifdef WITH_OSL
940         /* TODO(sergey): This gives us library we've been linking against.
941          *               In theory with dynamic OSL library it might not be
942          *               accurate, but there's nothing in OSL API which we
943          *               might use to get version in runtime.
944          */
945         int curversion = OSL_LIBRARY_VERSION_CODE;
946         PyModule_AddObject(mod, "with_osl", Py_True);
947         Py_INCREF(Py_True);
948         PyModule_AddObject(mod, "osl_version",
949                            Py_BuildValue("(iii)",
950                                           curversion / 10000, (curversion / 100) % 100, curversion % 100));
951         PyModule_AddObject(mod, "osl_version_string",
952                            PyUnicode_FromFormat("%2d, %2d, %2d",
953                                                 curversion / 10000, (curversion / 100) % 100, curversion % 100));
954 #else
955         PyModule_AddObject(mod, "with_osl", Py_False);
956         Py_INCREF(Py_False);
957         PyModule_AddStringConstant(mod, "osl_version", "unknown");
958         PyModule_AddStringConstant(mod, "osl_version_string", "unknown");
959 #endif
960
961 #ifdef WITH_CYCLES_DEBUG
962         PyModule_AddObject(mod, "with_cycles_debug", Py_True);
963         Py_INCREF(Py_True);
964 #else
965         PyModule_AddObject(mod, "with_cycles_debug", Py_False);
966         Py_INCREF(Py_False);
967 #endif
968
969 #ifdef WITH_NETWORK
970         PyModule_AddObject(mod, "with_network", Py_True);
971         Py_INCREF(Py_True);
972 #else  /* WITH_NETWORK */
973         PyModule_AddObject(mod, "with_network", Py_False);
974         Py_INCREF(Py_False);
975 #endif  /* WITH_NETWORK */
976
977 #ifdef WITH_EMBREE
978         PyModule_AddObject(mod, "with_embree", Py_True);
979         Py_INCREF(Py_True);
980 #else  /* WITH_EMBREE */
981         PyModule_AddObject(mod, "with_embree", Py_False);
982         Py_INCREF(Py_False);
983 #endif  /* WITH_EMBREE */
984
985         return (void*)mod;
986 }