Code refactor: move more memory allocation logic into device API.
[blender.git] / intern / cycles / device / device_cpu.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 <stdlib.h>
18 #include <string.h>
19
20 /* So ImathMath is included before our kernel_cpu_compat. */
21 #ifdef WITH_OSL
22 /* So no context pollution happens from indirectly included windows.h */
23 #  include "util/util_windows.h"
24 #  include <OSL/oslexec.h>
25 #endif
26
27 #include "device/device.h"
28 #include "device/device_denoising.h"
29 #include "device/device_intern.h"
30 #include "device/device_split_kernel.h"
31
32 #include "kernel/kernel.h"
33 #include "kernel/kernel_compat_cpu.h"
34 #include "kernel/kernel_types.h"
35 #include "kernel/split/kernel_split_data.h"
36 #include "kernel/kernel_globals.h"
37
38 #include "kernel/filter/filter.h"
39
40 #include "kernel/osl/osl_shader.h"
41 #include "kernel/osl/osl_globals.h"
42
43 #include "render/buffers.h"
44
45 #include "util/util_debug.h"
46 #include "util/util_foreach.h"
47 #include "util/util_function.h"
48 #include "util/util_logging.h"
49 #include "util/util_map.h"
50 #include "util/util_opengl.h"
51 #include "util/util_optimization.h"
52 #include "util/util_progress.h"
53 #include "util/util_system.h"
54 #include "util/util_thread.h"
55
56 CCL_NAMESPACE_BEGIN
57
58 class CPUDevice;
59
60 /* Has to be outside of the class to be shared across template instantiations. */
61 static const char *logged_architecture = "";
62
63 template<typename F>
64 class KernelFunctions {
65 public:
66         KernelFunctions()
67         {
68                 kernel = (F)NULL;
69         }
70
71         KernelFunctions(F kernel_default,
72                         F kernel_sse2,
73                         F kernel_sse3,
74                         F kernel_sse41,
75                         F kernel_avx,
76                         F kernel_avx2)
77         {
78                 const char *architecture_name = "default";
79                 kernel = kernel_default;
80
81                 /* Silence potential warnings about unused variables
82                  * when compiling without some architectures. */
83                 (void)kernel_sse2;
84                 (void)kernel_sse3;
85                 (void)kernel_sse41;
86                 (void)kernel_avx;
87                 (void)kernel_avx2;
88 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX2
89                 if(system_cpu_support_avx2()) {
90                         architecture_name = "AVX2";
91                         kernel = kernel_avx2;
92                 }
93                 else
94 #endif
95 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX
96                 if(system_cpu_support_avx()) {
97                         architecture_name = "AVX";
98                         kernel = kernel_avx;
99                 }
100                 else
101 #endif
102 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE41
103                 if(system_cpu_support_sse41()) {
104                         architecture_name = "SSE4.1";
105                         kernel = kernel_sse41;
106                 }
107                 else
108 #endif
109 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE3
110                 if(system_cpu_support_sse3()) {
111                         architecture_name = "SSE3";
112                         kernel = kernel_sse3;
113                 }
114                 else
115 #endif
116 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE2
117                 if(system_cpu_support_sse2()) {
118                         architecture_name = "SSE2";
119                         kernel = kernel_sse2;
120                 }
121 #endif
122
123                 if(strcmp(architecture_name, logged_architecture) != 0) {
124                         VLOG(1) << "Will be using " << architecture_name << " kernels.";
125                         logged_architecture = architecture_name;
126                 }
127         }
128
129         inline F operator()() const {
130                 assert(kernel);
131                 return kernel;
132         }
133 protected:
134         F kernel;
135 };
136
137 class CPUSplitKernel : public DeviceSplitKernel {
138         CPUDevice *device;
139 public:
140         explicit CPUSplitKernel(CPUDevice *device);
141
142         virtual bool enqueue_split_kernel_data_init(const KernelDimensions& dim,
143                                                     RenderTile& rtile,
144                                                     int num_global_elements,
145                                                     device_memory& kernel_globals,
146                                                     device_memory& kernel_data_,
147                                                     device_memory& split_data,
148                                                     device_memory& ray_state,
149                                                     device_memory& queue_index,
150                                                     device_memory& use_queues_flag,
151                                                     device_memory& work_pool_wgs);
152
153         virtual SplitKernelFunction* get_split_kernel_function(const string& kernel_name,
154                                                                const DeviceRequestedFeatures&);
155         virtual int2 split_kernel_local_size();
156         virtual int2 split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask *task);
157         virtual uint64_t state_buffer_size(device_memory& kg, device_memory& data, size_t num_threads);
158 };
159
160 class CPUDevice : public Device
161 {
162 public:
163         TaskPool task_pool;
164         KernelGlobals kernel_globals;
165
166         device_vector<TextureInfo> texture_info;
167         bool need_texture_info;
168
169 #ifdef WITH_OSL
170         OSLGlobals osl_globals;
171 #endif
172
173         bool use_split_kernel;
174
175         DeviceRequestedFeatures requested_features;
176
177         KernelFunctions<void(*)(KernelGlobals *, float *, int, int, int, int, int)>             path_trace_kernel;
178         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)> convert_to_half_float_kernel;
179         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)> convert_to_byte_kernel;
180         KernelFunctions<void(*)(KernelGlobals *, uint4 *, float4 *, int, int, int, int, int)>   shader_kernel;
181
182         KernelFunctions<void(*)(int, TilesInfo*, int, int, float*, float*, float*, float*, float*, int*, int, int)> filter_divide_shadow_kernel;
183         KernelFunctions<void(*)(int, TilesInfo*, int, int, int, int, float*, float*, int*, int, int)>               filter_get_feature_kernel;
184         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                               filter_detect_outliers_kernel;
185         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                               filter_combine_halves_kernel;
186
187         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, int, int, float, float)> filter_nlm_calc_difference_kernel;
188         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_blur_kernel;
189         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_calc_weight_kernel;
190         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int, int)>       filter_nlm_update_output_kernel;
191         KernelFunctions<void(*)(float*, float*, int*, int)>                                      filter_nlm_normalize_kernel;
192
193         KernelFunctions<void(*)(float*, int, int, int, float*, int*, int*, int, int, float)>                              filter_construct_transform_kernel;
194         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, float*, float3*, int*, int*, int, int, int, int)> filter_nlm_construct_gramian_kernel;
195         KernelFunctions<void(*)(int, int, int, int, int, float*, int*, float*, float3*, int*, int)>                       filter_finalize_kernel;
196
197         KernelFunctions<void(*)(KernelGlobals *, ccl_constant KernelData*, ccl_global void*, int, ccl_global char*,
198                                int, int, int, int, int, int, int, int, ccl_global int*, int,
199                                ccl_global char*, ccl_global unsigned int*, unsigned int, ccl_global float*)>        data_init_kernel;
200         unordered_map<string, KernelFunctions<void(*)(KernelGlobals*, KernelData*)> > split_kernels;
201
202 #define KERNEL_FUNCTIONS(name) \
203               KERNEL_NAME_EVAL(cpu, name), \
204               KERNEL_NAME_EVAL(cpu_sse2, name), \
205               KERNEL_NAME_EVAL(cpu_sse3, name), \
206               KERNEL_NAME_EVAL(cpu_sse41, name), \
207               KERNEL_NAME_EVAL(cpu_avx, name), \
208               KERNEL_NAME_EVAL(cpu_avx2, name)
209
210         CPUDevice(DeviceInfo& info_, Stats &stats_, bool background_)
211         : Device(info_, stats_, background_),
212           texture_info(this, "__texture_info", MEM_TEXTURE),
213 #define REGISTER_KERNEL(name) name ## _kernel(KERNEL_FUNCTIONS(name))
214           REGISTER_KERNEL(path_trace),
215           REGISTER_KERNEL(convert_to_half_float),
216           REGISTER_KERNEL(convert_to_byte),
217           REGISTER_KERNEL(shader),
218           REGISTER_KERNEL(filter_divide_shadow),
219           REGISTER_KERNEL(filter_get_feature),
220           REGISTER_KERNEL(filter_detect_outliers),
221           REGISTER_KERNEL(filter_combine_halves),
222           REGISTER_KERNEL(filter_nlm_calc_difference),
223           REGISTER_KERNEL(filter_nlm_blur),
224           REGISTER_KERNEL(filter_nlm_calc_weight),
225           REGISTER_KERNEL(filter_nlm_update_output),
226           REGISTER_KERNEL(filter_nlm_normalize),
227           REGISTER_KERNEL(filter_construct_transform),
228           REGISTER_KERNEL(filter_nlm_construct_gramian),
229           REGISTER_KERNEL(filter_finalize),
230           REGISTER_KERNEL(data_init)
231 #undef REGISTER_KERNEL
232         {
233                 if(info.cpu_threads == 0) {
234                         info.cpu_threads = TaskScheduler::num_threads();
235                 }
236
237 #ifdef WITH_OSL
238                 kernel_globals.osl = &osl_globals;
239 #endif
240                 use_split_kernel = DebugFlags().cpu.split_kernel;
241                 if(use_split_kernel) {
242                         VLOG(1) << "Will be using split kernel.";
243                 }
244                 need_texture_info = false;
245
246 #define REGISTER_SPLIT_KERNEL(name) split_kernels[#name] = KernelFunctions<void(*)(KernelGlobals*, KernelData*)>(KERNEL_FUNCTIONS(name))
247                 REGISTER_SPLIT_KERNEL(path_init);
248                 REGISTER_SPLIT_KERNEL(scene_intersect);
249                 REGISTER_SPLIT_KERNEL(lamp_emission);
250                 REGISTER_SPLIT_KERNEL(do_volume);
251                 REGISTER_SPLIT_KERNEL(queue_enqueue);
252                 REGISTER_SPLIT_KERNEL(indirect_background);
253                 REGISTER_SPLIT_KERNEL(shader_setup);
254                 REGISTER_SPLIT_KERNEL(shader_sort);
255                 REGISTER_SPLIT_KERNEL(shader_eval);
256                 REGISTER_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao);
257                 REGISTER_SPLIT_KERNEL(subsurface_scatter);
258                 REGISTER_SPLIT_KERNEL(direct_lighting);
259                 REGISTER_SPLIT_KERNEL(shadow_blocked_ao);
260                 REGISTER_SPLIT_KERNEL(shadow_blocked_dl);
261                 REGISTER_SPLIT_KERNEL(enqueue_inactive);
262                 REGISTER_SPLIT_KERNEL(next_iteration_setup);
263                 REGISTER_SPLIT_KERNEL(indirect_subsurface);
264                 REGISTER_SPLIT_KERNEL(buffer_update);
265 #undef REGISTER_SPLIT_KERNEL
266 #undef KERNEL_FUNCTIONS
267         }
268
269         ~CPUDevice()
270         {
271                 task_pool.stop();
272                 texture_info.free();
273         }
274
275         virtual bool show_samples() const
276         {
277                 return (info.cpu_threads == 1);
278         }
279
280         void load_texture_info()
281         {
282                 if(need_texture_info) {
283                         texture_info.copy_to_device();
284                         need_texture_info = false;
285                 }
286         }
287
288         void mem_alloc(device_memory& mem)
289         {
290                 if(mem.type == MEM_TEXTURE) {
291                         assert(!"mem_alloc not supported for textures.");
292                 }
293                 else {
294                         if(mem.name) {
295                                 VLOG(1) << "Buffer allocate: " << mem.name << ", "
296                                                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
297                                                 << string_human_readable_size(mem.memory_size()) << ")";
298                         }
299
300                         mem.device_pointer = mem.data_pointer;
301
302                         if(!mem.device_pointer) {
303                                 mem.device_pointer = (device_ptr)malloc(mem.memory_size());
304                         }
305
306                         mem.device_size = mem.memory_size();
307                         stats.mem_alloc(mem.device_size);
308                 }
309         }
310
311         void mem_copy_to(device_memory& mem)
312         {
313                 if(mem.type == MEM_TEXTURE) {
314                         tex_free(mem);
315                         tex_alloc(mem);
316                 }
317                 else if(mem.type == MEM_PIXELS) {
318                         assert(!"mem_copy_to not supported for pixels.");
319                 }
320                 else {
321                         if(!mem.device_pointer) {
322                                 mem_alloc(mem);
323                         }
324
325                         /* copy is no-op */
326                 }
327         }
328
329         void mem_copy_from(device_memory& /*mem*/,
330                            int /*y*/, int /*w*/, int /*h*/,
331                            int /*elem*/)
332         {
333                 /* no-op */
334         }
335
336         void mem_zero(device_memory& mem)
337         {
338                 if(!mem.device_pointer) {
339                         mem_alloc(mem);
340                 }
341
342                 if(mem.device_pointer) {
343                         memset((void*)mem.device_pointer, 0, mem.memory_size());
344                 }
345         }
346
347         void mem_free(device_memory& mem)
348         {
349                 if(mem.type == MEM_TEXTURE) {
350                         tex_free(mem);
351                 }
352                 else if(mem.device_pointer) {
353                         if(!mem.data_pointer) {
354                                 free((void*)mem.device_pointer);
355                         }
356                         mem.device_pointer = 0;
357                         stats.mem_free(mem.device_size);
358                         mem.device_size = 0;
359                 }
360         }
361
362         virtual device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int /*size*/)
363         {
364                 return (device_ptr) (((char*) mem.device_pointer) + mem.memory_elements_size(offset));
365         }
366
367         void const_copy_to(const char *name, void *host, size_t size)
368         {
369                 kernel_const_copy(&kernel_globals, name, host, size);
370         }
371
372         void tex_alloc(device_memory& mem)
373         {
374                 VLOG(1) << "Texture allocate: " << mem.name << ", "
375                         << string_human_readable_number(mem.memory_size()) << " bytes. ("
376                         << string_human_readable_size(mem.memory_size()) << ")";
377
378                 if(mem.interpolation == INTERPOLATION_NONE) {
379                         /* Data texture. */
380                         kernel_tex_copy(&kernel_globals,
381                                                         mem.name,
382                                                         mem.data_pointer,
383                                                         mem.data_size);
384                 }
385                 else {
386                         /* Image Texture. */
387                         int flat_slot = 0;
388                         if(string_startswith(mem.name, "__tex_image")) {
389                                 int pos =  string(mem.name).rfind("_");
390                                 flat_slot = atoi(mem.name + pos + 1);
391                         }
392                         else {
393                                 assert(0);
394                         }
395
396                         if(flat_slot >= texture_info.size()) {
397                                 /* Allocate some slots in advance, to reduce amount
398                                  * of re-allocations. */
399                                 texture_info.resize(flat_slot + 128);
400                         }
401
402                         TextureInfo& info = texture_info[flat_slot];
403                         info.data = (uint64_t)mem.data_pointer;
404                         info.cl_buffer = 0;
405                         info.interpolation = mem.interpolation;
406                         info.extension = mem.extension;
407                         info.width = mem.data_width;
408                         info.height = mem.data_height;
409                         info.depth = mem.data_depth;
410
411                         need_texture_info = true;
412                 }
413
414                 mem.device_pointer = mem.data_pointer;
415                 mem.device_size = mem.memory_size();
416                 stats.mem_alloc(mem.device_size);
417         }
418
419         void tex_free(device_memory& mem)
420         {
421                 if(mem.device_pointer) {
422                         mem.device_pointer = 0;
423                         stats.mem_free(mem.device_size);
424                         mem.device_size = 0;
425                         need_texture_info = true;
426                 }
427         }
428
429         void *osl_memory()
430         {
431 #ifdef WITH_OSL
432                 return &osl_globals;
433 #else
434                 return NULL;
435 #endif
436         }
437
438         void thread_run(DeviceTask *task)
439         {
440                 if(task->type == DeviceTask::RENDER) {
441                         thread_render(*task);
442                 }
443                 else if(task->type == DeviceTask::FILM_CONVERT)
444                         thread_film_convert(*task);
445                 else if(task->type == DeviceTask::SHADER)
446                         thread_shader(*task);
447         }
448
449         class CPUDeviceTask : public DeviceTask {
450         public:
451                 CPUDeviceTask(CPUDevice *device, DeviceTask& task)
452                 : DeviceTask(task)
453                 {
454                         run = function_bind(&CPUDevice::thread_run, device, this);
455                 }
456         };
457
458         bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task)
459         {
460                 TilesInfo *tiles = (TilesInfo*) task->tiles_mem.data_pointer;
461                 for(int i = 0; i < 9; i++) {
462                         tiles->buffers[i] = buffers[i];
463                 }
464
465                 task->tiles_mem.copy_to_device();
466
467                 return true;
468         }
469
470         bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr,
471                                        DenoisingTask *task)
472         {
473                 int4 rect = task->rect;
474                 int   r   = task->nlm_state.r;
475                 int   f   = task->nlm_state.f;
476                 float a   = task->nlm_state.a;
477                 float k_2 = task->nlm_state.k_2;
478
479                 int w = align_up(rect.z-rect.x, 4);
480                 int h = rect.w-rect.y;
481
482                 float *blurDifference = (float*) task->nlm_state.temporary_1_ptr;
483                 float *difference     = (float*) task->nlm_state.temporary_2_ptr;
484                 float *weightAccum    = (float*) task->nlm_state.temporary_3_ptr;
485
486                 memset(weightAccum, 0, sizeof(float)*w*h);
487                 memset((float*) out_ptr, 0, sizeof(float)*w*h);
488
489                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
490                         int dy = i / (2*r+1) - r;
491                         int dx = i % (2*r+1) - r;
492
493                         int local_rect[4] = {max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy)};
494                         filter_nlm_calc_difference_kernel()(dx, dy,
495                                                             (float*) guide_ptr,
496                                                             (float*) variance_ptr,
497                                                             difference,
498                                                             local_rect,
499                                                             w, 0,
500                                                             a, k_2);
501
502                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
503                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, w, f);
504                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
505
506                         filter_nlm_update_output_kernel()(dx, dy,
507                                                           blurDifference,
508                                                           (float*) image_ptr,
509                                                           (float*) out_ptr,
510                                                           weightAccum,
511                                                           local_rect,
512                                                           w, f);
513                 }
514
515                 int local_rect[4] = {0, 0, rect.z-rect.x, rect.w-rect.y};
516                 filter_nlm_normalize_kernel()((float*) out_ptr, weightAccum, local_rect, w);
517
518                 return true;
519         }
520
521         bool denoising_construct_transform(DenoisingTask *task)
522         {
523                 for(int y = 0; y < task->filter_area.w; y++) {
524                         for(int x = 0; x < task->filter_area.z; x++) {
525                                 filter_construct_transform_kernel()((float*) task->buffer.mem.device_pointer,
526                                                                     x + task->filter_area.x,
527                                                                     y + task->filter_area.y,
528                                                                     y*task->filter_area.z + x,
529                                                                     (float*) task->storage.transform.device_pointer,
530                                                                     (int*)   task->storage.rank.device_pointer,
531                                                                     &task->rect.x,
532                                                                     task->buffer.pass_stride,
533                                                                     task->radius,
534                                                                     task->pca_threshold);
535                         }
536                 }
537                 return true;
538         }
539
540         bool denoising_reconstruct(device_ptr color_ptr,
541                                    device_ptr color_variance_ptr,
542                                    device_ptr output_ptr,
543                                    DenoisingTask *task)
544         {
545                 mem_zero(task->storage.XtWX);
546                 mem_zero(task->storage.XtWY);
547
548                 float *difference     = (float*) task->reconstruction_state.temporary_1_ptr;
549                 float *blurDifference = (float*) task->reconstruction_state.temporary_2_ptr;
550
551                 int r = task->radius;
552                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
553                         int dy = i / (2*r+1) - r;
554                         int dx = i % (2*r+1) - r;
555
556                         int local_rect[4] = {max(0, -dx), max(0, -dy),
557                                              task->reconstruction_state.source_w - max(0, dx),
558                                              task->reconstruction_state.source_h - max(0, dy)};
559                         filter_nlm_calc_difference_kernel()(dx, dy,
560                                                             (float*) color_ptr,
561                                                             (float*) color_variance_ptr,
562                                                             difference,
563                                                             local_rect,
564                                                             task->buffer.w,
565                                                             task->buffer.pass_stride,
566                                                             1.0f,
567                                                             task->nlm_k_2);
568                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
569                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, task->buffer.w, 4);
570                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
571                         filter_nlm_construct_gramian_kernel()(dx, dy,
572                                                               blurDifference,
573                                                               (float*)  task->buffer.mem.device_pointer,
574                                                               (float*)  task->storage.transform.device_pointer,
575                                                               (int*)    task->storage.rank.device_pointer,
576                                                               (float*)  task->storage.XtWX.device_pointer,
577                                                               (float3*) task->storage.XtWY.device_pointer,
578                                                               local_rect,
579                                                               &task->reconstruction_state.filter_rect.x,
580                                                               task->buffer.w,
581                                                               task->buffer.h,
582                                                               4,
583                                                               task->buffer.pass_stride);
584                 }
585                 for(int y = 0; y < task->filter_area.w; y++) {
586                         for(int x = 0; x < task->filter_area.z; x++) {
587                                 filter_finalize_kernel()(x,
588                                                          y,
589                                                          y*task->filter_area.z + x,
590                                                          task->buffer.w,
591                                                          task->buffer.h,
592                                                          (float*)  output_ptr,
593                                                          (int*)    task->storage.rank.device_pointer,
594                                                          (float*)  task->storage.XtWX.device_pointer,
595                                                          (float3*) task->storage.XtWY.device_pointer,
596                                                          &task->reconstruction_state.buffer_params.x,
597                                                          task->render_buffer.samples);
598                         }
599                 }
600                 return true;
601         }
602
603         bool denoising_combine_halves(device_ptr a_ptr, device_ptr b_ptr,
604                                       device_ptr mean_ptr, device_ptr variance_ptr,
605                                       int r, int4 rect, DenoisingTask * /*task*/)
606         {
607                 for(int y = rect.y; y < rect.w; y++) {
608                         for(int x = rect.x; x < rect.z; x++) {
609                                 filter_combine_halves_kernel()(x, y,
610                                                                (float*) mean_ptr,
611                                                                (float*) variance_ptr,
612                                                                (float*) a_ptr,
613                                                                (float*) b_ptr,
614                                                                &rect.x,
615                                                                r);
616                         }
617                 }
618                 return true;
619         }
620
621         bool denoising_divide_shadow(device_ptr a_ptr, device_ptr b_ptr,
622                                      device_ptr sample_variance_ptr, device_ptr sv_variance_ptr,
623                                      device_ptr buffer_variance_ptr, DenoisingTask *task)
624         {
625                 for(int y = task->rect.y; y < task->rect.w; y++) {
626                         for(int x = task->rect.x; x < task->rect.z; x++) {
627                                 filter_divide_shadow_kernel()(task->render_buffer.samples,
628                                                               task->tiles,
629                                                               x, y,
630                                                               (float*) a_ptr,
631                                                               (float*) b_ptr,
632                                                               (float*) sample_variance_ptr,
633                                                               (float*) sv_variance_ptr,
634                                                               (float*) buffer_variance_ptr,
635                                                               &task->rect.x,
636                                                               task->render_buffer.pass_stride,
637                                                               task->render_buffer.denoising_data_offset);
638                         }
639                 }
640                 return true;
641         }
642
643         bool denoising_get_feature(int mean_offset,
644                                    int variance_offset,
645                                    device_ptr mean_ptr,
646                                    device_ptr variance_ptr,
647                                    DenoisingTask *task)
648         {
649                 for(int y = task->rect.y; y < task->rect.w; y++) {
650                         for(int x = task->rect.x; x < task->rect.z; x++) {
651                                 filter_get_feature_kernel()(task->render_buffer.samples,
652                                                             task->tiles,
653                                                             mean_offset,
654                                                             variance_offset,
655                                                             x, y,
656                                                             (float*) mean_ptr,
657                                                             (float*) variance_ptr,
658                                                             &task->rect.x,
659                                                             task->render_buffer.pass_stride,
660                                                             task->render_buffer.denoising_data_offset);
661                         }
662                 }
663                 return true;
664         }
665
666         bool denoising_detect_outliers(device_ptr image_ptr,
667                                        device_ptr variance_ptr,
668                                        device_ptr depth_ptr,
669                                        device_ptr output_ptr,
670                                        DenoisingTask *task)
671         {
672                 for(int y = task->rect.y; y < task->rect.w; y++) {
673                         for(int x = task->rect.x; x < task->rect.z; x++) {
674                                 filter_detect_outliers_kernel()(x, y,
675                                                                 (float*) image_ptr,
676                                                                 (float*) variance_ptr,
677                                                                 (float*) depth_ptr,
678                                                                 (float*) output_ptr,
679                                                                 &task->rect.x,
680                                                                 task->buffer.pass_stride);
681                         }
682                 }
683                 return true;
684         }
685
686         void path_trace(DeviceTask &task, RenderTile &tile, KernelGlobals *kg)
687         {
688                 float *render_buffer = (float*)tile.buffer;
689                 int start_sample = tile.start_sample;
690                 int end_sample = tile.start_sample + tile.num_samples;
691
692                 for(int sample = start_sample; sample < end_sample; sample++) {
693                         if(task.get_cancel() || task_pool.canceled()) {
694                                 if(task.need_finish_queue == false)
695                                         break;
696                         }
697
698                         for(int y = tile.y; y < tile.y + tile.h; y++) {
699                                 for(int x = tile.x; x < tile.x + tile.w; x++) {
700                                         path_trace_kernel()(kg, render_buffer,
701                                                             sample, x, y, tile.offset, tile.stride);
702                                 }
703                         }
704
705                         tile.sample = sample + 1;
706
707                         task.update_progress(&tile, tile.w*tile.h);
708                 }
709         }
710
711         void denoise(DeviceTask &task, RenderTile &tile)
712         {
713                 tile.sample = tile.start_sample + tile.num_samples;
714
715                 DenoisingTask denoising(this);
716
717                 denoising.functions.construct_transform = function_bind(&CPUDevice::denoising_construct_transform, this, &denoising);
718                 denoising.functions.reconstruct = function_bind(&CPUDevice::denoising_reconstruct, this, _1, _2, _3, &denoising);
719                 denoising.functions.divide_shadow = function_bind(&CPUDevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
720                 denoising.functions.non_local_means = function_bind(&CPUDevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
721                 denoising.functions.combine_halves = function_bind(&CPUDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
722                 denoising.functions.get_feature = function_bind(&CPUDevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
723                 denoising.functions.detect_outliers = function_bind(&CPUDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
724                 denoising.functions.set_tiles = function_bind(&CPUDevice::denoising_set_tiles, this, _1, &denoising);
725
726                 denoising.filter_area = make_int4(tile.x, tile.y, tile.w, tile.h);
727                 denoising.render_buffer.samples = tile.sample;
728
729                 RenderTile rtiles[9];
730                 rtiles[4] = tile;
731                 task.map_neighbor_tiles(rtiles, this);
732                 denoising.tiles_from_rendertiles(rtiles);
733
734                 denoising.init_from_devicetask(task);
735
736                 denoising.run_denoising();
737
738                 task.unmap_neighbor_tiles(rtiles, this);
739
740                 task.update_progress(&tile, tile.w*tile.h);
741         }
742
743         void thread_render(DeviceTask& task)
744         {
745                 if(task_pool.canceled()) {
746                         if(task.need_finish_queue == false)
747                                 return;
748                 }
749
750                 /* allocate buffer for kernel globals */
751                 device_only_memory<KernelGlobals> kgbuffer(this, "kernel_globals");
752                 kgbuffer.alloc_to_device(1);
753
754                 KernelGlobals *kg = new ((void*) kgbuffer.device_pointer) KernelGlobals(thread_kernel_globals_init());
755
756                 CPUSplitKernel *split_kernel = NULL;
757                 if(use_split_kernel) {
758                         split_kernel = new CPUSplitKernel(this);
759                         requested_features.max_closure = MAX_CLOSURE;
760                         if(!split_kernel->load_kernels(requested_features)) {
761                                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
762                                 kgbuffer.free();
763                                 delete split_kernel;
764                                 return;
765                         }
766                 }
767
768                 RenderTile tile;
769                 while(task.acquire_tile(this, tile)) {
770                         if(tile.task == RenderTile::PATH_TRACE) {
771                                 if(use_split_kernel) {
772                                         device_only_memory<uchar> void_buffer(this, "void_buffer");
773                                         split_kernel->path_trace(&task, tile, kgbuffer, void_buffer);
774                                 }
775                                 else {
776                                         path_trace(task, tile, kg);
777                                 }
778                         }
779                         else if(tile.task == RenderTile::DENOISE) {
780                                 denoise(task, tile);
781                         }
782
783                         task.release_tile(tile);
784
785                         if(task_pool.canceled()) {
786                                 if(task.need_finish_queue == false)
787                                         break;
788                         }
789                 }
790
791                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
792                 kg->~KernelGlobals();
793                 kgbuffer.free();
794                 delete split_kernel;
795         }
796
797         void thread_film_convert(DeviceTask& task)
798         {
799                 float sample_scale = 1.0f/(task.sample + 1);
800
801                 if(task.rgba_half) {
802                         for(int y = task.y; y < task.y + task.h; y++)
803                                 for(int x = task.x; x < task.x + task.w; x++)
804                                         convert_to_half_float_kernel()(&kernel_globals, (uchar4*)task.rgba_half, (float*)task.buffer,
805                                                                        sample_scale, x, y, task.offset, task.stride);
806                 }
807                 else {
808                         for(int y = task.y; y < task.y + task.h; y++)
809                                 for(int x = task.x; x < task.x + task.w; x++)
810                                         convert_to_byte_kernel()(&kernel_globals, (uchar4*)task.rgba_byte, (float*)task.buffer,
811                                                                  sample_scale, x, y, task.offset, task.stride);
812
813                 }
814         }
815
816         void thread_shader(DeviceTask& task)
817         {
818                 KernelGlobals kg = kernel_globals;
819
820 #ifdef WITH_OSL
821                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
822 #endif
823                 for(int sample = 0; sample < task.num_samples; sample++) {
824                         for(int x = task.shader_x; x < task.shader_x + task.shader_w; x++)
825                                 shader_kernel()(&kg,
826                                                 (uint4*)task.shader_input,
827                                                 (float4*)task.shader_output,
828                                                 task.shader_eval_type,
829                                                 task.shader_filter,
830                                                 x,
831                                                 task.offset,
832                                                 sample);
833
834                         if(task.get_cancel() || task_pool.canceled())
835                                 break;
836
837                         task.update_progress(NULL);
838
839                 }
840
841 #ifdef WITH_OSL
842                 OSLShader::thread_free(&kg);
843 #endif
844         }
845
846         int get_split_task_count(DeviceTask& task)
847         {
848                 if(task.type == DeviceTask::SHADER)
849                         return task.get_subtask_count(info.cpu_threads, 256);
850                 else
851                         return task.get_subtask_count(info.cpu_threads);
852         }
853
854         void task_add(DeviceTask& task)
855         {
856                 /* Load texture info. */
857                 load_texture_info();
858
859                 /* split task into smaller ones */
860                 list<DeviceTask> tasks;
861
862                 if(task.type == DeviceTask::SHADER)
863                         task.split(tasks, info.cpu_threads, 256);
864                 else
865                         task.split(tasks, info.cpu_threads);
866
867                 foreach(DeviceTask& task, tasks)
868                         task_pool.push(new CPUDeviceTask(this, task));
869         }
870
871         void task_wait()
872         {
873                 task_pool.wait_work();
874         }
875
876         void task_cancel()
877         {
878                 task_pool.cancel();
879         }
880
881 protected:
882         inline KernelGlobals thread_kernel_globals_init()
883         {
884                 KernelGlobals kg = kernel_globals;
885                 kg.transparent_shadow_intersections = NULL;
886                 const int decoupled_count = sizeof(kg.decoupled_volume_steps) /
887                                             sizeof(*kg.decoupled_volume_steps);
888                 for(int i = 0; i < decoupled_count; ++i) {
889                         kg.decoupled_volume_steps[i] = NULL;
890                 }
891                 kg.decoupled_volume_steps_index = 0;
892 #ifdef WITH_OSL
893                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
894 #endif
895                 return kg;
896         }
897
898         inline void thread_kernel_globals_free(KernelGlobals *kg)
899         {
900                 if(kg == NULL) {
901                         return;
902                 }
903
904                 if(kg->transparent_shadow_intersections != NULL) {
905                         free(kg->transparent_shadow_intersections);
906                 }
907                 const int decoupled_count = sizeof(kg->decoupled_volume_steps) /
908                                             sizeof(*kg->decoupled_volume_steps);
909                 for(int i = 0; i < decoupled_count; ++i) {
910                         if(kg->decoupled_volume_steps[i] != NULL) {
911                                 free(kg->decoupled_volume_steps[i]);
912                         }
913                 }
914 #ifdef WITH_OSL
915                 OSLShader::thread_free(kg);
916 #endif
917         }
918
919         virtual bool load_kernels(DeviceRequestedFeatures& requested_features_) {
920                 requested_features = requested_features_;
921
922                 return true;
923         }
924 };
925
926 /* split kernel */
927
928 class CPUSplitKernelFunction : public SplitKernelFunction {
929 public:
930         CPUDevice* device;
931         void (*func)(KernelGlobals *kg, KernelData *data);
932
933         CPUSplitKernelFunction(CPUDevice* device) : device(device), func(NULL) {}
934         ~CPUSplitKernelFunction() {}
935
936         virtual bool enqueue(const KernelDimensions& dim, device_memory& kernel_globals, device_memory& data)
937         {
938                 if(!func) {
939                         return false;
940                 }
941
942                 KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
943                 kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
944
945                 for(int y = 0; y < dim.global_size[1]; y++) {
946                         for(int x = 0; x < dim.global_size[0]; x++) {
947                                 kg->global_id = make_int2(x, y);
948
949                                 func(kg, (KernelData*)data.device_pointer);
950                         }
951                 }
952
953                 return true;
954         }
955 };
956
957 CPUSplitKernel::CPUSplitKernel(CPUDevice *device) : DeviceSplitKernel(device), device(device)
958 {
959 }
960
961 bool CPUSplitKernel::enqueue_split_kernel_data_init(const KernelDimensions& dim,
962                                                     RenderTile& rtile,
963                                                     int num_global_elements,
964                                                     device_memory& kernel_globals,
965                                                     device_memory& data,
966                                                     device_memory& split_data,
967                                                     device_memory& ray_state,
968                                                     device_memory& queue_index,
969                                                     device_memory& use_queues_flags,
970                                                     device_memory& work_pool_wgs)
971 {
972         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
973         kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
974
975         for(int y = 0; y < dim.global_size[1]; y++) {
976                 for(int x = 0; x < dim.global_size[0]; x++) {
977                         kg->global_id = make_int2(x, y);
978
979                         device->data_init_kernel()((KernelGlobals*)kernel_globals.device_pointer,
980                                                    (KernelData*)data.device_pointer,
981                                                    (void*)split_data.device_pointer,
982                                                    num_global_elements,
983                                                    (char*)ray_state.device_pointer,
984                                                    rtile.start_sample,
985                                                    rtile.start_sample + rtile.num_samples,
986                                                    rtile.x,
987                                                    rtile.y,
988                                                    rtile.w,
989                                                    rtile.h,
990                                                    rtile.offset,
991                                                    rtile.stride,
992                                                    (int*)queue_index.device_pointer,
993                                                    dim.global_size[0] * dim.global_size[1],
994                                                    (char*)use_queues_flags.device_pointer,
995                                                    (uint*)work_pool_wgs.device_pointer,
996                                                    rtile.num_samples,
997                                                    (float*)rtile.buffer);
998                 }
999         }
1000
1001         return true;
1002 }
1003
1004 SplitKernelFunction* CPUSplitKernel::get_split_kernel_function(const string& kernel_name,
1005                                                                const DeviceRequestedFeatures&)
1006 {
1007         CPUSplitKernelFunction *kernel = new CPUSplitKernelFunction(device);
1008
1009         kernel->func = device->split_kernels[kernel_name]();
1010         if(!kernel->func) {
1011                 delete kernel;
1012                 return NULL;
1013         }
1014
1015         return kernel;
1016 }
1017
1018 int2 CPUSplitKernel::split_kernel_local_size()
1019 {
1020         return make_int2(1, 1);
1021 }
1022
1023 int2 CPUSplitKernel::split_kernel_global_size(device_memory& /*kg*/, device_memory& /*data*/, DeviceTask * /*task*/) {
1024         return make_int2(1, 1);
1025 }
1026
1027 uint64_t CPUSplitKernel::state_buffer_size(device_memory& kernel_globals, device_memory& /*data*/, size_t num_threads) {
1028         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
1029
1030         return split_data_buffer_size(kg, num_threads);
1031 }
1032
1033 Device *device_cpu_create(DeviceInfo& info, Stats &stats, bool background)
1034 {
1035         return new CPUDevice(info, stats, background);
1036 }
1037
1038 void device_cpu_info(vector<DeviceInfo>& devices)
1039 {
1040         DeviceInfo info;
1041
1042         info.type = DEVICE_CPU;
1043         info.description = system_cpu_brand_string();
1044         info.id = "CPU";
1045         info.num = 0;
1046         info.advanced_shading = true;
1047         info.has_qbvh = system_cpu_support_sse2();
1048         info.has_volume_decoupled = true;
1049         info.has_osl = true;
1050
1051         devices.insert(devices.begin(), info);
1052 }
1053
1054 string device_cpu_capabilities(void)
1055 {
1056         string capabilities = "";
1057         capabilities += system_cpu_support_sse2() ? "SSE2 " : "";
1058         capabilities += system_cpu_support_sse3() ? "SSE3 " : "";
1059         capabilities += system_cpu_support_sse41() ? "SSE41 " : "";
1060         capabilities += system_cpu_support_avx() ? "AVX " : "";
1061         capabilities += system_cpu_support_avx2() ? "AVX2" : "";
1062         if(capabilities[capabilities.size() - 1] == ' ')
1063                 capabilities.resize(capabilities.size() - 1);
1064         return capabilities;
1065 }
1066
1067 CCL_NAMESPACE_END