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