4417065bb7fb5770c4da628b7ac5e9cc53301fe9
[blender.git] / intern / cycles / device / opencl / opencl_base.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 #ifdef WITH_OPENCL
18
19 #include "device/opencl/opencl.h"
20
21 #include "kernel/kernel_types.h"
22
23 #include "util/util_algorithm.h"
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_path.h"
29 #include "util/util_time.h"
30
31 CCL_NAMESPACE_BEGIN
32
33 struct texture_slot_t {
34         texture_slot_t(const string& name, int slot)
35                 : name(name),
36                   slot(slot) {
37         }
38         string name;
39         int slot;
40 };
41
42 bool OpenCLDeviceBase::opencl_error(cl_int err)
43 {
44         if(err != CL_SUCCESS) {
45                 string message = string_printf("OpenCL error (%d): %s", err, clewErrorString(err));
46                 if(error_msg == "")
47                         error_msg = message;
48                 fprintf(stderr, "%s\n", message.c_str());
49                 return true;
50         }
51
52         return false;
53 }
54
55 void OpenCLDeviceBase::opencl_error(const string& message)
56 {
57         if(error_msg == "")
58                 error_msg = message;
59         fprintf(stderr, "%s\n", message.c_str());
60 }
61
62 void OpenCLDeviceBase::opencl_assert_err(cl_int err, const char* where)
63 {
64         if(err != CL_SUCCESS) {
65                 string message = string_printf("OpenCL error (%d): %s in %s", err, clewErrorString(err), where);
66                 if(error_msg == "")
67                         error_msg = message;
68                 fprintf(stderr, "%s\n", message.c_str());
69 #ifndef NDEBUG
70                 abort();
71 #endif
72         }
73 }
74
75 OpenCLDeviceBase::OpenCLDeviceBase(DeviceInfo& info, Stats &stats, Profiler &profiler, bool background_)
76 : Device(info, stats, profiler, background_),
77   memory_manager(this),
78   texture_info(this, "__texture_info", MEM_TEXTURE)
79 {
80         cpPlatform = NULL;
81         cdDevice = NULL;
82         cxContext = NULL;
83         cqCommandQueue = NULL;
84         null_mem = 0;
85         device_initialized = false;
86         textures_need_update = true;
87
88         vector<OpenCLPlatformDevice> usable_devices;
89         OpenCLInfo::get_usable_devices(&usable_devices);
90         if(usable_devices.size() == 0) {
91                 opencl_error("OpenCL: no devices found.");
92                 return;
93         }
94         assert(info.num < usable_devices.size());
95         OpenCLPlatformDevice& platform_device = usable_devices[info.num];
96         cpPlatform = platform_device.platform_id;
97         cdDevice = platform_device.device_id;
98         platform_name = platform_device.platform_name;
99         device_name = platform_device.device_name;
100         VLOG(2) << "Creating new Cycles device for OpenCL platform "
101                 << platform_name << ", device "
102                 << device_name << ".";
103
104         {
105                 /* try to use cached context */
106                 thread_scoped_lock cache_locker;
107                 cxContext = OpenCLCache::get_context(cpPlatform, cdDevice, cache_locker);
108
109                 if(cxContext == NULL) {
110                         /* create context properties array to specify platform */
111                         const cl_context_properties context_props[] = {
112                                 CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform,
113                                 0, 0
114                         };
115
116                         /* create context */
117                         cxContext = clCreateContext(context_props, 1, &cdDevice,
118                                 context_notify_callback, cdDevice, &ciErr);
119
120                         if(opencl_error(ciErr)) {
121                                 opencl_error("OpenCL: clCreateContext failed");
122                                 return;
123                         }
124
125                         /* cache it */
126                         OpenCLCache::store_context(cpPlatform, cdDevice, cxContext, cache_locker);
127                 }
128         }
129
130         cqCommandQueue = clCreateCommandQueue(cxContext, cdDevice, 0, &ciErr);
131         if(opencl_error(ciErr)) {
132                 opencl_error("OpenCL: Error creating command queue");
133                 return;
134         }
135
136         null_mem = (device_ptr)clCreateBuffer(cxContext, CL_MEM_READ_ONLY, 1, NULL, &ciErr);
137         if(opencl_error(ciErr)) {
138                 opencl_error("OpenCL: Error creating memory buffer for NULL");
139                 return;
140         }
141
142         /* Allocate this right away so that texture_info is placed at offset 0 in the device memory buffers */
143         texture_info.resize(1);
144         memory_manager.alloc("texture_info", texture_info);
145
146         fprintf(stderr, "Device init success\n");
147         device_initialized = true;
148 }
149
150 OpenCLDeviceBase::~OpenCLDeviceBase()
151 {
152         task_pool.stop();
153
154         memory_manager.free();
155
156         if(null_mem)
157                 clReleaseMemObject(CL_MEM_PTR(null_mem));
158
159         ConstMemMap::iterator mt;
160         for(mt = const_mem_map.begin(); mt != const_mem_map.end(); mt++) {
161                 delete mt->second;
162         }
163
164         base_program.release();
165         if(cqCommandQueue)
166                 clReleaseCommandQueue(cqCommandQueue);
167         if(cxContext)
168                 clReleaseContext(cxContext);
169 }
170
171 void CL_CALLBACK OpenCLDeviceBase::context_notify_callback(const char *err_info,
172         const void * /*private_info*/, size_t /*cb*/, void *user_data)
173 {
174         string device_name = OpenCLInfo::get_device_name((cl_device_id)user_data);
175         fprintf(stderr, "OpenCL error (%s): %s\n", device_name.c_str(), err_info);
176 }
177
178 bool OpenCLDeviceBase::opencl_version_check()
179 {
180         string error;
181         if(!OpenCLInfo::platform_version_check(cpPlatform, &error)) {
182                 opencl_error(error);
183                 return false;
184         }
185         if(!OpenCLInfo::device_version_check(cdDevice, &error)) {
186                 opencl_error(error);
187                 return false;
188         }
189         return true;
190 }
191
192 string OpenCLDeviceBase::device_md5_hash(string kernel_custom_build_options)
193 {
194         MD5Hash md5;
195         char version[256], driver[256], name[256], vendor[256];
196
197         clGetPlatformInfo(cpPlatform, CL_PLATFORM_VENDOR, sizeof(vendor), &vendor, NULL);
198         clGetDeviceInfo(cdDevice, CL_DEVICE_VERSION, sizeof(version), &version, NULL);
199         clGetDeviceInfo(cdDevice, CL_DEVICE_NAME, sizeof(name), &name, NULL);
200         clGetDeviceInfo(cdDevice, CL_DRIVER_VERSION, sizeof(driver), &driver, NULL);
201
202         md5.append((uint8_t*)vendor, strlen(vendor));
203         md5.append((uint8_t*)version, strlen(version));
204         md5.append((uint8_t*)name, strlen(name));
205         md5.append((uint8_t*)driver, strlen(driver));
206
207         string options = kernel_build_options();
208         options += kernel_custom_build_options;
209         md5.append((uint8_t*)options.c_str(), options.size());
210
211         return md5.get_hex();
212 }
213
214 bool OpenCLDeviceBase::load_kernels(const DeviceRequestedFeatures& requested_features)
215 {
216         VLOG(2) << "Loading kernels for platform " << platform_name
217                 << ", device " << device_name << ".";
218         /* Verify if device was initialized. */
219         if(!device_initialized) {
220                 fprintf(stderr, "OpenCL: failed to initialize device.\n");
221                 return false;
222         }
223
224         /* Verify we have right opencl version. */
225         if(!opencl_version_check())
226                 return false;
227
228         base_program = OpenCLProgram(this, "base", "kernel.cl", build_options_for_base_program(requested_features));
229         base_program.add_kernel(ustring("convert_to_byte"));
230         base_program.add_kernel(ustring("convert_to_half_float"));
231         base_program.add_kernel(ustring("displace"));
232         base_program.add_kernel(ustring("background"));
233         base_program.add_kernel(ustring("bake"));
234         base_program.add_kernel(ustring("zero_buffer"));
235
236         denoising_program = OpenCLProgram(this, "denoising", "filter.cl", "");
237         denoising_program.add_kernel(ustring("filter_divide_shadow"));
238         denoising_program.add_kernel(ustring("filter_get_feature"));
239         denoising_program.add_kernel(ustring("filter_detect_outliers"));
240         denoising_program.add_kernel(ustring("filter_combine_halves"));
241         denoising_program.add_kernel(ustring("filter_construct_transform"));
242         denoising_program.add_kernel(ustring("filter_nlm_calc_difference"));
243         denoising_program.add_kernel(ustring("filter_nlm_blur"));
244         denoising_program.add_kernel(ustring("filter_nlm_calc_weight"));
245         denoising_program.add_kernel(ustring("filter_nlm_update_output"));
246         denoising_program.add_kernel(ustring("filter_nlm_normalize"));
247         denoising_program.add_kernel(ustring("filter_nlm_construct_gramian"));
248         denoising_program.add_kernel(ustring("filter_finalize"));
249
250         vector<OpenCLProgram*> programs;
251         programs.push_back(&base_program);
252         programs.push_back(&denoising_program);
253         /* Call actual class to fill the vector with its programs. */
254         if(!load_kernels(requested_features, programs)) {
255                 return false;
256         }
257
258         /* Parallel compilation is supported by Cycles, but currently all OpenCL frameworks
259          * serialize the calls internally, so it's not much use right now.
260          * Note: When enabling parallel compilation, use_stdout in the OpenCLProgram constructor
261          * should be set to false as well. */
262 #if 0
263         TaskPool task_pool;
264         foreach(OpenCLProgram *program, programs) {
265                 task_pool.push(function_bind(&OpenCLProgram::load, program));
266         }
267         task_pool.wait_work();
268
269         foreach(OpenCLProgram *program, programs) {
270                 VLOG(2) << program->get_log();
271                 if(!program->is_loaded()) {
272                         program->report_error();
273                         return false;
274                 }
275         }
276 #else
277         foreach(OpenCLProgram *program, programs) {
278                 program->load();
279                 if(!program->is_loaded()) {
280                         return false;
281                 }
282         }
283 #endif
284
285         return true;
286 }
287
288 void OpenCLDeviceBase::mem_alloc(device_memory& mem)
289 {
290         if(mem.name) {
291                 VLOG(1) << "Buffer allocate: " << mem.name << ", "
292                             << string_human_readable_number(mem.memory_size()) << " bytes. ("
293                             << string_human_readable_size(mem.memory_size()) << ")";
294         }
295
296         size_t size = mem.memory_size();
297
298         /* check there is enough memory available for the allocation */
299         cl_ulong max_alloc_size = 0;
300         clGetDeviceInfo(cdDevice, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_alloc_size, NULL);
301
302         if(DebugFlags().opencl.mem_limit) {
303                 max_alloc_size = min(max_alloc_size,
304                                      cl_ulong(DebugFlags().opencl.mem_limit - stats.mem_used));
305         }
306
307         if(size > max_alloc_size) {
308                 string error = "Scene too complex to fit in available memory.";
309                 if(mem.name != NULL) {
310                         error += string_printf(" (allocating buffer %s failed.)", mem.name);
311                 }
312                 set_error(error);
313
314                 return;
315         }
316
317         cl_mem_flags mem_flag;
318         void *mem_ptr = NULL;
319
320         if(mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
321                 mem_flag = CL_MEM_READ_ONLY;
322         else
323                 mem_flag = CL_MEM_READ_WRITE;
324
325         /* Zero-size allocation might be invoked by render, but not really
326          * supported by OpenCL. Using NULL as device pointer also doesn't really
327          * work for some reason, so for the time being we'll use special case
328          * will null_mem buffer.
329          */
330         if(size != 0) {
331                 mem.device_pointer = (device_ptr)clCreateBuffer(cxContext,
332                                                                 mem_flag,
333                                                                 size,
334                                                                 mem_ptr,
335                                                                 &ciErr);
336                 opencl_assert_err(ciErr, "clCreateBuffer");
337         }
338         else {
339                 mem.device_pointer = null_mem;
340         }
341
342         stats.mem_alloc(size);
343         mem.device_size = size;
344 }
345
346 void OpenCLDeviceBase::mem_copy_to(device_memory& mem)
347 {
348         if(mem.type == MEM_TEXTURE) {
349                 tex_free(mem);
350                 tex_alloc(mem);
351         }
352         else {
353                 if(!mem.device_pointer) {
354                         mem_alloc(mem);
355                 }
356
357                 /* this is blocking */
358                 size_t size = mem.memory_size();
359                 if(size != 0) {
360                         opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
361                                                            CL_MEM_PTR(mem.device_pointer),
362                                                            CL_TRUE,
363                                                            0,
364                                                            size,
365                                                            mem.host_pointer,
366                                                            0,
367                                                            NULL, NULL));
368                 }
369         }
370 }
371
372 void OpenCLDeviceBase::mem_copy_from(device_memory& mem, int y, int w, int h, int elem)
373 {
374         size_t offset = elem*y*w;
375         size_t size = elem*w*h;
376         assert(size != 0);
377         opencl_assert(clEnqueueReadBuffer(cqCommandQueue,
378                                           CL_MEM_PTR(mem.device_pointer),
379                                           CL_TRUE,
380                                           offset,
381                                           size,
382                                           (uchar*)mem.host_pointer + offset,
383                                           0,
384                                           NULL, NULL));
385 }
386
387 void OpenCLDeviceBase::mem_zero_kernel(device_ptr mem, size_t size)
388 {
389         cl_kernel ckZeroBuffer = base_program(ustring("zero_buffer"));
390
391         size_t global_size[] = {1024, 1024};
392         size_t num_threads = global_size[0] * global_size[1];
393
394         cl_mem d_buffer = CL_MEM_PTR(mem);
395         cl_ulong d_offset = 0;
396         cl_ulong d_size = 0;
397
398         while(d_offset < size) {
399                 d_size = std::min<cl_ulong>(num_threads*sizeof(float4), size - d_offset);
400
401                 kernel_set_args(ckZeroBuffer, 0, d_buffer, d_size, d_offset);
402
403                 ciErr = clEnqueueNDRangeKernel(cqCommandQueue,
404                                                ckZeroBuffer,
405                                                2,
406                                                NULL,
407                                                global_size,
408                                                NULL,
409                                                0,
410                                                NULL,
411                                                NULL);
412                 opencl_assert_err(ciErr, "clEnqueueNDRangeKernel");
413
414                 d_offset += d_size;
415         }
416 }
417
418 void OpenCLDeviceBase::mem_zero(device_memory& mem)
419 {
420         if(!mem.device_pointer) {
421                 mem_alloc(mem);
422         }
423
424         if(mem.device_pointer) {
425                 if(base_program.is_loaded()) {
426                         mem_zero_kernel(mem.device_pointer, mem.memory_size());
427                 }
428
429                 if(mem.host_pointer) {
430                         memset(mem.host_pointer, 0, mem.memory_size());
431                 }
432
433                 if(!base_program.is_loaded()) {
434                         void* zero = mem.host_pointer;
435
436                         if(!mem.host_pointer) {
437                                 zero = util_aligned_malloc(mem.memory_size(), 16);
438                                 memset(zero, 0, mem.memory_size());
439                         }
440
441                         opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
442                                                            CL_MEM_PTR(mem.device_pointer),
443                                                            CL_TRUE,
444                                                            0,
445                                                            mem.memory_size(),
446                                                            zero,
447                                                            0,
448                                                            NULL, NULL));
449
450                         if(!mem.host_pointer) {
451                                 util_aligned_free(zero);
452                         }
453                 }
454         }
455 }
456
457 void OpenCLDeviceBase::mem_free(device_memory& mem)
458 {
459         if(mem.type == MEM_TEXTURE) {
460                 tex_free(mem);
461         }
462         else {
463                 if(mem.device_pointer) {
464                         if(mem.device_pointer != null_mem) {
465                                 opencl_assert(clReleaseMemObject(CL_MEM_PTR(mem.device_pointer)));
466                         }
467                         mem.device_pointer = 0;
468
469                         stats.mem_free(mem.device_size);
470                         mem.device_size = 0;
471                 }
472         }
473 }
474
475 int OpenCLDeviceBase::mem_sub_ptr_alignment()
476 {
477         return OpenCLInfo::mem_sub_ptr_alignment(cdDevice);
478 }
479
480 device_ptr OpenCLDeviceBase::mem_alloc_sub_ptr(device_memory& mem, int offset, int size)
481 {
482         cl_mem_flags mem_flag;
483         if(mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
484                 mem_flag = CL_MEM_READ_ONLY;
485         else
486                 mem_flag = CL_MEM_READ_WRITE;
487
488         cl_buffer_region info;
489         info.origin = mem.memory_elements_size(offset);
490         info.size = mem.memory_elements_size(size);
491
492         device_ptr sub_buf = (device_ptr) clCreateSubBuffer(CL_MEM_PTR(mem.device_pointer),
493                                                             mem_flag,
494                                                             CL_BUFFER_CREATE_TYPE_REGION,
495                                                             &info,
496                                                             &ciErr);
497         opencl_assert_err(ciErr, "clCreateSubBuffer");
498         return sub_buf;
499 }
500
501 void OpenCLDeviceBase::mem_free_sub_ptr(device_ptr device_pointer)
502 {
503         if(device_pointer && device_pointer != null_mem) {
504                 opencl_assert(clReleaseMemObject(CL_MEM_PTR(device_pointer)));
505         }
506 }
507
508 void OpenCLDeviceBase::const_copy_to(const char *name, void *host, size_t size)
509 {
510         ConstMemMap::iterator i = const_mem_map.find(name);
511         device_vector<uchar> *data;
512
513         if(i == const_mem_map.end()) {
514                 data = new device_vector<uchar>(this, name, MEM_READ_ONLY);
515                 data->alloc(size);
516                 const_mem_map.insert(ConstMemMap::value_type(name, data));
517         }
518         else {
519                 data = i->second;
520         }
521
522         memcpy(data->data(), host, size);
523         data->copy_to_device();
524 }
525
526 void OpenCLDeviceBase::tex_alloc(device_memory& mem)
527 {
528         VLOG(1) << "Texture allocate: " << mem.name << ", "
529                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
530                 << string_human_readable_size(mem.memory_size()) << ")";
531
532         memory_manager.alloc(mem.name, mem);
533         /* Set the pointer to non-null to keep code that inspects its value from thinking its unallocated. */
534         mem.device_pointer = 1;
535         textures[mem.name] = &mem;
536         textures_need_update = true;
537 }
538
539 void OpenCLDeviceBase::tex_free(device_memory& mem)
540 {
541         if(mem.device_pointer) {
542                 mem.device_pointer = 0;
543
544                 if(memory_manager.free(mem)) {
545                         textures_need_update = true;
546                 }
547
548                 foreach(TexturesMap::value_type& value, textures) {
549                         if(value.second == &mem) {
550                                 textures.erase(value.first);
551                                 break;
552                         }
553                 }
554         }
555 }
556
557 size_t OpenCLDeviceBase::global_size_round_up(int group_size, int global_size)
558 {
559         int r = global_size % group_size;
560         return global_size + ((r == 0)? 0: group_size - r);
561 }
562
563 void OpenCLDeviceBase::enqueue_kernel(cl_kernel kernel, size_t w, size_t h, bool x_workgroups, size_t max_workgroup_size)
564 {
565         size_t workgroup_size, max_work_items[3];
566
567         clGetKernelWorkGroupInfo(kernel, cdDevice,
568                 CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL);
569         clGetDeviceInfo(cdDevice,
570                 CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t)*3, max_work_items, NULL);
571
572         if(max_workgroup_size > 0 && workgroup_size > max_workgroup_size) {
573                 workgroup_size = max_workgroup_size;
574         }
575
576         /* Try to divide evenly over 2 dimensions. */
577         size_t local_size[2];
578         if(x_workgroups) {
579                 local_size[0] = workgroup_size;
580                 local_size[1] = 1;
581         }
582         else {
583                 size_t sqrt_workgroup_size = max((size_t)sqrt((double)workgroup_size), 1);
584                 local_size[0] = local_size[1] = sqrt_workgroup_size;
585         }
586
587         /* Some implementations have max size 1 on 2nd dimension. */
588         if(local_size[1] > max_work_items[1]) {
589                 local_size[0] = workgroup_size/max_work_items[1];
590                 local_size[1] = max_work_items[1];
591         }
592
593         size_t global_size[2] = {global_size_round_up(local_size[0], w),
594                                  global_size_round_up(local_size[1], h)};
595
596         /* Vertical size of 1 is coming from bake/shade kernels where we should
597          * not round anything up because otherwise we'll either be doing too
598          * much work per pixel (if we don't check global ID on Y axis) or will
599          * be checking for global ID to always have Y of 0.
600          */
601         if(h == 1) {
602                 global_size[h] = 1;
603         }
604
605         /* run kernel */
606         opencl_assert(clEnqueueNDRangeKernel(cqCommandQueue, kernel, 2, NULL, global_size, NULL, 0, NULL, NULL));
607         opencl_assert(clFlush(cqCommandQueue));
608 }
609
610 void OpenCLDeviceBase::set_kernel_arg_mem(cl_kernel kernel, cl_uint *narg, const char *name)
611 {
612         cl_mem ptr;
613
614         MemMap::iterator i = mem_map.find(name);
615         if(i != mem_map.end()) {
616                 ptr = CL_MEM_PTR(i->second);
617         }
618         else {
619                 /* work around NULL not working, even though the spec says otherwise */
620                 ptr = CL_MEM_PTR(null_mem);
621         }
622
623         opencl_assert(clSetKernelArg(kernel, (*narg)++, sizeof(ptr), (void*)&ptr));
624 }
625
626 void OpenCLDeviceBase::set_kernel_arg_buffers(cl_kernel kernel, cl_uint *narg)
627 {
628         flush_texture_buffers();
629
630         memory_manager.set_kernel_arg_buffers(kernel, narg);
631 }
632
633 void OpenCLDeviceBase::flush_texture_buffers()
634 {
635         if(!textures_need_update) {
636                 return;
637         }
638         textures_need_update = false;
639
640         /* Setup slots for textures. */
641         int num_slots = 0;
642
643         vector<texture_slot_t> texture_slots;
644
645 #define KERNEL_TEX(type, name) \
646         if(textures.find(#name) != textures.end()) { \
647                 texture_slots.push_back(texture_slot_t(#name, num_slots)); \
648         } \
649         num_slots++;
650 #include "kernel/kernel_textures.h"
651
652         int num_data_slots = num_slots;
653
654         foreach(TexturesMap::value_type& tex, textures) {
655                 string name = tex.first;
656
657                 if(string_startswith(name, "__tex_image")) {
658                         int pos = name.rfind("_");
659                         int id = atoi(name.data() + pos + 1);
660                         texture_slots.push_back(texture_slot_t(name,
661                                                                    num_data_slots + id));
662                         num_slots = max(num_slots, num_data_slots + id + 1);
663                 }
664         }
665
666         /* Realloc texture descriptors buffer. */
667         memory_manager.free(texture_info);
668         texture_info.resize(num_slots);
669         memory_manager.alloc("texture_info", texture_info);
670
671         /* Fill in descriptors */
672         foreach(texture_slot_t& slot, texture_slots) {
673                 TextureInfo& info = texture_info[slot.slot];
674
675                 MemoryManager::BufferDescriptor desc = memory_manager.get_descriptor(slot.name);
676                 info.data = desc.offset;
677                 info.cl_buffer = desc.device_buffer;
678
679                 if(string_startswith(slot.name, "__tex_image")) {
680                         device_memory *mem = textures[slot.name];
681
682                         info.width = mem->data_width;
683                         info.height = mem->data_height;
684                         info.depth = mem->data_depth;
685
686                         info.interpolation = mem->interpolation;
687                         info.extension = mem->extension;
688                 }
689         }
690
691         /* Force write of descriptors. */
692         memory_manager.free(texture_info);
693         memory_manager.alloc("texture_info", texture_info);
694 }
695
696 void OpenCLDeviceBase::film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half)
697 {
698         /* cast arguments to cl types */
699         cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
700         cl_mem d_rgba = (rgba_byte)? CL_MEM_PTR(rgba_byte): CL_MEM_PTR(rgba_half);
701         cl_mem d_buffer = CL_MEM_PTR(buffer);
702         cl_int d_x = task.x;
703         cl_int d_y = task.y;
704         cl_int d_w = task.w;
705         cl_int d_h = task.h;
706         cl_float d_sample_scale = 1.0f/(task.sample + 1);
707         cl_int d_offset = task.offset;
708         cl_int d_stride = task.stride;
709
710
711         cl_kernel ckFilmConvertKernel = (rgba_byte)? base_program(ustring("convert_to_byte")): base_program(ustring("convert_to_half_float"));
712
713         cl_uint start_arg_index =
714                 kernel_set_args(ckFilmConvertKernel,
715                                 0,
716                                 d_data,
717                                 d_rgba,
718                                 d_buffer);
719
720         set_kernel_arg_buffers(ckFilmConvertKernel, &start_arg_index);
721
722         start_arg_index += kernel_set_args(ckFilmConvertKernel,
723                                            start_arg_index,
724                                            d_sample_scale,
725                                            d_x,
726                                            d_y,
727                                            d_w,
728                                            d_h,
729                                            d_offset,
730                                            d_stride);
731
732         enqueue_kernel(ckFilmConvertKernel, d_w, d_h);
733 }
734
735 bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr,
736                                                  device_ptr guide_ptr,
737                                                  device_ptr variance_ptr,
738                                                  device_ptr out_ptr,
739                                                  DenoisingTask *task)
740 {
741         int stride = task->buffer.stride;
742         int w = task->buffer.width;
743         int h = task->buffer.h;
744         int r = task->nlm_state.r;
745         int f = task->nlm_state.f;
746         float a = task->nlm_state.a;
747         float k_2 = task->nlm_state.k_2;
748
749         int pass_stride = task->buffer.pass_stride;
750         int num_shifts = (2*r+1)*(2*r+1);
751         int channel_offset = task->nlm_state.is_color? task->buffer.pass_stride : 0;
752
753         device_sub_ptr difference(task->buffer.temporary_mem, 0, pass_stride*num_shifts);
754         device_sub_ptr blurDifference(task->buffer.temporary_mem, pass_stride*num_shifts, pass_stride*num_shifts);
755         device_sub_ptr weightAccum(task->buffer.temporary_mem, 2*pass_stride*num_shifts, pass_stride);
756         cl_mem weightAccum_mem = CL_MEM_PTR(*weightAccum);
757         cl_mem difference_mem = CL_MEM_PTR(*difference);
758         cl_mem blurDifference_mem = CL_MEM_PTR(*blurDifference);
759
760         cl_mem image_mem = CL_MEM_PTR(image_ptr);
761         cl_mem guide_mem = CL_MEM_PTR(guide_ptr);
762         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
763         cl_mem out_mem = CL_MEM_PTR(out_ptr);
764         cl_mem scale_mem = NULL;
765
766         mem_zero_kernel(*weightAccum, sizeof(float)*pass_stride);
767         mem_zero_kernel(out_ptr, sizeof(float)*pass_stride);
768
769         cl_kernel ckNLMCalcDifference = denoising_program(ustring("filter_nlm_calc_difference"));
770         cl_kernel ckNLMBlur           = denoising_program(ustring("filter_nlm_blur"));
771         cl_kernel ckNLMCalcWeight     = denoising_program(ustring("filter_nlm_calc_weight"));
772         cl_kernel ckNLMUpdateOutput   = denoising_program(ustring("filter_nlm_update_output"));
773         cl_kernel ckNLMNormalize      = denoising_program(ustring("filter_nlm_normalize"));
774
775         kernel_set_args(ckNLMCalcDifference, 0,
776                         guide_mem,
777                         variance_mem,
778                         scale_mem,
779                         difference_mem,
780                         w, h, stride,
781                         pass_stride,
782                         r, channel_offset,
783                         0, a, k_2);
784         kernel_set_args(ckNLMBlur, 0,
785                         difference_mem,
786                         blurDifference_mem,
787                         w, h, stride,
788                         pass_stride,
789                         r, f);
790         kernel_set_args(ckNLMCalcWeight, 0,
791                         blurDifference_mem,
792                         difference_mem,
793                         w, h, stride,
794                         pass_stride,
795                         r, f);
796         kernel_set_args(ckNLMUpdateOutput, 0,
797                         blurDifference_mem,
798                         image_mem,
799                         out_mem,
800                         weightAccum_mem,
801                         w, h, stride,
802                         pass_stride,
803                         channel_offset,
804                         r, f);
805
806         enqueue_kernel(ckNLMCalcDifference, w*h, num_shifts, true);
807         enqueue_kernel(ckNLMBlur,           w*h, num_shifts, true);
808         enqueue_kernel(ckNLMCalcWeight,     w*h, num_shifts, true);
809         enqueue_kernel(ckNLMBlur,           w*h, num_shifts, true);
810         enqueue_kernel(ckNLMUpdateOutput,   w*h, num_shifts, true);
811
812         kernel_set_args(ckNLMNormalize, 0,
813                         out_mem, weightAccum_mem, w, h, stride);
814         enqueue_kernel(ckNLMNormalize, w, h);
815
816         return true;
817 }
818
819 bool OpenCLDeviceBase::denoising_construct_transform(DenoisingTask *task)
820 {
821         cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
822         cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
823         cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
824         cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
825
826         char use_time = task->buffer.use_time? 1 : 0;
827
828         cl_kernel ckFilterConstructTransform = denoising_program(ustring("filter_construct_transform"));
829
830         int arg_ofs = kernel_set_args(ckFilterConstructTransform, 0,
831                                       buffer_mem,
832                                       tile_info_mem);
833         cl_mem buffers[9];
834         for(int i = 0; i < 9; i++) {
835                 buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
836                 arg_ofs += kernel_set_args(ckFilterConstructTransform,
837                                            arg_ofs,
838                                            buffers[i]);
839         }
840         kernel_set_args(ckFilterConstructTransform,
841                         arg_ofs,
842                         transform_mem,
843                         rank_mem,
844                         task->filter_area,
845                         task->rect,
846                         task->buffer.pass_stride,
847                         task->buffer.frame_stride,
848                         use_time,
849                         task->radius,
850                         task->pca_threshold);
851
852         enqueue_kernel(ckFilterConstructTransform,
853                        task->storage.w,
854                        task->storage.h,
855                        256);
856
857         return true;
858 }
859
860 bool OpenCLDeviceBase::denoising_accumulate(device_ptr color_ptr,
861                                             device_ptr color_variance_ptr,
862                                             device_ptr scale_ptr,
863                                             int frame,
864                                             DenoisingTask *task)
865 {
866         cl_mem color_mem = CL_MEM_PTR(color_ptr);
867         cl_mem color_variance_mem = CL_MEM_PTR(color_variance_ptr);
868         cl_mem scale_mem = CL_MEM_PTR(scale_ptr);
869
870         cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
871         cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
872         cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
873         cl_mem XtWX_mem = CL_MEM_PTR(task->storage.XtWX.device_pointer);
874         cl_mem XtWY_mem = CL_MEM_PTR(task->storage.XtWY.device_pointer);
875
876         cl_kernel ckNLMCalcDifference   = denoising_program(ustring("filter_nlm_calc_difference"));
877         cl_kernel ckNLMBlur             = denoising_program(ustring("filter_nlm_blur"));
878         cl_kernel ckNLMCalcWeight       = denoising_program(ustring("filter_nlm_calc_weight"));
879         cl_kernel ckNLMConstructGramian = denoising_program(ustring("filter_nlm_construct_gramian"));
880
881         int w = task->reconstruction_state.source_w;
882         int h = task->reconstruction_state.source_h;
883         int stride = task->buffer.stride;
884         int frame_offset = frame * task->buffer.frame_stride;
885         int t = task->tile_info->frames[frame];
886         char use_time = task->buffer.use_time? 1 : 0;
887
888         int r = task->radius;
889         int pass_stride = task->buffer.pass_stride;
890         int num_shifts = (2*r+1)*(2*r+1);
891
892         device_sub_ptr difference(task->buffer.temporary_mem, 0, pass_stride*num_shifts);
893         device_sub_ptr blurDifference(task->buffer.temporary_mem, pass_stride*num_shifts, pass_stride*num_shifts);
894         cl_mem difference_mem = CL_MEM_PTR(*difference);
895         cl_mem blurDifference_mem = CL_MEM_PTR(*blurDifference);
896
897         kernel_set_args(ckNLMCalcDifference, 0,
898                         color_mem,
899                         color_variance_mem,
900                         scale_mem,
901                         difference_mem,
902                         w, h, stride,
903                         pass_stride,
904                         r,
905                         pass_stride,
906                         frame_offset,
907                         1.0f, task->nlm_k_2);
908         kernel_set_args(ckNLMBlur, 0,
909                         difference_mem,
910                         blurDifference_mem,
911                         w, h, stride,
912                         pass_stride,
913                         r, 4);
914         kernel_set_args(ckNLMCalcWeight, 0,
915                         blurDifference_mem,
916                         difference_mem,
917                         w, h, stride,
918                         pass_stride,
919                         r, 4);
920         kernel_set_args(ckNLMConstructGramian, 0,
921                         t,
922                         blurDifference_mem,
923                         buffer_mem,
924                         transform_mem,
925                         rank_mem,
926                         XtWX_mem,
927                         XtWY_mem,
928                         task->reconstruction_state.filter_window,
929                         w, h, stride,
930                         pass_stride,
931                         r, 4,
932                         frame_offset,
933                         use_time);
934
935         enqueue_kernel(ckNLMCalcDifference,   w*h, num_shifts, true);
936         enqueue_kernel(ckNLMBlur,             w*h, num_shifts, true);
937         enqueue_kernel(ckNLMCalcWeight,       w*h, num_shifts, true);
938         enqueue_kernel(ckNLMBlur,             w*h, num_shifts, true);
939         enqueue_kernel(ckNLMConstructGramian, w*h, num_shifts, true, 256);
940
941         return true;
942 }
943
944 bool OpenCLDeviceBase::denoising_solve(device_ptr output_ptr,
945                                        DenoisingTask *task)
946 {
947         cl_kernel ckFinalize = denoising_program(ustring("filter_finalize"));
948
949         cl_mem output_mem = CL_MEM_PTR(output_ptr);
950         cl_mem rank_mem   = CL_MEM_PTR(task->storage.rank.device_pointer);
951         cl_mem XtWX_mem   = CL_MEM_PTR(task->storage.XtWX.device_pointer);
952         cl_mem XtWY_mem   = CL_MEM_PTR(task->storage.XtWY.device_pointer);
953
954         int w = task->reconstruction_state.source_w;
955         int h = task->reconstruction_state.source_h;
956
957         kernel_set_args(ckFinalize, 0,
958                         output_mem,
959                         rank_mem,
960                         XtWX_mem,
961                         XtWY_mem,
962                         task->filter_area,
963                         task->reconstruction_state.buffer_params,
964                         task->render_buffer.samples);
965         enqueue_kernel(ckFinalize, w, h);
966
967         return true;
968 }
969
970 bool OpenCLDeviceBase::denoising_combine_halves(device_ptr a_ptr,
971                                                 device_ptr b_ptr,
972                                                 device_ptr mean_ptr,
973                                                 device_ptr variance_ptr,
974                                                 int r, int4 rect,
975                                                 DenoisingTask *task)
976 {
977         cl_mem a_mem = CL_MEM_PTR(a_ptr);
978         cl_mem b_mem = CL_MEM_PTR(b_ptr);
979         cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
980         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
981
982         cl_kernel ckFilterCombineHalves = denoising_program(ustring("filter_combine_halves"));
983
984         kernel_set_args(ckFilterCombineHalves, 0,
985                         mean_mem,
986                         variance_mem,
987                         a_mem,
988                         b_mem,
989                         rect,
990                         r);
991         enqueue_kernel(ckFilterCombineHalves,
992                        task->rect.z-task->rect.x,
993                        task->rect.w-task->rect.y);
994
995         return true;
996 }
997
998 bool OpenCLDeviceBase::denoising_divide_shadow(device_ptr a_ptr,
999                                                device_ptr b_ptr,
1000                                                device_ptr sample_variance_ptr,
1001                                                device_ptr sv_variance_ptr,
1002                                                device_ptr buffer_variance_ptr,
1003                                                DenoisingTask *task)
1004 {
1005         cl_mem a_mem = CL_MEM_PTR(a_ptr);
1006         cl_mem b_mem = CL_MEM_PTR(b_ptr);
1007         cl_mem sample_variance_mem = CL_MEM_PTR(sample_variance_ptr);
1008         cl_mem sv_variance_mem = CL_MEM_PTR(sv_variance_ptr);
1009         cl_mem buffer_variance_mem = CL_MEM_PTR(buffer_variance_ptr);
1010
1011         cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
1012
1013         cl_kernel ckFilterDivideShadow = denoising_program(ustring("filter_divide_shadow"));
1014
1015         int arg_ofs = kernel_set_args(ckFilterDivideShadow, 0,
1016                                       task->render_buffer.samples,
1017                                       tile_info_mem);
1018         cl_mem buffers[9];
1019         for(int i = 0; i < 9; i++) {
1020                 buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
1021                 arg_ofs += kernel_set_args(ckFilterDivideShadow, arg_ofs,
1022                                            buffers[i]);
1023         }
1024         kernel_set_args(ckFilterDivideShadow, arg_ofs,
1025                         a_mem,
1026                         b_mem,
1027                         sample_variance_mem,
1028                         sv_variance_mem,
1029                         buffer_variance_mem,
1030                         task->rect,
1031                         task->render_buffer.pass_stride,
1032                         task->render_buffer.offset);
1033         enqueue_kernel(ckFilterDivideShadow,
1034                        task->rect.z-task->rect.x,
1035                        task->rect.w-task->rect.y);
1036
1037         return true;
1038 }
1039
1040 bool OpenCLDeviceBase::denoising_get_feature(int mean_offset,
1041                                              int variance_offset,
1042                                              device_ptr mean_ptr,
1043                                              device_ptr variance_ptr,
1044                                              float scale,
1045                                              DenoisingTask *task)
1046 {
1047         cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
1048         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
1049
1050         cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
1051
1052         cl_kernel ckFilterGetFeature = denoising_program(ustring("filter_get_feature"));
1053
1054         int arg_ofs = kernel_set_args(ckFilterGetFeature, 0,
1055                                       task->render_buffer.samples,
1056                                       tile_info_mem);
1057         cl_mem buffers[9];
1058         for(int i = 0; i < 9; i++) {
1059                 buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
1060                 arg_ofs += kernel_set_args(ckFilterGetFeature, arg_ofs,
1061                                            buffers[i]);
1062         }
1063         kernel_set_args(ckFilterGetFeature, arg_ofs,
1064                         mean_offset,
1065                         variance_offset,
1066                         mean_mem,
1067                         variance_mem,
1068                         scale,
1069                         task->rect,
1070                         task->render_buffer.pass_stride,
1071                         task->render_buffer.offset);
1072         enqueue_kernel(ckFilterGetFeature,
1073                        task->rect.z-task->rect.x,
1074                        task->rect.w-task->rect.y);
1075
1076         return true;
1077 }
1078
1079 bool OpenCLDeviceBase::denoising_write_feature(int out_offset,
1080                                                device_ptr from_ptr,
1081                                                device_ptr buffer_ptr,
1082                                                DenoisingTask *task)
1083 {
1084         cl_mem from_mem = CL_MEM_PTR(from_ptr);
1085         cl_mem buffer_mem = CL_MEM_PTR(buffer_ptr);
1086
1087         cl_kernel ckFilterWriteFeature = denoising_program(ustring("filter_write_feature"));
1088
1089         kernel_set_args(ckFilterWriteFeature, 0,
1090                         task->render_buffer.samples,
1091                         task->reconstruction_state.buffer_params,
1092                         task->filter_area,
1093                         from_mem,
1094                         buffer_mem,
1095                         out_offset,
1096                         task->rect);
1097         enqueue_kernel(ckFilterWriteFeature,
1098                        task->filter_area.z,
1099                        task->filter_area.w);
1100
1101         return true;
1102 }
1103
1104 bool OpenCLDeviceBase::denoising_detect_outliers(device_ptr image_ptr,
1105                                                  device_ptr variance_ptr,
1106                                                  device_ptr depth_ptr,
1107                                                  device_ptr output_ptr,
1108                                                  DenoisingTask *task)
1109 {
1110         cl_mem image_mem = CL_MEM_PTR(image_ptr);
1111         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
1112         cl_mem depth_mem = CL_MEM_PTR(depth_ptr);
1113         cl_mem output_mem = CL_MEM_PTR(output_ptr);
1114
1115         cl_kernel ckFilterDetectOutliers = denoising_program(ustring("filter_detect_outliers"));
1116
1117         kernel_set_args(ckFilterDetectOutliers, 0,
1118                         image_mem,
1119                         variance_mem,
1120                         depth_mem,
1121                         output_mem,
1122                         task->rect,
1123                         task->buffer.pass_stride);
1124         enqueue_kernel(ckFilterDetectOutliers,
1125                        task->rect.z-task->rect.x,
1126                        task->rect.w-task->rect.y);
1127
1128         return true;
1129 }
1130
1131 void OpenCLDeviceBase::denoise(RenderTile &rtile, DenoisingTask& denoising)
1132 {
1133         denoising.functions.construct_transform = function_bind(&OpenCLDeviceBase::denoising_construct_transform, this, &denoising);
1134         denoising.functions.accumulate = function_bind(&OpenCLDeviceBase::denoising_accumulate, this, _1, _2, _3, _4, &denoising);
1135         denoising.functions.solve = function_bind(&OpenCLDeviceBase::denoising_solve, this, _1, &denoising);
1136         denoising.functions.divide_shadow = function_bind(&OpenCLDeviceBase::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
1137         denoising.functions.non_local_means = function_bind(&OpenCLDeviceBase::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
1138         denoising.functions.combine_halves = function_bind(&OpenCLDeviceBase::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
1139         denoising.functions.get_feature = function_bind(&OpenCLDeviceBase::denoising_get_feature, this, _1, _2, _3, _4, _5, &denoising);
1140         denoising.functions.write_feature = function_bind(&OpenCLDeviceBase::denoising_write_feature, this, _1, _2, _3, &denoising);
1141         denoising.functions.detect_outliers = function_bind(&OpenCLDeviceBase::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
1142
1143         denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h);
1144         denoising.render_buffer.samples = rtile.sample;
1145         denoising.buffer.gpu_temporary_mem = true;
1146
1147         denoising.run_denoising(&rtile);
1148 }
1149
1150 void OpenCLDeviceBase::shader(DeviceTask& task)
1151 {
1152         /* cast arguments to cl types */
1153         cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
1154         cl_mem d_input = CL_MEM_PTR(task.shader_input);
1155         cl_mem d_output = CL_MEM_PTR(task.shader_output);
1156         cl_int d_shader_eval_type = task.shader_eval_type;
1157         cl_int d_shader_filter = task.shader_filter;
1158         cl_int d_shader_x = task.shader_x;
1159         cl_int d_shader_w = task.shader_w;
1160         cl_int d_offset = task.offset;
1161
1162         cl_kernel kernel;
1163
1164         if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1165                 kernel = base_program(ustring("bake"));
1166         }
1167         else if(task.shader_eval_type == SHADER_EVAL_DISPLACE) {
1168                 kernel = base_program(ustring("displace"));
1169         }
1170         else {
1171                 kernel = base_program(ustring("background"));
1172         }
1173
1174         cl_uint start_arg_index =
1175                 kernel_set_args(kernel,
1176                                 0,
1177                                 d_data,
1178                                 d_input,
1179                                 d_output);
1180
1181         set_kernel_arg_buffers(kernel, &start_arg_index);
1182
1183         start_arg_index += kernel_set_args(kernel,
1184                                            start_arg_index,
1185                                            d_shader_eval_type);
1186         if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1187                 start_arg_index += kernel_set_args(kernel,
1188                                                    start_arg_index,
1189                                                    d_shader_filter);
1190         }
1191         start_arg_index += kernel_set_args(kernel,
1192                                            start_arg_index,
1193                                            d_shader_x,
1194                                            d_shader_w,
1195                                            d_offset);
1196
1197         for(int sample = 0; sample < task.num_samples; sample++) {
1198
1199                 if(task.get_cancel())
1200                         break;
1201
1202                 kernel_set_args(kernel, start_arg_index, sample);
1203
1204                 enqueue_kernel(kernel, task.shader_w, 1);
1205
1206                 clFinish(cqCommandQueue);
1207
1208                 task.update_progress(NULL);
1209         }
1210 }
1211
1212 string OpenCLDeviceBase::kernel_build_options(const string *debug_src)
1213 {
1214         string build_options = "-cl-no-signed-zeros -cl-mad-enable ";
1215
1216         if(platform_name == "NVIDIA CUDA") {
1217                 build_options += "-D__KERNEL_OPENCL_NVIDIA__ "
1218                                  "-cl-nv-maxrregcount=32 "
1219                                  "-cl-nv-verbose ";
1220
1221                 uint compute_capability_major, compute_capability_minor;
1222                 clGetDeviceInfo(cdDevice, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV,
1223                                 sizeof(cl_uint), &compute_capability_major, NULL);
1224                 clGetDeviceInfo(cdDevice, CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV,
1225                                 sizeof(cl_uint), &compute_capability_minor, NULL);
1226
1227                 build_options += string_printf("-D__COMPUTE_CAPABILITY__=%u ",
1228                                                compute_capability_major * 100 +
1229                                                compute_capability_minor * 10);
1230         }
1231
1232         else if(platform_name == "Apple")
1233                 build_options += "-D__KERNEL_OPENCL_APPLE__ ";
1234
1235         else if(platform_name == "AMD Accelerated Parallel Processing")
1236                 build_options += "-D__KERNEL_OPENCL_AMD__ ";
1237
1238         else if(platform_name == "Intel(R) OpenCL") {
1239                 build_options += "-D__KERNEL_OPENCL_INTEL_CPU__ ";
1240
1241                 /* Options for gdb source level kernel debugging.
1242                  * this segfaults on linux currently.
1243                  */
1244                 if(OpenCLInfo::use_debug() && debug_src)
1245                         build_options += "-g -s \"" + *debug_src + "\" ";
1246         }
1247
1248         if(info.has_half_images) {
1249                 build_options += "-D__KERNEL_CL_KHR_FP16__ ";
1250         }
1251
1252         if(OpenCLInfo::use_debug()) {
1253                 build_options += "-D__KERNEL_OPENCL_DEBUG__ ";
1254         }
1255
1256 #ifdef WITH_CYCLES_DEBUG
1257         build_options += "-D__KERNEL_DEBUG__ ";
1258 #endif
1259
1260         return build_options;
1261 }
1262
1263 /* TODO(sergey): In the future we can use variadic templates, once
1264  * C++0x is allowed. Should allow to clean this up a bit.
1265  */
1266 int OpenCLDeviceBase::kernel_set_args(cl_kernel kernel,
1267                     int start_argument_index,
1268                     const ArgumentWrapper& arg1,
1269                     const ArgumentWrapper& arg2,
1270                     const ArgumentWrapper& arg3,
1271                     const ArgumentWrapper& arg4,
1272                     const ArgumentWrapper& arg5,
1273                     const ArgumentWrapper& arg6,
1274                     const ArgumentWrapper& arg7,
1275                     const ArgumentWrapper& arg8,
1276                     const ArgumentWrapper& arg9,
1277                     const ArgumentWrapper& arg10,
1278                     const ArgumentWrapper& arg11,
1279                     const ArgumentWrapper& arg12,
1280                     const ArgumentWrapper& arg13,
1281                     const ArgumentWrapper& arg14,
1282                     const ArgumentWrapper& arg15,
1283                     const ArgumentWrapper& arg16,
1284                     const ArgumentWrapper& arg17,
1285                     const ArgumentWrapper& arg18,
1286                     const ArgumentWrapper& arg19,
1287                     const ArgumentWrapper& arg20,
1288                     const ArgumentWrapper& arg21,
1289                     const ArgumentWrapper& arg22,
1290                     const ArgumentWrapper& arg23,
1291                     const ArgumentWrapper& arg24,
1292                     const ArgumentWrapper& arg25,
1293                     const ArgumentWrapper& arg26,
1294                     const ArgumentWrapper& arg27,
1295                     const ArgumentWrapper& arg28,
1296                     const ArgumentWrapper& arg29,
1297                     const ArgumentWrapper& arg30,
1298                     const ArgumentWrapper& arg31,
1299                     const ArgumentWrapper& arg32,
1300                     const ArgumentWrapper& arg33)
1301 {
1302         int current_arg_index = 0;
1303 #define FAKE_VARARG_HANDLE_ARG(arg) \
1304         do { \
1305                 if(arg.pointer != NULL) { \
1306                         opencl_assert(clSetKernelArg( \
1307                                 kernel, \
1308                                 start_argument_index + current_arg_index, \
1309                                 arg.size, arg.pointer)); \
1310                         ++current_arg_index; \
1311                 } \
1312                 else { \
1313                         return current_arg_index; \
1314                 } \
1315         } while(false)
1316         FAKE_VARARG_HANDLE_ARG(arg1);
1317         FAKE_VARARG_HANDLE_ARG(arg2);
1318         FAKE_VARARG_HANDLE_ARG(arg3);
1319         FAKE_VARARG_HANDLE_ARG(arg4);
1320         FAKE_VARARG_HANDLE_ARG(arg5);
1321         FAKE_VARARG_HANDLE_ARG(arg6);
1322         FAKE_VARARG_HANDLE_ARG(arg7);
1323         FAKE_VARARG_HANDLE_ARG(arg8);
1324         FAKE_VARARG_HANDLE_ARG(arg9);
1325         FAKE_VARARG_HANDLE_ARG(arg10);
1326         FAKE_VARARG_HANDLE_ARG(arg11);
1327         FAKE_VARARG_HANDLE_ARG(arg12);
1328         FAKE_VARARG_HANDLE_ARG(arg13);
1329         FAKE_VARARG_HANDLE_ARG(arg14);
1330         FAKE_VARARG_HANDLE_ARG(arg15);
1331         FAKE_VARARG_HANDLE_ARG(arg16);
1332         FAKE_VARARG_HANDLE_ARG(arg17);
1333         FAKE_VARARG_HANDLE_ARG(arg18);
1334         FAKE_VARARG_HANDLE_ARG(arg19);
1335         FAKE_VARARG_HANDLE_ARG(arg20);
1336         FAKE_VARARG_HANDLE_ARG(arg21);
1337         FAKE_VARARG_HANDLE_ARG(arg22);
1338         FAKE_VARARG_HANDLE_ARG(arg23);
1339         FAKE_VARARG_HANDLE_ARG(arg24);
1340         FAKE_VARARG_HANDLE_ARG(arg25);
1341         FAKE_VARARG_HANDLE_ARG(arg26);
1342         FAKE_VARARG_HANDLE_ARG(arg27);
1343         FAKE_VARARG_HANDLE_ARG(arg28);
1344         FAKE_VARARG_HANDLE_ARG(arg29);
1345         FAKE_VARARG_HANDLE_ARG(arg30);
1346         FAKE_VARARG_HANDLE_ARG(arg31);
1347         FAKE_VARARG_HANDLE_ARG(arg32);
1348         FAKE_VARARG_HANDLE_ARG(arg33);
1349 #undef FAKE_VARARG_HANDLE_ARG
1350         return current_arg_index;
1351 }
1352
1353 void OpenCLDeviceBase::release_kernel_safe(cl_kernel kernel)
1354 {
1355         if(kernel) {
1356                 clReleaseKernel(kernel);
1357         }
1358 }
1359
1360 void OpenCLDeviceBase::release_mem_object_safe(cl_mem mem)
1361 {
1362         if(mem != NULL) {
1363                 clReleaseMemObject(mem);
1364         }
1365 }
1366
1367 void OpenCLDeviceBase::release_program_safe(cl_program program)
1368 {
1369         if(program) {
1370                 clReleaseProgram(program);
1371         }
1372 }
1373
1374 /* ** Those guys are for workign around some compiler-specific bugs ** */
1375
1376 cl_program OpenCLDeviceBase::load_cached_kernel(
1377         ustring key,
1378         thread_scoped_lock& cache_locker)
1379 {
1380         return OpenCLCache::get_program(cpPlatform,
1381                                         cdDevice,
1382                                         key,
1383                                         cache_locker);
1384 }
1385
1386 void OpenCLDeviceBase::store_cached_kernel(
1387         cl_program program,
1388         ustring key,
1389         thread_scoped_lock& cache_locker)
1390 {
1391         OpenCLCache::store_program(cpPlatform,
1392                                    cdDevice,
1393                                    program,
1394                                    key,
1395                                    cache_locker);
1396 }
1397
1398 string OpenCLDeviceBase::build_options_for_base_program(
1399         const DeviceRequestedFeatures& requested_features)
1400 {
1401         /* TODO(sergey): By default we compile all features, meaning
1402          * mega kernel is not getting feature-based optimizations.
1403          *
1404          * Ideally we need always compile kernel with as less features
1405          * enabled as possible to keep performance at it's max.
1406          */
1407
1408         /* For now disable baking when not in use as this has major
1409          * impact on kernel build times.
1410          */
1411         if(!requested_features.use_baking) {
1412                 return "-D__NO_BAKING__";
1413         }
1414
1415         return "";
1416 }
1417
1418 CCL_NAMESPACE_END
1419
1420 #endif