core/graphic
그래픽.
- GL 컨텍스트로 출력하는 렌더러. 원본(WebGL2)과 같은 셰이더와 같은 상태 모델을 쓴다.
- Canvas2D 시절의 좌표계(좌상 원점, 픽셀 단위)와 상태 모델(변환/알파 스택)을 그대로 재현한다.
- 모든 드로우는 draw_vertices() 한 지점으로 수렴한다. 단색 도형도 1x1 흰색 텍스처로 텍스처 경로와 통일.
- 클리핑은 스텐실 버퍼 기반. 텍스트는 문자열 텍스처로 구워 출력.
- 묶어 그리기(기본 켬): 같은 텍스처를 잇달아 그리면 정점을 CPU 에서 변환해 모았다가 한 번에 그린다. 원본과 같은 묶음 셰이더로 정점마다 색과 틴트를 실어, 틴트가 걸린 그리기도 묶는다. 클립 영역 기록은 묶지 않는다. 블렌드, 클립, 파티클 그리기, 프레임 끝에서 모은 것을 먼저 내보낸다(flush_batch). 원본도 기본으로 켠다. (setSpriteBatchingEnabled)
- 화면 밖 거르기(기본 켬): NodeTree 가 노드를 그리기 전에 is_local_rect_visible 로 묻는다. 원본도 기본으로 켜고 WorldNode 가 같은 함수로 묻는다. (setCullingEnabled)
- 셰이더 바꿔 끼우기(set_shader_program_override): ShaderSprite 같은 효과가 기본 프로그램 대신 제 프로그램으로 그린다. 바꿔 끼운 동안은 묶지 않는다. 바꿔 끼울 프로그램은 resolve_shader_program 이 이름으로 담아 두고, 어트리뷰트 위치를 기본 프로그램과 같게 고정해 기본 버텍스 어레이를 같이 쓴다.
- 마지막으로 건 셰이더 프로그램과 텍스처 유닛 0 의 텍스처를 기억해, 같은 것을 다시 거는 GL 호출을 건너뛴다. (원본도 같다) GL 을 밖에서 만질 수 있는 때(get_gl 로 컨텍스트를 내줄 때, restore_render_state, 프레임 시작과 끝)에는 잊고 다음에 다시 건다.
- 밉맵 단계 보정(set_image_mipmap_bias)은 기본, 묶음, 파티클 셰이더의 textureLodBias 유니폼으로 건다. 바꿔 끼운 셰이더는 그 유니폼이 있으면 받는다. (원본과 같음)
- 글자 방향(set_text_direction, 원본 setTextDirection)은 상태에 들고, 구운 문자열을 그 문단 방향으로 모양 짓는다. (textshaping.rs 의 양방향 정렬과 모양 짓기)
- 블렌드 모드 26 가지(원본과 같음): 13 가지는 고정 블렌딩, 13 가지는 그릴 영역 아래를 지금 프레임버퍼에서 blit_framebuffer 로 떠 와 W3C 공식대로 셰이더로 섞는다. Multiply 는 기본 프레임버퍼에서는 고정 블렌딩, 렌더 타겟에 그릴 때는 셰이더로 섞는다. (바탕이 반투명하면 고정 블렌딩이 W3C 식과 달라서, 원본과 같음) 셰이더 글은 원본과 한 글자도 다르지 않다. 바꿔 끼운 셰이더는 덧그림 칸(데스크탑은 늘 RGBA16F, 웹은 원본처럼 EXT_color_buffer_float 가 있을 때 RGBA16F)에 먼저 그리고 섞어 옮긴다.
- 기본 프레임버퍼에 그릴 때는 알파를 쓰지 않는다(apply_color_mask). 원본과 웹은 캔버스가 alpha: false 라 화면 알파가 늘 1 인데, 데스크탑 기본 프레임버퍼는 알파가 있어 알파를 낮추는 모드 뒤에 DST_ALPHA 를 쓰는 모드와 셰이더 섞기가 웹과 달랐다. 렌더 타겟에는 알파도 쓴다.
Graphics.
- A renderer that draws to a GL context. Uses the same shaders and the same state model as the original (WebGL2).
- Reproduces the coordinate system (top-left origin, pixel units) and state model (transform/alpha stack) of the Canvas2D days as is.
- All draws converge on one point, draw_vertices(). Solid shapes also use a 1x1 white texture to unify with the texture path.
- Clipping is based on the stencil buffer. Text is baked into string textures and drawn.
- Batching (on by default): consecutive draws with the same texture have their vertices transformed on the CPU, gathered, and drawn at once. With the same batch shader as the original, color and tint go with each vertex, so tinted draws are batched too. Clip region recording is not batched. Blends, clips, particle draws and the end of the frame flush what has been gathered first (flush_batch). The original also turns it on by default. (setSpriteBatchingEnabled)
- Offscreen culling (on by default): NodeTree asks is_local_rect_visible before drawing a node. The original also turns it on by default and WorldNode asks with the same function. (setCullingEnabled)
- Shader override (set_shader_program_override): effects such as ShaderSprite draw with their own program instead of the default one. No batching while overridden. resolve_shader_program keeps the override programs by name and fixes their attribute locations to match the default program so they share the default vertex array.
- Remembers the last bound shader program and the texture of texture unit 0, and skips GL calls that bind the same thing again. (same as the original) When GL can be touched from outside (when handing out the context with get_gl, restore_render_state, frame start and end), it forgets them and binds again next time.
- The mipmap level bias (set_image_mipmap_bias) is applied through the textureLodBias uniform of the default, batch and particle shaders. An override shader receives it if it has that uniform. (same as the original)
- Text direction (set_text_direction, the original setTextDirection) is held in the state, and baked strings are shaped in that paragraph direction. (bidirectional ordering and shaping in textshaping.rs)
- 26 blend modes (same as the original): 13 use fixed blending, and 13 grab what is under the draw area from the current framebuffer with blit_framebuffer and mix it in a shader following the W3C formulas. Multiply uses fixed blending on the default framebuffer and shader mixing when drawing to a render target. (fixed blending differs from the W3C formula when the backdrop is translucent, same as the original) The shader text does not differ from the original by a single character. Override shaders are drawn first into an overlay slot (always RGBA16F on desktop, RGBA16F on the web when EXT_color_buffer_float is available like the original) and then mixed over.
- Alpha is not written when drawing to the default framebuffer (apply_color_mask). In the original and on the web the canvas is alpha: false so screen alpha is always 1, but the desktop default framebuffer has alpha, so modes using DST_ALPHA and shader mixing after a mode that lowers alpha differed from the web. Alpha is written to render targets.
GlTexturetype
GL 객체 타입. (데스크탑은 glow::Native*, 웹은 WebGL 객체. glow 컨텍스트가 정한 것을 그대로 쓴다)
GL object types. (glow::Native* on desktop, WebGL objects on the web. Uses whatever the glow context defines)
pub type GlTexture = <glow::Context as glow::HasContext>::TextureGlBuffertype
GL 버퍼 객체. (버텍스 버퍼 같은 것)
GL buffer object. (such as a vertex buffer)
pub type GlBuffer = <glow::Context as glow::HasContext>::BufferGlVertexArraytype
GL 버텍스 어레이 객체.
GL vertex array object.
pub type GlVertexArray = <glow::Context as glow::HasContext>::VertexArrayGlProgramtype
GL 셰이더 프로그램 객체.
GL shader program object.
pub type GlProgram = <glow::Context as glow::HasContext>::ProgramGlShadertype
GL 셰이더 객체. (버텍스나 프래그먼트 셰이더 하나)
GL shader object. (one vertex or fragment shader)
pub type GlShader = <glow::Context as glow::HasContext>::ShaderGlUniformLocationtype
GL 유니폼 위치. (데스크탑은 정수 하나를 감싼 값, 웹은 WebGL 위치 객체)
GL uniform location. (a value wrapping one integer on desktop, a WebGL location object on the web)
pub type GlUniformLocation = <glow::Context as glow::HasContext>::UniformLocationGlFramebuffertype
GL 프레임버퍼 객체. (렌더 타겟)
GL framebuffer object. (render target)
pub type GlFramebuffer = <glow::Context as glow::HasContext>::FramebufferGeometryKeystruct traits Clone, Debug, Default
기하 캐시 열쇠. (Component::write_geometry_key 가 그리기 입력을 적는 곳, 원본 GeometryKey)
- add 로 적은 값을 지난번에 적은 값과 차례대로 견준다. 하나라도 다르거나 수가 다르면 바뀐 것으로 본다.
- 견주며 바로 덮어 적으므로 프레임마다 배열을 새로 만들지 않는다. (글은 바뀐 때만 새로 담는다)
Geometry cache key. (Where Component::write_geometry_key writes the drawing inputs, original GeometryKey)
- Values written with add are compared in order with the values written last time. If any differs or the count differs, it counts as changed.
- It overwrites while comparing, so no array is created every frame. (Text is stored again only when it changed)
use vanilla::GeometryKey;
let mut geometry_key = GeometryKey::new();
geometry_key.begin();
geometry_key.add(10.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());
geometry_key.begin();
geometry_key.add(10.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());
geometry_key.begin();
geometry_key.add(12.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());생성.
Constructor.
반환ReturnsGeometryKey 빈 열쇠. (처음 end 는 false)An empty key. (The first end is false)
짝Counterpart: vanilla.js GeometryKey.constructor
적기 시작. (Graphic 이 write_geometry_key 앞에 부른다)
Starts writing. (Graphic calls it before write_geometry_key)
짝Counterpart: vanilla.js GeometryKey.begin
값 하나 적기. (수, 참거짓, 글, 색, 벡터, 사각형, 공유 객체(Rc), Option)
Writes one value. (number, bool, text, color, vector, rectangle, shared object (Rc), Option)
- valueimpl GeometryKeyValue
- 그리기가 읽는 값. (Rc 는 가리키는 자리로 견준다, 원본의 객체 참조 견주기)A value that drawing reads. (Rc is compared by the address it points to, like the original's object reference comparison)
짝Counterpart: vanilla.js GeometryKey.add
적기 끝. (지난번과 같으면 true)
Ends writing. (true if the same as last time)
반환Returnsbool 이번에 적은 값이 지난번과 모두 같으면 true. (처음 적은 때는 false)true if everything written this time equals what was written last time. (false the first time)
짝Counterpart: vanilla.js GeometryKey.end
GeometryKeyValuetrait
GeometryKey::add 로 적을 수 있는 값. (원본 add 가 받는 수, 글, 참거짓, 객체 참조, null)
A value that can be written with GeometryKey::add. (a number, text, bool, object reference or null, as the original add accepts)
use vanilla::GeometryKey;
let mut geometry_key = GeometryKey::new();
geometry_key.begin();
geometry_key.add(1.5_f64);
geometry_key.add(true);
geometry_key.end();
geometry_key.begin();
geometry_key.add(1.5_f64);
geometry_key.add(true);
assert!(geometry_key.end());열쇠에 이 값을 적기.
Writes this value into the key.
- geometry_key&mut GeometryKey
- 적을 열쇠.The key to write into.
Graphicstruct
그래픽. (원본 Graphic, GL 컨텍스트에 Canvas2D 처럼 그리는 2D 렌더러)
- 엔진이 하나 들어 씬과 노드의 그리기 함수에
&mut Graphic으로 넘기고, 그리기 밖에서는engine.get_graphic(),get_graphic_mut()로 꺼낸다. 좌표는 좌상 원점, 픽셀 단위다. - 상태(변환, 전역 투명도, 블렌드 모드, 색, 글꼴, 정렬, 글자 방향)는 push_state, pop_state 로 쌓고 되돌린다. 프레임 첫머리(apply_settings)에 변환, 전역 투명도, 틴트, 블렌드 모드가 처음 값으로 돌아간다.
Graphics. (the original Graphic, a 2D renderer that draws to a GL context like Canvas2D)
- The engine holds one and passes it as
&mut Graphicto the draw functions of scenes and nodes, and outside drawing it is taken withengine.get_graphic()andget_graphic_mut(). Coordinates have a top-left origin, in pixels. - State (transform, global alpha, blend mode, color, font, alignment, text direction) is pushed and restored with push_state, pop_state. At the start of a frame (apply_settings) the transform, global alpha, tint and blend mode return to their initial values.
use vanilla::{Colors, Engine, EngineConfiguration, Graphic, Rect, Scene, SceneBase, TextAlign, TextBaseline, Vector2};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn draw(&mut self, graphic: &mut Graphic) {
graphic.push_state();
graphic.translate(640.0, 360.0);
graphic.rotate(0.25);
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(-100.0, -60.0, 200.0, 120.0));
graphic.pop_state();
graphic.set_stroke_color("#ff8800");
graphic.draw_stroke_circle(Vector2::create(200.0, 200.0), 50.0, 4.0);
graphic.set_font_string("24px sans-serif");
graphic.set_text_align(TextAlign::Center);
graphic.set_text_baseline(TextBaseline::Middle);
graphic.set_fill_color(Colors::VANILLA);
graphic.draw_fill_text("Hello", 640.0, 620.0);
}
}
fn main() {
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
scene_base: SceneBase::new(),
};
if let Err(error) = engine.run(Box::new(main_scene)) {
eprintln!("{}", error);
}
}pub fn new(gl: glow::Context, preserve_drawing_buffer: bool, color_space: crate::core::colorspace::ColorSpace) -> Result<Graphic, String>#생성. (preserve_drawing_buffer 는 원본 생성 인자 preserveDrawingBuffer, 엔진 설정의 같은 이름 값을 넘긴다)
Constructor. (preserve_drawing_buffer is the original constructor argument preserveDrawingBuffer, pass the value of the same name from the engine settings)
- glglow::Context
- 그릴 GL 컨텍스트. (Graphic 이 가진다)GL context to draw to. (owned by Graphic)
- preserve_drawing_bufferbool
- 프레임이 끝난 뒤에도 그린 것을 남길지. (켜면 프레임 첫머리에 색을 비우지 않는다)Whether to keep what was drawn after the frame ends. (when on, the color is not cleared at the start of a frame)
- color_spacecrate::core::colorspace::ColorSpace
- 3D 색 공간. (원본 생성 인자 colorSpace, 엔진 설정의 color_space 를 넘긴다, 2D 는 어느 값이든 감마 공간)3D color space. (original constructor argument colorSpace, pass color_space from the engine configuration, 2D is in gamma space either way)
반환ReturnsResult<Graphic, String> 만든 그래픽. 기본 셰이더의 컴파일이나 링크, GL 객체(버텍스 어레이, 버퍼, 텍스처) 만들기에 실패하면 그 오류 글을 담은 Err.The created graphics. Err holding the error text if compiling or linking the default shaders, or creating GL objects (vertex arrays, buffers, textures) fails.
짝Counterpart: vanilla.js Graphic.constructor
프레임이 끝난 뒤에도 그린 것을 남기는지. (원본 preserveDrawingBuffer)
Whether what was drawn is kept after the frame ends. (the original preserveDrawingBuffer)
반환Returnsbool 생성 인자 preserve_drawing_buffer 의 값.Value of the constructor argument preserve_drawing_buffer.
설정 반영. (매 프레임 시작 시 엔진이 호출)
- 드로잉 버퍼 크기 변화 감지 및 뷰포트/프로젝션 갱신.
- 프레임 시작 기준 상태로 리셋.
- 브라우저는 preserveDrawingBuffer 가 꺼져 있으면 화면에 낸 뒤 드로잉 버퍼를 비워 준다. 창은 화면을 넘긴 뒤의 뒷 버퍼가 정해져 있지 않아 여기서 직접 비운다. 켜져 있으면 원본처럼 색을 비우지 않는다. (원본 applySettings 는 스텐실만 비운다. 지난 프레임 그림 위에 그리고, 데스크탑은 플랫폼이 지난 프레임 그림을 되살려 둔다)
Applies settings. (called by the engine at the start of every frame)
- Detects drawing buffer size changes and updates the viewport/projection.
- Resets to the frame-start state.
- The browser clears the drawing buffer after presenting when preserveDrawingBuffer is off. A window's back buffer after presenting is undefined, so it is cleared directly here. When on, the color is not cleared like the original. (the original applySettings clears only the stencil. It draws over the last frame's picture, and on desktop the platform restores the last frame's picture)
- drawing_buffer_widthi32
- 드로잉 버퍼 너비. (픽셀, 뷰포트와 프로젝션에 쓴다)Drawing buffer width. (pixels, used for the viewport and projection)
- drawing_buffer_heighti32
- 드로잉 버퍼 높이. (픽셀)Drawing buffer height. (pixels)
짝Counterpart: vanilla.js Graphic.applySettings
프레임 마무리. (엔진이 화면을 넘기기 전에 호출)
Finishes the frame. (called by the engine before presenting)
깊이 버퍼 비우기. (원본 clearDepthBuffer, 2D 그리기 사이에 3D 를 끼우기 전에)
- 자르기(begin_clip_rect, 스텐실)를 건 뒤 그리는 도중에 깊이를 비우면 갤럭시 폴드3(Adreno 660)의 드라이버가 3D 를 하나도 그리지 못한 일이 있다. (원본 게임) 자르기 안에 3D 를 그릴 노드는 begin_clip_rect 앞에서 이것을 부르고, run_external_pass 에는 is_depth_cleared 를 false 로 준다.
Clears the depth buffer. (the original clearDepthBuffer, before inserting 3D between 2D draws)
- Clearing depth in the middle of drawing after setting a clip (begin_clip_rect, stencil) once made the Galaxy Fold3 (Adreno 660) driver draw no 3D at all. (the original game) Nodes that draw 3D inside a clip call this before begin_clip_rect, and give is_depth_cleared false to run_external_pass.
짝Counterpart: vanilla.js Graphic.clearDepthBuffer
pub fn run_external_pass<R>(&mut self, is_depth_cleared: bool, pass: impl FnOnce(&GlContext) -> R) -> R#2D 그리기 사이에 GL 패스 끼우기. (원본 runExternalPass)
- 앞의 2D 묶음을 내보내고, is_depth_cleared 면 깊이를 비운 뒤 pass 를 부르고, 끝나면 restore_render_state 를 부른다.
- pass 는 GL 컨텍스트를 받아 프로그램, 버텍스 어레이, 뷰포트, 섞기, 깊이, 면 가리기를 바꿔도 된다. (스텐실 자르기는 그대로 걸려 있고, 끝나면 스텐실 자르기 상태를 되돌린다)
- 받은 컨텍스트(GlContext)의 상태 함수는 GL 상태 캐시를 거치므로, pass 안에서 상태를 바꾼 뒤 엔진 그리기를 이어 불러도 엔진이 바뀐 상태를 안다.
- 이 함수 밖에서 같은 컨텍스트로 GL 을 써도 다음 2D 그리기가 프로그램, 버텍스 어레이, 정점 버퍼, 텍스처 유닛, 섞기, 깊이, 면 가리기, 가위, 뷰포트를 상태 캐시에 견주어 다시 건다. 남는 약속은 둘이다. 2D 는 지금 묶인 프레임 버퍼에 그리므로 게임 프레임 버퍼를 묶었으면 들어올 때 것으로 돌려 두고, 스텐실 상태는 바꾸지 않는다.
- pass 가 돌려준 값을 그대로 돌려준다. pass 가 패닉해도 풀리는 동안 가드가 restore_render_state 를 부른다. (원본은 던져도 되돌린다)
Inserts a GL pass between 2D draws. (the original runExternalPass)
- Flushes the preceding 2D batch, clears depth if is_depth_cleared, calls pass, and calls restore_render_state when done.
- pass receives the GL context and may change the program, vertex array, viewport, blending, depth, and face culling. (The stencil clip stays set, and the stencil clip state is restored at the end)
- The state functions of the received context (GlContext) go through the GL state cache, so the engine knows the changed state even if engine drawing continues after changing state inside pass.
- Even if GL is used with the same context outside this function, the next 2D draw compares the program, vertex array, vertex buffer, texture units, blending, depth, face culling, scissor, and viewport against the state cache and sets them again. Two promises remain. 2D draws into the currently bound framebuffer, so if you bound a game framebuffer, put back the one bound on entry, and do not change the stencil state.
- Returns what pass returned as is. Even if pass panics, a guard calls restore_render_state while unwinding. (the original restores even when it throws)
- is_depth_clearedbool
- pass 앞에서 깊이 버퍼를 비울지. (자르기 안에 3D 를 그릴 때는 false 로 주고 begin_clip_rect 앞에서 clear_depth_buffer 를 부른다)Whether to clear the depth buffer before pass. (when drawing 3D inside a clip, give false and call clear_depth_buffer before begin_clip_rect)
- passimpl FnOnce(&GlContext) -> R
- GL 컨텍스트를 받아 그리는 함수.Function that receives the GL context and draws.
반환ReturnsR pass 가 돌려준 값.Value pass returned.
짝Counterpart: vanilla.js Graphic.runExternalPass
use vanilla::Graphic;
fn draw(graphic: &mut Graphic) {
let maximum_texture_size = graphic.run_external_pass(true, |gl| {
unsafe {
gl.enable(glow::DEPTH_TEST);
gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE)
}
});
assert!(maximum_texture_size > 0);
}이미지 스무딩 활성화 여부 설정.
- 도트(픽셀) 스프라이트 게임은 false 로 설정해 선명하게 렌더링.
Sets whether image smoothing is enabled.
- Pixel-art (dot) sprite games set this to false to render crisply.
- valuebool
- true 면 LINEAR 로 부드럽게, false 면 NEAREST 로 픽셀 그대로. (처음 true)true for smooth LINEAR, false for NEAREST keeping pixels as is. (initially true)
짝Counterpart: vanilla.js Graphic.setImageSmoothingEnabled
이미지 스무딩 활성화 여부 반환.
Returns whether image smoothing is enabled.
반환Returnsbool 스무딩이 켜져 있으면 true.true if smoothing is on.
짝Counterpart: vanilla.js Graphic.isImageSmoothingEnabled
이미지 스무딩 퀄리티 설정. (GL 은 LINEAR / NEAREST 이분법이라 보관만 한다, 처음은 High)
Sets the image smoothing quality. (GL only has LINEAR / NEAREST, so it is only stored, initially High)
- valueImageSmoothingQuality
- 스무딩 퀄리티. (보관만 하고 그리기에는 쓰지 않는다)Smoothing quality. (only stored, not used for drawing)
짝Counterpart: vanilla.js Graphic.setImageSmoothingQuality
이미지 스무딩 퀄리티 반환.
Returns the image smoothing quality.
반환ReturnsImageSmoothingQuality 설정한 퀄리티. (처음 High)The set quality. (initially High)
짝Counterpart: vanilla.js Graphic.getImageSmoothingQuality
이미지 밉맵 사용 여부 설정. (크게 줄여 그리는 이미지의 자글거림을 줄인다)
Sets whether image mipmaps are used. (reduces the shimmering of images drawn much smaller)
- valuebool
- true 면 이미지 텍스처를 줄일 때 밉맵 필터를 쓴다. (처음 false)true to use a mipmap filter when image textures are minified. (initially false)
짝Counterpart: vanilla.js Graphic.setImageMipmapEnabled
이미지 밉맵 사용 여부 반환.
Returns whether image mipmaps are used.
반환Returnsbool 밉맵을 쓰면 true.true if mipmaps are used.
짝Counterpart: vanilla.js Graphic.isImageMipmapEnabled
이미지 밉맵 단계 보정 설정. (기본 0, 원본 setImageMipmapBias)
- 밉맵 단계를 고를 때 더하는 값. 음수면 한 단계 큰 그림 쪽을 골라 또렷해지고, 너무 작으면 다시 자글거린다. (-0.5 안팎)
- 기본 셰이더(낱장, 묶어 그리기, 파티클)에 적용한다. 바꿔 끼운 셰이더는 textureLodBias 유니폼이 있으면 받는다.
Sets the image mipmap level bias. (default 0, the original setImageMipmapBias)
- A value added when picking the mipmap level. Negative picks one level larger and looks sharper, but too small shimmers again. (around -0.5)
- Applied to the default shaders (single, batched, particle). Override shaders receive it if they have the textureLodBias uniform.
- valuef64
- 밉맵 단계에 더할 값. (음수면 또렷하게, 0 이면 보정 없음)Value to add to the mipmap level. (negative is sharper, 0 means no bias)
짝Counterpart: vanilla.js Graphic.setImageMipmapBias
이미지 밉맵 단계 보정 반환.
Returns the image mipmap level bias.
반환Returnsf64 설정한 보정 값. (처음 0)The set bias value. (initially 0)
짝Counterpart: vanilla.js Graphic.getImageMipmapBias
모든 노드의 기즈모를 강제로 보일지 설정.
Sets whether to force the gizmos of all nodes to show.
- is_force_gizmos_visiblebool
- true 면 노드마다 기즈모 보이기 설정과 상관없이 그린다. (처음 false)true draws them regardless of each node's gizmo visibility setting. (initially false)
짝Counterpart: vanilla.js Graphic.setForceGizmosVisible
모든 노드의 기즈모를 강제로 보일지 반환.
Returns whether the gizmos of all nodes are forced to show.
반환Returnsbool 강제로 보이게 했으면 true.true if forced to show.
짝Counterpart: vanilla.js Graphic.isForceGizmosVisible
상태 저장. (Canvas2D save 대응)
- 한 번 쓴 칸은 남겨 두고 다시 쓴다. 폰트 문자열은 칸의 저장소에 옮겨 적어 매번 새로 잡지 않는다.
Saves the state. (corresponds to Canvas2D save)
- A slot used once is kept and reused. The font string is copied into the slot's storage so it is not allocated anew every time.
짝Counterpart: vanilla.js Graphic.pushState
상태 복원. (Canvas2D restore 대응)
- 폰트 문자열은 칸의 저장소와 맞바꾼다.
Restores the state. (corresponds to Canvas2D restore)
- The font string is swapped with the slot's storage.
짝Counterpart: vanilla.js Graphic.popState
이동 변환 누적.
Accumulates a translation transform.
- xf64
- 가로 이동. (지금 좌표계 단위, 픽셀)Horizontal translation. (in current coordinate system units, pixels)
- yf64
- 세로 이동. (아래가 +)Vertical translation. (down is +)
짝Counterpart: vanilla.js Graphic.translate
회전 변환 누적.
Accumulates a rotation transform.
- radianf64
- 회전 각도. (라디안, 화면에서 시계 방향이 +)Rotation angle. (radians, clockwise on screen is +)
짝Counterpart: vanilla.js Graphic.rotate
크기 변환 누적.
Accumulates a scale transform.
- xf64
- 가로 배율. (1 이면 그대로, 음수면 뒤집힌다)Horizontal scale. (1 keeps it as is, negative flips it)
- yf64
- 세로 배율.Vertical scale.
짝Counterpart: vanilla.js Graphic.scale
변환 행렬 직접 설정. (Canvas2D setTransform(a, b, c, d, e, f) 대응)
- 지금 행렬에 곱하지 않고 바꿔 넣는다. 점 (x, y) 는 (a x + c y + e, b x + d y + f) 로 옮겨진다.
Sets the transform matrix directly. (equivalent to Canvas2D setTransform(a, b, c, d, e, f))
- Replaces the current matrix instead of multiplying it. A point (x, y) is moved to (a x + c y + e, b x + d y + f).
- af64
- 가로 배율. (x 에 곱해 새 x 에 더한다)Horizontal scale. (multiplied by x and added to the new x)
- bf64
- 세로 기울임. (x 에 곱해 새 y 에 더한다)Vertical skew. (multiplied by x and added to the new y)
- cf64
- 가로 기울임. (y 에 곱해 새 x 에 더한다)Horizontal skew. (multiplied by y and added to the new x)
- df64
- 세로 배율. (y 에 곱해 새 y 에 더한다)Vertical scale. (multiplied by y and added to the new y)
- ef64
- 가로 이동. (픽셀)Horizontal translation. (pixels)
- ff64
- 세로 이동. (픽셀)Vertical translation. (pixels)
짝Counterpart: vanilla.js Graphic.setTransform
변환 행렬 초기화.
Resets the transform matrix.
짝Counterpart: vanilla.js Graphic.resetTransform
현재 변환 행렬 반환.
Returns the current transform matrix.
반환ReturnsTransformMatrix 지금 변환 행렬의 복사본.Copy of the current transform matrix.
짝Counterpart: vanilla.js Graphic.getTransformMatrix
전역 투명도 설정.
Sets the global alpha.
- valuef64
- 전역 투명도. (0 ~ 1 로 자른다, 처음 1)Global alpha. (clamped to 0 ~ 1, initially 1)
짝Counterpart: vanilla.js Graphic.setGlobalAlpha
전역 투명도 반환.
Returns the global alpha.
반환Returnsf64 지금 전역 투명도. (0 ~ 1)Current global alpha. (0 ~ 1)
짝Counterpart: vanilla.js Graphic.getGlobalAlpha
전역 투명도 곱셈 누적. (노드 트리의 투명도 상속용)
Multiplies into the global alpha. (for alpha inheritance in the node tree)
- valuef64
- 지금 전역 투명도에 곱할 값. (곱한 결과를 0 ~ 1 로 자른다)Value to multiply the current global alpha by. (the product is clamped to 0 ~ 1)
짝Counterpart: vanilla.js Graphic.multiplyGlobalAlpha
블렌드 모드 설정. (원본 setBlendMode)
- 고정 블렌딩으로 되는 13 가지는 blend_func 로 건다.
- 나머지 13 가지(Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity)는 그리기마다 그릴 영역 아래를 떠 와 셰이더로 섞는다. 이 모드에서는 묶어 그리지 않고, 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번이 든다. (바꿔 끼운 셰이더로 그릴 때는 덧그림 칸에 먼저 그리고 옮기므로 드로우 콜이 두 번)
- Multiply 는 렌더 타겟(기본 프레임버퍼가 아닌 것)에 그릴 때만 셰이더로 섞는다. (get_draw_shader_blend_mode_index)
Sets the blend mode. (the original setBlendMode)
- The 13 modes that fixed blending can do are set with blend_func.
- The remaining 13 (Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity) grab what is under the draw area on every draw and mix it in a shader. These modes are not batched, and each draw takes one region copy and one draw call. (when drawing with an override shader it is drawn into the overlay slot first and then moved, so two draw calls)
- Multiply is mixed in a shader only when drawing to a render target (not the default framebuffer). (get_draw_shader_blend_mode_index)
- blend_modeBlendMode
- 다음 그리기부터 쓸 블렌드 모드. (지금과 같으면 아무것도 하지 않는다, 바뀌면 모아 둔 묶음을 먼저 내보낸다)Blend mode to use from the next draw. (does nothing if it is the same as now, flushes the gathered batch first if it changes)
짝Counterpart: vanilla.js Graphic.setBlendMode
블렌드 모드 반환.
Returns the blend mode.
반환ReturnsBlendMode 지금 블렌드 모드. (프레임 첫머리에 Normal)Current blend mode. (Normal at the start of a frame)
짝Counterpart: vanilla.js Graphic.getBlendMode
이미지 틴트 색상 설정. (None 이면 해제)
- 이미지 실루엣(알파) 안쪽에만 tint.alpha 비율로 색을 덮는다.
Sets the image tint color. (cleared if None)
- Covers with the color at the tint.alpha ratio only inside the image silhouette (alpha).
- colorOption<Color>
- 덮을 색. (알파가 덮는 비율, None 이면 틴트를 끈다, 프레임 첫머리에 None)Color to cover with. (alpha is the cover ratio, None turns the tint off, None at the start of a frame)
짝Counterpart: vanilla.js Graphic.setImageTintColor
이미지 틴트 색상 반환.
Returns the image tint color.
반환ReturnsOption<Color> 지금 틴트 색. 걸려 있지 않으면 None.Current tint color. None if not set.
짝Counterpart: vanilla.js Graphic.getImageTintColor
채우기 색상 설정. (Color 또는 "#rrggbb" 같은 문자열)
Sets the fill color. (Color or a string like "#rrggbb")
- colorimpl Into<Color>
- 채우기 색. (Color 나 "#rrggbb" 같은 글, 처음 검정)Fill color. (Color or text like "#rrggbb", initially black)
짝Counterpart: vanilla.js Graphic.setFillColor
채우기 색상 반환.
Returns the fill color.
반환ReturnsColor 지금 채우기 색.Current fill color.
짝Counterpart: vanilla.js Graphic.getFillColor
선 색상 설정. (Color 또는 "#rrggbb" 같은 문자열)
Sets the stroke color. (Color or a string like "#rrggbb")
- colorimpl Into<Color>
- 선 색. (Color 나 "#rrggbb" 같은 글, 처음 검정)Stroke color. (Color or text like "#rrggbb", initially black)
짝Counterpart: vanilla.js Graphic.setStrokeColor
선 색상 반환.
Returns the stroke color.
반환ReturnsColor 지금 선 색.Current stroke color.
짝Counterpart: vanilla.js Graphic.getStrokeColor
pub fn write_quad(&mut self, offset: usize, left_x: f64, top_y: f64, right_x: f64, bottom_y: f64, left_u: f64, top_v: f64, right_u: f64, bottom_v: f64) -> usize#버텍스 데이터에 쿼드(삼각형 2개, 버텍스 6개) 기록.
- 기록 후의 오프셋(플로트 단위)을 반환.
- 스크래치 배열(get_vertex_data, 정점 4096 개, 플로트 16384 개)을 넘게 쓰면 패닉한다.
Writes a quad (2 triangles, 6 vertices) into the vertex data.
- Returns the offset (in floats) after writing.
- Panics if it writes past the scratch array (get_vertex_data, 4096 vertices, 16384 floats).
- offsetusize
- 기록을 시작할 자리. (스크래치 배열의 플로트 번호, 정점 하나에 x, y, u, v 플로트 4 개)Position to start writing at. (float index into the scratch array, 4 floats x, y, u, v per vertex)
- left_xf64
- 왼쪽 x. (지금 변환 전의 좌표, 픽셀)Left x. (coordinates before the current transform, pixels)
- top_yf64
- 위쪽 y. (픽셀)Top y. (pixels)
- right_xf64
- 오른쪽 x. (픽셀)Right x. (pixels)
- bottom_yf64
- 아래쪽 y. (픽셀)Bottom y. (pixels)
- left_uf64
- 왼쪽 텍스처 좌표. (0 ~ 1)Left texture coordinate. (0 ~ 1)
- top_vf64
- 위쪽 텍스처 좌표. (0 ~ 1, 0 이 그림의 위)Top texture coordinate. (0 ~ 1, 0 is the top of the image)
- right_uf64
- 오른쪽 텍스처 좌표. (0 ~ 1)Right texture coordinate. (0 ~ 1)
- bottom_vf64
- 아래쪽 텍스처 좌표. (0 ~ 1)Bottom texture coordinate. (0 ~ 1)
반환Returnsusize 기록한 뒤의 오프셋. (offset + 24, 4 로 나누면 그때까지의 정점 수)Offset after writing. (offset + 24, divided by 4 it is the vertex count so far)
짝Counterpart: vanilla.js Graphic.writeQuad
기록된 버텍스 출력. (모든 드로우가 수렴하는 단일 지점)
Draws the written vertices. (the single point all draws converge on)
- vertex_countusize
- 그릴 정점 수. (스크래치 배열 앞에서부터, 삼각형마다 3 개, 0 이면 아무것도 하지 않는다)Number of vertices to draw. (from the start of the scratch array, 3 per triangle, does nothing if 0)
- textureGlTexture
- 입힐 텍스처. (단색은 get_white_texture)Texture to apply. (get_white_texture for solid colors)
- colorColor
- 텍스처 색에 곱할 색. (그림 그대로는 get_white_color)Color to multiply the texture color by. (get_white_color to keep the image as is)
짝Counterpart: vanilla.js Graphic.drawVertices
use vanilla::core::graphic::FLOATS_PER_VERTEX;
use vanilla::{Color, Graphic};
fn draw(graphic: &mut Graphic) {
let mut offset = graphic.write_quad(0, 10.0, 10.0, 110.0, 60.0, 0.0, 0.0, 1.0, 1.0);
offset = graphic.write_quad(offset, 10.0, 80.0, 110.0, 130.0, 0.0, 0.0, 1.0, 1.0);
let white_texture = graphic.get_white_texture();
graphic.draw_vertices(offset / FLOATS_PER_VERTEX, white_texture, Color::create(1.0, 0.5, 0.0, 1.0));
}기하 캐시 켜기 / 끄기. (기본 켜짐, 원본 setGeometryCachingEnabled)
- 켜져 있으면 write_geometry_key 로 그리기 입력을 알리는 컴포넌트(Paint, UIView, Text, Sprite 등)가 그린 정점을 컴포넌트마다 캐시해 둔다. 입력, 변환, 투명도가 그대로면 draw 를 부르지 않고 캐시를 묶음에 옮기고, 이동(스크롤 등)만 바뀌면 캐시한 지역 정점에 새 행렬만 곱한다.
- 캐시 조각만으로 찬 묶음은 프레임의 그리기 차례마다 GPU 버퍼에 남겨, 바뀐 것이 없으면 정점을 올리지 않고 드로 콜만 낸다.
- 끄면 늘 draw 를 부른다. (화면은 같다)
Turns the geometry cache on or off. (On by default, original setGeometryCachingEnabled)
- While on, components that report their drawing inputs with write_geometry_key (Paint, UIView, Text, Sprite and so on) have the vertices they drew cached per component. If the inputs, transform and opacity are unchanged, draw is not called and the cache is moved into the batch; if only the translation changed (scrolling and so on), only the new matrix is applied to the cached local vertices.
- A batch filled only with cache pieces is kept in a GPU buffer per draw order in the frame, and when nothing changed only the draw call is issued without uploading vertices.
- When off, draw is always called. (The picture is the same)
- is_geometry_caching_enabledbool
- 켤지.Whether to turn it on.
짝Counterpart: vanilla.js Graphic.setGeometryCachingEnabled
use vanilla::Graphic;
fn draw(graphic: &mut Graphic) {
graphic.set_geometry_caching_enabled(true);
println!("{} {}", graphic.is_geometry_caching_enabled(), graphic.get_last_frame_geometry_cache_hit_count());
}기하 캐시가 켜져 있는지.
Whether the geometry cache is on.
반환Returnsbool 켜져 있으면 true. (처음 true)true if on. (true at first)
짝Counterpart: vanilla.js Graphic.isGeometryCachingEnabled
지난 프레임에 기하 캐시로 그린 컴포넌트 수. (draw 를 부르지 않은 것)
The number of components drawn from the geometry cache last frame. (draw was not called)
반환Returnsu32 캐시한 정점을 옮기거나 행렬만 다시 걸어 그린 컴포넌트 수.The number of components drawn by moving the cached vertices or only re-applying the matrix.
짝Counterpart: vanilla.js Graphic.getLastFrameGeometryCacheHitCount
지난 프레임에 기하 캐시를 다시 적은 컴포넌트 수. (캐시하는 컴포넌트 가운데 draw 를 부른 것)
The number of components whose geometry cache was written again last frame. (those among cached components that called draw)
반환Returnsu32 입력이나 배율, 회전 등이 바뀌어 draw 를 다시 부른 컴포넌트 수.The number of components whose draw was called again because the input, scale, rotation and so on changed.
짝Counterpart: vanilla.js Graphic.getLastFrameGeometryRebuildCount
지난 프레임에 정점을 다시 올리지 않고 GPU 에 남겨 둔 버퍼로 그린 묶음 수.
- 기하 캐시 조각만으로 찬 묶음이 지난 프레임 같은 차례의 묶음과 조각까지 같으면 정점을 옮기지도 올리지도 않고 드로 콜만 낸다.
The number of batches drawn last frame from a buffer left on the GPU, without uploading vertices again.
- A batch whose pieces (geometry cache pieces and the vertex values of directly written spans) are all the same as the batch of the same order last frame issues only the draw call, without moving or uploading vertices.
- A batch with only part changed has just the changed ranges updated with buffer_sub_data and is not counted here.
반환Returnsu32 남긴 버퍼로 그린 묶음 수.The number of batches drawn from the kept buffer.
짝Counterpart: vanilla.js Graphic.getLastFrameRetainedBatchCount
use vanilla::Graphic;
fn draw(graphic: &mut Graphic) {
println!("{} {}", graphic.get_last_frame_retained_batch_count(), graphic.get_last_frame_draw_call_count());
}pub fn draw_component(&mut self, component: &mut dyn Component, transform: &NodeTransform)#컴포넌트 그리기. (노드가 컴포넌트마다 부른다, 기하 캐시를 거친다, 원본 drawComponent)
- 컴포넌트가 write_geometry_key 로 입력을 알리지 않거나, 캐시가 꺼졌거나, 묶어 그리지 않는 상태면 draw 를 그대로 부른다.
- 입력과 그리는 상태(배율, 회전, 섞기, 틴트, 글 방향)가 지난번과 같으면: 이동과 투명도도 같으면 캐시한 디바이스 정점을 묶음에 그대로 옮기고, 다르면 캐시한 지역 정점에 지금 행렬과 투명도를 다시 건다. (스크롤은 부모의 이동만 바뀌므로 자식 컴포넌트는 draw 없이 행렬 곱만 한다, 글은 픽셀 스냅까지 같게 다시 셈한다)
- 그 밖에는 draw 를 불러 캐시를 다시 적는다. 그리기 중에 자르기, 층, 섞기 바꾸기 등 묶음 밖의 일을 하면 그 컴포넌트는 캐시하지 않는다.
Draws a component. (A node calls it per component, goes through the geometry cache, original drawComponent)
- If the component does not report its inputs with write_geometry_key, the cache is off, or the state is not batched drawing, draw is called as is.
- If the inputs and the drawing state (scale, rotation, blend, tint, text direction) equal last time:
if translation and opacity are also the same, the cached device vertices are moved into the batch as they are; otherwise the current matrix and opacity are applied again to the cached local vertices.
(When scrolling only the parent's translation changes, so child components only multiply the matrix without calling draw; text recomputes even the pixel snap the same way)- Otherwise draw is called and the cache is written again. If something outside the batch such as clipping, layers or blend changes happens during drawing, that component is not cached.
- component&mut dyn Component
- 그릴 컴포넌트. (캐시는 컴포넌트가 쥔다)The component to draw. (the component holds the cache)
- transform&NodeTransform
- 컴포넌트가 붙은 노드의 트랜스폼.The transform of the node the component is attached to.
짝Counterpart: vanilla.js Graphic.drawComponent
모아 둔 묶음 내보내기. (GL 상태를 바꾸기 전, 프레임 끝, GL 을 직접 쓰기 전에 부른다)
- 묶음의 텍스처를 0 번부터의 유닛에 묶는다. 쓰지 않는 칸의 유닛에는 흰 텍스처를 묶어, 지난 그리기의 텍스처가 지금 그리는 칸(렌더 타겟)이어도 되먹임이 생기지 않게 한다. (원본과 같음)
Flushes the gathered batch. (called before changing GL state, at the end of a frame, and before using GL directly)
- Binds the batch textures to units from 0 up. Units of unused slots get the white texture, so a texture from an earlier draw never forms a feedback loop even if it is the current target (render target). (same as the original)
짝Counterpart: vanilla.js Graphic.flushBatch
묶어 그리기 켜고 끄기. (기본 켬. 끄면 원본처럼 그리기 하나에 드로우 콜 하나)
- 켜면 연이은 드로우(이미지, 도형, 글자, 정점 색 쿼드)를 정점에 변환과 색을 실어 쌓아 두었다가 한 번의 드로우 콜로 그린다.
- 텍스처는 한 묶음에 여러 장(기기 텍스처 유닛 수와 16 가운데 작은 것)까지 묶어 텍스처가 바뀌어도 이어진다. (PixiJS 와 같은 꼴)
- 축에 맞고 화소 경계에 놓인 자르기(begin_clip_rect)는 정점의 자르기 사각형으로 셰이더가 잘라 묶음을 끊지 않는다. (돌아갔거나 둥근 자르기는 스텐실)
- 텍스처 칸이 차거나, 블렌드, 스텐실 자르기, 바꿔 끼운 셰이더가 바뀌거나 버퍼가 차면 그때까지 쌓인 것을 그리고, 프레임 끝에 엔진이 남은 것을 그린다.
Turns batching on or off. (on by default. When off, one draw call per draw, like the original)
- When on, consecutive draws (images, shapes, text, vertex-color quads) are accumulated with transform and color carried in the vertices and drawn in one draw call.
- One batch binds several textures (the smaller of the device texture unit count and 16), so the batch continues when the texture changes. (the same scheme as PixiJS)
- Axis-aligned clips (begin_clip_rect) whose edges lie on pixel boundaries are clipped by the shader with a clip rectangle carried in the vertices, so they do not break the batch. (rotated or rounded clips use the stencil)
- When the texture slots fill up, when the blend, a stencil clip or a swapped-in shader changes, or when the buffer is full, what has accumulated is drawn, and the engine draws the rest at the end of the frame.
- is_batching_enabledbool
- true 면 연이은 그리기를 모아 한 번에 그린다. (끌 때 모아 둔 것을 먼저 내보낸다)If true, consecutive draws are gathered and drawn at once. (turning it off flushes what has been gathered first)
짝Counterpart: vanilla.js Graphic.setBatchingEnabled
묶어 그리기 여부.
Whether batching is on.
반환Returnsbool 묶어 그리기가 켜져 있으면 true. (처음 true)true if batching is on. (initially true)
짝Counterpart: vanilla.js Graphic.isBatchingEnabled
화면 밖 거르기 켜고 끄기. (기본 켬)
Turns offscreen culling on and off. (on by default)
- is_culling_enabledbool
- true 면 화면 밖 노드의 그리기를 건너뛴다.true skips drawing offscreen nodes.
짝Counterpart: vanilla.js Graphic.setCullingEnabled
화면 밖 거르기 여부.
Whether offscreen culling is on.
반환Returnsbool 화면 밖 거르기가 켜져 있으면 true. (처음 true)true if offscreen culling is on. (initially true)
짝Counterpart: vanilla.js Graphic.isCullingEnabled
현재 변환 기준의 사각형이 화면(드로잉 버퍼)과 걸린 자르기 안에 걸치는지. (네 꼭짓점을 변환한 경계 상자로 본다)
- begin_clip_rect 로 건 자르기(겹친 것 모두)의 경계 상자 밖이면 보이지 않는 것으로 본다. (유니티 RectMask2D 처럼 스크롤 칸 밖 줄을 그리지 않는다)
Whether a rectangle in the current transform overlaps the screen (drawing buffer) and the active clip. (judged by the bounding box of the four transformed corners)
- Outside the bounding box of the clips set with begin_clip_rect (all nested ones), it counts as not visible. (like Unity RectMask2D, rows outside a scroll view are not drawn)
- rectRect
- 지금 변환 기준의 사각형. (로컬 좌표, 픽셀)Rectangle in the current transform. (local coordinates, pixels)
반환Returnsbool 변환한 네 꼭짓점의 경계 상자가 드로잉 버퍼(0, 0 에서 너비, 높이까지)와 걸린 자르기의 경계 상자 안에 걸치면 true. (경계에 닿기만 해도 true)true if the bounding box of the four transformed corners overlaps the drawing buffer (from 0, 0 to width, height) and the bounding box of the active clip. (touching the edge counts as true)
짝Counterpart: vanilla.js Graphic.isLocalRectVisible
하위 트리째 그리기 건너뛰기 켜고 끄기. (기본 켬, 원본 setSubtreeCullingEnabled)
- 켜면 노드와 자손이 그리는 곳을 모두 품는 하위 트리 그리기 경계(NodeTree::read_subtree_draw_bounds)가 화면과 걸린 자르기 밖일 때 그 노드와 자손의 그리기를 통째로 건너뛴다. tick 은 그대로 돈다.
- 화면 밖 거르기(set_culling_enabled)가 꺼져 있으면 이것도 하지 않는다. 기즈모를 모두 그리게 했으면 건너뛰지 않는다.
Turns subtree draw skipping on or off. (on by default, original setSubtreeCullingEnabled)
- When on, if the subtree draw bounds that hold everything a node and its descendants draw (NodeTree::read_subtree_draw_bounds) are outside the screen and the active clip, drawing of the node and its descendants is skipped as a whole. tick still runs.
- Does nothing while off-screen culling (set_culling_enabled) is off. Never skips while all gizmos are drawn.
- is_subtree_culling_enabledbool
- true 면 화면 밖 하위 트리를 통째로 건너뛴다.true skips off-screen subtrees as a whole.
짝Counterpart: vanilla.js Graphic.setSubtreeCullingEnabled
use vanilla::Graphic;
fn compare_culling(graphic: &mut Graphic) {
assert!(graphic.is_subtree_culling_enabled());
graphic.set_subtree_culling_enabled(false);
assert!(!graphic.is_subtree_culling_enabled());
let culled_subtree_count = graphic.get_last_frame_culled_subtree_count();
assert!(culled_subtree_count < u32::MAX);
}하위 트리째 그리기 건너뛰기 여부. (원본 isSubtreeCullingEnabled)
Whether subtree draw skipping is on. (original isSubtreeCullingEnabled)
반환Returnsbool 켜져 있으면 true. (처음 true)true if on. (true at first)
짝Counterpart: vanilla.js Graphic.isSubtreeCullingEnabled
지난 프레임에 화면 밖이라 그리기를 통째로 건너뛴 하위 트리 수. (원본 getLastFrameCulledSubtreeCount)
Number of subtrees whose drawing was skipped as a whole last frame because they were off screen. (original getLastFrameCulledSubtreeCount)
반환Returnsu32 지난 프레임에 건너뛴 하위 트리 수. (begin_frame_statistics 가 넘겨 둔 값, 건너뛴 노드의 자손은 세지 않는다)Number of subtrees skipped last frame. (the value begin_frame_statistics carried over, descendants of a skipped node are not counted)
짝Counterpart: vanilla.js Graphic.getLastFrameCulledSubtreeCount
이번 프레임에 화면 밖이라 그리기를 통째로 건너뛴 하위 트리 수 더하기. (원본 addCulledSubtreeCount, NodeTree::draw_children 이 보이는 범위 밖 자식을 한꺼번에 건너뛰고 부른다)
Adds to the number of subtrees skipped as a whole this frame because they were off screen. (original addCulledSubtreeCount, NodeTree::draw_children calls it after skipping the children outside the visible range at once)
- culled_subtree_countu32
- 더할 하위 트리 수.Number of subtrees to add.
짝Counterpart: vanilla.js Graphic.addCulledSubtreeCount
보이는 사각형(화면과 걸린 자르기, is_local_rect_visible 과 같은 것)을 지금 변환의 지역 좌표로 거꾸로 옮긴 경계 상자 읽기. (원본 readLocalVisibleBounds)
- 돌림이나 기울임이 있으면 넉넉하다(네 꼭짓점의 경계 상자, 디바이스 사각형을 한 픽셀씩 넓혀 옮김). 이 사각형 밖에 그리는 것은 보이지 않는다.
- 노드가 많은 자식 가운데 보이는 범위를 찾을 때 쓴다(NodeTree::draw_children). 변환과 자르기가 같으면 다시 셈하지 않는다.
Reads the visible rect (the screen and the active clip, the same as is_local_rect_visible) moved back into the local coordinates of the current transform as a bounding box. (original readLocalVisibleBounds)
- Generous with rotation or skew (bounding box of the four corners, the device rect is widened by one pixel before moving). Anything drawn outside this rect is not visible.
- Used to find the visible range among a node's many children (NodeTree::draw_children). Not recomputed while the transform and the clip stay the same.
반환ReturnsOption<Rect> 지역 좌표의 보이는 경계 상자. 화면 밖 거르기나 하위 트리 거르기가 꺼졌거나, 기즈모를 모두 그리거나, 뷰포트를 아직 정하지 않았거나, 변환을 거꾸로 걸 수 없으면(배율 0) None.Visible bounding box in local coordinates. None if off-screen culling or subtree culling is off, all gizmos are drawn, the viewport is not set yet, or the transform cannot be inverted (scale 0).
짝Counterpart: vanilla.js Graphic.readLocalVisibleBounds
use vanilla::Graphic;
fn read_scaled(graphic: &mut Graphic) {
if let Some(visible_rect) = graphic.read_local_visible_bounds() {
graphic.push_state();
graphic.scale(2.0, 2.0);
let scaled_rect = graphic.read_local_visible_bounds().expect("visible");
assert!((scaled_rect.size.x * 2.0 - visible_rect.size.x).abs() < 1e-9);
graphic.pop_state();
}
}하위 트리가 보이는 사각형(화면과 걸린 자르기) 안에 다 든 노드를 그리는 중인지. (원본 Graphic.isInsideVisibleBounds)
- 참이면 그 노드의 자손은 화면 밖 견주기 없이 그려도 된다. 그 아래에서 자르기를 새로 걸면 그 자르기 안에서는 거짓이다(다시 견준다).
- 화면 밖 거르기나 하위 트리 거르기가 꺼졌거나 기즈모를 모두 그리면 거짓.
Whether a node whose subtree lies fully inside the visible rect (the screen and the applied clip) is being drawn. (original Graphic.isInsideVisibleBounds)
- When true, the descendants of that node may be drawn without the off screen check. Under a clip begun below it, it is false inside that clip (checked again).
- False when off screen culling or subtree culling is off, or when all gizmos are drawn.
반환Returnsbool 다 안이면 true.true when fully inside.
짝Counterpart: vanilla.js Graphic.isInsideVisibleBounds
use vanilla::Graphic;
fn draw_marker(graphic: &mut Graphic) {
if graphic.is_inside_visible_bounds() {
assert!(graphic.is_subtree_culling_enabled());
}
}이번 프레임에 거른 노드 수 더하기. (NodeTree 가 부른다)
Adds to the number of nodes culled this frame. (called by NodeTree)
- culled_node_countu32
- 더할 노드 수.Number of nodes to add.
짝Counterpart: vanilla.js Graphic.addCulledNodeCount
지난 프레임에 화면 밖이라 거른 노드 수.
Number of nodes culled as offscreen last frame.
반환Returnsu32 지난 프레임에 거른 노드 수. (begin_frame_statistics 가 넘겨 둔 값)Number of nodes culled last frame. (the value handed over by begin_frame_statistics)
짝Counterpart: vanilla.js Graphic.getLastFrameCulledNodeCount
프레임 그리기 통계 시작.
- 엔진이 매 프레임 씬을 그리기 전에 부른다. 지난 프레임의 드로우 콜 / 정점 수를 넘겨 두고 이번 프레임 값을 비운다.
Starts the frame drawing statistics.
- The engine calls it every frame before drawing the scene. Hands over the last frame's draw call / vertex counts and clears this frame's values.
짝Counterpart: vanilla.js Graphic.beginFrameStatistics
지난 프레임의 드로우 콜 수.
The last frame's draw call count.
반환Returnsu32 지난 프레임의 드로우 콜 수. (begin_frame_statistics 가 넘겨 둔 값)Number of draw calls last frame. (the value handed over by begin_frame_statistics)
짝Counterpart: vanilla.js Graphic.getLastFrameDrawCallCount
지난 프레임에 그린 정점 수.
Number of vertices drawn in the last frame.
반환Returnsu32 지난 프레임에 그린 정점 수.Number of vertices drawn in the last frame.
짝Counterpart: vanilla.js Graphic.getLastFrameVertexCount
지난 프레임에 그린 삼각형 수.
Number of triangles drawn in the last frame.
반환Returnsu32 지난 프레임의 정점 수를 3 으로 나눈 값.Number of vertices last frame divided by 3.
짝Counterpart: vanilla.js Graphic.getLastFrameTriangleCount
파티클 버텍스 기록용 배열 반환. (minimum_float_count 이상, 용량을 넘으면 용량까지)
Returns the array for writing particle vertices. (at least minimum_float_count, up to the capacity if it exceeds the capacity)
- minimum_float_countusize
- 쓸 플로트 수. (정점 하나에 PARTICLE_FLOATS_PER_VERTEX 개: x, y, u, v, r, g, b, a)Number of floats to use. (PARTICLE_FLOATS_PER_VERTEX per vertex: x, y, u, v, r, g, b, a)
반환Returns&mut [f32] 앞에서부터 minimum_float_count 개의 배열. (용량 정점 8192 개를 넘게 달라면 용량까지, 지난번 값이 남아 있을 수 있다)Array of minimum_float_count from the start. (up to the capacity if asked for more than the 8192 vertex capacity, previous values may remain)
짝Counterpart: vanilla.js Graphic.getParticleVertexData
정점마다 색을 실은 쿼드 출력. (get_particle_vertex_data 에 기록한 것)
Draws quads with a color per vertex. (what was written to get_particle_vertex_data)
- vertex_countusize
- 그릴 정점 수. (쿼드마다 6 개, 용량과 get_particle_vertex_data 로 받은 길이까지만 그린다, 0 이면 아무것도 하지 않는다)Number of vertices to draw. (6 per quad, draws only up to the capacity and the length received from get_particle_vertex_data, does nothing if 0)
- textureGlTexture
- 입힐 텍스처. (get_soft_disc_texture, get_image_texture 같은 것)Texture to apply. (such as get_soft_disc_texture, get_image_texture)
짝Counterpart: vanilla.js Graphic.drawColoredQuads
use vanilla::core::graphic::PARTICLE_FLOATS_PER_VERTEX;
use vanilla::Graphic;
fn draw(graphic: &mut Graphic) {
let soft_disc_texture = graphic.get_soft_disc_texture();
let particle_list: [(f64, f64, [f64; 4]); 2] = [(100.0, 100.0, [1.0, 0.5, 0.0, 1.0]), (140.0, 120.0, [0.2, 0.6, 1.0, 0.5])];
let half_size = 24.0;
let corner_list: [[f64; 4]; 6] = [[-half_size, -half_size, 0.0, 0.0], [half_size, -half_size, 1.0, 0.0], [half_size, half_size, 1.0, 1.0], [-half_size, -half_size, 0.0, 0.0], [half_size, half_size, 1.0, 1.0], [-half_size, half_size, 0.0, 1.0]];
let vertex_data = graphic.get_particle_vertex_data(particle_list.len() * 6 * PARTICLE_FLOATS_PER_VERTEX);
let mut offset = 0;
for (center_x, center_y, color) in particle_list {
for corner in corner_list {
let vertex = [center_x + corner[0], center_y + corner[1], corner[2], corner[3], color[0], color[1], color[2], color[3]];
vertex_data[offset..offset + PARTICLE_FLOATS_PER_VERTEX].copy_from_slice(&vertex.map(|value| value as f32));
offset += PARTICLE_FLOATS_PER_VERTEX;
}
}
graphic.draw_colored_quads(offset / PARTICLE_FLOATS_PER_VERTEX, soft_disc_texture);
}부드러운 원 텍스처 반환. (가장자리가 잦아드는 64x64 원, 파티클 기본 스프라이트. 지연 생성)
- GL 텍스처를 만들지 못하면 패닉한다.
Returns the soft disc texture. (a 64x64 disc whose edge fades out, the default particle sprite. Created lazily)
- Panics if the GL texture cannot be created.
반환ReturnsGlTexture 64 x 64 픽셀 텍스처. (반지름 0.7 까지 꽉 차고 0.7 에서 1 까지 smoothstep 으로 사라지는 흰 원, 프리멀티플라이드)64 x 64 pixel texture. (a white disc that is full up to radius 0.7 and fades out with smoothstep from 0.7 to 1, premultiplied)
짝Counterpart: vanilla.js Graphic.getSoftDiscTexture
그림을 GPU 에 미리 올리기. (원본 prepareImage, 처음 그리는 프레임에 올리기가 몰리지 않게 씬을 불러오는 동안 부른다)
- 지금 이미지 스무딩과 밉맵 설정으로 올린다. (그릴 때 설정이 다르면 그때 거르기만 바꾼다)
- 이미 올린 그림이면 아무것도 하지 않는다. 크기가 0 인 그림은 올리지 않는다.
- 코드로 지은 그림(Image::create_from_pixels 같은 것)처럼 ImageAsset 으로 읽지 않은 그림을 씬의 load 에서 올려 둘 때 쓴다.
Uploads an image to the GPU in advance. (the original prepareImage, called while the scene loads so uploads do not pile up on the first drawing frame)
- Uploads with the current image smoothing and mipmap settings. (If the settings differ when drawing, only the filtering is changed then)
- Does nothing if the image is already uploaded. Does not upload an image of size 0.
- Used to upload in the scene's load an image not read through ImageAsset, such as an image built in code (Image::create_from_pixels and the like).
- image&Rc<Image>
- 올릴 그림.The image to upload.
반환Returnsbool 텍스처가 있으면 true. (크기가 0 이거나 GL 텍스처를 만들지 못하면 false)true if there is a texture. (false if the size is 0 or the GL texture cannot be created)
짝Counterpart: vanilla.js Graphic.prepareImage
use std::rc::Rc;
use vanilla::{Engine, Image};
fn load(engine: &Engine) -> Rc<Image> {
let dot_image = Image::create_from_pixels(32, 32, [255u8, 102, 0, 255].repeat(32 * 32));
if let Some(mut graphic) = engine.get_graphic_mut() {
let is_prepared = graphic.prepare_image(&dot_image);
println!("{}", is_prepared);
}
dot_image
}읽었지만 아직 올리지 않은 그림 올리기. (원본 prepareLoadedImages, ImageAsset 과 AssetLoader 가 읽어 푼 그림, 푼 차례로)
- 엔진이 씬의 맡긴 애셋이 다 읽힌 뒤(로딩 화면 동안) 프레임마다 나눠 부른다. 씬이 따로 부를 일은 없다.
- 시간 한도를 주면 그 시간을 넘긴 뒤에는 멈추고 남은 수를 돌려준다. (한 번에 적어도 하나는 올린다, 유니티의 asyncUploadTimeSlice 와 같다)
- 제 것(이 Graphic 을 든 엔진으로 읽은 그림)만 올린다. 주인을 모르는 그림은 Graphic 이 하나뿐일 때만 올린다. (원본과 같음)
Uploads images read but not uploaded yet. (the original prepareLoadedImages, images read and decoded by ImageAsset and AssetLoader, in decode order)
- The engine calls it split across frames after the scene's tracked assets are read (during the loading screen). The scene has no need to call it itself.
- Given a time limit, stops after exceeding that time and returns the remaining count. (Uploads at least one at a time, same as Unity's asyncUploadTimeSlice)
- Uploads only its own (images read with the engine holding this Graphic). Images with an unknown owner are uploaded only when there is a single Graphic. (same as the original)
- time_limit_millisecondsf64
- 이번에 쓸 시간 한도. (밀리초, f64::INFINITY 면 모두)The time limit to use this time. (milliseconds, f64::INFINITY for all)
반환Returnsusize 아직 올리지 않고 남은 그림 수. (0 이면 다 올렸다)The number of images left not uploaded yet. (0 when all are uploaded)
짝Counterpart: vanilla.js Graphic.prepareLoadedImages
use vanilla::{Engine, ImageAsset};
async fn load(engine: &Engine, image_asset: &mut ImageAsset) {
let _ = image_asset.load(engine, "examples/assets/spritesheet.png").await;
if let Some(mut graphic) = engine.get_graphic_mut() {
let remaining_count = graphic.prepare_loaded_images(f64::INFINITY);
println!("{}", remaining_count);
}
}이미지의 텍스처 반환. (파티클처럼 직접 쿼드를 쓰는 곳에서)
Returns the texture of an image. (for places that write quads directly, like particles)
- image&Rc<Image>
- 텍스처를 받을 이미지. (처음이면 올리고 CPU 픽셀을 놓는다)Image to get the texture for. (uploads it the first time and releases the CPU pixels)
반환ReturnsOption<GlTexture> 지금 스무딩과 밉맵 설정을 건 텍스처. GL 텍스처를 만들지 못하면 None.Texture with the current smoothing and mipmap settings applied. None if the GL texture cannot be created.
선 출력.
- set_stroke_color()
Draws lines.
- set_stroke_color()
- positions&[Vector2]
- 이을 점들. (2 개 미만이면 그리지 않는다)Points to connect. (not drawn if fewer than 2)
- sizef64
- 선 두께. (픽셀)Line thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawLine
닫힌 선 출력. (마지막 점과 첫 점을 잇는 루프)
- set_stroke_color()
Draws a closed line. (a loop connecting the last point to the first)
- set_stroke_color()
- positions&[Vector2]
- 이을 점들. (2 개 미만이면 그리지 않는다)Points to connect. (not drawn if fewer than 2)
- sizef64
- 선 두께. (픽셀)Line thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawLineLoop
폴리라인 출력. (세그먼트별 두께 확장 쿼드)
- 내부 조인트는 반두께 연장으로 이음새를 메운다.
Draws a polyline. (per-segment quads expanded by thickness)
- Inner joints are filled by extending half the thickness.
- positions&[Vector2]
- 이을 점들. (2 개 미만이면 그리지 않는다, 스크래치 배열에 들어가는 선분 682 개까지만 그린다)Points to connect. (not drawn if fewer than 2, draws only up to the 682 segments that fit in the scratch array)
- sizef64
- 선 두께. (픽셀)Line thickness. (pixels)
- is_closedbool
- true 면 마지막 점과 첫 점도 잇는다.true also connects the last point to the first.
짝Counterpart: vanilla.js Graphic.drawPolyline
사각형 출력.
- set_fill_color()
Draws a rectangle.
- set_fill_color()
- rectRect
- 칠할 사각형. (지금 변환 전의 좌표, 픽셀)Rectangle to fill. (coordinates before the current transform, pixels)
짝Counterpart: vanilla.js Graphic.drawRect
사각형 외곽선 출력. (Canvas2D strokeRect 대응, 선 중심이 경계선 위)
- set_stroke_color()
Draws a rectangle outline. (corresponds to Canvas2D strokeRect, the line center is on the border)
- set_stroke_color()
- rectRect
- 외곽선을 그을 사각형. (픽셀)Rectangle to outline. (pixels)
- line_widthf64
- 선 두께. (픽셀, 경계선 양쪽으로 절반씩)Line thickness. (pixels, half on each side of the border)
짝Counterpart: vanilla.js Graphic.drawStrokeRect
pub fn build_round_rect_positions(&self, rect: Rect, round_size: f64) -> [Vector2; ROUND_RECT_POSITION_COUNT]#라운드 사각형 경로 좌표 목록 생성. (시계 방향, 볼록 다각형)
Creates the list of rounded rectangle path coordinates. (clockwise, convex polygon)
- rectRect
- 사각형. (픽셀)Rectangle. (pixels)
- round_sizef64
- 모서리 반지름. (가로세로 가운데 짧은 쪽의 절반을 넘으면 그 값으로 줄인다)Corner radius. (reduced to half of the shorter side if it exceeds that)
반환Returns[Vector2; ROUND_RECT_POSITION_COUNT] 모서리마다 9 개씩 36 개의 점. (우상, 우하, 좌하, 좌상 모서리 차례)36 points, 9 per corner. (in top-right, bottom-right, bottom-left, top-left corner order)
짝Counterpart: vanilla.js Graphic.buildRoundRectPositions
볼록 다각형 채움 출력. (첫 점 기준 팬 분할)
- 정점 버퍼가 차면 쌓인 삼각형을 그리고 비운 뒤 이어 적는다. (점이 많아도 삼각형을 버리지 않는다)
Draws a filled convex polygon. (fan split from the first point)
- When the vertex buffer fills, it draws the accumulated triangles, empties it and keeps writing. (triangles are not dropped even with many points)
- positions&[Vector2]
- 볼록 다각형의 꼭짓점. (3 개 미만이면 그리지 않는다)Vertices of a convex polygon. (not drawn if fewer than 3)
- colorColor
- 칠할 색. (채우기 색은 쓰지 않는다)Color to fill with. (the fill color is not used)
짝Counterpart: vanilla.js Graphic.drawConvexPolygon
라운드 사각형 출력.
- set_fill_color()
Draws a rounded rectangle.
- set_fill_color()
- rectRect
- 칠할 사각형. (픽셀)Rectangle to fill. (pixels)
- round_sizef64
- 모서리 반지름. (0 이하면 draw_rect 와 같다)Corner radius. (same as draw_rect if 0 or less)
짝Counterpart: vanilla.js Graphic.drawRoundRect
라운드 사각형 외곽선 출력.
- set_stroke_color()
Draws a rounded rectangle outline.
- set_stroke_color()
- rectRect
- 외곽선을 그을 사각형. (픽셀)Rectangle to outline. (pixels)
- round_sizef64
- 모서리 반지름. (0 이하면 draw_stroke_rect 와 같다)Corner radius. (same as draw_stroke_rect if 0 or less)
- line_widthf64
- 선 두께. (픽셀)Line thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawStrokeRoundRect
원 출력.
- set_fill_color()
Draws a circle.
- set_fill_color()
- centerVector2
- 가운데. (픽셀)Center. (pixels)
- radiusf64
- 반지름. (픽셀, 0 이하면 그리지 않는다)Radius. (pixels, not drawn if 0 or less)
짝Counterpart: vanilla.js Graphic.drawCircle
원 외곽선 출력.
- set_stroke_color()
Draws a circle outline.
- set_stroke_color()
- centerVector2
- 가운데. (픽셀)Center. (pixels)
- radiusf64
- 반지름. (픽셀, 0 이하면 그리지 않는다)Radius. (pixels, not drawn if 0 or less)
- line_widthf64
- 선 두께. (픽셀, 반지름 양쪽으로 절반씩)Line thickness. (pixels, half on each side of the radius)
짝Counterpart: vanilla.js Graphic.drawStrokeCircle
pub fn draw_ring(&mut self, center: Vector2, inner_radius: f64, outer_radius: f64, start_radian: f64, end_radian: f64)#고리(띠) 출력. (안쪽 반지름과 바깥 반지름 사이를 start_radian 부터 end_radian 까지 칠한다)
- set_fill_color()
- 각도는 라디안, 0 이 오른쪽이고 화면에서 시계 방향으로 는다. (12 시에서 시작하려면 -PI / 2, 한 바퀴는 0 에서 PI * 2)
- 조각마다 네모 하나를 겹치지 않게 이어 붙여 한 번에 그리므로, 반투명 색이어도 조각의 이음매가 짙어지지 않는다.
- 조각 수는 draw_circle 처럼 화면에서의 바깥 반지름을 따라 정하고(한 바퀴 16 ~ 64), 그리는 각도만큼만 쓴다.
Draws a ring (band). (fills between the inner and outer radius from start_radian to end_radian)
- set_fill_color()
- Angles are in radians, 0 is to the right and they increase clockwise on screen. (-PI / 2 to start at 12 o'clock, a full turn is 0 to PI * 2)
- Each segment is one quad joined without overlap and drawn at once, so the seams between segments do not darken even with a translucent color.
- The segment count follows the on-screen outer radius like draw_circle (16 ~ 64 per full turn), and only as many as the drawn angle needs are used.
- centerVector2
- 가운데. (픽셀)Center. (pixels)
- inner_radiusf64
- 안쪽 반지름. (픽셀, 0 이면 부채꼴)Inner radius. (pixels, a sector if 0)
- outer_radiusf64
- 바깥 반지름. (픽셀, 0 이하거나 inner_radius 이하면 그리지 않는다)Outer radius. (pixels, not drawn if 0 or less or not greater than inner_radius)
- start_radianf64
- 시작 각도. (라디안)Start angle. (radians)
- end_radianf64
- 끝 각도. (라디안, 시작과 같으면 그리지 않는다, 차이는 한 바퀴까지만 쓴다)End angle. (radians, not drawn if equal to the start, the difference is used only up to a full turn)
짝Counterpart: vanilla.js Graphic.drawRing
use vanilla::{math, Graphic, Vector2};
fn draw_progress(graphic: &mut Graphic, progress: f64) {
let start_radian = -math::PI / 2.0;
graphic.set_fill_color("#40c057");
graphic.draw_ring(Vector2::create(200.0, 200.0), 40.0, 50.0, start_radian, start_radian + math::PI * 2.0 * progress);
}pub fn draw_arc(&mut self, center: Vector2, radius: f64, start_radian: f64, end_radian: f64, line_width: f64)#호 출력. (반지름을 따라 line_width 두께의 선으로 start_radian 부터 end_radian 까지)
- set_stroke_color()
- 각도와 조각 수는 draw_ring 과 같다. 선의 두께 가운데가 반지름에 온다.
Draws an arc. (a line of line_width thickness along the radius from start_radian to end_radian)
- set_stroke_color()
- Angles and segment count are the same as draw_ring. The middle of the line thickness lies on the radius.
- centerVector2
- 가운데. (픽셀)Center. (pixels)
- radiusf64
- 반지름. (픽셀, 선 두께의 가운데)Radius. (pixels, the middle of the line thickness)
- start_radianf64
- 시작 각도. (라디안)Start angle. (radians)
- end_radianf64
- 끝 각도. (라디안)End angle. (radians)
- line_widthf64
- 선 두께. (픽셀)Line thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawArc
pub fn draw_ring_with_color(&mut self, center: Vector2, inner_radius: f64, outer_radius: f64, start_radian: f64, end_radian: f64, color: Color)#고리 출력의 셈. (draw_ring, draw_arc 가 부른다)
Ring drawing math. (called by draw_ring, draw_arc)
- centerVector2
- 가운데. (픽셀)Center. (pixels)
- inner_radiusf64
- 안쪽 반지름. (픽셀)Inner radius. (pixels)
- outer_radiusf64
- 바깥 반지름. (픽셀, 0 이하거나 inner_radius 이하면 그리지 않는다)Outer radius. (pixels, not drawn if 0 or less or not greater than inner_radius)
- start_radianf64
- 시작 각도. (라디안, 0 이 오른쪽)Start angle. (radians, 0 is to the right)
- end_radianf64
- 끝 각도. (라디안, 시작과 같으면 그리지 않는다, 차이는 한 바퀴까지만 쓴다)End angle. (radians, not drawn if equal to the start, the difference is used only up to a full turn)
- colorColor
- 칠할 색.Color to fill with.
짝Counterpart: vanilla.js Graphic.drawRingWithColor
선분 여럿 출력. (위치 배열 하나에 선분마다 x0, y0, x1, y1 넷씩, 한 번에 그린다)
- set_stroke_color()
- 선분마다 두께만큼 넓힌 네모 하나다. (draw_line 과 달리 이음새를 메우지 않는다, 따로 떨어진 선분 용)
- Vector2 배열을 만들지 않고 숫자 배열을 그대로 읽는다. 길이가 0 인 선분은 건너뛴다.
- 정점 버퍼가 차면 거기까지 그리고 이어서 담는다. (묶어 그리기가 켜져 있으면 같은 텍스처라 한 번의 드로우 콜로 이어진다)
Draws many line segments. (four values x0, y0, x1, y1 per segment in one position array, drawn at once)
- set_stroke_color()
- Each segment is one quad widened by the thickness. (unlike draw_line, joints are not filled, for separate segments)
- Reads the number array as is without building a Vector2 array. Segments of length 0 are skipped.
- When the vertex buffer fills, it draws up to there and continues gathering. (with batching on, it is the same texture so it continues in one draw call)
- position_values&[f64]
- 선분마다 x0, y0, x1, y1 넷씩 놓인 숫자 배열. (픽셀, 넷이 안 되는 끝은 버린다, 4 개 미만이면 그리지 않는다)Number array with four values x0, y0, x1, y1 per segment. (pixels, a trailing remainder of fewer than four is dropped, not drawn if fewer than 4)
- sizef64
- 선 두께. (픽셀)Line thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawLineSegments
use vanilla::{Colors, Graphic};
fn draw_grid(graphic: &mut Graphic) {
let mut position_values: Vec<f64> = Vec::new();
for line_index in 0..=10 {
let offset = line_index as f64 * 32.0;
position_values.extend_from_slice(&[offset, 0.0, offset, 320.0]);
position_values.extend_from_slice(&[0.0, offset, 320.0, offset]);
}
graphic.set_stroke_color(Colors::WHITE);
graphic.draw_line_segments(&position_values, 1.0);
}이미지 출력.
Draws an image.
- image&Rc<Image>
- 그릴 이미지. (채우기 색은 쓰지 않고 틴트와 전역 투명도만 먹는다)Image to draw. (the fill color is not used, only tint and global alpha apply)
- positionVector2
- 왼쪽 위. (픽셀)Top left. (pixels)
- content_sizeVector2
- 그릴 크기. (픽셀, 이미지 전체를 이 크기로 늘린다)Size to draw. (pixels, the whole image is stretched to this size)
짝Counterpart: vanilla.js Graphic.drawImage
pub fn draw_image_with_image_rect(&mut self, image: &Rc<Image>, position: Vector2, content_size: Vector2, image_rect: Rect)#이미지의 일부만 출력. (image_rect 가 비었으면 전체)
Draws only part of an image. (the whole image if image_rect is empty)
- image&Rc<Image>
- 그릴 이미지.Image to draw.
- positionVector2
- 왼쪽 위. (픽셀)Top left. (pixels)
- content_sizeVector2
- 그릴 크기. (픽셀)Size to draw. (pixels)
- image_rectRect
- 그릴 이미지 영역. (이미지 픽셀, 네 값이 모두 0 이면 전체)Image region to draw. (image pixels, the whole image if all four values are 0)
짝Counterpart: vanilla.js Graphic.drawImageWithImageRect
pub fn draw_image_with_source_and_destination(&mut self, image: &Rc<Image>, source_x: f64, source_y: f64, source_width: f64, source_height: f64, destination_x: f64, destination_y: f64, destination_width: f64, destination_height: f64)#이미지의 소스 영역을 지정 영역에 출력. (Canvas2D drawImage 9인자 대응)
- 이미지의 텍스처를 얻지 못하면 그리지 않는다.
Draws a source region of an image into a given region. (equivalent to the 9-argument Canvas2D drawImage)
- Not drawn if the image texture cannot be obtained.
- image&Rc<Image>
- 그릴 이미지.Image to draw.
- source_xf64
- 소스 영역 왼쪽. (이미지 픽셀)Left of the source region. (image pixels)
- source_yf64
- 소스 영역 위. (이미지 픽셀)Top of the source region. (image pixels)
- source_widthf64
- 소스 영역 너비. (이미지 픽셀)Width of the source region. (image pixels)
- source_heightf64
- 소스 영역 높이. (이미지 픽셀)Height of the source region. (image pixels)
- destination_xf64
- 그릴 자리 왼쪽. (픽셀)Left of the destination. (pixels)
- destination_yf64
- 그릴 자리 위. (픽셀)Top of the destination. (pixels)
- destination_widthf64
- 그릴 너비. (픽셀)Width to draw. (pixels)
- destination_heightf64
- 그릴 높이. (픽셀)Height to draw. (pixels)
짝Counterpart: vanilla.js Graphic.drawImageWithSourceAndDestination
pub fn draw_image_with_nine_slice(&mut self, image: &Rc<Image>, position: Vector2, size: Vector2, nine_slice: Rect)#이미지 나인패치 출력.
- nine_slice 의 position.x / position.y / size.x / size.y 가 각각 왼쪽 / 위 / 오른쪽 / 아래 두께.
Draws an image as a nine-patch.
- position.x / position.y / size.x / size.y of nine_slice are the left / top / right / bottom thickness respectively.
- image&Rc<Image>
- 그릴 이미지.Image to draw.
- positionVector2
- 왼쪽 위. (픽셀, 내림한다)Top left. (pixels, floored)
- sizeVector2
- 그릴 크기. (픽셀, 올림하고, 양쪽 두께의 합보다 작으면 그 합)Size to draw. (pixels, ceiled, and the sum of both thicknesses if smaller than that)
- nine_sliceRect
- 네 테두리 두께. (이미지 픽셀이자 그릴 픽셀, 두께가 모두 0 이면 그냥 늘려 그린다)Thickness of the four borders. (both image pixels and drawn pixels, simply stretched if all thicknesses are 0)
짝Counterpart: vanilla.js Graphic.drawImageWithNineSlice
use std::rc::Rc;
use vanilla::{Graphic, Image, Rect, Vector2};
fn draw_panel(graphic: &mut Graphic, panel_image: &Rc<Image>) {
graphic.draw_image_with_nine_slice(panel_image, Vector2::create(20.0, 20.0), Vector2::create(300.0, 120.0), Rect::create(16.0, 16.0, 16.0, 16.0));
}폰트 문자열 설정. (Canvas2D font 대응, 예: "16px DOSGothic")
Sets the font string. (equivalent to Canvas2D font, e.g. "16px DOSGothic")
- font_string&str
- Canvas2D font 꼴 글. ("bold 16px sans-serif" 처럼, 빈 글이면 바꾸지 않는다)Text in Canvas2D font form. (like "bold 16px sans-serif", unchanged if empty)
짝Counterpart: vanilla.js Graphic.setFontString
폰트 문자열 반환.
Returns the font string.
반환Returns&str 지금 폰트 문자열. (처음 "10px sans-serif")Current font string. (initially "10px sans-serif")
짝Counterpart: vanilla.js Graphic.getFontString
가로 정렬 설정.
Sets the horizontal alignment.
- text_alignTextAlign
- 가로 정렬. (처음 Start)Horizontal alignment. (initially Start)
짝Counterpart: vanilla.js Graphic.setTextAlign
가로 정렬 반환.
Returns the horizontal alignment.
반환ReturnsTextAlign 지금 가로 정렬.Current horizontal alignment.
짝Counterpart: vanilla.js Graphic.getTextAlign
글자 방향 설정. (원본 setTextDirection, Canvas2D direction 대응)
- 문단의 방향이다. 글자 안의 순서(양방향 알고리즘)와 정렬 Start / End 의 왼쪽, 오른쪽이 이것을 따른다.
- Inherit 는 Ltr 로 본다. (기본) Auto 는 문자열마다 처음 나오는 방향이 강한 글자로 정한다. 사용자가 쓴 글(닉네임 등)에 쓴다.
Sets the text direction. (the original setTextDirection, corresponds to Canvas2D direction)
- It is the paragraph direction. The order within the text (bidirectional algorithm) and the left and right of alignment Start / End follow it.
- Inherit is treated as Ltr. (default) Auto decides per string by the first strongly directional character. Use it for user-written text (nicknames and such).
- text_directionTextDirection
- 글자 방향. (처음 Inherit)Text direction. (initially Inherit)
짝Counterpart: vanilla.js Graphic.setTextDirection
글자 방향 반환.
Returns the text direction.
반환ReturnsTextDirection 설정한 글자 방향. (Inherit, Auto 를 풀지 않은 그대로, 실제 방향은 resolve_text_direction)The set text direction. (Inherit, Auto as is without resolving, the actual direction is resolve_text_direction)
짝Counterpart: vanilla.js Graphic.getTextDirection
문자열의 실제 방향 계산. (Ltr 또는 Rtl, 원본 resolveTextDirection)
Computes the actual direction of a string. (Ltr or Rtl, the original resolveTextDirection)
- text&str
- Auto 일 때 방향을 볼 문자열.String to check the direction of when Auto.
반환ReturnsTextDirection 설정이 Rtl 이면 Rtl, Auto 면 detect_text_direction(text), 그 밖(Inherit, Ltr)은 Ltr.Rtl if the setting is Rtl, detect_text_direction(text) if Auto, Ltr otherwise (Inherit, Ltr).
짝Counterpart: vanilla.js Graphic.resolveTextDirection
pub fn resolve_text_align(&self, text_align: TextAlign, text_direction: TextDirection) -> TextAlign#실제 가로 정렬 계산. (Start / End 를 방향에 따라 Left / Right 로, 원본 resolveTextAlign)
Computes the actual horizontal alignment. (Start / End to Left / Right by direction, the original resolveTextAlign)
- text_alignTextAlign
- 풀 정렬.Alignment to resolve.
- text_directionTextDirection
- 글자 방향. (Rtl 만 오른쪽에서 왼쪽으로 본다)Text direction. (only Rtl is treated as right to left)
반환ReturnsTextAlign Start 는 Rtl 이면 Right, 아니면 Left. End 는 그 반대. 그 밖은 그대로.Start is Right if Rtl, otherwise Left. End is the opposite. Others stay as is.
짝Counterpart: vanilla.js Graphic.resolveTextAlign
세로 기준선 설정.
Sets the vertical baseline.
- text_baselineTextBaseline
- 세로 기준선. (처음 Alphabetic)Vertical baseline. (initially Alphabetic)
짝Counterpart: vanilla.js Graphic.setTextBaseline
세로 기준선 반환.
Returns the vertical baseline.
반환ReturnsTextBaseline 지금 세로 기준선.Current vertical baseline.
짝Counterpart: vanilla.js Graphic.getTextBaseline
문자열 측정. (현재 폰트 문자열 기준)
Measures a string. (with the current font string)
- text&str
- 잴 문자열.String to measure.
반환ReturnsTextMetrics 잰 값. (픽셀, 지금 변환은 보지 않는다) 데스크탑에서 그릴 얼굴이 하나도 없으면 모두 0 이다.Measured values. (pixels, the current transform is ignored) All 0 on desktop if there is no face to draw with.
짝Counterpart: vanilla.js Graphic.measureText
use vanilla::{Colors, Graphic, Rect, TextAlign, TextBaseline};
fn draw_label(graphic: &mut Graphic, text: &str) {
graphic.set_font_string("20px sans-serif");
let text_metrics = graphic.measure_text(text);
let padding = 8.0;
let box_width = text_metrics.width + padding * 2.0;
let box_height = text_metrics.font_ascent + text_metrics.font_descent + padding * 2.0;
graphic.set_fill_color(Colors::BLACK);
graphic.draw_rect(Rect::create(20.0, 20.0, box_width, box_height));
graphic.set_text_align(TextAlign::Left);
graphic.set_text_baseline(TextBaseline::Top);
graphic.set_fill_color(Colors::WHITE);
graphic.draw_fill_text(text, 20.0 + padding, 20.0 + padding);
}문자열 측정. (주어진 폰트 문자열 기준, 현재 폰트 문자열은 바꾸지 않는다)
Measures a string. (with the given font string, the current font string is not changed)
- font_string&str
- 잴 때 쓸 폰트 문자열. (Canvas2D font 꼴)Font string to measure with. (Canvas2D font form)
- text&str
- 잴 문자열.String to measure.
반환ReturnsTextMetrics 잰 값. (픽셀, 지금 변환은 보지 않는다) 데스크탑에서 그릴 얼굴이 하나도 없으면 모두 0 이다.Measured values. (pixels, the current transform is ignored) All 0 on desktop if there is no face to draw with.
짝Counterpart: vanilla.js Graphic.measureTextWithFontString
텍스트 베이크 스케일 양자화 단위 설정.
- 기본 0.25. 확대 축소가 잦은 글자가 스케일마다 새로 구워지지 않게 묶는다.
- 0 이면 양자화하지 않고 실제 스케일 그대로 굽는다.
Sets the text bake scale quantization step.
- Default 0.25. Groups scales so text that is often zoomed is not baked anew for every scale.
- 0 means no quantization, baking at the actual scale.
- text_bake_scale_stepf64
- 양자화 단위. (0 미만은 0)Quantization step. (0 if less than 0)
짝Counterpart: vanilla.js Graphic.setTextBakeScaleStep
텍스트 베이크 스케일 양자화 단위 반환.
Returns the text bake scale quantization step.
반환Returnsf64 양자화 단위. (처음 0.25)Quantization step. (initially 0.25)
짝Counterpart: vanilla.js Graphic.getTextBakeScaleStep
배율이 움직이는 노드의 텍스트 베이크 스케일 양자화 단위 설정. (기본 0.25)
- 양자화 단위(set_text_bake_scale_step)가 0 일 때, 그리는 노드의 변환 배율이 지난 프레임과 다르면(확대 움직임, 팝업, 트윈, 카메라 확대) 이 단위로 묶은 배율로 굽는다. 프레임마다 다른 배율로 새로 굽지 않는다.
- 배율이 멈추면(지난 프레임과 같으면) 정확한 배율로 다시 구워 1:1 로 또렷하다.
- 0 이면 움직이는 동안에도 묶지 않는다. (지금까지와 같다)
Sets the text bake scale quantization step for nodes whose scale is moving. (default 0.25)
- When the quantization step (set_text_bake_scale_step) is 0 and the transform scale of the drawn node differs from the last frame (zoom motion, popups, tweens, camera zoom), it bakes at the scale grouped by this step. It does not bake anew at a different scale every frame.
- When the scale stops (same as the last frame), it bakes again at the exact scale and is sharp at 1:1.
- 0 means no grouping even while moving. (same as before)
- text_bake_motion_scale_stepf64
- 배율이 움직이는 동안의 양자화 단위. (0 미만은 0)Quantization step while the scale is moving. (0 if less than 0)
짝Counterpart: vanilla.js Graphic.setTextBakeMotionScaleStep
배율이 움직이는 노드의 텍스트 베이크 스케일 양자화 단위 반환.
Returns the text bake scale quantization step for nodes whose scale is changing.
반환Returnsf64 배율이 움직이는 동안의 양자화 단위. (처음 0.25)Quantization step while the scale is moving. (initially 0.25)
짝Counterpart: vanilla.js Graphic.getTextBakeMotionScaleStep
지금 그리는 노드의 배율이 움직이는 중인지 설정. (NodeTree 가 정한다, 노드 밖에서 직접 그릴 때 부르는 쪽이 정할 수 있다)
Sets whether the scale of the node being drawn is moving. (decided by NodeTree, the caller can decide when drawing directly outside a node)
- is_text_bake_scale_movingbool
- 배율이 움직이는 중이면 true.true if the scale is moving.
짝Counterpart: vanilla.js Graphic.setTextBakeScaleMoving
지금 그리는 노드의 배율이 움직이는 중인지 반환.
Returns whether the scale of the node being drawn is changing.
반환Returnsbool 움직이는 중으로 정해져 있으면 true.true if marked as moving.
짝Counterpart: vanilla.js Graphic.isTextBakeScaleMoving
노드의 변환 배율이 지난 프레임과 달라 움직이는 중인지 셈해 정하고, 노드에 기억할 배율을 돌려준다. (NodeTree 가 push_transform 뒤에 부른다)
- last_drawn_maximum_scale 은 그 노드를 지난번 그릴 때의 값이다. (0 이면 아직 모른다, 처음 그리는 노드는 움직이지 않는 것으로 본다)
- 양자화 단위가 0 이 아니면 늘 묶어 굽으므로 셈하지 않고 받은 값을 그대로 돌려준다.
Computes and decides whether the node's transform scale is moving because it differs from the last frame, and returns the scale to remember on the node. (NodeTree calls it after push_transform)
- last_drawn_maximum_scale is the value from when that node was last drawn. (0 means unknown yet, a node drawn for the first time is treated as not moving)
- If the quantization step is not 0 it always bakes grouped, so it returns the given value as is without computing.
- last_drawn_maximum_scalef64
- 그 노드를 지난번 그릴 때 돌려받은 배율. (0 이면 처음)Scale returned when that node was last drawn. (0 if first time)
반환Returnsf64 노드에 기억할 배율. (지금 변환의 가장 큰 배율, 양자화 단위가 0 이 아니거나 움직임 단위가 0 이면 받은 값 그대로)Scale to remember on the node. (the largest scale of the current transform, the given value as is if the quantization step is not 0 or the motion step is 0)
텍스트 픽셀 스냅 설정.
- 켜면 회전 / 기울임이 없는 변환에서 글자 쿼드의 왼쪽 위를 디바이스 픽셀 격자에 맞춘다.
Sets text pixel snapping.
- When on, the top left of glyph quads is aligned to the device pixel grid for transforms without rotation / skew.
- is_text_pixel_snap_enabledbool
- true 면 글자를 디바이스 픽셀에 맞춘다. (처음 false)true aligns text to device pixels. (initially false)
짝Counterpart: vanilla.js Graphic.setTextPixelSnapEnabled
텍스트 픽셀 스냅 여부 반환.
Returns whether text pixel snapping is on.
반환Returnsbool 픽셀 스냅이 켜져 있으면 true.true if pixel snapping is on.
짝Counterpart: vanilla.js Graphic.isTextPixelSnapEnabled
글자 안티앨리어싱 켬 / 끔. (원본 Graphic.setTextAntialiasEnabled)
- 끄면 구운 글자의 알파를 문턱값 128 로 0 과 255 로 가르고 텍스처를 NEAREST 로 뽑는다. (도트 글꼴용)
- 켜고 끈 다음에 굽는 글자부터 적용된다. 이미 구워 둔 글자는 그대로다.
Text antialiasing on / off. (the original Graphic.setTextAntialiasEnabled)
- When off, the alpha of baked text is split into 0 and 255 at threshold 128 and the texture is sampled with NEAREST. (for pixel fonts)
- It applies from text baked after switching. Text already baked stays as it is.
- is_text_antialias_enabledbool
- true 면 켠다. (처음 true)If true, turns it on. (true at first)
짝Counterpart: vanilla.js Graphic.setTextAntialiasEnabled
글자 안티앨리어싱이 켜져 있는지. (원본 Graphic.isTextAntialiasEnabled)
Whether text antialiasing is on. (the original Graphic.isTextAntialiasEnabled)
반환Returnsbool 켜져 있으면 true.true if enabled.
짝Counterpart: vanilla.js Graphic.isTextAntialiasEnabled
텍스트 베이크 스케일 계산. (현재 변환 행렬 기반, 양자화 단위는 set_text_bake_scale_step)
Computes the text bake scale. (based on the current transform matrix, the quantization step is set_text_bake_scale_step)
반환Returnsf64 지금 변환의 가장 큰 배율을 양자화 단위로 반올림한 값. (0.25 ~ 8 로 자른다, 단위가 0 이고 움직이는 중이면 움직임 단위로, 둘 다 0 이면 반올림하지 않는다)The largest scale of the current transform rounded to the quantization step. (clamped to 0.25 ~ 8, to the motion step if the step is 0 and moving, not rounded if both are 0)
짝Counterpart: vanilla.js Graphic.calculateTextBakeScale
pub fn draw_text_entry(&mut self, entry: TextEntry, x: f64, y: f64, color: Option<Color>, text_direction: TextDirection)#글 배치 엔트리를 정렬/베이스라인에 맞춰 글리프 쿼드로 출력.
- 문자열을 통째로 구웠을 때의 사각형 자리(픽셀 스냅 포함)를 셈하고, 그 안의 글리프 사각형을 아틀라스에서 뽑아 그린다.
- text_direction 은 정렬 Start / End 를 가를 방향이다. (Ltr 또는 Rtl, 원본 drawTextEntry 의 textDirection)
Draws a text layout entry as glyph quads aligned to the alignment/baseline.
- Computes the rectangle the whole string would occupy if baked at once (pixel snap included) and draws the glyph rectangles inside it from the atlas.
- text_direction is the direction that decides alignment Start / End. (Ltr or Rtl, textDirection of the original drawTextEntry)
- entryTextEntry
- 글 배치 엔트리. (TextStringTextureCache::get_entry)Text layout entry. (TextStringTextureCache::get_entry)
- xf64
- 기준 x. (가로 정렬의 기준점, 픽셀)Reference x. (reference point of the horizontal alignment, pixels)
- yf64
- 기준 y. (세로 기준선의 기준점, 픽셀)Reference y. (reference point of the vertical baseline, pixels)
- colorOption<Color>
- 곱할 색. (None 이면 흰색, 구운 그대로)Color to multiply by. (white if None, as baked)
- text_directionTextDirection
- 정렬 Start, End 를 가를 방향.Direction that decides alignment Start, End.
짝Counterpart: vanilla.js Graphic.drawTextEntry
텍스트 채움 출력. (Canvas2D fillText 대응)
- set_fill_color() / set_font_string() / set_text_align() / set_text_baseline()
Draws filled text. (corresponds to Canvas2D fillText)
- set_fill_color() / set_font_string() / set_text_align() / set_text_baseline()
- text&str
- 그릴 문자열. (빈 글이면 그리지 않는다)String to draw. (not drawn if empty)
- xf64
- 기준 x. (set_text_align 의 기준점, 픽셀)Reference x. (reference point of set_text_align, pixels)
- yf64
- 기준 y. (set_text_baseline 의 기준점, 픽셀)Reference y. (reference point of set_text_baseline, pixels)
짝Counterpart: vanilla.js Graphic.drawFillText
텍스트 외곽선 출력. (Canvas2D strokeText 대응)
- set_stroke_color() / set_font_string() / set_text_align() / set_text_baseline()
Draws outlined text. (corresponds to Canvas2D strokeText)
- set_stroke_color() / set_font_string() / set_text_align() / set_text_baseline()
- text&str
- 그릴 문자열. (빈 글이면 그리지 않는다)String to draw. (not drawn if empty)
- xf64
- 기준 x. (set_text_align 의 기준점, 픽셀)Reference x. (reference point of set_text_align, pixels)
- yf64
- 기준 y. (set_text_baseline 의 기준점, 픽셀)Reference y. (reference point of set_text_baseline, pixels)
- line_widthf64
- 외곽선 두께. (픽셀)Outline thickness. (pixels)
짝Counterpart: vanilla.js Graphic.drawStrokeText
출력 영역 제한 시작.
- 스텐실 버퍼 기반이라 회전/스케일이 걸린 영역도 정확히 잘린다.
- round_size 를 주면 둥근 사각형으로 잘린다.
- 상태를 push_state 로 쌓으므로 end_clip_rect 와 짝을 맞춰 부른다. (end_clip_rect 가 pop_state 로 되돌린다) 겹쳐 걸면 교집합으로 잘린다.
Starts limiting the draw area.
- Based on the stencil buffer, so rotated/scaled areas are clipped exactly.
- Giving round_size clips to a rounded rectangle.
- Pushes the state with push_state, so call it paired with end_clip_rect. (end_clip_rect restores with pop_state) Nested clips clip to the intersection.
- rectRect
- 자를 사각형. (지금 변환 기준, 픽셀)Rectangle to clip to. (in the current transform, pixels)
- round_sizef64
- 모서리 반지름. (0 이하면 네모)Corner radius. (square if 0 or less)
짝Counterpart: vanilla.js Graphic.beginClipRect
use vanilla::{Colors, Graphic, Rect, Vector2};
fn draw(graphic: &mut Graphic) {
graphic.begin_clip_rect(Rect::create(100.0, 100.0, 200.0, 100.0), 12.0);
graphic.set_fill_color(Colors::WHITE);
graphic.draw_circle(Vector2::create(100.0, 100.0), 80.0);
graphic.end_clip_rect();
}투명도 층 시작. (CSS opacity, 어도비 투명도 묶음처럼 end_opacity_layer 까지 그린 것을 따로 칸에 모았다가 지금 전역 알파로 한 번에 얹는다)
- 층 안의 그림은 서로 겹친 자리가 비치지 않는다. (노드마다 투명도를 곱해 따로 얹으면 겹친 자리에서 아래 그림이 비친다)
- 층 안은 전역 알파 1 에서 시작한다. 층 칸은 화면과 같은 크기의 RGBA8 이고 깊이를 비우고 스텐실을 지금 자르기 깊이로 채워 둬 층 안의 자르기와 3D 패스(run_external_pass 의 is_depth_cleared 거짓)도 그대로 된다. 바깥 자르기는 얹을 때 걸린다. 층은 겹쳐 열 수 있다. 칸을 지을 수 없으면 층 없이 그대로 그린다.
- NodeTree 는 set_opacity_layer 를 켠 노드의 투명도가 1 보다 작으면 그 노드와 자손을 층으로 그린다.
Starts an opacity layer. (Like CSS opacity or an Adobe transparency group, collects what is drawn until end_opacity_layer into a separate target and puts it on at once with the current global alpha)
- Drawings inside the layer do not show through where they overlap each other. (Multiplying opacity per node and putting each on separately shows the drawing below where they overlap)
- The layer starts at global alpha 1. The layer target is an RGBA8 the size of the screen, and its depth is cleared and its stencil is filled with the current clip depth, so clips and 3D passes (is_depth_cleared false in run_external_pass) inside the layer work as they are. The outer clip applies when putting it on. Layers can be nested. If the target cannot be built, draws as is without a layer.
- NodeTree draws a node with set_opacity_layer on and the node's descendants as a layer when its opacity is less than 1.
짝Counterpart: vanilla.js Graphic.beginOpacityLayer
use vanilla::{Graphic, Rect};
fn draw(graphic: &mut Graphic) {
graphic.push_state();
graphic.set_global_alpha(0.5);
graphic.begin_opacity_layer();
graphic.set_fill_color("#ff0000");
graphic.draw_rect(Rect::create(100.0, 100.0, 200.0, 100.0));
graphic.set_fill_color("#0000ff");
graphic.draw_rect(Rect::create(200.0, 150.0, 200.0, 100.0));
graphic.end_opacity_layer();
graphic.pop_state();
}투명도 층 끝. (begin_opacity_layer 뒤에 그린 것을 앞 프레임버퍼에 층을 열 때의 전역 알파로 얹는다)
Ends an opacity layer. (Lays what was drawn after begin_opacity_layer onto the previous framebuffer with the global alpha at the time the layer was opened)
짝Counterpart: vanilla.js Graphic.endOpacityLayer
출력 영역 제한 종료.
Ends clipping the output region.
짝Counterpart: vanilla.js Graphic.endClipRect
셰이더 프로그램 반환. (바꿔 끼운 것이 있으면 그것, 없으면 기본 프로그램)
Returns the shader program. (the override if there is one, otherwise the default program)
반환Returns&ShaderProgram 바꿔 끼운 프로그램이 있으면 그것, 없으면 기본 프로그램.The override program if there is one, otherwise the default program.
짝Counterpart: vanilla.js Graphic.getShaderProgram
셰이더 프로그램 바꿔 끼우기. (None 이면 기본 프로그램으로 복귀)
- 기본 프로그램과 같은 어트리뷰트 위치 / 유니폼 이름(projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture)을 갖춰야 한다.
- 바꿔 끼운 프로그램이 쓰이는 동안 그 프로그램이 사용 중이다. 효과 유니폼은 바꿔 끼운 바로 뒤에 GL 로 직접 올린다.
Overrides the shader program. (returns to the default program if None)
- Must have the same attribute locations / uniform names as the default program (projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture).
- While the override program is in effect, that program is in use. Effect uniforms are uploaded directly through GL right after overriding.
- shader_programOption<Rc<ShaderProgram>>
- 바꿔 끼울 프로그램. (resolve_shader_program 으로 받는다, None 이면 기본 프로그램)Program to override with. (obtained with resolve_shader_program, the default program if None)
짝Counterpart: vanilla.js Graphic.setShaderProgramOverride
pub fn resolve_shader_program(&mut self, program_group_name: &'static str, program_name: &'static str, create_shader_source: impl FnOnce() -> (String, String)) -> Option<Rc<ShaderProgram>>#이름으로 담아 둔 바꿔 끼울 셰이더 프로그램 반환. (없으면 create_shader_source 가 준 버텍스 / 프래그먼트 소스로 만들어 담는다)
- 원본 ShaderSprite 의 컨텍스트별 프로그램 캐시 자리. 러스트 판은 GL 컨텍스트를 든 Graphic 이 담는다.
- 어트리뷰트 위치를 기본 프로그램과 같게 고정해 링크하므로 기본 버텍스 어레이를 그대로 쓴다.
- 만들기에 실패하면 한 번만 알리고 None 을 담아 두어 다시 만들지 않는다.
Returns the override shader program kept by name. (if none, creates and keeps it from the vertex / fragment source given by create_shader_source)
- In place of the per-context program cache of the original ShaderSprite. In the Rust version, Graphic, which holds the GL context, keeps it.
- Links with attribute locations fixed to match the default program, so the default vertex array is used as is.
- If creation fails, it reports once and keeps None so it is not created again.
- program_group_name&'static str
- 묶음 이름. (효과 종류 같은 것, 열쇠의 앞)Group name. (such as the effect kind, the front part of the key)
- program_name&'static str
- 프로그램 이름. (열쇠의 뒤)Program name. (the back part of the key)
- create_shader_sourceimpl FnOnce() -> (String, String)
- 담긴 것이 없을 때만 부르는 함수. ((버텍스 소스, 프래그먼트 소스), GLSL ES 3.00)Function called only when nothing is kept. ((vertex source, fragment source), GLSL ES 3.00)
반환ReturnsOption<Rc<ShaderProgram>> 담아 둔 프로그램. 만들기에 실패했으면 None. (그 뒤로도 None)The kept program. None if creation failed. (None from then on too)
짝Counterpart: vanilla.js Graphic.resolveShaderProgram
use std::rc::Rc;
use vanilla::{Graphic, Image, Vector2};
const GRAY_VERTEXSHADER_SOURCE: &str = "#version 300 es
in vec2 vertexPosition;
in vec2 vertexTextureCoordinate;
uniform mat3 projectionMatrix;
uniform mat3 modelMatrix;
out vec2 fragmentTextureCoordinate;
void main() {
vec3 transformedPosition = projectionMatrix * (modelMatrix * vec3(vertexPosition, 1.0));
gl_Position = vec4(transformedPosition.xy, 0.0, 1.0);
fragmentTextureCoordinate = vertexTextureCoordinate;
}
";
const GRAY_FRAGMENTSHADER_SOURCE: &str = "#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
uniform sampler2D mainTexture;
uniform vec4 mainColor;
uniform float globalAlpha;
out vec4 outputColor;
void main() {
vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate);
float gray = dot(textureColor.rgb, vec3(0.299, 0.587, 0.114));
float alpha = textureColor.a * mainColor.a * globalAlpha;
outputColor = vec4(vec3(gray) * mainColor.a * globalAlpha, alpha);
}
";
fn draw_gray(graphic: &mut Graphic, image: &Rc<Image>) {
let shader_program = graphic.resolve_shader_program("example", "gray", || (GRAY_VERTEXSHADER_SOURCE.to_string(), GRAY_FRAGMENTSHADER_SOURCE.to_string()));
graphic.set_shader_program_override(shader_program);
graphic.draw_image(image, Vector2::create(0.0, 0.0), Vector2::create(128.0, 128.0));
graphic.set_shader_program_override(None);
}렌더 상태 복구. (외부 GL 패스가 프로그램 / 버텍스 어레이 / 뷰포트 / 블렌드를 바꾼 뒤 Graphic 출력을 이어갈 때, 원본 restoreRenderState)
- 스텐실 자르기 상태는 되돌리지 않는다. (run_external_pass 가 끝에 되돌린다, 원본과 같음)
Restores the render state. (for continuing Graphic output after an external GL pass changed the program / vertex array / viewport / blending, the original restoreRenderState)
- Does not restore the stencil clip state. (run_external_pass restores it at the end, same as the original)
짝Counterpart: vanilla.js Graphic.restoreRenderState
드로잉 버퍼 너비 반환. (픽셀, 원본 webGL2RenderingContext.drawingBufferWidth)
Returns the drawing buffer width. (pixels, the original webGL2RenderingContext.drawingBufferWidth)
반환Returnsi32 마지막 apply_settings 의 드로잉 버퍼 너비. (픽셀)Drawing buffer width of the last apply_settings. (pixels)
짝Counterpart: vanilla.js Graphic.getDrawingBufferWidth
드로잉 버퍼 높이 반환. (픽셀, 원본 webGL2RenderingContext.drawingBufferHeight)
Returns the drawing buffer height. (pixels, the original webGL2RenderingContext.drawingBufferHeight)
반환Returnsi32 마지막 apply_settings 의 드로잉 버퍼 높이. (픽셀)Drawing buffer height of the last apply_settings. (pixels)
짝Counterpart: vanilla.js Graphic.getDrawingBufferHeight
지금 그린 화면 읽기. (너비, 높이, 위에서 아래로 놓인 RGBA. 화면을 넘기기 전에 부른다)
- 원본 캔버스처럼 불투명으로 본다. (알파 255)
Reads the screen drawn so far. (width, height, RGBA laid out top to bottom. Call it before presenting)
- Treated as opaque like the original canvas. (alpha 255)
반환Returns(u32, u32, Vec<u8>) (너비, 높이, 픽셀). 픽셀은 위 줄부터 놓인 RGBA 바이트(너비 x 높이 x 4)이고 알파는 모두 255 다. (지금 읽기 프레임버퍼에서 읽는다)(width, height, pixels). Pixels are RGBA bytes laid out from the top row (width x height x 4) and alpha is all 255. (read from the current read framebuffer)
짝Counterpart: vanilla.js Graphic.readFramebufferPixels
3D 색 공간 반환. (원본 getColorSpace, 생성 때 정한 값, 엔진 설정의 color_space)
Returns the 3D color space. (original getColorSpace, fixed at creation, color_space from the engine configuration)
반환Returnscrate::core::colorspace::ColorSpace ColorSpace::Gamma 나 ColorSpace::Linear. (2D 묶음은 어느 값이든 감마 공간에서 합성한다)ColorSpace::Gamma or ColorSpace::Linear. (2D batches are composited in gamma space either way)
짝Counterpart: vanilla.js Graphic.getColorSpace
GL 컨텍스트 반환. (원본 getWebGL2RenderingContext)
- 받은 컨텍스트(GlContext)의 상태 함수는 GL 상태 캐시를 거치므로, 받은 뒤 바꾼 상태를 엔진이 안다. Graphic 은 묶음과 2D 상태를 따로 기억하지 않고 그리기 앞에 상태 캐시에 견주므로, 받은 쪽이 프로그램, 텍스처, 섞기 같은 것을 바꿔도 다음 2D 그리기가 다시 건다.
- 색 쓰기 마스크는 모든 채널로 되돌려 준다. (데스크탑 기본 프레임버퍼에 알파를 쓰지 않으려 Graphic 이 끈 것)
- GL 상태 캐시는 잊지 않는다. (원본과 같음, 안의 glow::Context 는 꺼낼 수 없어 받은 쪽이 상태 캐시를 건너뛰지 못한다)
Returns the GL context. (the original getWebGL2RenderingContext)
- The state functions of the received context (GlContext) go through the GL state cache, so the engine knows state changed after receiving it. Graphic does not remember bindings and 2D state separately and compares against the state cache before drawing, so even if the receiver changes the program, textures, blending, and the like, the next 2D draw sets them again.
- Returns the color write mask to all channels. (what Graphic turned off so as not to write alpha to the desktop default framebuffer)
- Does not forget the GL state cache. (same as the original; the inner glow::Context cannot be taken out, so the receiver cannot skip the state cache)
반환Returns&GlContext Graphic 이 든 GL 컨텍스트. 엔진 함수의 &GlContext 인자로 그대로 넘긴다. (안의 glow::Context 는 꺼낼 수 없다)The GL context the Graphic holds. Pass it as is as the &GlContext argument of engine functions. (The inner glow::Context cannot be taken out)
지금 그리는 프레임 버퍼 반환. (원본 getCurrentFramebuffer, 상태 캐시가 기억한 값, 그리는 중 GL 에 묻지 않는다)
Return the framebuffer being drawn to now. (original getCurrentFramebuffer, the value remembered by the state cache, GL is not asked while drawing)
반환ReturnsOption<GlFramebuffer> 지금 묶인 그리기 프레임 버퍼. 기본 프레임 버퍼(창, 캔버스)면 None.The draw framebuffer bound now. None for the default framebuffer (window, canvas).
짝Counterpart: vanilla.js Graphic.getCurrentFramebuffer
use vanilla::Graphic;
fn draw(graphic: &mut Graphic) {
let framebuffer = graphic.get_current_framebuffer();
let viewport = graphic.get_current_viewport();
println!("{} {} {}", framebuffer.is_none(), viewport.get_width(), viewport.get_height());
graphic.reset_gl_state_cache();
}지금 뷰포트 반환. (원본 getCurrentViewport, 픽셀, 왼쪽 아래가 원점, 상태 캐시가 기억한 값)
Return the current viewport. (original getCurrentViewport, pixels, bottom-left origin, the value remembered by the state cache)
반환ReturnsRect 뷰포트 사각형. (x, y, 너비, 높이)Viewport rectangle. (x, y, width, height)
짝Counterpart: vanilla.js Graphic.getCurrentViewport
GL 상태 캐시 잊기. (원본 resetGLStateCache, 상태 캐시를 거치지 않고 GL 상태를 바꾼 뒤 부른다, 다음에 읽을 때 GL 에 한 번씩 묻는다)
- get_gl, run_external_pass, 툰 렌더러의 콜백이 주는 GlContext 는 상태 함수가 상태 캐시를 거치므로, 같은 콜백 안에서 엔진 그리기를 이어 불러도 부를 것 없다.
- GlContext 는 안의 glow::Context 를 꺼낼 길이 없어 게임 코드로는 상태 캐시를 건너뛰지 못한다. 다른 라이브러리가 같은 GL 컨텍스트의 상태를 바꾼 뒤 같은 콜백 안에서 엔진 그리기를 이어 부를 때 부른다.
- 엔진은 GL 을 넘기는 자리(get_gl, run_external_pass, 툰 렌더러의 콜백)에서 스스로 잊지 않는다. (원본과 같음)
- 상태 캐시를 거치지 않은 호출을 찾으려면 환경 변수 VANILLA_GL_STATE_CHECK=1 로 돌린다. (엔진 그리기 앞마다 기억한 값과 진짜 GL 을 견주어 어긋난 곳과 앞의 상태 호출을 표준 오류에 남긴다)
Reset the GL state cache. (original resetGLStateCache, call it after changing GL state without going through the state cache; each value is asked from GL once on the next read)
- The GlContext given by get_gl, run_external_pass and toon renderer callbacks sends state functions through the state cache, so there is no need to call this even when engine drawing continues inside the same callback.
- GlContext has no way to take out the inner glow::Context, so game code cannot bypass the state cache. Call it when another library changed the state of the same GL context and engine drawing continues inside the same callback.
- The engine does not reset by itself where it hands GL over (get_gl, run_external_pass, toon renderer callbacks). (Same as the original)
- To find calls that bypassed the state cache, run with the environment variable VANILLA_GL_STATE_CHECK=1. (Before every engine draw it compares the remembered values with real GL and prints the mismatched part and the preceding state calls to standard error)
짝Counterpart: vanilla.js Graphic.resetGLStateCache
WebGL 컨텍스트를 잃은 상태인지. (원본 isContextLost, 웹이 webglcontextlost 에서 참이 되고 엔진이 기본 자원을 다시 지은 뒤 거짓이 된다)
- 잃은 동안 엔진은 그리지 않고 씬 갱신만 한다. 데스크탑은 컨텍스트를 잃지 않아 늘 false 다.
Whether the WebGL context is lost. (The original's isContextLost, true after webglcontextlost on the web and false again once the engine has rebuilt its base resources)
- While lost, the engine does not draw and only updates scenes. Desktop never loses the context, so this is always false.
반환Returnsbool 잃은 동안 true.true while lost.
짝Counterpart: vanilla.js Graphic.isContextLost
use vanilla::{Colors, Graphic, Rect};
fn draw(graphic: &mut Graphic) {
if graphic.is_context_lost() {
return;
}
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(8.0, 8.0, 32.0, 32.0));
}GPU 메모리 셈 켜기. (원본 Graphic.enableGpuMemoryTracking, 개발용)
- 켠 뒤에 지은 텍스처, 렌더버퍼, 버퍼부터 센다. 이미 켰으면 아무것도 하지 않는다. 켜기 전에는 GL 짓기와 크기 정하기 호출이 깃발 하나만 보고 지나가 프레임에 드는 일이 없다. 엔진이 처음 짓는 자원까지 세려면 EngineConfiguration::track_gpu_memory.
Turns GPU memory tracking on. (original Graphic.enableGpuMemoryTracking, for development)
- Counts the textures, renderbuffers and buffers created after it is turned on. Does nothing if it is already on. Before it is on, GL creation and sizing calls only look at one flag, so nothing runs per frame. To count the resources the engine creates first, use EngineConfiguration::track_gpu_memory.
짝Counterpart: vanilla.js Graphic.enableGpuMemoryTracking
use vanilla::Graphic;
fn enable(graphic: &Graphic) {
graphic.enable_gpu_memory_tracking();
assert!(graphic.is_gpu_memory_tracking_enabled());
}GPU 메모리 셈이 켜져 있는지. (원본 Graphic.isGpuMemoryTrackingEnabled)
Whether GPU memory tracking is on. (original Graphic.isGpuMemoryTrackingEnabled)
반환Returnsbool 켜져 있으면 true.true if enabled.
짝Counterpart: vanilla.js Graphic.isGpuMemoryTrackingEnabled
use vanilla::Graphic;
fn check(graphic: &Graphic) -> bool {
graphic.is_gpu_memory_tracking_enabled()
}GPU 메모리 읽기. (원본 Graphic.readGpuMemoryUsage, 개발용)
- 텍스처, 렌더버퍼, 버퍼가 쓰는 GPU 메모리를 종류별과 주인별로 읽는다. (형식과 크기로 셈한 이름값, 멀티샘플 렌더버퍼는 샘플 수를 곱한다) 셈이 꺼져 있으면 이 호출이 켜고 그 뒤에 지은 것부터 센다. 처음부터 다 세려면 EngineConfiguration::track_gpu_memory 를 true 로 둔다.
Reads GPU memory. (original Graphic.readGpuMemoryUsage, for development)
- Reads the GPU memory used by textures, renderbuffers and buffers by kind and by owner. (nominal values computed from format and size; multisample renderbuffers multiply by the sample count) If tracking is off, this call turns it on and counts what is created after it. To count everything from the start, set EngineConfiguration::track_gpu_memory to true.
반환Returnscrate::core::gpumemorytracker::GpuMemoryUsage 합(캔버스 기본 프레임 버퍼 몫 포함), 캔버스 몫, 종류별 몫, 주인별 몫(큰 것부터, 주인은 지은 호출 스택의 위쪽 세 칸).The total (including the canvas default framebuffer share), the canvas share, the share by kind and by owner (largest first; the owner is the top three frames of the creating call stack).
짝Counterpart: vanilla.js Graphic.readGpuMemoryUsage
use vanilla::Graphic;
fn read(graphic: &Graphic) {
let usage = graphic.read_gpu_memory_usage();
println!("{} {}", usage.total_bytes, usage.owner_list.len());
}버텍스 어레이 반환. (기본 그리기의 것, GL 을 만지려면 get_gl 로 컨텍스트를 받는다)
Returns the vertex array. (the one for default drawing, get the context with get_gl to touch GL)
반환ReturnsGlVertexArray 기본 버텍스 어레이.Default vertex array.
짝Counterpart: vanilla.js Graphic.getVertexArray
버텍스 버퍼 반환.
Returns the vertex buffer.
반환ReturnsGlBuffer 기본 버텍스 버퍼.Default vertex buffer.
짝Counterpart: vanilla.js Graphic.getVertexBuffer
스크래치 버텍스 데이터 반환. (write_quad 와 draw_vertices 가 쓰는 배열)
Returns the scratch vertex data. (the array write_quad and draw_vertices use)
반환Returns&mut [f32] 스크래치 버텍스 배열. (정점 4096 개, 정점마다 x, y, u, v 플로트 4 개)Scratch vertex array. (4096 vertices, 4 floats x, y, u, v per vertex)
짝Counterpart: vanilla.js Graphic.getVertexData
흰색 텍스처 반환.
Returns the white texture.
반환ReturnsGlTexture 1 x 1 흰색 텍스처. (단색 그리기에 쓴다)1 x 1 white texture. (used for solid color drawing)
짝Counterpart: vanilla.js Graphic.getWhiteTexture
흰색 반환.
Returns white.
반환ReturnsColor 흰색. (draw_vertices 에 텍스처 색 그대로 그릴 때 넘긴다)White. (passed to draw_vertices to draw the texture color as is)
짝Counterpart: vanilla.js Graphic.getWhiteColor
이미지 텍스처 캐시 반환.
Returns the image texture cache.
반환Returns&ImageTextureCache 이미지 텍스처 캐시.Image texture cache.
짝Counterpart: vanilla.js Graphic.getImageTextureCache
문자열 텍스처 캐시 반환. (폰트 등록)
Returns the string texture cache. (for font registration)
반환Returns&mut TextStringTextureCache 문자열 텍스처 캐시.String texture cache.
짝Counterpart: vanilla.js Graphic.getTextStringTextureCache
함수Functions
오른쪽에서 왼쪽으로 쓰는 글자인지. (원본 RIGHT_TO_LEFT_CHARACTER_PATTERN: 히브리어, 아랍어, 시리아어, 타나, 은코 등과 그 표현형)
Whether a character is written right to left. (the original RIGHT_TO_LEFT_CHARACTER_PATTERN: Hebrew, Arabic, Syriac, Thaana, N'Ko and others and their presentation forms)
- characterchar
- 볼 글자.Character to check.
반환Returnsbool 코드 포인트가 U+0590 ~ U+08FF, U+FB1D ~ U+FDFF, U+FE70 ~ U+FEFF, U+10800 ~ U+10FFF, U+1E800 ~ U+1EFFF 안이면 true.true if the code point is within U+0590 ~ U+08FF, U+FB1D ~ U+FDFF, U+FE70 ~ U+FEFF, U+10800 ~ U+10FFF, U+1E800 ~ U+1EFFF.
글의 첫 강한 방향. (원본 resolveTextDirection 의 "auto": 글자 갈래 문자와 LRM, RLM, ALM 가운데 처음 것, 없으면 Ltr)
First strong direction of the text. (the "auto" of the original resolveTextDirection: the first of letter category characters and LRM, RLM, ALM, Ltr if none)
- text&str
- 볼 문자열.String to check.
반환ReturnsTextDirection 처음 나오는 강한 글자(글자 갈래 문자와 LRM, RLM, ALM)가 오른쪽에서 왼쪽 글자나 RLM(U+200F), ALM(U+061C)이면 Rtl, 그 밖이면 Ltr. 강한 글자가 없으면 Ltr.Rtl if the first strong character (letter category characters and LRM, RLM, ALM) is a right-to-left character or RLM (U+200F), ALM (U+061C), otherwise Ltr. Ltr if there is no strong character.
짝Counterpart: vanilla.js detectTextDirection
use vanilla::{detect_text_direction, TextDirection};
assert_eq!(detect_text_direction("Hello"), TextDirection::Ltr);
assert_eq!(detect_text_direction("123 \u{05E9}\u{05DC}\u{05D5}\u{05DD}"), TextDirection::Rtl);
assert_eq!(detect_text_direction("\u{200F}abc"), TextDirection::Rtl);
assert_eq!(detect_text_direction("2024!"), TextDirection::Ltr);상수Constants
버텍스 1개당 float 수. (x, y, u, v)
Number of floats per vertex. (x, y, u, v)
반환Returnsusize
파티클 버텍스 1개당 float 수. (x, y, u, v, r, g, b, a)
Number of floats per particle vertex. (x, y, u, v, r, g, b, a)
반환Returnsusize
BlendModeenum traits Clone, Copy, Debug, PartialEq, Eq, Hash
블렌드 모드. (원본 SpriteBlendMode, Canvas2D globalCompositeOperation 대응)
- 26 가지 모두 그린다. 13 가지(포터 더프 연산자, Lighter, Multiply, Screen)는 고정 블렌딩, 나머지 13 가지는 그릴 영역 아래를 떠 와 셰이더로 섞는다. (원본과 같음)
- Canvas2D 는 SourceIn, SourceOut, DestinationIn, DestinationAtop, Copy 가 그린 도형 밖(자르기 안 전체)도 지우지만, Graphic 은 그린 도형 안만 바꾼다. (원본과 같음)
Blend mode. (the original SpriteBlendMode, corresponds to Canvas2D globalCompositeOperation)
- All 26 are drawn. 13 (Porter-Duff operators, Lighter, Multiply, Screen) use fixed blending, and the other 13 grab what is under the draw area and mix it in a shader. (same as the original)
- In Canvas2D, SourceIn, SourceOut, DestinationIn, DestinationAtop, Copy also erase outside the drawn shape (the whole clip area), but Graphic changes only inside the drawn shape. (same as the original)
| 이름Name | 설명Description |
|---|---|
Normal | 기본 알파 합성. ("source-over", 고정 블렌딩)Default alpha compositing. ("source-over", fixed blending) |
SourceIn | 바탕과 겹친 곳만 그린다. ("source-in", 바탕 알파를 마스크로, 고정 블렌딩)Draws only where it overlaps the backdrop. ("source-in", backdrop alpha as a mask, fixed blending) |
SourceOut | 바탕과 겹치지 않은 곳만 그린다. ("source-out", 고정 블렌딩)Draws only where it does not overlap the backdrop. ("source-out", fixed blending) |
SourceAtop | 바탕 위의 겹친 곳에만 합성한다. ("source-atop", 고정 블렌딩)Composites only over the overlapping part of the backdrop. ("source-atop", fixed blending) |
DestinationOver | 바탕 아래에 합성한다. ("destination-over", 고정 블렌딩)Composites under the backdrop. ("destination-over", fixed blending) |
DestinationIn | 바탕에서 겹친 곳만 남긴다. ("destination-in", 고정 블렌딩)Keeps only the overlapping part of the backdrop. ("destination-in", fixed blending) |
DestinationOut | 바탕에서 겹치지 않은 곳만 남긴다. ("destination-out", 고정 블렌딩)Keeps only the non-overlapping part of the backdrop. ("destination-out", fixed blending) |
DestinationAtop | 겹친 곳은 바탕을 남기고, 바탕이 없는 곳은 그린 것을 둔다. ("destination-atop", 고정 블렌딩)Keeps the backdrop where they overlap, and puts the drawing where there is no backdrop. ("destination-atop", fixed blending) |
Lighter | 색을 더한다. ("lighter", 고정 블렌딩)Adds colors. ("lighter", fixed blending) |
Copy | 바탕을 보지 않고 그린 것만 둔다. ("copy", 고정 블렌딩)Puts only the drawing, ignoring the backdrop. ("copy", fixed blending) |
Xor | 겹친 곳을 빼고 둘 다 둔다. ("xor", 고정 블렌딩)Keeps both except where they overlap. ("xor", fixed blending) |
Multiply | 곱하기 합성. ("multiply", 어두워진다, 기본 프레임버퍼는 고정 블렌딩, 렌더 타겟은 셰이더 섞기)Multiply compositing. ("multiply", darkens, fixed blending on the default framebuffer, shader mixing on render targets) |
Screen | 스크린 합성. ("screen", 밝아진다, 고정 블렌딩)Screen compositing. ("screen", lightens, fixed blending) |
Overlay | 오버레이. ("overlay", 명암을 키운다, 셰이더 섞기)Overlay. ("overlay", increases contrast, shader mixing) |
Darken | 어두운 쪽을 고른다. ("darken", 셰이더 섞기)Picks the darker one. ("darken", shader mixing) |
Lighten | 밝은 쪽을 고른다. ("lighten", 셰이더 섞기)Picks the lighter one. ("lighten", shader mixing) |
ColorDodge | 컬러 닷지. ("color-dodge", 밝아진다, 셰이더 섞기)Color dodge. ("color-dodge", lightens, shader mixing) |
ColorBurn | 컬러 번. ("color-burn", 어두워진다, 셰이더 섞기)Color burn. ("color-burn", darkens, shader mixing) |
HardLight | 하드 라이트. ("hard-light", 셰이더 섞기)Hard light. ("hard-light", shader mixing) |
SoftLight | 소프트 라이트. ("soft-light", 셰이더 섞기)Soft light. ("soft-light", shader mixing) |
Difference | 차이 합성. ("difference", 셰이더 섞기)Difference compositing. ("difference", shader mixing) |
Exclusion | 대비가 낮은 차이 합성. ("exclusion", 셰이더 섞기)Lower contrast difference compositing. ("exclusion", shader mixing) |
Hue | 그린 것의 색조에 바탕의 채도와 밝기. ("hue", 셰이더 섞기)Hue of the drawing with the saturation and luminosity of the backdrop. ("hue", shader mixing) |
Saturation | 그린 것의 채도에 바탕의 색조와 밝기. ("saturation", 셰이더 섞기)Saturation of the drawing with the hue and luminosity of the backdrop. ("saturation", shader mixing) |
Color | 그린 것의 색조와 채도에 바탕의 밝기. ("color", 셰이더 섞기)Hue and saturation of the drawing with the luminosity of the backdrop. ("color", shader mixing) |
Luminosity | 그린 것의 밝기에 바탕의 색조와 채도. ("luminosity", 셰이더 섞기)Luminosity of the drawing with the hue and saturation of the backdrop. ("luminosity", shader mixing) |
원본 이름으로 찾기. (모르는 이름이면 None. 타임라인, 파티클 서술처럼 JSON 에서 읽을 때 쓴다)
Finds by the original name. (None for unknown names. Used when reading from JSON such as timelines and particle descriptions)
- name&str
- 원본 globalCompositeOperation 이름. ("multiply" 처럼 소문자와 하이픈, 대소문자를 가린다)The original globalCompositeOperation name. (lowercase and hyphens like "multiply", case-sensitive)
반환ReturnsOption<BlendMode> 이름에 맞는 블렌드 모드. 모르는 이름이면 None.Blend mode matching the name. None for unknown names.
use vanilla::BlendMode;
assert_eq!(BlendMode::from_name("multiply"), Some(BlendMode::Multiply));
assert_eq!(BlendMode::from_name("source-over"), Some(BlendMode::Normal));
assert_eq!(BlendMode::from_name("unknown"), None);
assert_eq!(BlendMode::ColorDodge.get_name(), "color-dodge");원본 이름 반환. ("source-over" 같은 문자열)
Returns the original name. (a string like "source-over")
반환Returns&'static str 원본 globalCompositeOperation 이름. (Normal 은 "source-over")The original globalCompositeOperation name. ("source-over" for Normal)
TextAlignenum traits Clone, Copy, Debug, PartialEq, Eq
가로 정렬.
Horizontal alignment.
| 이름Name | 설명Description |
|---|---|
Left | 왼쪽 맞춤. (x 가 글의 왼쪽 끝)Left aligned. (x is the left end of the text) |
Center | 가운데 맞춤. (x 가 글의 가로 가운데)Center aligned. (x is the horizontal center of the text) |
Right | 오른쪽 맞춤. (x 가 글의 오른쪽 끝)Right aligned. (x is the right end of the text) |
Start | 글 방향의 시작 쪽 맞춤. (Ltr 은 왼쪽, Rtl 은 오른쪽, Graphic 의 처음 값)Aligned to the start side of the text direction. (left for Ltr, right for Rtl, the initial value of Graphic) |
End | 글 방향의 끝 쪽 맞춤. (Ltr 은 오른쪽, Rtl 은 왼쪽)Aligned to the end side of the text direction. (right for Ltr, left for Rtl) |
TextBaselineenum traits Clone, Copy, Debug, PartialEq, Eq
세로 기준선.
Vertical baseline.
| 이름Name | 설명Description |
|---|---|
Top | 위 끝 기준. (y 가 글꼴 어센트의 위 끝)Top baseline. (y is the top of the font ascent) |
Middle | 가운데 기준. (y 가 어센트 위 끝과 디센트 아래 끝의 가운데)Middle baseline. (y is midway between the top of the ascent and the bottom of the descent) |
Bottom | 아래 끝 기준. (y 가 글꼴 디센트의 아래 끝)Bottom baseline. (y is the bottom of the font descent) |
Ideographic | 표의 문자 기준선. (Bottom 과 같이 y 가 디센트의 아래 끝)Ideographic baseline. (like Bottom, y is the bottom of the descent) |
Hanging | 매달린 기준선. (y 가 기준선에서 어센트의 0.8 배 위)Hanging baseline. (y is 0.8 times the ascent above the baseline) |
Alphabetic | 알파벳 기준선. (y 가 기준선, Graphic 의 처음 값)Alphabetic baseline. (y is the baseline, the initial value of Graphic) |
TextDirectionenum traits Clone, Copy, Debug, PartialEq, Eq, Hash
글자 방향. (원본 "inherit" | "ltr" | "rtl" | "auto", Canvas2D direction)
- Inherit 는 Graphic 에서는 왼쪽에서 오른쪽으로 본다. 글자 컴포넌트에서는 그리는 때의 Graphic 방향을 따른다는 뜻이다.
- Auto 는 문자열마다 처음 나오는 방향이 강한 글자로 정한다. (HTML 의 dir="auto", 없으면 왼쪽에서 오른쪽)
Text direction. (the original "inherit" | "ltr" | "rtl" | "auto", Canvas2D direction)
- Inherit is treated as left to right in Graphic. In text components it means following the Graphic direction at draw time.
- Auto decides per string by the first strongly directional character. (dir="auto" of HTML, left to right if none)
| 이름Name | 설명Description |
|---|---|
Inherit | 물려받기. (Graphic 의 처음 값, Graphic 에서는 Ltr 로 본다)Inherit. (the initial value of Graphic, treated as Ltr in Graphic) |
Ltr | 왼쪽에서 오른쪽.Left to right. |
Rtl | 오른쪽에서 왼쪽.Right to left. |
Auto | 문자열마다 처음 나오는 방향이 강한 글자로 정한다. (없으면 Ltr)Decides per string by the first strongly directional character. (Ltr if none) |
원본 글로 읽기. ("ltr", "rtl", "auto", 그 밖은 Inherit)
Reads from the original text. ("ltr", "rtl", "auto", Inherit otherwise)
- name&str
- 원본 글. ("inherit", "ltr", "rtl", "auto", 대소문자를 가린다)Original text. ("inherit", "ltr", "rtl", "auto", case-sensitive)
반환ReturnsTextDirection 읽은 방향. 모르는 글이면 Inherit.The read direction. Inherit for unknown text.
원본 글. ("inherit", "ltr", "rtl", "auto")
Original text. ("inherit", "ltr", "rtl", "auto")
반환Returns&'static str 원본 글. ("inherit", "ltr", "rtl", "auto" 가운데 하나)Original text. (one of "inherit", "ltr", "rtl", "auto")
모양 짓기 방향. (Rtl 만 오른쪽에서 왼쪽, 실제 방향으로 푼 뒤에 쓴다)
Shaping direction. (only Rtl is right to left, used after resolving to the actual direction)
반환ReturnsShapingDirection Rtl 이면 ShapingDirection::RightToLeft, 그 밖(Inherit, Auto 포함)은 ShapingDirection::LeftToRight.ShapingDirection::RightToLeft if Rtl, otherwise (including Inherit, Auto) ShapingDirection::LeftToRight.
ImageSmoothingQualityenum traits Clone, Copy, Debug, PartialEq, Eq
이미지 스무딩 퀄리티. (원본 setImageSmoothingQuality 의 "low", "medium", "high")
- GL 은 LINEAR / NEAREST 둘뿐이라 원본처럼 보관만 한다.
Image smoothing quality. ("low", "medium", "high" of the original setImageSmoothingQuality)
- GL only has LINEAR / NEAREST, so it is only stored like the original.
| 이름Name | 설명Description |
|---|---|
Low | 낮음. ("low")Low. ("low") |
Medium | 중간. ("medium")Medium. ("medium") |
High | 높음. ("high", Graphic 의 처음 값)High. ("high", the initial value of Graphic) |