Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wasm vega renderer: Finish symbol mark support #68

Merged
merged 2 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 80 additions & 21 deletions avenger-vega-renderer/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,51 +165,93 @@ function importGroup(vegaGroup) {
return groupMark;
}

function importSymbol(vegaSymbolMark) {
const len = vegaSymbolMark.items.length;
const symbolMark = new SymbolMark(len, vegaSymbolMark.clip, vegaSymbolMark.name);
function importSymbol(vegaSymbolMark, force_clip) {
const items = vegaSymbolMark.items;
const len = items.length;

const symbolMark = new SymbolMark(
len, vegaSymbolMark.clip || force_clip, vegaSymbolMark.name, vegaSymbolMark.zindex
);

// Handle empty mark
if (len === 0) {
return symbolMark;
}

const firstItem = items[0];
const firstShape = firstItem.shape ?? "circle";

if (firstShape === "stroke") {
// TODO: Handle line legends
return symbolMark
}

// Only include stroke_width if there is a stroke color
const firstHasStroke = firstItem.stroke != null;
let strokeWidth;
if (firstHasStroke) {
strokeWidth = firstItem.strokeWidth ?? 1;
}
symbolMark.set_stroke_width(strokeWidth);

// Semi-required values get initialized
const x = new Float32Array(len).fill(0);
const y = new Float32Array(len).fill(0);

const fill = new Array(len);
let anyFill = false;
let fillIsGradient = firstItem.fill != null && typeof firstItem.fill === "object";

const size = new Float32Array(len).fill(20);
let anySize = false;

const stroke = new Array(len);
let anyStroke = false;
let strokeIsGradient = firstItem.stroke != null && typeof firstItem.stroke === "object";

const angle = new Float32Array(len).fill(0);
let anyAngle = false;

const opacity = new Float32Array(len).fill(1);
let anyOpacity = false;
const zindex = new Float32Array(len).fill(0);
let anyZindex = false;

const fill = new Array(len).fill("");
let anyFill = false;
const fillOpacity = new Float32Array(len).fill(1);
const strokeOpacity = new Float32Array(len).fill(1);

const shapes = new Array(len);
let anyShape = false;

const items = vegaSymbolMark.items;
items.forEach((item, i) => {
x[i] = item.x;
y[i] = item.y;
x[i] = item.x ?? 0;
y[i] = item.y ?? 0;

const baseOpacity = item.opacity ?? 1;
fillOpacity[i] = (item.fillOpacity ?? 1) * baseOpacity;
strokeOpacity[i] = (item.strokeOpacity ?? 1) * baseOpacity;

if (item.fill != null) {
fill[i] = item.fill;
anyFill ||= true;
}

if (item.size != null) {
size[i] = item.size;
anySize = true;
}

if (item.stroke != null) {
stroke[i] = item.stroke;
anyStroke ||= true;
}

if (item.angle != null) {
angle[i] = item.angle;
anyAngle ||= true;
}

if (item.opacity != null) {
opacity[i] = item.opacity;
anyOpacity ||= true;
}

if (item.fill != null) {
fill[i] = item.fill;
anyFill ||= true;
if (item.zindex != null) {
zindex[i] = item.zindex;
anyZindex ||= true;
}

if (item.shape != null) {
Expand All @@ -220,17 +262,34 @@ function importSymbol(vegaSymbolMark) {

symbolMark.set_xy(x, y);

if (anyFill) {
if (fillIsGradient) {
symbolMark.set_fill_gradient(fill, fillOpacity);
} else {
const encoded = encodeStringArray(fill);
symbolMark.set_fill(encoded.values, encoded.indices, fillOpacity);
}
}

if (anySize) {
symbolMark.set_size(size);
}

if (anyStroke) {
if (strokeIsGradient) {
symbolMark.set_stroke_gradient(stroke, strokeOpacity);
} else {
const encoded = encodeStringArray(stroke);
symbolMark.set_stroke(encoded.values, encoded.indices, strokeOpacity);
}
}

if (anyAngle) {
symbolMark.set_angle(angle);
}

if (anyFill || anyOpacity) {
const encoded = encodeStringArray(fill);
symbolMark.set_fill(encoded.values, encoded.indices, opacity);
if (anyZindex) {
symbolMark.set_zindex(zindex);
}

if (anyShape) {
Expand Down
65 changes: 54 additions & 11 deletions avenger-vega-renderer/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ use avenger::marks::group::{Clip, SceneGroup as RsSceneGroup};
use avenger::marks::mark::SceneMark;
use avenger::marks::symbol::SymbolShape;
use avenger::marks::text::{FontStyleSpec, FontWeightSpec, TextAlignSpec, TextBaselineSpec};
use avenger::marks::value::{ColorOrGradient, EncodingValue};
use avenger::marks::value::{ColorOrGradient, EncodingValue, Gradient};
use avenger::marks::{
rule::RuleMark as RsRuleMark, symbol::SymbolMark as RsSymbolMark, text::TextMark as RsTextMark,
};
use avenger::scene_graph::SceneGraph as RsSceneGraph;
use avenger_vega::error::AvengerVegaError;
use avenger_vega::marks::values::CssColorOrGradient;
use gloo_utils::format::JsValueSerdeExt;
use wasm_bindgen::prelude::*;

Expand All @@ -19,20 +21,24 @@ pub struct SymbolMark {
#[wasm_bindgen]
impl SymbolMark {
#[wasm_bindgen(constructor)]
pub fn new(len: u32, clip: bool, name: Option<String>) -> Self {
pub fn new(len: u32, clip: bool, name: Option<String>, zindex: Option<i32>) -> Self {
Self {
inner: RsSymbolMark {
len,
clip,
zindex,
name: name.unwrap_or_default(),
fill: EncodingValue::Scalar {
value: ColorOrGradient::Color([0.0, 0.0, 1.0, 0.5]),
},
..Default::default()
},
}
}

pub fn set_zindex(&mut self, zindex: Vec<i32>) {
let mut indices: Vec<usize> = (0..self.inner.len as usize).collect();
indices.sort_by_key(|i| zindex[*i]);
self.inner.indices = Some(indices);
}

pub fn set_xy(&mut self, x: Vec<f32>, y: Vec<f32>) {
self.inner.x = EncodingValue::Array { values: x };
self.inner.y = EncodingValue::Array { values: y };
Expand All @@ -46,8 +52,8 @@ impl SymbolMark {
self.inner.angle = EncodingValue::Array { values: angle };
}

pub fn set_zindex(&mut self, zindex: Option<i32>) {
self.inner.zindex = zindex;
pub fn set_stroke_width(&mut self, width: Option<f32>) {
self.inner.stroke_width = width;
}

pub fn set_stroke(
Expand All @@ -62,6 +68,17 @@ impl SymbolMark {
Ok(())
}

pub fn set_stroke_gradient(
&mut self,
values: JsValue,
opacity: Vec<f32>,
) -> Result<(), JsError> {
self.inner.stroke = EncodingValue::Array {
values: decode_gradients(values, opacity, &mut self.inner.gradients)?,
};
Ok(())
}

pub fn set_fill(
&mut self,
color_values: JsValue,
Expand All @@ -74,6 +91,13 @@ impl SymbolMark {
Ok(())
}

pub fn set_fill_gradient(&mut self, values: JsValue, opacity: Vec<f32>) -> Result<(), JsError> {
self.inner.fill = EncodingValue::Array {
values: decode_gradients(values, opacity, &mut self.inner.gradients)?,
};
Ok(())
}

pub fn set_shape(&mut self, shape_values: JsValue, indices: Vec<usize>) -> Result<(), JsError> {
let shapes: Vec<String> = shape_values.into_serde()?;
let shapes = shapes
Expand Down Expand Up @@ -112,6 +136,11 @@ impl RuleMark {
},
}
}

pub fn set_zindex(&mut self, zindex: Option<i32>) {
self.inner.zindex = zindex;
}

pub fn set_xy(&mut self, x0: Vec<f32>, y0: Vec<f32>, x1: Vec<f32>, y1: Vec<f32>) {
self.inner.x0 = EncodingValue::Array { values: x0 };
self.inner.y0 = EncodingValue::Array { values: y0 };
Expand Down Expand Up @@ -155,6 +184,10 @@ impl TextMark {
}
}

pub fn set_zindex(&mut self, zindex: Option<i32>) {
self.inner.zindex = zindex;
}

pub fn set_xy(&mut self, x: Vec<f32>, y: Vec<f32>) {
self.inner.x = EncodingValue::Array { values: x };
self.inner.y = EncodingValue::Array { values: y };
Expand All @@ -176,10 +209,6 @@ impl TextMark {
self.inner.indices = Some(indices);
}

pub fn set_zindex(&mut self, zindex: i32) {
self.inner.zindex = Some(zindex);
}

pub fn set_text(&mut self, text: JsValue) -> Result<(), JsError> {
let text: Vec<String> = text.into_serde()?;
self.inner.text = EncodingValue::Array { values: text };
Expand Down Expand Up @@ -281,6 +310,20 @@ impl TextMark {
}
}

fn decode_gradients(
values: JsValue,
opacity: Vec<f32>,
gradients: &mut Vec<Gradient>,
) -> Result<Vec<ColorOrGradient>, JsError> {
let values: Vec<CssColorOrGradient> = values.into_serde()?;
values
.iter()
.zip(opacity)
.map(|(grad, opacity)| grad.to_color_or_grad(opacity, gradients))
.collect::<Result<Vec<_>, AvengerVegaError>>()
.map_err(|_| JsError::new("Failed to parse gradients"))
}

fn decode_colors(
color_values: JsValue,
indices: Vec<usize>,
Expand Down
48 changes: 45 additions & 3 deletions avenger-vega-renderer/test/test_baselines.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,37 @@ def failures_path():
@pytest.mark.parametrize(
"category,spec_name,tolerance",
[
("symbol", "binned_scatter_circle", 0.0001),
("symbol", "binned_scatter_diamonds", 0.0001),
("symbol", "binned_scatter_square", 0.0001),
("symbol", "binned_scatter_triangle-down", 0.0001),
("symbol", "binned_scatter_triangle-up", 0.0001),
("symbol", "binned_scatter_triangle-left", 0.0001),
("symbol", "binned_scatter_triangle-right", 0.0001),
("symbol", "binned_scatter_triangle", 0.0001),
("symbol", "binned_scatter_wedge", 0.0001),
("symbol", "binned_scatter_arrow", 0.0001),
("symbol", "binned_scatter_cross", 0.0001),
("symbol", "binned_scatter_circle", 0.0001),
("symbol", "binned_scatter_path", 0.0001),
("symbol", "binned_scatter_path_star", 0.0001),
("symbol", "binned_scatter_path_star", 0.0001),
("symbol", "binned_scatter_cross_stroke", 0.0001),
("symbol", "binned_scatter_circle_stroke", 0.0001),
("symbol", "binned_scatter_circle_stroke_no_fill", 0.0001),
("symbol", "binned_scatter_path_star_stroke_no_fill", 0.0001),
("symbol", "scatter_transparent_stroke", 0.0001),
("symbol", "scatter_transparent_stroke_star", 0.0001),
("symbol", "scatter_transparent_stroke_star", 0.0001),
("symbol", "wind_vector", 0.0001),
("symbol", "wedge_angle", 0.0001),
("symbol", "wedge_stroke_angle", 0.0001),
("symbol", "zindex_circles", 0.0001),
("symbol", "mixed_symbols", 0.0001),

# The canvas renderer messes up these gradients, avenger renders them correctly
("gradients", "symbol_cross_gradient", 0.03),
("gradients", "symbol_circles_gradient_stroke", 0.03),
("gradients", "symbol_radial_gradient", 0.0002),
],
)
def test_image_baselines(
Expand Down Expand Up @@ -105,8 +132,13 @@ class ComparisonResult:


def compare(page: Page, spec: dict) -> ComparisonResult:
canvas_img = spec_to_image(page, spec, "canvas")
avenger_errs = []
page.on("pageerror", lambda e: avenger_errs.append(e))
avenger_img = spec_to_image(page, spec, "avenger")
if avenger_errs:
pytest.fail('\n'.join(avenger_errs))

canvas_img = spec_to_image(page, spec, "canvas")
diff_img = Image.new("RGBA", canvas_img.size)
mismatch = pixelmatch(canvas_img, avenger_img, diff_img, threshold=0.2)
score = mismatch / (canvas_img.width * canvas_img.height)
Expand All @@ -127,4 +159,14 @@ def spec_to_image(
f"vegaEmbed('#plot-container', {json.dumps(spec)}, {json.dumps(embed_opts)});"
)
page.evaluate_handle(script)
return Image.open(io.BytesIO(page.locator("canvas").first.screenshot()))
img = Image.open(io.BytesIO(page.locator("canvas").first.screenshot()))

# Check that the image is not entirely white (which happens on rendering errors sometimes)
pixels = img.load()
for x in range(img.width):
for y in range(img.height):
if pixels[x, y] != (255, 255, 255, 255):
# Found non-white pixel, return
return img

pytest.fail("Retrieved blank image")
5 changes: 5 additions & 0 deletions avenger-vega-renderer/test/test_server/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@ module.exports = {
],
}),
],
devServer: {
client: {
overlay: false, // Disabling the error overlay
},
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"data": [
{
"name": "source_0",
"url": "data/movies.json",
"url": "https://raw.githubusercontent.com/vega/vega-datasets/main/data/movies.json",
"format": {"type": "json", "parse": {"Release Date": "date"}},
"transform": [
{"type": "filter", "expr": "datum['IMDB Rating'] != null"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"data": [
{
"name": "source_0",
"url": "data/movies.json",
"url": "https://raw.githubusercontent.com/vega/vega-datasets/main/data/movies.json",
"format": {"type": "json"},
"transform": [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"data": [
{
"name": "source_0",
"url": "data/movies.json",
"url": "https://raw.githubusercontent.com/vega/vega-datasets/main/data/movies.json",
"format": {"type": "json"},
"transform": [
{
Expand Down
Loading