graphics3d/skinnedmodelrenderer
스킨드 모델 렌더러. (원본 graphics3d/skinnedmodelrenderer.js)
- 스키닝 PBR 셰이더 템플릿 + 환경 상태(섀도우 맵 / 태양 / 안개) 소유, 씬당 하나. SkinnedModel 은 데이터/포즈만 갖고, 렌더링은 이 객체가 모델 인스턴스를 받아 한다.
- 프래그먼트 셰이더 소스를 주입하면 같은 스키닝/모프 버텍스 경로 위에 다른 셰이딩 템플릿을 세울 수 있다. (파생 렌더러는 셰이더를 쓴 뒤 고유 유니폼을 설정하고 draw() 를 부른다)
- GLSL 은 원본과 같다. (쿡-토런스 GGX, 화면공간 미분 코탄젠트 노멀맵, 3x3 PCF 섀도우, 반구 앰비언트, 거리 안개) 원본 템플릿 문자열의 ${MORPH_GLSL} / ${MORPH_TARGET_MAXIMUM} 은 concat! 과 숫자 96 으로 옮겼다. (시험이 둘이 같은지 본다)
- 텍스처 유닛: 0 = base_color, 1 = 섀도우 맵, 2 ~ 8 = 머티리얼 슬롯, 15 = 모프 타깃 텍스처. 섀도우 맵이 없으면 섀도우 유닛에 1x1 비교 깊이 텍스처를 묶는다. (원본과 같다)
- 원본과 다른 것:
- 그리기 함수는 gl 과 &mut SkinnedModel 을 받는다. 바뀐 모프 타깃 업로드(원본 update 6단계)와 와이어프레임 인덱스 업로드를 여기서 먼저 한다. 행렬 인자는 원본 getElements() 처럼 &[f64; 16] 이다. (matrix.get_elements())
- set_shadow_map 은 원본처럼 배열을 참조로 들지 않고 16개를 복사해 둔다.
- 생성은 셰이더 컴파일 실패를 오류(Result)로 돌려준다.
Skinned model renderer. (the original graphics3d/skinnedmodelrenderer.js)
- Owns the skinning PBR shader template + environment state (shadow map / sun / fog), one per scene. SkinnedModel holds only data/pose, and this object does the rendering, taking a model instance.
- Injecting fragment shader source lets you build another shading template on the same skinning/morph vertex path. (a derived renderer sets its own uniforms after using the shader and calls draw())
- The GLSL is the same as the original. (Cook-Torrance GGX, screen space derivative cotangent normal map, 3x3 PCF shadow, hemisphere ambient, distance fog) ${MORPH_GLSL} / ${MORPH_TARGET_MAXIMUM} in the original template string are ported as concat! and the number 96. (a test checks that the two match)
- Texture units: 0 = base_color, 1 = shadow map, 2 ~ 8 = material slots, 15 = morph target texture. Without a shadow map, a 1x1 comparison depth texture is bound to the shadow unit. (same as the original)
- Differences from the original:
- Draw functions take gl and &mut SkinnedModel. Uploading changed morph targets (step 6 of the original update) and wireframe indices is done here first. Matrix arguments are &[f64; 16] like the original getElements(). (matrix.get_elements())
- set_shadow_map copies 16 values instead of holding the array by reference like the original.
- Creation returns shader compile failure as an error (Result).
SkinnedModelRendererstruct
스킨드 모델 렌더러.
Skinned model renderer.
use vanilla::{Graphic, Matrix4, SkinnedModel, SkinnedModelRenderer, Vector3};
fn create_renderer(graphic: &Graphic) -> Result<SkinnedModelRenderer, String> {
let mut skinned_model_renderer = SkinnedModelRenderer::new(graphic.get_gl(), None, None)?;
let sun_direction = Vector3::create(0.5, 0.8, 0.35).normalize();
skinned_model_renderer.set_sun_direction(sun_direction.x, sun_direction.y, sun_direction.z);
skinned_model_renderer.set_fog_color(0.62, 0.72, 0.86);
skinned_model_renderer.set_fog_range(25.0, 80.0);
Ok(skinned_model_renderer)
}
fn draw_model(graphic: &mut Graphic, skinned_model_renderer: &SkinnedModelRenderer, skinned_model: &mut SkinnedModel) {
graphic.flush_batch();
let aspect_ratio = graphic.get_drawing_buffer_width() as f64 / graphic.get_drawing_buffer_height().max(1) as f64;
let camera_position = Vector3::create(0.0, 1.6, 4.0);
let mut view_projection_matrix = Matrix4::create_perspective(std::f64::consts::PI / 3.0, aspect_ratio, 0.1, 100.0);
view_projection_matrix.multiply(&Matrix4::create_look_at(camera_position, Vector3::create(0.0, 1.0, 0.0), Vector3::up()));
let model_matrix = Matrix4::create_identity();
let gl = graphic.get_gl();
unsafe {
gl.enable(glow::DEPTH_TEST);
gl.clear(glow::DEPTH_BUFFER_BIT);
}
skinned_model_renderer.draw(gl, skinned_model, view_projection_matrix.get_elements(), model_matrix.get_elements(), camera_position.x, camera_position.y, camera_position.z);
graphic.restore_render_state();
}
pub fn new(gl: &GlContext, fragment_shader_source: Option<&str>, vertex_shader_source: Option<&str>) -> Result<SkinnedModelRenderer, String>#생성. (대체 프래그먼트 / 버텍스 셰이더 소스, None 이면 기본 PBR / 기본 스키닝)
- 대체 버텍스 셰이더는 같은 어트리뷰트 위치 / 출력 규약을 지켜야 한다.
Constructor. (replacement fragment / vertex shader source, default PBR / default skinning when None)
- A replacement vertex shader must follow the same attribute location / output conventions.
- gl&GlContext
- GL 컨텍스트.GL context.
- fragment_shader_sourceOption<&str>
- 대체 프래그먼트 셰이더 소스. (GLSL ES 3.0, None 이면 기본 PBR)Replacement fragment shader source. (GLSL ES 3.0, None uses the default PBR)
- vertex_shader_sourceOption<&str>
- 대체 버텍스 셰이더 소스. (None 이면 기본 스키닝)Replacement vertex shader source. (None uses the default skinning)
반환ReturnsResult<SkinnedModelRenderer, String> 새 렌더러. (그림자 강도 0, 태양 방향 (0, 1, 0), 안개 색 (0.8, 0.85, 0.92), 안개 거리 55 ~ 250) 셰이더 컴파일이나 링크, 빈 그림자 텍스처 만들기에 실패하면 Err.A new renderer. (shadow strength 0, sun direction (0, 1, 0), fog color (0.8, 0.85, 0.92), fog distance 55 ~ 250) Err if shader compilation or linking, or creating the empty shadow texture fails.
짝Counterpart: vanilla.js SkinnedModelRenderer.constructor
use vanilla::SkinnedModelRenderer;
const FLAT_FRAGMENTSHADER_SOURCE: &str = "#version 300 es
precision highp float;
out vec4 outputColor;
void main() {
outputColor = vec4(1.0, 0.5, 0.2, 1.0);
}";
fn create_flat_renderer(gl: &vanilla::GlContext) -> Result<SkinnedModelRenderer, String> {
SkinnedModelRenderer::new(gl, Some(FLAT_FRAGMENTSHADER_SOURCE), None)
}뼈 행렬 올리기. (JointBlock 유니폼 블록, 프로그램은 ShaderProgram 이 링크 뒤에 같은 바인딩 자리로 묶는다, 원본 uploadJointMatrices)
Upload joint matrices. (JointBlock uniform block; ShaderProgram binds the program to the same binding point after linking; original uploadJointMatrices)
- gl&GlContext
- GL 컨텍스트.GL context.
- joint_matrix_array&[f32]
- 뼈 행렬의 수. (16 의 배수)Number of joint matrices. (a multiple of 16)
짝Counterpart: vanilla.js SkinnedModelRenderer.uploadJointMatrices
pub fn draw(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16], camera_x: f64, camera_y: f64, camera_z: f64)#출력. (모델 인스턴스의 드로어블 순회, 머티리얼 적용 + 조인트 행렬 업로드)
- 깊이 테스트 / 컬링 / 블렌드 / 프레임버퍼는 호출자가 잡는다. (원본과 같다)
Draw. (iterates the model instance's drawables, applies materials + uploads joint matrices)
- Depth test / culling / blend / framebuffer are set by the caller. (same as the original)
- gl&GlContext
- GL 컨텍스트.GL context.
- skinned_model&mut SkinnedModel
- 그릴 모델. (바뀐 모프 타깃을 먼저 올린다)Model to draw. (changed morph targets are uploaded first)
- view_projection_elements&[f32; 16]
- 뷰 x 투영 행렬. (열 우선 16개, matrix.get_elements())View x projection matrix. (16 column-major values, matrix.get_elements())
- model_matrix_elements&[f32; 16]
- 모델 행렬. (열 우선 16개)Model matrix. (16 column-major values)
- camera_xf64
- 카메라 월드 X. (정반사와 안개 거리에 쓴다)Camera world X. (used for specular reflection and fog distance)
- camera_yf64
- 카메라 월드 Y.Camera world Y.
- camera_zf64
- 카메라 월드 Z.Camera world Z.
짝Counterpart: vanilla.js SkinnedModelRenderer.draw
pub fn draw_depth(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, light_view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16])#깊이 패스 출력. (섀도우 맵 캐스팅, ShadowMap.begin_render() 이후 호출)
Draws the depth pass. (shadow map casting, call after ShadowMap.begin_render())
- gl&GlContext
- GL 컨텍스트.GL context.
- skinned_model&mut SkinnedModel
- 그림자를 드리울 모델. (바뀐 모프 타깃을 먼저 올린다)Model that casts the shadow. (uploads changed morph targets first)
- light_view_projection_elements&[f32; 16]
- 빛의 뷰 x 투영 행렬. (열 우선 16개, ShadowMap::get_light_view_projection_matrix)Light view x projection matrix. (16 column-major values, ShadowMap::get_light_view_projection_matrix)
- model_matrix_elements&[f32; 16]
- 모델 행렬. (열 우선 16개)Model matrix. (16 column-major values)
짝Counterpart: vanilla.js SkinnedModelRenderer.drawDepth
use vanilla::{Matrix4, ShadowMap, SkinnedModel, SkinnedModelRenderer, Vector3};
fn draw_with_shadow(gl: &vanilla::GlContext, skinned_model_renderer: &mut SkinnedModelRenderer, shadow_map: &mut ShadowMap, skinned_model: &mut SkinnedModel, view_projection_matrix: &Matrix4, camera_position: Vector3, drawing_buffer_width: i32, drawing_buffer_height: i32) {
let model_matrix = Matrix4::create_identity();
let sun_direction = Vector3::create(0.5, 0.8, 0.35).normalize();
shadow_map.update_light_matrix(Vector3::zero(), sun_direction.multiply_scalar(-1.0), 4.0, 0.5, 30.0);
let light_view_projection_elements = *shadow_map.get_light_view_projection_matrix().get_elements();
shadow_map.begin_render(gl);
skinned_model_renderer.draw_depth(gl, skinned_model, &light_view_projection_elements, model_matrix.get_elements());
skinned_model_renderer.set_shadow_map(Some(shadow_map.get_depth_texture()), Some(&light_view_projection_elements), 1.0 / shadow_map.get_resolution() as f64);
skinned_model_renderer.set_shadow_strength(1.0);
skinned_model_renderer.set_sun_direction(sun_direction.x, sun_direction.y, sun_direction.z);
unsafe {
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
gl.viewport(0, 0, drawing_buffer_width, drawing_buffer_height);
gl.clear(glow::DEPTH_BUFFER_BIT);
}
skinned_model_renderer.draw(gl, skinned_model, view_projection_matrix.get_elements(), model_matrix.get_elements(), camera_position.x, camera_position.y, camera_position.z);
}pub fn draw_wireframe(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16], red: f64, green: f64, blue: f64, alpha: f64)#와이어프레임 출력. (모서리 선, 모프 / 스키닝 반영, 블렌드 / 깊이 상태는 호출자가 잡는다)
- 드로어블 버텍스 어레이의 엘리먼트 버퍼를 잠시 선 인덱스로 바꿔 그리고 원래 인덱스로 되돌린다.
Draws the wireframe. (edge lines, reflects morph / skinning, the caller sets blend / depth state)
- Temporarily swaps the drawable vertex array's element buffer to line indices, draws, and restores the original indices.
- gl&GlContext
- GL 컨텍스트.GL context.
- skinned_model&mut SkinnedModel
- 그릴 모델. (선 인덱스가 없는 드로어블은 여기서 먼저 올린다)Model to draw. (drawables without line indices are uploaded here first)
- view_projection_elements&[f32; 16]
- 뷰 x 투영 행렬. (열 우선 16개)View x projection matrix. (16 column-major values)
- model_matrix_elements&[f32; 16]
- 모델 행렬. (열 우선 16개)Model matrix. (16 column-major values)
- redf64
- 선 색 빨강. (0 ~ 1)Line color red. (0 ~ 1)
- greenf64
- 선 색 초록. (0 ~ 1)Line color green. (0 ~ 1)
- bluef64
- 선 색 파랑. (0 ~ 1)Line color blue. (0 ~ 1)
- alphaf64
- 선 불투명도. (0 ~ 1, 블렌드를 켜야 반투명이 된다)Line opacity. (0 ~ 1, blending must be on for translucency)
짝Counterpart: vanilla.js SkinnedModelRenderer.drawWireframe
pub fn apply_morph_uniforms(&self, gl: &GlContext, shader_program: &ShaderProgram, drawable: &Drawable)#모프 유니폼 적용. (드로어블의 모프 텍스처/가중치, 타깃이 없으면 개수 0 으로 비활성)
Applies morph uniforms. (drawable's morph texture/weights, disabled with count 0 if there are no targets)
- gl&GlContext
- GL 컨텍스트.GL context.
- shader_program&ShaderProgram
- 유니폼을 넣을 셰이더. (지금 쓰는 프로그램)Shader to set the uniforms on. (the program currently in use)
- drawable&Drawable
- 모프 상태를 읽을 드로어블.Drawable to read the morph state from.
짝Counterpart: vanilla.js SkinnedModelRenderer.applyMorphUniforms
pub fn set_shadow_map(&mut self, shadow_map_texture: Option<GlTexture>, light_view_projection_elements: Option<&[f32; 16]>, texel_size: f64)#섀도우 맵 설정. (본 패스에서 그림자 수신, 행렬은 복사해 둔다)
Sets the shadow map. (receives shadows in the main pass, the matrix is copied)
- shadow_map_textureOption<GlTexture>
- 섀도우 맵 깊이 텍스처. (None 이면 그림자를 받지 않는다)Shadow map depth texture. (None means no shadows are received)
- light_view_projection_elementsOption<&[f32; 16]>
- 빛의 뷰 x 투영 행렬. (16개를 복사해 둔다, None 이면 그림자를 받지 않는다)Light view x projection matrix. (the 16 values are copied, None means no shadows are received)
- texel_sizef64
- 섀도우 맵 텍셀 크기. (1 / 해상도, PCF 표본 간격, 기본 1 / 2048)Shadow map texel size. (1 / resolution, PCF sample spacing, default 1 / 2048)
짝Counterpart: vanilla.js SkinnedModelRenderer.setShadowMap
그림자 강도 설정. (0 = 수신 안 함)
Sets the shadow strength. (0 = no receiving)
- shadow_strengthf64
- 그림자 강도. (0 ~ 1, 0 이면 받지 않는다, 기본 0)Shadow strength. (0 ~ 1, 0 means no shadows are received, default 0)
짝Counterpart: vanilla.js SkinnedModelRenderer.setShadowStrength
태양 방향 설정.
Sets the sun direction.
- xf64
- 태양 쪽을 가리키는 방향 X. (셰이더가 정규화한다, 기본 (0, 1, 0))Direction X pointing toward the sun. (normalized by the shader, default (0, 1, 0))
- yf64
- 방향 Y.Direction Y.
- zf64
- 방향 Z.Direction Z.
짝Counterpart: vanilla.js SkinnedModelRenderer.setSunDirection
안개 색 설정.
Sets the fog color.
- redf64
- 빨강. (0 ~ 1)Red. (0 ~ 1)
- greenf64
- 초록. (0 ~ 1)Green. (0 ~ 1)
- bluef64
- 파랑. (0 ~ 1)Blue. (0 ~ 1)
짝Counterpart: vanilla.js SkinnedModelRenderer.setFogColor
안개 거리 범위 설정.
Sets the fog distance range.
- start_distancef64
- 안개가 끼기 시작하는 카메라 거리. (월드 단위, 기본 55)Camera distance where fog begins. (world units, default 55)
- end_distancef64
- 안개가 다 덮는 카메라 거리. (월드 단위, 기본 250, 사이는 smoothstep)Camera distance at which fog covers fully. (world units, default 250, smoothstep in between)
짝Counterpart: vanilla.js SkinnedModelRenderer.setFogRange
빈 그림자 텍스처 반환. (그림자를 받지 않을 때 섀도우 유닛에 묶는 1x1 비교 깊이 텍스처, 파생 렌더러가 같이 쓴다)
Returns the empty shadow texture. (1x1 comparison depth texture bound to the shadow unit when not receiving shadows, shared by derived renderers)
반환ReturnsGlTexture 1x1 비교 깊이 텍스처. (렌더러가 들고 있으니 지우지 않는다)1x1 comparison depth texture. (held by the renderer, so do not delete it)
짝Counterpart: vanilla.js SkinnedModelRenderer.getEmptyShadowTexture
셰이더 프로그램 반환. (스키닝 PBR 템플릿, 모델과 머티리얼이 나눠 든다)
Returns the shader program. (the skinning PBR template, shared by models and materials)
반환ReturnsRc<ShaderProgram> 셰이더 프로그램. (Rc 를 복제해 준다)Shader program. (returns a clone of the Rc)
짝Counterpart: vanilla.js SkinnedModelRenderer.getShaderProgram
깊이 셰이더 프로그램 반환.
Returns the depth shader program.
반환Returns&ShaderProgram 깊이 패스 셰이더 프로그램. (draw_depth 가 쓴다)Depth pass shader program. (used by draw_depth)
짝Counterpart: vanilla.js SkinnedModelRenderer.getDepthShaderProgram
와이어프레임 셰이더 프로그램 반환.
Returns the wireframe shader program.
반환Returns&ShaderProgram 와이어프레임 셰이더 프로그램. (draw_wireframe 이 쓴다)Wireframe shader program. (used by draw_wireframe)
짝Counterpart: vanilla.js SkinnedModelRenderer.getWireframeShaderProgram
상수Constants
모프 타깃 텍스처 유닛. (머티리얼 슬롯 0 / 2~8, 섀도우 맵 1, 추가 슬롯 9~ 와 겹치지 않는 값)
Morph target texture unit. (a value that does not overlap material slots 0 / 2~8, shadow map 1, or extra slots 9~)
반환Returnsu32
모프 타깃 GLSL. (원본 MORPH_GLSL, 파생 렌더러가 대체 버텍스 셰이더에 넣어 쓴다)
Morph target GLSL. (the original MORPH_GLSL, derived renderers put it into their replacement vertex shaders)
반환Returns&str
짝Counterpart: vanilla.js MORPH_GLSL
스키닝 버텍스 셰이더. (모프 타깃 → 조인트 4개 가중 혼합, 어트리뷰트 위치 고정)
Skinning vertex shader. (morph targets → weighted blend of 4 joints, fixed attribute locations)
반환Returns&str
스키닝 프래그먼트 셰이더. (metallic-roughness PBR + 태양/반구 라이팅 + 섀도우 맵 + 거리 안개)
- 노멀 매핑은 화면 공간 미분 기반 코탄젠트 프레임 사용. (탄젠트 어트리뷰트 불필요)
- FBX 스펙큘러/글로스 경로: use_glossiness=1 이면 러프니스 = 1 - 글로스, 스펙큘러 맵은 F0 변조.
Skinning fragment shader. (metallic-roughness PBR + sun/hemisphere lighting + shadow map + distance fog)
- Normal mapping uses a cotangent frame based on screen-space derivatives. (no tangent attribute needed)
- FBX specular/gloss path: when use_glossiness=1, roughness = 1 - gloss, and the specular map modulates F0.
반환Returns&str