3D engine that AI agents drive
Add Cook M1 Cycles integrator, camera, filter, sampler, and lights (#894)
Nguyen Xuan An0f9f465b16ef
diff --git a/packages/render-native/src/cycles/camera.wgsl b/packages/render-native/src/cycles/camera.wgslnew file mode 100644index 00000000..56fdfcac--- /dev/null+++ b/packages/render-native/src/cycles/camera.wgsl@@ -0,0 +1,118 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Perspective, orthographic, and thin-lens primary camera ray generation (`cam_*`),+// ported from Cycles `kernel/camera/camera.h` and `kernel/sample/mapping.h`.++struct CamRay {+ origin: vec3<f32>,+ direction: vec3<f32>,+ t_min: f32,+ t_max: f32,+}++fn cam_sample_uniform_disk(rand_uv: vec2<f32>) -> vec2<f32> {+ let offset = 2.0 * rand_uv - vec2<f32>(1.0, 1.0);+ if (offset.x == 0.0 && offset.y == 0.0) {+ return vec2<f32>(0.0, 0.0);+ }+ var radius = 0.0;+ var phi = 0.0;+ if (abs(offset.x) > abs(offset.y)) {+ radius = offset.x;+ phi = (0.25 * PI) * (offset.y / offset.x);+ } else {+ radius = offset.y;+ phi = (0.5 * PI) - (0.25 * PI) * (offset.x / offset.y);+ }+ return vec2<f32>(radius * cos(phi), radius * sin(phi));+}++fn cam_sample_regular_polygon(blades: u32, rotation: f32, rand_uv: vec2<f32>) -> vec2<f32> {+ let corners = f32(blades);+ let corner_index = floor(rand_uv.x * corners);+ let u_remapped = rand_uv.x * corners - corner_index;+ let su = sqrt(u_remapped);+ let weight_a = 1.0 - su;+ let weight_b = rand_uv.y * su;+ let step_angle = TWO_PI / corners;+ let angle_0 = rotation + corner_index * step_angle;+ let angle_1 = angle_0 + step_angle;+ let vertex_0 = vec2<f32>(cos(angle_0), sin(angle_0));+ let vertex_1 = vec2<f32>(cos(angle_1), sin(angle_1));+ return weight_a * vertex_0 + weight_b * vertex_1;+}++fn cam_sample_aperture(rand_uv: vec2<f32>) -> vec2<f32> {+ if (kernel_params.aperture_blades >= 3u) {+ return cam_sample_regular_polygon(kernel_params.aperture_blades, kernel_params.aperture_rotation, rand_uv);+ }+ return cam_sample_uniform_disk(rand_uv);+}++fn cam_safe_unit_axis(axis: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {+ let len = length(axis);+ if (len > 1e-12) {+ return axis / len;+ }+ return fallback;+}++fn cam_generate_ray(pixel_x: u32, pixel_y: u32, filter_offset: vec2<f32>, lens_uv: vec2<f32>) -> CamRay {+ let raster_x = f32(pixel_x) + 0.5 + filter_offset.x;+ let raster_y = f32(pixel_y) + 0.5 + filter_offset.y;+ let inv_width = 1.0 / f32(max(kernel_params.image_width, 1u));+ let inv_height = 1.0 / f32(max(kernel_params.image_height, 1u));+ let sensor_x = raster_x * inv_width * 2.0 - 1.0 + 2.0 * kernel_params.lens_shift.x;+ let sensor_y = 1.0 - raster_y * inv_height * 2.0 + 2.0 * kernel_params.lens_shift.y;++ let forward = cam_safe_unit_axis(kernel_params.camera_forward, vec3<f32>(0.0, 0.0, -1.0));+ let unit_right = cam_safe_unit_axis(kernel_params.camera_right, vec3<f32>(1.0, 0.0, 0.0));+ let unit_up = cam_safe_unit_axis(kernel_params.camera_up, vec3<f32>(0.0, 1.0, 0.0));++ let is_ortho = (kernel_params.kernel_flags & KERNEL_FLAG_ORTHOGRAPHIC_CAMERA) != 0u;+ let far_plane = select(1.0e30, kernel_params.camera_far, kernel_params.camera_far > kernel_params.camera_near);+ let near_plane = max(kernel_params.camera_near, 0.0);++ var ray: CamRay;+ if (is_ortho) {+ var origin = kernel_params.camera_position+ + kernel_params.camera_right * sensor_x+ + kernel_params.camera_up * sensor_y;+ var direction = forward;+ if (kernel_params.aperture_radius > 0.0 && kernel_params.focal_distance > 0.0) {+ let bokeh = cam_sample_aperture(lens_uv) * kernel_params.aperture_radius;+ let lens_offset = unit_right * bokeh.x + unit_up * bokeh.y;+ origin += lens_offset;+ direction = normalize(forward * kernel_params.focal_distance - lens_offset);+ }+ let cos_forward = max(dot(direction, forward), 1e-6);+ ray.origin = origin;+ ray.direction = direction;+ ray.t_min = near_plane / cos_forward;+ ray.t_max = select(1.0e30, far_plane / cos_forward, far_plane < 1.0e29);+ return ray;+ }++ let unnormalized_dir = forward+ + kernel_params.camera_right * sensor_x+ + kernel_params.camera_up * sensor_y;+ let center_dir = normalize(unnormalized_dir);+ var origin = kernel_params.camera_position;+ var direction = center_dir;++ if (kernel_params.aperture_radius > 0.0 && kernel_params.focal_distance > 0.0) {+ let bokeh = cam_sample_aperture(lens_uv) * kernel_params.aperture_radius;+ let lens_offset = unit_right * bokeh.x + unit_up * bokeh.y;+ let focus_offset = unnormalized_dir * kernel_params.focal_distance;+ origin += lens_offset;+ direction = normalize(focus_offset - lens_offset);+ }++ let cos_forward = max(dot(center_dir, forward), 1e-6);+ ray.origin = origin;+ ray.direction = direction;+ ray.t_min = near_plane / cos_forward;+ ray.t_max = select(1.0e30, far_plane / cos_forward, far_plane < 1.0e29);+ return ray;+}diff --git a/packages/render-native/src/cycles/filter.wgsl b/packages/render-native/src/cycles/filter.wgslnew file mode 100644index 00000000..17001ab8--- /dev/null+++ b/packages/render-native/src/cycles/filter.wgsl@@ -0,0 +1,72 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Pixel reconstruction filter importance sampling (`flt_*`), ported from Cycles `scene/film.cpp`.++const FLT_LUT_LAST_INDEX: u32 = 64u;++const FLT_GAUSSIAN_INV_CDF = array<f32, 65>(+ 0.0000000, 0.0048961, 0.0097940, 0.0146957, 0.0196031,+ 0.0245180, 0.0294425, 0.0343784, 0.0393277, 0.0442925,+ 0.0492748, 0.0542767, 0.0593005, 0.0643484, 0.0694226,+ 0.0745256, 0.0796598, 0.0848279, 0.0900325, 0.0952764,+ 0.1005625, 0.1058940, 0.1112741, 0.1167063, 0.1221941,+ 0.1277415, 0.1333524, 0.1390314, 0.1447830, 0.1506124,+ 0.1565248, 0.1625260, 0.1686224, 0.1748208, 0.1811286,+ 0.1875538, 0.1941054, 0.2007931, 0.2076277, 0.2146211,+ 0.2217866, 0.2291392, 0.2366954, 0.2444744, 0.2524975,+ 0.2607896, 0.2693789, 0.2782986, 0.2875873, 0.2972911,+ 0.3074647, 0.3181747, 0.3295027, 0.3415510, 0.3544493,+ 0.3683669, 0.3835301, 0.4002522, 0.4189849, 0.4404176,+ 0.4656830, 0.4968570, 0.5384687, 0.6043897, 1.5000000,+);++const FLT_BLACKMAN_HARRIS_INV_CDF = array<f32, 65>(+ 0.0000000, 0.0056058, 0.0112136, 0.0168255, 0.0224434,+ 0.0280694, 0.0337057, 0.0393542, 0.0450171, 0.0506965,+ 0.0563948, 0.0621141, 0.0678568, 0.0736252, 0.0794219,+ 0.0852493, 0.0911102, 0.0970072, 0.1029432, 0.1089211,+ 0.1149442, 0.1210157, 0.1271389, 0.1333176, 0.1395556,+ 0.1458569, 0.1522258, 0.1586668, 0.1651850, 0.1717856,+ 0.1784741, 0.1852566, 0.1921397, 0.1991303, 0.2062363,+ 0.2134660, 0.2208285, 0.2283338, 0.2359932, 0.2438187,+ 0.2518240, 0.2600243, 0.2684367, 0.2770803, 0.2859770,+ 0.2951516, 0.3046328, 0.3144536, 0.3246529, 0.3352763,+ 0.3463782, 0.3580243, 0.3702950, 0.3832900, 0.3971356,+ 0.4119955, 0.4280867, 0.4457076, 0.4652846, 0.4874611,+ 0.5132813, 0.5446273, 0.5855150, 0.6478121, 1.0000000,+);++fn flt_lookup_gaussian_1d(unit_value: f32) -> f32 {+ let sign_scale = select(1.0, -1.0, unit_value < 0.5);+ let folded = clamp(abs(2.0 * unit_value - 1.0), 0.0, 1.0);+ let scaled = folded * f32(FLT_LUT_LAST_INDEX);+ let index_lo = min(u32(floor(scaled)), FLT_LUT_LAST_INDEX - 1u);+ let fraction = scaled - f32(index_lo);+ let magnitude = mix(FLT_GAUSSIAN_INV_CDF[index_lo], FLT_GAUSSIAN_INV_CDF[index_lo + 1u], fraction);+ return sign_scale * magnitude;+}++fn flt_lookup_blackman_harris_1d(unit_value: f32) -> f32 {+ let sign_scale = select(1.0, -1.0, unit_value < 0.5);+ let folded = clamp(abs(2.0 * unit_value - 1.0), 0.0, 1.0);+ let scaled = folded * f32(FLT_LUT_LAST_INDEX);+ let index_lo = min(u32(floor(scaled)), FLT_LUT_LAST_INDEX - 1u);+ let fraction = scaled - f32(index_lo);+ let magnitude = mix(FLT_BLACKMAN_HARRIS_INV_CDF[index_lo], FLT_BLACKMAN_HARRIS_INV_CDF[index_lo + 1u], fraction);+ return sign_scale * magnitude;+}++fn flt_sample_offset(unit_uv: vec2<f32>) -> vec2<f32> {+ let width = max(kernel_params.filter_width, 0.0);+ if (width == 0.0) {+ return vec2<f32>(0.0, 0.0);+ }+ if (kernel_params.filter_type == FILTER_GAUSSIAN) {+ return vec2<f32>(flt_lookup_gaussian_1d(unit_uv.x), flt_lookup_gaussian_1d(unit_uv.y)) * width;+ }+ if (kernel_params.filter_type == FILTER_BLACKMAN_HARRIS) {+ return vec2<f32>(flt_lookup_blackman_harris_1d(unit_uv.x), flt_lookup_blackman_harris_1d(unit_uv.y)) * width;+ }+ return (unit_uv - vec2<f32>(0.5, 0.5)) * width;+}diff --git a/packages/render-native/src/cycles/integrator.wgsl b/packages/render-native/src/cycles/integrator.wgslnew file mode 100644index 00000000..fd3c4a3e--- /dev/null+++ b/packages/render-native/src/cycles/integrator.wgsl@@ -0,0 +1,1034 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Unidirectional MIS path integrator (`int_*` + `@compute fn main`), ported from Cycles+// `kernel/integrator/{shade_surface.h,shade_light.h,shade_background.h,intersect_closest.h,intersect_shadow.h}`.++const INT_MAX_PATH_STEPS: u32 = 128u;+const INT_ADAPTIVE_BATCH_SIZE: u32 = 8u;+const INT_ADAPTIVE_LUMINANCE_FLOOR: f32 = 1.0e-3;++struct IntSurfaceHit {+ hit: u32,+ t: f32,+ instance_index: u32,+ triangle_index: u32,+ barycentrics: vec2<f32>,+}++fn int_luminance(rgb: vec3<f32>) -> f32 {+ return 0.2126729 * rgb.x + 0.7151522 * rgb.y + 0.0721750 * rgb.z;+}++fn int_sanitize_radiance(value: vec3<f32>) -> vec3<f32> {+ let valid_x = value.x >= 0.0 && value.x < 1.0e30;+ let valid_y = value.y >= 0.0 && value.y < 1.0e30;+ let valid_z = value.z >= 0.0 && value.z < 1.0e30;+ return vec3<f32>(+ select(0.0, value.x, valid_x),+ select(0.0, value.y, valid_y),+ select(0.0, value.z, valid_z),+ );+}++fn int_clamp_contribution(raw_value: vec3<f32>, clamp_bounce: i32) -> vec3<f32> {+ var value = int_sanitize_radiance(raw_value);+ let ceiling = select(kernel_params.clamp_direct, kernel_params.clamp_indirect, clamp_bounce > 0);+ if (ceiling > 0.0 && ceiling < 1.0e29) {+ let channel_sum = value.x + value.y + value.z;+ if (channel_sum > ceiling) {+ value *= ceiling / channel_sum;+ }+ }+ return value;+}++fn int_pixel_has_converged(statistics: vec4<f32>) -> bool {+ if ((kernel_params.kernel_flags & KERNEL_FLAG_ADAPTIVE_SAMPLING) == 0u || kernel_params.adaptive_threshold <= 0.0) {+ return false;+ }+ if (statistics.z >= 0.5) {+ return true;+ }+ let min_samples = max(kernel_params.adaptive_min_samples, 16u);+ let taken = u32(statistics.w);+ if (taken < min_samples || (taken - min_samples) % INT_ADAPTIVE_BATCH_SIZE != 0u) {+ return false;+ }+ let count = f32(taken);+ let mean = statistics.x / count;+ let variance = max(0.0, statistics.y / count - mean * mean) * count / max(count - 1.0, 1.0);+ return sqrt(variance / count) < kernel_params.adaptive_threshold * (mean + INT_ADAPTIVE_LUMINANCE_FLOOR);+}++fn int_resolve_instance_index(custom_data: u32, _instance_slot: u32) -> u32 {+ return min(custom_data, max(kernel_params.instance_count, 1u) - 1u);+}++fn int_resolve_triangle_index(instance: InstanceRecord, geometry_index: u32, primitive_index: u32) -> u32 {+ let cutout_offset = select(0u, instance.opaque_triangle_count, geometry_index > 0u);+ return instance.triangle_offset + cutout_offset + primitive_index;+}++fn int_resolve_material_index(instance: InstanceRecord, triangle: TriangleRecord) -> u32 {+ return select(instance.material_override, triangle.material_index, instance.material_override == INVALID_INDEX);+}++fn int_wrap_coord(coord: i32, extent: i32, wrap_mode: u32) -> u32 {+ if (wrap_mode == 1u) {+ return u32(clamp(coord, 0, extent - 1));+ }+ if (wrap_mode == 2u) {+ let period = 2 * extent;+ let wrapped = ((coord % period) + period) % period;+ let mirrored = select(wrapped, period - 1 - wrapped, wrapped >= extent);+ return u32(clamp(mirrored, 0, extent - 1));+ }+ return u32(((coord % extent) + extent) % extent);+}++fn int_fetch_texel_channel(descriptor: TextureDescriptor, x: u32, y: u32, channel: u32) -> f32 {+ let format = descriptor.format_and_sampler & 0xFFu;+ let texel_index = y * descriptor.width + x;+ if (format == 0u || format == 1u) {+ let rgba = unpack4x8unorm(texture_texels[descriptor.data_offset + texel_index]);+ return select(rgba.w, rgba.x, channel == 0u);+ }+ if (format == 2u) {+ let chan_offset = select(3u, 0u, channel == 0u);+ return bitcast<f32>(texture_texels[descriptor.data_offset + texel_index * 4u + chan_offset]);+ }+ if (format == 3u && channel == 0u) {+ return unpack2x16float(texture_texels[descriptor.data_offset + texel_index]).x;+ }+ return 1.0;+}++fn int_sample_texture_channel(texture_index: i32, uv0: vec2<f32>, uv1: vec2<f32>, channel: u32) -> f32 {+ if (texture_index < 0 || u32(texture_index) >= kernel_params.texture_count) {+ return 1.0;+ }+ let descriptor = texture_descriptors[u32(texture_index)];+ if (descriptor.width == 0u || descriptor.height == 0u) {+ return 1.0;+ }+ let use_uv1 = (descriptor.format_and_sampler & (1u << 21u)) != 0u;+ let base_uv = select(uv0, uv1, use_uv1);+ let transformed_uv = base_uv * descriptor.uv_scale + descriptor.uv_offset;+ let wrap_u = (descriptor.format_and_sampler >> 16u) & 3u;+ let wrap_v = (descriptor.format_and_sampler >> 18u) & 3u;+ let nearest = (descriptor.format_and_sampler & (1u << 20u)) != 0u;+ let width_i = i32(descriptor.width);+ let height_i = i32(descriptor.height);++ if (nearest) {+ let col = int_wrap_coord(i32(floor(transformed_uv.x * f32(descriptor.width))), width_i, wrap_u);+ let row = int_wrap_coord(i32(floor(transformed_uv.y * f32(descriptor.height))), height_i, wrap_v);+ return int_fetch_texel_channel(descriptor, col, row, channel);+ }++ let px = transformed_uv.x * f32(descriptor.width) - 0.5;+ let py = transformed_uv.y * f32(descriptor.height) - 0.5;+ let x0 = floor(px);+ let y0 = floor(py);+ let fx = px - x0;+ let fy = py - y0;+ var value_sum = 0.0;+ for (var corner = 0u; corner < 4u; corner += 1u) {+ let dx = i32(corner & 1u);+ let dy = i32(corner >> 1u);+ let col = int_wrap_coord(i32(x0) + dx, width_i, wrap_u);+ let row = int_wrap_coord(i32(y0) + dy, height_i, wrap_v);+ let wx = select(1.0 - fx, fx, dx == 1);+ let wy = select(1.0 - fy, fy, dy == 1);+ value_sum += int_fetch_texel_channel(descriptor, col, row, channel) * (wx * wy);+ }+ return value_sum;+}++fn int_evaluate_surface_opacity(triangle: TriangleRecord, material: MaterialRecord, barycentrics: vec2<f32>) -> f32 {+ if (material.alpha_mode == ALPHA_MODE_OPAQUE) {+ return 1.0;+ }+ var opacity = clamp(material.alpha, 0.0, 1.0);+ if (material.base_color_tex < 0 && material.alpha_tex < 0) {+ return opacity;+ }+ let u = barycentrics.x;+ let v = barycentrics.y;+ let w = 1.0 - u - v;+ let uv0 = w * vec2<f32>(triangle.uv0_u, triangle.uv0_v)+ + u * vec2<f32>(triangle.uv1_u, triangle.uv1_v)+ + v * vec2<f32>(triangle.uv2_u, triangle.uv2_v);+ let uv1 = select(+ uv0,+ w * triangle.uv_set1_0 + u * triangle.uv_set1_1 + v * triangle.uv_set1_2,+ (triangle.flags & TRIANGLE_FLAG_HAS_UV1) != 0u,+ );+ if (material.base_color_tex >= 0) {+ opacity *= int_sample_texture_channel(material.base_color_tex, uv0, uv1, 3u);+ }+ if (material.alpha_tex >= 0) {+ opacity *= int_sample_texture_channel(material.alpha_tex, uv0, uv1, 0u);+ }+ return clamp(opacity, 0.0, 1.0);+}++fn int_trace_closest_surface(+ ray_origin: vec3<f32>,+ ray_dir: vec3<f32>,+ initial_t_min: f32,+ t_max: f32,+ visibility_mask: u32,+ self_instance: u32,+ self_triangle: u32,+) -> IntSurfaceHit {+ var result: IntSurfaceHit;+ result.hit = 0u;+ result.t = t_max;+ result.instance_index = INVALID_INDEX;+ result.triangle_index = INVALID_INDEX;+ result.barycentrics = vec2<f32>(0.0, 0.0);++ if (kernel_params.instance_count == 0u || kernel_params.triangle_count == 0u) {+ return result;+ }++ var current_t_min = initial_t_min;+ let step_eps = max(kernel_params.ray_epsilon, 1.0e-6);++ for (var pass_step = 0u; pass_step <= INT_MAX_PATH_STEPS; pass_step += 1u) {+ if (current_t_min >= t_max) {+ return result;+ }++ var query: ray_query;+ rayQueryInitialize(&query, scene_tlas, RayDesc(0u, visibility_mask & 0xFFu, current_t_min, t_max, ray_origin, ray_dir));+ while (rayQueryProceed(&query)) {+ let candidate = rayQueryGetCandidateIntersection(&query);+ let cand_inst_idx = int_resolve_instance_index(candidate.instance_custom_data, candidate.instance_index);+ let cand_inst = instances[cand_inst_idx];+ if ((cand_inst.visibility_flags & visibility_mask) == 0u) {+ continue;+ }+ let cand_tri_idx = int_resolve_triangle_index(cand_inst, candidate.geometry_index, candidate.primitive_index);+ if (cand_inst_idx == self_instance && cand_tri_idx == self_triangle && candidate.t < initial_t_min + 1.0e-3) {+ continue;+ }+ let cand_tri = triangles[cand_tri_idx];+ let cand_mat = materials[int_resolve_material_index(cand_inst, cand_tri)];+ if (cand_mat.alpha_mode == ALPHA_MODE_MASK) {+ let opacity = int_evaluate_surface_opacity(cand_tri, cand_mat, candidate.barycentrics);+ if (opacity < cand_mat.alpha_cutoff) {+ continue;+ }+ }+ rayQueryConfirmIntersection(&query);+ }++ let committed = rayQueryGetCommittedIntersection(&query);+ if (committed.kind == RAY_QUERY_INTERSECTION_NONE) {+ return result;+ }++ let hit_inst_idx = int_resolve_instance_index(committed.instance_custom_data, committed.instance_index);+ let hit_inst = instances[hit_inst_idx];+ let hit_tri_idx = int_resolve_triangle_index(hit_inst, committed.geometry_index, committed.primitive_index);++ if (hit_inst_idx == self_instance && hit_tri_idx == self_triangle && committed.t < initial_t_min + 1.0e-3) {+ current_t_min = committed.t + step_eps;+ continue;+ }+ if ((hit_inst.visibility_flags & visibility_mask) == 0u) {+ current_t_min = committed.t + step_eps;+ continue;+ }++ let hit_tri = triangles[hit_tri_idx];+ let hit_mat = materials[int_resolve_material_index(hit_inst, hit_tri)];+ if (hit_mat.alpha_mode == ALPHA_MODE_MASK) {+ let opacity = int_evaluate_surface_opacity(hit_tri, hit_mat, committed.barycentrics);+ if (opacity < hit_mat.alpha_cutoff) {+ current_t_min = committed.t + step_eps;+ continue;+ }+ }++ result.hit = 1u;+ result.t = committed.t;+ result.instance_index = hit_inst_idx;+ result.triangle_index = hit_tri_idx;+ result.barycentrics = committed.barycentrics;+ return result;+ }++ return result;+}++fn int_volume_segment_overlap(ray_origin: vec3<f32>, ray_dir: vec3<f32>, min_t: f32, max_t: f32) -> vec2<f32> {+ let inv_dir = vec3<f32>(+ select(1.0 / ray_dir.x, 1.0e30 * select(-1.0, 1.0, ray_dir.x >= 0.0), abs(ray_dir.x) < 1.0e-12),+ select(1.0 / ray_dir.y, 1.0e30 * select(-1.0, 1.0, ray_dir.y >= 0.0), abs(ray_dir.y) < 1.0e-12),+ select(1.0 / ray_dir.z, 1.0e30 * select(-1.0, 1.0, ray_dir.z >= 0.0), abs(ray_dir.z) < 1.0e-12),+ );+ let t0s = (kernel_params.volume_bounds_min - ray_origin) * inv_dir;+ let t1s = (kernel_params.volume_bounds_max - ray_origin) * inv_dir;+ let t_enter = max(min_t, max(min(t0s.x, t1s.x), max(min(t0s.y, t1s.y), min(t0s.z, t1s.z))));+ let t_exit = min(max_t, min(max(t0s.x, t1s.x), min(max(t0s.y, t1s.y), max(t0s.z, t1s.z))));+ return vec2<f32>(t_enter, t_exit);+}++fn int_trace_shadow(+ ray_origin: vec3<f32>,+ ray_dir: vec3<f32>,+ max_distance: f32,+ self_instance: u32,+ self_triangle: u32,+ target_instance: u32,+ target_triangle: u32,+) -> vec3<f32> {+ let step_eps = max(kernel_params.ray_epsilon, 1.0e-6);+ let shadow_t_max = select(1.0e30, max(max_distance - step_eps, 0.0), max_distance < 1.0e29);+ var transmittance = vec3<f32>(1.0);++ if (shadow_t_max > 0.0 && kernel_params.instance_count > 0u && kernel_params.triangle_count > 0u) {+ var current_t_min = 0.0;+ var transparent_hits = 0u;+ for (var step = 0u; step <= INT_MAX_PATH_STEPS; step += 1u) {+ if (current_t_min >= shadow_t_max) {+ break;+ }+ var query: ray_query;+ rayQueryInitialize(+ &query,+ scene_tlas,+ RayDesc(0u, INSTANCE_VISIBILITY_SHADOW, current_t_min, shadow_t_max, ray_origin, ray_dir),+ );+ while (rayQueryProceed(&query)) {+ let candidate = rayQueryGetCandidateIntersection(&query);+ let cand_inst_idx = int_resolve_instance_index(candidate.instance_custom_data, candidate.instance_index);+ let cand_inst = instances[cand_inst_idx];+ if ((cand_inst.visibility_flags & INSTANCE_VISIBILITY_SHADOW) == 0u) {+ continue;+ }+ let cand_tri_idx = int_resolve_triangle_index(cand_inst, candidate.geometry_index, candidate.primitive_index);+ if (cand_inst_idx == self_instance && cand_tri_idx == self_triangle && candidate.t < 1.0e-3) {+ continue;+ }+ if (cand_inst_idx == target_instance && cand_tri_idx == target_triangle) {+ continue;+ }+ let cand_tri = triangles[cand_tri_idx];+ let cand_mat = materials[int_resolve_material_index(cand_inst, cand_tri)];+ if (cand_mat.alpha_mode == ALPHA_MODE_MASK) {+ let opacity = int_evaluate_surface_opacity(cand_tri, cand_mat, candidate.barycentrics);+ if (opacity < cand_mat.alpha_cutoff) {+ continue;+ }+ }+ rayQueryConfirmIntersection(&query);+ }++ let committed = rayQueryGetCommittedIntersection(&query);+ if (committed.kind == RAY_QUERY_INTERSECTION_NONE) {+ break;+ }+ let hit_inst_idx = int_resolve_instance_index(committed.instance_custom_data, committed.instance_index);+ let hit_inst = instances[hit_inst_idx];+ let hit_tri_idx = int_resolve_triangle_index(hit_inst, committed.geometry_index, committed.primitive_index);++ if ((hit_inst_idx == self_instance && hit_tri_idx == self_triangle && committed.t < 1.0e-3)+ || (hit_inst_idx == target_instance && hit_tri_idx == target_triangle)+ || (hit_inst.visibility_flags & INSTANCE_VISIBILITY_SHADOW) == 0u) {+ current_t_min = committed.t + step_eps;+ continue;+ }++ let hit_tri = triangles[hit_tri_idx];+ let hit_mat = materials[int_resolve_material_index(hit_inst, hit_tri)];+ let supports_transparent_shadow = hit_mat.alpha_mode == ALPHA_MODE_BLEND+ || (hit_mat.flags & MATERIAL_FLAG_TRANSPARENT_SHADOW) != 0u;+ if (supports_transparent_shadow) {+ let opacity = int_evaluate_surface_opacity(hit_tri, hit_mat, committed.barycentrics);+ if (opacity < 1.0) {+ if (transparent_hits >= kernel_params.max_transparent_bounces) {+ return vec3<f32>(0.0);+ }+ transmittance *= (1.0 - opacity);+ transparent_hits += 1u;+ current_t_min = committed.t + step_eps;+ continue;+ }+ }+ return vec3<f32>(0.0);+ }+ }++ if ((kernel_params.kernel_flags & KERNEL_FLAG_HAS_VOLUME) != 0u && kernel_params.volume_density > 0.0) {+ let overlap = int_volume_segment_overlap(ray_origin, ray_dir, 0.0, shadow_t_max);+ if (overlap.y > overlap.x) {+ transmittance *= exp(-kernel_params.volume_density * (overlap.y - overlap.x));+ }+ }++ return transmittance;+}++fn int_transform_point(instance: InstanceRecord, point_obj: vec3<f32>) -> vec3<f32> {+ return vec3<f32>(+ dot(instance.object_to_world_row0.xyz, point_obj) + instance.object_to_world_row0.w,+ dot(instance.object_to_world_row1.xyz, point_obj) + instance.object_to_world_row1.w,+ dot(instance.object_to_world_row2.xyz, point_obj) + instance.object_to_world_row2.w,+ );+}++fn int_transform_vector(instance: InstanceRecord, vec_obj: vec3<f32>) -> vec3<f32> {+ return vec3<f32>(+ dot(instance.object_to_world_row0.xyz, vec_obj),+ dot(instance.object_to_world_row1.xyz, vec_obj),+ dot(instance.object_to_world_row2.xyz, vec_obj),+ );+}++fn int_transform_normal(instance: InstanceRecord, normal_obj: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {+ let world_normal = normal_obj.x * instance.world_to_object_row0.xyz+ + normal_obj.y * instance.world_to_object_row1.xyz+ + normal_obj.z * instance.world_to_object_row2.xyz;+ let len = length(world_normal);+ if (len > 1.0e-12) {+ return world_normal / len;+ }+ return fallback;+}++fn int_build_shading_point(surface_hit: IntSurfaceHit, wo: vec3<f32>) -> ShadingPoint {+ let instance = instances[surface_hit.instance_index];+ let triangle = triangles[surface_hit.triangle_index];+ let bary_u = surface_hit.barycentrics.x;+ let bary_v = surface_hit.barycentrics.y;+ let bary_w = 1.0 - bary_u - bary_v;++ let pos_obj = triangle.p0 + triangle.edge1 * bary_u + triangle.edge2 * bary_v;+ let pos_world = int_transform_point(instance, pos_obj);+ let world_edge1 = int_transform_vector(instance, triangle.edge1);+ let world_edge2 = int_transform_vector(instance, triangle.edge2);+ var raw_ng = cross(world_edge1, world_edge2);+ if ((instance.visibility_flags & INSTANCE_FLAG_NEGATIVE_SCALE) != 0u) {+ raw_ng = -raw_ng;+ }+ let ng_len = length(raw_ng);+ let outward_ng = select(wo, raw_ng / ng_len, ng_len > 1.0e-16);+ let is_front = dot(outward_ng, wo) >= 0.0;+ let geometric_normal = select(-outward_ng, outward_ng, is_front);++ var shading_normal = geometric_normal;+ if ((triangle.flags & TRIANGLE_FLAG_SMOOTH_NORMALS) != 0u) {+ let interp_n = bary_w * triangle.n0 + bary_u * triangle.n1 + bary_v * triangle.n2;+ let outward_ns = int_transform_normal(instance, interp_n, outward_ng);+ let oriented_ns = select(-outward_ns, outward_ns, is_front);+ if (dot(oriented_ns, geometric_normal) > 0.0) {+ shading_normal = oriented_ns;+ }+ }++ let uv0_0 = vec2<f32>(triangle.uv0_u, triangle.uv0_v);+ let uv0_1 = vec2<f32>(triangle.uv1_u, triangle.uv1_v);+ let uv0_2 = vec2<f32>(triangle.uv2_u, triangle.uv2_v);+ let uv0 = bary_w * uv0_0 + bary_u * uv0_1 + bary_v * uv0_2;+ let uv1 = select(+ uv0,+ bary_w * triangle.uv_set1_0 + bary_u * triangle.uv_set1_1 + bary_v * triangle.uv_set1_2,+ (triangle.flags & TRIANGLE_FLAG_HAS_UV1) != 0u,+ );+ let vertex_color = select(+ vec3<f32>(1.0),+ bary_w * triangle.color0 + bary_u * triangle.color1 + bary_v * triangle.color2,+ (triangle.flags & TRIANGLE_FLAG_HAS_VERTEX_COLORS) != 0u,+ );++ var tangent = vec3<f32>(0.0);+ var bitangent = vec3<f32>(0.0);+ var built_frame = false;+ if ((triangle.flags & TRIANGLE_FLAG_HAS_TANGENTS) != 0u) {+ let interp_t = bary_w * triangle.tangent0 + bary_u * triangle.tangent1 + bary_v * triangle.tangent2;+ var world_t = int_transform_vector(instance, interp_t);+ world_t -= shading_normal * dot(world_t, shading_normal);+ let t_len = length(world_t);+ if (t_len > 1.0e-8) {+ tangent = world_t / t_len;+ let scale_sign = select(1.0, -1.0, (instance.visibility_flags & INSTANCE_FLAG_NEGATIVE_SCALE) != 0u);+ let hand_sign = select(1.0, -1.0, triangle.tangent_sign < 0.0) * scale_sign;+ bitangent = cross(shading_normal, tangent) * hand_sign;+ built_frame = true;+ }+ }+ if (!built_frame) {+ let duv1 = uv0_1 - uv0_0;+ let duv2 = uv0_2 - uv0_0;+ let det = duv1.x * duv2.y - duv2.x * duv1.y;+ if (abs(det) > 1.0e-12) {+ var grad_t = (world_edge1 * duv2.y - world_edge2 * duv1.y) / det;+ let grad_b = (world_edge2 * duv1.x - world_edge1 * duv2.x) / det;+ grad_t -= shading_normal * dot(grad_t, shading_normal);+ let t_len = length(grad_t);+ if (t_len > 1.0e-8) {+ tangent = grad_t / t_len;+ let raw_b = cross(shading_normal, tangent);+ let hand = select(1.0, -1.0, dot(raw_b, grad_b) < 0.0);+ bitangent = raw_b * hand;+ built_frame = true;+ }+ }+ }+ if (!built_frame) {+ lgt_make_orthonormal_basis(shading_normal, &tangent, &bitangent);+ }++ var emissive_index = INVALID_INDEX;+ if (instance.emissive_base_offset != INVALID_INDEX && triangle.local_emissive_offset != INVALID_INDEX) {+ emissive_index = instance.emissive_base_offset + triangle.local_emissive_offset;+ }++ var point: ShadingPoint;+ point.position = pos_world;+ point.ray_t = surface_hit.t;+ point.geometric_normal = geometric_normal;+ point.front_face = select(0u, 1u, is_front);+ point.shading_normal = shading_normal;+ point.material_index = int_resolve_material_index(instance, triangle);+ point.coat_normal = shading_normal;+ point.instance_index = surface_hit.instance_index;+ point.tangent = tangent;+ point.triangle_index = surface_hit.triangle_index;+ point.bitangent = bitangent;+ point.emissive_index = emissive_index;+ point.uv0 = uv0;+ point.uv1 = uv1;+ point.barycentrics = surface_hit.barycentrics;+ point.object_random = instance.object_random;+ point.light_group_mask_lo = instance.light_group_mask_lo;+ point.vertex_color = vertex_color;+ point.light_group_mask_hi = instance.light_group_mask_hi;+ return point;+}++fn int_ray_offset_origin(point: ShadingPoint, wi: vec3<f32>) -> vec3<f32> {+ let sign_ng = select(-1.0, 1.0, dot(point.geometric_normal, wi) >= 0.0);+ let scale = max(kernel_params.ray_epsilon, 1.0e-5 * max(1.0, max(abs(point.position.x), max(abs(point.position.y), abs(point.position.z)))));+ return point.position + point.geometric_normal * (sign_ng * scale);+}++fn int_closure_albedo(closure: Closure, material: MaterialRecord) -> vec3<f32> {+ if (closure.lobe_count == 0u) {+ return clamp(material.base_color, vec3<f32>(0.0), vec3<f32>(1.0));+ }+ var sum_weight = vec3<f32>(0.0);+ let count = min(closure.lobe_count, MAX_CLOSURE_LOBES);+ for (var i = 0u; i < count; i += 1u) {+ if (closure.lobes[i].lobe_type != LOBE_TRANSPARENT) {+ sum_weight += max(closure.lobes[i].weight, vec3<f32>(0.0));+ }+ }+ return clamp(sum_weight, vec3<f32>(0.0), vec3<f32>(1.0));+}++fn int_is_singular_bsdf_sample(closure: Closure, sample: ClosureSample, check_eval: ClosureEval) -> bool {+ if (check_eval.pdf <= 0.0) {+ return true;+ }+ if (sample.sampled_lobe_type == LOBE_DIFFUSE || sample.sampled_lobe_type == LOBE_SHEEN) {+ return false;+ }+ let count = min(closure.lobe_count, MAX_CLOSURE_LOBES);+ for (var i = 0u; i < count; i += 1u) {+ let lobe = closure.lobes[i];+ if (lobe.lobe_type == sample.sampled_lobe_type) {+ let max_alpha = max(lobe.alpha_x, lobe.alpha_y);+ if (max_alpha <= 1.0e-3 && sample.pdf <= 1.0 && abs(check_eval.pdf - sample.pdf) > 1.0e-4) {+ return true;+ }+ }+ }+ return false;+}++fn int_accumulate_direct_sample(+ sample: LgtDirectSample,+ closure: Closure,+ point: ShadingPoint,+ wo: vec3<f32>,+ throughput: vec3<f32>,+ medium_sigma: vec3<f32>,+ in_medium: bool,+ bounce: u32,+ radiance: ptr<function, vec3<f32>>,+) {+ if (sample.valid == 0u || sample.pdf <= 0.0) {+ return;+ }+ let bsdf = closure_eval(closure, sample.wi, wo);+ if (bsdf.value.x <= 0.0 && bsdf.value.y <= 0.0 && bsdf.value.z <= 0.0) {+ return;+ }+ let mis_weight = select(lgt_power_heuristic(sample.pdf, bsdf.pdf), 1.0, sample.is_delta != 0u);+ if (mis_weight <= 0.0) {+ return;+ }+ var unshadowed = throughput * bsdf.value * sample.radiance * (mis_weight / sample.pdf);+ if (in_medium && sample.distance < 1.0e29) {+ unshadowed *= exp(-medium_sigma * sample.distance);+ }+ if (unshadowed.x <= 0.0 && unshadowed.y <= 0.0 && unshadowed.z <= 0.0) {+ return;+ }++ var visibility = vec3<f32>(1.0);+ if (sample.cast_shadow != 0u) {+ let shadow_origin = int_ray_offset_origin(point, sample.wi);+ visibility = int_trace_shadow(+ shadow_origin,+ sample.wi,+ sample.distance,+ point.instance_index,+ point.triangle_index,+ sample.target_instance,+ sample.target_triangle,+ );+ }+ if (visibility.x <= 0.0 && visibility.y <= 0.0 && visibility.z <= 0.0) {+ return;+ }+ *radiance += int_clamp_contribution(unshadowed * visibility, i32(bounce));+}++fn int_eval_henyey_greenstein(cos_theta: f32, g: f32) -> f32 {+ let g_clamped = clamp(g, -0.99, 0.99);+ let g2 = g_clamped * g_clamped;+ let denom = max(1.0 + g2 - 2.0 * g_clamped * cos_theta, 1.0e-8);+ return (0.25 * INV_PI) * (1.0 - g2) / (denom * sqrt(denom));+}++fn int_sample_henyey_greenstein(incident_dir: vec3<f32>, g: f32, rand_uv: vec2<f32>, pdf_out: ptr<function, f32>) -> vec3<f32> {+ let g_clamped = clamp(g, -0.99, 0.99);+ var cos_theta = 1.0 - 2.0 * rand_uv.x;+ if (abs(g_clamped) > 1.0e-4) {+ let g2 = g_clamped * g_clamped;+ let term = (1.0 - g2) / (1.0 - g_clamped + 2.0 * g_clamped * rand_uv.x);+ cos_theta = clamp((1.0 + g2 - term * term) / (2.0 * g_clamped), -1.0, 1.0);+ }+ let sin_theta = sqrt(max(0.0, 1.0 - cos_theta * cos_theta));+ let phi = TWO_PI * rand_uv.y;+ var axis_x: vec3<f32>;+ var axis_y: vec3<f32>;+ lgt_make_orthonormal_basis(incident_dir, &axis_x, &axis_y);+ *pdf_out = int_eval_henyey_greenstein(cos_theta, g_clamped);+ return normalize(axis_x * (sin_theta * cos(phi)) + axis_y * (sin_theta * sin(phi)) + incident_dir * cos_theta);+}++fn int_accumulate_volume_direct_sample(+ sample: LgtDirectSample,+ scatter_pos: vec3<f32>,+ incident_dir: vec3<f32>,+ throughput: vec3<f32>,+ bounce: u32,+ radiance: ptr<function, vec3<f32>>,+) {+ if (sample.valid == 0u || sample.pdf <= 0.0) {+ return;+ }+ let phase = int_eval_henyey_greenstein(dot(incident_dir, sample.wi), kernel_params.volume_anisotropy);+ let mis_weight = select(lgt_power_heuristic(sample.pdf, phase), 1.0, sample.is_delta != 0u);+ let unshadowed = throughput * sample.radiance * (phase * mis_weight / sample.pdf);+ if (unshadowed.x <= 0.0 && unshadowed.y <= 0.0 && unshadowed.z <= 0.0) {+ return;+ }+ var visibility = vec3<f32>(1.0);+ if (sample.cast_shadow != 0u) {+ visibility = int_trace_shadow(+ scatter_pos,+ sample.wi,+ sample.distance,+ INVALID_INDEX,+ INVALID_INDEX,+ sample.target_instance,+ sample.target_triangle,+ );+ }+ *radiance += int_clamp_contribution(unshadowed * visibility, i32(bounce));+}++@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {+ let pixel_x = global_id.x;+ let pixel_y = global_id.y;+ if (pixel_x >= kernel_params.image_width || pixel_y >= kernel_params.image_height) {+ return;+ }++ let pixel_index = pixel_y * kernel_params.image_width + pixel_x;+ let pixel_count = kernel_params.image_width * kernel_params.image_height;+ var stats = film_accumulation[3u * pixel_count + pixel_index];+ if (int_pixel_has_converged(stats)) {+ stats.z = 1.0;+ film_accumulation[3u * pixel_count + pixel_index] = stats;+ return;+ }++ let limit_bounce = kernel_params.max_bounces + 1u;+ let limit_diffuse = kernel_params.max_diffuse_bounces + 1u;+ let limit_glossy = kernel_params.max_glossy_bounces + 1u;+ let limit_transmission = kernel_params.max_transmission_bounces + 1u;+ let limit_volume = kernel_params.max_volume_bounces + 1u;+ let sample_count = max(kernel_params.samples_per_dispatch, 1u);+ let exposure = select(1.0, kernel_params.film_exposure, kernel_params.film_exposure > 0.0);+ let has_world_volume = (kernel_params.kernel_flags & KERNEL_FLAG_HAS_VOLUME) != 0u && kernel_params.volume_density > 0.0;++ var batch_radiance = vec3<f32>(0.0);+ var batch_depth = 0.0;+ var batch_albedo = vec3<f32>(0.0);+ var batch_normal = vec3<f32>(0.0);+ var taken_in_batch = 0u;++ for (var s = 0u; s < sample_count; s += 1u) {+ if (s > 0u && int_pixel_has_converged(stats)) {+ stats.z = 1.0;+ break;+ }++ let sample_index = kernel_params.sample_offset + s;+ var rng = smp_init(pixel_x, pixel_y, sample_index, kernel_params.seed);+ let filter_offset = flt_sample_offset(smp_next_2d(&rng));+ let lens_uv = smp_next_2d(&rng);+ let cam_ray = cam_generate_ray(pixel_x, pixel_y, filter_offset, lens_uv);++ var ray_origin = cam_ray.origin;+ var ray_dir = cam_ray.direction;+ var ray_t_min = cam_ray.t_min;+ var ray_t_max = cam_ray.t_max;+ var ray_visibility = INSTANCE_VISIBILITY_CAMERA;+ var self_instance = INVALID_INDEX;+ var self_triangle = INVALID_INDEX;++ var throughput = vec3<f32>(1.0);+ var medium_sigma = vec3<f32>(0.0);+ var in_medium = false;+ var is_camera_ray = true;+ var is_transparent_bg_ray = (kernel_params.kernel_flags & KERNEL_FLAG_TRANSPARENT_BACKGROUND) != 0u;+ var mis_skip = true;+ var prev_bsdf_pdf = 0.0;+ var prev_recv_lo = 0xFFFFFFFFu;+ var prev_recv_hi = 0xFFFFFFFFu;+ var terminate_on_hit = false;++ var bounce = 0u;+ var diffuse_bounces = 0u;+ var glossy_bounces = 0u;+ var transmission_bounces = 0u;+ var volume_bounces = 0u;+ var transparent_bounces = 0u;++ var sample_radiance = vec3<f32>(0.0);+ var first_depth = 0.0;+ var first_albedo = vec3<f32>(0.0);+ var first_normal = vec3<f32>(0.0);+ var recorded_features = false;++ for (var step = 0u; step < INT_MAX_PATH_STEPS; step += 1u) {+ let surface_hit = int_trace_closest_surface(+ ray_origin,+ ray_dir,+ ray_t_min,+ ray_t_max,+ ray_visibility,+ self_instance,+ self_triangle,+ );++ var volume_scattered = false;+ var volume_scatter_t = surface_hit.t;+ if (has_world_volume) {+ let overlap = int_volume_segment_overlap(ray_origin, ray_dir, ray_t_min, surface_hit.t);+ if (overlap.y > overlap.x) {+ let vol_u = smp_next_1d(&rng);+ let free_flight = -log(max(1.0 - vol_u, 1.0e-12)) / kernel_params.volume_density;+ let vol_len = overlap.y - overlap.x;+ if (free_flight < vol_len) {+ volume_scattered = true;+ volume_scatter_t = overlap.x + free_flight;+ }+ }+ }++ let segment_end_t = select(surface_hit.t, volume_scatter_t, volume_scattered);+ let analytic_emission = lgt_eval_analytic_lights_along_segment(+ ray_origin,+ ray_dir,+ ray_t_min,+ segment_end_t,+ is_camera_ray,+ mis_skip,+ prev_bsdf_pdf,+ prev_recv_lo,+ prev_recv_hi,+ in_medium,+ medium_sigma,+ );+ if (analytic_emission.x > 0.0 || analytic_emission.y > 0.0 || analytic_emission.z > 0.0) {+ sample_radiance += int_clamp_contribution(throughput * analytic_emission, i32(bounce) - 1);+ }++ if (volume_scattered) {+ if (terminate_on_hit) {+ break;+ }+ if (in_medium) {+ throughput *= exp(-medium_sigma * max(volume_scatter_t - ray_t_min, 0.0));+ }+ throughput *= kernel_params.volume_albedo;+ let scatter_pos = ray_origin + ray_dir * volume_scatter_t;+ if (!recorded_features) {+ first_depth = volume_scatter_t;+ first_albedo = clamp(kernel_params.volume_albedo, vec3<f32>(0.0), vec3<f32>(1.0));+ first_normal = -ray_dir;+ recorded_features = true;+ }++ if (kernel_params.light_count > 0u) {+ let light_samp = lgt_sample_analytic_light(scatter_pos, 0xFFFFFFFFu, 0xFFFFFFFFu, smp_next_1d(&rng), smp_next_2d(&rng));+ int_accumulate_volume_direct_sample(light_samp, scatter_pos, ray_dir, throughput, bounce, &sample_radiance);+ }+ if (kernel_params.env_width > 0u && kernel_params.env_height > 0u && kernel_params.background_mis_weight > 0.0) {+ let env_samp = lgt_sample_environment(smp_next_4d(&rng));+ int_accumulate_volume_direct_sample(env_samp, scatter_pos, ray_dir, throughput, bounce, &sample_radiance);+ }++ var phase_pdf = 0.0;+ let next_dir = int_sample_henyey_greenstein(ray_dir, kernel_params.volume_anisotropy, smp_next_2d(&rng), &phase_pdf);+ bounce += 1u;+ volume_bounces += 1u;+ if (bounce >= limit_bounce || volume_bounces >= limit_volume) {+ terminate_on_hit = true;+ }+ if (!terminate_on_hit && bounce > kernel_params.min_bounce_rr) {+ let max_channel = max(throughput.x, max(throughput.y, throughput.z));+ let survival = clamp(max_channel, 0.05, 1.0);+ if (survival < 1.0) {+ if (smp_next_1d(&rng) >= survival) {+ break;+ }+ throughput /= survival;+ }+ }+ ray_origin = scatter_pos;+ ray_dir = next_dir;+ ray_t_min = 0.0;+ ray_t_max = 1.0e30;+ ray_visibility = INSTANCE_VISIBILITY_VOLUME_SCATTER;+ self_instance = INVALID_INDEX;+ self_triangle = INVALID_INDEX;+ is_camera_ray = false;+ is_transparent_bg_ray = false;+ mis_skip = false;+ prev_bsdf_pdf = phase_pdf;+ prev_recv_lo = 0xFFFFFFFFu;+ prev_recv_hi = 0xFFFFFFFFu;+ continue;+ }++ if (surface_hit.hit == 0u) {+ let escaped = lgt_eval_escaped_ray(+ ray_dir,+ is_camera_ray,+ is_transparent_bg_ray,+ mis_skip,+ prev_bsdf_pdf,+ prev_recv_lo,+ prev_recv_hi,+ );+ if (escaped.x > 0.0 || escaped.y > 0.0 || escaped.z > 0.0) {+ sample_radiance += int_clamp_contribution(throughput * escaped, i32(bounce) - 1);+ }+ if (!recorded_features) {+ first_albedo = clamp(escaped, vec3<f32>(0.0), vec3<f32>(1.0));+ recorded_features = true;+ }+ break;+ }++ if (in_medium) {+ throughput *= exp(-medium_sigma * max(surface_hit.t - ray_t_min, 0.0));+ }++ let wo = -ray_dir;+ let point = int_build_shading_point(surface_hit, wo);+ let closure = closure_build(point, wo);+ let material = materials[point.material_index];+ let is_pure_transparent = closure.lobe_count == 1u && closure.lobes[0].lobe_type == LOBE_TRANSPARENT;++ if (!recorded_features && !is_pure_transparent) {+ first_depth = surface_hit.t;+ first_albedo = int_closure_albedo(closure, material);+ first_normal = point.shading_normal;+ recorded_features = true;+ }++ if (closure.emission.x > 0.0 || closure.emission.y > 0.0 || closure.emission.z > 0.0) {+ let emission_weight = lgt_emissive_surface_weight(+ point.emissive_index,+ surface_hit.t,+ ray_dir,+ is_camera_ray,+ mis_skip,+ prev_bsdf_pdf,+ prev_recv_lo,+ prev_recv_hi,+ );+ if (emission_weight > 0.0) {+ sample_radiance += int_clamp_contribution(throughput * closure.emission * emission_weight, i32(bounce) - 1);+ }+ }++ if (terminate_on_hit) {+ if (closure.lobe_count > 0u && closure.lobes[0].lobe_type == LOBE_TRANSPARENT && closure.total_sample_weight > 0.0) {+ if (transparent_bounces < kernel_params.max_transparent_bounces) {+ let trans_prob = clamp(closure.lobes[0].sample_weight / closure.total_sample_weight, 0.0, 1.0);+ if (trans_prob > 0.0 && smp_next_1d(&rng) < trans_prob) {+ transparent_bounces += 1u;+ throughput *= closure.lobes[0].weight / trans_prob;+ ray_t_min = surface_hit.t + max(kernel_params.ray_epsilon, 1.0e-6);+ self_instance = point.instance_index;+ self_triangle = point.triangle_index;+ continue;+ }+ }+ }+ break;+ }++ if (closure.lobe_count == 0u || closure.total_sample_weight <= 0.0) {+ break;+ }++ if (kernel_params.light_count > 0u) {+ let light_sample = lgt_sample_analytic_light(+ point.position,+ point.light_group_mask_lo,+ point.light_group_mask_hi,+ smp_next_1d(&rng),+ smp_next_2d(&rng),+ );+ int_accumulate_direct_sample(light_sample, closure, point, wo, throughput, medium_sigma, in_medium, bounce, &sample_radiance);+ }++ if (kernel_params.emissive_triangle_count > 0u) {+ let tri_sample = lgt_sample_emissive_triangle(point, smp_next_1d(&rng), smp_next_2d(&rng));+ int_accumulate_direct_sample(tri_sample, closure, point, wo, throughput, medium_sigma, in_medium, bounce, &sample_radiance);+ }++ if (kernel_params.env_width > 0u && kernel_params.env_height > 0u && kernel_params.background_mis_weight > 0.0) {+ let env_sample = lgt_sample_environment(smp_next_4d(&rng));+ int_accumulate_direct_sample(env_sample, closure, point, wo, throughput, medium_sigma, in_medium, bounce, &sample_radiance);+ }++ let bsdf_sample = closure_sample(closure, wo, smp_next_3d(&rng));+ if (bsdf_sample.pdf <= 0.0 || (bsdf_sample.eval.x <= 0.0 && bsdf_sample.eval.y <= 0.0 && bsdf_sample.eval.z <= 0.0)) {+ break;+ }++ if (bsdf_sample.sampled_lobe_type == LOBE_TRANSPARENT) {+ if (transparent_bounces >= kernel_params.max_transparent_bounces) {+ break;+ }+ transparent_bounces += 1u;+ throughput *= bsdf_sample.eval / bsdf_sample.pdf;+ ray_t_min = surface_hit.t + max(kernel_params.ray_epsilon, 1.0e-6);+ self_instance = point.instance_index;+ self_triangle = point.triangle_index;+ continue;+ }++ let check_eval = closure_eval(closure, bsdf_sample.wi, wo);+ let is_singular = int_is_singular_bsdf_sample(closure, bsdf_sample, check_eval);+ throughput *= bsdf_sample.eval / bsdf_sample.pdf;++ bounce += 1u;+ let cos_ng_wi = dot(point.geometric_normal, bsdf_sample.wi);+ let is_transmission = bsdf_sample.sampled_lobe_type == LOBE_GLASS_GGX && cos_ng_wi < 0.0;++ if (is_transmission) {+ transmission_bounces += 1u;+ ray_visibility = INSTANCE_VISIBILITY_TRANSMISSION;+ if (transmission_bounces >= limit_transmission) {+ terminate_on_hit = true;+ }+ if ((material.flags & MATERIAL_FLAG_THIN_WALLED) == 0u) {+ if (point.front_face != 0u) {+ medium_sigma = max(closure.absorption_sigma, vec3<f32>(0.0));+ in_medium = medium_sigma.x > 0.0 || medium_sigma.y > 0.0 || medium_sigma.z > 0.0;+ } else {+ medium_sigma = vec3<f32>(0.0);+ in_medium = false;+ }+ }+ } else if (bsdf_sample.sampled_lobe_type == LOBE_DIFFUSE || bsdf_sample.sampled_lobe_type == LOBE_SHEEN) {+ diffuse_bounces += 1u;+ ray_visibility = INSTANCE_VISIBILITY_DIFFUSE;+ if (diffuse_bounces >= limit_diffuse) {+ terminate_on_hit = true;+ }+ } else {+ glossy_bounces += 1u;+ ray_visibility = INSTANCE_VISIBILITY_GLOSSY;+ if (glossy_bounces >= limit_glossy) {+ terminate_on_hit = true;+ }+ }++ if (bounce >= limit_bounce) {+ terminate_on_hit = true;+ }++ if (!terminate_on_hit && bounce > kernel_params.min_bounce_rr) {+ let max_channel = max(throughput.x, max(throughput.y, throughput.z));+ let survival = clamp(max_channel, 0.05, 1.0);+ if (survival < 1.0) {+ if (smp_next_1d(&rng) >= survival) {+ break;+ }+ throughput /= survival;+ }+ }++ ray_origin = int_ray_offset_origin(point, bsdf_sample.wi);+ ray_dir = bsdf_sample.wi;+ ray_t_min = 0.0;+ ray_t_max = 1.0e30;+ self_instance = point.instance_index;+ self_triangle = point.triangle_index;+ is_camera_ray = false;+ is_transparent_bg_ray = false;+ mis_skip = is_singular;+ prev_bsdf_pdf = select(check_eval.pdf, bsdf_sample.pdf, is_singular);+ prev_recv_lo = point.light_group_mask_lo;+ prev_recv_hi = point.light_group_mask_hi;+ }++ let exposed = int_sanitize_radiance(sample_radiance * exposure);+ let lum = int_luminance(exposed);+ batch_radiance += exposed;+ batch_depth += select(0.0, first_depth, first_depth >= 0.0 && first_depth < 1.0e29);+ batch_albedo += int_sanitize_radiance(first_albedo);+ batch_normal += first_normal;+ stats.x += lum;+ stats.y += lum * lum;+ stats.w += 1.0;+ taken_in_batch += 1u;+ }++ if (taken_in_batch > 0u) {+ film_accumulation[pixel_index] += vec4<f32>(batch_radiance, batch_depth);+ film_accumulation[pixel_count + pixel_index] += vec4<f32>(batch_albedo, 0.0);+ film_accumulation[2u * pixel_count + pixel_index] += vec4<f32>(batch_normal, 0.0);+ film_accumulation[3u * pixel_count + pixel_index] = stats;+ }+}diff --git a/packages/render-native/src/cycles/lights.wgsl b/packages/render-native/src/cycles/lights.wgslnew file mode 100644index 00000000..7a01302c--- /dev/null+++ b/packages/render-native/src/cycles/lights.wgsl@@ -0,0 +1,947 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Analytic lights, emissive mesh triangles, environment HDRI sampling, forward MIS, and+// 64-bit light-linking (`lgt_*`), ported from Cycles `kernel/light/*.h`.++struct LgtDirectSample {+ valid: u32,+ is_delta: u32,+ wi: vec3<f32>,+ distance: f32,+ radiance: vec3<f32>,+ pdf: f32,+ target_instance: u32,+ target_triangle: u32,+ cast_shadow: u32,+}++fn lgt_empty_sample() -> LgtDirectSample {+ var sample: LgtDirectSample;+ sample.valid = 0u;+ sample.is_delta = 0u;+ sample.wi = vec3<f32>(0.0, 1.0, 0.0);+ sample.distance = 0.0;+ sample.radiance = vec3<f32>(0.0);+ sample.pdf = 0.0;+ sample.target_instance = INVALID_INDEX;+ sample.target_triangle = INVALID_INDEX;+ sample.cast_shadow = 1u;+ return sample;+}++fn lgt_power_heuristic(pdf_a: f32, pdf_b: f32) -> f32 {+ if (pdf_a <= 0.0) {+ return 0.0;+ }+ if (pdf_b <= 0.0) {+ return 1.0;+ }+ if (pdf_a >= pdf_b) {+ let ratio = pdf_b / pdf_a;+ return 1.0 / (1.0 + ratio * ratio);+ }+ let ratio = pdf_a / pdf_b;+ return (ratio * ratio) / (1.0 + ratio * ratio);+}++fn lgt_links_match(receiver_lo: u32, receiver_hi: u32, emitter_lo: u32, emitter_hi: u32) -> bool {+ return ((receiver_lo & emitter_lo) | (receiver_hi & emitter_hi)) != 0u;+}++fn lgt_make_orthonormal_basis(axis_z: vec3<f32>, axis_x: ptr<function, vec3<f32>>, axis_y: ptr<function, vec3<f32>>) {+ let sign_z = select(-1.0, 1.0, axis_z.z >= 0.0);+ let coeff_a = -1.0 / (sign_z + axis_z.z);+ let coeff_b = axis_z.x * axis_z.y * coeff_a;+ *axis_x = vec3<f32>(1.0 + sign_z * axis_z.x * axis_z.x * coeff_a, sign_z * coeff_b, -sign_z * axis_z.x);+ *axis_y = vec3<f32>(coeff_b, sign_z + axis_z.y * axis_z.y * coeff_a, -axis_z.y);+}++fn lgt_sample_uniform_cone(axis: vec3<f32>, one_minus_cos_max: f32, rand_uv: vec2<f32>, cos_theta_out: ptr<function, f32>) -> vec3<f32> {+ let one_minus_cos = rand_uv.x * one_minus_cos_max;+ let cos_theta = 1.0 - one_minus_cos;+ let sin_theta = sqrt(max(0.0, one_minus_cos * (2.0 - one_minus_cos)));+ let phi = TWO_PI * rand_uv.y;+ var tangent_x: vec3<f32>;+ var tangent_y: vec3<f32>;+ lgt_make_orthonormal_basis(axis, &tangent_x, &tangent_y);+ *cos_theta_out = cos_theta;+ return normalize(+ tangent_x * (sin_theta * cos(phi))+ + tangent_y * (sin_theta * sin(phi))+ + axis * cos_theta+ );+}++fn lgt_sample_uniform_sphere(rand_uv: vec2<f32>) -> vec3<f32> {+ let z = 1.0 - 2.0 * rand_uv.x;+ let radial = sqrt(max(0.0, 1.0 - z * z));+ let phi = TWO_PI * rand_uv.y;+ return vec3<f32>(radial * cos(phi), radial * sin(phi), z);+}++fn lgt_sin_sqr_to_one_minus_cos(sin_sq: f32) -> f32 {+ let clamped = clamp(sin_sq, 0.0, 1.0);+ let cos_val = sqrt(max(0.0, 1.0 - clamped));+ return clamped / (1.0 + cos_val);+}++fn lgt_sun_one_minus_cos(light: LightRecord) -> f32 {+ if (light.area_or_solid_angle > 0.0 && light.cos_half_angle < 1.0) {+ return clamp(light.area_or_solid_angle * INV_TWO_PI, 0.0, 2.0);+ }+ return max(0.0, 1.0 - light.cos_half_angle);+}++fn lgt_spot_attenuation(light: LightRecord, ray_from_light: vec3<f32>) -> f32 {+ let cos_angle = dot(ray_from_light, light.direction);+ if (cos_angle <= light.cos_half_angle) {+ return 0.0;+ }+ if (light.spot_blend <= 0.0) {+ return 1.0;+ }+ let span = max((1.0 - light.cos_half_angle) * light.spot_blend, 1.0e-8);+ let t = clamp((cos_angle - light.cos_half_angle) / span, 0.0, 1.0);+ return t * t * (3.0 - 2.0 * t);+}++fn lgt_range_falloff(distance: f32, max_distance: f32) -> f32 {+ if (max_distance >= 1.0e29 || max_distance <= 0.0) {+ return 1.0;+ }+ if (distance >= max_distance) {+ return 0.0;+ }+ return 1.0;+}++fn lgt_ray_sphere_intersect(+ ray_origin: vec3<f32>,+ ray_dir: vec3<f32>,+ center: vec3<f32>,+ radius: f32,+ hit_t: ptr<function, f32>,+) -> bool {+ let to_center = center - ray_origin;+ let dist_sq = dot(to_center, to_center);+ let radius_sq = radius * radius;+ let proj = dot(to_center, ray_dir);+ if (dist_sq > radius_sq && proj <= 0.0) {+ return false;+ }+ let perp = to_center - ray_dir * proj;+ let disc = radius_sq - dot(perp, perp);+ if (disc < 0.0) {+ return false;+ }+ let half_chord = sqrt(disc);+ let candidate_t = select(proj + half_chord, proj - half_chord, dist_sq > radius_sq);+ if (candidate_t <= 0.0) {+ return false;+ }+ *hit_t = candidate_t;+ return true;+}++fn lgt_sphere_solid_angle_pdf(dist_sq: f32, radius: f32, hit_t: f32, ray_origin: vec3<f32>, ray_dir: vec3<f32>, center: vec3<f32>) -> f32 {+ let radius_sq = radius * radius;+ if (dist_sq > radius_sq) {+ let one_minus_cos = lgt_sin_sqr_to_one_minus_cos(radius_sq / dist_sq);+ return 1.0 / max(TWO_PI * one_minus_cos, 1.0e-30);+ }+ let hit_point = ray_origin + ray_dir * hit_t;+ let sphere_normal = normalize(hit_point - center);+ let cos_light = max(abs(dot(sphere_normal, ray_dir)), 1.0e-8);+ return (hit_t * hit_t) / max(4.0 * PI * radius_sq * cos_light, 1.0e-20);+}++fn lgt_area_spread_attenuation(wi: vec3<f32>, light_normal: vec3<f32>, tan_half_spread: f32, spread_normalization: f32) -> f32 {+ let cos_emit = dot(-wi, light_normal);+ if (cos_emit <= 0.0) {+ return 0.0;+ }+ let sin_emit = sqrt(max(0.0, 1.0 - cos_emit * cos_emit));+ let tan_emit = sin_emit / max(cos_emit, 1.0e-8);+ if (tan_half_spread <= 0.0) {+ return select(0.0, PI, tan_emit <= 1.0e-5);+ }+ return max((tan_half_spread - tan_emit) * spread_normalization, 0.0);+}++// Cycles `area_light_rect_sample` (Urena et al. solid-angle spherical rectangle parameterization).+fn lgt_area_rect_sample_or_pdf(+ shading_pos: vec3<f32>,+ rect_center: vec3<f32>,+ axis_u: vec3<f32>,+ len_u: f32,+ axis_v: vec3<f32>,+ len_v: f32,+ rand_uv: vec2<f32>,+ sample_coord: bool,+ point_in_out: ptr<function, vec3<f32>>,+) -> f32 {+ var axis_z = cross(axis_u, axis_v);+ let z_len = length(axis_z);+ if (z_len <= 1.0e-12 || len_u <= 0.0 || len_v <= 0.0) {+ return 0.0;+ }+ axis_z /= z_len;++ let to_center = rect_center - shading_pos;+ var z0 = dot(to_center, axis_z);+ if (z0 > 0.0) {+ axis_z = -axis_z;+ z0 = -z0;+ }+ if (-z0 <= 1.0e-8) {+ return 0.0;+ }++ let xc = dot(to_center, axis_u);+ let yc = dot(to_center, axis_v);+ let x0 = xc - 0.5 * len_u;+ let x1 = xc + 0.5 * len_u;+ let y0 = yc - 0.5 * len_v;+ let y1 = yc + 0.5 * len_v;++ var nz = vec4<f32>(-y0, x1, y1, -x0);+ nz /= sqrt(nz * nz + vec4<f32>(z0 * z0));++ let g0 = asin(clamp(-nz.x * nz.y, -1.0, 1.0));+ let g1 = asin(clamp(-nz.y * nz.z, -1.0, 1.0));+ let g2 = asin(clamp(-nz.z * nz.w, -1.0, 1.0));+ let g3 = asin(clamp(-nz.w * nz.x, -1.0, 1.0));+ let solid_angle = -(g0 + g1 + g2 + g3);+ let nz_sq = nz * nz;+ let min_nz_sq = min(min(nz_sq.x, nz_sq.y), min(nz_sq.z, nz_sq.w));+ let use_planar_fallback = solid_angle < 1.0e-5 || min_nz_sq > 0.99999;++ if (use_planar_fallback) {+ if (sample_coord) {+ let local_u = (rand_uv.x - 0.5) * len_u;+ let local_v = (rand_uv.y - 0.5) * len_v;+ *point_in_out = rect_center + axis_u * local_u + axis_v * local_v;+ }+ let dist = length((*point_in_out) - shading_pos);+ return (dist * dist * dist) / max(-z0 * len_u * len_v, 1.0e-20);+ }++ if (sample_coord) {+ let b0 = nz.x;+ let b1 = nz.z;+ let b0_sq = b0 * b0;+ let au = rand_uv.x * solid_angle + g2 + g3;+ let sin_au = sin(au);+ let fu = select(0.0, (cos(au) * b0 + b1) / sin_au, abs(sin_au) > 1.0e-12);+ let cu_sign = select(-1.0, 1.0, fu >= 0.0);+ let cu = clamp(cu_sign / sqrt(fu * fu + b0_sq), -1.0, 1.0);+ var xu = -(cu * z0) / max(sqrt(max(0.0, 1.0 - cu * cu)), 1.0e-7);+ xu = clamp(xu, x0, x1);++ let d2 = xu * xu + z0 * z0;+ let h0 = y0 / sqrt(d2 + y0 * y0);+ let h1 = y1 / sqrt(d2 + y1 * y1);+ let hv = h0 + rand_uv.y * (h1 - h0);+ let hv_sq = hv * hv;+ let yv = select(y1, hv * sqrt(d2 / max(1.0 - hv_sq, 1.0e-7)), hv_sq < 1.0 - 1.0e-6);+ *point_in_out = shading_pos + axis_u * xu + axis_v * yv + axis_z * z0;+ }++ return 1.0 / solid_angle;+}++fn lgt_sample_ellipse_point(center: vec3<f32>, axis_u: vec3<f32>, size_u: f32, axis_v: vec3<f32>, size_v: f32, rand_uv: vec2<f32>) -> vec3<f32> {+ let disk = cam_sample_uniform_disk(rand_uv);+ return center + axis_u * (disk.x * 0.5 * size_u) + axis_v * (disk.y * 0.5 * size_v);+}++fn lgt_binary_search_light_cdf(pick_u: f32, count: u32) -> u32 {+ var low = 0u;+ var high = count - 1u;+ for (var step = 0u; step < 24u; step += 1u) {+ if (low >= high) {+ break;+ }+ let mid = (low + high) >> 1u;+ if (lights[mid].cdf_upper <= pick_u) {+ low = mid + 1u;+ } else {+ high = mid;+ }+ }+ return low;+}++fn lgt_binary_search_emissive_cdf(pick_u: f32, count: u32) -> u32 {+ var low = 0u;+ var high = count - 1u;+ for (var step = 0u; step < 24u; step += 1u) {+ if (low >= high) {+ break;+ }+ let mid = (low + high) >> 1u;+ if (emissive_triangles[mid].cdf_upper <= pick_u) {+ low = mid + 1u;+ } else {+ high = mid;+ }+ }+ return low;+}++fn lgt_binary_search_env_cdf(base_offset: u32, count: u32, pick_u: f32) -> u32 {+ var low = 0u;+ var high = count - 1u;+ for (var step = 0u; step < 24u; step += 1u) {+ if (low >= high) {+ break;+ }+ let mid = (low + high) >> 1u;+ if (environment_texels[base_offset + mid].x <= pick_u) {+ low = mid + 1u;+ } else {+ high = mid;+ }+ }+ return low;+}++fn lgt_sample_point_or_spot_light(light: LightRecord, shading_pos: vec3<f32>, rand_uv: vec2<f32>) -> LgtDirectSample {+ var out = lgt_empty_sample();+ out.cast_shadow = select(0u, 1u, (light.flags & LIGHT_FLAG_CAST_SHADOW) != 0u);+ let is_spot = light.light_type == LIGHT_TYPE_SPOT;+ let to_center = light.position - shading_pos;+ let dist_sq = dot(to_center, to_center);++ if (light.radius <= 0.0) {+ if (dist_sq <= 1.0e-16) {+ return out;+ }+ let dist = sqrt(dist_sq);+ let falloff = lgt_range_falloff(dist, light.max_distance);+ if (falloff <= 0.0) {+ return out;+ }+ let wi = to_center / dist;+ var spot_weight = 1.0;+ if (is_spot) {+ spot_weight = lgt_spot_attenuation(light, -wi);+ if (spot_weight <= 0.0) {+ return out;+ }+ }+ out.valid = 1u;+ out.is_delta = 1u;+ out.wi = wi;+ out.distance = dist;+ out.radiance = light.radiance * (spot_weight * falloff / dist_sq);+ out.pdf = light.selection_pdf;+ return out;+ }++ let radius = light.radius;+ let radius_sq = radius * radius;+ var wi = vec3<f32>(0.0);+ var hit_t = 0.0;+ var pdf_solid_angle = 0.0;++ if (dist_sq > radius_sq) {+ let dist = sqrt(dist_sq);+ let center_dir = to_center / dist;+ let one_minus_cos_sphere = lgt_sin_sqr_to_one_minus_cos(radius_sq / dist_sq);+ let one_minus_cos_spot = max(0.0, 1.0 - light.cos_half_angle);++ if (is_spot && one_minus_cos_spot < one_minus_cos_sphere) {+ if (one_minus_cos_spot <= 1.0e-12) {+ return out;+ }+ var cos_cone = 1.0;+ wi = lgt_sample_uniform_cone(-light.direction, one_minus_cos_spot, rand_uv, &cos_cone);+ if (!lgt_ray_sphere_intersect(shading_pos, wi, light.position, radius, &hit_t)) {+ return out;+ }+ pdf_solid_angle = 1.0 / max(TWO_PI * one_minus_cos_spot, 1.0e-30);+ } else {+ var cos_theta = 1.0;+ wi = lgt_sample_uniform_cone(center_dir, one_minus_cos_sphere, rand_uv, &cos_theta);+ let proj = dot(to_center, wi);+ let perp = to_center - wi * proj;+ let disc = max(0.0, radius_sq - dot(perp, perp));+ hit_t = max(proj - sqrt(disc), 0.0);+ pdf_solid_angle = 1.0 / max(TWO_PI * one_minus_cos_sphere, 1.0e-30);+ }+ } else {+ let sphere_normal = lgt_sample_uniform_sphere(rand_uv);+ let light_point = light.position + sphere_normal * radius;+ let diff = light_point - shading_pos;+ let dist = length(diff);+ if (dist <= 1.0e-8) {+ return out;+ }+ wi = diff / dist;+ hit_t = dist;+ let cos_light = max(abs(dot(sphere_normal, wi)), 1.0e-8);+ pdf_solid_angle = (dist * dist) / max(4.0 * PI * radius_sq * cos_light, 1.0e-20);+ }++ let falloff = lgt_range_falloff(hit_t, light.max_distance);+ if (falloff <= 0.0 || pdf_solid_angle <= 0.0) {+ return out;+ }++ var spot_weight = 1.0;+ if (is_spot && dist_sq > radius_sq) {+ spot_weight = lgt_spot_attenuation(light, -wi);+ if (spot_weight <= 0.0) {+ return out;+ }+ }++ out.valid = 1u;+ out.is_delta = select(1u, 0u, (light.flags & LIGHT_FLAG_MULTIPLE_IMPORTANCE) != 0u);+ out.wi = wi;+ out.distance = hit_t;+ out.radiance = light.radiance * (spot_weight * falloff);+ out.pdf = light.selection_pdf * pdf_solid_angle;+ return out;+}++fn lgt_sample_area_light(light: LightRecord, shading_pos: vec3<f32>, rand_uv: vec2<f32>) -> LgtDirectSample {+ var out = lgt_empty_sample();+ out.cast_shadow = select(0u, 1u, (light.flags & LIGHT_FLAG_CAST_SHADOW) != 0u);+ let light_normal = light.direction;+ if (dot(shading_pos - light.position, light_normal) <= 0.0) {+ return out;+ }++ var sampled_point = light.position;+ var pdf_solid_angle = 0.0;+ var wi = vec3<f32>(0.0);+ var hit_t = 0.0;++ if (light.light_type == LIGHT_TYPE_AREA_RECT) {+ pdf_solid_angle = lgt_area_rect_sample_or_pdf(+ shading_pos,+ light.position,+ light.axis_u,+ light.size_u,+ light.axis_v,+ light.size_v,+ rand_uv,+ true,+ &sampled_point,+ );+ let diff = sampled_point - shading_pos;+ hit_t = length(diff);+ if (hit_t <= 1.0e-8 || pdf_solid_angle <= 0.0) {+ return out;+ }+ wi = diff / hit_t;+ if (dot(-wi, light_normal) <= 0.0) {+ return out;+ }+ } else {+ if (light.size_u <= 0.0 || light.size_v <= 0.0) {+ return out;+ }+ sampled_point = lgt_sample_ellipse_point(light.position, light.axis_u, light.size_u, light.axis_v, light.size_v, rand_uv);+ let diff = sampled_point - shading_pos;+ hit_t = length(diff);+ if (hit_t <= 1.0e-8) {+ return out;+ }+ wi = diff / hit_t;+ let cos_light = dot(-wi, light_normal);+ if (cos_light <= 0.0) {+ return out;+ }+ let ellipse_area = 0.25 * PI * light.size_u * light.size_v;+ pdf_solid_angle = (hit_t * hit_t) / max(ellipse_area * cos_light, 1.0e-20);+ }++ let falloff = lgt_range_falloff(hit_t, light.max_distance);+ if (falloff <= 0.0) {+ return out;+ }++ var spread_weight = 1.0;+ if (light.spread_normalization > 0.0) {+ spread_weight = lgt_area_spread_attenuation(wi, light_normal, light.tan_half_spread, light.spread_normalization);+ if (spread_weight <= 0.0) {+ return out;+ }+ }++ out.valid = 1u;+ out.is_delta = select(1u, 0u, (light.flags & LIGHT_FLAG_MULTIPLE_IMPORTANCE) != 0u);+ out.wi = wi;+ out.distance = hit_t;+ out.radiance = light.radiance * (spread_weight * falloff);+ out.pdf = light.selection_pdf * pdf_solid_angle;+ return out;+}++fn lgt_sample_sun_light(light: LightRecord, rand_uv: vec2<f32>) -> LgtDirectSample {+ var out = lgt_empty_sample();+ out.cast_shadow = select(0u, 1u, (light.flags & LIGHT_FLAG_CAST_SHADOW) != 0u);+ let to_sun = normalize(-light.direction);+ let one_minus_cos = lgt_sun_one_minus_cos(light);++ if (one_minus_cos <= 1.0e-12) {+ out.valid = 1u;+ out.is_delta = 1u;+ out.wi = to_sun;+ out.distance = 1.0e30;+ out.radiance = light.radiance;+ out.pdf = light.selection_pdf;+ return out;+ }++ var cos_theta = 1.0;+ let wi = lgt_sample_uniform_cone(to_sun, one_minus_cos, rand_uv, &cos_theta);+ let pdf_cone = 1.0 / max(TWO_PI * one_minus_cos, 1.0e-30);+ out.valid = 1u;+ out.is_delta = select(1u, 0u, (light.flags & LIGHT_FLAG_MULTIPLE_IMPORTANCE) != 0u);+ out.wi = wi;+ out.distance = 1.0e30;+ out.radiance = light.radiance;+ out.pdf = light.selection_pdf * pdf_cone;+ return out;+}++fn lgt_sample_analytic_light(+ shading_pos: vec3<f32>,+ receiver_lo: u32,+ receiver_hi: u32,+ pick_u: f32,+ sample_uv: vec2<f32>,+) -> LgtDirectSample {+ let count = kernel_params.light_count;+ if (count == 0u) {+ return lgt_empty_sample();+ }+ let light_index = lgt_binary_search_light_cdf(pick_u, count);+ let light = lights[light_index];+ if (light.selection_pdf <= 0.0) {+ return lgt_empty_sample();+ }+ if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) {+ return lgt_empty_sample();+ }+ if (light.light_type == LIGHT_TYPE_POINT || light.light_type == LIGHT_TYPE_SPOT) {+ return lgt_sample_point_or_spot_light(light, shading_pos, sample_uv);+ }+ if (light.light_type == LIGHT_TYPE_AREA_RECT || light.light_type == LIGHT_TYPE_AREA_DISK) {+ return lgt_sample_area_light(light, shading_pos, sample_uv);+ }+ if (light.light_type == LIGHT_TYPE_SUN) {+ return lgt_sample_sun_light(light, sample_uv);+ }+ return lgt_empty_sample();+}++fn lgt_sample_emissive_triangle(point: ShadingPoint, pick_u: f32, sample_uv: vec2<f32>) -> LgtDirectSample {+ var out = lgt_empty_sample();+ let count = kernel_params.emissive_triangle_count;+ if (count == 0u) {+ return out;+ }+ let index = lgt_binary_search_emissive_cdf(pick_u, count);+ let emitter = emissive_triangles[index];+ if (emitter.selection_pdf <= 0.0 || emitter.area <= 0.0) {+ return out;+ }+ if (!lgt_links_match(point.light_group_mask_lo, point.light_group_mask_hi, emitter.light_group_mask_lo, emitter.light_group_mask_hi)) {+ return out;+ }+ if (emitter.instance_index == point.instance_index && emitter.triangle_index == point.triangle_index) {+ return out;+ }++ let su = sqrt(sample_uv.x);+ let bary_u = 1.0 - su;+ let bary_v = sample_uv.y * su;+ let light_point = emitter.p0 + emitter.edge1 * bary_u + emitter.edge2 * bary_v;+ let diff = light_point - point.position;+ let dist_sq = dot(diff, diff);+ if (dist_sq <= 1.0e-16) {+ return out;+ }+ let dist = sqrt(dist_sq);+ let wi = diff / dist;+ let cos_light = abs(dot(emitter.geometric_normal, wi));+ if (cos_light <= 1.0e-8) {+ return out;+ }++ let mat = materials[emitter.material_index];+ let mis_enabled = (mat.flags & MATERIAL_FLAG_EMISSIVE_MIS) != 0u;+ let pdf_solid_angle = dist_sq / max(emitter.area * cos_light, 1.0e-20);++ out.valid = 1u;+ out.is_delta = select(1u, 0u, mis_enabled);+ out.wi = wi;+ out.distance = dist;+ out.radiance = emitter.radiance;+ out.pdf = emitter.selection_pdf * pdf_solid_angle;+ out.target_instance = emitter.instance_index;+ out.target_triangle = emitter.triangle_index;+ out.cast_shadow = 1u;+ return out;+}++fn lgt_direction_to_env_uv(direction: vec3<f32>, polar_out: ptr<function, f32>) -> vec2<f32> {+ let cosine = cos(kernel_params.env_rotation);+ let sine = sin(kernel_params.env_rotation);+ let map_x = cosine * direction.x - sine * direction.z;+ let map_z = sine * direction.x + cosine * direction.z;+ let u_raw = atan2(map_x, -map_z) * INV_TWO_PI + 0.5;+ let u_wrapped = u_raw - floor(u_raw);+ let polar = acos(clamp(direction.y, -1.0, 1.0));+ *polar_out = polar;+ return vec2<f32>(u_wrapped, polar * INV_PI);+}++fn lgt_env_uv_to_direction(uv: vec2<f32>, polar_out: ptr<function, f32>) -> vec3<f32> {+ let polar = uv.y * PI;+ let azimuth = (uv.x - 0.5) * TWO_PI;+ let sin_polar = sin(polar);+ let map_x = sin_polar * sin(azimuth);+ let map_z = -sin_polar * cos(azimuth);+ let cosine = cos(kernel_params.env_rotation);+ let sine = sin(kernel_params.env_rotation);+ *polar_out = polar;+ return vec3<f32>(+ cosine * map_x + sine * map_z,+ cos(polar),+ -sine * map_x + cosine * map_z,+ );+}++fn lgt_eval_hdri_radiance(direction: vec3<f32>) -> vec3<f32> {+ let width = kernel_params.env_width;+ let height = kernel_params.env_height;+ if (width == 0u || height == 0u) {+ return kernel_params.env_color;+ }+ var polar = 0.0;+ let uv = lgt_direction_to_env_uv(direction, &polar);+ let tex_x = uv.x * f32(width) - 0.5;+ let tex_y = uv.y * f32(height) - 0.5;+ let x0_f = floor(tex_x);+ let y0_f = floor(tex_y);+ let frac_x = tex_x - x0_f;+ let frac_y = tex_y - y0_f;+ let cols = i32(width);+ let rows = i32(height);++ var accum = vec3<f32>(0.0);+ for (var corner = 0u; corner < 4u; corner += 1u) {+ let dx = i32(corner & 1u);+ let dy = i32(corner >> 1u);+ let col = u32(((i32(x0_f) + dx) % cols + cols) % cols);+ let row = u32(clamp(i32(y0_f) + dy, 0, rows - 1));+ let weight_x = select(1.0 - frac_x, frac_x, dx == 1);+ let weight_y = select(1.0 - frac_y, frac_y, dy == 1);+ let texel = environment_texels[row * width + col].xyz;+ accum += texel * (weight_x * weight_y);+ }+ return accum * kernel_params.env_color;+}++fn lgt_environment_pdf(direction: vec3<f32>) -> f32 {+ let width = kernel_params.env_width;+ let height = kernel_params.env_height;+ if (width == 0u || height == 0u || kernel_params.background_mis_weight <= 0.0) {+ return 0.0;+ }+ var polar = 0.0;+ let uv = lgt_direction_to_env_uv(direction, &polar);+ let sin_polar = sin(polar);+ if (sin_polar <= 1.0e-8) {+ return 0.0;+ }+ let col = min(u32(floor(uv.x * f32(width))), width - 1u);+ let row = min(u32(floor(uv.y * f32(height))), height - 1u);+ let cdf_base = kernel_params.env_cdf_offset;+ let marginal_prob = environment_texels[cdf_base + row].y;+ let cond_prob = environment_texels[cdf_base + height + row * width + col].y;+ return (marginal_prob * cond_prob * f32(width * height)) / (TWO_PI * PI * sin_polar);+}++fn lgt_sample_environment(sample_u4: vec4<f32>) -> LgtDirectSample {+ var out = lgt_empty_sample();+ let width = kernel_params.env_width;+ let height = kernel_params.env_height;+ if (width == 0u || height == 0u || kernel_params.background_mis_weight <= 0.0) {+ return out;+ }+ let cdf_base = kernel_params.env_cdf_offset;+ let row = lgt_binary_search_env_cdf(cdf_base, height, sample_u4.x);+ let marginal_prob = environment_texels[cdf_base + row].y;+ if (marginal_prob <= 0.0) {+ return out;+ }+ let cond_base = cdf_base + height + row * width;+ let col = lgt_binary_search_env_cdf(cond_base, width, sample_u4.y);+ let cond_prob = environment_texels[cond_base + col].y;+ if (cond_prob <= 0.0) {+ return out;+ }++ let u_coord = (f32(col) + sample_u4.z) / f32(width);+ let v_coord = (f32(row) + sample_u4.w) / f32(height);+ var polar = 0.0;+ let wi = lgt_env_uv_to_direction(vec2<f32>(u_coord, v_coord), &polar);+ let sin_polar = sin(polar);+ if (sin_polar <= 1.0e-8) {+ return out;+ }++ let pdf_solid_angle = (marginal_prob * cond_prob * f32(width * height)) / (TWO_PI * PI * sin_polar);+ if (pdf_solid_angle <= 0.0) {+ return out;+ }++ out.valid = 1u;+ out.is_delta = 0u;+ out.wi = wi;+ out.distance = 1.0e30;+ out.radiance = lgt_eval_hdri_radiance(wi);+ out.pdf = pdf_solid_angle;+ out.cast_shadow = 1u;+ return out;+}++fn lgt_eval_analytic_lights_along_segment(+ ray_origin: vec3<f32>,+ ray_dir: vec3<f32>,+ t_min: f32,+ t_max: f32,+ is_camera_ray: bool,+ mis_skip: bool,+ prev_bsdf_pdf: f32,+ receiver_lo: u32,+ receiver_hi: u32,+ in_medium: bool,+ medium_sigma: vec3<f32>,+) -> vec3<f32> {+ let count = kernel_params.light_count;+ if (count == 0u) {+ return vec3<f32>(0.0);+ }+ var total = vec3<f32>(0.0);++ for (var index = 0u; index < count; index += 1u) {+ let light = lights[index];+ if (light.light_type == LIGHT_TYPE_SUN) {+ continue;+ }+ if (is_camera_ray) {+ if ((light.flags & LIGHT_FLAG_CAMERA_VISIBLE) == 0u) {+ continue;+ }+ } else {+ if ((light.flags & LIGHT_FLAG_MULTIPLE_IMPORTANCE) == 0u) {+ continue;+ }+ if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) {+ continue;+ }+ }++ if (light.light_type == LIGHT_TYPE_POINT || light.light_type == LIGHT_TYPE_SPOT) {+ if (light.radius <= 0.0) {+ continue;+ }+ let is_spot = light.light_type == LIGHT_TYPE_SPOT;+ if (is_spot && dot(ray_dir, ray_origin - light.position) >= 0.0) {+ continue;+ }+ var hit_t = 0.0;+ if (!lgt_ray_sphere_intersect(ray_origin, ray_dir, light.position, light.radius, &hit_t)) {+ continue;+ }+ if (hit_t <= t_min || hit_t >= t_max) {+ continue;+ }+ let falloff = lgt_range_falloff(hit_t, light.max_distance);+ if (falloff <= 0.0) {+ continue;+ }+ let to_center = light.position - ray_origin;+ let dist_sq = dot(to_center, to_center);+ var spot_weight = 1.0;+ if (is_spot && dist_sq > light.radius * light.radius) {+ spot_weight = lgt_spot_attenuation(light, -ray_dir);+ if (spot_weight <= 0.0) {+ continue;+ }+ }+ var pdf_solid_angle = lgt_sphere_solid_angle_pdf(dist_sq, light.radius, hit_t, ray_origin, ray_dir, light.position);+ if (is_spot && dist_sq > light.radius * light.radius) {+ let one_minus_cos_sphere = lgt_sin_sqr_to_one_minus_cos((light.radius * light.radius) / dist_sq);+ let one_minus_cos_spot = max(0.0, 1.0 - light.cos_half_angle);+ let one_minus_cos = min(one_minus_cos_sphere, one_minus_cos_spot);+ pdf_solid_angle = 1.0 / max(TWO_PI * one_minus_cos, 1.0e-30);+ }+ let pdf_nee = light.selection_pdf * pdf_solid_angle;+ let mis_weight = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);+ let medium_atten = select(vec3<f32>(1.0), exp(-medium_sigma * max(hit_t - t_min, 0.0)), in_medium);+ total += light.radiance * medium_atten * (spot_weight * falloff * mis_weight);+ continue;+ }++ if (light.light_type == LIGHT_TYPE_AREA_RECT || light.light_type == LIGHT_TYPE_AREA_DISK) {+ if (light.size_u <= 0.0 || light.size_v <= 0.0) {+ continue;+ }+ let light_normal = light.direction;+ let denom = dot(ray_dir, light_normal);+ if (denom >= -1.0e-8) {+ continue;+ }+ let hit_t = dot(light.position - ray_origin, light_normal) / denom;+ if (hit_t <= t_min || hit_t >= t_max) {+ continue;+ }+ let falloff = lgt_range_falloff(hit_t, light.max_distance);+ if (falloff <= 0.0) {+ continue;+ }+ var hit_point = ray_origin + ray_dir * hit_t;+ let in_plane = hit_point - light.position;+ let coord_u = dot(in_plane, light.axis_u) / light.size_u;+ let coord_v = dot(in_plane, light.axis_v) / light.size_v;++ var pdf_solid_angle = 0.0;+ if (light.light_type == LIGHT_TYPE_AREA_RECT) {+ if (abs(coord_u) > 0.5 || abs(coord_v) > 0.5) {+ continue;+ }+ pdf_solid_angle = lgt_area_rect_sample_or_pdf(+ ray_origin,+ light.position,+ light.axis_u,+ light.size_u,+ light.axis_v,+ light.size_v,+ vec2<f32>(0.0, 0.0),+ false,+ &hit_point,+ );+ } else {+ if (coord_u * coord_u + coord_v * coord_v > 0.25) {+ continue;+ }+ let ellipse_area = 0.25 * PI * light.size_u * light.size_v;+ let cos_light = max(-denom, 1.0e-8);+ pdf_solid_angle = (hit_t * hit_t) / max(ellipse_area * cos_light, 1.0e-20);+ }++ var spread_weight = 1.0;+ if (light.spread_normalization > 0.0) {+ spread_weight = lgt_area_spread_attenuation(ray_dir, light_normal, light.tan_half_spread, light.spread_normalization);+ if (spread_weight <= 0.0) {+ continue;+ }+ }+ let pdf_nee = light.selection_pdf * pdf_solid_angle;+ let mis_weight = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);+ let medium_atten = select(vec3<f32>(1.0), exp(-medium_sigma * max(hit_t - t_min, 0.0)), in_medium);+ total += light.radiance * medium_atten * (spread_weight * falloff * mis_weight);+ }+ }++ return total;+}++fn lgt_eval_escaped_ray(+ ray_dir: vec3<f32>,+ is_camera_ray: bool,+ is_transparent_background_ray: bool,+ mis_skip: bool,+ prev_bsdf_pdf: f32,+ receiver_lo: u32,+ receiver_hi: u32,+) -> vec3<f32> {+ var total = vec3<f32>(0.0);++ if (!is_transparent_background_ray) {+ let env_radiance = lgt_eval_hdri_radiance(ray_dir);+ var env_mis = 1.0;+ if (!is_camera_ray && !mis_skip && kernel_params.env_width > 0u && kernel_params.env_height > 0u && kernel_params.background_mis_weight > 0.0) {+ let pdf_env = lgt_environment_pdf(ray_dir);+ env_mis = lgt_power_heuristic(prev_bsdf_pdf, pdf_env);+ }+ total += env_radiance * env_mis;+ }++ let count = kernel_params.light_count;+ for (var index = 0u; index < count; index += 1u) {+ let light = lights[index];+ if (light.light_type != LIGHT_TYPE_SUN) {+ continue;+ }+ if (is_camera_ray) {+ if ((light.flags & LIGHT_FLAG_CAMERA_VISIBLE) == 0u) {+ continue;+ }+ } else {+ if ((light.flags & LIGHT_FLAG_MULTIPLE_IMPORTANCE) == 0u) {+ continue;+ }+ if (!lgt_links_match(receiver_lo, receiver_hi, light.light_group_mask_lo, light.light_group_mask_hi)) {+ continue;+ }+ }+ let one_minus_cos = lgt_sun_one_minus_cos(light);+ if (one_minus_cos <= 1.0e-12) {+ continue;+ }+ let to_sun = normalize(-light.direction);+ if (dot(ray_dir, to_sun) < 1.0 - one_minus_cos) {+ continue;+ }+ let pdf_nee = light.selection_pdf / max(TWO_PI * one_minus_cos, 1.0e-30);+ let sun_mis = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);+ total += light.radiance * sun_mis;+ }++ return total;+}++fn lgt_emissive_surface_weight(+ emissive_index: u32,+ hit_distance: f32,+ ray_dir: vec3<f32>,+ is_camera_ray: bool,+ mis_skip: bool,+ prev_bsdf_pdf: f32,+ receiver_lo: u32,+ receiver_hi: u32,+) -> f32 {+ if (emissive_index == INVALID_INDEX || emissive_index >= kernel_params.emissive_triangle_count) {+ return 1.0;+ }+ let emitter = emissive_triangles[emissive_index];+ if (!is_camera_ray) {+ if (!lgt_links_match(receiver_lo, receiver_hi, emitter.light_group_mask_lo, emitter.light_group_mask_hi)) {+ return 0.0;+ }+ }+ if (is_camera_ray || mis_skip || emitter.selection_pdf <= 0.0 || emitter.area <= 0.0) {+ return 1.0;+ }+ let mat = materials[emitter.material_index];+ if ((mat.flags & MATERIAL_FLAG_EMISSIVE_MIS) == 0u) {+ return 1.0;+ }+ let cos_light = abs(dot(emitter.geometric_normal, ray_dir));+ if (cos_light <= 1.0e-8) {+ return 0.0;+ }+ let pdf_nee = emitter.selection_pdf * (hit_distance * hit_distance) / max(emitter.area * cos_light, 1.0e-20);+ return lgt_power_heuristic(prev_bsdf_pdf, pdf_nee);+}diff --git a/packages/render-native/src/cycles/sampler.wgsl b/packages/render-native/src/cycles/sampler.wgslnew file mode 100644index 00000000..5e122b56--- /dev/null+++ b/packages/render-native/src/cycles/sampler.wgsl@@ -0,0 +1,87 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Stateless uncorrelated 4D PCG hash sampler (`smp_*`) for the Cycles-parity native kernel.++const SMP_UINT_TO_UNIT_FLOAT: f32 = 1.0 / 16777216.0;++struct SmpState {+ pixel_x: u32,+ pixel_y: u32,+ sample_index: u32,+ dimension: u32,+ seed: u32,+}++fn smp_pcg4d(input_words: vec4<u32>) -> vec4<u32> {+ var v = input_words * 1664525u + 1013904223u;+ v.x += v.y * v.w;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v.w += v.y * v.z;+ v = v ^ (v >> vec4<u32>(16u));+ v.x += v.y * v.w;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v.w += v.y * v.z;+ return v;+}++fn smp_word_to_unit_float(word: u32) -> f32 {+ return f32(word >> 8u) * SMP_UINT_TO_UNIT_FLOAT;+}++fn smp_draw_words(state: ptr<function, SmpState>) -> vec4<u32> {+ let dim = (*state).dimension;+ (*state).dimension = dim + 1u;+ let seed = (*state).seed;+ let raw = vec4<u32>(+ (*state).pixel_x ^ (seed * 0x9E3779B9u),+ (*state).pixel_y ^ (seed * 0x85EBCA6Bu + 0x7F4A7C15u),+ (*state).sample_index ^ (seed * 0xC2B2AE35u + 0x165667B1u),+ dim + (seed ^ 0x27D4EB2Fu),+ );+ return smp_pcg4d(raw);+}++fn smp_init(pixel_x: u32, pixel_y: u32, sample_index: u32, seed: u32) -> SmpState {+ var state: SmpState;+ state.pixel_x = pixel_x;+ state.pixel_y = pixel_y;+ state.sample_index = sample_index;+ state.dimension = 0u;+ state.seed = seed;+ return state;+}++fn smp_next_1d(state: ptr<function, SmpState>) -> f32 {+ let words = smp_draw_words(state);+ return smp_word_to_unit_float(words.x);+}++fn smp_next_2d(state: ptr<function, SmpState>) -> vec2<f32> {+ let words = smp_draw_words(state);+ return vec2<f32>(+ smp_word_to_unit_float(words.x),+ smp_word_to_unit_float(words.y),+ );+}++fn smp_next_3d(state: ptr<function, SmpState>) -> vec3<f32> {+ let words = smp_draw_words(state);+ return vec3<f32>(+ smp_word_to_unit_float(words.x),+ smp_word_to_unit_float(words.y),+ smp_word_to_unit_float(words.z),+ );+}++fn smp_next_4d(state: ptr<function, SmpState>) -> vec4<f32> {+ let words = smp_draw_words(state);+ return vec4<f32>(+ smp_word_to_unit_float(words.x),+ smp_word_to_unit_float(words.y),+ smp_word_to_unit_float(words.z),+ smp_word_to_unit_float(words.w),+ );+}