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