# graphics3d/subsurfacescatteringeffect (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/graphics3d/subsurfacescatteringeffect/

화면 공간 서브서피스 스캐터링. (원본 graphics3d/subsurfacescatteringeffect.js)
- 분리형, 확산 조도 버퍼를 깊이 인식 가로/세로 블러. 피부 확산 프로파일(가우시안 합)로 채널별 커널을 만들고,
  산란 폭(월드 단위)을 깊이에 맞춰 화면에 투영한다.
- render() 입력은 알파에 산란 마스크를 담은 조도 텍스처와 같은 패스의 깊이 텍스처. 결과는 get_result_texture().
- GLSL, 커널 식, 기본값(산란 폭 0.2, 폴오프 (1, 0.37, 0.3), 강도 (0.48, 0.41, 0.28))은 원본과 같다.
  원본 ${KERNEL_SAMPLE_COUNT} / ${KERNEL_RANGE} 는 숫자 17 / 3 으로 옮겼다.
- GL 을 쓰는 함수는 gl 을 받고, 생성과 크기 변경은 GL 객체를 못 만들면 오류(Result)를 돌려준다.

## SubsurfaceScatteringEffect (struct)

화면 공간 서브서피스 스캐터링.

예제: 피부 MRT 패스의 조도(0 번 어태치먼트)를 깊이에 맞춰 흩기

```rust
use vanilla::{Camera3D, RenderTarget, SubsurfaceScatteringEffect};

fn create_scattering(gl: &vanilla::GlContext) -> Result<SubsurfaceScatteringEffect, String> {
	let mut subsurface_scattering_effect = SubsurfaceScatteringEffect::new(gl)?;
	subsurface_scattering_effect.set_scatter_width(0.015);
	Ok(subsurface_scattering_effect)
}

fn render_scattering(gl: &vanilla::GlContext, subsurface_scattering_effect: &mut SubsurfaceScatteringEffect, scene_render_target: &RenderTarget, camera: &Camera3D) -> Result<(), String> {
	subsurface_scattering_effect.resize(gl, scene_render_target.get_width(), scene_render_target.get_height())?;
	subsurface_scattering_effect.render(gl, scene_render_target.get_color_texture(0), scene_render_target.get_depth_texture(), camera.get_field_of_view(), camera.get_aspect_ratio(), camera.get_near_distance(), camera.get_far_distance());
	let scattered_irradiance_texture = subsurface_scattering_effect.get_result_texture();
	assert!(scattered_irradiance_texture.is_some());
	Ok(())
}
```

- `pub fn new(gl: &GlContext) -> Result<SubsurfaceScatteringEffect, String>` (constructor, since 0.3.2): 생성. (패스 1개 + 반정밀 실수 타겟 2장, resize 로 크기를 맞춘다)
  - `gl` &GlContext: GL 컨텍스트. (Graphic::get_gl 로 꺼낸다)
  - returns Result<SubsurfaceScatteringEffect, String>: 새 이펙트. (산란 폭 0.2, 폴오프 (1, 0.37, 0.3), 강도 (0.48, 0.41, 0.28), 커널까지 셈한 것) 셰이더 컴파일이나 판 만들기에 실패하면 Err(오류 글).
- `pub fn compute_kernel(&mut self)` (method, since 0.3.2): 커널 계산. (피부 확산 프로파일을 오프셋 구간 넓이로 적분, 중앙 샘플을 0번에)
- `pub fn build_kernel(falloff_color: [f64; 3], strength_color: [f64; 3]) -> [f32; KERNEL_SAMPLE_COUNT * 4]` (static, since 0.3.2): 커널 만들기. (GL 무관, 표본마다 rgb 가중치 + w 오프셋)
  - `falloff_color` [f64; 3]: 채널별 폴오프. (r, g, b, 클수록 그 채널이 멀리 퍼진다)
  - `strength_color` [f64; 3]: 채널별 강도. (r, g, b, 0 이면 그 채널은 흩지 않고 중앙만 1)
  - returns [f32; KERNEL_SAMPLE_COUNT * 4]: 표본 KERNEL_SAMPLE_COUNT(17) 개의 r 가중, g 가중, b 가중, 오프셋을 차례로 이은 배열. (0 번이 중앙이고 오프셋 0, 채널마다 가중치 합 1, 오프셋은 -3 ~ 3)

  예제: 피부 기본 프로파일의 커널은 채널마다 합이 1 이고, 강도 0 이면 중앙만 남는다

  ```rust
  use vanilla::graphics3d::subsurfacescatteringeffect::KERNEL_SAMPLE_COUNT;
  use vanilla::SubsurfaceScatteringEffect;
  
  let kernel = SubsurfaceScatteringEffect::build_kernel([1.0, 0.37, 0.3], [0.48, 0.41, 0.28]);
  for channel_index in 0..3 {
  	let weight_sum: f64 = (0..KERNEL_SAMPLE_COUNT).map(|sample_index| kernel[sample_index * 4 + channel_index] as f64).sum();
  	assert!((weight_sum - 1.0).abs() < 1.0e-5);
  }
  assert_eq!(kernel[3], 0.0);
  
  let identity_kernel = SubsurfaceScatteringEffect::build_kernel([1.0, 0.37, 0.3], [0.0, 0.0, 0.0]);
  assert_eq!(identity_kernel[0], 1.0);
  assert_eq!(identity_kernel[4], 0.0);
  ```

- `pub fn resize(&mut self, gl: &GlContext, width: i32, height: i32) -> Result<(), String>` (method, since 0.3.2): 크기 변경. (조도 버퍼 해상도 기준, 전체 해상도 실수 타겟 2장)
  - `gl` &GlContext: GL 컨텍스트.
  - `width` i32: 조도 버퍼 가로 크기. (픽셀, 판도 같은 크기)
  - `height` i32: 조도 버퍼 세로 크기. (픽셀, 판도 같은 크기)
  - returns Result<(), String>: 판을 맞췄으면 Ok. 다시 짓다 GL 객체를 못 만들면 Err(GL 의 오류 글).
- `pub fn render(&self, gl: &GlContext, irradiance_texture: Option<GlTexture>, depth_texture: Option<GlTexture>, field_of_view_radian: f64, aspect_ratio: f64, near_distance: f64, far_distance: f64)` (method, since 0.3.2): 산란 렌더링. (가로 → 핑, 세로 → 퐁, 결과는 get_result_texture())
  - 부수 효과: 깊이/블렌드 비활성, TEXTURE0 활성, 프레임버퍼 바인드가 변경된다.
  - 깊이 텍스처는 1 번 유닛에 묶었다가 끝에 풀어 둔다. (1 번은 섀도우 샘플러 자리)
  - `gl` &GlContext: GL 컨텍스트.
  - `irradiance_texture` Option<GlTexture>: 확산 조도 텍스처. (rgb 조도, a 산란 마스크, 마스크가 0.001 밑인 곳은 그대로 둔다)
  - `depth_texture` Option<GlTexture>: 같은 패스의 깊이 텍스처. (하드웨어 깊이 0 ~ 1)
  - `field_of_view_radian` f64: 세로 시야각. (라디안, 산란 폭을 화면에 투영할 때)
  - `aspect_ratio` f64: 가로 세로 비. (너비 / 높이, 가로 걸음을 보정한다)
  - `near_distance` f64: 투영의 가까운 거리. (깊이를 선형으로 풀 때)
  - `far_distance` f64: 투영의 먼 거리.
- `pub fn get_result_texture(&self) -> Option<GlTexture>` (method, since 0.3.2): 결과 텍스처 반환. (render() 이후)
  - returns Option<GlTexture>: 흩은 조도 텍스처. (퐁 판, a 에 산란 마스크) destroy 뒤면 None.
- `pub fn set_scatter_width(&mut self, scatter_width: f64)` (method, since 0.3.2): 산란 폭 설정. (월드 단위, 커널 전체 반경)
  - `scatter_width` f64: 산란 폭. (월드 단위, 기본 0.2, 화면에 투영한 폭은 화면 높이의 0.05 를 넘지 않게 셰이더가 자른다)
- `pub fn get_scatter_width(&self) -> f64` (method, since 0.3.2): 산란 폭 반환.
  - returns f64: 산란 폭. (월드 단위)
- `pub fn set_profile(&mut self, falloff_color: [f64; 3], strength_color: [f64; 3])` (method, since 0.3.2): 확산 프로파일 설정. (채널별 폴오프 / 강도, 피부 기본 (1, 0.37, 0.3) / (0.48, 0.41, 0.28))
  - 커널을 바로 다시 셈한다.
  - `falloff_color` [f64; 3]: 채널별 폴오프. (r, g, b, 클수록 그 채널이 멀리 퍼진다)
  - `strength_color` [f64; 3]: 채널별 강도. (r, g, b, 0 이면 그 채널은 흩지 않는다)
- `pub fn get_falloff_color(&self) -> [f64; 3]` (method, since 0.3.2): 폴오프 색 반환.
  - returns [f64; 3]: 채널별 폴오프. (r, g, b)
- `pub fn get_strength_color(&self) -> [f64; 3]` (method, since 0.3.2): 강도 색 반환.
  - returns [f64; 3]: 채널별 강도. (r, g, b)
- `pub fn destroy(&mut self, gl: &GlContext)` (method, since 0.3.2): 파괴. (GL 리소스 해제)
  - `gl` &GlContext: 만들 때 쓴 GL 컨텍스트.
- `pub fn get_scatter_pass(&self) -> &FullscreenPass` (method, since 0.3.2): 산란 패스 반환.
  - returns &FullscreenPass: 산란 패스. (가로, 세로 둘 다 이 패스)
- `pub fn get_ping_render_target(&self) -> &RenderTarget` (method, since 0.3.2): 핑 렌더 타겟 반환. (가로 블러 결과)
  - returns &RenderTarget: 핑 렌더 타겟. (가로 산란 결과)
- `pub fn get_pong_render_target(&self) -> &RenderTarget` (method, since 0.3.2): 퐁 렌더 타겟 반환. (최종 결과 보관)
  - returns &RenderTarget: 퐁 렌더 타겟. (세로 산란 결과, 결과 텍스처의 주인)

## Functions and constants

- `pub const KERNEL_SAMPLE_COUNT: usize = 17` (field, since 0.3.2): 커널 샘플 수. (중앙 1 + 양측, 홀수, 셰이더의 17 과 같아야 한다)
  - returns usize
- `pub const KERNEL_RANGE: f64 = 3.0` (field, since 0.3.2): 커널 오프셋 범위. (확산 프로파일 단위, 셰이더에서 산란 폭으로 정규화, 셰이더의 3 과 같아야 한다)
  - returns f64
