opencl_split.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047
  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. #ifdef WITH_OPENCL
  17. # include "device/opencl/opencl.h"
  18. # include "kernel/kernel_types.h"
  19. # include "kernel/split/kernel_split_data_types.h"
  20. # include "util/util_algorithm.h"
  21. # include "util/util_debug.h"
  22. # include "util/util_foreach.h"
  23. # include "util/util_logging.h"
  24. # include "util/util_md5.h"
  25. # include "util/util_path.h"
  26. # include "util/util_time.h"
  27. CCL_NAMESPACE_BEGIN
  28. struct texture_slot_t {
  29. texture_slot_t(const string &name, int slot) : name(name), slot(slot)
  30. {
  31. }
  32. string name;
  33. int slot;
  34. };
  35. static const string NON_SPLIT_KERNELS =
  36. "denoising "
  37. "base "
  38. "background "
  39. "displace ";
  40. static const string SPLIT_BUNDLE_KERNELS =
  41. "data_init "
  42. "path_init "
  43. "state_buffer_size "
  44. "scene_intersect "
  45. "queue_enqueue "
  46. "shader_setup "
  47. "shader_sort "
  48. "enqueue_inactive "
  49. "next_iteration_setup "
  50. "indirect_subsurface "
  51. "buffer_update";
  52. const string OpenCLDevice::get_opencl_program_name(const string &kernel_name)
  53. {
  54. if (NON_SPLIT_KERNELS.find(kernel_name) != std::string::npos) {
  55. return kernel_name;
  56. }
  57. else if (SPLIT_BUNDLE_KERNELS.find(kernel_name) != std::string::npos) {
  58. return "split_bundle";
  59. }
  60. else {
  61. return "split_" + kernel_name;
  62. }
  63. }
  64. const string OpenCLDevice::get_opencl_program_filename(const string &kernel_name)
  65. {
  66. if (kernel_name == "denoising") {
  67. return "filter.cl";
  68. }
  69. else if (SPLIT_BUNDLE_KERNELS.find(kernel_name) != std::string::npos) {
  70. return "kernel_split_bundle.cl";
  71. }
  72. else {
  73. return "kernel_" + kernel_name + ".cl";
  74. }
  75. }
  76. /* Enable features that we always want to compile to reduce recompilation events */
  77. void OpenCLDevice::enable_default_features(DeviceRequestedFeatures &features)
  78. {
  79. features.use_transparent = true;
  80. features.use_shadow_tricks = true;
  81. features.use_principled = true;
  82. features.use_denoising = true;
  83. if (!background) {
  84. features.max_nodes_group = NODE_GROUP_LEVEL_MAX;
  85. features.nodes_features = NODE_FEATURE_ALL;
  86. features.use_hair = true;
  87. features.use_subsurface = true;
  88. features.use_camera_motion = false;
  89. features.use_object_motion = false;
  90. }
  91. }
  92. string OpenCLDevice::get_build_options(const DeviceRequestedFeatures &requested_features,
  93. const string &opencl_program_name,
  94. bool preview_kernel)
  95. {
  96. /* first check for non-split kernel programs */
  97. if (opencl_program_name == "base" || opencl_program_name == "denoising") {
  98. return "";
  99. }
  100. else if (opencl_program_name == "bake") {
  101. /* Note: get_build_options for bake is only requested when baking is enabled.
  102. * displace and background are always requested.
  103. * `__SPLIT_KERNEL__` must not be present in the compile directives for bake */
  104. DeviceRequestedFeatures features(requested_features);
  105. enable_default_features(features);
  106. features.use_denoising = false;
  107. features.use_object_motion = false;
  108. features.use_camera_motion = false;
  109. features.use_hair = true;
  110. features.use_subsurface = true;
  111. features.max_nodes_group = NODE_GROUP_LEVEL_MAX;
  112. features.nodes_features = NODE_FEATURE_ALL;
  113. features.use_integrator_branched = false;
  114. return features.get_build_options();
  115. }
  116. else if (opencl_program_name == "displace") {
  117. /* As displacement does not use any nodes from the Shading group (eg BSDF).
  118. * We disable all features that are related to shading. */
  119. DeviceRequestedFeatures features(requested_features);
  120. enable_default_features(features);
  121. features.use_denoising = false;
  122. features.use_object_motion = false;
  123. features.use_camera_motion = false;
  124. features.use_baking = false;
  125. features.use_transparent = false;
  126. features.use_shadow_tricks = false;
  127. features.use_subsurface = false;
  128. features.use_volume = false;
  129. features.nodes_features &= ~NODE_FEATURE_VOLUME;
  130. features.use_denoising = false;
  131. features.use_principled = false;
  132. features.use_integrator_branched = false;
  133. return features.get_build_options();
  134. }
  135. else if (opencl_program_name == "background") {
  136. /* Background uses Background shading
  137. * It is save to disable shadow features, subsurface and volumetric. */
  138. DeviceRequestedFeatures features(requested_features);
  139. enable_default_features(features);
  140. features.use_baking = false;
  141. features.use_object_motion = false;
  142. features.use_camera_motion = false;
  143. features.use_transparent = false;
  144. features.use_shadow_tricks = false;
  145. features.use_denoising = false;
  146. /* NOTE: currently possible to use surface nodes like `Hair Info`, `Bump` node.
  147. * Perhaps we should remove them in UI as it does not make any sense when
  148. * rendering background. */
  149. features.nodes_features &= ~NODE_FEATURE_VOLUME;
  150. features.use_subsurface = false;
  151. features.use_volume = false;
  152. features.use_shader_raytrace = false;
  153. features.use_patch_evaluation = false;
  154. features.use_integrator_branched = false;
  155. return features.get_build_options();
  156. }
  157. string build_options = "-D__SPLIT_KERNEL__ ";
  158. /* Set compute device build option. */
  159. cl_device_type device_type;
  160. OpenCLInfo::get_device_type(this->cdDevice, &device_type, &this->ciErr);
  161. assert(this->ciErr == CL_SUCCESS);
  162. if (device_type == CL_DEVICE_TYPE_GPU) {
  163. build_options += "-D__COMPUTE_DEVICE_GPU__ ";
  164. }
  165. DeviceRequestedFeatures nofeatures;
  166. enable_default_features(nofeatures);
  167. /* Add program specific optimized compile directives */
  168. if (preview_kernel) {
  169. DeviceRequestedFeatures preview_features;
  170. preview_features.use_hair = true;
  171. build_options += "-D__KERNEL_AO_PREVIEW__ ";
  172. build_options += preview_features.get_build_options();
  173. }
  174. else if (opencl_program_name == "split_do_volume" && !requested_features.use_volume) {
  175. build_options += nofeatures.get_build_options();
  176. }
  177. else {
  178. DeviceRequestedFeatures features(requested_features);
  179. enable_default_features(features);
  180. /* Always turn off baking at this point. Baking is only usefull when building the bake kernel.
  181. * this also makes sure that the kernels that are build during baking can be reused
  182. * when not doing any baking. */
  183. features.use_baking = false;
  184. /* Do not vary on shaders when program doesn't do any shading.
  185. * We have bundled them in a single program. */
  186. if (opencl_program_name == "split_bundle") {
  187. features.max_nodes_group = 0;
  188. features.nodes_features = 0;
  189. features.use_shader_raytrace = false;
  190. }
  191. /* No specific settings, just add the regular ones */
  192. build_options += features.get_build_options();
  193. }
  194. return build_options;
  195. }
  196. OpenCLDevice::OpenCLSplitPrograms::OpenCLSplitPrograms(OpenCLDevice *device_)
  197. {
  198. device = device_;
  199. }
  200. OpenCLDevice::OpenCLSplitPrograms::~OpenCLSplitPrograms()
  201. {
  202. program_split.release();
  203. program_lamp_emission.release();
  204. program_do_volume.release();
  205. program_indirect_background.release();
  206. program_shader_eval.release();
  207. program_holdout_emission_blurring_pathtermination_ao.release();
  208. program_subsurface_scatter.release();
  209. program_direct_lighting.release();
  210. program_shadow_blocked_ao.release();
  211. program_shadow_blocked_dl.release();
  212. }
  213. void OpenCLDevice::OpenCLSplitPrograms::load_kernels(
  214. vector<OpenCLProgram *> &programs,
  215. const DeviceRequestedFeatures &requested_features,
  216. bool is_preview)
  217. {
  218. if (!requested_features.use_baking) {
  219. # define ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(kernel_name) \
  220. program_split.add_kernel(ustring("path_trace_" #kernel_name));
  221. # define ADD_SPLIT_KERNEL_PROGRAM(kernel_name) \
  222. const string program_name_##kernel_name = "split_" #kernel_name; \
  223. program_##kernel_name = OpenCLDevice::OpenCLProgram( \
  224. device, \
  225. program_name_##kernel_name, \
  226. "kernel_" #kernel_name ".cl", \
  227. device->get_build_options(requested_features, program_name_##kernel_name, is_preview)); \
  228. program_##kernel_name.add_kernel(ustring("path_trace_" #kernel_name)); \
  229. programs.push_back(&program_##kernel_name);
  230. /* Ordered with most complex kernels first, to reduce overall compile time. */
  231. ADD_SPLIT_KERNEL_PROGRAM(subsurface_scatter);
  232. if (requested_features.use_volume || is_preview) {
  233. ADD_SPLIT_KERNEL_PROGRAM(do_volume);
  234. }
  235. ADD_SPLIT_KERNEL_PROGRAM(shadow_blocked_dl);
  236. ADD_SPLIT_KERNEL_PROGRAM(shadow_blocked_ao);
  237. ADD_SPLIT_KERNEL_PROGRAM(holdout_emission_blurring_pathtermination_ao);
  238. ADD_SPLIT_KERNEL_PROGRAM(lamp_emission);
  239. ADD_SPLIT_KERNEL_PROGRAM(direct_lighting);
  240. ADD_SPLIT_KERNEL_PROGRAM(indirect_background);
  241. ADD_SPLIT_KERNEL_PROGRAM(shader_eval);
  242. /* Quick kernels bundled in a single program to reduce overhead of starting
  243. * Blender processes. */
  244. program_split = OpenCLDevice::OpenCLProgram(
  245. device,
  246. "split_bundle",
  247. "kernel_split_bundle.cl",
  248. device->get_build_options(requested_features, "split_bundle", is_preview));
  249. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(data_init);
  250. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(state_buffer_size);
  251. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(path_init);
  252. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(scene_intersect);
  253. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(queue_enqueue);
  254. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(shader_setup);
  255. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(shader_sort);
  256. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(enqueue_inactive);
  257. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(next_iteration_setup);
  258. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(indirect_subsurface);
  259. ADD_SPLIT_KERNEL_BUNDLE_PROGRAM(buffer_update);
  260. programs.push_back(&program_split);
  261. # undef ADD_SPLIT_KERNEL_PROGRAM
  262. # undef ADD_SPLIT_KERNEL_BUNDLE_PROGRAM
  263. }
  264. }
  265. namespace {
  266. /* Copy dummy KernelGlobals related to OpenCL from kernel_globals.h to
  267. * fetch its size.
  268. */
  269. typedef struct KernelGlobalsDummy {
  270. ccl_constant KernelData *data;
  271. ccl_global char *buffers[8];
  272. # define KERNEL_TEX(type, name) TextureInfo name;
  273. # include "kernel/kernel_textures.h"
  274. # undef KERNEL_TEX
  275. SplitData split_data;
  276. SplitParams split_param_data;
  277. } KernelGlobalsDummy;
  278. } // namespace
  279. struct CachedSplitMemory {
  280. int id;
  281. device_memory *split_data;
  282. device_memory *ray_state;
  283. device_memory *queue_index;
  284. device_memory *use_queues_flag;
  285. device_memory *work_pools;
  286. device_ptr *buffer;
  287. };
  288. class OpenCLSplitKernelFunction : public SplitKernelFunction {
  289. public:
  290. OpenCLDevice *device;
  291. OpenCLDevice::OpenCLProgram program;
  292. CachedSplitMemory &cached_memory;
  293. int cached_id;
  294. OpenCLSplitKernelFunction(OpenCLDevice *device, CachedSplitMemory &cached_memory)
  295. : device(device), cached_memory(cached_memory), cached_id(cached_memory.id - 1)
  296. {
  297. }
  298. ~OpenCLSplitKernelFunction()
  299. {
  300. program.release();
  301. }
  302. virtual bool enqueue(const KernelDimensions &dim, device_memory &kg, device_memory &data)
  303. {
  304. if (cached_id != cached_memory.id) {
  305. cl_uint start_arg_index = device->kernel_set_args(
  306. program(), 0, kg, data, *cached_memory.split_data, *cached_memory.ray_state);
  307. device->set_kernel_arg_buffers(program(), &start_arg_index);
  308. start_arg_index += device->kernel_set_args(program(),
  309. start_arg_index,
  310. *cached_memory.queue_index,
  311. *cached_memory.use_queues_flag,
  312. *cached_memory.work_pools,
  313. *cached_memory.buffer);
  314. cached_id = cached_memory.id;
  315. }
  316. device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
  317. program(),
  318. 2,
  319. NULL,
  320. dim.global_size,
  321. dim.local_size,
  322. 0,
  323. NULL,
  324. NULL);
  325. device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
  326. if (device->ciErr != CL_SUCCESS) {
  327. string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
  328. clewErrorString(device->ciErr));
  329. device->opencl_error(message);
  330. return false;
  331. }
  332. return true;
  333. }
  334. };
  335. class OpenCLSplitKernel : public DeviceSplitKernel {
  336. OpenCLDevice *device;
  337. CachedSplitMemory cached_memory;
  338. public:
  339. explicit OpenCLSplitKernel(OpenCLDevice *device) : DeviceSplitKernel(device), device(device)
  340. {
  341. }
  342. virtual SplitKernelFunction *get_split_kernel_function(
  343. const string &kernel_name, const DeviceRequestedFeatures &requested_features)
  344. {
  345. OpenCLSplitKernelFunction *kernel = new OpenCLSplitKernelFunction(device, cached_memory);
  346. const string program_name = device->get_opencl_program_name(kernel_name);
  347. kernel->program = OpenCLDevice::OpenCLProgram(
  348. device,
  349. program_name,
  350. device->get_opencl_program_filename(kernel_name),
  351. device->get_build_options(requested_features, program_name, device->use_preview_kernels));
  352. kernel->program.add_kernel(ustring("path_trace_" + kernel_name));
  353. kernel->program.load();
  354. if (!kernel->program.is_loaded()) {
  355. delete kernel;
  356. return NULL;
  357. }
  358. return kernel;
  359. }
  360. virtual uint64_t state_buffer_size(device_memory &kg, device_memory &data, size_t num_threads)
  361. {
  362. device_vector<uint64_t> size_buffer(device, "size_buffer", MEM_READ_WRITE);
  363. size_buffer.alloc(1);
  364. size_buffer.zero_to_device();
  365. uint threads = num_threads;
  366. OpenCLDevice::OpenCLSplitPrograms *programs = device->get_split_programs();
  367. cl_kernel kernel_state_buffer_size = programs->program_split(
  368. ustring("path_trace_state_buffer_size"));
  369. device->kernel_set_args(kernel_state_buffer_size, 0, kg, data, threads, size_buffer);
  370. size_t global_size = 64;
  371. device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
  372. kernel_state_buffer_size,
  373. 1,
  374. NULL,
  375. &global_size,
  376. NULL,
  377. 0,
  378. NULL,
  379. NULL);
  380. device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
  381. size_buffer.copy_from_device(0, 1, 1);
  382. size_t size = size_buffer[0];
  383. size_buffer.free();
  384. if (device->ciErr != CL_SUCCESS) {
  385. string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
  386. clewErrorString(device->ciErr));
  387. device->opencl_error(message);
  388. return 0;
  389. }
  390. return size;
  391. }
  392. virtual bool enqueue_split_kernel_data_init(const KernelDimensions &dim,
  393. RenderTile &rtile,
  394. int num_global_elements,
  395. device_memory &kernel_globals,
  396. device_memory &kernel_data,
  397. device_memory &split_data,
  398. device_memory &ray_state,
  399. device_memory &queue_index,
  400. device_memory &use_queues_flag,
  401. device_memory &work_pool_wgs)
  402. {
  403. cl_int dQueue_size = dim.global_size[0] * dim.global_size[1];
  404. /* Set the range of samples to be processed for every ray in
  405. * path-regeneration logic.
  406. */
  407. cl_int start_sample = rtile.start_sample;
  408. cl_int end_sample = rtile.start_sample + rtile.num_samples;
  409. OpenCLDevice::OpenCLSplitPrograms *programs = device->get_split_programs();
  410. cl_kernel kernel_data_init = programs->program_split(ustring("path_trace_data_init"));
  411. cl_uint start_arg_index = device->kernel_set_args(kernel_data_init,
  412. 0,
  413. kernel_globals,
  414. kernel_data,
  415. split_data,
  416. num_global_elements,
  417. ray_state);
  418. device->set_kernel_arg_buffers(kernel_data_init, &start_arg_index);
  419. start_arg_index += device->kernel_set_args(kernel_data_init,
  420. start_arg_index,
  421. start_sample,
  422. end_sample,
  423. rtile.x,
  424. rtile.y,
  425. rtile.w,
  426. rtile.h,
  427. rtile.offset,
  428. rtile.stride,
  429. queue_index,
  430. dQueue_size,
  431. use_queues_flag,
  432. work_pool_wgs,
  433. rtile.num_samples,
  434. rtile.buffer);
  435. /* Enqueue ckPathTraceKernel_data_init kernel. */
  436. device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
  437. kernel_data_init,
  438. 2,
  439. NULL,
  440. dim.global_size,
  441. dim.local_size,
  442. 0,
  443. NULL,
  444. NULL);
  445. device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
  446. if (device->ciErr != CL_SUCCESS) {
  447. string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
  448. clewErrorString(device->ciErr));
  449. device->opencl_error(message);
  450. return false;
  451. }
  452. cached_memory.split_data = &split_data;
  453. cached_memory.ray_state = &ray_state;
  454. cached_memory.queue_index = &queue_index;
  455. cached_memory.use_queues_flag = &use_queues_flag;
  456. cached_memory.work_pools = &work_pool_wgs;
  457. cached_memory.buffer = &rtile.buffer;
  458. cached_memory.id++;
  459. return true;
  460. }
  461. virtual int2 split_kernel_local_size()
  462. {
  463. return make_int2(64, 1);
  464. }
  465. virtual int2 split_kernel_global_size(device_memory &kg,
  466. device_memory &data,
  467. DeviceTask * /*task*/)
  468. {
  469. cl_device_type type = OpenCLInfo::get_device_type(device->cdDevice);
  470. /* Use small global size on CPU devices as it seems to be much faster. */
  471. if (type == CL_DEVICE_TYPE_CPU) {
  472. VLOG(1) << "Global size: (64, 64).";
  473. return make_int2(64, 64);
  474. }
  475. cl_ulong max_buffer_size;
  476. clGetDeviceInfo(
  477. device->cdDevice, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_buffer_size, NULL);
  478. if (DebugFlags().opencl.mem_limit) {
  479. max_buffer_size = min(max_buffer_size,
  480. cl_ulong(DebugFlags().opencl.mem_limit - device->stats.mem_used));
  481. }
  482. VLOG(1) << "Maximum device allocation size: " << string_human_readable_number(max_buffer_size)
  483. << " bytes. (" << string_human_readable_size(max_buffer_size) << ").";
  484. /* Limit to 2gb, as we shouldn't need more than that and some devices may support much more. */
  485. max_buffer_size = min(max_buffer_size / 2, (cl_ulong)2l * 1024 * 1024 * 1024);
  486. size_t num_elements = max_elements_for_max_buffer_size(kg, data, max_buffer_size);
  487. int2 global_size = make_int2(max(round_down((int)sqrt(num_elements), 64), 64),
  488. (int)sqrt(num_elements));
  489. VLOG(1) << "Global size: " << global_size << ".";
  490. return global_size;
  491. }
  492. };
  493. bool OpenCLDevice::opencl_error(cl_int err)
  494. {
  495. if (err != CL_SUCCESS) {
  496. string message = string_printf("OpenCL error (%d): %s", err, clewErrorString(err));
  497. if (error_msg == "")
  498. error_msg = message;
  499. fprintf(stderr, "%s\n", message.c_str());
  500. return true;
  501. }
  502. return false;
  503. }
  504. void OpenCLDevice::opencl_error(const string &message)
  505. {
  506. if (error_msg == "")
  507. error_msg = message;
  508. fprintf(stderr, "%s\n", message.c_str());
  509. }
  510. void OpenCLDevice::opencl_assert_err(cl_int err, const char *where)
  511. {
  512. if (err != CL_SUCCESS) {
  513. string message = string_printf(
  514. "OpenCL error (%d): %s in %s", err, clewErrorString(err), where);
  515. if (error_msg == "")
  516. error_msg = message;
  517. fprintf(stderr, "%s\n", message.c_str());
  518. # ifndef NDEBUG
  519. abort();
  520. # endif
  521. }
  522. }
  523. OpenCLDevice::OpenCLDevice(DeviceInfo &info, Stats &stats, Profiler &profiler, bool background)
  524. : Device(info, stats, profiler, background),
  525. kernel_programs(this),
  526. preview_programs(this),
  527. memory_manager(this),
  528. texture_info(this, "__texture_info", MEM_TEXTURE)
  529. {
  530. cpPlatform = NULL;
  531. cdDevice = NULL;
  532. cxContext = NULL;
  533. cqCommandQueue = NULL;
  534. null_mem = 0;
  535. device_initialized = false;
  536. textures_need_update = true;
  537. use_preview_kernels = !background;
  538. vector<OpenCLPlatformDevice> usable_devices;
  539. OpenCLInfo::get_usable_devices(&usable_devices);
  540. if (usable_devices.size() == 0) {
  541. opencl_error("OpenCL: no devices found.");
  542. return;
  543. }
  544. assert(info.num < usable_devices.size());
  545. OpenCLPlatformDevice &platform_device = usable_devices[info.num];
  546. device_num = info.num;
  547. cpPlatform = platform_device.platform_id;
  548. cdDevice = platform_device.device_id;
  549. platform_name = platform_device.platform_name;
  550. device_name = platform_device.device_name;
  551. VLOG(2) << "Creating new Cycles device for OpenCL platform " << platform_name << ", device "
  552. << device_name << ".";
  553. {
  554. /* try to use cached context */
  555. thread_scoped_lock cache_locker;
  556. cxContext = OpenCLCache::get_context(cpPlatform, cdDevice, cache_locker);
  557. if (cxContext == NULL) {
  558. /* create context properties array to specify platform */
  559. const cl_context_properties context_props[] = {
  560. CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform, 0, 0};
  561. /* create context */
  562. cxContext = clCreateContext(
  563. context_props, 1, &cdDevice, context_notify_callback, cdDevice, &ciErr);
  564. if (opencl_error(ciErr)) {
  565. opencl_error("OpenCL: clCreateContext failed");
  566. return;
  567. }
  568. /* cache it */
  569. OpenCLCache::store_context(cpPlatform, cdDevice, cxContext, cache_locker);
  570. }
  571. }
  572. cqCommandQueue = clCreateCommandQueue(cxContext, cdDevice, 0, &ciErr);
  573. if (opencl_error(ciErr)) {
  574. opencl_error("OpenCL: Error creating command queue");
  575. return;
  576. }
  577. null_mem = (device_ptr)clCreateBuffer(cxContext, CL_MEM_READ_ONLY, 1, NULL, &ciErr);
  578. if (opencl_error(ciErr)) {
  579. opencl_error("OpenCL: Error creating memory buffer for NULL");
  580. return;
  581. }
  582. /* Allocate this right away so that texture_info
  583. * is placed at offset 0 in the device memory buffers. */
  584. texture_info.resize(1);
  585. memory_manager.alloc("texture_info", texture_info);
  586. device_initialized = true;
  587. split_kernel = new OpenCLSplitKernel(this);
  588. if (!background) {
  589. load_preview_kernels();
  590. }
  591. }
  592. OpenCLDevice::~OpenCLDevice()
  593. {
  594. task_pool.stop();
  595. load_required_kernel_task_pool.stop();
  596. load_kernel_task_pool.stop();
  597. memory_manager.free();
  598. if (null_mem)
  599. clReleaseMemObject(CL_MEM_PTR(null_mem));
  600. ConstMemMap::iterator mt;
  601. for (mt = const_mem_map.begin(); mt != const_mem_map.end(); mt++) {
  602. delete mt->second;
  603. }
  604. base_program.release();
  605. bake_program.release();
  606. displace_program.release();
  607. background_program.release();
  608. denoising_program.release();
  609. if (cqCommandQueue)
  610. clReleaseCommandQueue(cqCommandQueue);
  611. if (cxContext)
  612. clReleaseContext(cxContext);
  613. delete split_kernel;
  614. }
  615. void CL_CALLBACK OpenCLDevice::context_notify_callback(const char *err_info,
  616. const void * /*private_info*/,
  617. size_t /*cb*/,
  618. void *user_data)
  619. {
  620. string device_name = OpenCLInfo::get_device_name((cl_device_id)user_data);
  621. fprintf(stderr, "OpenCL error (%s): %s\n", device_name.c_str(), err_info);
  622. }
  623. bool OpenCLDevice::opencl_version_check()
  624. {
  625. string error;
  626. if (!OpenCLInfo::platform_version_check(cpPlatform, &error)) {
  627. opencl_error(error);
  628. return false;
  629. }
  630. if (!OpenCLInfo::device_version_check(cdDevice, &error)) {
  631. opencl_error(error);
  632. return false;
  633. }
  634. return true;
  635. }
  636. string OpenCLDevice::device_md5_hash(string kernel_custom_build_options)
  637. {
  638. MD5Hash md5;
  639. char version[256], driver[256], name[256], vendor[256];
  640. clGetPlatformInfo(cpPlatform, CL_PLATFORM_VENDOR, sizeof(vendor), &vendor, NULL);
  641. clGetDeviceInfo(cdDevice, CL_DEVICE_VERSION, sizeof(version), &version, NULL);
  642. clGetDeviceInfo(cdDevice, CL_DEVICE_NAME, sizeof(name), &name, NULL);
  643. clGetDeviceInfo(cdDevice, CL_DRIVER_VERSION, sizeof(driver), &driver, NULL);
  644. md5.append((uint8_t *)vendor, strlen(vendor));
  645. md5.append((uint8_t *)version, strlen(version));
  646. md5.append((uint8_t *)name, strlen(name));
  647. md5.append((uint8_t *)driver, strlen(driver));
  648. string options = kernel_build_options();
  649. options += kernel_custom_build_options;
  650. md5.append((uint8_t *)options.c_str(), options.size());
  651. return md5.get_hex();
  652. }
  653. bool OpenCLDevice::load_kernels(const DeviceRequestedFeatures &requested_features)
  654. {
  655. VLOG(2) << "Loading kernels for platform " << platform_name << ", device " << device_name << ".";
  656. /* Verify if device was initialized. */
  657. if (!device_initialized) {
  658. fprintf(stderr, "OpenCL: failed to initialize device.\n");
  659. return false;
  660. }
  661. /* Verify we have right opencl version. */
  662. if (!opencl_version_check())
  663. return false;
  664. load_required_kernels(requested_features);
  665. vector<OpenCLProgram *> programs;
  666. kernel_programs.load_kernels(programs, requested_features, false);
  667. if (!requested_features.use_baking && requested_features.use_denoising) {
  668. denoising_program = OpenCLProgram(
  669. this, "denoising", "filter.cl", get_build_options(requested_features, "denoising"));
  670. denoising_program.add_kernel(ustring("filter_divide_shadow"));
  671. denoising_program.add_kernel(ustring("filter_get_feature"));
  672. denoising_program.add_kernel(ustring("filter_write_feature"));
  673. denoising_program.add_kernel(ustring("filter_detect_outliers"));
  674. denoising_program.add_kernel(ustring("filter_combine_halves"));
  675. denoising_program.add_kernel(ustring("filter_construct_transform"));
  676. denoising_program.add_kernel(ustring("filter_nlm_calc_difference"));
  677. denoising_program.add_kernel(ustring("filter_nlm_blur"));
  678. denoising_program.add_kernel(ustring("filter_nlm_calc_weight"));
  679. denoising_program.add_kernel(ustring("filter_nlm_update_output"));
  680. denoising_program.add_kernel(ustring("filter_nlm_normalize"));
  681. denoising_program.add_kernel(ustring("filter_nlm_construct_gramian"));
  682. denoising_program.add_kernel(ustring("filter_finalize"));
  683. programs.push_back(&denoising_program);
  684. }
  685. load_required_kernel_task_pool.wait_work();
  686. /* Parallel compilation of Cycles kernels, this launches multiple
  687. * processes to workaround OpenCL frameworks serializing the calls
  688. * internally within a single process. */
  689. foreach (OpenCLProgram *program, programs) {
  690. if (!program->load()) {
  691. load_kernel_task_pool.push(function_bind(&OpenCLProgram::compile, program));
  692. }
  693. }
  694. return true;
  695. }
  696. void OpenCLDevice::load_required_kernels(const DeviceRequestedFeatures &requested_features)
  697. {
  698. vector<OpenCLProgram *> programs;
  699. base_program = OpenCLProgram(
  700. this, "base", "kernel_base.cl", get_build_options(requested_features, "base"));
  701. base_program.add_kernel(ustring("convert_to_byte"));
  702. base_program.add_kernel(ustring("convert_to_half_float"));
  703. base_program.add_kernel(ustring("zero_buffer"));
  704. programs.push_back(&base_program);
  705. if (requested_features.use_true_displacement) {
  706. displace_program = OpenCLProgram(
  707. this, "displace", "kernel_displace.cl", get_build_options(requested_features, "displace"));
  708. displace_program.add_kernel(ustring("displace"));
  709. programs.push_back(&displace_program);
  710. }
  711. if (requested_features.use_background_light) {
  712. background_program = OpenCLProgram(this,
  713. "background",
  714. "kernel_background.cl",
  715. get_build_options(requested_features, "background"));
  716. background_program.add_kernel(ustring("background"));
  717. programs.push_back(&background_program);
  718. }
  719. if (requested_features.use_baking) {
  720. bake_program = OpenCLProgram(
  721. this, "bake", "kernel_bake.cl", get_build_options(requested_features, "bake"));
  722. bake_program.add_kernel(ustring("bake"));
  723. programs.push_back(&bake_program);
  724. }
  725. foreach (OpenCLProgram *program, programs) {
  726. if (!program->load()) {
  727. load_required_kernel_task_pool.push(function_bind(&OpenCLProgram::compile, program));
  728. }
  729. }
  730. }
  731. void OpenCLDevice::load_preview_kernels()
  732. {
  733. DeviceRequestedFeatures no_features;
  734. vector<OpenCLProgram *> programs;
  735. preview_programs.load_kernels(programs, no_features, true);
  736. foreach (OpenCLProgram *program, programs) {
  737. if (!program->load()) {
  738. load_required_kernel_task_pool.push(function_bind(&OpenCLProgram::compile, program));
  739. }
  740. }
  741. }
  742. bool OpenCLDevice::wait_for_availability(const DeviceRequestedFeatures &requested_features)
  743. {
  744. if (background) {
  745. load_kernel_task_pool.wait_work();
  746. use_preview_kernels = false;
  747. }
  748. else {
  749. /* We use a device setting to determine to load preview kernels or not
  750. * Better to check on device level than per kernel as mixing preview and
  751. * non-preview kernels does not work due to different data types */
  752. if (use_preview_kernels) {
  753. use_preview_kernels = !load_kernel_task_pool.finished();
  754. }
  755. }
  756. return split_kernel->load_kernels(requested_features);
  757. }
  758. OpenCLDevice::OpenCLSplitPrograms *OpenCLDevice::get_split_programs()
  759. {
  760. return use_preview_kernels ? &preview_programs : &kernel_programs;
  761. }
  762. DeviceKernelStatus OpenCLDevice::get_active_kernel_switch_state()
  763. {
  764. /* Do not switch kernels for background renderings
  765. * We do foreground rendering but use the preview kernels
  766. * Check for the optimized kernels
  767. *
  768. * This works also the other way around, where we are using
  769. * optimized kernels but new ones are being compiled due
  770. * to other features that are needed */
  771. if (background) {
  772. /* The if-statements below would find the same result,
  773. * But as the `finished` method uses a mutex we added
  774. * this as an early exit */
  775. return DEVICE_KERNEL_USING_FEATURE_KERNEL;
  776. }
  777. bool other_kernels_finished = load_kernel_task_pool.finished();
  778. if (use_preview_kernels) {
  779. if (other_kernels_finished) {
  780. return DEVICE_KERNEL_FEATURE_KERNEL_AVAILABLE;
  781. }
  782. else {
  783. return DEVICE_KERNEL_WAITING_FOR_FEATURE_KERNEL;
  784. }
  785. }
  786. else {
  787. if (other_kernels_finished) {
  788. return DEVICE_KERNEL_USING_FEATURE_KERNEL;
  789. }
  790. else {
  791. return DEVICE_KERNEL_FEATURE_KERNEL_INVALID;
  792. }
  793. }
  794. }
  795. void OpenCLDevice::mem_alloc(device_memory &mem)
  796. {
  797. if (mem.name) {
  798. VLOG(1) << "Buffer allocate: " << mem.name << ", "
  799. << string_human_readable_number(mem.memory_size()) << " bytes. ("
  800. << string_human_readable_size(mem.memory_size()) << ")";
  801. }
  802. size_t size = mem.memory_size();
  803. /* check there is enough memory available for the allocation */
  804. cl_ulong max_alloc_size = 0;
  805. clGetDeviceInfo(cdDevice, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_alloc_size, NULL);
  806. if (DebugFlags().opencl.mem_limit) {
  807. max_alloc_size = min(max_alloc_size, cl_ulong(DebugFlags().opencl.mem_limit - stats.mem_used));
  808. }
  809. if (size > max_alloc_size) {
  810. string error = "Scene too complex to fit in available memory.";
  811. if (mem.name != NULL) {
  812. error += string_printf(" (allocating buffer %s failed.)", mem.name);
  813. }
  814. set_error(error);
  815. return;
  816. }
  817. cl_mem_flags mem_flag;
  818. void *mem_ptr = NULL;
  819. if (mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
  820. mem_flag = CL_MEM_READ_ONLY;
  821. else
  822. mem_flag = CL_MEM_READ_WRITE;
  823. /* Zero-size allocation might be invoked by render, but not really
  824. * supported by OpenCL. Using NULL as device pointer also doesn't really
  825. * work for some reason, so for the time being we'll use special case
  826. * will null_mem buffer.
  827. */
  828. if (size != 0) {
  829. mem.device_pointer = (device_ptr)clCreateBuffer(cxContext, mem_flag, size, mem_ptr, &ciErr);
  830. opencl_assert_err(ciErr, "clCreateBuffer");
  831. }
  832. else {
  833. mem.device_pointer = null_mem;
  834. }
  835. stats.mem_alloc(size);
  836. mem.device_size = size;
  837. }
  838. void OpenCLDevice::mem_copy_to(device_memory &mem)
  839. {
  840. if (mem.type == MEM_TEXTURE) {
  841. tex_free(mem);
  842. tex_alloc(mem);
  843. }
  844. else {
  845. if (!mem.device_pointer) {
  846. mem_alloc(mem);
  847. }
  848. /* this is blocking */
  849. size_t size = mem.memory_size();
  850. if (size != 0) {
  851. opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
  852. CL_MEM_PTR(mem.device_pointer),
  853. CL_TRUE,
  854. 0,
  855. size,
  856. mem.host_pointer,
  857. 0,
  858. NULL,
  859. NULL));
  860. }
  861. }
  862. }
  863. void OpenCLDevice::mem_copy_from(device_memory &mem, int y, int w, int h, int elem)
  864. {
  865. size_t offset = elem * y * w;
  866. size_t size = elem * w * h;
  867. assert(size != 0);
  868. opencl_assert(clEnqueueReadBuffer(cqCommandQueue,
  869. CL_MEM_PTR(mem.device_pointer),
  870. CL_TRUE,
  871. offset,
  872. size,
  873. (uchar *)mem.host_pointer + offset,
  874. 0,
  875. NULL,
  876. NULL));
  877. }
  878. void OpenCLDevice::mem_zero_kernel(device_ptr mem, size_t size)
  879. {
  880. base_program.wait_for_availability();
  881. cl_kernel ckZeroBuffer = base_program(ustring("zero_buffer"));
  882. size_t global_size[] = {1024, 1024};
  883. size_t num_threads = global_size[0] * global_size[1];
  884. cl_mem d_buffer = CL_MEM_PTR(mem);
  885. cl_ulong d_offset = 0;
  886. cl_ulong d_size = 0;
  887. while (d_offset < size) {
  888. d_size = std::min<cl_ulong>(num_threads * sizeof(float4), size - d_offset);
  889. kernel_set_args(ckZeroBuffer, 0, d_buffer, d_size, d_offset);
  890. ciErr = clEnqueueNDRangeKernel(
  891. cqCommandQueue, ckZeroBuffer, 2, NULL, global_size, NULL, 0, NULL, NULL);
  892. opencl_assert_err(ciErr, "clEnqueueNDRangeKernel");
  893. d_offset += d_size;
  894. }
  895. }
  896. void OpenCLDevice::mem_zero(device_memory &mem)
  897. {
  898. if (!mem.device_pointer) {
  899. mem_alloc(mem);
  900. }
  901. if (mem.device_pointer) {
  902. if (base_program.is_loaded()) {
  903. mem_zero_kernel(mem.device_pointer, mem.memory_size());
  904. }
  905. if (mem.host_pointer) {
  906. memset(mem.host_pointer, 0, mem.memory_size());
  907. }
  908. if (!base_program.is_loaded()) {
  909. void *zero = mem.host_pointer;
  910. if (!mem.host_pointer) {
  911. zero = util_aligned_malloc(mem.memory_size(), 16);
  912. memset(zero, 0, mem.memory_size());
  913. }
  914. opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
  915. CL_MEM_PTR(mem.device_pointer),
  916. CL_TRUE,
  917. 0,
  918. mem.memory_size(),
  919. zero,
  920. 0,
  921. NULL,
  922. NULL));
  923. if (!mem.host_pointer) {
  924. util_aligned_free(zero);
  925. }
  926. }
  927. }
  928. }
  929. void OpenCLDevice::mem_free(device_memory &mem)
  930. {
  931. if (mem.type == MEM_TEXTURE) {
  932. tex_free(mem);
  933. }
  934. else {
  935. if (mem.device_pointer) {
  936. if (mem.device_pointer != null_mem) {
  937. opencl_assert(clReleaseMemObject(CL_MEM_PTR(mem.device_pointer)));
  938. }
  939. mem.device_pointer = 0;
  940. stats.mem_free(mem.device_size);
  941. mem.device_size = 0;
  942. }
  943. }
  944. }
  945. int OpenCLDevice::mem_sub_ptr_alignment()
  946. {
  947. return OpenCLInfo::mem_sub_ptr_alignment(cdDevice);
  948. }
  949. device_ptr OpenCLDevice::mem_alloc_sub_ptr(device_memory &mem, int offset, int size)
  950. {
  951. cl_mem_flags mem_flag;
  952. if (mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
  953. mem_flag = CL_MEM_READ_ONLY;
  954. else
  955. mem_flag = CL_MEM_READ_WRITE;
  956. cl_buffer_region info;
  957. info.origin = mem.memory_elements_size(offset);
  958. info.size = mem.memory_elements_size(size);
  959. device_ptr sub_buf = (device_ptr)clCreateSubBuffer(
  960. CL_MEM_PTR(mem.device_pointer), mem_flag, CL_BUFFER_CREATE_TYPE_REGION, &info, &ciErr);
  961. opencl_assert_err(ciErr, "clCreateSubBuffer");
  962. return sub_buf;
  963. }
  964. void OpenCLDevice::mem_free_sub_ptr(device_ptr device_pointer)
  965. {
  966. if (device_pointer && device_pointer != null_mem) {
  967. opencl_assert(clReleaseMemObject(CL_MEM_PTR(device_pointer)));
  968. }
  969. }
  970. void OpenCLDevice::const_copy_to(const char *name, void *host, size_t size)
  971. {
  972. ConstMemMap::iterator i = const_mem_map.find(name);
  973. device_vector<uchar> *data;
  974. if (i == const_mem_map.end()) {
  975. data = new device_vector<uchar>(this, name, MEM_READ_ONLY);
  976. data->alloc(size);
  977. const_mem_map.insert(ConstMemMap::value_type(name, data));
  978. }
  979. else {
  980. data = i->second;
  981. }
  982. memcpy(data->data(), host, size);
  983. data->copy_to_device();
  984. }
  985. void OpenCLDevice::tex_alloc(device_memory &mem)
  986. {
  987. VLOG(1) << "Texture allocate: " << mem.name << ", "
  988. << string_human_readable_number(mem.memory_size()) << " bytes. ("
  989. << string_human_readable_size(mem.memory_size()) << ")";
  990. memory_manager.alloc(mem.name, mem);
  991. /* Set the pointer to non-null to keep code that inspects its value from thinking its
  992. * unallocated. */
  993. mem.device_pointer = 1;
  994. textures[mem.name] = &mem;
  995. textures_need_update = true;
  996. }
  997. void OpenCLDevice::tex_free(device_memory &mem)
  998. {
  999. if (mem.device_pointer) {
  1000. mem.device_pointer = 0;
  1001. if (memory_manager.free(mem)) {
  1002. textures_need_update = true;
  1003. }
  1004. foreach (TexturesMap::value_type &value, textures) {
  1005. if (value.second == &mem) {
  1006. textures.erase(value.first);
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. size_t OpenCLDevice::global_size_round_up(int group_size, int global_size)
  1013. {
  1014. int r = global_size % group_size;
  1015. return global_size + ((r == 0) ? 0 : group_size - r);
  1016. }
  1017. void OpenCLDevice::enqueue_kernel(
  1018. cl_kernel kernel, size_t w, size_t h, bool x_workgroups, size_t max_workgroup_size)
  1019. {
  1020. size_t workgroup_size, max_work_items[3];
  1021. clGetKernelWorkGroupInfo(
  1022. kernel, cdDevice, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL);
  1023. clGetDeviceInfo(
  1024. cdDevice, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t) * 3, max_work_items, NULL);
  1025. if (max_workgroup_size > 0 && workgroup_size > max_workgroup_size) {
  1026. workgroup_size = max_workgroup_size;
  1027. }
  1028. /* Try to divide evenly over 2 dimensions. */
  1029. size_t local_size[2];
  1030. if (x_workgroups) {
  1031. local_size[0] = workgroup_size;
  1032. local_size[1] = 1;
  1033. }
  1034. else {
  1035. size_t sqrt_workgroup_size = max((size_t)sqrt((double)workgroup_size), 1);
  1036. local_size[0] = local_size[1] = sqrt_workgroup_size;
  1037. }
  1038. /* Some implementations have max size 1 on 2nd dimension. */
  1039. if (local_size[1] > max_work_items[1]) {
  1040. local_size[0] = workgroup_size / max_work_items[1];
  1041. local_size[1] = max_work_items[1];
  1042. }
  1043. size_t global_size[2] = {global_size_round_up(local_size[0], w),
  1044. global_size_round_up(local_size[1], h)};
  1045. /* Vertical size of 1 is coming from bake/shade kernels where we should
  1046. * not round anything up because otherwise we'll either be doing too
  1047. * much work per pixel (if we don't check global ID on Y axis) or will
  1048. * be checking for global ID to always have Y of 0.
  1049. */
  1050. if (h == 1) {
  1051. global_size[h] = 1;
  1052. }
  1053. /* run kernel */
  1054. opencl_assert(
  1055. clEnqueueNDRangeKernel(cqCommandQueue, kernel, 2, NULL, global_size, NULL, 0, NULL, NULL));
  1056. opencl_assert(clFlush(cqCommandQueue));
  1057. }
  1058. void OpenCLDevice::set_kernel_arg_mem(cl_kernel kernel, cl_uint *narg, const char *name)
  1059. {
  1060. cl_mem ptr;
  1061. MemMap::iterator i = mem_map.find(name);
  1062. if (i != mem_map.end()) {
  1063. ptr = CL_MEM_PTR(i->second);
  1064. }
  1065. else {
  1066. /* work around NULL not working, even though the spec says otherwise */
  1067. ptr = CL_MEM_PTR(null_mem);
  1068. }
  1069. opencl_assert(clSetKernelArg(kernel, (*narg)++, sizeof(ptr), (void *)&ptr));
  1070. }
  1071. void OpenCLDevice::set_kernel_arg_buffers(cl_kernel kernel, cl_uint *narg)
  1072. {
  1073. flush_texture_buffers();
  1074. memory_manager.set_kernel_arg_buffers(kernel, narg);
  1075. }
  1076. void OpenCLDevice::flush_texture_buffers()
  1077. {
  1078. if (!textures_need_update) {
  1079. return;
  1080. }
  1081. textures_need_update = false;
  1082. /* Setup slots for textures. */
  1083. int num_slots = 0;
  1084. vector<texture_slot_t> texture_slots;
  1085. # define KERNEL_TEX(type, name) \
  1086. if (textures.find(#name) != textures.end()) { \
  1087. texture_slots.push_back(texture_slot_t(#name, num_slots)); \
  1088. } \
  1089. num_slots++;
  1090. # include "kernel/kernel_textures.h"
  1091. int num_data_slots = num_slots;
  1092. foreach (TexturesMap::value_type &tex, textures) {
  1093. string name = tex.first;
  1094. if (string_startswith(name, "__tex_image")) {
  1095. int pos = name.rfind("_");
  1096. int id = atoi(name.data() + pos + 1);
  1097. texture_slots.push_back(texture_slot_t(name, num_data_slots + id));
  1098. num_slots = max(num_slots, num_data_slots + id + 1);
  1099. }
  1100. }
  1101. /* Realloc texture descriptors buffer. */
  1102. memory_manager.free(texture_info);
  1103. texture_info.resize(num_slots);
  1104. memory_manager.alloc("texture_info", texture_info);
  1105. /* Fill in descriptors */
  1106. foreach (texture_slot_t &slot, texture_slots) {
  1107. TextureInfo &info = texture_info[slot.slot];
  1108. MemoryManager::BufferDescriptor desc = memory_manager.get_descriptor(slot.name);
  1109. info.data = desc.offset;
  1110. info.cl_buffer = desc.device_buffer;
  1111. if (string_startswith(slot.name, "__tex_image")) {
  1112. device_memory *mem = textures[slot.name];
  1113. info.width = mem->data_width;
  1114. info.height = mem->data_height;
  1115. info.depth = mem->data_depth;
  1116. info.interpolation = mem->interpolation;
  1117. info.extension = mem->extension;
  1118. }
  1119. }
  1120. /* Force write of descriptors. */
  1121. memory_manager.free(texture_info);
  1122. memory_manager.alloc("texture_info", texture_info);
  1123. }
  1124. void OpenCLDevice::thread_run(DeviceTask *task)
  1125. {
  1126. flush_texture_buffers();
  1127. if (task->type == DeviceTask::FILM_CONVERT) {
  1128. film_convert(*task, task->buffer, task->rgba_byte, task->rgba_half);
  1129. }
  1130. else if (task->type == DeviceTask::SHADER) {
  1131. shader(*task);
  1132. }
  1133. else if (task->type == DeviceTask::RENDER) {
  1134. RenderTile tile;
  1135. DenoisingTask denoising(this, *task);
  1136. /* Allocate buffer for kernel globals */
  1137. device_only_memory<KernelGlobalsDummy> kgbuffer(this, "kernel_globals");
  1138. kgbuffer.alloc_to_device(1);
  1139. /* Keep rendering tiles until done. */
  1140. while (task->acquire_tile(this, tile)) {
  1141. if (tile.task == RenderTile::PATH_TRACE) {
  1142. assert(tile.task == RenderTile::PATH_TRACE);
  1143. scoped_timer timer(&tile.buffers->render_time);
  1144. split_kernel->path_trace(task, tile, kgbuffer, *const_mem_map["__data"]);
  1145. /* Complete kernel execution before release tile. */
  1146. /* This helps in multi-device render;
  1147. * The device that reaches the critical-section function
  1148. * release_tile waits (stalling other devices from entering
  1149. * release_tile) for all kernels to complete. If device1 (a
  1150. * slow-render device) reaches release_tile first then it would
  1151. * stall device2 (a fast-render device) from proceeding to render
  1152. * next tile.
  1153. */
  1154. clFinish(cqCommandQueue);
  1155. }
  1156. else if (tile.task == RenderTile::DENOISE) {
  1157. tile.sample = tile.start_sample + tile.num_samples;
  1158. denoise(tile, denoising);
  1159. task->update_progress(&tile, tile.w * tile.h);
  1160. }
  1161. task->release_tile(tile);
  1162. }
  1163. kgbuffer.free();
  1164. }
  1165. }
  1166. void OpenCLDevice::film_convert(DeviceTask &task,
  1167. device_ptr buffer,
  1168. device_ptr rgba_byte,
  1169. device_ptr rgba_half)
  1170. {
  1171. /* cast arguments to cl types */
  1172. cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
  1173. cl_mem d_rgba = (rgba_byte) ? CL_MEM_PTR(rgba_byte) : CL_MEM_PTR(rgba_half);
  1174. cl_mem d_buffer = CL_MEM_PTR(buffer);
  1175. cl_int d_x = task.x;
  1176. cl_int d_y = task.y;
  1177. cl_int d_w = task.w;
  1178. cl_int d_h = task.h;
  1179. cl_float d_sample_scale = 1.0f / (task.sample + 1);
  1180. cl_int d_offset = task.offset;
  1181. cl_int d_stride = task.stride;
  1182. cl_kernel ckFilmConvertKernel = (rgba_byte) ? base_program(ustring("convert_to_byte")) :
  1183. base_program(ustring("convert_to_half_float"));
  1184. cl_uint start_arg_index = kernel_set_args(ckFilmConvertKernel, 0, d_data, d_rgba, d_buffer);
  1185. set_kernel_arg_buffers(ckFilmConvertKernel, &start_arg_index);
  1186. start_arg_index += kernel_set_args(ckFilmConvertKernel,
  1187. start_arg_index,
  1188. d_sample_scale,
  1189. d_x,
  1190. d_y,
  1191. d_w,
  1192. d_h,
  1193. d_offset,
  1194. d_stride);
  1195. enqueue_kernel(ckFilmConvertKernel, d_w, d_h);
  1196. }
  1197. bool OpenCLDevice::denoising_non_local_means(device_ptr image_ptr,
  1198. device_ptr guide_ptr,
  1199. device_ptr variance_ptr,
  1200. device_ptr out_ptr,
  1201. DenoisingTask *task)
  1202. {
  1203. int stride = task->buffer.stride;
  1204. int w = task->buffer.width;
  1205. int h = task->buffer.h;
  1206. int r = task->nlm_state.r;
  1207. int f = task->nlm_state.f;
  1208. float a = task->nlm_state.a;
  1209. float k_2 = task->nlm_state.k_2;
  1210. int pass_stride = task->buffer.pass_stride;
  1211. int num_shifts = (2 * r + 1) * (2 * r + 1);
  1212. int channel_offset = task->nlm_state.is_color ? task->buffer.pass_stride : 0;
  1213. device_sub_ptr difference(task->buffer.temporary_mem, 0, pass_stride * num_shifts);
  1214. device_sub_ptr blurDifference(
  1215. task->buffer.temporary_mem, pass_stride * num_shifts, pass_stride * num_shifts);
  1216. device_sub_ptr weightAccum(
  1217. task->buffer.temporary_mem, 2 * pass_stride * num_shifts, pass_stride);
  1218. cl_mem weightAccum_mem = CL_MEM_PTR(*weightAccum);
  1219. cl_mem difference_mem = CL_MEM_PTR(*difference);
  1220. cl_mem blurDifference_mem = CL_MEM_PTR(*blurDifference);
  1221. cl_mem image_mem = CL_MEM_PTR(image_ptr);
  1222. cl_mem guide_mem = CL_MEM_PTR(guide_ptr);
  1223. cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
  1224. cl_mem out_mem = CL_MEM_PTR(out_ptr);
  1225. cl_mem scale_mem = NULL;
  1226. mem_zero_kernel(*weightAccum, sizeof(float) * pass_stride);
  1227. mem_zero_kernel(out_ptr, sizeof(float) * pass_stride);
  1228. cl_kernel ckNLMCalcDifference = denoising_program(ustring("filter_nlm_calc_difference"));
  1229. cl_kernel ckNLMBlur = denoising_program(ustring("filter_nlm_blur"));
  1230. cl_kernel ckNLMCalcWeight = denoising_program(ustring("filter_nlm_calc_weight"));
  1231. cl_kernel ckNLMUpdateOutput = denoising_program(ustring("filter_nlm_update_output"));
  1232. cl_kernel ckNLMNormalize = denoising_program(ustring("filter_nlm_normalize"));
  1233. kernel_set_args(ckNLMCalcDifference,
  1234. 0,
  1235. guide_mem,
  1236. variance_mem,
  1237. scale_mem,
  1238. difference_mem,
  1239. w,
  1240. h,
  1241. stride,
  1242. pass_stride,
  1243. r,
  1244. channel_offset,
  1245. 0,
  1246. a,
  1247. k_2);
  1248. kernel_set_args(
  1249. ckNLMBlur, 0, difference_mem, blurDifference_mem, w, h, stride, pass_stride, r, f);
  1250. kernel_set_args(
  1251. ckNLMCalcWeight, 0, blurDifference_mem, difference_mem, w, h, stride, pass_stride, r, f);
  1252. kernel_set_args(ckNLMUpdateOutput,
  1253. 0,
  1254. blurDifference_mem,
  1255. image_mem,
  1256. out_mem,
  1257. weightAccum_mem,
  1258. w,
  1259. h,
  1260. stride,
  1261. pass_stride,
  1262. channel_offset,
  1263. r,
  1264. f);
  1265. enqueue_kernel(ckNLMCalcDifference, w * h, num_shifts, true);
  1266. enqueue_kernel(ckNLMBlur, w * h, num_shifts, true);
  1267. enqueue_kernel(ckNLMCalcWeight, w * h, num_shifts, true);
  1268. enqueue_kernel(ckNLMBlur, w * h, num_shifts, true);
  1269. enqueue_kernel(ckNLMUpdateOutput, w * h, num_shifts, true);
  1270. kernel_set_args(ckNLMNormalize, 0, out_mem, weightAccum_mem, w, h, stride);
  1271. enqueue_kernel(ckNLMNormalize, w, h);
  1272. return true;
  1273. }
  1274. bool OpenCLDevice::denoising_construct_transform(DenoisingTask *task)
  1275. {
  1276. cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
  1277. cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
  1278. cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
  1279. cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
  1280. char use_time = task->buffer.use_time ? 1 : 0;
  1281. cl_kernel ckFilterConstructTransform = denoising_program(ustring("filter_construct_transform"));
  1282. int arg_ofs = kernel_set_args(ckFilterConstructTransform, 0, buffer_mem, tile_info_mem);
  1283. cl_mem buffers[9];
  1284. for (int i = 0; i < 9; i++) {
  1285. buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
  1286. arg_ofs += kernel_set_args(ckFilterConstructTransform, arg_ofs, buffers[i]);
  1287. }
  1288. kernel_set_args(ckFilterConstructTransform,
  1289. arg_ofs,
  1290. transform_mem,
  1291. rank_mem,
  1292. task->filter_area,
  1293. task->rect,
  1294. task->buffer.pass_stride,
  1295. task->buffer.frame_stride,
  1296. use_time,
  1297. task->radius,
  1298. task->pca_threshold);
  1299. enqueue_kernel(ckFilterConstructTransform, task->storage.w, task->storage.h, 256);
  1300. return true;
  1301. }
  1302. bool OpenCLDevice::denoising_accumulate(device_ptr color_ptr,
  1303. device_ptr color_variance_ptr,
  1304. device_ptr scale_ptr,
  1305. int frame,
  1306. DenoisingTask *task)
  1307. {
  1308. cl_mem color_mem = CL_MEM_PTR(color_ptr);
  1309. cl_mem color_variance_mem = CL_MEM_PTR(color_variance_ptr);
  1310. cl_mem scale_mem = CL_MEM_PTR(scale_ptr);
  1311. cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
  1312. cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
  1313. cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
  1314. cl_mem XtWX_mem = CL_MEM_PTR(task->storage.XtWX.device_pointer);
  1315. cl_mem XtWY_mem = CL_MEM_PTR(task->storage.XtWY.device_pointer);
  1316. cl_kernel ckNLMCalcDifference = denoising_program(ustring("filter_nlm_calc_difference"));
  1317. cl_kernel ckNLMBlur = denoising_program(ustring("filter_nlm_blur"));
  1318. cl_kernel ckNLMCalcWeight = denoising_program(ustring("filter_nlm_calc_weight"));
  1319. cl_kernel ckNLMConstructGramian = denoising_program(ustring("filter_nlm_construct_gramian"));
  1320. int w = task->reconstruction_state.source_w;
  1321. int h = task->reconstruction_state.source_h;
  1322. int stride = task->buffer.stride;
  1323. int frame_offset = frame * task->buffer.frame_stride;
  1324. int t = task->tile_info->frames[frame];
  1325. char use_time = task->buffer.use_time ? 1 : 0;
  1326. int r = task->radius;
  1327. int pass_stride = task->buffer.pass_stride;
  1328. int num_shifts = (2 * r + 1) * (2 * r + 1);
  1329. device_sub_ptr difference(task->buffer.temporary_mem, 0, pass_stride * num_shifts);
  1330. device_sub_ptr blurDifference(
  1331. task->buffer.temporary_mem, pass_stride * num_shifts, pass_stride * num_shifts);
  1332. cl_mem difference_mem = CL_MEM_PTR(*difference);
  1333. cl_mem blurDifference_mem = CL_MEM_PTR(*blurDifference);
  1334. kernel_set_args(ckNLMCalcDifference,
  1335. 0,
  1336. color_mem,
  1337. color_variance_mem,
  1338. scale_mem,
  1339. difference_mem,
  1340. w,
  1341. h,
  1342. stride,
  1343. pass_stride,
  1344. r,
  1345. pass_stride,
  1346. frame_offset,
  1347. 1.0f,
  1348. task->nlm_k_2);
  1349. kernel_set_args(
  1350. ckNLMBlur, 0, difference_mem, blurDifference_mem, w, h, stride, pass_stride, r, 4);
  1351. kernel_set_args(
  1352. ckNLMCalcWeight, 0, blurDifference_mem, difference_mem, w, h, stride, pass_stride, r, 4);
  1353. kernel_set_args(ckNLMConstructGramian,
  1354. 0,
  1355. t,
  1356. blurDifference_mem,
  1357. buffer_mem,
  1358. transform_mem,
  1359. rank_mem,
  1360. XtWX_mem,
  1361. XtWY_mem,
  1362. task->reconstruction_state.filter_window,
  1363. w,
  1364. h,
  1365. stride,
  1366. pass_stride,
  1367. r,
  1368. 4,
  1369. frame_offset,
  1370. use_time);
  1371. enqueue_kernel(ckNLMCalcDifference, w * h, num_shifts, true);
  1372. enqueue_kernel(ckNLMBlur, w * h, num_shifts, true);
  1373. enqueue_kernel(ckNLMCalcWeight, w * h, num_shifts, true);
  1374. enqueue_kernel(ckNLMBlur, w * h, num_shifts, true);
  1375. enqueue_kernel(ckNLMConstructGramian, w * h, num_shifts, true, 256);
  1376. return true;
  1377. }
  1378. bool OpenCLDevice::denoising_solve(device_ptr output_ptr, DenoisingTask *task)
  1379. {
  1380. cl_kernel ckFinalize = denoising_program(ustring("filter_finalize"));
  1381. cl_mem output_mem = CL_MEM_PTR(output_ptr);
  1382. cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
  1383. cl_mem XtWX_mem = CL_MEM_PTR(task->storage.XtWX.device_pointer);
  1384. cl_mem XtWY_mem = CL_MEM_PTR(task->storage.XtWY.device_pointer);
  1385. int w = task->reconstruction_state.source_w;
  1386. int h = task->reconstruction_state.source_h;
  1387. kernel_set_args(ckFinalize,
  1388. 0,
  1389. output_mem,
  1390. rank_mem,
  1391. XtWX_mem,
  1392. XtWY_mem,
  1393. task->filter_area,
  1394. task->reconstruction_state.buffer_params,
  1395. task->render_buffer.samples);
  1396. enqueue_kernel(ckFinalize, w, h);
  1397. return true;
  1398. }
  1399. bool OpenCLDevice::denoising_combine_halves(device_ptr a_ptr,
  1400. device_ptr b_ptr,
  1401. device_ptr mean_ptr,
  1402. device_ptr variance_ptr,
  1403. int r,
  1404. int4 rect,
  1405. DenoisingTask *task)
  1406. {
  1407. cl_mem a_mem = CL_MEM_PTR(a_ptr);
  1408. cl_mem b_mem = CL_MEM_PTR(b_ptr);
  1409. cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
  1410. cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
  1411. cl_kernel ckFilterCombineHalves = denoising_program(ustring("filter_combine_halves"));
  1412. kernel_set_args(ckFilterCombineHalves, 0, mean_mem, variance_mem, a_mem, b_mem, rect, r);
  1413. enqueue_kernel(ckFilterCombineHalves, task->rect.z - task->rect.x, task->rect.w - task->rect.y);
  1414. return true;
  1415. }
  1416. bool OpenCLDevice::denoising_divide_shadow(device_ptr a_ptr,
  1417. device_ptr b_ptr,
  1418. device_ptr sample_variance_ptr,
  1419. device_ptr sv_variance_ptr,
  1420. device_ptr buffer_variance_ptr,
  1421. DenoisingTask *task)
  1422. {
  1423. cl_mem a_mem = CL_MEM_PTR(a_ptr);
  1424. cl_mem b_mem = CL_MEM_PTR(b_ptr);
  1425. cl_mem sample_variance_mem = CL_MEM_PTR(sample_variance_ptr);
  1426. cl_mem sv_variance_mem = CL_MEM_PTR(sv_variance_ptr);
  1427. cl_mem buffer_variance_mem = CL_MEM_PTR(buffer_variance_ptr);
  1428. cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
  1429. cl_kernel ckFilterDivideShadow = denoising_program(ustring("filter_divide_shadow"));
  1430. int arg_ofs = kernel_set_args(
  1431. ckFilterDivideShadow, 0, task->render_buffer.samples, tile_info_mem);
  1432. cl_mem buffers[9];
  1433. for (int i = 0; i < 9; i++) {
  1434. buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
  1435. arg_ofs += kernel_set_args(ckFilterDivideShadow, arg_ofs, buffers[i]);
  1436. }
  1437. kernel_set_args(ckFilterDivideShadow,
  1438. arg_ofs,
  1439. a_mem,
  1440. b_mem,
  1441. sample_variance_mem,
  1442. sv_variance_mem,
  1443. buffer_variance_mem,
  1444. task->rect,
  1445. task->render_buffer.pass_stride,
  1446. task->render_buffer.offset);
  1447. enqueue_kernel(ckFilterDivideShadow, task->rect.z - task->rect.x, task->rect.w - task->rect.y);
  1448. return true;
  1449. }
  1450. bool OpenCLDevice::denoising_get_feature(int mean_offset,
  1451. int variance_offset,
  1452. device_ptr mean_ptr,
  1453. device_ptr variance_ptr,
  1454. float scale,
  1455. DenoisingTask *task)
  1456. {
  1457. cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
  1458. cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
  1459. cl_mem tile_info_mem = CL_MEM_PTR(task->tile_info_mem.device_pointer);
  1460. cl_kernel ckFilterGetFeature = denoising_program(ustring("filter_get_feature"));
  1461. int arg_ofs = kernel_set_args(ckFilterGetFeature, 0, task->render_buffer.samples, tile_info_mem);
  1462. cl_mem buffers[9];
  1463. for (int i = 0; i < 9; i++) {
  1464. buffers[i] = CL_MEM_PTR(task->tile_info->buffers[i]);
  1465. arg_ofs += kernel_set_args(ckFilterGetFeature, arg_ofs, buffers[i]);
  1466. }
  1467. kernel_set_args(ckFilterGetFeature,
  1468. arg_ofs,
  1469. mean_offset,
  1470. variance_offset,
  1471. mean_mem,
  1472. variance_mem,
  1473. scale,
  1474. task->rect,
  1475. task->render_buffer.pass_stride,
  1476. task->render_buffer.offset);
  1477. enqueue_kernel(ckFilterGetFeature, task->rect.z - task->rect.x, task->rect.w - task->rect.y);
  1478. return true;
  1479. }
  1480. bool OpenCLDevice::denoising_write_feature(int out_offset,
  1481. device_ptr from_ptr,
  1482. device_ptr buffer_ptr,
  1483. DenoisingTask *task)
  1484. {
  1485. cl_mem from_mem = CL_MEM_PTR(from_ptr);
  1486. cl_mem buffer_mem = CL_MEM_PTR(buffer_ptr);
  1487. cl_kernel ckFilterWriteFeature = denoising_program(ustring("filter_write_feature"));
  1488. kernel_set_args(ckFilterWriteFeature,
  1489. 0,
  1490. task->render_buffer.samples,
  1491. task->reconstruction_state.buffer_params,
  1492. task->filter_area,
  1493. from_mem,
  1494. buffer_mem,
  1495. out_offset,
  1496. task->rect);
  1497. enqueue_kernel(ckFilterWriteFeature, task->filter_area.z, task->filter_area.w);
  1498. return true;
  1499. }
  1500. bool OpenCLDevice::denoising_detect_outliers(device_ptr image_ptr,
  1501. device_ptr variance_ptr,
  1502. device_ptr depth_ptr,
  1503. device_ptr output_ptr,
  1504. DenoisingTask *task)
  1505. {
  1506. cl_mem image_mem = CL_MEM_PTR(image_ptr);
  1507. cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
  1508. cl_mem depth_mem = CL_MEM_PTR(depth_ptr);
  1509. cl_mem output_mem = CL_MEM_PTR(output_ptr);
  1510. cl_kernel ckFilterDetectOutliers = denoising_program(ustring("filter_detect_outliers"));
  1511. kernel_set_args(ckFilterDetectOutliers,
  1512. 0,
  1513. image_mem,
  1514. variance_mem,
  1515. depth_mem,
  1516. output_mem,
  1517. task->rect,
  1518. task->buffer.pass_stride);
  1519. enqueue_kernel(ckFilterDetectOutliers, task->rect.z - task->rect.x, task->rect.w - task->rect.y);
  1520. return true;
  1521. }
  1522. void OpenCLDevice::denoise(RenderTile &rtile, DenoisingTask &denoising)
  1523. {
  1524. denoising.functions.construct_transform = function_bind(
  1525. &OpenCLDevice::denoising_construct_transform, this, &denoising);
  1526. denoising.functions.accumulate = function_bind(
  1527. &OpenCLDevice::denoising_accumulate, this, _1, _2, _3, _4, &denoising);
  1528. denoising.functions.solve = function_bind(&OpenCLDevice::denoising_solve, this, _1, &denoising);
  1529. denoising.functions.divide_shadow = function_bind(
  1530. &OpenCLDevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
  1531. denoising.functions.non_local_means = function_bind(
  1532. &OpenCLDevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
  1533. denoising.functions.combine_halves = function_bind(
  1534. &OpenCLDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
  1535. denoising.functions.get_feature = function_bind(
  1536. &OpenCLDevice::denoising_get_feature, this, _1, _2, _3, _4, _5, &denoising);
  1537. denoising.functions.write_feature = function_bind(
  1538. &OpenCLDevice::denoising_write_feature, this, _1, _2, _3, &denoising);
  1539. denoising.functions.detect_outliers = function_bind(
  1540. &OpenCLDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
  1541. denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h);
  1542. denoising.render_buffer.samples = rtile.sample;
  1543. denoising.buffer.gpu_temporary_mem = true;
  1544. denoising.run_denoising(&rtile);
  1545. }
  1546. void OpenCLDevice::shader(DeviceTask &task)
  1547. {
  1548. /* cast arguments to cl types */
  1549. cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
  1550. cl_mem d_input = CL_MEM_PTR(task.shader_input);
  1551. cl_mem d_output = CL_MEM_PTR(task.shader_output);
  1552. cl_int d_shader_eval_type = task.shader_eval_type;
  1553. cl_int d_shader_filter = task.shader_filter;
  1554. cl_int d_shader_x = task.shader_x;
  1555. cl_int d_shader_w = task.shader_w;
  1556. cl_int d_offset = task.offset;
  1557. OpenCLDevice::OpenCLProgram *program = &background_program;
  1558. if (task.shader_eval_type >= SHADER_EVAL_BAKE) {
  1559. program = &bake_program;
  1560. }
  1561. else if (task.shader_eval_type == SHADER_EVAL_DISPLACE) {
  1562. program = &displace_program;
  1563. }
  1564. program->wait_for_availability();
  1565. cl_kernel kernel = (*program)();
  1566. cl_uint start_arg_index = kernel_set_args(kernel, 0, d_data, d_input, d_output);
  1567. set_kernel_arg_buffers(kernel, &start_arg_index);
  1568. start_arg_index += kernel_set_args(kernel, start_arg_index, d_shader_eval_type);
  1569. if (task.shader_eval_type >= SHADER_EVAL_BAKE) {
  1570. start_arg_index += kernel_set_args(kernel, start_arg_index, d_shader_filter);
  1571. }
  1572. start_arg_index += kernel_set_args(kernel, start_arg_index, d_shader_x, d_shader_w, d_offset);
  1573. for (int sample = 0; sample < task.num_samples; sample++) {
  1574. if (task.get_cancel())
  1575. break;
  1576. kernel_set_args(kernel, start_arg_index, sample);
  1577. enqueue_kernel(kernel, task.shader_w, 1);
  1578. clFinish(cqCommandQueue);
  1579. task.update_progress(NULL);
  1580. }
  1581. }
  1582. string OpenCLDevice::kernel_build_options(const string *debug_src)
  1583. {
  1584. string build_options = "-cl-no-signed-zeros -cl-mad-enable ";
  1585. if (platform_name == "NVIDIA CUDA") {
  1586. build_options +=
  1587. "-D__KERNEL_OPENCL_NVIDIA__ "
  1588. "-cl-nv-maxrregcount=32 "
  1589. "-cl-nv-verbose ";
  1590. uint compute_capability_major, compute_capability_minor;
  1591. clGetDeviceInfo(cdDevice,
  1592. CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV,
  1593. sizeof(cl_uint),
  1594. &compute_capability_major,
  1595. NULL);
  1596. clGetDeviceInfo(cdDevice,
  1597. CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV,
  1598. sizeof(cl_uint),
  1599. &compute_capability_minor,
  1600. NULL);
  1601. build_options += string_printf("-D__COMPUTE_CAPABILITY__=%u ",
  1602. compute_capability_major * 100 + compute_capability_minor * 10);
  1603. }
  1604. else if (platform_name == "Apple")
  1605. build_options += "-D__KERNEL_OPENCL_APPLE__ ";
  1606. else if (platform_name == "AMD Accelerated Parallel Processing")
  1607. build_options += "-D__KERNEL_OPENCL_AMD__ ";
  1608. else if (platform_name == "Intel(R) OpenCL") {
  1609. build_options += "-D__KERNEL_OPENCL_INTEL_CPU__ ";
  1610. /* Options for gdb source level kernel debugging.
  1611. * this segfaults on linux currently.
  1612. */
  1613. if (OpenCLInfo::use_debug() && debug_src)
  1614. build_options += "-g -s \"" + *debug_src + "\" ";
  1615. }
  1616. if (info.has_half_images) {
  1617. build_options += "-D__KERNEL_CL_KHR_FP16__ ";
  1618. }
  1619. if (OpenCLInfo::use_debug()) {
  1620. build_options += "-D__KERNEL_OPENCL_DEBUG__ ";
  1621. }
  1622. # ifdef WITH_CYCLES_DEBUG
  1623. build_options += "-D__KERNEL_DEBUG__ ";
  1624. # endif
  1625. return build_options;
  1626. }
  1627. /* TODO(sergey): In the future we can use variadic templates, once
  1628. * C++0x is allowed. Should allow to clean this up a bit.
  1629. */
  1630. int OpenCLDevice::kernel_set_args(cl_kernel kernel,
  1631. int start_argument_index,
  1632. const ArgumentWrapper &arg1,
  1633. const ArgumentWrapper &arg2,
  1634. const ArgumentWrapper &arg3,
  1635. const ArgumentWrapper &arg4,
  1636. const ArgumentWrapper &arg5,
  1637. const ArgumentWrapper &arg6,
  1638. const ArgumentWrapper &arg7,
  1639. const ArgumentWrapper &arg8,
  1640. const ArgumentWrapper &arg9,
  1641. const ArgumentWrapper &arg10,
  1642. const ArgumentWrapper &arg11,
  1643. const ArgumentWrapper &arg12,
  1644. const ArgumentWrapper &arg13,
  1645. const ArgumentWrapper &arg14,
  1646. const ArgumentWrapper &arg15,
  1647. const ArgumentWrapper &arg16,
  1648. const ArgumentWrapper &arg17,
  1649. const ArgumentWrapper &arg18,
  1650. const ArgumentWrapper &arg19,
  1651. const ArgumentWrapper &arg20,
  1652. const ArgumentWrapper &arg21,
  1653. const ArgumentWrapper &arg22,
  1654. const ArgumentWrapper &arg23,
  1655. const ArgumentWrapper &arg24,
  1656. const ArgumentWrapper &arg25,
  1657. const ArgumentWrapper &arg26,
  1658. const ArgumentWrapper &arg27,
  1659. const ArgumentWrapper &arg28,
  1660. const ArgumentWrapper &arg29,
  1661. const ArgumentWrapper &arg30,
  1662. const ArgumentWrapper &arg31,
  1663. const ArgumentWrapper &arg32,
  1664. const ArgumentWrapper &arg33)
  1665. {
  1666. int current_arg_index = 0;
  1667. # define FAKE_VARARG_HANDLE_ARG(arg) \
  1668. do { \
  1669. if (arg.pointer != NULL) { \
  1670. opencl_assert(clSetKernelArg( \
  1671. kernel, start_argument_index + current_arg_index, arg.size, arg.pointer)); \
  1672. ++current_arg_index; \
  1673. } \
  1674. else { \
  1675. return current_arg_index; \
  1676. } \
  1677. } while (false)
  1678. FAKE_VARARG_HANDLE_ARG(arg1);
  1679. FAKE_VARARG_HANDLE_ARG(arg2);
  1680. FAKE_VARARG_HANDLE_ARG(arg3);
  1681. FAKE_VARARG_HANDLE_ARG(arg4);
  1682. FAKE_VARARG_HANDLE_ARG(arg5);
  1683. FAKE_VARARG_HANDLE_ARG(arg6);
  1684. FAKE_VARARG_HANDLE_ARG(arg7);
  1685. FAKE_VARARG_HANDLE_ARG(arg8);
  1686. FAKE_VARARG_HANDLE_ARG(arg9);
  1687. FAKE_VARARG_HANDLE_ARG(arg10);
  1688. FAKE_VARARG_HANDLE_ARG(arg11);
  1689. FAKE_VARARG_HANDLE_ARG(arg12);
  1690. FAKE_VARARG_HANDLE_ARG(arg13);
  1691. FAKE_VARARG_HANDLE_ARG(arg14);
  1692. FAKE_VARARG_HANDLE_ARG(arg15);
  1693. FAKE_VARARG_HANDLE_ARG(arg16);
  1694. FAKE_VARARG_HANDLE_ARG(arg17);
  1695. FAKE_VARARG_HANDLE_ARG(arg18);
  1696. FAKE_VARARG_HANDLE_ARG(arg19);
  1697. FAKE_VARARG_HANDLE_ARG(arg20);
  1698. FAKE_VARARG_HANDLE_ARG(arg21);
  1699. FAKE_VARARG_HANDLE_ARG(arg22);
  1700. FAKE_VARARG_HANDLE_ARG(arg23);
  1701. FAKE_VARARG_HANDLE_ARG(arg24);
  1702. FAKE_VARARG_HANDLE_ARG(arg25);
  1703. FAKE_VARARG_HANDLE_ARG(arg26);
  1704. FAKE_VARARG_HANDLE_ARG(arg27);
  1705. FAKE_VARARG_HANDLE_ARG(arg28);
  1706. FAKE_VARARG_HANDLE_ARG(arg29);
  1707. FAKE_VARARG_HANDLE_ARG(arg30);
  1708. FAKE_VARARG_HANDLE_ARG(arg31);
  1709. FAKE_VARARG_HANDLE_ARG(arg32);
  1710. FAKE_VARARG_HANDLE_ARG(arg33);
  1711. # undef FAKE_VARARG_HANDLE_ARG
  1712. return current_arg_index;
  1713. }
  1714. void OpenCLDevice::release_kernel_safe(cl_kernel kernel)
  1715. {
  1716. if (kernel) {
  1717. clReleaseKernel(kernel);
  1718. }
  1719. }
  1720. void OpenCLDevice::release_mem_object_safe(cl_mem mem)
  1721. {
  1722. if (mem != NULL) {
  1723. clReleaseMemObject(mem);
  1724. }
  1725. }
  1726. void OpenCLDevice::release_program_safe(cl_program program)
  1727. {
  1728. if (program) {
  1729. clReleaseProgram(program);
  1730. }
  1731. }
  1732. /* ** Those guys are for workign around some compiler-specific bugs ** */
  1733. cl_program OpenCLDevice::load_cached_kernel(ustring key, thread_scoped_lock &cache_locker)
  1734. {
  1735. return OpenCLCache::get_program(cpPlatform, cdDevice, key, cache_locker);
  1736. }
  1737. void OpenCLDevice::store_cached_kernel(cl_program program,
  1738. ustring key,
  1739. thread_scoped_lock &cache_locker)
  1740. {
  1741. OpenCLCache::store_program(cpPlatform, cdDevice, program, key, cache_locker);
  1742. }
  1743. Device *opencl_create_split_device(DeviceInfo &info,
  1744. Stats &stats,
  1745. Profiler &profiler,
  1746. bool background)
  1747. {
  1748. return new OpenCLDevice(info, stats, profiler, background);
  1749. }
  1750. CCL_NAMESPACE_END
  1751. #endif