WhatsCanvas Public API Reference¶
This document is generated from the declarations and Doxygen comments in
include/wsc/. Update the public headers first; this reference intentionally
has no independent behavioral-contract source.
Headers¶
wsc/wsc.hwsc/base.hwsc/Canvas.hwsc/CanvasStats.hwsc/Color.hwsc/Font.hwsc/FontSystem.hwsc/FontResolver.hwsc/Image.hwsc/ImageFilter.hwsc/Log.hwsc/Matrix.hwsc/Paint.hwsc/Path.hwsc/Picture.hwsc/Surface.hwsc/TextureSource.hwsc/Version.h
wsc/wsc.h¶
Convenience umbrella header for the common WhatsCanvas drawing API.
WhatsCanvas requires C++17. Installed packages should normally be consumed
through one of the imported CMake targets: WhatsCanvas::Software,
WhatsCanvas::OpenGL, or WhatsCanvas::OpenGLES.
Quick start for a simple off-screen drawing:
1. Pick a backend (Software is the simplest starting point).
2. Create a Canvas with the desired size.
3. Call beginFrame() before drawing anything.
4. Configure a Paint (color, stroke width, fill/stroke style, etc.).
5. Draw geometry or text.
6. Call endFrame(). If the canvas is rendering to a window/output target,
call present() after the frame ends.
The smallest off-screen program is:
#include <wsc/wsc.h>
auto canvas = wsc::Canvas::create(wsc::Canvas::Backend::Software, 256, 256);
if (!canvas) return 1;
canvas->beginFrame();
canvas->drawColor(wsc::Color::WHITE);
wsc::Paint paint;
paint.setColor(wsc::Color(40, 120, 240));
canvas->drawCircle(128, 128, 64, paint);
canvas->endFrame();
return canvas->savePixelsPPM("frame.ppm") ? 0 : 2;
A Canvas is rendering-thread confined. Every frame follows
beginFrame() -> draw calls -> endFrame(); call present() afterwards
only for a configured output target. OpenGL/OpenGL ES hosts must make their
context current and call Canvas::loadOpenGL() before creating the Canvas.
Common startup checklist:
- For the first app, prefer Canvas::Backend::Software to validate drawing
logic and resource lifetime before switching to a GL-backed backend.
- Check the return value of Canvas::create() and Canvas::loadOpenGL().
- Do not call draw methods outside a frame or on a different thread from the
Canvas's owner thread.
- When using a window-backed target (OutputTarget::ToWindow()), call
present() after endFrame() only for that output target.
See also: README.md in this installed directory for package linking, high-DPI,
resource ownership, context-loss, image, and font integration guidance.
Advanced integrations include their feature header explicitly:
- <wsc/FontResolver.h> for custom/lazy/remote font providers;
- <wsc/FontSystem.h> for font registration and installed-font discovery;
- <wsc/CanvasStats.h> for detailed frame diagnostics;
- <wsc/Log.h> for the logging configuration API.
wsc/base.h¶
class Point¶
Integer point in Canvas' top-left-origin 2D coordinate space.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Point(int x = 0, int y = 0);int getX() const;void setX(int x);int getY() const;void setY(int y);void set(int x, int y);bool operator==(const Point &other) const;bool operator!=(const Point &other) const;Point operator+(const Point &other) const;Point operator+(int scalar) const;Point operator-(const Point &other) const;Point operator-(int scalar) const;Point &operator+=(const Point &other);Point &operator+=(int scalar);Point &operator-=(const Point &other);Point &operator-=(int scalar);Point operator*(int scalar) const;
class PointF¶
Floating-point point in Canvas' top-left-origin 2D coordinate space.
Additional public members¶
Straightforward accessors, value operations, and overloads:
PointF(float x = 0.0f, float y = 0.0f);float getX() const;void setX(float x);float getY() const;void setY(float y);void set(float x, float y);bool operator==(const PointF &other) const;bool operator!=(const PointF &other) const;PointF operator+(const PointF &other) const;PointF operator+(float scalar) const;PointF operator-(const PointF &other) const;PointF operator-(float scalar) const;PointF &operator+=(const PointF &other);PointF &operator+=(float scalar);PointF &operator-=(const PointF &other);PointF &operator-=(float scalar);PointF operator*(float scalar) const;PointF operator/(float scalar) const;
class Size¶
Integer width and height pair. Values are stored verbatim; callers provide positive dimensions where an API requires a drawable area.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Size(int width = 0, int height = 0);int getWidth() const;void setWidth(int width);int getHeight() const;void setHeight(int height);void set(int width, int height);bool operator==(const Size &other) const;bool operator!=(const Size &other) const;
class SizeF¶
Floating-point width and height pair. Values are stored verbatim.
Additional public members¶
Straightforward accessors, value operations, and overloads:
SizeF(float width = 0.0f, float height = 0.0f);float getWidth() const;void setWidth(float width);float getHeight() const;void setHeight(float height);void set(float width, float height);bool operator==(const SizeF &other) const;bool operator!=(const SizeF &other) const;
class RectF¶
Floating-point (x, y, width, height) rectangle.
This is not a left/top/right/bottom tuple. Geometry helpers assume non-negative width and height; Canvas drawing methods document where they normalize negative dimensions. Edges are inclusive for contains().
RectF¶
RectF(float x = 0.0f, float y = 0.0f, float width = 0.0f, float height = 0.0f);RectF(const PointF &leftTop, const PointF &bottomRight);
Construct from top-left position and size.
contains¶
bool contains(float px, float py) const;bool contains(const PointF &point) const;
Whether a point lies on or inside all four edges.
transform¶
void transform(float dx, float dy);
Translate only the rectangle origin.
scale¶
void scale(float sx, float sy);
Scale width and height around the unchanged top-left origin.
getIntersection¶
RectF getIntersection(const RectF &other) const;
Return the positive-area overlap, or an empty default rectangle.
Additional public members¶
Straightforward accessors, value operations, and overloads:
float getX() const;void setX(float x);float getY() const;void setY(float y);PointF getLeftTop() const;PointF getBottomRight() const;float getWidth() const;void setWidth(float width);float getHeight() const;void setHeight(float height);SizeF getSize() const;PointF getCenter() const;void setCenter(const PointF ¢er);void setCenter(float cx, float cy);float getArea() const;float getPerimeter() const;bool intersects(const RectF &other) const;bool isSquare() const;
class Rect¶
Integer (x, y, width, height) rectangle; see RectF for edge and helper semantics.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Rect(int x = 0, int y = 0, int width = 0, int height = 0);Rect(const Point &leftTop, const Point &bottomRight);int getX() const;void setX(int x);int getY() const;void setY(int y);Point getLeftTop() const;Point getBottomRight() const;int getWidth() const;void setWidth(int width);int getHeight() const;void setHeight(int height);Size getSize() const;PointF getCenter() const;void setCenter(const Point ¢er);void setCenter(int cx, int cy);bool contains(int px, int py) const;bool contains(const Point &point) const;void transform(int dx, int dy);void scale(float sx, float sy);int getArea() const;int getPerimeter() const;bool intersects(const Rect &other) const;bool isSquare() const;Rect getIntersection(const Rect &other) const;
wsc/Canvas.h¶
class Canvas¶
Stateful drawing surface and command recorder exposed by WhatsCanvas.
A Canvas owns one renderer backend and its backend resources. It is confined to the application's rendering thread; concurrent access to one Canvas, or sharing its Images/external textures across unrelated Canvas instances, is not part of the public contract. OpenGL/OpenGL ES calls require the host context to be current on that thread.
Coordinates use a top-left origin with X increasing right and Y increasing
down. Rect/RectF values are (x, y, width, height), angles are radians, and
drawing uses physical pixels unless setDevicePixelRatio() establishes a
logical-coordinate scale. Drawing state (matrix, DPR, clip, color and blend
mode) is scoped by save()/restore().
Typical drawing flow:
auto canvas = wsc::Canvas::create(wsc::Canvas::Backend::Software, 256, 256);
if (!canvas) return;
canvas->beginFrame();
canvas->drawColor(wsc::Color::WHITE);
wsc::Paint paint;
paint.setColor(wsc::Color(40, 120, 240));
canvas->drawRoundRect(wsc::RectF(32, 32, 192, 128), 16.0f, paint);
canvas->endFrame();
A normal frame is beginFrame() -> draw calls -> endFrame(). Pixel
readback and Canvas-as-texture sampling require the frame to have ended;
call present() afterwards only when an output target needs presentation.
OutputTarget is a design choice that separates drawing from presentation.
A Canvas records commands and renders to an internal backend resource; the
output target decides where the finished frame is sent: an offscreen buffer
for readback/texture reuse, a native OS window for presentation, or a
host-owned framebuffer/swapchain for embedding in an existing graphics
pipeline. This lets the same drawing code target different destinations
without reworking the drawing commands themselves. The flow is typically:
create -> setOutputTarget -> beginFrame -> draw -> endFrame -> present().
Minimal software frame:
auto canvas = wsc::Canvas::create(wsc::Canvas::Backend::Software, 64, 64);
canvas->beginFrame();
canvas->drawColor(wsc::Color::WHITE);
canvas->endFrame();
Minimal OpenGL frame (host setup is abbreviated):
makeContextCurrent(); // Provided by the window system.
wsc::Canvas::loadOpenGL(getProcAddress); // Host GL address lookup.
auto canvas = wsc::Canvas::create(wsc::Canvas::Backend::OpenGL, 64, 64);
canvas->beginFrame();
canvas->drawColor(wsc::Color::WHITE);
canvas->endFrame();
swapBuffers(); // Provided by the window system.
Common lifecycle checklist:
- Create a Canvas once for a backend/device and keep it on the same render
thread.
- Call beginFrame() before issuing draw commands.
- Use Paint to set fill/stroke/text state and RectF/PointF/Path for
geometry. save()/restore() apply state changes within a frame.
- End the frame with endFrame(). Only present to a window-backed target when
the target needs a display update.
- Call finalizeContext() or destroy the canvas during teardown; do not use a
GL-backed canvas after the owning context is lost unless the backend is
reinitialized.
initialize¶
static void initialize();
Initialize every currently registered Canvas. Usually unnecessary because beginFrame() initializes lazily. GL contexts for all GL canvases must be current when this process-wide helper is used.
finalize¶
static void finalize();
Finalize every currently registered Canvas. Prefer finalizeContext() when different canvases belong to different contexts/threads.
loadOpenGL¶
static bool loadOpenGL(OpenGLProcAddress loadProcAddress);
Load the process GL/GLES entry-point table. Call after the host context is current and before creating/initializing an OpenGL or OpenGLES Canvas. Returns false for a null loader, an incompatible context, or a build with no GL-family renderer. Other backends do not call this function.
getOpenGLVersionString¶
static std::string getOpenGLVersionString();
Return the active GL version string, or an empty string when GL is not loaded.
setGammaCorrect¶
static void setGammaCorrect(bool enabled);
Enable or disable gamma-correct rendering. When enabled, all color operations are performed in linear color space, producing visually correct alpha blending. The GPU framebuffer uses sRGB format for automatic linear→sRGB conversion on output.
isGammaCorrect¶
static bool isGammaCorrect();
Check whether gamma-correct rendering is currently enabled.
~Canvas¶
~Canvas();
Release the Canvas and owned resources. A GL context must still be current unless finalizeContext() or abandonContext() was called first.
create¶
static std::unique_ptr<Canvas> create(Backend backend, int width, int height);static std::unique_ptr<Canvas> create(std::initializer_list<Backend> preferred, int width, int height);
Create a canvas on backend, sized to physical width x height pixels.
Dimensions must be positive before rendering. Returns nullptr when
the backend is unavailable in this build/host. The canvas is sized but
not initialized. Call beginFrame() (which initializes lazily) or
initializeContext() before drawing. For the OpenGL backends, make your
GL context current and call loadOpenGL() before initialization or the
first frame; Software/Vulkan/Metal need no external GL context.
isBackendAvailable¶
static bool isBackendAvailable(Backend backend);
Whether backend can be created in this build/host.
backend¶
Backend backend() const;
The backend this canvas was created with.
getRenderStats¶
RenderStats getRenderStats() const;
Return the current diagnostic counters without synchronizing extra GPU work. GPU time is valid only when gpuTimeAvailable is true.
setGpuTimingEnabled¶
void setGpuTimingEnabled(bool enabled);
Enable optional backend GPU frame timers. Disabled by default so normal rendering and comparative benchmarks pay no query overhead.
initializeContext¶
bool initializeContext();
Initialize backend resources now. Returns false on unavailable/misconfigured backends, invalid size, or missing/current-context failures. beginFrame() also initializes lazily but cannot return the failure to the caller.
finalizeContext¶
void finalizeContext();
Orderly backend teardown. For GL-family backends the owning context must be current. The Canvas may be initialized again later.
abandonContext¶
void abandonContext();
Forget all GPU objects after an involuntary backend-context loss. Unlike finalizeContext(), this never attempts to delete objects from the lost context. The Canvas keeps its CPU-side state and can be initialized again when a replacement context is current.
isContextInitialized¶
bool isContextInitialized() const;
Whether backend initialization completed successfully.
releaseResources¶
void releaseResources();
Purge Canvas-owned caches and derived GPU resources while keeping the backend initialized. Later draws recreate resources on demand.
setSize¶
void setSize(int width, int height);
Resize the physical drawing surface and invalidate size-dependent caches. Pass positive physical-pixel dimensions. Hosts should also call resizeOutput() for a configured window swapchain.
getWidth¶
int getWidth() const;
Physical drawing-surface width and height in pixels.
setColor¶
void setColor(Color color);void setColor(float r, float g, float b, float a = 1.0f);
Convenience current color used by the parameterless draw* helpers.
setBlendMode¶
void setBlendMode(Paint::BlendMode blendMode);
Canvas-level blend state for subsequent draws. A non-SRC_OVER value overrides the Paint blend mode and is scoped by save()/restore().
drawColor¶
void drawColor(const Color &color);void drawColor(float r, float g, float b, float a = 1.0f);
Fill/clear the entire target with a color. Unlike drawPaint(), this intentionally ignores the current clip.
drawPaint¶
void drawPaint(const Paint &paint);
Fill the current clip with paint, respecting its shader, alpha and blend mode.
drawPoint¶
void drawPoint(int x, int y, const Paint &paint);void drawPoint(float x, float y, const Paint &paint);void drawPoint(const Point &point, const Paint &paint);void drawPoint(const PointF &point, const Paint &paint);
Draw independent points using Paint stroke color/width and the current transform/clip.
drawPoints¶
void drawPoints(const std::vector<Point> &points, const Paint &paint);void drawPoints(const std::vector<PointF> &points, const Paint &paint);
Draw every vector element as an independent point. Non-finite PointF values are skipped.
drawLine¶
void drawLine(int x1, int y1, int x2, int y2, const Paint &paint);void drawLine(float x1, float y1, float x2, float y2, const Paint &paint);void drawLine(const Point &start, const Point &end, const Paint &paint);void drawLine(const PointF &start, const PointF &end, const Paint &paint);
Draw one stroked segment. Paint style is treated as stroke semantics.
drawLines¶
void drawLines(const std::vector<Point> &points, const Paint &paint);void drawLines(const std::vector<PointF> &points, const Paint &paint);
Draw independent segments from pairs [p0,p1], [p2,p3], ...; an odd
final point is ignored.
drawPolyline¶
void drawPolyline(const std::vector<Point> &points, const Paint &paint);void drawPolyline(const std::vector<PointF> &points, const Paint &paint);
Stroke one connected open contour. Fewer than two valid points draw nothing.
drawPolygon¶
void drawPolygon(const std::vector<Point> &points, const Paint &paint);void drawPolygon(const std::vector<PointF> &points, const Paint &paint);
Draw one closed contour using Paint fill/stroke style. Fewer than three valid points draw nothing; repeating the first point is optional.
drawRect¶
void drawRect(const RectF &rect, const Paint &paint);void drawRect(const Rect &rect, const Paint &paint);
Draw (x,y,width,height); negative dimensions are normalized and a zero
dimension draws nothing.
drawRoundRect¶
void drawRoundRect(const RectF &rect, float radius, const Paint &paint);void drawRoundRect(const Rect &rect, float radius, const Paint &paint);void drawRoundRect(const RectF &rect, float topLeftRadius, float topRightRadius, float bottomRightRadius, float bottomLeftRadius, const Paint &paint);void drawRoundRect(const Rect &rect, float topLeftRadius, float topRightRadius, float bottomRightRadius, float bottomLeftRadius, const Paint &paint);
Draw a rounded rectangle. Negative radii become zero and oversized corner radii are proportionally reduced so adjacent corners fit.
drawBoxShadow¶
void drawBoxShadow(const RectF &rect, float radius, float spread, float blurRadius, float dx, float dy, const Color &color);void drawBoxShadow(const RectF &rect, float topLeftRadius, float topRightRadius, float bottomRightRadius, float bottomLeftRadius, float spread, float blurRadius, float dx, float dy, const Color &color);
Draw only an outer rounded-rectangle shadow. Spread expands the source rectangle; negative blur radii become zero.
drawCircle¶
void drawCircle(float centerX, float centerY, float radius, const Paint &paint);void drawCircle(const PointF ¢er, float radius, const Paint &paint);void drawCircle(const Point ¢er, float radius, const Paint &paint);
Draw a circle; non-positive/non-finite radii or coordinates draw nothing.
drawOval¶
void drawOval(const RectF &bounds, const Paint &paint);void drawOval(const Rect &bounds, const Paint &paint);
Draw an oval inscribed in normalized (x,y,width,height) bounds.
drawArc¶
void drawArc(const RectF &bounds, float startRadians, float sweepRadians, bool useCenter, const Paint &paint);void drawArc(const Rect &bounds, float startRadians, float sweepRadians, bool useCenter, const Paint &paint);void drawArc(const RectF &bounds, float startRadians, float sweepRadians, ArcMode mode, const Paint &paint);void drawArc(const Rect &bounds, float startRadians, float sweepRadians, ArcMode mode, const Paint &paint);
Draw an ellipse arc. Zero radians starts at the rightmost point; positive sweep follows the positive-angle direction in the Canvas' Y-down space (clockwise on screen) and is clamped to one revolution. Prefer ArcMode; the boolean overload is retained for compatibility.
drawPath¶
void drawPath(const Path &path, const Paint &paint);
Draw all Path contours using the active transform, clip and Paint style. Empty paths are ignored; input geometry is copied when command recording requires it.
measureStrokeBounds¶
RectF measureStrokeBounds(const Path &path, const Paint &paint) const;
Return local-space bounds of the actual stroke mesh, including cap, join, dash and corner effects. Map with mapRect() for device-space bounds.
drawImage¶
void drawImage(const Image &image, float x, float y, const Paint &paint);void drawImage(const Image &image, const RectF &dst, const Paint &paint);void drawImage(const Image &image, const RectF &src, const RectF &dst, const Paint &paint);void drawImage(const ITextureSource &source, float x, float y, const Paint &paint);void drawImage(const ITextureSource &source, const RectF &dst, const Paint &paint);
Draw a valid Image. The (x,y) overload uses its intrinsic pixel size;
destination rectangles scale it; source rectangles use image-pixel
coordinates. Invalid/backend-incompatible images draw nothing. Paint
color tints the image, so use Color::WHITE for original colors.
drawImageRects¶
void drawImageRects(const Image &image, const ImageRect *rects, std::size_t count, const Paint &paint);
Ordered atlas/sprite rectangles with one image, paint and canvas state. Equivalent to drawImage for each pair, including source clamping and destination normalization. Input is consumed before returning. Complex sampling/paint and Picture recording use the scalar implementation.
drawImageFit¶
void drawImageFit(const Image &image, const RectF &dst, ImageFit fit, const Paint &paint);void drawImageFit(const Image &image, const RectF &dst, ImageFit fit, ImageAnchor anchor, const Paint &paint);void drawImageFit(const Image &image, const RectF &dst, ImageFit fit, float alignX, float alignY, const Paint &paint);
Fit an image into dst; custom alignment values are clamped to [0,1].
drawImageNinePatch¶
void drawImageNinePatch(const Image &image, const RectF ¢erSrc, const RectF &dst, const Paint &paint);
Draw a nine-patch. centerSrc is the stretchable source region in image pixels.
drawImageRounded¶
void drawImageRounded(const Image &image, const RectF &dst, float radius, const Paint &paint);void drawImageRounded(const Image &image, const RectF &dst, float topLeftRadius, float topRightRadius, float bottomRightRadius, float bottomLeftRadius, const Paint &paint);
Draw an image clipped to a rounded destination rectangle.
drawImageCircle¶
void drawImageCircle(const Image &image, const PointF ¢er, float radius, const Paint &paint);
Draw an image center-cropped into a circle.
drawImageTiled¶
void drawImageTiled(const Image &image, const RectF &dst, const Paint &paint);void drawImageTiled(const Image &image, const RectF &dst, float tileWidth, float tileHeight, const Paint &paint);
Tile an image across dst; explicit tile sizes must be positive.
loadImage¶
bool loadImage(Image &image, const char *imagePath);
Decode a file into image. Returns false for a null/unreadable/unsupported
file or resource creation failure. Prefer Image::loadFromEncodedMemory
when the host owns asset I/O.
loadImageFromEncodedMemory¶
bool loadImageFromEncodedMemory(Image &image, const unsigned char *data, int size, bool generateMipmaps = true);
Decode encoded image bytes. The input is consumed before return and need not outlive the call.
loadImageFromRGBA¶
bool loadImageFromRGBA(Image &image, const unsigned char *pixels, int width, int height, bool generateMipmaps = false);bool loadImageFromRGBA(Image &image, const std::vector<unsigned char> &pixels, int width, int height, bool generateMipmaps = false);
Upload tightly packed RGBA8 bytes (width*height*4). Returns false for
invalid dimensions/size, null data, or backend resource failure.
replaceImageRGBA¶
bool replaceImageRGBA(Image &image, const unsigned char *pixels, int width, int height, bool generateMipmaps = false);bool replaceImageRGBA(Image &image, const std::vector<unsigned char> &pixels, int width, int height, bool generateMipmaps = false);
Replace the complete image snapshot; may change dimensions.
updateImageRGBA¶
bool updateImageRGBA(Image &image, const unsigned char *pixels, int x, int y, int width, int height, bool regenerateMipmaps = true);bool updateImageRGBA(Image &image, const std::vector<unsigned char> &pixels, int x, int y, int width, int height, bool regenerateMipmaps = true);
Replace a tightly packed RGBA8 sub-rectangle. The region must lie inside the existing image; mipmaps are regenerated when requested.
wrapExternalTexture¶
bool wrapExternalTexture(Image &image, std::uint32_t textureId, int width, int height, bool mipmapsGenerated = false);
Wrap a caller-owned texture from this Canvas' current GL context. No ownership transfers; keep it alive until the Image is reset/destroyed.
wrapExternalMetalTexture¶
bool wrapExternalMetalTexture(Image &image, void *texture, int width, int height, bool mipmapsGenerated = false);
Wrap an externally-owned idtexture must be a valid MTLTexture from this canvas's MTLDevice.
drawText¶
void drawText(const std::string &text, float x, float y, const Paint &paint);
Draw one normalized UTF-8 run. Invalid sequences are replaced
predictably. (x,y) uses Paint alignment/baseline; text does not wrap.
drawTextBox¶
void drawTextBox(const std::string &text, const RectF &bounds, const Paint &paint);void drawTextBox(const std::string &text, const RectF &bounds, float lineHeight, const Paint &paint);void drawTextBox(const std::string &text, const RectF &bounds, float lineHeight, int maxLines, bool ellipsize, const Paint &paint);
Draw wrapped text inside a rectangle, optionally limiting lines and ellipsizing overflow.
layoutTextBox¶
std::vector<TextLine> layoutTextBox(const std::string &text, const RectF &bounds, const Paint &paint) const;std::vector<TextLine> layoutTextBox(const std::string &text, const RectF &bounds, float lineHeight, const Paint &paint) const;std::vector<TextLine> layoutTextBox(const std::string &text, const RectF &bounds, float lineHeight, int maxLines, bool ellipsize, const Paint &paint) const;
Layout normalized UTF-8 without drawing. Returned source ranges are UTF-8 byte offsets and remain valid only for the exact input string.
drawTextOnPath¶
void drawTextOnPath(const std::string &text, const Path &path, const Paint &paint);void drawTextOnPath(const std::string &text, const Path &path, float hOffset, float vOffset, const Paint &paint);
Draw normalized UTF-8 along the Path baseline. hOffset advances along
the path and vOffset moves perpendicular to it.
measureText¶
float measureText(const std::string &text, const Paint &paint) const;
Measure using the same shaping/fallback state as drawing, without emitting draw commands. Returned values are in logical coordinates.
measureTextBounds¶
RectF measureTextBounds(const std::string &text, const Paint &paint) const;
Return logical bounds relative to the Paint-selected text origin.
measureTextMetrics¶
TextMetrics measureTextMetrics(const std::string &text, const Paint &paint) const;
Return width, font vertical metrics, line gap/height and logical bounds.
registerFontFace¶
bool registerFontFace(const FontFace &face);
Register a font face so its family can be selected via Paint::setFontFamily.
addFontProvider¶
bool addFontProvider(std::shared_ptr<FontProvider> provider);
Add an application font provider. The Canvas retains shared ownership; portable text supports lazy asset/dynamic providers.
refreshSystemFonts¶
bool refreshSystemFonts();
Re-enumerate installed fonts and update this Canvas while preserving explicitly registered fonts and fallback chains.
setFontFallbackChain¶
bool setFontFallbackChain(const FontFallbackChain &chain);
Set the fallback chain used to resolve glyphs missing from the primary font.
setTextBackend¶
bool setTextBackend(TextBackend backend, TextRenderMode renderMode = TextRenderMode::Grayscale);
Select the text backend (and, for the native backend, its render mode). Resets text state (registered fonts / fallback chains), so call it before registering fonts. Returns true if the requested backend is now active.
textBackend¶
TextBackend textBackend() const;
The text backend currently in effect.
save¶
int save();
Push the current graphics state and return the previous save count. Pass that value to restoreToCount() to balance this call, even if nested code performs additional saves.
saveLayer¶
int saveLayer(const RectF &bounds, const Paint &paint);int saveLayer(const Rect &bounds, const Paint &paint);int saveLayer(const RectF &bounds, const Paint &paint, const LayerOptions &options);int saveLayer(const Rect &bounds, const Paint &paint, const LayerOptions &options);
Begin a bounds-clipped offscreen layer composited with paint on restore.
This allocates/intermediates rendering work and is more expensive than
save(); keep bounds tight and use it only when group compositing is needed.
restore¶
void restore();
Pop the most recent state. An unmatched restore is a safe no-op.
getSaveCount¶
int getSaveCount() const;
Current state-stack depth; the base state has count 1.
restoreToCount¶
void restoreToCount(int saveCount);
Pop to saveCount; values below 1 are clamped to the base state.
getMatrix¶
Matrix4 getMatrix() const;
Current total transform matrix (local space to device space).
mapPoint¶
PointF mapPoint(const PointF &point) const;
Map local coordinates through the current matrix and DPR to physical device coordinates. A non-invertible/non-finite transform makes inverse operations return false.
mapRect¶
RectF mapRect(const RectF &rect) const;RectF mapRect(const Rect &rect) const;
Map four corners and return their physical device-space axis-aligned bounds.
inverseMapPoint¶
bool inverseMapPoint(const PointF &devicePoint, PointF &localPoint) const;
Inverse-map physical device coordinates; false leaves output unspecified when the current transform is singular or non-finite.
isPointInClip¶
bool isPointInClip(const PointF &devicePoint) const;
Clip and hit-test query points are expressed in physical device coordinates.
hitTestPathFill¶
bool hitTestPathFill(const Path &path, const PointF &devicePoint) const;
Test a physical device point against the current clip and inverse-mapped Path.
hasClip¶
bool hasClip() const;
Whether an explicit clip is active. getClipBounds() returns device-space conservative bounds and false for an empty effective clip.
quickReject¶
bool quickReject(const RectF &rect) const;bool quickReject(const Rect &rect) const;bool quickReject(const Path &path, const Paint &paint) const;
Conservative visibility test in local coordinates. False means "possibly visible", not guaranteed visible; true means drawing can be skipped.
clipPath¶
void clipPath(const Path &path);
Intersect the current clip with a transformed anti-aliased Path. Clip operations only shrink the clip and are scoped by save()/restore().
clipRect¶
void clipRect(const RectF &rect);void clipRect(const Rect &rect);
Intersect the current clip with a rectangle.
setMatrix¶
void setMatrix(const Matrix4 &matrix);
Replace the logical transform while preserving the current DPR base scale.
resetMatrix¶
void resetMatrix();
Reset to identity in logical space (the DPR base scale remains active).
setDevicePixelRatio¶
void setDevicePixelRatio(float ratio);
Set the device pixel ratio (HiDPI / content scale). Folded into the root
transform so resetMatrix() restores a ratiox base scale: draw in
logical coordinates and content — including crisp, device-resolution
text — renders at ratiox physical pixels. The canvas size is expected to
be the physical framebuffer size. Default 1.0.
Side effect (M2): this resets the CURRENT transform to a dpr-scaled base
(as if resetMatrix() were called). The ratio is stored on the current
graphics state, so it is saved/restored in lockstep with the matrix by
save()/restore() — a restore() that crosses this call restores the
matching prior ratio and matrix together.
devicePixelRatio¶
float devicePixelRatio() const;
The current device pixel ratio (default 1.0). Reflects the value on the current graphics state, so it tracks save()/restore().
concat¶
void concat(const Matrix4 &matrix);
Post-multiply the current logical matrix by another column-major transform.
translate¶
void translate(float dx, float dy);
Translate/scale/rotate the current logical transform. Rotation is in radians.
recordPicture¶
std::shared_ptr<const Picture> recordPicture(const std::function<void(Canvas &)> &recorder);
Record backend-neutral Canvas operations into an immutable Picture. Recording does not submit GPU work and leaves this Canvas' state exactly as it was before the callback. Nested recording is rejected.
drawPicture¶
void drawPicture(const Picture &picture);
Replay a retained Picture inside an implicit save/restore boundary.
drawPictureRasterized¶
void drawPictureRasterized(const Picture &picture);
Replay an isolated static Picture through a context-keyed raster cache. This is intended for RepaintBoundary-like content whose compositing as one offscreen layer is semantically correct. GPU resources are derived data and are purged before context teardown.
setRetainedPictureRasterCacheBudgetBytes¶
void setRetainedPictureRasterCacheBudgetBytes(std::size_t bytes);
Set the soft memory budget shared by rasterized Pictures on this Canvas. A zero budget disables raster caching and falls back to drawPicture().
retainedPictureRasterCacheBudgetBytes¶
std::size_t retainedPictureRasterCacheBudgetBytes() const;
Current soft raster-cache budget; zero disables retained rasterization.
beginFrame¶
void beginFrame();
Begin a frame of drawing. Initializes the backend lazily, resets per-frame state/statistics, and discards any previously queued commands. It does not clear a host-owned OpenGL framebuffer; the host controls that clear.
endFrame¶
void endFrame();
End the current frame: submit all recorded drawing to the backend and make
it readable. This is the paired counterpart of beginFrame() and is
required before reading pixels or using this Canvas as a texture source.
The offscreen flow is beginFrame -> draw -> endFrame -> readPixelsRGBA.
endFrame() submits and consumes the recorded commands. On the normal output
path, Software clears on every submission, Vulkan/Metal clear when a
draw list starts, and OpenGL does not clear implicitly. A render-target
canvas rebuilds its offscreen texture only when commands are queued. Call
endFrame() exactly once per frame, right before reading back or presenting.
shutdown¶
void shutdown();
Clear pending commands and finalize the backend. Equivalent to an orderly explicit teardown; the Canvas object remains reusable after reinitialization.
readPixelsRGBA¶
bool readPixelsRGBA(std::vector<unsigned char> &pixels) const;std::vector<unsigned char> readPixelsRGBA() const;
Read the rendered image back as top-left-origin RGBA bytes. Read tightly packed, top-left-origin RGBA8 pixels after endFrame(). Returns false and clears the output when readback is unavailable.
readPixelsRGBAAsync¶
bool readPixelsRGBAAsync(ReadPixelsCallback callback);
Submit one asynchronous readback where supported. Poll once per later frame until the callback runs; Software and Metal currently return false.
savePixelsPPM¶
bool savePixelsPPM(const std::string &path) const;
Save a binary PPM snapshot after endFrame(); returns false on read/I/O failure.
hashPixelsRGBA¶
static std::uint64_t hashPixelsRGBA(const std::vector<unsigned char> &pixels);
Stable byte hash for exact regression checks. Hardware/backend AA differences make it unsuitable as a cross-platform perceptual metric.
setOutputTarget¶
bool setOutputTarget(const OutputTarget &target);
OutputTarget describes the destination of each rendered frame:
- OutputTarget::Offscreen() for CPU readback or texture reuse;
- OutputTarget::ToWindow() for window presentation;
- OutputTarget::GLFramebuffer() / OutputTarget::VulkanImageTarget() for
embedding in a host-owned render target.
Set the target once for the Canvas's presentation mode. A window target
usually requires the host to provide a valid native surface and a current
graphics context. Returns false when the target is unsupported for this
backend/platform. Default is OutputTarget::Offscreen().
present¶
bool present();
Deliver the current frame to the output target. Call after endFrame().
For a Window target this swaps/blits to the window; for off-screen and
wrap-external targets it is a no-op returning true.
resizeOutput¶
void resizeOutput(int width, int height);
Notify a Window output target of a new physical drawable size. Also call setSize() so Canvas coordinates and backend viewport match.
isPresentable¶
bool isPresentable() const;
Whether the current backend/platform can present to a window.
vulkanInstance¶
void *vulkanInstance() const;
Borrow raw handles owned by this Vulkan Canvas. Values are null/zero for other backends and become invalid at context finalization/destruction.
metalDevice¶
void *metalDevice() const;
Borrow Objective-C Metal objects as opaque pointers. They remain owned by the Canvas and become invalid at context finalization/destruction.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Canvas(const Canvas &) = delete;Canvas &operator=(const Canvas &) = delete;int getTextureWidth() const override;int getTextureHeight() const override;bool isTextureValid() const override;bool isRenderTarget() const override;int getHeight() const;Color getColor() const;Paint::BlendMode getBlendMode() const;bool inverseMapRect(const RectF &deviceRect, RectF &localRect) const;bool hitTestPathStroke(const Path &path, const PointF &devicePoint, float strokeWidth) const;bool getClipBounds(RectF &bounds) const;void scale(float sx, float sy);void rotate(float radians);bool pollReadPixelsRGBAAsync();bool hasPendingReadPixelsRGBAAsync() const;std::uint64_t computePixelsHashRGBA() const;void *vulkanPhysicalDevice() const;void *vulkanDevice() const;void *vulkanQueue() const;unsigned int vulkanQueueFamily() const;void *metalCommandQueue() const;void *metalLastRenderedTexture() const;
wsc/CanvasStats.h¶
Opt-in detailed rendering diagnostics for Canvas.
Include this header only when reading Canvas::getRenderStats(). The common drawing API keeps the large diagnostic field set out of Canvas.h.
struct Canvas::RenderStats¶
Diagnostic snapshot for the most recently recorded/submitted frame. beginFrame() resets per-frame counters. Process/cache lifetime counters are identified explicitly in their field comments.
No public methods detected by the lightweight generator.
wsc/Color.h¶
class Color¶
Straight-alpha sRGB RGBA value used by drawing operations.
Integer channels are represented on the 0-255 scale and float accessors on the normalized 0-1 scale. Float constructors clamp; the integer constructor expects caller-provided 0-255 values and stores them verbatim.
Color¶
Color();Color(int r, int g, int b, int a = 255);Color(float r, float g, float b, float a = 1.0f);
Default-constructs opaque black.
fromFloat¶
static Color fromFloat(float r, float g, float b, float a = 1.0f);
Factory from float RGBA values in [0.0, 1.0] range.
fromHex¶
static Color fromHex(const std::string &hex);
Parse #RRGGBB or #RRGGBBAA (alpha last).
Throws: std::invalid_argument when the string length is not 7 or 9.
getR¶
int getR() const;
Channel accessors as 0-255 integers.
a¶
float a() const;
Channel accessors as normalized [0.0, 1.0] floats.
getNormalized¶
void getNormalized(float *rgba) const;
Write normalized channels in RGBA order. rgba must point to at least
four writable floats.
Additional public members¶
Straightforward accessors, value operations, and overloads:
int getG() const;int getB() const;int getA() const;float r() const;float g() const;float b() const;
wsc/Font.h¶
Enums:
- FontSlant
Slant style of a font face.
- FontSourceType
Whether a font face is backed by a file path or an in-memory buffer.
struct FontDescriptor¶
Identifies a desired font by UTF-8 family name, weight and slant. Weight follows the CSS/OpenType 1-1000 scale (400 normal, 700 bold).
Additional public members¶
Straightforward accessors, value operations, and overloads:
FontDescriptor() = default;explicit FontDescriptor(std::string familyName);FontDescriptor(std::string familyName, int fontWeight, FontSlant fontSlant = FontSlant::NORMAL);
struct FontCodepointRange¶
An inclusive range of Unicode code points, used to scope a font face.
Additional public members¶
Straightforward accessors, value operations, and overloads:
FontCodepointRange() = default;FontCodepointRange(std::uint32_t firstCodepoint, std::uint32_t lastCodepoint);bool contains(std::uint32_t codepoint) const;
struct FontVariationCoordinate¶
A user-space coordinate for one OpenType variable-font axis. The tag must contain exactly four bytes (for example, "wght" or "wdth").
No public methods detected by the lightweight generator.
class FontFace¶
Copyable description of one concrete font face registered on a Canvas.
Factory functions do not parse the font immediately. Canvas registration or provider matching validates/opens the selected face. Memory factories retain immutable bytes; file-backed faces require the path to remain readable when the Canvas first materializes the face.
fromFile¶
static FontFace fromFile(FontDescriptor descriptor, std::string path, int faceIndex = 0);
Describe a face from a font file (optionally a TTC/OTC face index).
fromMemory¶
static FontFace fromMemory(FontDescriptor descriptor, std::vector<std::uint8_t> bytes, int faceIndex = 0);
Take ownership of an immutable font-file byte snapshot.
fromSharedMemory¶
static FontFace fromSharedMemory(FontDescriptor descriptor, std::shared_ptr<const std::vector<std::uint8_t>> bytes, int faceIndex = 0, std::string sourceId = std::string());
Retain an immutable byte snapshot supplied by a platform/provider. sourceId is diagnostic identity only; rendering never reopens it. This lets a provider materialize an Android system font while its AFont handle/path is valid and keep using it after that platform handle closes.
sourceId¶
const std::string &sourceId() const;
Provider-owned logical origin for memory-backed data. It may be a platform identifier and is not required to be an openable file path.
setVariationCoordinate¶
bool setVariationCoordinate(std::string tag, float value);
Set one four-byte OpenType variation axis; returns false for an invalid tag or non-finite value.
addCodepointRange¶
void addCodepointRange(std::uint32_t firstCodepoint, std::uint32_t lastCodepoint);
Add provider-supplied inclusive coverage metadata. This is a resolution hint, not a replacement for inspecting the font cmap.
isValid¶
bool isValid() const;
Structural descriptor validity only; it does not guarantee decodable font data.
Additional public members¶
Straightforward accessors, value operations, and overloads:
const FontDescriptor &descriptor() const;const std::string &family() const;int weight() const;FontSlant slant() const;FontSourceType sourceType() const;int faceIndex() const;const std::string &path() const;const std::vector<std::uint8_t> *bytes() const;const std::shared_ptr<const std::vector<std::uint8_t>> &sharedBytes() const;const std::vector<FontVariationCoordinate> &variationCoordinates() const;const std::vector<FontCodepointRange> &codepointRanges() const;bool hasCodepointRanges() const;bool supportsCodepoint(std::uint32_t codepoint) const;
class FontFallbackChain¶
Ordered family fallback policy for one primary family. Family comparisons use canonical ASCII case/whitespace matching while display spelling is kept.
addFallbackFamily¶
void addFallbackFamily(std::string family);
Append one non-empty family unless its canonical name is already present.
familiesInResolutionOrder¶
std::vector<std::string> familiesInResolutionOrder() const;
Return primary first followed by explicit fallbacks.
Additional public members¶
Straightforward accessors, value operations, and overloads:
FontFallbackChain() = default;explicit FontFallbackChain(std::string primaryFamily);const std::string &primaryFamily() const;void setPrimaryFamily(std::string family);bool contains(const std::string &family) const;void clearFallbacks();const std::vector<std::string> &fallbackFamilies() const;
wsc/FontSystem.h¶
Opt-in font registration and installed-font discovery APIs.
Basic text drawing only needs Font.h. Include this header when an application owns a FontManager or directly controls the process-wide installed-font cache.
class FontManager¶
Owning collection of file/memory FontFace values with style matching.
Registration copies/owns all descriptors and bytes. Face pointers returned by lookup remain stable across additional registrations but are invalidated by clear(), assignment or destruction. This container is not thread-safe.
registerFontFile¶
bool registerFontFile(const FontDescriptor &descriptor, const std::string &path, int faceIndex = 0);
Register a structurally valid descriptor. File readability/font parsing is deferred to the rendering backend.
registerFace¶
bool registerFace(FontFace face);
Store a structurally valid face; returns false without mutation otherwise.
findFirstFace¶
const FontFace *findFirstFace(const std::string &family) const;
Return a borrowed stable face pointer, or nullptr when the family is unknown.
findFacesInMatchOrder¶
std::vector<const FontFace *> findFacesInMatchOrder(const std::string &family, int weight = 400, FontSlant slant = FontSlant::NORMAL) const;
Return every face in CSS-compatible style preference order. This keeps coverage checks separate from style selection: a resolver may reject the first face when it does not cover the requested character cluster.
addFallbackFamily¶
bool addFallbackFamily(const std::string &primaryFamily, const std::string &fallbackFamily);
Append a fallback only when both families are already registered.
Additional public members¶
Straightforward accessors, value operations, and overloads:
FontManager() = default;FontManager(const FontManager &other);FontManager(FontManager &&) noexcept = default;FontManager &operator=(const FontManager &other);FontManager &operator=(FontManager &&) noexcept = default;bool registerFontMemory(const FontDescriptor &descriptor, std::vector<std::uint8_t> bytes, int faceIndex = 0);bool hasFamily(const std::string &family) const;std::vector<const FontFace *> findFaces(const std::string &family) const;const FontFace *findBestFace(const std::string &family, int weight = 400, FontSlant slant = FontSlant::NORMAL) const;const FontFallbackChain *fallbackChain(const std::string &family) const;std::vector<std::string> resolveFamilies(const std::string &preferredFamily) const;const std::vector<FontFace> &faces() const;std::uint64_t generation() const;void clear();
class FontSystem¶
Process-wide native installed-font discovery and portable fallback aliases. Applications normally use Canvas::refreshSystemFonts() rather than calling the cache controls directly.
defaultSystemFontFaces¶
static std::vector<FontFace> defaultSystemFontFaces();
Build the portable fallback aliases from fonts reported by the native platform font manager's current cached snapshot. No operating-system font paths are assumed.
refreshDefaultSystemFontFaces¶
static void refreshDefaultSystemFontFaces();
Discard both the discovery and the default-slot process-wide caches so the next discoverInstalledFontFaces() / defaultSystemFontFaces() call re-runs platform enumeration. Cheap to call; useful after the host installs a new font at runtime.
refreshDiscoveredFontFaces¶
static void refreshDiscoveredFontFaces();
Discard only the discoverInstalledFontFaces() cache. defaultSystemFontFaces() keeps its own cached slot table until refreshDefaultSystemFontFaces() is called. Prefer this entry point when the caller only consumes the discovery output directly (e.g. a font picker) and wants to avoid rebuilding the WhatsCanvas fallback slot table.
refreshDefaultSystemFontFacesOnly¶
static void refreshDefaultSystemFontFacesOnly();
Discard only the defaultSystemFontFaces() cache. The next call rebuilds the slot table from the cached discovery output; call refreshDiscoveredFontFaces() first if the underlying installed font set has actually changed.
refreshInstalledFonts¶
static std::uint64_t refreshInstalledFonts();
Re-enumerate installed fonts, publish a new process-wide snapshot, and invalidate the default-slot cache. Returns the monotonically increasing discovery generation. This is the preferred high-level refresh API.
installedFontGeneration¶
static std::uint64_t installedFontGeneration();
Generation of the current discovery snapshot, or zero before the first discovery/default lookup or explicit refresh is requested.
discoverInstalledFontFaces¶
static std::vector<FontFace> discoverInstalledFontFaces();
Query the platform's native font manager (CoreText on macOS, DirectWrite on Windows, fontconfig on Linux) for every installed font face. Each returned FontFace is registered under its real system family name (e.g. "Menlo", "Consolas", "PingFang SC"), weight, and file path. Returns an empty vector when the platform API is unavailable or not linked in.
Additional public members¶
Straightforward accessors, value operations, and overloads:
static bool fileExists(const std::string &path);static FontFallbackChain defaultFallbackChain(const std::string &primaryFamily = kDefaultPrimaryFamily);
wsc/FontResolver.h¶
Enums:
- FontProviderKind
Font source layers are queried in this order for the same family. Explicit fallback families are considered only after all providers have had a chance to satisfy the requested family.
- RemoteFontState
Lifecycle of a remotely supplied font source. The provider never performs network I/O itself; a Web/native host drains queued requests and reports the result back on its event loop.
struct FontMatchRequest¶
One style/coverage lookup. codepoints are Unicode scalar values used to
choose a face that can cover the whole requested cluster/run.
No public methods detected by the lightweight generator.
struct FontMatchResult¶
Resolution result and diagnostics. The face pointer is borrowed from the provider and must be invalidated when the resolver generation changes.
Additional public members¶
Straightforward accessors, value operations, and overloads:
explicit operator bool() const;
class FontProvider¶
Abstract source of font metadata and faces. Providers are owned through shared_ptr by FontResolver/Canvas and are called synchronously on the rendering thread unless a concrete provider documents host-driven I/O.
generationForFamily¶
virtual std::uint64_t generationForFamily(const std::string &) const;
Family-scoped generation for resolution caches. Providers without targeted invalidation may return their global generation.
refresh¶
virtual void refresh();
Invalidate provider-owned discovery and resolution caches after the host reports a system-font change. Static asset providers may no-op.
families¶
virtual std::vector<std::string> families() const;
Families known from provider metadata. Platform providers that only support open-ended character matching may return an empty list.
displayFamilyName¶
virtual std::string displayFamilyName(const std::string &family) const;
Return a stable display spelling without forcing a lazy source load.
match¶
virtual std::vector<const FontFace *> match(const FontMatchRequest &request) const = 0;
Return candidates in provider-specific style preference order. Platform providers may use request.locale/codepoints; file providers normally defer definitive glyph coverage to FontResolver's coverage predicate.
Additional public members¶
Straightforward accessors, value operations, and overloads:
virtual ~FontProvider() = default;virtual FontProviderKind kind() const = 0;virtual const std::string &name() const = 0;virtual std::uint64_t generation() const = 0;virtual bool hasFamily(const std::string &family) const = 0;
class FontManagerProvider¶
Adapts the existing file/memory FontManager to the provider contract.
Additional public members¶
Straightforward accessors, value operations, and overloads:
FontManagerProvider(std::shared_ptr<FontManager> manager, FontProviderKind providerKind, std::string providerName);FontProviderKind kind() const override;const std::string &name() const override;std::uint64_t generation() const override;bool hasFamily(const std::string &family) const override;std::string displayFamilyName(const std::string &family) const override;std::vector<std::string> families() const override;std::vector<const FontFace *> match(const FontMatchRequest &request) const override;
struct LazyFontSource¶
Metadata for an application font whose bytes are supplied on first match. sourceId is an application-owned stable key (asset path, bundle key, URL, or content identifier); it is passed to LazyFontProvider::Loader.
No public methods detected by the lightweight generator.
class LazyFontProvider¶
Provider for asset/dynamic/test fonts that defers byte loading until the source family is first matched. Failed loads are memoized until the family is explicitly invalidated or its source registration is replaced.
registerSource¶
bool registerSource(LazyFontSource source);
Add or replace one source identified by (family, sourceId). Registration validates metadata but does not invoke Loader.
invalidateFamily¶
bool invalidateFamily(const std::string &family);
Forget loaded/failed state for one family so its sources can be retried.
removeFamily¶
bool removeFamily(const std::string &family);
Remove every source in one family. Previously returned pointers become invalid and callers must observe the changed generation.
Additional public members¶
Straightforward accessors, value operations, and overloads:
LazyFontProvider(FontProviderKind providerKind, std::string providerName, Loader loader);LazyFontProvider(const LazyFontProvider &) = delete;~LazyFontProvider() override;LazyFontProvider &operator=(const LazyFontProvider &) = delete;FontProviderKind kind() const override;const std::string &name() const override;std::uint64_t generation() const override;std::uint64_t generationForFamily(const std::string &family) const override;void refresh() override;bool hasFamily(const std::string &family) const override;std::vector<std::string> families() const override;std::string displayFamilyName(const std::string &family) const override;std::vector<const FontFace *> match(const FontMatchRequest &request) const override;std::size_t sourceCount() const;std::size_t loadedFaceCount() const;
struct RemoteFontSource¶
No public methods detected by the lightweight generator.
struct RemoteFontRequest¶
No public methods detected by the lightweight generator.
struct RemoteFontProviderOptions¶
No public methods detected by the lightweight generator.
class RemoteFontProvider¶
Host-driven asynchronous provider for Web fallback subsets, cloud fonts, or any source that cannot synchronously return bytes from FontProvider::match.
registerSource¶
bool registerSource(RemoteFontSource source);
sourceId must be unique within this provider. Re-registering it replaces metadata and invalidates any loaded/failed instance.
takeDownloadRequests¶
std::vector<RemoteFontRequest> takeDownloadRequests();
Move queued sources to DOWNLOADING, respecting maxConcurrentDownloads. The host starts these requests and later calls completeDownload or failDownload on the same source id.
takeChangedFamilies¶
std::vector<std::string> takeChangedFamilies();
Drain family changes accumulated since the previous call. Results are deduplicated and sorted so the host can schedule one safe-frame relayout/repaint instead of re-entering layout from download callbacks.
failDownload¶
bool failDownload(const std::string &sourceId, std::uint64_t requestToken, bool permanent, std::size_t consumedBytes = 0);
consumedBytes counts transfer budget already spent by the failed try. Non-permanent failures return to IDLE until maxAttemptsPerSource.
Additional public members¶
Straightforward accessors, value operations, and overloads:
RemoteFontProvider(FontProviderKind providerKind, std::string providerName, RemoteFontProviderOptions options = {});RemoteFontProvider(const RemoteFontProvider &) = delete;~RemoteFontProvider() override;RemoteFontProvider &operator=(const RemoteFontProvider &) = delete;FontProviderKind kind() const override;const std::string &name() const override;std::uint64_t generation() const override;std::uint64_t generationForFamily(const std::string &family) const override;void refresh() override;bool hasFamily(const std::string &family) const override;std::vector<std::string> families() const override;std::string displayFamilyName(const std::string &family) const override;std::vector<const FontFace *> match(const FontMatchRequest &request) const override;bool removeFamily(const std::string &family);bool invalidateFamily(const std::string &family);bool completeDownload(const std::string &sourceId, std::uint64_t requestToken, std::vector<std::uint8_t> bytes);RemoteFontState state(const std::string &sourceId) const;std::size_t queuedCount() const;std::size_t downloadingCount() const;std::size_t downloadedBytes() const;
class FontResolver¶
Ordered provider and fallback coordinator used by Canvas text layout.
Provider priority is Dynamic -> Asset -> Test -> System. Resolver mutation and resolution are not a concurrent API; configure/use it on the owning Canvas rendering thread. Cache clients must include generation() or resolutionGeneration() in their keys.
addProvider¶
void addProvider(std::shared_ptr<FontProvider> provider);
Retain and insert a provider according to FontProviderKind priority.
setFallbackChain¶
bool setFallbackChain(const FontFallbackChain &chain);
Replace the fallback chain for its primary family. Known families are retained even if another entry is unavailable, and false reports that the caller supplied at least one unknown family.
generation¶
std::uint64_t generation() const;
Changes whenever provider membership, fallback policy, or a provider's own generation changes. Suitable for resolution/layout cache keys.
resolutionGeneration¶
std::uint64_t resolutionGeneration(const std::string &preferredFamily) const;
Generation scoped to the requested family and its explicit fallback chain. Lazy provider changes in unrelated families do not affect it.
Additional public members¶
Straightforward accessors, value operations, and overloads:
bool hasFamily(const std::string &family) const;void refreshProviders(FontProviderKind kind);std::vector<std::string> resolveFamilies(const std::string &preferredFamily) const;
wsc/Image.h¶
class Image¶
Move-only image resource created for one Canvas backend/device.
Upload/decode calls copy their input before returning. A successfully loaded Image may be drawn repeatedly by its owning Canvas; using it with an unrelated backend/device is unsupported and draws nothing. Destroy Images before orderly Canvas/context teardown when practical. External texture wrappers retain no ownership unless explicitly stated by that overload.
Minimal usage:
auto canvas = wsc::Canvas::create(wsc::Canvas::Backend::Software, 256, 256);
if (!canvas) return;
std::vector<unsigned char> rgba(256 * 256 * 4, 255);
wsc::Image image;
if (!image.loadFromRGBA(*canvas, rgba, 256, 256)) return;
canvas->beginFrame();
canvas->drawImage(image, 0.0f, 0.0f, 256.0f, 256.0f, wsc::Paint());
canvas->endFrame();
Ownership and reuse rules:
- Image is bound to a specific Canvas backend/device; reusing it with a
different Canvas or a different GL/Metal/Vulkan device is unsupported.
- Image instances are not thread-safe and should be used on the same render
thread as their owning Canvas.
- External texture wrappers only borrow the supplied handle; the caller must
keep that native resource alive for as long as the wrapper is used.
getWidth¶
int getWidth() const;
Pixel dimensions of the current resource, or zero before a successful load.
loadFromEncodedMemory¶
bool loadFromEncodedMemory(Canvas &canvas, const unsigned char *data, int size, bool generateMipmaps = true);
Decode an in-memory PNG/JPEG/etc. snapshot. Returns false for null/empty or unsupported data and for backend allocation/upload failure.
loadFromRGBA¶
bool loadFromRGBA(Canvas &canvas, const unsigned char *pixels, int width, int height, bool generateMipmaps = false);bool loadFromRGBA(Canvas &canvas, const std::vector<unsigned char> &pixels, int width, int height, bool generateMipmaps = false);
Upload tightly packed straight-alpha RGBA8 pixels (width*height*4
bytes). The dimensions must be positive.
replacePixelsRGBA¶
bool replacePixelsRGBA(Canvas &canvas, const unsigned char *pixels, int width, int height, bool generateMipmaps = false);bool replacePixelsRGBA(Canvas &canvas, const std::vector<unsigned char> &pixels, int width, int height, bool generateMipmaps = false);
Replace the entire image snapshot with RGBA8 pixels (may resize). Failure leaves the caller responsible for checking isTextureValid() before use.
updatePixelsRGBA¶
bool updatePixelsRGBA(Canvas &canvas, const unsigned char *pixels, int x, int y, int width, int height, bool regenerateMipmaps = true);bool updatePixelsRGBA(Canvas &canvas, const std::vector<unsigned char> &pixels, int x, int y, int width, int height, bool regenerateMipmaps = true);
Update an in-bounds sub-rectangle with tightly packed RGBA8 pixels.
wrapExternalTexture¶
bool wrapExternalTexture(Canvas &canvas, std::uint32_t textureId, int width, int height, bool mipmapsGenerated = false);
Wrap a non-zero externally owned GL texture from the Canvas' current context. No ownership transfers; the caller keeps it alive and deletes it.
wrapExternalMetalTexture¶
bool wrapExternalMetalTexture(Canvas &canvas, void *texture, int width, int height, bool mipmapsGenerated = false);
Wrap an externally-owned id
Additional public members¶
Straightforward accessors, value operations, and overloads:
Image();Image(const Image &) = delete;Image(Image &&other) noexcept;~Image() override;Image &operator=(const Image &) = delete;Image &operator=(Image &&other) noexcept;int getHeight() const;bool hasMipmaps() const;int getTextureWidth() const override;int getTextureHeight() const override;bool isTextureValid() const override;bool isRenderTarget() const override;
wsc/ImageFilter.h¶
class ImageFilter¶
A pixel filter applied to a saved layer or to the content behind it.
Blur and inner shadow are represented as a backend-neutral value, keeping GPU objects out of the Canvas API. Values are cheap to copy and are snapped by saveLayer(). Invalid/zero filters are ignored.
blur¶
static ImageFilter blur(float radiusX, float radiusY, TileMode tileMode = TileMode::Clamp);static ImageFilter blur(float radius, TileMode tileMode = TileMode::Clamp);
Create a Gaussian blur whose radii are measured in filter-target pixels. Values are clamped to kMaxBlurRadius for backend parity.
blurSigma¶
static ImageFilter blurSigma(float sigmaX, float sigmaY, TileMode tileMode = TileMode::Clamp);static ImageFilter blurSigma(float sigma, TileMode tileMode = TileMode::Clamp);
Create a Gaussian blur using the standard-deviation convention common to graphics APIs. The sampled reach is three sigma.
innerShadow¶
static ImageFilter innerShadow(float radiusX, float radiusY, float offsetX, float offsetY, const Color &color);static ImageFilter innerShadow(float radius, float offsetX, float offsetY, const Color &color);
Create an inset shadow from the filtered layer's alpha. The source pixels and alpha are preserved; the shadow is composited only inside the source silhouette. Offsets follow inset-shadow convention: positive X shades the left edge and positive Y shades the top edge.
frostedGlass¶
static ImageFilter frostedGlass(float blurSigma, float saturation = 1.18f, float brightness = 1.04f, float contrast = 1.02f, float grain = 0.012f, TileMode tileMode = TileMode::Clamp);
Create a practical frosted-glass backdrop filter. Color adjustment is applied after the blur, leaving layer content drawn above it untouched.
setColorAdjustment¶
ImageFilter &setColorAdjustment(float saturation, float brightness = 1.0f, float contrast = 1.0f);
Configure post-blur color adjustment. Saturation 0 produces grayscale; 1 leaves the channel unchanged. Brightness and contrast use 1 as neutral. This blur-only modifier is ignored by other filter types.
setGrain¶
ImageFilter &setGrain(float amount);
Add stable monochrome grain after a blur. Small values around 0.005-0.02 reduce visible banding. This is ignored by other filter types.
type¶
Type type() const;
Query normalized/clamped filter properties.
samplingOutset¶
float samplingOutset() const;
Conservative source sampling expansion required by this filter.
outputOutset¶
float outputOutset() const;
Expansion of the visible filtered result beyond the original layer. Inner shadows remain clipped inside the source silhouette.
Additional public members¶
Straightforward accessors, value operations, and overloads:
ImageFilter() = default;static ImageFilter innerShadowSigma(float sigmaX, float sigmaY, float offsetX, float offsetY, const Color &color);static ImageFilter innerShadowSigma(float sigma, float offsetX, float offsetY, const Color &color);bool isValid() const;float radiusX() const;float radiusY() const;float offsetX() const;float offsetY() const;Color shadowColor() const;TileMode tileMode() const;float saturation() const;float brightness() const;float contrast() const;float grain() const;bool hasColorAdjustment() const;bool hasGrain() const;
class ImageFilterChain¶
An ordered, bounded image-filter pipeline.
Blur and inner shadow retain the compact ImageFilter value ABI. Generic color-matrix and offset nodes live in this explicit chain so their larger payloads do not add pointers or ownership to every ImageFilter value. A chain stores at most kMaxNodes; invalid nodes and overflow appends are ignored and leave the chain unchanged.
append¶
ImageFilterChain &append(const ImageFilter &filter);
Append one valid filter when capacity remains; otherwise no-op.
appendColorMatrix¶
ImageFilterChain &appendColorMatrix(const std::array<float, 20> &matrix);
Append a row-major 4x5 RGBA matrix. The fifth element of every row is an additive normalized-channel offset.
appendOffset¶
ImageFilterChain &appendOffset(float dx, float dy);
Translate the filtered image. Pixels exposed outside the source bounds are transparent (Decal semantics).
operator[]¶
const Node &operator[](std::size_t index) const;
Borrow a node. index must be less than size().
Additional public members¶
Straightforward accessors, value operations, and overloads:
ImageFilterChain() = default;explicit ImageFilterChain(const ImageFilter &filter);std::size_t size() const;bool empty() const;bool isValid() const;float samplingOutset() const;float outputOutset() const;
class LayerOptions¶
Optional effects attached to a saveLayer operation.
imageFilter processes the layer's own content. backdropFilter processes
the pixels already drawn behind the layer before the layer content is added.
Filters run in the order stored by ImageFilterChain and are evaluated only
when the corresponding saveLayer is restored.
setImageFilter¶
LayerOptions &setImageFilter(const ImageFilter &filter);LayerOptions &setImageFilter(const ImageFilterChain &filters);
Replace the layer-content filter/chain. Later calls replace earlier ones.
setBackdropFilter¶
LayerOptions &setBackdropFilter(const ImageFilter &filter);LayerOptions &setBackdropFilter(const ImageFilterChain &filters);
Replace the backdrop filter/chain. A backdrop observes only pixels recorded before the matching saveLayer().
Additional public members¶
Straightforward accessors, value operations, and overloads:
const ImageFilter &imageFilter() const;const ImageFilter &backdropFilter() const;const ImageFilterChain &imageFilterChain() const;const ImageFilterChain &backdropFilterChain() const;bool hasImageFilter() const;bool hasBackdropFilter() const;
wsc/Log.h¶
Enums:
- LogLevel
Severity levels for diagnostic messages, ordered from most to least verbose.
struct LogMessage¶
A single diagnostic record delivered to the active log handler.
No public methods detected by the lightweight generator.
class Log¶
Central diagnostics/logging facility for WhatsCanvas. Thread-safe.
By default only Warning and Error messages are emitted, and they are
written to stderr. Applications can lower the threshold with setLevel
(e.g. to LogLevel::Debug) to investigate rendering problems, or route
every message into their own logging system with setHandler.
setLevel¶
static void setLevel(LogLevel level);
Set the minimum severity that is emitted. Messages below this level are
dropped cheaply before the handler runs. Use LogLevel::Off to silence
all output.
level¶
static LogLevel level();
Current minimum severity threshold.
isEnabled¶
static bool isEnabled(LogLevel level);
Whether a message at level would currently be emitted.
setHandler¶
static void setHandler(LogHandler handler);
Install a custom sink. Pass nullptr to restore the default handler,
which writes formatted messages to stderr.
write¶
static void write(LogLevel level, const char *category, std::string message);
Emit a diagnostic message. Filtered against the current level first, so
callers may pass an already-built string; for hot paths prefer guarding
with isEnabled.
levelName¶
static const char *levelName(LogLevel level);
Human-readable name of a level, e.g. "ERROR". Never null.
wsc/Matrix.h¶
class Matrix4¶
Column-major 4x4 transform matrix used by Canvas::setMatrix/concat.
The default constructor and identity() produce identity. Storage index is
column * 4 + row, matching OpenGL/GLM conventions. Canvas treats values as
logical transforms and preserves its device-pixel-ratio base separately.
Matrix4¶
Matrix4();explicit Matrix4(const std::array<float, 16> &values);explicit Matrix4(const float *columnMajorValues);
Construct identity.
at¶
float at(std::size_t column, std::size_t row) const;
Read/write one cell. Out-of-range reads return 0 and writes are ignored.
Additional public members¶
Straightforward accessors, value operations, and overloads:
static Matrix4 identity();const std::array<float, 16> &values() const;const float *data() const;float *data();void set(std::size_t column, std::size_t row, float value);
wsc/Paint.h¶
class Paint¶
Copyable drawing-state value for geometry, text, images and layer compositing.
Canvas snapshots the Paint values needed by a recorded draw, so a Paint may be changed or destroyed immediately after the call. Unless a method says otherwise, dimensions are logical Canvas units. Defaults are anti-aliasing on, opaque black fill/stroke, FILL style, 1-unit stroke, 16-unit text, SRC_OVER blending and linear image sampling.
Minimal setup:
wsc::Paint fillPaint;
fillPaint.setColor(wsc::Color(40, 120, 240));
fillPaint.setStyle(wsc::Paint::Style::FILL);
wsc::Paint strokePaint;
strokePaint.setColor(wsc::Color::BLACK);
strokePaint.setStyle(wsc::Paint::Style::STROKE);
strokePaint.setStrokeWidth(2.0f);
Typical usage patterns:
- Solid color: setColor() / setAlpha() / setFillColor()
- Stroke: setStyle(Paint::Style::STROKE), setStrokeWidth(), setStrokeCap()
- Gradient: setLinearGradient() or setRadialGradient()
- Text: set setTextSize(), setTextAlign(), setTextBaseline() and then
draw text with a Canvas method
- Layer blending: adjust setBlendMode() and image tinting through
setColor() / setFillColor() when needed
Paint¶
Paint();Paint(const Paint &other);Paint(Paint &&other) noexcept;
Construct the documented default state. Paint is cheap to copy and move.
setAntiAlias¶
void setAntiAlias(bool aa);
Enable or disable geometry edge anti-aliasing. Text backends may apply their own rasterization mode.
setColor¶
void setColor(const Color &color);void setColor(int r, int g, int b, int a = 255);void setColor(float r, float g, float b, float a = 1.0f);
Set both fill and stroke color and clear any gradient shader. This color also tints images; use Color::WHITE to draw an image untinted.
setFillColor¶
void setFillColor(const Color &color);
Set only the fill/image-tint color and clear any gradient shader.
setAlpha¶
void setAlpha(int alpha);void setAlpha(float alpha);
Overall opacity multiplier (0-255 / 0.0-1.0) applied on top of the color.
setLinearGradient¶
void setLinearGradient(float startX, float startY, float endX, float endY, const Color &startColor, const Color &endColor);void setLinearGradient(float startX, float startY, float endX, float endY, const std::vector<ColorStop> &stops);
Configure a linear gradient in local coordinates. Stop positions are clamped to [0,1], non-finite stops are removed and the remainder sorted. Replaces the current solid/gradient shader.
setRadialGradient¶
void setRadialGradient(float centerX, float centerY, float radius, const Color &startColor, const Color &endColor);void setRadialGradient(float centerX, float centerY, float radius, const std::vector<ColorStop> &stops);
Configure a radial gradient in local coordinates. Radius should be positive; stop normalization matches setLinearGradient().
clearShader¶
void clearShader();
Remove any gradient and return to solid-color fill.
setShaderTileMode¶
void setShaderTileMode(ShaderTileMode tileMode);
Control sampling outside the normalized gradient range.
setShadowLayer¶
void setShadowLayer(float radius, float dx, float dy, const Color &color);
Attach a drop shadow beneath supported geometry/text. Radius is blur
reach and (dx,dy) is the local offset. Non-positive/transparent values
effectively disable visible output; call clearShadowLayer() to reset.
setStrokeWidth¶
void setStrokeWidth(float width);
Centered stroke width in logical units; used when Style includes STROKE. Callers should provide a finite non-negative value.
setStrokeMiterLimit¶
void setStrokeMiterLimit(float limit);
Set the miter length/stroke-width limit; clamped to at least 1.
setTextSize¶
void setTextSize(float size);
Text size in logical units for drawText/drawTextBox. Must be positive.
setTextMaskBlur¶
void setTextMaskBlur(float radius);
Blur each glyph's coverage mask before compositing text. Radius is in logical text units, scaled with text, independent of color and opacity. Zero disables it. Portable alpha glyphs cache the result; unsupported/color glyphs and large radii fall back to a filtered layer. Overlapping glyphs may differ from blurring the already-composited run.
setFontFamily¶
void setFontFamily(const std::string &family);
Preferred UTF-8 font family. Resolution uses registered/provider/system faces and the Canvas fallback chain; an empty family selects defaults.
setFontWeight¶
void setFontWeight(int weight);
CSS/OpenType-style weight, clamped to [1,1000] (400 normal, 700 bold).
setFontVariation¶
void setFontVariation(const std::string &tag, float value);
Set or replace a whole-run OpenType variable-font axis override.
Tags must contain exactly four bytes (for example wght, wdth, or
opsz) and values must be finite. Paint overrides take precedence over
coordinates carried by the resolved FontFace.
clearFontVariations¶
void clearFontVariations();
Remove all Paint-level variable-font overrides.
setLetterSpacing¶
void setLetterSpacing(float spacing);
Additional advance in logical units between shaped clusters. Non-finite input resets to zero.
setTextAlign¶
void setTextAlign(TextAlign align);
Set horizontal and vertical anchoring of the (x,y) text draw position.
setTextLocale¶
void setTextLocale(const std::string &locale);
BCP-47 locale (e.g. "en-US", "ja-JP") for locale-aware shaping and fallback. Honoured by portable HarfBuzz and native DirectWrite paths; empty by default.
setFontFeature¶
void setFontFeature(const std::string &tag, std::uint32_t value = 1);
Set or update a whole-run OpenType feature override.
There is no tag whitelist: any case-sensitive tag of exactly four bytes
is forwarded to portable HarfBuzz shaping and native DirectWrite. An
unsupported tag is normally ignored by the font/shaper, while tags of
any other length are silently ignored here. Repeating a tag replaces its
previous value. value == 0 disables a feature, value == 1 normally
enables it, and other values are passed through for feature-specific
alternate selection. The dependency-free simple shaper does not apply
OpenType feature overrides.
clearFontFeatures¶
void clearFontFeatures();
Remove every explicit feature override and restore font/shaper defaults. This differs from retaining a tag with value 0, which explicitly disables that feature.
getFontFeatures¶
const std::vector<FontFeature> &getFontFeatures() const;
Return the active whole-run overrides, with at most one entry per tag.
setUnderline¶
void setUnderline(bool enabled);
Text decorations. Honoured by the native (DirectWrite) backend; off by default.
setTextRenderMode¶
void setTextRenderMode(TextRenderMode mode);
Per-Paint text render mode override. Default = inherit backend setting.
setBlendMode¶
void setBlendMode(BlendMode blendMode);
Compositing blend mode for subsequent draws.
setImageSampling¶
void setImageSampling(ImageSampling sampling);
Set image minification/magnification sampling. MIPMAP_LINEAR falls back when the source has no mipmaps.
setCornerPathEffect¶
void setCornerPathEffect(float radius);
Round Path corners by a non-negative local radius before fill/stroke. Non-finite or negative input disables the effect.
setDashPathEffect¶
void setDashPathEffect(const std::vector<float> &intervals, float phase = 0.0f);
Dash a stroke using alternating positive on/off interval lengths. Invalid entries are removed; an odd valid list is duplicated to become even. Empty output disables dashing. Phase is in local units.
setColorMatrix¶
void setColorMatrix(const std::array<float, 20> &matrix);
Apply a row-major 4x5 straight-RGBA color matrix. The fifth value in each row is an additive normalized-channel offset. Any non-finite element clears the filter.
setStrokeColor¶
void setStrokeColor(const Color &color);void setStrokeColor(int r, int g, int b, int a = 255);void setStrokeColor(float r, float g, float b, float a = 1.0f);
Set only the stroke color; does not change fill color or shader.
setStyle¶
void setStyle(Style style);
Select fill/stroke evaluation for geometry and Path operations.
setStrokeCap¶
void setStrokeCap(StrokeCap cap);
Configure cap/join geometry for stroked paths and lines.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Paint &operator=(const Paint &other);Paint &operator=(Paint &&other) noexcept;~Paint();bool isAntiAlias() const;int getAlpha() const;float getAlphaF() const;Color getFillColor() const;ShaderType getShaderType() const;ShaderTileMode getShaderTileMode() const;bool hasLinearGradient() const;bool hasRadialGradient() const;float getGradientStartX() const;float getGradientStartY() const;float getGradientEndX() const;float getGradientEndY() const;Color getGradientStartColor() const;Color getGradientEndColor() const;const std::vector<ColorStop> &getGradientStops() const;float getRadialCenterX() const;float getRadialCenterY() const;float getRadialRadius() const;Color getRadialStartColor() const;Color getRadialEndColor() const;void clearShadowLayer();bool hasShadowLayer() const;float getShadowRadius() const;float getShadowDx() const;float getShadowDy() const;Color getShadowColor() const;Color getColor() const;float getStrokeWidth() const;float getStrokeMiterLimit() const;float getTextSize() const;float getTextMaskBlur() const;void setFont(const std::string &family);const std::string &getFontFamily() const;const std::string &getFont() const;bool hasFontFamily() const;void clearFontFamily();void clearFont();int getFontWeight() const;void setFontSlant(FontSlant slant);FontSlant getFontSlant() const;const std::vector<FontVariationCoordinate> &getFontVariations() const;float getLetterSpacing() const;TextAlign getTextAlign() const;void setTextBaseline(TextBaseline baseline);TextBaseline getTextBaseline() const;const std::string &getTextLocale() const;bool hasTextLocale() const;bool isUnderline() const;void setStrikethrough(bool enabled);bool isStrikethrough() const;TextRenderMode getTextRenderMode() const;BlendMode getBlendMode() const;ImageSampling getImageSampling() const;void setImageTileMode(ImageTileMode tileMode);ImageTileMode getImageTileMode() const;void clearCornerPathEffect();bool hasCornerPathEffect() const;float getCornerPathEffectRadius() const;void clearDashPathEffect();bool hasDashPathEffect() const;const std::vector<float> &getDashIntervals() const;float getDashPhase() const;void clearColorMatrix();bool hasColorMatrix() const;const std::array<float, 20> &getColorMatrix() const;Color getStrokeColor() const;Style getStyle() const;StrokeCap getStrokeCap() const;void setStrokeJoin(StrokeJoin join);StrokeJoin getStrokeJoin() const;
wsc/Path.h¶
class Path¶
Mutable, backend-neutral 2D path in local Canvas coordinates.
A path may contain multiple contours. Curve calls are flattened into line segments when recorded, so measurement, hit testing and rendering consume the same stable geometry. Path values are ordinary copyable CPU objects and may be reused across canvases.
setFillType¶
void setFillType(FillType fillType);
Select the winding rule used by fill drawing and contains().
moveTo¶
void moveTo(float x, float y);
Start a new contour at (x, y).
lineTo¶
void lineTo(float x, float y);
Add a straight segment to (x, y).
quadTo¶
void quadTo(float controlX, float controlY, float endX, float endY);void quadTo(const PointF &control, const PointF &end);
Add a flattened quadratic Bezier segment. With no current contour this behaves like moveTo(end).
cubicTo¶
void cubicTo(float control1X, float control1Y, float control2X, float control2Y, float endX, float endY);void cubicTo(const PointF &control1, const PointF &control2, const PointF &end);
Add a flattened cubic Bezier segment. With no current contour this behaves like moveTo(end).
close¶
void close();
Close the current contour back to its start point.
reset¶
void reset();
Clear all contours.
getPoints¶
const std::vector<PathPoint> &getPoints() const;
Borrow the internal flattened verb list until the next mutation.
getBounds¶
RectF getBounds() const;
Tight bounding box of the path geometry (fill).
getStrokeBounds¶
RectF getStrokeBounds(float strokeWidth) const;
Conservative local bounds for a simple centered stroke. Use Canvas::measureStrokeBounds for Paint cap/join/dash/effect accuracy.
contains¶
bool contains(float x, float y) const;bool contains(const PointF &point) const;
Point-in-fill / point-near-stroke hit tests.
strokeContains¶
bool strokeContains(float x, float y, float strokeWidth) const;bool strokeContains(const PointF &point, float strokeWidth) const;
Centerline-distance stroke test using the supplied width. It does not model Paint cap/join/dash effects; use Canvas hit testing for transforms/clip.
length¶
float length() const;
Total outline length of the path.
pointAtLength¶
bool pointAtLength(float targetLength, PointF &point) const;
Sample a distance along all contours in order. Negative distances clamp to zero; distances beyond the end return the final point/tangent. False means the input is non-finite or the path has no non-zero segment.
pointAndTangentAtLength¶
bool pointAndTangentAtLength(float targetLength, PointF &point, PointF &tangent) const;
Tangent output is normalized when successful.
reversed¶
Path reversed() const;
Return a copy with contour direction reversed.
trim¶
Path trim(float startLength, float endLength) const;Path trim(float startLength, float endLength, bool wrap) const;Path trim(float startLength, float endLength, bool wrap, bool reverse) const;
Return the geometry between absolute path lengths. Non-wrapping input is
ordered/clamped; wrap allows a span to cross the path end; reverse
measures the requested span from reversed contour direction.
roundedCorners¶
Path roundedCorners(float radius) const;
Return a copy with corners rounded by the given radius.
offset¶
void offset(float dx, float dy);
Translate all points by (dx, dy).
addRect¶
void addRect(const RectF &rect);
Append common shapes as new contours. Non-positive radii/sizes produce no drawable area.
addOval¶
void addOval(const RectF &rect);
Shape rectangles use (x,y,width,height) and append a new closed contour.
Additional public members¶
Straightforward accessors, value operations, and overloads:
Path();FillType getFillType() const;bool isEmpty() const;std::size_t getContourCount() const;std::size_t getClosedContourCount() const;bool isClosed() const;std::vector<RectF> getContourBounds() const;void addRoundRect(const RectF &rect, float radius);void addRoundRect(const RectF &rect, float topLeftRadius, float topRightRadius, float bottomRightRadius, float bottomLeftRadius);void addCircle(float x, float y, float radius);
wsc/Picture.h¶
class Picture¶
Immutable, backend-neutral sequence of Canvas operations.
A Picture owns CPU-side drawing inputs only. It deliberately does not own backend command buffers, textures, or other GPU-context objects, so the same Picture can be replayed after a context is recreated or on another Canvas. The callback passed to Canvas::recordPicture is synchronous. Operations that depend on destination/backend state, including saveLayer and DPR changes, reject recording and make recordPicture return an empty shared pointer.
operationCount¶
std::size_t operationCount() const;
Number of retained Canvas operations.
Additional public members¶
Straightforward accessors, value operations, and overloads:
~Picture();Picture(const Picture &) = delete;Picture(Picture &&) = delete;Picture &operator=(const Picture &) = delete;Picture &operator=(Picture &&) = delete;bool empty() const;
wsc/Surface.h¶
Backend-neutral output/presentation descriptors.
These are non-owning descriptions: the host keeps OS windows, displays, external framebuffers and images alive for as long as the Canvas uses them.
struct NativeSurface¶
A neutral operating-system window handle. The only input common to every graphics backend is the OS window itself; each backend builds its own surface/swapchain from this. All handles are borrowed, not owned.
No public methods detected by the lightweight generator.
struct SwapchainConfig¶
Neutral swapchain preferences. Backends map these to their own concepts and gracefully degrade preferences they cannot honor. Sizes are not stored here; use Canvas::setSize/resizeOutput with the physical drawable dimensions.
No public methods detected by the lightweight generator.
struct OutputTarget¶
Where a canvas delivers its rendered frames. A single "output axis": off-screen (read back / use as a texture), an on-screen window, or a host-owned backend render target (embed into an existing GL/Vulkan renderer). Construct via the static factories and pass to Canvas::setOutputTarget(). Changing targets invalidates the previous target configuration.
Minimal usage patterns:
- Off-screen rendering: OutputTarget::Offscreen()
- Window presentation: OutputTarget::ToWindow(surface) where surface is a
prepared NativeSurface
- Host-owned framebuffer: OutputTarget::GLFramebuffer(...)
- Host-owned Vulkan image: OutputTarget::VulkanImageTarget(...)
Typical lifecycle for an off-screen target:
auto canvas = wsc::Canvas::create(...); canvas->setOutputTarget(wsc::OutputTarget::Offscreen()); canvas->beginFrame(); draw...; canvas->endFrame();
For a window target, the final frame submission is endFrame(); present();.
Offscreen¶
static OutputTarget Offscreen();
Off-screen: render internally, read back with readPixelsRGBA.
OffscreenTexture¶
static OutputTarget OffscreenTexture();
Off-screen but also usable as a texture in another canvas (drawImage).
ToWindow¶
static OutputTarget ToWindow(const NativeSurface &surface, const SwapchainConfig &config = SwapchainConfig());
Present to a borrowed OS window. Returns a descriptor only; support and handle validity are checked when Canvas::setOutputTarget() is called.
GLFramebuffer¶
static OutputTarget GLFramebuffer(unsigned int framebuffer, int width, int height, bool opaque = false);
Render into a host-owned OpenGL framebuffer in this Canvas' current context. Width/height are physical pixels; framebuffer 0 means the context's default framebuffer. The host retains ownership.
VulkanImageTarget¶
static OutputTarget VulkanImageTarget(void *image, unsigned long long format, int width, int height);
Render into a host-owned VkImage (created on this canvas's Vulkan device,
R8G8B8A8_UNORM with COLOR_ATTACHMENT and TRANSFER_SRC usage). format is
a VkFormat encoded as an integer. The host owns synchronization and image
lifetime outside WhatsCanvas submissions.
wsc/TextureSource.h¶
class ITextureSource¶
Unified interface for any object that can serve as a renderer image source. Both Image and Canvas implement this interface, allowing either to be used wherever a texture is expected. Sources are backend/device-bound and are sampled only after their content is valid; Canvas sources require endFrame().
getTextureWidth¶
virtual int getTextureWidth() const = 0;
Width of the underlying texture in pixels.
getTextureHeight¶
virtual int getTextureHeight() const = 0;
Height of the underlying texture in pixels.
isTextureValid¶
virtual bool isTextureValid() const = 0;
Whether the texture data is valid and ready for sampling.
isRenderTarget¶
virtual bool isRenderTarget() const = 0;
Whether this source is a render target (Canvas) rather than a loaded image.
Additional public members¶
Straightforward accessors, value operations, and overloads:
ITextureSource() = default;ITextureSource(const ITextureSource &) = delete;ITextureSource &operator=(const ITextureSource &) = delete;virtual ~ITextureSource() = default;
wsc/Version.h¶
Compile-time semantic version of the public WhatsCanvas headers. Runtime libraries and headers should come from the same installed package.