core/graphic
그래픽.
Graphics.
GeometryKeyextends Object
기하 캐시 열쇠. (Component.writeGeometryKey 가 그리기 입력을 적는 곳)
- add 로 적은 값을 지난번에 적은 값과 차례대로 === 로 견준다. 하나라도 다르거나 수가 다르면 바뀐 것으로 본다.
- 견주며 바로 덮어 적으므로 프레임마다 배열을 새로 만들지 않는다.
Geometry cache key. (where Component.writeGeometryKey writes its draw inputs)
- Compares the values written with add against the previous ones in order with ===. If any differs or the count differs, it counts as changed.
- Overwrites while comparing, so it does not create a new array every frame.
import { GeometryKey } from "./build/vanilla.js";
const geometryKey = new GeometryKey();
geometryKey.begin();
geometryKey.add(10);
geometryKey.add("#ff0000");
console.log(geometryKey.end());
geometryKey.begin();
geometryKey.add(10);
geometryKey.add("#ff0000");
console.log(geometryKey.end());
geometryKey.begin();
geometryKey.add(12);
geometryKey.add("#ff0000");
console.log(geometryKey.end());적기 시작. (Graphic 이 writeGeometryKey 앞에 부른다)
Starts writing. (Graphic calls it before writeGeometryKey)
짝Counterpart: vanilla-engine GeometryKey.begin
값 하나 적기. (숫자, 문자열, 참거짓, 객체 참조, null)
Writes one value. (number, string, boolean, object reference, null)
- value*
- 그리기가 읽는 값. (객체는 참조로 견주므로, 안의 값이 바뀔 수 있는 Color 같은 것은 칸을 따로 적는다)A value the draw reads. (objects are compared by reference, so write the fields of mutable values such as Color separately)
짝Counterpart: vanilla-engine GeometryKey.add
적기 끝. (지난번과 같으면 true)
Ends writing. (true if same as last time)
반환Returnsboolean 이번에 적은 값이 지난번과 모두 같으면 참. (처음 적은 때는 거짓)True if every value written this time equals the previous ones. (false the first time)
짝Counterpart: vanilla-engine GeometryKey.end
Graphicextends Object
그래픽.
- Canvas 의 WebGL2 렌더링 컨텍스트를 통해 출력하는 렌더러.
- Canvas2D 시절의 좌표계(좌상 원점, 픽셀 단위)와 상태 모델(변환/알파 스택)을 그대로 재현한다. 모든 드로우는 drawVertices() 한 지점으로 수렴한다.
Graphics.
- A renderer that outputs through the Canvas's WebGL2 rendering context.
- Reproduces the Canvas2D-era coordinate system (top-left origin, pixel units) and state model (transform/alpha stack) as is. All draws converge on the single point drawVertices().
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.setFillColor("#203040");
graphic.drawRoundRect(Rect.create(40, 40, 260, 160), 16);
graphic.setStrokeColor("#ffcc00");
graphic.drawStrokeCircle(Vector2.create(460, 120), 60, 4);
graphic.setFillColor("#ffffff");
graphic.setFontString("24px sans-serif");
graphic.setTextAlign("center");
graphic.setTextBaseline("middle");
graphic.drawFillText("Graphic", 170, 120);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());constructor(canvas, preserveDrawingBuffer, antialias = true, colorSpace = ColorSpace.gamma, trackGpuMemory = false)#생성.
Constructor.
- canvasHTMLCanvasElement
- 그릴 캔버스. (WebGL2 컨텍스트를 얻지 못하면 오류를 던진다)Canvas to draw on. (throws an error if a WebGL2 context is unavailable)
- preserveDrawingBufferboolean
- 프레임이 끝난 뒤에도 그린 것을 캔버스에 남길지. (true 일 때만 남긴다)Whether drawings stay on the canvas after the frame ends. (kept only when true)
- antialiasboolean
- 캔버스의 멀티샘플 안티에일리어싱을 켤지. (기본 true, false 일 때만 끈다)Whether to enable multisample anti-aliasing on the canvas. (default true, turned off only when false)
- colorSpacestring
- 3D 색 공간. (ColorSpace, 기본 ColorSpace.gamma, 엔진은 EngineConfiguration.colorSpace 를 넘긴다)3D color space. (ColorSpace, default ColorSpace.gamma, the engine passes EngineConfiguration.colorSpace)
- trackGpuMemoryboolean
- GPU 메모리 셈을 처음부터 켤지. (기본 false, 엔진은 EngineConfiguration.trackGpuMemory 를 넘긴다)Whether to turn on GPU memory tracking from the start. (Default false, the engine passes EngineConfiguration.trackGpuMemory)
짝Counterpart: vanilla-engine Graphic.new
설정 반영. (매 프레임 시작 시 엔진이 호출)
- 캔버스 크기 변화 감지 및 뷰포트/프로젝션 갱신.
- 프레임 시작 기준 상태로 리셋.
Applies settings. (called by the engine at the start of every frame)
- Detects canvas size changes and updates the viewport/projection.
- Resets to the frame-start baseline state.
- engineEngine
- 엔진.Engine.
짝Counterpart: vanilla-engine Graphic.apply_settings
이미지 스무딩 활성화 여부 설정.
- 도트(픽셀) 스프라이트 게임은 false 로 설정해 선명하게 렌더링.
Sets whether image smoothing is enabled.
- Pixel-art (dot) sprite games set this to false to render crisply.
- valueboolean
- 참이면 이미지를 부드럽게(LINEAR), 거짓이면 또렷하게(NEAREST) 뽑는다.Samples images smoothly (LINEAR) if true, crisply (NEAREST) if false.
짝Counterpart: vanilla-engine Graphic.set_image_smoothing_enabled
이미지 스무딩 활성화 여부 반환.
Returns whether image smoothing is enabled.
반환Returnsboolean 이미지 스무딩이 켜졌으면 참.True if image smoothing is on.
짝Counterpart: vanilla-engine Graphic.is_image_smoothing_enabled
이미지 밉맵 활성화 여부 설정. (기본 false)
- 켜면 스무딩이 켜진 이미지 텍스처에 밉맵을 만들고 축소 필터를 LINEAR_MIPMAP_LINEAR 로 한다.
- 큰 그림(아틀라스 등)을 크게 줄여 그릴 때 가장자리의 계단과 자글거림이 줄어든다.
- 아틀라스는 그림 둘레의 여백(늘여 붙인 가장자리)이 넉넉해야 작은 밉맵 단계에서 옆 그림이 번져 들지 않는다.
Sets whether image mipmaps are enabled. (default false)
- When on, builds mipmaps for image textures with smoothing on and sets the minification filter to LINEAR_MIPMAP_LINEAR.
- Reduces stair-stepping and shimmering at the edges when large images (atlases, etc.) are drawn heavily scaled down.
- An atlas needs generous padding (stretched edges) around each image so neighboring images do not bleed in at small mipmap levels.
- valueboolean
- 이미지 밉맵을 켤지.Whether to enable image mipmaps.
짝Counterpart: vanilla-engine Graphic.set_image_mipmap_enabled
이미지 밉맵 활성화 여부 반환.
Returns whether image mipmaps are enabled.
반환Returnsboolean 이미지 밉맵이 켜졌으면 참.True if image mipmaps are on.
짝Counterpart: vanilla-engine Graphic.is_image_mipmap_enabled
이미지 밉맵 단계 보정 설정. (기본 0)
- 밉맵 단계를 고를 때 더하는 값. 음수면 한 단계 큰 그림 쪽을 골라 또렷해지고, 너무 작으면 다시 자글거린다. (-0.5 안팎)
- 기본 셰이더(낱장, 묶어 그리기, 파티클)에 적용한다. 바꿔 끼운 셰이더는 textureLodBias 유니폼이 있으면 받는다.
Sets the image mipmap level bias. (default 0)
- Value added when choosing the mipmap level. Negative picks the next larger image and looks sharper; too small and it shimmers again. (around -0.5)
- Applies to the default shaders (single image, sprite batching, particles). A swapped-in shader receives it if it has a textureLodBias uniform.
- valuenumber
- 밉맵 단계에 더할 값. (음수면 또렷해진다)Value added to the mipmap level. (sharper if negative)
짝Counterpart: vanilla-engine Graphic.set_image_mipmap_bias
이미지 밉맵 단계 보정 반환.
Returns the image mipmap level bias.
반환Returnsnumber 밉맵 단계 보정 값.Mipmap level bias.
짝Counterpart: vanilla-engine Graphic.get_image_mipmap_bias
이미지 스무딩 퀄리티 설정. ("low", "medium", "high")
- WebGL2 에서는 LINEAR/NEAREST 이분법이라 보관만 한다.
Sets the image smoothing quality. ("low", "medium", "high")
- WebGL2 only has the LINEAR/NEAREST choice, so the value is only stored.
- valuestring
- "low", "medium", "high" 가운데. (보관만 한다)One of "low", "medium", "high". (only stored)
짝Counterpart: vanilla-engine Graphic.set_image_smoothing_quality
이미지 스무딩 퀄리티 반환. ("low", "medium", "high", 처음은 "high")
Returns the image smoothing quality. ("low", "medium", "high", initially "high")
반환Returnsstring 이미지 스무딩 퀄리티.Image smoothing quality.
짝Counterpart: vanilla-engine Graphic.get_image_smoothing_quality
모든 기즈모 강제 표시 설정.
Sets forced display of all gizmos.
- isForceGizmosVisibleboolean
- 참이면 노드마다의 설정과 상관없이 모든 기즈모를 그린다.If true, draws all gizmos regardless of each node's setting.
짝Counterpart: vanilla-engine Graphic.set_force_gizmos_visible
모든 기즈모 강제 표시 여부 반환.
Returns whether all gizmos are force-displayed.
반환Returnsboolean 모든 기즈모를 강제로 그리면 참.True if all gizmos are forced visible.
짝Counterpart: vanilla-engine Graphic.is_force_gizmos_visible
상태 저장. (변환/알파/블렌드/색상/폰트/틴트, Canvas2D save 대응)
Saves the state. (transform/alpha/blend/color/font/tint, equivalent to Canvas2D save)
짝Counterpart: vanilla-engine Graphic.push_state
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.pushState();
graphic.translate(320, 180);
graphic.rotate(Math.PI / 6);
graphic.setGlobalAlpha(0.5);
graphic.setFillColor("#ff6600");
graphic.drawRect(Rect.create(-50, -50, 100, 100));
graphic.popState();
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());상태 복원. (Canvas2D restore 대응)
Restores the state. (equivalent to Canvas2D restore)
짝Counterpart: vanilla-engine Graphic.pop_state
이동 변환 누적.
Accumulates a translation transform.
- xnumber
- X 이동량.X translation.
- ynumber
- Y 이동량.Y translation.
짝Counterpart: vanilla-engine Graphic.translate
회전 변환 누적.
Accumulates a rotation transform.
- radiannumber
- 회전각. (라디안, 양수면 화면에서 시계 방향)Rotation angle. (radians, clockwise on screen if positive)
짝Counterpart: vanilla-engine Graphic.rotate
크기 변환 누적.
Accumulates a scale transform.
- xnumber
- X 배율.X scale.
- ynumber
- Y 배율.Y scale.
짝Counterpart: vanilla-engine Graphic.scale
변환 행렬 직접 설정. (Canvas2D setTransform(a, b, c, d, e, f) 대응)
Sets the transform matrix directly. (equivalent to Canvas2D setTransform(a, b, c, d, e, f))
- anumber
- 가로 배율. (x' = a x + c y + e)Horizontal scaling. (x' = a x + c y + e)
- bnumber
- 세로 기울임. (y' = b x + d y + f)Vertical skewing. (y' = b x + d y + f)
- cnumber
- 가로 기울임. (x' = a x + c y + e)Horizontal skewing. (x' = a x + c y + e)
- dnumber
- 세로 배율. (y' = b x + d y + f)Vertical scaling. (y' = b x + d y + f)
- enumber
- 가로 이동. (x' = a x + c y + e)Horizontal translation. (x' = a x + c y + e)
- fnumber
- 세로 이동. (y' = b x + d y + f)Vertical translation. (y' = b x + d y + f)
짝Counterpart: vanilla-engine Graphic.set_transform
변환 행렬 초기화.
Resets the transform matrix.
짝Counterpart: vanilla-engine Graphic.reset_transform
현재 변환 행렬 반환.
Returns the current transform matrix.
반환ReturnsTransformMatrix 지금 변환 행렬. (Graphic 이 들고 고쳐 쓰므로 값을 남기려면 복제한다)The current transform matrix. (held and reused by Graphic, so clone it to keep its values)
짝Counterpart: vanilla-engine Graphic.get_transform_matrix
전역 투명도 설정.
Sets the global alpha.
- valuenumber
- 전역 투명도. (0 ~ 1 로 자른다)Global alpha. (clamped to 0 ~ 1)
짝Counterpart: vanilla-engine Graphic.set_global_alpha
전역 투명도 반환.
Returns the global alpha.
반환Returnsnumber 전역 투명도. (0 ~ 1)Global alpha. (0 ~ 1)
짝Counterpart: vanilla-engine Graphic.get_global_alpha
전역 투명도 곱셈 누적. (노드 트리의 투명도 상속용)
Multiplies into the global alpha. (for alpha inheritance in the node tree)
- valuenumber
- 곱할 투명도. (곱한 값은 0 ~ 1 로 자른다)Alpha to multiply by. (the product is clamped to 0 ~ 1)
짝Counterpart: vanilla-engine Graphic.multiply_global_alpha
블렌드 모드 설정. (SpriteBlendMode 문자열 수용, Canvas2D globalCompositeOperation 26 가지)
- 고정 블렌딩으로 되는 13 가지(포터 더프 연산자, lighter, multiply, screen)는 blendFunc 로 건다.
- 나머지 13 가지(overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity)는 그리기마다 그릴 영역 아래를 떠 와 셰이더로 섞는다. 이 모드에서는 묶어 그리지 않고, 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번이 든다. (바꿔 끼운 셰이더로 그릴 때는 덧그림 칸에 먼저 그리고 옮기므로 드로우 콜이 두 번)
- multiply 는 렌더 타겟(프레임버퍼를 묶은 동안)에 그릴 때만 셰이더로 섞는다. (getDrawShaderBlendModeIndex)
- 모르는 이름은 source-over 로 그린다.
Sets the blend mode. (accepts SpriteBlendMode strings, the 26 Canvas2D globalCompositeOperation modes)
- The 13 modes possible with fixed blending (Porter-Duff operators, lighter, multiply, screen) are set with blendFunc.
- The other 13 (overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity) copy the area beneath each draw and blend in the shader. In these modes sprite batching is not used, and each draw costs one area copy and one draw call. (when drawing with a swapped-in shader, it draws to an overlay buffer first and then transfers, so two draw calls)
- multiply blends in the shader only when drawing to a render target (while a framebuffer is bound). (getDrawShaderBlendModeIndex)
- Unknown names draw as source-over.
- blendModestring
- 블렌드 모드. (Canvas2D globalCompositeOperation 이름, 모르는 이름은 한 번 경고하고 source-over 로 그린다)Blend mode. (a Canvas2D globalCompositeOperation name, an unknown name warns once and draws with source-over)
짝Counterpart: vanilla-engine Graphic.set_blend_mode
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.setBlendMode("lighter");
graphic.setFillColor("rgba(255, 80, 80, 0.8)");
graphic.drawCircle(Vector2.create(280, 180), 80);
graphic.setFillColor("rgba(80, 80, 255, 0.8)");
graphic.drawCircle(Vector2.create(360, 180), 80);
graphic.setBlendMode("source-over");
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
블렌드 모드 반환.
Returns the blend mode.
반환Returnsstring 블렌드 모드. (프레임마다 "source-over" 로 돌아간다)Blend mode. (reset to "source-over" every frame)
짝Counterpart: vanilla-engine Graphic.get_blend_mode
이미지 틴트 색상 설정. (null 이면 해제)
- 이미지 실루엣(알파) 안쪽에만 tint.alpha 비율로 색을 덮는다.
Sets the image tint color. (null clears it)
- Covers color only inside the image silhouette (alpha), at the tint.alpha ratio.
- colorColor | null
- 틴트 색. (사본을 둔다, Color 가 아니면 해제)Tint color. (a copy is kept, cleared if not a Color)
짝Counterpart: vanilla-engine Graphic.set_image_tint_color
이미지 틴트 색상 반환.
Returns the image tint color.
반환ReturnsColor | null 틴트 색. (없으면 null)Tint color. (null if none)
짝Counterpart: vanilla-engine Graphic.get_image_tint_color
색상 설정.
Sets the color.
- colorColor | string
- 채우기 색. (Color 나 "#rrggbb(aa)", "rgb(a)(...)" 글, 거짓 값이면 바꾸지 않는다)Fill color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, unchanged if falsy)
짝Counterpart: vanilla-engine Graphic.set_fill_color
채우기 색상 반환.
Returns the fill color.
반환ReturnsColor 채우기 색. (처음은 검정)Fill color. (initially black)
짝Counterpart: vanilla-engine Graphic.get_fill_color
색상 설정.
Sets the color.
- colorColor | string
- 선 색. (Color 나 "#rrggbb(aa)", "rgb(a)(...)" 글, 거짓 값이면 바꾸지 않는다)Stroke color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, unchanged if falsy)
짝Counterpart: vanilla-engine Graphic.set_stroke_color
선 색상 반환.
Returns the stroke color.
반환ReturnsColor 선 색. (처음은 검정)Stroke color. (initially black)
짝Counterpart: vanilla-engine Graphic.get_stroke_color
버텍스 데이터에 쿼드(삼각형 2개, 버텍스 6개) 기록.
- 기록 후의 오프셋(플로트 단위)을 반환.
Writes a quad (2 triangles, 6 vertices) into the vertex data.
- Returns the offset (in floats) after writing.
- offsetnumber
- 적기 시작할 자리. (플로트 단위)Position to start writing at. (in floats)
- leftXnumber
- 왼쪽 X.Left X.
- topYnumber
- 위 Y.Top Y.
- rightXnumber
- 오른쪽 X.Right X.
- bottomYnumber
- 아래 Y.Bottom Y.
- leftUnumber
- 왼쪽 U. (0 ~ 1)Left U. (0 ~ 1)
- topVnumber
- 위 V. (0 ~ 1)Top V. (0 ~ 1)
- rightUnumber
- 오른쪽 U. (0 ~ 1)Right U. (0 ~ 1)
- bottomVnumber
- 아래 V. (0 ~ 1)Bottom V. (0 ~ 1)
반환Returnsnumber 적은 뒤의 자리. (플로트 단위, offset 에 24 를 더한 값)Position after writing. (in floats, offset plus 24)
짝Counterpart: vanilla-engine Graphic.write_quad
기록된 버텍스 출력. (모든 드로우가 수렴하는 단일 지점, 추후 배칭 삽입 지점)
Outputs the recorded vertices. (the single point all draws converge on, the future batching insertion point)
- vertexCountnumber
- 그릴 정점 수. (getVertexData 에 적은 것, 0 이하면 그리지 않는다)Number of vertices to draw. (written to getVertexData, nothing is drawn if 0 or less)
- textureWebGLTexture
- 쓸 텍스처.Texture to use.
- colorColor
- 곱할 색.Color to multiply by.
짝Counterpart: vanilla-engine Graphic.draw_vertices
import { Engine, EngineConfiguration, Scene, Vector2, Color } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const floatCount = graphic.writeQuad(0, 100, 100, 300, 200, 0, 0, 1, 1);
const whiteTexture = graphic.getWhiteTexture();
const color = Color.createFromHEX("#ff00ff");
graphic.drawVertices(floatCount / 4, whiteTexture, color);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());드로우 콜 하나의 유니폼 업로드. (drawVertices 가 부른다)
- 유니폼 자리는 셰이더 프로그램이 바뀔 때만 다시 찾는다.
- 기본 프로그램의 틴트와 전역 투명도는 지난번에 올린 값과 같으면 다시 올리지 않는다. (프레임 시작과 프로그램이 바뀔 때 잊는다)
- 바꿔 끼운 셰이더 프로그램에는 늘 올린다.
Uploads the uniforms for one draw call. (called by drawVertices)
- Uniform locations are looked up again only when the shader program changes.
- The default program's tint and global alpha are not re-uploaded if equal to the last uploaded values. (forgotten at frame start and when the program changes)
- Always uploaded for a swapped-in shader program.
- shaderProgramShaderProgram
- 올릴 셰이더 프로그램.Shader program to upload to.
- colorColor
- mainColor 로 올릴 색.Color to upload as mainColor.
WebGL 컨텍스트를 잃은 상태인지.
Whether the WebGL context is lost.
반환Returnsboolean 잃었으면 true.true if lost.
짝Counterpart: vanilla-engine Graphic.is_context_lost
import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
const engine = new Engine(new EngineConfiguration());
engine.run(new Scene());
if (!engine.getGraphic().isContextLost()) {
console.log("draw");
}GPU 메모리 셈 켜기. (개발용)
Turning on GPU memory tracking
짝Counterpart: vanilla-engine Graphic.enable_gpu_memory_tracking
import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
const engine = new Engine(new EngineConfiguration());
engine.run(new Scene());
engine.getGraphic().enableGpuMemoryTracking();
console.log(engine.getGraphic().isGpuMemoryTrackingEnabled());GPU 메모리 셈이 켜져 있는지.
Whether GPU memory tracking is on.
반환Returnsboolean 켜져 있으면 true.true if on.
짝Counterpart: vanilla-engine Graphic.is_gpu_memory_tracking_enabled
import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
const engine = new Engine(new EngineConfiguration());
engine.run(new Scene());
console.log(engine.getGraphic().isGpuMemoryTrackingEnabled());GPU 메모리 읽기. (개발용)
Reads GPU memory. (For development)
반환Returns{ totalBytes: number, canvasBytes: number, kindTable: object, ownerList: Array<{ owner: string, kind: string, count: number, bytes: number }> } 합(캔버스 기본 프레임 버퍼 몫 포함), 캔버스 몫, 종류별 { count, bytes }, 주인별 몫(큰 것부터, 주인은 지은 호출 스택의 위쪽 세 칸).Total (including the default framebuffer share of the canvas), canvas share, per-kind { count, bytes }, per-owner shares (largest first, the owner is the top three frames of the call stack that created the object).
짝Counterpart: vanilla-engine Graphic.read_gpu_memory_usage
import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
const engineConfiguration = new EngineConfiguration();
engineConfiguration.trackGpuMemory = true;
const engine = new Engine(engineConfiguration);
engine.run(new Scene());
const usage = engine.getGraphic().readGpuMemoryUsage();
console.log(usage.totalBytes, usage.ownerList.length > 0 ? usage.ownerList[0].owner : "none");프레임 그리기 통계 시작.
- 엔진이 매 프레임 씬을 그리기 전에 부른다. 지난 프레임의 드로우 콜 / 정점 수를 넘겨 두고 이번 프레임 값을 비운다.
- 2D 경로(drawVertices, drawColoredQuads)만 센다. 3D 렌더러와 화면 효과 패스는 세지 않는다.
Starts frame draw statistics.
- The engine calls this every frame before drawing the scene. Keeps the last frame's draw call / vertex counts and clears this frame's values.
- Counts only the 2D path (drawVertices, drawColoredQuads). The 3D renderer and screen effect passes are not counted.
짝Counterpart: vanilla-engine Graphic.begin_frame_statistics
지난 프레임의 드로우 콜 수 반환.
Returns the last frame's draw call count.
반환Returnsnumber 지난 프레임의 드로우 콜 수.The last frame's draw call count.
짝Counterpart: vanilla-engine Graphic.get_last_frame_draw_call_count
지난 프레임에 그린 정점 수 반환.
Returns the number of vertices drawn in the last frame.
반환Returnsnumber 지난 프레임에 그린 정점 수.Number of vertices drawn in the last frame.
짝Counterpart: vanilla-engine Graphic.get_last_frame_vertex_count
지난 프레임에 그린 삼각형 수 반환. (모든 드로우 콜이 삼각형 목록이다)
Returns the number of triangles drawn in the last frame. (every draw call is a triangle list)
반환Returnsnumber 지난 프레임에 그린 삼각형 수.Number of triangles drawn in the last frame.
짝Counterpart: vanilla-engine Graphic.get_last_frame_triangle_count
화면 밖 거르기 설정. (기본 true)
- 켜면 WorldNode 가 컴포넌트를 그리기 전에, 켜진 컴포넌트가 모두 내용 영역 안에서만 그린다고 알리면(Component.isDrawnInsideContent) 내용 영역이 화면 밖일 때 그 노드의 컴포넌트 그리기를 건너뛴다. 자식은 저마다 따로 보고 그대로 그린다.
- 판정은 그릴 때의 지금 변환(부모의 위치, 배율, 회전과 pushState 로 건 것 모두)으로 옮긴 영역의 경계 상자로 한다.
- 알리지 않는 컴포넌트(기본, 글자, 파티클, 직접 만든 컴포넌트)가 하나라도 켜져 있으면 그 노드는 거르지 않는다. draw 를 덮어쓴 노드도 거르지 않는다.
- 하위 트리 거르기(setSubtreeCullingEnabled, 기본 켜짐)를 켜 두면 노드의 하위 트리 그리기 경계(TransformNode.readSubtreeDrawBounds)가 화면 밖일 때 그 노드와 자손의 그리기 순회를 통째로 건너뛴다. (갱신 tick 은 그대로 돈다)
Sets off-screen culling. (default true)
- When on, before WorldNode draws its components, if all enabled components report that they draw only inside the content area (Component.isDrawnInsideContent), the node's component drawing is skipped when the content area is off screen. Children are each checked separately and drawn as usual.
- The test uses the bounding box of the area moved by the current transform at draw time (parent position, scale, rotation and anything set with pushState).
- If even one component that does not report (default, text, particle, user-made components) is enabled, the node is not culled. Nodes that override draw are not culled either.
- With subtree culling (setSubtreeCullingEnabled, on by default), when a node's subtree draw bounds (TransformNode.readSubtreeDrawBounds) are off screen, the draw traversal of that node and its descendants is skipped entirely. (tick updates still run)
- isCullingEnabledboolean
- 화면 밖 거르기를 켤지. (true 일 때만 켠다)Whether to enable off screen culling. (enabled only when true)
짝Counterpart: vanilla-engine Graphic.set_culling_enabled
화면 밖 거르기 여부 반환.
Returns whether off-screen culling is on.
반환Returnsboolean 화면 밖 거르기가 켜졌으면 참.True if off screen culling is on.
짝Counterpart: vanilla-engine Graphic.is_culling_enabled
화면 밖 하위 트리 거르기 설정. (기본 true, 화면 밖 거르기 setCullingEnabled 가 켜졌을 때만 거른다)
- 켜면 drawNode 가 노드에 변환을 건 뒤 그 노드의 하위 트리 그리기 경계(TransformNode.readSubtreeDrawBounds)를 지금 변환으로 옮겨, 화면과 걸린 자르기(beginClipRect) 밖이면 그 노드와 자손의 그리기 순회를 통째로 건너뛴다. (스크롤 목록의 보이지 않는 줄을 돌지 않는다)
- 경계는 변환, 내용 크기, 자식, 켜짐, 보임, 컴포넌트가 바뀐 때만 다시 셈한다. 어디에 그리는지 모르는 것이 든 하위 트리는 건너뛰지 않는다.
- 갱신(tick)은 그대로 돈다. 기즈모를 모두 그리게 했으면(setForceGizmosVisible) 건너뛰지 않는다.
Sets off-screen subtree culling. (default true, culls only while off-screen culling setCullingEnabled is on)
- When on, after drawNode applies a node's transform it moves that node's subtree draw bounds (TransformNode.readSubtreeDrawBounds) by the current transform, and if they are outside the screen and the active clips (beginClipRect) the draw traversal of that node and its descendants is skipped entirely. (invisible rows of a scroll list are not visited)
- The bounds are recalculated only when a transform, content size, child, active state, visibility or component changes. A subtree that contains something whose drawing area is unknown is never skipped.
- Updates (tick) still run. Nothing is skipped while all gizmos are forced visible (setForceGizmosVisible).
- isSubtreeCullingEnabledboolean
- 화면 밖 하위 트리 거르기를 켤지. (true 일 때만 켠다)Whether to turn on off-screen subtree culling. (turns on only when true)
짝Counterpart: vanilla-engine Graphic.set_subtree_culling_enabled
import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
graphic.setSubtreeCullingEnabled(true);
super.draw(graphic);
console.log(graphic.isSubtreeCullingEnabled(), graphic.getLastFrameCulledSubtreeCount());
}
}
const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());화면 밖 하위 트리 거르기 여부 반환.
Returns whether off-screen subtree culling is on.
반환Returnsboolean 켜졌으면 참. (화면 밖 거르기가 꺼져 있으면 켜져 있어도 거르지 않는다)True if on. (nothing is culled while off-screen culling is off, even if this is on)
짝Counterpart: vanilla-engine Graphic.is_subtree_culling_enabled
지난 프레임에 화면 밖이라 그리기를 통째로 건너뛴 하위 트리 수 반환.
Returns the number of subtrees whose drawing was skipped entirely in the last frame because they were off screen.
반환Returnsnumber 지난 프레임에 건너뛴 하위 트리 수.The number of subtrees skipped in the last frame.
짝Counterpart: vanilla-engine Graphic.get_last_frame_culled_subtree_count
하위 트리가 보이는 사각형 안에 다 든 노드를 그리는 중인지 반환. (그리기 순회가 정한다)
- 하위 트리 거르기가 노드의 하위 트리 경계가 보이는 사각형(화면과 걸린 자르기를 한 디바이스 픽셀 좁힌 것) 안에 다 든다고 보면, 그 노드를 그리는 동안 참이다. 그 아래 자손은 화면 밖 견주기(하위 트리 경계, 컴포넌트 거르기, 보이는 자식 범위)를 하지 않고 그린다. 그리는 것이 없는 자손(경계 크기 0)만 건너뛴다.
- 그 아래에서 자르기(beginClipRect, 마스크와 스크롤 칸)를 새로 걸면 그 자르기를 풀 때까지 거짓이다. (새 자르기 안에서 다시 견준다)
- 화면 밖 거르기나 하위 트리 거르기가 꺼졌거나 기즈모를 모두 그리면 거짓.
Returns whether a node whose subtree lies fully inside the visible rectangle is being drawn. (Decided by the draw traversal)
- When subtree culling finds that a node's subtree bounds lie fully inside the visible rectangle (the screen and active clips shrunk by one device pixel), this is true while that node is drawn. Its descendants are drawn without off-screen tests (subtree bounds, component culling, visible child range). Only descendants that draw nothing (bounds of size 0) are skipped.
- If a new clip (beginClipRect, masks and scroll views) is set below it, this is false until that clip ends. (Tested again inside the new clip)
- False if off-screen culling or subtree culling is off, or all gizmos are drawn.
반환Returnsboolean 지금 그리는 노드가 보이는 사각형 안에 다 들면 참.True if the node being drawn lies fully inside the visible rectangle.
짝Counterpart: vanilla-engine Graphic.is_inside_visible_bounds
import { Engine, EngineConfiguration, Scene, WorldNode, Component, Paint, Rect, Vector2, Pivot, Colors } from "./build/vanilla.js";
class InsideProbe extends Component {
isDrawnInsideContent() {
return true;
}
draw(graphic) {
graphic.setFillColor(Colors.white);
graphic.drawRect(Rect.create(0, 0, 10, 10));
console.log(graphic.isInsideVisibleBounds());
}
}
class MainScene extends Scene {
initialize(engine) {
super.initialize(engine);
const node = new WorldNode();
node.setPivot(Pivot.topLeft);
node.setRect(100, 100, 40, 40);
node.addComponent(Paint);
node.addComponent(InsideProbe);
this.getRoot().addChild(node);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());보이는 사각형(화면과 걸린 자르기)을 지금 변환의 지역 좌표로 거꾸로 옮긴 경계 상자 읽기. (하위 트리 거르기가 켜졌을 때만, 알면 true)
- 돌림이나 기울임이 있으면 넉넉하다(네 꼭짓점의 경계 상자, 한 디바이스 픽셀씩 넓힘). 이 사각형 밖에 그리는 것은 보이지 않는다.
- 노드가 많은 자식 가운데 보이는 범위를 찾을 때 쓴다(TransformNode.drawChildren). 변환과 자르기가 같으면 다시 셈하지 않는다.
- 화면 밖 거르기나 하위 트리 거르기가 꺼졌거나, 기즈모를 모두 그리거나, 뷰포트를 아직 정하지 않았거나, 변환을 거꾸로 걸 수 없으면(배율 0) false.
Reads the visible rectangle (the screen and active clips) moved back into the current transform's local coordinates as a bounding box. (Only while subtree culling is on; true if known)
- With rotation or skew it is conservative (the bounding box of the four corners, grown by one device pixel). Anything drawn outside this rectangle is not visible.
- Used by a node to find the visible range among many children (TransformNode.drawChildren). Not recalculated while the transform and clip stay the same.
- False 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).
- rectRect
- 경계 상자를 적을 곳. (지금 변환의 지역 좌표)Where to write the bounding box. (In the current transform's local coordinates)
반환Returnsboolean 알면 참. (모르면 rect 를 건드리지 않는다)True if known. (Otherwise rect is left untouched)
짝Counterpart: vanilla-engine Graphic.read_local_visible_bounds
import { Engine, EngineConfiguration, Scene, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const visibleRect = Rect.zero();
graphic.pushState();
graphic.translate(100, 0);
console.log(graphic.readLocalVisibleBounds(visibleRect), visibleRect.position.x < -100);
graphic.popState();
}
}
const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());이번 프레임에 화면 밖이라 그리기를 통째로 건너뛴 하위 트리 수 더하기. (TransformNode.drawChildren 이 보이는 범위 밖 자식을 한꺼번에 건너뛰고 부른다)
Adds to the number of subtrees whose drawing was skipped entirely this frame because they were off screen. (TransformNode.drawChildren calls it after skipping the children outside the visible range at once)
- culledSubtreeCountnumber
- 더할 하위 트리 수.The number of subtrees to add.
짝Counterpart: vanilla-engine Graphic.add_culled_subtree_count
지금 변환으로 옮긴 사각형이 화면(드로잉 버퍼)과 걸린 자르기 안에 걸치는지 반환. (네 꼭짓점을 옮긴 경계 상자로 본다)
- 투영과 같은 디바이스 픽셀 좌표로 보므로 클립 공간 밖인지와 같다. (뷰포트를 줄여 그려도 맞다)
- beginClipRect 로 건 자르기(겹친 것 모두)의 경계 상자 밖이면 보이지 않는 것으로 본다. (유니티 RectMask2D 처럼 스크롤 칸 밖 줄을 그리지 않는다)
- 뷰포트를 아직 정하지 않았으면(applySettings 전) 걸치는 것으로 본다.
Returns whether a rectangle moved by the current transform overlaps the screen (drawing buffer) and the active clip. (judged by the bounding box of the four moved corners)
- It works in the same device pixel coordinates as the projection, so it equals testing outside clip space. (correct even when drawing to a smaller viewport)
- Outside the bounding box of the clips set with beginClipRect (all nested ones), it counts as not visible. (like Unity RectMask2D, rows outside a scroll view are not drawn)
- Before the viewport is set (before applySettings), it counts as overlapping.
- rectRect
- 지금 변환으로 옮기기 전의 사각형. (로컬 좌표)Rect before the current transform. (local coordinates)
반환Returnsboolean 화면에 걸치면 참.True if it overlaps the screen.
짝Counterpart: vanilla-engine Graphic.is_local_rect_visible
이번 프레임에 화면 밖이라 컴포넌트를 건너뛴 노드 수 더하기. (WorldNode 가 부른다)
Adds to this frame's count of nodes whose components were skipped for being off screen. (called by WorldNode)
- culledNodeCountnumber
- 더할 노드 수.Number of nodes to add.
짝Counterpart: vanilla-engine Graphic.add_culled_node_count
지난 프레임에 화면 밖이라 컴포넌트를 건너뛴 노드 수 반환.
Returns the last frame's count of nodes whose components were skipped for being off screen.
반환Returnsnumber 지난 프레임에 건너뛴 노드 수.Number of nodes skipped in the last frame.
짝Counterpart: vanilla-engine Graphic.get_last_frame_culled_node_count
묶어 그리기 켜고 끄기. (엔진이 처음에 켠다, 끄면 그리기 하나에 드로우 콜 하나)
- 켜면 연이은 드로우(이미지, 도형, 글자, 정점 색 쿼드)를 정점에 변환과 색을 실어 쌓아 두었다가 한 번의 드로우 콜로 그린다.
- 텍스처는 한 묶음에 여러 장(기기 텍스처 유닛 수와 16 가운데 작은 것)까지 묶어 텍스처가 바뀌어도 이어진다. (PixiJS 와 같은 꼴)
- 축에 맞고 화소 경계에 놓인 자르기(beginClipRect)는 정점의 자르기 사각형으로 셰이더가 잘라 묶음을 끊지 않는다. (돌아갔거나 둥근 자르기는 스텐실)
- 텍스처 칸이 차거나, 블렌드, 스텐실 자르기, 바꿔 끼운 셰이더가 바뀌거나 버퍼가 차면 그때까지 쌓인 것을 그리고, 프레임 끝에 엔진이 남은 것을 그린다.
- 엔진 루프 밖에서 그려도(엔진 없이 만든 Graphic, 제 requestAnimationFrame, 입력 처리기) 그 작업이 끝날 때(마이크로태스크) 남은 것을 그린다. 브라우저가 캔버스를 화면에 내기 전이라, 2D 캔버스처럼 따로 내보내지 않아도 보인다.
- 켠 채로 WebGL 을 직접 다루는 패스(외부 렌더러 등)를 끼울 때는 그 전에 flushBatch() 를 부른다.
Turns batched drawing on and off. (the engine turns it on at the start, off means one draw call per draw)
- 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 (beginClipRect) 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.
- Drawing outside the engine loop (a Graphic made without an engine, your own requestAnimationFrame, an input handler) is also drawn when that task ends (a microtask). That is before the browser presents the canvas, so it shows without an explicit flush, like a 2D canvas.
- When inserting a pass that touches WebGL directly (an external renderer and the like) while it is on, call flushBatch() first.
- isBatchingEnabledboolean
- 묶어 그리기를 켤지. (true 일 때만 켠다, 끄면 쌓인 것을 먼저 그린다)Whether to enable batching. (enabled only when true, turning it off draws what is queued first)
짝Counterpart: vanilla-engine Graphic.set_batching_enabled
묶어 그리기를 켰는지 반환.
Returns whether batched drawing is on.
반환Returnsboolean 묶어 그리기가 켜졌으면 참.True if batching is on.
짝Counterpart: vanilla-engine Graphic.is_batching_enabled
쌓인 묶음 그리기. (쌓인 것이 없으면 아무것도 하지 않는다)
- 묶음의 텍스처를 0 번부터의 유닛에 묶는다. 쓰지 않는 칸의 유닛에는 흰 텍스처를 묶어, 지난 그리기의 텍스처가 지금 그리는 칸(렌더 타겟)이어도 되먹임이 생기지 않게 한다.
Draws the accumulated batch. (does nothing if nothing has accumulated)
- 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).
짝Counterpart: vanilla-engine Graphic.flush_batch
기하 캐시 켜기 / 끄기. (기본 켜짐)
- 켜져 있으면 writeGeometryKey 로 그리기 입력을 알리는 컴포넌트(Paint, UIView, Text 등)가 그린 정점을 컴포넌트마다 캐시해 둔다. 입력, 변환, 투명도가 그대로면 draw 를 부르지 않고 캐시를 묶음에 옮기고, 이동(스크롤 등)만 바뀌면 캐시한 지역 정점에 새 행렬만 곱한다. (유니티 UGUI 가 Graphic 의 메시를 지역 좌표로 두고 바뀐 것만 다시 짓는 것, 언리얼 Slate Invalidation 과 같은 사상)
- 끄면 지난 판처럼 프레임마다 모든 컴포넌트의 draw 를 부른다. (화면 결과는 같다)
Turns the geometry cache on or off. (on by default)
- When on, the vertices drawn by components that report their draw inputs through writeGeometryKey (Paint, UIView, Text, etc.) are cached per component. If the inputs, transform and opacity are unchanged, draw is not called and the cache is copied into the batch; if only the translation changes (scrolling etc.), only the new matrix is applied to the cached local vertices. (the same idea as Unity UGUI keeping each Graphic's mesh in local space and rebuilding only what changed, and Unreal Slate Invalidation)
- When off, draw is called for every component every frame as in earlier versions. (the screen result is the same)
- isGeometryCachingEnabledboolean
- 켤지.Whether to enable it.
짝Counterpart: vanilla-engine Graphic.set_geometry_caching_enabled
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
initialize(engine) {
super.initialize(engine);
const boxNode = new WorldNode();
boxNode.setLocalPosition(Vector2.create(320, 180));
boxNode.setContentSize(Vector2.create(200, 100));
boxNode.addComponent(Paint).setColor("#3399ff");
this.getRoot().addChild(boxNode);
}
draw(graphic) {
graphic.setGeometryCachingEnabled(true);
super.draw(graphic);
console.log(graphic.isGeometryCachingEnabled(), graphic.getLastFrameGeometryCacheHitCount());
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());기하 캐시가 켜져 있는지 반환.
Returns whether the geometry cache is on.
반환Returnsboolean 켜져 있으면 참.True if enabled.
짝Counterpart: vanilla-engine Graphic.is_geometry_caching_enabled
지난 프레임에 기하 캐시로 그린 컴포넌트 수 반환. (draw 를 부르지 않은 것)
Returns the number of components drawn from the geometry cache in the last frame. (draw was not called)
반환Returnsnumber 캐시를 그대로 옮기거나 새 행렬만 곱해 그린 컴포넌트 수.Number of components drawn by copying the cache as is or by applying only the new matrix.
짝Counterpart: vanilla-engine Graphic.get_last_frame_geometry_cache_hit_count
지난 프레임에 기하 캐시를 다시 적은 컴포넌트 수 반환. (캐시하는 컴포넌트 가운데 draw 를 부른 것)
Returns the number of components whose geometry cache was rewritten in the last frame. (among caching components, those whose draw was called)
반환Returnsnumber 입력이나 배율, 회전 등이 바뀌어 draw 를 다시 부른 컴포넌트 수.Number of components whose draw was called again because inputs, scale, rotation, etc. changed.
짝Counterpart: vanilla-engine Graphic.get_last_frame_geometry_rebuild_count
지난 프레임에 정점을 다시 올리지 않고 GPU 에 남겨 둔 버퍼로 그린 묶음 수 반환.
- 묶음에 넣은 조각(기하 캐시 조각과 판, 캐시 없이 바로 쓴 구간의 정점 값)이 지난 프레임 같은 차례의 묶음과 모두 같으면 정점을 옮기지도 올리지도 않고 드로 콜만 낸다.
- 일부만 바뀐 묶음은 바뀐 범위만 bufferSubData 로 고쳐 올리고, 이 수에 들지 않는다.
Returns the number of batches in the last frame drawn from buffers retained on the GPU without uploading vertices again.
- When every segment put into a batch (geometry cache segments with their versions, and the vertex values of spans written directly without a cache) matches the batch at the same position in the previous frame, no vertices are copied or uploaded and only the draw call is issued.
- A batch where only part changed uploads only the changed ranges with bufferSubData and is not counted here.
반환Returnsnumber 남긴 버퍼로 그린 묶음 수.Number of batches drawn from retained buffers.
짝Counterpart: vanilla-engine Graphic.get_last_frame_retained_batch_count
import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
initialize(engine) {
super.initialize(engine);
const boxNode = new WorldNode();
boxNode.setLocalPosition(Vector2.create(320, 180));
boxNode.setContentSize(Vector2.create(200, 100));
boxNode.addComponent(Paint).setColor("#3399ff");
this.getRoot().addChild(boxNode);
}
draw(graphic) {
super.draw(graphic);
console.log(graphic.getLastFrameRetainedBatchCount(), graphic.getLastFrameDrawCallCount());
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());컴포넌트 그리기. (노드가 컴포넌트마다 부른다, 기하 캐시를 거친다)
- 컴포넌트가 writeGeometryKey 로 입력을 알리지 않거나, 캐시가 꺼졌거나, 묶어 그리지 않는 상태면 draw 를 그대로 부른다.
- 입력과 그리는 상태(배율, 회전, 섞기, 틴트, 글 방향)가 지난번과 같으면: 이동과 투명도도 같으면 캐시한 디바이스 정점을 묶음에 그대로 옮기고, 다르면 캐시한 지역 정점에 지금 행렬과 투명도를 다시 건다. (스크롤은 부모의 이동만 바뀌므로 자식 컴포넌트는 draw 없이 행렬 곱만 한다, 글은 픽셀 스냅까지 같게 다시 셈한다)
- 그 밖에는 draw 를 불러 캐시를 다시 적는다. 그리기 중에 자르기, 층, 섞기 바꾸기 등 묶음 밖의 일을 하면 그 컴포넌트는 캐시하지 않는다.
Draws a component. (nodes call it for each component, it goes through the geometry cache)
- If the component does not report its inputs through writeGeometryKey, the cache is off, or the state is not batched, draw is called as is.
- If the inputs and the drawing state (scale, rotation, blend, tint, text direction) are the same as last time:
if the translation and opacity are also the same, the cached device vertices are copied into the batch as is; otherwise the current matrix and opacity are applied again to the cached local vertices.
(scrolling only changes the parent's translation, so child components only do a matrix multiply without draw; text recomputes pixel snapping identically)- Otherwise draw is called to rewrite the cache. If the draw does work outside the batch such as clipping, layers or changing the blend mode, that component is not cached.
- componentComponent
- 그릴 컴포넌트.Component to draw.
짝Counterpart: vanilla-engine Graphic.draw_component
파티클 배치 버텍스 배열 반환. (필요 시 증설, x, y, u, v, r, g, b, a 인터리브)
Returns the particle batch vertex array. (grows as needed, interleaved x, y, u, v, r, g, b, a)
- minimumFloatCountnumber
- 적어도 필요한 플로트 수. (모자라면 두 배씩 늘린다)Minimum number of floats needed. (doubled until large enough)
반환ReturnsFloat32Array 파티클 정점 배열. (정점마다 x, y, u, v, r, g, b, a, 늘리면 새 배열이다)Particle vertex array. (x, y, u, v, r, g, b, a per vertex, a new array when grown)
짝Counterpart: vanilla-engine Graphic.get_particle_vertex_data
파티클 배치 출력. (getParticleVertexData 에 채운 정점을 한 번에 그린다)
Outputs the particle batch. (draws the vertices filled into getParticleVertexData at once)
- vertexCountnumber
- 그릴 정점 수. (0 이하면 그리지 않는다)Number of vertices to draw. (nothing is drawn if 0 or less)
- textureWebGLTexture
- 쓸 텍스처. (getSoftDiscTexture 같은)Texture to use. (such as getSoftDiscTexture)
짝Counterpart: vanilla-engine Graphic.draw_colored_quads
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
const COLOR_LIST = [[1, 0.3, 0.3], [0.3, 1, 0.3], [0.3, 0.5, 1]];
const CORNER_LIST = [[0, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 1]];
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const quadCount = COLOR_LIST.length;
const vertexData = graphic.getParticleVertexData(quadCount * 6 * 8);
let offset = 0;
for (let quadIndex = 0; quadIndex < quadCount; ++quadIndex) {
const leftX = 120 + quadIndex * 150;
const topY = 140;
const size = 80;
const color = COLOR_LIST[quadIndex];
for (const corner of CORNER_LIST) {
vertexData[offset++] = leftX + corner[0] * size;
vertexData[offset++] = topY + corner[1] * size;
vertexData[offset++] = corner[0];
vertexData[offset++] = corner[1];
vertexData[offset++] = color[0];
vertexData[offset++] = color[1];
vertexData[offset++] = color[2];
vertexData[offset++] = 1;
}
}
const softDiscTexture = graphic.getSoftDiscTexture();
graphic.drawColoredQuads(quadCount * 6, softDiscTexture);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());부드러운 원 텍스처 반환. (가장자리가 잦아드는 64x64 원, 파티클 기본 스프라이트)
Returns the soft circle texture. (64x64 circle that fades out at the edge, the default particle sprite)
반환ReturnsWebGLTexture 부드러운 원 텍스처. (처음 부를 때 만든다)Soft disc texture. (created on the first call)
짝Counterpart: vanilla-engine Graphic.get_soft_disc_texture
선 출력.
- setStrokeColor()
Draws a line.
- setStrokeColor()
- positionsVector2[]
- 선이 지날 점 목록. (2 개보다 적으면 그리지 않는다)Points the line passes through. (nothing is drawn if fewer than 2)
- sizenumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_line
닫힌 선 출력. (마지막 점과 첫 점을 잇는 루프)
- setStrokeColor()
Draws a closed line. (a loop joining the last point to the first)
- setStrokeColor()
- positionsVector2[]
- 선이 지날 점 목록. (2 개보다 적으면 그리지 않는다)Points the line passes through. (nothing is drawn if fewer than 2)
- sizenumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_line_loop
폴리라인 출력. (세그먼트별 두께 확장 쿼드)
- 내부 조인트는 반두께 연장으로 이음새를 메운다.
- 정점 버퍼가 차면 쌓인 것을 그리고 비운 뒤 이어 적는다. (점이 많아도 선분을 버리지 않는다)
Draws a polyline. (per-segment quads expanded by thickness)
- Inner joints are filled by extending half the thickness.
- When the vertex buffer fills, it draws what has accumulated, empties it and keeps writing. (segments are not dropped even with many points)
- positionsVector2[]
- 선이 지날 점 목록. (2 개보다 적으면 그리지 않는다)Points the line passes through. (nothing is drawn if fewer than 2)
- sizenumber
- 선 굵기.Line width.
- isClosedboolean
- 참이면 마지막 점과 첫 점을 잇는다.Connects the last point to the first if true.
짝Counterpart: vanilla-engine Graphic.draw_polyline
사각형 출력.
- setFillColor()
Draws a rectangle.
- setFillColor()
- rectRect
- 칠할 사각형.Rect to fill.
짝Counterpart: vanilla-engine Graphic.draw_rect
사각형 외곽선 출력. (Canvas2D strokeRect 대응, 선 중심이 경계선 위)
- setStrokeColor()
Draws a rectangle outline. (equivalent to Canvas2D strokeRect, line center on the border)
- setStrokeColor()
- rectRect
- 테를 그릴 사각형.Rect to outline.
- lineWidthnumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_stroke_rect
라운드 사각형 경로 좌표 목록 생성. (시계 방향, 볼록 다각형)
Creates the list of rounded rectangle path coordinates. (clockwise, convex polygon)
- rectRect
- 사각형.Rect.
- roundSizenumber
- 모서리 반지름. (짧은 변의 반을 넘으면 반으로 자른다)Corner radius. (clamped to half of the shorter side)
반환ReturnsVector2[] 경로의 점 목록. (새 배열)Points of the path. (a new array)
짝Counterpart: vanilla-engine Graphic.build_round_rect_positions
라운드 사각형 경로 좌표를 ROUND_RECT_POSITION_DATA 에 적는다. (시계 방향, 볼록 다각형, x, y 차례)
- 점마다의 cos / sin 은 처음에 구해 둔 표를 쓴다.
Writes the rounded rectangle path coordinates into ROUND_RECT_POSITION_DATA. (clockwise, convex polygon, x, y order)
- The cos / sin for each point come from a table computed up front.
- rectRect
- 사각형.Rect.
- roundSizenumber
- 모서리 반지름. (짧은 변의 반을 넘으면 반으로 자른다)Corner radius. (clamped to half of the shorter side)
볼록 다각형 채움 출력. (첫 점 기준 팬 분할)
- 정점 버퍼가 차면 쌓인 삼각형을 그리고 비운 뒤 이어 적는다. (점이 많아도 삼각형을 버리지 않는다)
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)
- positionsVector2[]
- 볼록 다각형의 점 목록. (3 개보다 적으면 그리지 않는다)Points of the convex polygon. (nothing is drawn if fewer than 3)
- colorColor
- 칠할 색.Color to fill with.
짝Counterpart: vanilla-engine Graphic.draw_convex_polygon
라운드 사각형 출력.
- setFillColor()
Draws a rounded rectangle.
- setFillColor()
- rectRect
- 칠할 사각형.Rect to fill.
- roundSizenumber
- 모서리 반지름. (0 이하면 각진 사각형, 짧은 변의 반을 넘으면 반으로 자른다)Corner radius. (a sharp rectangle if 0 or less, clamped to half of the shorter side)
짝Counterpart: vanilla-engine Graphic.draw_round_rect
ROUND_RECT_POSITION_DATA 에 적힌 라운드 사각형 채움 출력. (첫 점 기준 팬 분할, drawConvexPolygon 과 같은 삼각형)
Draws the filled rounded rectangle written in ROUND_RECT_POSITION_DATA. (fan split from the first point, same triangles as drawConvexPolygon)
- colorColor
- 칠할 색.Color to fill with.
라운드 사각형 외곽선 출력.
- setStrokeColor()
Draws a rounded rectangle outline.
- setStrokeColor()
- rectRect
- 테를 그릴 사각형.Rect to outline.
- roundSizenumber
- 모서리 반지름. (0 이하면 각진 사각형, 짧은 변의 반을 넘으면 반으로 자른다)Corner radius. (a sharp rectangle if 0 or less, clamped to half of the shorter side)
- lineWidthnumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_stroke_round_rect
원 출력.
- setFillColor()
Draws a circle.
- setFillColor()
- centerVector2
- 가운데.Center.
- radiusnumber
- 반지름. (0 이하면 그리지 않는다)Radius. (nothing is drawn if 0 or less)
짝Counterpart: vanilla-engine Graphic.draw_circle
원 외곽선 출력.
- setStrokeColor()
Draws a circle outline.
- setStrokeColor()
- centerVector2
- 가운데.Center.
- radiusnumber
- 반지름. (0 이하면 그리지 않는다)Radius. (nothing is drawn if 0 or less)
- lineWidthnumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_stroke_circle
고리(띠) 출력. (안쪽 반지름과 바깥 반지름 사이를 startRadian 부터 endRadian 까지 칠한다)
- setFillColor()
- 각도는 라디안, 0 이 오른쪽이고 화면에서 시계 방향으로 는다. (12 시에서 시작하려면 -PI / 2)
- 조각마다 네모 하나를 겹치지 않게 이어 붙여 한 번에 그리므로, 반투명 색이어도 조각의 이음매가 짙어지지 않는다.
- 조각 수는 drawCircle 처럼 화면에서의 바깥 반지름을 따라 정하고(한 바퀴 16 ~ 64), 그리는 각도만큼만 쓴다.
Draws a ring (band). (fills between the inner and outer radius from startRadian to endRadian)
- setFillColor()
- Angles are in radians, 0 is to the right and increases clockwise on screen. (-PI / 2 to start at 12 o'clock)
- 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 drawCircle (16 ~ 64 per full turn), and only the portion for the drawn angle is used.
- centerVector2
- 가운데.Center.
- innerRadiusnumber
- 안쪽 반지름.Inner radius.
- outerRadiusnumber
- 바깥 반지름. (0 이하이거나 안쪽 반지름 이하면 그리지 않는다)Outer radius. (nothing is drawn if 0 or less, or not greater than the inner radius)
- startRadiannumber
- 기본 0.Default 0.
- endRadiannumber
- 기본 PI * 2.Default PI * 2.
짝Counterpart: vanilla-engine Graphic.draw_ring
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const center = Vector2.create(320, 180);
const progress = 0.7;
const startRadian = -Math.PI / 2;
graphic.setFillColor("#44dd88");
graphic.drawRing(center, 50, 70, startRadian, startRadian + Math.PI * 2 * progress);
graphic.setStrokeColor("#ffffff");
graphic.drawArc(center, 90, startRadian, startRadian + Math.PI, 3);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());호 출력. (반지름을 따라 lineWidth 두께의 선으로 startRadian 부터 endRadian 까지)
- setStrokeColor()
- 각도와 조각 수는 drawRing 과 같다. 선의 두께 가운데가 반지름에 온다.
Draws an arc. (a line of lineWidth thickness along the radius, from startRadian to endRadian)
- setStrokeColor()
- Angles and segment count are the same as drawRing. The middle of the line thickness lies on the radius.
- centerVector2
- 가운데.Center.
- radiusnumber
- 반지름. (선 굵기의 가운데)Radius. (the middle of the line width)
- startRadiannumber
- 시작 각. (라디안)Start angle. (radians)
- endRadiannumber
- 끝 각. (라디안)End angle. (radians)
- lineWidthnumber
- 기본 1.Default 1.
짝Counterpart: vanilla-engine Graphic.draw_arc
drawRingWithColor(centerX, centerY, innerRadius, outerRadius, startRadian, endRadian, color)#고리 출력의 셈. (drawRing, drawArc 가 부른다)
Ring drawing computation. (called by drawRing, drawArc)
- centerXnumber
- 가운데 X.Center X.
- centerYnumber
- 가운데 Y.Center Y.
- innerRadiusnumber
- 안쪽 반지름.Inner radius.
- outerRadiusnumber
- 바깥 반지름. (0 이하이거나 안쪽 반지름 이하면 그리지 않는다)Outer radius. (nothing is drawn if 0 or less, or not greater than the inner radius)
- startRadiannumber
- 시작 각. (라디안)Start angle. (radians)
- endRadiannumber
- 끝 각. (라디안, 시작 각과 같으면 그리지 않는다, 한 바퀴를 넘으면 한 바퀴로 자른다)End angle. (radians, nothing is drawn if equal to the start angle, clamped to one full turn)
- colorColor
- 칠할 색.Color to fill with.
짝Counterpart: vanilla-engine Graphic.draw_ring_with_color
선분 여럿 출력. (위치 배열 하나에 선분마다 x0, y0, x1, y1 넷씩, 한 번에 그린다)
- setStrokeColor()
- 선분마다 두께만큼 넓힌 네모 하나다. (drawLine 과 달리 이음새를 메우지 않는다, 따로 떨어진 선분 용)
- Vector2 배열을 만들지 않고 숫자 배열(Array, Float32Array)을 그대로 읽는다. 길이가 0 인 선분은 건너뛴다.
- 정점 버퍼가 차면 거기까지 그리고 이어서 담는다. (묶어 그리기가 켜져 있으면 같은 텍스처라 한 번의 드로우 콜로 이어진다)
Draws multiple line segments. (one position array with four values x0, y0, x1, y1 per segment, drawn at once)
- setStrokeColor()
- Each segment is one quad widened by the thickness. (unlike drawLine, joints are not filled, meant for separate segments)
- Reads number arrays (Array, Float32Array) directly without creating Vector2 arrays. Zero-length segments are skipped.
- When the vertex buffer fills, draws up to there and continues filling. (with sprite batching on, it is the same texture so it continues as one draw call)
- positionValuesnumber[] | Float32Array
- 선분마다 x0, y0, x1, y1 넷씩 놓인 숫자 배열. (넷보다 적으면 그리지 않는다)Number array with x0, y0, x1, y1 for each segment. (nothing is drawn if fewer than four)
- sizenumber
- 기본 1.Default 1.
짝Counterpart: vanilla-engine Graphic.draw_line_segments
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const positionValues = [];
for (let x = 0; x <= 640; x += 40) {
positionValues.push(x, 0, x, 360);
}
for (let y = 0; y <= 360; y += 40) {
positionValues.push(0, y, 640, y);
}
graphic.setStrokeColor("rgba(255, 255, 255, 0.3)");
graphic.drawLineSegments(positionValues, 1);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());그림을 미리 GPU 에 올리기. (로딩 때 불러, 처음 그리는 프레임에 풀기와 올리기가 몰리지 않게)
- 지금 이미지 스무딩과 밉맵 설정으로 올린다. (그릴 때 설정이 다르면 그때 거르기만 바꾼다)
- 이미 올린 그림이면 아무것도 하지 않는다. 아직 읽히지 않은 그림(크기 0)은 올리지 않는다.
- 코드로 만든 캔버스처럼 ImageAsset 으로 읽지 않은 그림을 씬의 load 에서 올려 둘 때 쓴다.
Uploads an image to the GPU in advance. (Call it while loading so that decoding and uploading do not pile up on the first drawn frame)
- Uploads with the current image smoothing and mipmap settings. (If the settings differ when drawing, only the filtering changes then)
- Does nothing if the image is already uploaded. Does not upload an image that is not loaded yet (size 0).
- Use it in a scene's load to upload images that were not loaded with ImageAsset, such as canvases made in code.
- imageHTMLImageElement | HTMLCanvasElement | OffscreenCanvas
- 올릴 그림.The image to upload.
반환Returnsboolean 텍스처가 있으면 true. (null 이거나 아직 읽히지 않은 그림이면 false)true if a texture exists. (false if null or the image is not loaded yet)
짝Counterpart: vanilla-engine Graphic.prepare_image
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
async load(engine) {
await super.load(engine);
this.dotImage = new OffscreenCanvas(32, 32);
const context = this.dotImage.getContext("2d");
context.fillStyle = "#ff6600";
context.fillRect(0, 0, 32, 32);
const isPrepared = engine.getGraphic().prepareImage(this.dotImage);
console.log(isPrepared);
}
draw(graphic) {
super.draw(graphic);
graphic.drawImage(this.dotImage, Vector2.create(304, 164), Vector2.create(32, 32));
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());읽었지만 아직 올리지 않은 그림 올리기. (ImageAsset 이 읽은 그림, 읽은 차례로)
- SceneManager 가 씬의 load 가 끝난 뒤(로딩 화면 동안) 프레임마다 나눠 부른다. 씬이 따로 부를 일은 없다.
- 시간 한도를 주면 그 시간을 넘긴 뒤에는 멈추고 남은 수를 돌려준다. (한 번에 적어도 하나는 올린다, 유니티의 asyncUploadTimeSlice 와 같다)
- 미리 푼 그림(ImageBitmap)은 올린 뒤 닫는다. 미리 풀지 않은 꼴의 그림은 그림 요소를 그대로 올린다.
Uploads images that were loaded but not uploaded yet. (Images loaded by ImageAsset, in loading order)
- SceneManager calls it split across frames after a scene's load finishes (during the loading screen). A scene does not need to call it.
- Given a time limit, it stops after exceeding that time and returns the remaining count. (Uploads at least one per call, same as Unity's asyncUploadTimeSlice)
- A pre-decoded image (ImageBitmap) is closed after uploading. An image of a format that is not pre-decoded is uploaded from the image element as is.
- timeLimitMillisecondsnumber
- 이번에 쓸 시간 한도. (밀리초, 기본 Infinity 는 모두)The time limit to use this time. (Milliseconds, the default Infinity means all)
반환Returnsnumber 아직 올리지 않고 남은 그림 수. (0 이면 다 올렸다)The number of images still left to upload. (0 means all are uploaded)
짝Counterpart: vanilla-engine Graphic.prepare_loaded_images
import { Engine, EngineConfiguration, Scene, ImageAsset, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
async load(engine) {
await super.load(engine);
this.imageAsset = new ImageAsset();
await this.imageAsset.load("examples/assets/spritesheet.png");
const remainingCount = engine.getGraphic().prepareLoadedImages();
console.log(remainingCount);
}
draw(graphic) {
super.draw(graphic);
graphic.drawImage(this.imageAsset.getImage(), Vector2.create(170, 30), Vector2.create(300, 300));
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());이미지 출력.
- setFillColor() Not Supported.
Draws an image.
- setFillColor() Not Supported.
- imageHTMLImageElement | HTMLCanvasElement
- 그릴 그림. (null 이나 undefined 면 오류를 던진다)Image to draw. (throws an error if null or undefined)
- positionVector2
- 그릴 왼쪽 위.Top left to draw at.
- contentSizeVector2
- 그릴 크기. (음수면 뒤집힌다)Size to draw. (flipped if negative)
짝Counterpart: vanilla-engine Graphic.draw_image
이미지의 일부만 출력.
- setFillColor() Not Supported.
Draws only part of an image.
- setFillColor() Not Supported.
- imageHTMLImageElement | HTMLCanvasElement
- 그릴 그림. (null 이나 undefined 면 오류를 던진다)Image to draw. (throws an error if null or undefined)
- positionVector2
- 그릴 왼쪽 위.Top left to draw at.
- contentSizeVector2
- 그릴 크기. (음수면 뒤집힌다)Size to draw. (flipped if negative)
- imageRectRect
- 그림 안에서 그릴 영역. (픽셀, null 이거나 비었으면 그림 전체)Area of the image to draw. (pixels, the whole image if null or empty)
짝Counterpart: vanilla-engine Graphic.draw_image_with_image_rect
drawImageWithSourceAndDestination(image, sourceX, sourceY, sourceWidth, sourceHeight, destinationX, destinationY, destinationWidth, destinationHeight)#이미지의 소스 영역을 지정 영역에 출력. (Canvas2D drawImage 9인자 대응)
Draws a source region of an image into a given region. (equivalent to the 9-argument Canvas2D drawImage)
- imageHTMLImageElement | HTMLCanvasElement
- 그릴 그림. (아직 불러오지 않아 크기가 0 이면 그리지 않는다)Image to draw. (nothing is drawn if its size is 0 because it is not loaded yet)
- sourceXnumber
- 그림 안의 왼쪽. (픽셀)Left inside the image. (pixels)
- sourceYnumber
- 그림 안의 위. (픽셀)Top inside the image. (pixels)
- sourceWidthnumber
- 그림 안의 너비. (픽셀)Width inside the image. (pixels)
- sourceHeightnumber
- 그림 안의 높이. (픽셀)Height inside the image. (pixels)
- destinationXnumber
- 그릴 왼쪽.Left to draw at.
- destinationYnumber
- 그릴 위.Top to draw at.
- destinationWidthnumber
- 그릴 너비. (음수면 뒤집힌다)Width to draw. (flipped if negative)
- destinationHeightnumber
- 그릴 높이. (음수면 뒤집힌다)Height to draw. (flipped if negative)
짝Counterpart: vanilla-engine Graphic.draw_image_with_source_and_destination
import { Engine, EngineConfiguration, Scene, Vector2, ImageAsset } from "./build/vanilla.js";
class MainScene extends Scene {
async load(engine) {
await super.load(engine);
this.imageAsset = new ImageAsset();
await this.imageAsset.load("examples/assets/spritesheet.png");
}
draw(graphic) {
super.draw(graphic);
const image = this.imageAsset.image;
graphic.drawImageWithSourceAndDestination(image, 200, 0, 200, 200, 220, 80, 200, 200);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());이미지 나인패치 출력.
- setFillColor() Not Supported.
Draws an image as a nine-patch.
- setFillColor() Not Supported.
- imageHTMLImageElement | HTMLCanvasElement
- 그릴 그림.Image to draw.
- positionVector2
- 그릴 왼쪽 위. (내림한다)Top left to draw at. (floored)
- sizeVector2
- 그릴 크기. (올림한다, 경계 두께 합보다 작으면 그 합)Size to draw. (ceiled, at least the sum of the border thicknesses)
- nineSliceRect
- 나인 슬라이스 경계. (position.x 왼쪽, position.y 위, size.x 오른쪽, size.y 아래 두께, 픽셀)Nine slice borders. (position.x left, position.y top, size.x right, size.y bottom thickness, pixels)
짝Counterpart: vanilla-engine Graphic.draw_image_with_nine_slice
폰트 문자열 설정. (Canvas2D font 대응, 예: "16px DOSGothic", 이름 default 는 엔진 기본 글꼴 사슬)
Sets the font string. (equivalent to Canvas2D font, e.g. "16px DOSGothic", the family name default is the engine default font chain)
- fontStringstring
- CSS 글꼴 글. (예: "16px DOSGothic", 이름 default 는 엔진 기본 글꼴 사슬 SYSTEM_FONT_STRING, 비었으면 바꾸지 않는다)CSS font string. (e.g. "16px DOSGothic", the family name default is the engine default font chain SYSTEM_FONT_STRING, unchanged if empty)
짝Counterpart: vanilla-engine Graphic.set_font_string
폰트 문자열 반환.
Returns the font string.
반환Returnsstring CSS 글꼴 글. (처음은 "10px sans-serif")CSS font string. (initially "10px sans-serif")
짝Counterpart: vanilla-engine Graphic.get_font_string
텍스트 가로 정렬 설정. ("left" | "center" | "right" | "start" | "end")
Sets the horizontal text alignment. ("left" | "center" | "right" | "start" | "end")
- textAlignstring
- 가로 정렬. (비었으면 바꾸지 않는다)Horizontal alignment. (unchanged if empty)
짝Counterpart: vanilla-engine Graphic.set_text_align
텍스트 가로 정렬 반환.
Returns the horizontal text alignment.
반환Returnsstring 가로 정렬. (처음은 "start")Horizontal alignment. (initially "start")
짝Counterpart: vanilla-engine Graphic.get_text_align
텍스트 방향 설정. ("inherit" | "ltr" | "rtl" | "auto", Canvas2D direction 대응)
- 문단의 방향이다. 글자 안의 순서(양방향 알고리즘)와 정렬 "start" / "end" 의 왼쪽, 오른쪽이 이것을 따른다.
- "inherit" 는 "ltr" 로 본다. (기본, 지금까지와 같다)
- "auto" 는 문자열마다 처음 나오는 방향이 강한 글자로 정한다. (HTML 의 dir="auto", 없으면 "ltr") 사용자가 쓴 글(닉네임 등)에 쓴다.
Sets the text direction. ("inherit" | "ltr" | "rtl" | "auto", equivalent to Canvas2D direction)
- This is the paragraph direction. The order within the text (bidirectional algorithm) and the left/right of alignment "start" / "end" follow it.
- "inherit" is treated as "ltr". (default, same as before)
- "auto" decides per string by the first strongly directional character. (HTML dir="auto", "ltr" if none) Used for user-written text (nicknames, etc.).
- textDirectionstring
- 글 방향. (비었으면 바꾸지 않는다)Text direction. (unchanged if empty)
짝Counterpart: vanilla-engine Graphic.set_text_direction
텍스트 방향 반환.
Returns the text direction.
반환Returnsstring 글 방향. (처음은 "inherit")Text direction. (initially "inherit")
짝Counterpart: vanilla-engine Graphic.get_text_direction
문자열의 실제 방향 계산. ("ltr" 또는 "rtl", "auto" 는 처음 나오는 방향이 강한 글자로)
Computes the actual direction of a string. ("ltr" or "rtl", "auto" uses the first strongly directional character)
- textstring
- 방향을 정할 글. ("auto" 일 때만 본다)Text that decides the direction. (inspected only for "auto")
반환Returnsstring "ltr" 또는 "rtl"."ltr" or "rtl".
짝Counterpart: vanilla-engine Graphic.resolve_text_direction
실제 가로 정렬 계산. ("start" / "end" 를 방향에 따라 "left" / "right" 로)
Computes the actual horizontal alignment. ("start" / "end" become "left" / "right" by direction)
- textAlignstring
- 정렬. ("left", "center", "right", "start", "end", 모르는 값은 "left")Alignment. ("left", "center", "right", "start", "end", "left" for unknown values)
- textDirectionstring
- "ltr" 또는 "rtl"."ltr" or "rtl".
반환Returnsstring "left" | "center" | "right"
짝Counterpart: vanilla-engine Graphic.resolve_text_align
텍스트 베이스라인 설정. ("top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom")
Sets the text baseline. ("top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom")
- textBaselinestring
- 세로 기준. (비었으면 바꾸지 않는다)Vertical baseline. (unchanged if empty)
짝Counterpart: vanilla-engine Graphic.set_text_baseline
텍스트 베이스라인 반환.
Returns the text baseline.
반환Returnsstring 세로 기준. (처음은 "alphabetic")Vertical baseline. (initially "alphabetic")
짝Counterpart: vanilla-engine Graphic.get_text_baseline
문자열 측정. (현재 폰트 기준, Canvas2D measureText 대응)
Measures a string. (based on the current font, equivalent to Canvas2D measureText)
- textstring
- 잴 글.Text to measure.
반환ReturnsTextMetrics 지금 글꼴로 잰 치수. (캐시가 나눠 쓰므로 고치지 않는다)Metrics measured with the current font. (shared by the cache so do not modify)
짝Counterpart: vanilla-engine Graphic.measure_text
문자열 측정. (주어진 폰트 문자열 기준, 현재 폰트 문자열은 바꾸지 않는다)
Measures a string. (with the given font string, does not change the current font string)
- fontStringstring
- 잴 때 쓸 폰트 문자열. (Canvas2D font 꼴)Font string to measure with. (Canvas2D font form)
- textstring
- 잴 글.Text to measure.
반환ReturnsTextMetrics 그 글꼴로 잰 치수. (캐시가 나눠 쓰므로 고치지 않는다, 지금 변환은 보지 않는다)Metrics measured with that font. (shared by the cache so do not modify it, the current transform is not considered)
짝Counterpart: vanilla-engine Graphic.measure_text_with_font_string
import { Engine, EngineConfiguration } from "./build/vanilla.js";
const engine = new Engine(new EngineConfiguration());
const graphic = engine.getGraphic();
const metrics = graphic.measureTextWithFontString("32px sans-serif", "Vanilla");
console.log(metrics.width > 0, graphic.getFontString());텍스트 베이크 스케일 양자화 단위 설정.
- 기본 0.25. 확대 축소가 잦은 글자가 스케일마다 새로 구워지지 않게 묶는다.
- 0 이면 양자화하지 않고 실제 스케일 그대로 굽는다. (스케일이 고정된 UI 글자를 늘리지 않고 1:1 로 그릴 때)
Sets the text bake scale quantization step.
- Default 0.25. Groups scales so text that is zoomed often is not re-baked for every scale.
- 0 means no quantization, baked at the actual scale. (for drawing fixed-scale UI text 1:1 without stretching)
- textBakeScaleStepnumber
- 양자화 단위. (음수는 0, 0 이면 양자화하지 않는다)Quantization step. (negative becomes 0, no quantization if 0)
짝Counterpart: vanilla-engine Graphic.set_text_bake_scale_step
텍스트 베이크 스케일 양자화 단위 반환.
Returns the text bake scale quantization step.
반환Returnsnumber 양자화 단위.Quantization step.
짝Counterpart: vanilla-engine Graphic.get_text_bake_scale_step
배율이 움직이는 노드의 텍스트 베이크 스케일 양자화 단위 설정. (기본 0.25)
- 양자화 단위(setTextBakeScaleStep)가 0 일 때, 그리는 노드의 변환 배율이 지난 프레임과 다르면(확대 움직임, 팝업, 트윈, 카메라 확대) 이 단위로 묶은 배율로 굽는다. 프레임마다 다른 배율로 새로 굽지 않는다.
- 배율이 멈추면(지난 프레임과 같으면) 정확한 배율로 다시 구워 1:1 로 또렷하다.
- 0 이면 움직이는 동안에도 묶지 않는다. (지금까지와 같다)
Sets the text bake scale quantization step for nodes whose scale is changing. (default 0.25)
- When the quantization step (setTextBakeScaleStep) is 0 and the drawn node's transform scale differs from the last frame (zoom motion, popup, tween, camera zoom), bakes at the scale grouped by this step. Does not re-bake at a different scale every frame.
- When the scale stops (same as the last frame), re-bakes at the exact scale so it is crisp 1:1.
- 0 means no grouping even while changing. (same as before)
- textBakeMotionScaleStepnumber
- 움직이는 동안의 양자화 단위. (음수는 0, 0 이면 묶지 않는다)Quantization step while moving. (negative becomes 0, no grouping if 0)
짝Counterpart: vanilla-engine Graphic.set_text_bake_motion_scale_step
배율이 움직이는 노드의 텍스트 베이크 스케일 양자화 단위 반환.
Returns the text bake scale quantization step for nodes whose scale is changing.
반환Returnsnumber 움직이는 동안의 양자화 단위.Quantization step while moving.
짝Counterpart: vanilla-engine Graphic.get_text_bake_motion_scale_step
지금 그리는 노드의 배율이 움직이는 중인지 설정. (drawNode 가 정한다, 노드 밖에서 직접 그릴 때 부르는 쪽이 정할 수 있다)
Sets whether the scale of the node being drawn is changing. (set by drawNode, the caller can set it when drawing directly outside a node)
- isTextBakeScaleMovingboolean
- 배율이 움직이는 중인지. (true 일 때만 움직이는 것으로 본다)Whether the scale is moving. (treated as moving only when true)
짝Counterpart: vanilla-engine Graphic.set_text_bake_scale_moving
지금 그리는 노드의 배율이 움직이는 중인지 반환.
Returns whether the scale of the node being drawn is changing.
반환Returnsboolean 배율이 움직이는 중이면 참.True if the scale is moving.
짝Counterpart: vanilla-engine Graphic.is_text_bake_scale_moving
노드의 변환 배율이 지난 프레임과 달라 움직이는 중인지 셈하고 기억하기. (drawNode 가 pushTransform 뒤에 부른다)
- 양자화 단위가 0 이 아니면 늘 묶어 굽으므로 셈하지 않는다.
- 처음 그리는 노드는 움직이지 않는 것으로 본다. (첫 프레임에 두 번 굽지 않게)
- 지난 프레임에 그리지 않은 노드(숨겼거나 화면 밖이라 하위 트리를 건너뛴 노드)도 처음 그리는 것처럼 본다. (건너뛴 사이에 배율이 바뀌어도 건너뛰지 않은 때와 같은 화면)
Computes and remembers whether a node's transform scale differs from the last frame, that is, is changing. (called by drawNode after pushTransform)
- If the quantization step is not 0, baking is always grouped, so this is not computed.
- A node drawn for the first time is treated as not changing. (to avoid baking twice on the first frame)
- A node that was not drawn in the previous frame (hidden, or skipped because its subtree was off screen) is also treated like one drawn for the first time. (the screen matches the unskipped case even if the scale changed while it was skipped)
- nodeTransformNode
- 그리는 노드. (지금 배율을 노드에 적어 둔다)Node being drawn. (the current scale is stored on the node)
반환Returnsboolean 배율이 지난 프레임과 달라 움직이는 중이면 참.True if the scale differs from the last frame and is moving.
텍스트 픽셀 스냅 설정.
- 켜면 회전 / 기울임이 없는 변환에서 글자 쿼드의 왼쪽 위를 디바이스 픽셀 격자에 맞춘다.
- 베이크 스케일이 실제 스케일과 같을 때(setTextBakeScaleStep(0)) 텍셀과 픽셀이 1:1 로 맞아 가장 선명하다.
Sets text pixel snapping.
- When on, aligns the top-left of glyph quads to the device pixel grid under transforms without rotation / skew.
- Sharpest when the bake scale equals the actual scale (setTextBakeScaleStep(0)), as texels and pixels match 1:1.
- isTextPixelSnapEnabledboolean
- 글자 쿼드를 디바이스 픽셀 격자에 맞출지.Whether to snap text quads to the device pixel grid.
짝Counterpart: vanilla-engine Graphic.set_text_pixel_snap_enabled
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
initialize(engine) {
const graphic = engine.getGraphic();
graphic.setTextBakeScaleStep(0);
graphic.setTextPixelSnapEnabled(true);
}
draw(graphic) {
super.draw(graphic);
graphic.setFillColor("#ffffff");
graphic.setFontString("16px sans-serif");
graphic.setTextAlign("left");
graphic.setTextBaseline("top");
graphic.drawFillText("Score 12345", 20, 20);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());텍스트 픽셀 스냅 여부 반환.
Returns whether text pixel snapping is on.
반환Returnsboolean 텍스트 픽셀 스냅이 켜졌으면 참.True if text pixel snapping is on.
짝Counterpart: vanilla-engine Graphic.is_text_pixel_snap_enabled
글자 안티앨리어싱 켬 / 끔. (러스트 Graphic::set_text_antialias_enabled 와 같다) 끄면 구운 글자의 알파를 문턱값 128 로 0 과 255 로 가르고 텍스처를 NEAREST 로 뽑는다. (도트 글꼴용) 이 Graphic 에만 걸린다. 바꾼 뒤 그리는 글부터 새 꼴이다. (이미 만든 글도 다음 그리기부터, 구운 글은 꼴마다 따로 남아 되돌리면 다시 굽지 않는다, 기본 켬)
Turns text antialiasing on or off. (Same as Rust Graphic::set_text_antialias_enabled) When off, baked glyph alpha is split into 0 and 255 at threshold 128 and the texture is sampled with NEAREST. (For pixel fonts) It applies only to this Graphic. Text drawn after the change uses the new form. (Text already made changes from its next draw too; baked text is kept per form, so switching back does not bake again. On by default)
- isTextAntialiasEnabledboolean
- 켜면 참.True to enable.
짝Counterpart: vanilla-engine Graphic.set_text_antialias_enabled
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
initialize(engine) {
engine.getGraphic().setTextAntialiasEnabled(false);
}
draw(graphic) {
super.draw(graphic);
graphic.setFillColor("#ffffff");
graphic.setFontString("16px sans-serif");
graphic.setTextAlign("left");
graphic.setTextBaseline("top");
graphic.drawFillText("PIXEL 123", 20, 20);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());글자 안티앨리어싱이 켜져 있는지.
Whether text antialiasing is on.
반환Returnsboolean 켜졌으면 참.True if on.
짝Counterpart: vanilla-engine Graphic.is_text_antialias_enabled
텍스트 베이크 스케일 계산. (현재 변환 행렬 기반, 양자화 단위는 setTextBakeScaleStep)
Computes the text bake scale. (based on the current transform matrix, quantization step from setTextBakeScaleStep)
반환Returnsnumber 굽는 배율. (0.25 ~ 8)Bake scale. (0.25 ~ 8)
짝Counterpart: vanilla-engine Graphic.calculate_text_bake_scale
글 배치 엔트리를 정렬/베이스라인에 맞춰 글리프 쿼드로 출력.
- 문자열을 통째로 구웠을 때의 사각형 자리(픽셀 스냅 포함)를 셈하고, 그 안의 글리프 사각형을 아틀라스에서 뽑아 그린다.
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.
- entryobject
- 글 배치 엔트리. (TextStringTextureCache.getEntry)Text layout entry. (TextStringTextureCache.getEntry)
- xnumber
- 기준 X. (정렬의 기준점)Anchor X. (the alignment anchor)
- ynumber
- 기준 Y. (세로 기준의 자리)Anchor Y. (the position of the vertical baseline)
- colorColor | null
- 흰색으로 구운 글자에 곱할 색. (null 이면 흰색 그대로)Color to multiply text baked in white by. (null keeps it white)
- textDirectionstring
- 정렬 "start" / "end" 를 가를 방향. ("ltr" 또는 "rtl", 기본 "ltr")Direction that resolves alignment "start" / "end". ("ltr" or "rtl", default "ltr")
짝Counterpart: vanilla-engine Graphic.draw_text_entry
텍스트 채움 출력. (Canvas2D fillText 대응)
- setFillColor() / setFontString() / setTextAlign() / setTextBaseline()
Draws filled text. (equivalent to Canvas2D fillText)
- setFillColor() / setFontString() / setTextAlign() / setTextBaseline()
- textstring
- 그릴 글. (비었으면 그리지 않는다)Text to draw. (nothing is drawn if empty)
- xnumber
- 기준 X. (정렬의 기준점)Anchor X. (the alignment anchor)
- ynumber
- 기준 Y. (세로 기준의 자리)Anchor Y. (the position of the vertical baseline)
짝Counterpart: vanilla-engine Graphic.draw_fill_text
텍스트 외곽선 출력. (Canvas2D strokeText 대응)
- setStrokeColor() / setFontString() / setTextAlign() / setTextBaseline()
Draws outlined text. (equivalent to Canvas2D strokeText)
- setStrokeColor() / setFontString() / setTextAlign() / setTextBaseline()
- textstring
- 그릴 글. (비었으면 그리지 않는다)Text to draw. (nothing is drawn if empty)
- xnumber
- 기준 X. (정렬의 기준점)Anchor X. (the alignment anchor)
- ynumber
- 기준 Y. (세로 기준의 자리)Anchor Y. (the position of the vertical baseline)
- lineWidthnumber
- 선 굵기. (기본 1)Line width. (default 1)
짝Counterpart: vanilla-engine Graphic.draw_stroke_text
노드 출력.
Draws a node.
- nodeTransformNode
- 그릴 노드. (null 이거나 꺼져 있으면 그리지 않는다)Node to draw. (nothing is drawn if null or inactive)
출력 영역 제한 시작.
- 스텐실 버퍼 기반이라 회전/스케일이 걸린 영역도 정확히 잘린다.
- roundSize 를 주면 둥근 사각형으로 잘린다. (Paint 의 roundSize 와 같은 값이면 배경과 정확히 맞는다)
Begins clipping the output region.
- Stencil buffer based, so rotated/scaled regions are clipped exactly too.
- Given roundSize, clips to a rounded rectangle. (matches the background exactly when equal to Paint's roundSize)
- rectRect
- 자를 사각형. (지금 변환으로 옮기기 전의 로컬 좌표)Rect to clip to. (local coordinates before the current transform)
- roundSizenumber
- 모서리 반지름. (기본 0, 0 이하면 각진 사각형)Corner radius. (default 0, a sharp rectangle if 0 or less)
짝Counterpart: vanilla-engine Graphic.begin_clip_rect
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.beginClipRect(Rect.create(100, 60, 200, 200), 24);
graphic.setFillColor("#3399ff");
graphic.drawCircle(Vector2.create(300, 160), 120);
graphic.endClipRect();
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());투명도 층 시작. (CSS opacity, 어도비 투명도 묶음처럼 endOpacityLayer 까지 그린 것을 따로 칸에 모았다가 지금 전역 알파로 한 번에 얹는다)
- 층 안의 그림은 서로 겹친 자리가 비치지 않는다. (노드마다 투명도를 곱해 따로 얹으면 겹친 자리에서 아래 그림이 비친다)
- 층 안은 전역 알파 1 에서 시작한다. 층 칸은 화면과 같은 크기의 RGBA8 이고 깊이를 비우고 스텐실을 지금 자르기 깊이로 채워 둬 층 안의 자르기와 3D 패스(clearDepth: false)도 그대로 된다. 바깥 자르기는 얹을 때 걸린다. 층은 겹쳐 열 수 있다. 칸을 지을 수 없으면 층 없이 그대로 그린다.
- 노드는 setOpacityLayer 를 켜고 투명도가 1 보다 작으면 그 노드와 자손을 층으로 그린다.
Begins an opacity layer. (Like CSS opacity or an Adobe transparency group, everything drawn until endOpacityLayer is gathered in a separate buffer and laid down at once with the current global alpha)
- Drawings inside the layer do not show through each other where they overlap. (Multiplying opacity per node and laying each down separately lets the drawing below show through at overlaps)
- Inside the layer the global alpha starts at 1. The layer buffer is RGBA8 at the screen size, its depth is cleared and its stencil is filled with the current clip depth, so clips and 3D passes (clearDepth: false) inside the layer still work. Outer clips apply when the layer is laid down. Layers can be nested. If the buffer cannot be made, drawing goes straight through without a layer.
- A node with setOpacityLayer turned on and opacity below 1 is drawn with its descendants as a layer.
짝Counterpart: vanilla-engine Graphic.begin_opacity_layer
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.pushState();
graphic.setGlobalAlpha(0.5);
graphic.beginOpacityLayer();
graphic.setFillColor("#ff0000");
graphic.drawRect(Rect.create(100, 100, 200, 100));
graphic.setFillColor("#0000ff");
graphic.drawRect(Rect.create(200, 150, 200, 100));
graphic.endOpacityLayer();
graphic.popState();
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());투명도 층 끝. (beginOpacityLayer 뒤에 그린 것을 앞 프레임버퍼에 층을 열 때의 전역 알파로 얹는다)
Ends an opacity layer. (Lays what was drawn after beginOpacityLayer onto the previous framebuffer with the global alpha at the time the layer was opened)
짝Counterpart: vanilla-engine Graphic.end_opacity_layer
출력 영역 제한 종료.
Ends clipping the output region.
짝Counterpart: vanilla-engine Graphic.end_clip_rect
3D 색 공간 반환. (ColorSpace, 툰 렌더러와 후처리가 엔진에서 읽는 기본값, 이 묶음의 2D 는 어느 값이든 감마 공간에서 합성한다)
Returns the 3D color space. (ColorSpace, the default the toon renderer and post process read from the engine, this batch's 2D composites in gamma space either way)
반환Returnsstring ColorSpace.gamma 나 ColorSpace.linear.ColorSpace.gamma or ColorSpace.linear.
짝Counterpart: vanilla-engine Graphic.get_color_space
import { Graphic, ColorSpace } from "./vanilla.js";
const graphic = new Graphic(document.createElement("canvas"), false, true, ColorSpace.linear);
if (graphic.getColorSpace() !== ColorSpace.linear) {
throw new Error("color space is not linear");
}WebGL2 렌더링 컨텍스트 반환.
Returns the WebGL2 rendering context.
반환ReturnsWebGL2RenderingContext WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
지금 그리는 프레임 버퍼 반환. (null 이면 캔버스, GL 에 묻지 않고 기억한 값)
Return the framebuffer being drawn to now. (null means the canvas, a remembered value read without asking GL)
반환ReturnsWebGLFramebuffer | null 지금 묶인 그리기 프레임 버퍼. (null 이면 캔버스의 기본 프레임 버퍼)The draw framebuffer bound now. (null means the canvas default framebuffer)
짝Counterpart: vanilla-engine Graphic.get_current_framebuffer
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.runExternalPass((webGL2RenderingContext) => {
const previousFramebuffer = graphic.getCurrentFramebuffer();
const framebuffer = webGL2RenderingContext.createFramebuffer();
webGL2RenderingContext.bindFramebuffer(webGL2RenderingContext.FRAMEBUFFER, framebuffer);
webGL2RenderingContext.bindFramebuffer(webGL2RenderingContext.FRAMEBUFFER, previousFramebuffer);
webGL2RenderingContext.deleteFramebuffer(framebuffer);
}, { clearDepth: false });
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());지금 뷰포트 반환. (디바이스 픽셀, GL 처럼 왼쪽 아래가 원점, GL 에 묻지 않고 기억한 값)
Return the current viewport. (device pixels, origin at the bottom left like GL, a remembered value read without asking GL)
반환ReturnsRect 지금 뷰포트. (위치 x, y 와 크기 너비, 높이, 새 Rect)The current viewport. (position x, y and size width, height, a new Rect)
짝Counterpart: vanilla-engine Graphic.get_current_viewport
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
const viewport = graphic.getCurrentViewport();
console.log(viewport.position.x, viewport.position.y, viewport.width, viewport.height);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());GL 상태 기억 다시 맞추기. (three.js 의 resetState 처럼 바깥 GL 코드가 상태를 바꾼 뒤 부른다)
- 엔진은 컨텍스트의 상태 함수(bindFramebuffer, viewport, enable 같은 것)를 가로채 기억하므로, 같은 컨텍스트 객체로 부른 것은 따로 알리지 않아도 된다.
- 프로토타입 함수를 직접 부르는 것처럼 가로채지 못한 길로 바꿨을 때 부른다. 기억을 모두 잊고 다음에 읽을 때 GL 에 한 번씩 묻는다. Graphic 은 묶음과 상태를 따로 기억하지 않고 이 기억에 견주므로, 그 뒤의 2D 그리기도 제 프로그램, 텍스처, 섞기를 다시 건다.
Resynchronize the remembered GL state. (call it after outside GL code changed the state, like resetState in three.js)
- The engine intercepts the context's state functions (bindFramebuffer, viewport, enable and so on) and remembers them, so calls made through the same context object need no notice.
- Call it after changing state in a way that cannot be intercepted, such as calling a prototype function directly. It forgets everything and asks GL once for each value the next time it is read. Graphic keeps no binding or state memory of its own and compares against this memory, so the 2D draws after it also set their own program, textures and blending again.
짝Counterpart: vanilla-engine Graphic.reset_gl_state_cache
import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.runExternalPass((webGL2RenderingContext) => {
WebGL2RenderingContext.prototype.viewport.call(webGL2RenderingContext, 0, 0, 64, 64);
graphic.resetGLStateCache();
console.log(graphic.getCurrentViewport().width);
}, { clearDepth: false });
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());드로잉 버퍼 너비 반환. (픽셀, 마지막으로 맞춘 뷰포트)
Returns the drawing buffer width. (pixels, the last set viewport)
반환Returnsnumber 드로잉 버퍼 너비. (픽셀)Drawing buffer width. (pixels)
짝Counterpart: vanilla-engine Graphic.get_drawing_buffer_width
드로잉 버퍼 높이 반환. (픽셀, 마지막으로 맞춘 뷰포트)
Returns the drawing buffer height. (pixels, the last set viewport)
반환Returnsnumber 드로잉 버퍼 높이. (픽셀)Drawing buffer height. (pixels)
짝Counterpart: vanilla-engine Graphic.get_drawing_buffer_height
지금 그린 화면 읽기. (너비, 높이, 위에서 아래로 놓인 RGBA. 화면을 넘기기 전에 부른다)
- 캔버스처럼 불투명으로 본다. (알파 255)
Reads the screen drawn so far. (width, height, RGBA laid out top to bottom. Call before the frame is presented)
- Treated as opaque like a canvas. (alpha 255)
반환Returns{ width: number, height: number, pixels: Uint8Array } 화면 픽셀. ({ width, height, pixels }, pixels 는 위 줄부터 RGBA, 알파 255)Screen pixels. ({ width, height, pixels }, pixels are RGBA from the top row, alpha 255)
짝Counterpart: vanilla-engine Graphic.read_framebuffer_pixels
셰이더 프로그램 반환.
Returns the shader program.
반환ReturnsShaderProgram 지금 쓰는 셰이더 프로그램. (바꿔 끼운 것이 있으면 그것)Shader program in use. (the override if any)
짝Counterpart: vanilla-engine Graphic.get_shader_program
셰이더 프로그램 바꿔 끼우기. (null 이면 기본 프로그램으로 복귀)
- 기본 프로그램과 같은 어트리뷰트 위치 / 유니폼 이름(projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture)을 갖춰야 한다.
Swaps in a shader program. (null returns to the default program)
- Must have the same attribute locations / uniform names as the default program (projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture).
- shaderProgramShaderProgram | null
- 바꿔 끼울 셰이더 프로그램. (null 이면 기본 프로그램)Shader program to swap in. (the default program if null)
짝Counterpart: vanilla-engine Graphic.set_shader_program_override
렌더 상태 복구. (외부 WebGL 패스가 프로그램 / 버텍스 어레이 / 뷰포트를 바꾼 뒤 Graphic 출력을 이어갈 때)
Restores the render state. (when continuing Graphic output after an external WebGL pass changed the program / vertex array / viewport)
짝Counterpart: vanilla-engine Graphic.restore_render_state
셰이더 프로그램 쓰게 하기. (상태 캐시가 이미 이 프로그램을 쓴다고 기억하면 다시 걸지 않는다)
- Graphic 은 쓰게 한 프로그램을 따로 기억하지 않는다. 게임이 같은 컨텍스트로 다른 프로그램을 쓰게 해도 다음 그리기가 제 프로그램을 다시 건다.
Puts a shader program in use. (does not set it again if the state cache remembers this program is already in use)
- Graphic keeps no memory of its own of the program in use. Even if a game puts another program in use through the same context, the next draw sets its own program again.
- shaderProgramShaderProgram
- 쓸 셰이더 프로그램.Shader program to use.
0 번 텍스처 유닛에 텍스처 묶기. (상태 캐시가 이미 묶였다고 기억하면 다시 묶지 않는다)
- 활성 유닛이 0 번이 아니면 0 번으로 돌린다. (게임이 다른 유닛을 활성으로 두고 돌아와도 0 번에 묶는다)
Binds a texture to texture unit 0. (does not bind it again if the state cache remembers it is already bound)
- If the active unit is not 0, switches back to unit 0. (binds to unit 0 even when a game comes back leaving another unit active)
- textureWebGLTexture
- 묶을 텍스처.Texture to bind.
깊이 버퍼 비우기. (2D 그리기 사이에 3D 를 끼우기 전에)
- 자르기(beginClipRect, 스텐실)를 건 뒤 그리는 도중에 깊이를 비우면 갤럭시 폴드3(Adreno 660)의 드라이버가 3D 를 하나도 그리지 못한 일이 있다. 자르기 안에 3D 를 그릴 노드는 beginClipRect 앞에서 이것을 부르고, runExternalPass 에는 clearDepth: false 를 준다.
Clears the depth buffer. (before inserting 3D between 2D draws)
- Clearing depth mid-draw after setting a clip (beginClipRect, stencil) once made the Galaxy Fold3 (Adreno 660) driver draw no 3D at all. Nodes that draw 3D inside a clip call this before beginClipRect, and pass clearDepth: false to runExternalPass.
짝Counterpart: vanilla-engine Graphic.clear_depth_buffer
2D 그리기 사이에 WebGL 패스 끼우기. (앞의 2D 묶음을 그리고, 깊이를 비운 뒤 callback, 끝나면 restoreRenderState)
- callback 은 WebGL2 컨텍스트를 받아 프로그램, 버텍스 어레이, 뷰포트, 섞기, 깊이, 면 가리기를 마음대로 바꿔도 된다. (스텐실 자르기는 그대로 걸려 있고, 스텐실 상태는 되돌리지 않으므로 바꾸지 않는다)
- callback 이 던지면 상태를 되돌린 뒤 다시 던진다.
- 이 함수 밖에서 같은 컨텍스트로 WebGL 을 써도 다음 2D 그리기가 프로그램, 버텍스 어레이, 텍스처 유닛, 섞기, 깊이, 면 가리기, 가위, 뷰포트를 상태 캐시에 견주어 다시 건다. 남는 약속은 둘이다. 2D 는 지금 묶인 프레임 버퍼에 그리므로 게임 프레임 버퍼를 묶었으면 들어올 때 것으로 돌려 두고, 스텐실 상태는 바꾸지 않는다.
Inserts a WebGL pass between 2D draws. (draws the preceding 2D batch, clears depth, then callback, and restoreRenderState when done)
- callback receives the WebGL2 context and may freely change the program, vertex array, viewport, blending, depth and face culling. (the stencil clip stays applied, and the stencil state is not restored, so do not change it)
- If callback throws, the state is restored and the error is rethrown.
- Even when WebGL is used through the same context outside this function, the next 2D draw compares the program, vertex array, texture units, blending, depth, face culling, scissor and viewport against the state cache and sets them again. Two promises remain. 2D draws into the framebuffer bound now, so if the game bound its own framebuffer it puts back the one it found, and it does not change the stencil state.
- callbackFunction
- (webGL2RenderingContext) => any
- optionsobject
- { clearDepth 깊이를 비울지 (기본 true, 자르기 안이면 clearDepthBuffer 머리말) }{ clearDepth whether to clear depth (default true, inside a clip see the clearDepthBuffer header comment) }
반환Returnsany callback 이 돌려준 것.The value returned by callback.
짝Counterpart: vanilla-engine Graphic.run_external_pass
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
class MainScene extends Scene {
draw(graphic) {
super.draw(graphic);
graphic.setFillColor("#888888");
graphic.drawRect(Rect.create(0, 0, 640, 360));
graphic.runExternalPass((webGL2RenderingContext) => {
webGL2RenderingContext.enable(webGL2RenderingContext.SCISSOR_TEST);
webGL2RenderingContext.scissor(20, 20, 100, 100);
webGL2RenderingContext.clearColor(0.2, 0.4, 0.8, 1);
webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT);
webGL2RenderingContext.disable(webGL2RenderingContext.SCISSOR_TEST);
}, { clearDepth: false });
graphic.setFillColor("#ffffff");
graphic.drawCircle(Vector2.create(320, 180), 40);
}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());버텍스 어레이 반환.
Returns the vertex array.
반환ReturnsWebGLVertexArrayObject 버텍스 어레이.Vertex array.
짝Counterpart: vanilla-engine Graphic.get_vertex_array
버텍스 버퍼 반환.
Returns the vertex buffer.
반환ReturnsWebGLBuffer 버텍스 버퍼.Vertex buffer.
짝Counterpart: vanilla-engine Graphic.get_vertex_buffer
스크래치 버텍스 데이터 반환.
Returns the scratch vertex data.
반환ReturnsFloat32Array 스크래치 버텍스 데이터. (정점마다 x, y, u, v)Scratch vertex data. (x, y, u, v per vertex)
짝Counterpart: vanilla-engine Graphic.get_vertex_data
흰색 텍스처 반환. (단색 도형용)
Returns the white texture. (for solid-color shapes)
반환ReturnsWebGLTexture 1x1 흰색 텍스처.1x1 white texture.
짝Counterpart: vanilla-engine Graphic.get_white_texture
흰색 색상 반환. (이미지/텍스트 출력용 기본 색상)
Returns the white color. (default color for image/text output)
반환ReturnsColor 흰색. (나눠 쓰므로 고치지 않는다)White. (shared so do not modify)
짝Counterpart: vanilla-engine Graphic.get_white_color
이미지 텍스처 캐시 반환.
Returns the image texture cache.
반환ReturnsImageTextureCache 이미지 텍스처 캐시.Image texture cache.
짝Counterpart: vanilla-engine Graphic.get_image_texture_cache
문자열 텍스처 캐시 반환.
Returns the string texture cache.
반환ReturnsTextStringTextureCache 문자열 텍스처 캐시.String texture cache.
짝Counterpart: vanilla-engine Graphic.get_text_string_texture_cache
이름으로 담아 둔 바꿔 끼울 셰이더 프로그램 반환. (없으면 createShaderSource 가 준 소스로 만들어 담는다)
- 어트리뷰트 위치를 기본 프로그램과 같게 고정해 링크하므로 기본 버텍스 어레이를 그대로 쓴다.
- 만들기에 실패하면 한 번만 알리고 null 을 담아 두어 다시 만들지 않는다.
Return a cached program, swappable into drawing, by name. (if none is cached, build it from the sources createShaderSource gives and cache it)
- Links with the attribute locations pinned to the default program, so the default vertex array is used as is.
- If building fails it reports once and caches null so it is never built again.
- programGroupNamestring
- 묶음 이름. (효과 종류 같은 것, 열쇠의 앞)Group name. (such as an effect kind, the first half of the key)
- programNamestring
- 프로그램 이름. (열쇠의 뒤)Program name. (the second half of the key)
- createShaderSource() => [string, string]
- 담긴 것이 없을 때만 부르는 함수. ([버텍스 소스, 프래그먼트 소스], GLSL ES 3.00)Function called only when nothing is cached. ([vertex source, fragment source], GLSL ES 3.00)
반환ReturnsShaderProgram | null 담아 둔 프로그램. 만들기에 실패했으면 null. (그 뒤로도 null)The cached program. null if building failed. (null afterwards too)
짝Counterpart: vanilla-engine Graphic.resolve_shader_program
import { Engine, EngineConfiguration, Scene, Color, Rect } from "./build/vanilla.js";
const VERTEXSHADER_SOURCE = `#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 = `#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 * mainColor.rgb, vec3(0.299, 0.587, 0.114));
float alpha = textureColor.a * mainColor.a * globalAlpha;
outputColor = vec4(vec3(gray) * alpha, alpha);
}
`;
class MainScene extends Scene {
preDraw(graphic) {
super.preDraw(graphic);
const shaderProgram = graphic.resolveShaderProgram("example", "gray", () => [VERTEXSHADER_SOURCE, GRAY_FRAGMENTSHADER_SOURCE]);
graphic.setShaderProgramOverride(shaderProgram);
graphic.setFillColor(new Color(1, 0.4, 0.2, 1));
graphic.drawRect(Rect.create(220, 100, 200, 160));
graphic.setShaderProgramOverride(null);
}
}
const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());함수Functions
글의 첫 강한 방향. ("ltr" 또는 "rtl", 글자 갈래 문자와 LRM, RLM, ALM 가운데 처음 것, 없으면 "ltr". setTextDirection("auto") 가 쓴다)
First strong direction of the text. ("ltr" or "rtl", the first among letter-class characters and LRM, RLM, ALM, "ltr" if none. Used by setTextDirection("auto"))
- textstring
- 볼 글. (비었으면 "ltr")Text to inspect. ("ltr" if empty)
반환Returnsstring "ltr" 또는 "rtl"."ltr" or "rtl".
짝Counterpart: vanilla-engine detect_text_direction