chart3d: соответствие ECMA-376 для 3D-типов диаграмм #43

Merged
pjandro merged 2 commits from chart3d-ecma-fixes into main 2026-10-25 16:27:15 +03:00
10 changed files with 996 additions and 142 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
@@ -53,23 +53,26 @@ class ConversionServiceTest {
ConversionService svc = new ConversionService(Duration.ofMinutes(2));
ThreadPoolExecutor workers = workersOf(svc);
CountDownLatch block = new CountDownLatch(1);
CountDownLatch workerBusy = new CountDownLatch(1);
List<Future<?>> fillers = new ArrayList<>();
try {
// заглушки-блокировки вместо реальных конвертаций: воркер занят,
// очередь полна, ни одной лишней конвертации в JVM
// очередь полна, ни одной лишней конвертации в JVM. Первый task
// сигналит ИЗ ВОРКЕР-ПОТОКА о старте: getActiveCount() — снимок-
// аппроксимация (w.isLocked()), и на загруженном CI-раннере поток
// мог не дойти до w.lock() за окно опроса (флейк «воркер не занят»).
for (int i = 0; i <= ConversionService.QUEUE_CAPACITY; i++) {
fillers.add(workers.submit(() -> {
workerBusy.countDown();
block.await();
return null;
}));
}
long deadline = System.nanoTime() + 5_000_000_000L;
while ((workers.getActiveCount() < 1
|| workers.getQueue().size() < ConversionService.QUEUE_CAPACITY)
&& System.nanoTime() < deadline) {
Thread.sleep(5);
}
assertTrue(workerBusy.await(10, TimeUnit.SECONDS), "воркер не взял задачу");
assertEquals(1, workers.getActiveCount(), "воркер не занят");
// task1 — firstTask воркера, в очередь он не ложился; остальные
// QUEUE_CAPACITY лежат, воркер заблокирован на task1 и не может их
// consumить — размер очереди точный, опрос не нужен.
assertEquals(ConversionService.QUEUE_CAPACITY, workers.getQueue().size(),
"очередь не полна");
@@ -17,12 +17,15 @@ import java.util.List;
* {@link Surface3dPainter#GUTTER_LEFT} и т.д.
*
* bar3D: кластерные колонки — ряды уходят в глубину (ширина полосы
* c:gapWidth, ширина колонки — полоса·(1−max(0,c:overlap))/nSer); торец
* затемняется (псевдо-свет, калибровка — Cartesian3dPainterTest).
* c:gapWidth, глубина колонки — слот 1/nSer·100/(100+c:gapDepth) по MS-OI29500
* §2.1.1474(a)); торец затемняется (псевдо-свет, калибровка — Cartesian3dPainterTest).
* line3D: полилиния ряда на своей глубине, лента-толщина не имитируется;
* area3D: стена ряда от пола до значений, полупрозрачная, как AREA.
* Ограничения: c:shape (cylinder/cone/pyramid…) рисуется как box;
* c:barDir="bar" — горизонтальная ориентация тех же боксов.
* c:shape (§21.2.2.177, ST_Shape §21.2.3.44): box/cone/coneToMax/cylinder/pyramid/
* pyramidToMax; c:shape ряда переопределяет форму диаграммы (MS-OI29500 §2.1.1545(a/b)),
* ToMax-формы сужаются к верху пропорционально val/max (семантика Excel — ECMA геометрию
* не нормирует); неизвестное значение — box. c:barDir="bar" — горизонтальная ориентация
* боксов (Word UI не сочетает barDir=bar с формами).
*
* Регрессия — Cartesian3dPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
@@ -39,11 +42,18 @@ final class Cartesian3dPainter {
private record Fit(double scale, double offX, double offY) {
}
/** Одна 3D-колонка: 8 спроецированных углов + цвет + глубина центра. */
private record Column(Surface3dPainter.Node center,
Surface3dPainter.Node[][][] corners, Color color) {
/** Грань колонки: полигон в модельных координатах {u, v, w} + цвет + средняя
* глубина вершин (порядок painter's algorithm). */
private record Face(double[][] pts, Color color, double depth) {
}
/** Одна 3D-колонка: глубина центра (сортировка колонок) + грани. */
private record Column(Surface3dPainter.Node center, List<Face> faces) {
}
/** Сегментов боковой поверхности cone/cylinder. */
private static final int ROUND_SEGMENTS = 12;
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
int nSer = spec.series.size();
int nCat = 0;
@@ -57,7 +67,17 @@ final class Cartesian3dPainter {
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
double[] range = ChartRenderer.valueRange(spec);
boolean bar3d = spec.type == ChartSpec.Type.BAR3D;
boolean horizontal = bar3d && spec.bar3dHorizontal;
// §21.2.2.76: c:grouping stacked/percentStacked — bar3D/area3D; line3D —
// игнорируется (Word UI не предлагает 3-D Stacked Line), горизонтальный
// bar3D остаётся кластерным.
boolean stacked = (bar3d && !horizontal || spec.type == ChartSpec.Type.AREA3D)
&& isStacked(spec.grouping);
boolean percent = stacked && "percentStacked".equalsIgnoreCase(spec.grouping);
// Кумулятивные значения по категориям: ряд si — полоса/сегмент cum[si]..cum[si+1].
double[][] cum = stacked ? stackedCumulative(spec, percent) : null;
double[] range = stacked ? stackedRange(cum) : ChartRenderer.valueRange(spec);
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1]);
double lo = bounds[0];
double hi = bounds[1];
@@ -66,7 +86,9 @@ final class Cartesian3dPainter {
double rotX = Math.toRadians(spec.rotX);
double rotY = -Math.toRadians(spec.rotY);
double persp = spec.perspective;
// §21.2.2.136 + MS-OI29500 §2.1.1516(b): rAngAx=true → перспектива
// игнорируется (ортография), c:perspective действует только при rAngAx=false.
double persp = spec.rightAngledAxes ? 0 : spec.perspective;
double leftGutter = Surface3dPainter.GUTTER_LEFT * box.getWidth();
double rightGutter = Surface3dPainter.GUTTER_RIGHT * box.getWidth();
double topGutter = Surface3dPainter.GUTTER_TOP * box.getHeight();
@@ -75,11 +97,12 @@ final class Cartesian3dPainter {
double availH = Math.max(10, box.getHeight() - topGutter - bottomGutter);
double depthScale = Surface3dPainter.DEPTH_RATIO * Math.max(0.05,
spec.depthPercent / 100.0);
double heightScale = Surface3dPainter.HEIGHT_RATIO * availH / availW;
// MS-OI29500 §2.1.1481(c): c:hPercent задан → высота = hPercent% от ширины
// области построения; опущен → автомасштаб (как у Surface3dPainter).
double heightScale = spec.hPercent != null
? spec.hPercent / 100.0 : Surface3dPainter.HEIGHT_RATIO * availH / availW;
double floorW = -0.5 * heightScale;
boolean bar3d = spec.type == ChartSpec.Type.BAR3D;
boolean horizontal = bar3d && spec.bar3dHorizontal;
List<Surface3dPainter.Node> nodes = new ArrayList<>();
Surface3dPainter.Node[] floor = {
@@ -100,26 +123,71 @@ final class Cartesian3dPainter {
List<Column> columns = new ArrayList<>();
double bw = 1.0 / nCat * 100.0 / (100.0 + spec.gapWidth);
double colW = bw * (100.0 - Math.max(0, spec.overlap)) / 100.0 / Math.max(1, nSer);
for (int si = 0; si < nSer; si++) {
ChartSpec.Series s = spec.series.get(si);
double v = vOf(si, nSer);
if (bar3d && stacked) {
// §21.2.2.76: stacked bar3D — одна полоса глубины на категорию (центр v=0,
// colD от c:gapDepth), ряд si — box-сегмент от w(cum[si−1]) до w(cum[si])
// (Word UI: формы c:shape для stacked недоступны — всегда box).
double colD = 100.0 / (100.0 + spec.gapDepth);
for (int c = 0; c < nCat; c++) {
Double val = c < s.values.size() ? s.values.get(c) : null;
if (val == null) {
continue;
double prev = 0;
for (int si = 0; si < nSer; si++) {
List<Double> vals = spec.series.get(si).values;
Double v = c < vals.size() ? vals.get(c) : null;
if (v == null) {
continue;
}
columns.add(makeStackedColumn(spec.series.get(si).fillAt(si, palette),
c, nCat, wOf(prev, lo, span, heightScale),
wOf(cum[si][c], lo, span, heightScale), bw, colD,
rotX, rotY, depthScale, persp, nodes));
prev = cum[si][c];
}
if (bar3d) {
columns.add(makeColumn(s.fillAt(si, palette), c,
si - (nSer - 1) / 2.0, nCat, val, lo, span, heightScale,
floorW, bw, colW, horizontal, rotX, rotY, depthScale,
persp, nodes));
} else {
double w = wOf(val, lo, span, heightScale);
double u = uOf(c, nCat);
nodes.add(proj(u, v, w, rotX, rotY, depthScale, persp));
if (spec.type == ChartSpec.Type.AREA3D) {
nodes.add(proj(u, v, floorW, rotX, rotY, depthScale, persp));
}
} else if (stacked) {
// stacked area3D: одна стена на v=0 — вписка по кумулятивным верхам.
for (int si = 0; si < nSer; si++) {
for (int c = 0; c < nCat; c++) {
nodes.add(proj(uOf(c, nCat), 0,
wOf(cum[si][c], lo, span, heightScale),
rotX, rotY, depthScale, persp));
}
}
} else {
// ToMax-формы: максимум значения по всем рядам/категориям — доля t = val/chartMax
// задаёт степень сужения к верху (семантика Excel; ECMA геометрию не нормирует).
double chartMax = 0;
for (ChartSpec.Series s : spec.series) {
for (Double val : s.values) {
if (val != null) {
chartMax = Math.max(chartMax, val);
}
}
}
for (int si = 0; si < nSer; si++) {
ChartSpec.Series s = spec.series.get(si);
double v = vOf(si, nSer);
for (int c = 0; c < nCat; c++) {
Double val = c < s.values.size() ? s.values.get(c) : null;
if (val == null) {
continue;
}
if (bar3d) {
String shape = s.shape3d != null ? s.shape3d : spec.shape3d;
double t = chartMax > 0 ? Math.max(0, Math.min(1, val / chartMax)) : 0;
if (horizontal || (shape.endsWith("ToMax") && t <= 0)) {
shape = "box";
}
columns.add(makeColumn(s.fillAt(si, palette), shape, t, c, si,
nCat, nSer, val, lo, span, heightScale, floorW, bw,
spec.gapDepth, horizontal, rotX, rotY, depthScale,
persp, nodes));
} else {
double w = wOf(val, lo, span, heightScale);
double u = uOf(c, nCat);
nodes.add(proj(u, v, w, rotX, rotY, depthScale, persp));
if (spec.type == ChartSpec.Type.AREA3D) {
nodes.add(proj(u, v, floorW, rotX, rotY, depthScale, persp));
}
}
}
}
@@ -148,10 +216,13 @@ final class Cartesian3dPainter {
}
if (bar3d) {
drawColumns(g, columns, fit);
drawColumns(g, columns, rotX, rotY, depthScale, persp, fit);
} else if (spec.type == ChartSpec.Type.LINE3D) {
drawLines(g, spec, palette, lo, span, heightScale, nCat, nSer,
rotX, rotY, depthScale, persp, fit);
} else if (stacked) {
drawStackedAreas(g, spec, palette, cum, lo, span, heightScale, nCat, nSer,
rotX, rotY, depthScale, persp, fit);
} else {
drawAreas(g, spec, palette, lo, span, heightScale, floorW, nCat, nSer,
rotX, rotY, depthScale, persp, fit);
@@ -161,11 +232,15 @@ final class Cartesian3dPainter {
rotX, rotY, depthScale, floorW, persp, fit);
}
/** Колонка bar3D: вертикальная (значение по w) или горизонтальная (по u). */
private static Column makeColumn(Color color, int c, double serOffset, int nCat,
/** Колонка bar3D: вертикальная (значение по w) или горизонтальная (по u, всегда
* box). Глубина: MS-OI29500 §2.1.1474(a) — c:gapDepth есть зазор между смежными
* полосами рядов в направлении оси глубины, % от глубины полосы (дефолт 150);
* CT_Bar3DChart не содержит c:overlap — колонки не перекрываются. */
private static Column makeColumn(Color color, String shape, double t,
int c, int si, int nCat, int nSer,
double val,
double lo, double span, double heightScale,
double floorW, double bw, double colW,
double floorW, double bw, double gapDepth,
boolean horizontal,
double rotX, double rotY, double depthScale,
double persp, List<Surface3dPainter.Node> nodes) {
@@ -176,75 +251,325 @@ final class Cartesian3dPainter {
double wTop;
if (horizontal) {
double band = (c + 0.5) / nCat - 0.5;
double vc = band + serOffset * colW;
v0 = vc - colW / 2.0;
v1 = vc + colW / 2.0;
double clusterD = 1.0 / nCat * 100.0 / (100.0 + gapDepth);
double serD = clusterD / nSer;
v0 = band - clusterD / 2.0 + si * serD;
v1 = v0 + serD;
double ua = uVal(0, lo, span);
double ub = uVal(val, lo, span);
u0 = Math.min(ua, ub);
u1 = Math.max(ua, ub);
wTop = floorW + colW * heightScale;
wTop = floorW + serD * heightScale;
} else {
double uc = uOf(c, nCat);
u0 = uc - bw / 2.0;
u1 = uc + bw / 2.0;
double vc = serOffset * colW;
v0 = vc - colW / 2.0;
v1 = vc + colW / 2.0;
double colD = 1.0 / nSer * 100.0 / (100.0 + gapDepth);
double vc = vOf(si, nSer);
v0 = vc - colD / 2.0;
v1 = vc + colD / 2.0;
wTop = wOf(val, lo, span, heightScale);
}
double[] us = {u0, u1};
double[] vs = {v0, v1};
double[] ws = {floorW, wTop};
Surface3dPainter.Node[][][] corners = new Surface3dPainter.Node[2][2][2];
for (int u = 0; u < 2; u++) {
for (int v = 0; v < 2; v++) {
for (int w = 0; w < 2; w++) {
corners[u][v][w] = proj(us[u], vs[v], ws[w],
rotX, rotY, depthScale, persp);
nodes.add(corners[u][v][w]);
List<Face> faces = buildFaces(color, shape, t, u0, u1, v0, v1, floorW, wTop,
rotX, rotY, depthScale, persp, nodes);
Surface3dPainter.Node center = proj((u0 + u1) / 2.0, (v0 + v1) / 2.0,
(floorW + wTop) / 2.0, rotX, rotY, depthScale, persp);
nodes.add(center);
return new Column(center, faces);
}
/** c:grouping stacked/percentStacked (§21.2.2.76). */
private static boolean isStacked(String grouping) {
return "stacked".equalsIgnoreCase(grouping)
|| "percentStacked".equalsIgnoreCase(grouping);
}
/** Кумулятивные значения stacked: cum[si][c] — сумма рядов 0..si в категории c;
* percentStacked — доля от суммы категории ×100 (сумма 0 → 0). */
private static double[][] stackedCumulative(ChartSpec spec, boolean percent) {
int nSer = spec.series.size();
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
nCat = Math.max(nCat, s.values.size());
}
double[] totals = new double[nCat];
if (percent) {
for (ChartSpec.Series s : spec.series) {
for (int c = 0; c < s.values.size(); c++) {
Double v = s.values.get(c);
if (v != null) {
totals[c] += v;
}
}
}
}
Surface3dPainter.Node center = proj((u0 + u1) / 2.0, (v0 + v1) / 2.0,
(floorW + wTop) / 2.0, rotX, rotY, depthScale, persp);
return new Column(center, corners, color);
double[][] cum = new double[nSer][nCat];
for (int c = 0; c < nCat; c++) {
double running = 0;
for (int si = 0; si < nSer; si++) {
List<Double> vals = spec.series.get(si).values;
Double v = c < vals.size() ? vals.get(c) : null;
double add = v == null ? 0 : v;
if (percent) {
add = totals[c] == 0 ? 0 : add / totals[c] * 100.0;
}
running += add;
cum[si][c] = running;
}
}
return cum;
}
/** Колонки от дальних к ближним: верх/перед цветом ряда, торец темнее. */
private static void drawColumns(Graphics2D g, List<Column> columns, Fit fit) {
/** Диапазон значений stacked: от 0 до максимума кумулятивных вершин (учитывая
* отрицательные суммы). */
private static double[] stackedRange(double[][] cum) {
double min = 0;
double max = 0;
for (double[] row : cum) {
for (double v : row) {
min = Math.min(min, v);
max = Math.max(max, v);
}
}
return new double[]{min, max};
}
/** Сегмент stacked bar3D: box от wBottom до wTop на полной полосе глубины
* категории (центр v=0, colD от c:gapDepth). */
private static Column makeStackedColumn(Color color, int c, int nCat,
double wBottom, double wTop,
double bw, double colD,
double rotX, double rotY, double depthScale,
double persp, List<Surface3dPainter.Node> nodes) {
double uc = uOf(c, nCat);
double u0 = uc - bw / 2.0;
double u1 = uc + bw / 2.0;
double v0 = -colD / 2.0;
double v1 = colD / 2.0;
List<Face> faces = buildFaces(color, "box", 0, u0, u1, v0, v1, wBottom, wTop,
rotX, rotY, depthScale, persp, nodes);
Surface3dPainter.Node center = proj((u0 + u1) / 2.0, 0.0, (wBottom + wTop) / 2.0,
rotX, rotY, depthScale, persp);
nodes.add(center);
return new Column(center, faces);
}
/** Стены stacked area3D: одна стена на v=0, ряд si — полоса между кумулятивными
* ломаными cum[si−1] и cum[si], полупрозрачная, как AREA. */
private static void drawStackedAreas(Graphics2D g, ChartSpec spec, List<Color> palette,
double[][] cum, double lo, double span,
double heightScale, int nCat, int nSer,
double rotX, double rotY, double depthScale,
double persp, Fit fit) {
for (int si = nSer - 1; si >= 0; si--) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
List<Double> baseX = new ArrayList<>();
List<Double> baseY = new ArrayList<>();
for (int i = 0; i < nCat; i++) {
double u = uOf(i, nCat);
double top = wOf(cum[si][i], lo, span, heightScale);
double bottom = wOf(si == 0 ? 0 : cum[si - 1][i], lo, span, heightScale);
double[] p = screen(proj(u, 0, top, rotX, rotY, depthScale, persp), fit);
double[] b = screen(proj(u, 0, bottom, rotX, rotY, depthScale, persp), fit);
xs.add(p[0]);
ys.add(p[1]);
baseX.add(b[0]);
baseY.add(b[1]);
}
if (xs.size() < MIN_POLYLINE_POINTS) {
continue;
}
Path2D band = new Path2D.Double();
band.moveTo(xs.get(0), ys.get(0));
for (int i = 1; i < xs.size(); i++) {
band.lineTo(xs.get(i), ys.get(i));
}
for (int i = baseX.size() - 1; i >= 0; i--) {
band.lineTo(baseX.get(i), baseY.get(i));
}
band.closePath();
g.setColor(DrawMlColor.withAlpha(c, 0.55));
g.fill(band);
g.setColor(c);
g.setStroke(new BasicStroke(1.2f));
g.draw(ChartRenderer.polyline(xs, ys, false));
}
}
/** Грани колонки в модельных координатах (§21.2.3.44 ST_Shape); все вершины
* проецируются в nodes — по ним происходит вписка. Неизвестная форма — box. */
private static List<Face> buildFaces(Color color, String shape, double t,
double u0, double u1, double v0, double v1,
double wBase, double wTop,
double rotX, double rotY, double depthScale,
double persp, List<Surface3dPainter.Node> nodes) {
List<Face> faces = switch (shape) {
case "cone" -> roundFaces(color, u0, u1, v0, v1, wBase, wTop, 0,
rotX, rotY, depthScale, persp);
case "coneToMax" -> roundFaces(color, u0, u1, v0, v1, wBase, wTop, 1 - t,
rotX, rotY, depthScale, persp);
case "cylinder" -> roundFaces(color, u0, u1, v0, v1, wBase, wTop, 1,
rotX, rotY, depthScale, persp);
case "pyramid" -> pyramidFaces(color, u0, u1, v0, v1, wBase, wTop, 0,
rotX, rotY, depthScale, persp);
case "pyramidToMax" -> pyramidFaces(color, u0, u1, v0, v1, wBase, wTop, 1 - t,
rotX, rotY, depthScale, persp);
default -> boxFaces(color, u0, u1, v0, v1, wBase, wTop,
rotX, rotY, depthScale, persp);
};
for (Face f : faces) {
for (double[] q : f.pts()) {
nodes.add(proj(q[0], q[1], q[2], rotX, rotY, depthScale, persp));
}
}
return faces;
}
/** Box: три видимые грани — верх, перед, торец u=max (затемнён, псевдо-свет). */
private static List<Face> boxFaces(Color color, double u0, double u1,
double v0, double v1, double wBase, double wTop,
double rotX, double rotY, double depthScale,
double persp) {
return List.of(
face(new double[][]{{u0, v0, wTop}, {u1, v0, wTop},
{u1, v1, wTop}, {u0, v1, wTop}},
color, rotX, rotY, depthScale, persp),
face(new double[][]{{u0, v0, wBase}, {u1, v0, wBase},
{u1, v0, wTop}, {u0, v0, wTop}},
color, rotX, rotY, depthScale, persp),
face(new double[][]{{u1, v0, wBase}, {u1, v1, wBase},
{u1, v1, wTop}, {u1, v0, wTop}},
color.darker(), rotX, rotY, depthScale, persp));
}
/** Пирамида (s=0 — апекс) / усечённая пирамида (s — доля верхнего сечения,
* крышка при s>0); правая грань затемнена, как торец box. */
private static List<Face> pyramidFaces(Color color, double u0, double u1,
double v0, double v1, double wBase, double wTop,
double s,
double rotX, double rotY, double depthScale,
double persp) {
double uc = (u0 + u1) / 2.0;
double vc = (v0 + v1) / 2.0;
double hu = (u1 - u0) / 2.0 * s;
double hv = (v1 - v0) / 2.0 * s;
double[][] base = {{u0, v0}, {u1, v0}, {u1, v1}, {u0, v1}};
double[][] top = {{uc - hu, vc - hv}, {uc + hu, vc - hv},
{uc + hu, vc + hv}, {uc - hu, vc + hv}};
List<Face> faces = new ArrayList<>();
for (int i = 0; i < 4; i++) {
int j = (i + 1) % 4;
Color c = i == 1 ? color.darker() : color;
if (s <= 0) {
faces.add(face(new double[][]{{base[i][0], base[i][1], wBase},
{base[j][0], base[j][1], wBase}, {uc, vc, wTop}},
c, rotX, rotY, depthScale, persp));
} else {
faces.add(face(new double[][]{{base[i][0], base[i][1], wBase},
{base[j][0], base[j][1], wBase},
{top[j][0], top[j][1], wTop},
{top[i][0], top[i][1], wTop}},
c, rotX, rotY, depthScale, persp));
}
}
if (s > 0) {
double[][] cap = new double[4][3];
for (int i = 0; i < 4; i++) {
cap[i] = new double[]{top[i][0], top[i][1], wTop};
}
faces.add(face(cap, color, rotX, rotY, depthScale, persp));
}
return faces;
}
/** Конус (s=0 — апекс), усечённый конус (0<s<1), цилиндр (s=1): основание —
* 12-угольник (эллипс в (u,v)), боковая лента + крышка при s>0; правая четверть
* ленты (к +u) затемнена, как торец box. */
private static List<Face> roundFaces(Color color, double u0, double u1,
double v0, double v1, double wBase, double wTop,
double s,
double rotX, double rotY, double depthScale,
double persp) {
double uc = (u0 + u1) / 2.0;
double vc = (v0 + v1) / 2.0;
double au = (u1 - u0) / 2.0;
double av = (v1 - v0) / 2.0;
List<Face> faces = new ArrayList<>();
for (int i = 0; i < ROUND_SEGMENTS; i++) {
double a0 = 2 * Math.PI * i / ROUND_SEGMENTS;
double a1 = 2 * Math.PI * (i + 1) / ROUND_SEGMENTS;
double am = (a0 + a1) / 2.0;
Color c = Math.cos(am) > Math.abs(Math.sin(am)) ? color.darker() : color;
double bx0 = uc + au * Math.cos(a0);
double by0 = vc + av * Math.sin(a0);
double bx1 = uc + au * Math.cos(a1);
double by1 = vc + av * Math.sin(a1);
if (s <= 0) {
faces.add(face(new double[][]{{bx0, by0, wBase}, {bx1, by1, wBase},
{uc, vc, wTop}}, c, rotX, rotY, depthScale, persp));
} else {
double tx0 = uc + au * s * Math.cos(a0);
double ty0 = vc + av * s * Math.sin(a0);
double tx1 = uc + au * s * Math.cos(a1);
double ty1 = vc + av * s * Math.sin(a1);
faces.add(face(new double[][]{{bx0, by0, wBase}, {bx1, by1, wBase},
{tx1, ty1, wTop}, {tx0, ty0, wTop}},
c, rotX, rotY, depthScale, persp));
}
}
if (s > 0) {
double[][] cap = new double[ROUND_SEGMENTS][3];
for (int i = 0; i < ROUND_SEGMENTS; i++) {
double a = 2 * Math.PI * i / ROUND_SEGMENTS;
cap[i] = new double[]{uc + au * s * Math.cos(a),
vc + av * s * Math.sin(a), wTop};
}
faces.add(face(cap, color, rotX, rotY, depthScale, persp));
}
return faces;
}
/** Грань с средней глубиной вершин (painter's algorithm). */
private static Face face(double[][] pts, Color color,
double rotX, double rotY, double depthScale, double persp) {
double d = 0;
for (double[] q : pts) {
d += Surface3dPainter.project(q[0], q[1], q[2],
rotX, rotY, depthScale, persp).depth();
}
return new Face(pts, color, d / pts.length);
}
/** Колонки от дальних к ближним; внутри колонки — грани по убыванию средней
* глубины вершин (painter's algorithm). */
private static void drawColumns(Graphics2D g, List<Column> columns,
double rotX, double rotY, double depthScale,
double persp, Fit fit) {
columns.sort(Comparator.comparingDouble((Column col) -> col.center.depth())
.reversed());
for (Column col : columns) {
g.setColor(col.color);
// верх: w = 1
quad(g, col, fit, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1);
// перед: v = 0 (при rotY=0 ближняя к камере сторона)
quad(g, col, fit, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1);
// торец u = max — затемнён (псевдо-свет, калибровка тестом)
g.setColor(col.color.darker());
quad(g, col, fit, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1);
}
}
/** Грань по четырём углам (u, v, w) — индексы массивов corners. */
private static void quad(Graphics2D g, Column col, Fit fit,
int u1, int v1, int w1, int u2, int v2, int w2,
int u3, int v3, int w3, int u4, int v4, int w4) {
int[] uu = {u1, u2, u3, u4};
int[] vv = {v1, v2, v3, v4};
int[] ww = {w1, w2, w3, w4};
Path2D p = new Path2D.Double();
for (int i = 0; i < 4; i++) {
double[] s = screen(col.corners[uu[i]][vv[i]][ww[i]], fit);
if (i == 0) {
p.moveTo(s[0], s[1]);
} else {
p.lineTo(s[0], s[1]);
List<Face> faces = new ArrayList<>(col.faces());
faces.sort(Comparator.comparingDouble(Face::depth).reversed());
for (Face f : faces) {
g.setColor(f.color());
Path2D p = new Path2D.Double();
for (int i = 0; i < f.pts().length; i++) {
double[] q = f.pts()[i];
double[] s = screen(proj(q[0], q[1], q[2],
rotX, rotY, depthScale, persp), fit);
if (i == 0) {
p.moveTo(s[0], s[1]);
} else {
p.lineTo(s[0], s[1]);
}
}
p.closePath();
g.fill(p);
}
}
p.closePath();
g.fill(p);
}
private static void drawLines(Graphics2D g, ChartSpec spec, List<Color> palette,
@@ -330,7 +655,9 @@ final class Cartesian3dPainter {
}
}
/** Подписи: значения — вдоль переднего левого ребра, категории — нижнего. */
/** Подписи: значения — вдоль переднего левого ребра, категории — нижнего,
* ряды — правого; c:delete (§21.2.2.38) убирает подписи оси.
* Регрессия — Cartesian3dPainterTest#bar3d_seriesAxisLabelsDrawn. */
private static void drawLabels(Graphics2D g, ChartSpec spec, List<Double> tickValues,
List<Surface3dPainter.Node> valueAnchors, int nCat,
boolean horizontal, double rotX, double rotY,
@@ -340,8 +667,10 @@ final class Cartesian3dPainter {
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec serAxis = spec.serAxis != null
? spec.serAxis : new ChartSpec.AxisSpec();
DrawMlText.Style vs = valAxis.labelStyle;
if (vs != null) {
if (vs != null && !valAxis.deleted) {
double h = DrawMlText.textHeight(vs) + 2;
for (int i = 0; i < valueAnchors.size(); i++) {
double[] p = screen(valueAnchors.get(i), fit);
@@ -353,7 +682,7 @@ final class Cartesian3dPainter {
}
}
DrawMlText.Style cs = catAxis.labelStyle;
if (cs != null) {
if (cs != null && !catAxis.deleted) {
List<String> cats = CartesianPainter.categoriesOf(spec, nCat);
double h = DrawMlText.textHeight(cs) + 2;
for (int c = 0; c < nCat; c++) {
@@ -371,6 +700,27 @@ final class Cartesian3dPainter {
new Rectangle2D.Double(p[0] - w / 2, p[1] + 8, w, h), "ctr", "t", 1.0);
}
}
// Ряды: правое нижнее ребро пола на глубине слота ряда (§21.2.2.175;
// CT_Bar3DChart/CT_Line3DChart/CT_Area3DChart несут третий axId — ось рядов).
// В горизонтальной ориентации по глубине лежат категории — подписей рядов нет.
DrawMlText.Style ss = serAxis.labelStyle;
if (ss != null && !serAxis.deleted && !horizontal) {
int nSer = spec.series.size();
double h = DrawMlText.textHeight(ss) + 2;
for (int r = 0; r < nSer; r++) {
String label = spec.series.get(r).name;
if (label == null || label.isEmpty()) {
continue;
}
Surface3dPainter.Node n = proj(0.5, vOf(r, nSer), floorW,
rotX, rotY, depthScale, persp);
double[] p = screen(n, fit);
double w = DrawMlText.textWidth(label, ss);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, ss, "l")),
new Rectangle2D.Double(p[0] + 4, p[1] - h / 2, w, h),
"l", "ctr", 1.0);
}
}
}
private static Fit fit(List<Surface3dPainter.Node> nodes, Rectangle2D box,
@@ -419,7 +769,8 @@ final class Cartesian3dPainter {
return (c + 0.5) / nCat - 0.5;
}
/** Центр слота ряда по глубине: ряды лежат полосами по всей глубине (§21.2.2.74). */
private static double vOf(int r, int nSer) {
return nSer > 1 ? (double) r / (nSer - 1) - 0.5 : 0;
return (r + 0.5) / nSer - 0.5;
}
}
@@ -55,6 +55,7 @@ import org.docx4j.dml.chart.CTView3D;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -109,6 +110,8 @@ final class ChartSpec {
final List<Double> xValues = new ArrayList<>();
/** bubble: размеры пузырей (c:bubbleSize). */
final List<Double> bubbleSizes = new ArrayList<>();
/** c:shape ряда bar3D (MS-OI29500 §2.1.1545(b)); null = дефолт диаграммы ({@link #shape3d}). */
String shape3d;
Color fillAt(int i, List<Color> palette) {
Color c = pointFills.get(i);
@@ -149,8 +152,14 @@ final class ChartSpec {
double rotX = 30;
double rotY = 0;
double depthPercent = 100;
/** CT_HPercent c:view3D/hPercent (§21.2.2.83), % от ширины области построения;
* null = элемент отсутствует → автомасштаб (MS-OI29500 §2.1.1481(a)). */
Double hPercent;
double perspective = 30;
boolean rightAngledAxes = true;
/** c:grouping 3D-групп (§21.2.2.76): standard|clustered|stacked|percentStacked;
* используют только bar3D/area3D. */
String grouping = "standard";
// Спека-параметры DrawingML, исполнение Word; дефолты — ECMA-376/Word.
// firstSliceAng (§21.2.2.68) определён только для CT_PieChart/CT_DoughnutChart;
// CT_Pie3DChart (§21.2.2.140, модель §A.5.1) его не содержит — JAXB-класс
@@ -310,6 +319,9 @@ final class ChartSpec {
if (v.getDepthPercent() != null) {
spec.depthPercent = v.getDepthPercent().getVal();
}
if (v.getHPercent() != null) {
spec.hPercent = (double) v.getHPercent().getVal();
}
if (v.getPerspective() != null) {
spec.perspective = v.getPerspective().getVal();
}
@@ -393,6 +405,9 @@ final class ChartSpec {
if (g.getGapDepth() != null) {
spec.gapDepth = g.getGapDepth().getVal();
}
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
spec.grouping = g.getGrouping().getVal().value();
}
for (org.docx4j.dml.chart.CTAreaSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
@@ -415,6 +430,9 @@ final class ChartSpec {
spec.bar3dHorizontal = g.getBarDir() != null
&& g.getBarDir().getVal() != null
&& "bar".equalsIgnoreCase(g.getBarDir().getVal().value());
if (g.getGrouping() != null && g.getGrouping().getVal() != null) {
spec.grouping = g.getGrouping().getVal().value();
}
if (g.getGapWidth() != null) {
spec.gapWidth = g.getGapWidth().getVal();
}
@@ -430,6 +448,9 @@ final class ChartSpec {
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
if (s.getShape() != null && s.getShape().getVal() != null) {
ser.shape3d = s.getShape().getVal().value();
}
spec.series.add(ser);
}
} else if (group instanceof CTRadarChart g) {
@@ -567,7 +588,11 @@ final class ChartSpec {
spec.series.add(ser);
}
if (bf != null) {
for (CTBandFmt b : bf.getBandFmt()) {
// §21.2.2.14: c:bandFmt «indexed from low to high» — порядок полос
// задаёт c:idx, а не порядок следования в XML; сортируем по idx.
List<CTBandFmt> fmts = new ArrayList<>(bf.getBandFmt());
fmts.sort(Comparator.comparingInt(b -> (int) b.getIdx().getVal()));
for (CTBandFmt b : fmts) {
Color c = b.getSpPr() != null && b.getSpPr().getSolidFill() != null
? colors.resolveFill(b.getSpPr().getSolidFill())
: null;
@@ -116,7 +116,9 @@ final class PiePainter {
// c:view3D/rotY — поворот пирога вокруг вертикали (default 0)
double rotY = -Math.toRadians(spec.rotY);
double ext = PIE_DEPTH * spec.depthPercent / 100.0 / 2.0;
double persp = spec.perspective;
// §21.2.2.136 + MS-OI29500 §2.1.1516(b): rAngAx=true → перспектива
// игнорируется (ортография), c:perspective действует только при rAngAx=false.
double persp = spec.rightAngledAxes ? 0 : spec.perspective;
double dcam = Surface3dPainter.cameraDistance(1, persp);
double minX = Double.MAX_VALUE;
@@ -112,7 +112,9 @@ final class Surface3dPainter {
// положительный поворот приближает к зрителю правый край, поэтому
// передняя кромка («Категория 1 → Категория 4») идёт вниз вправо.
double rotY = -Math.toRadians(spec.rotY);
double persp = spec.perspective;
// §21.2.2.136 + MS-OI29500 §2.1.1516(b): rAngAx=true → перспектива
// игнорируется (ортография), c:perspective действует только при rAngAx=false.
double persp = spec.rightAngledAxes ? 0 : spec.perspective;
// Пропорции «коробки» построения, снятые с эталона Word: глубина —
// DEPTH_RATIO ширины (c:view3D/depth от неё), высота значений —
@@ -129,7 +131,11 @@ final class Surface3dPainter {
double availW = Math.max(10, box.getWidth() - leftGutter - rightGutter);
double availH = Math.max(10, box.getHeight() - bottomGutter - topGutter);
double depthScale = DEPTH_RATIO * Math.max(0.05, spec.depthPercent / 100.0);
double heightScale = HEIGHT_RATIO * availH / availW;
// MS-OI29500 §2.1.1481(c): c:hPercent задан → высота значений = hPercent% от
// ширины области построения (в модельных единицах ширина u = 1.0); опущен →
// автомасштаб HEIGHT_RATIO·availH/availW (§2.1.1481(a), калибровка по эталону).
double heightScale = spec.hPercent != null
? spec.hPercent / 100.0 : HEIGHT_RATIO * availH / availW;
// 1. Узлы сетки и пол — в модельно-экранные координаты
Node[][] node = new Node[nSer][nCat];
@@ -208,6 +214,19 @@ final class Surface3dPainter {
double w01 = ((z[r + 1][c] - lo) / span - 0.5) * heightScale;
double w11 = ((z[r + 1][c + 1] - lo) / span - 0.5) * heightScale;
double w10 = ((z[r][c + 1] - lo) / span - 0.5) * heightScale;
if (spec.wireframe) {
// §21.2.2.230: «the surface chart is drawn as a wireframe» —
// только каркас без заливки (прецедент Surface2dPainter.drawWireframe);
// цвет ребра — полоса высот средней высоты ячейки, без шейдинга.
double wAvg = (w00 + w01 + w11 + w10) / 4.0;
List<Color> bands = spec.bandColors.isEmpty() ? palette : spec.bandColors;
int k = Math.max(0, Math.min(bandCount - 1, (int) Math.floor(
(wAvg - (-0.5 * heightScale)) / (spanUnit * heightScale))));
tris.add(wireQuad(u0, u1, v0, v1, w00, w01, w11, w10,
bands.get(k % bands.size()),
rotX, rotY, depthScale, persp, fit));
continue;
}
// Диагональ — та, чьи концы выше (сумма значений больше). Седловая
// ячейка в проекции вогнутая, и фиксированная диагональ даёт то
// грань не той полосы, то треугольник внутри треугольника. Word
@@ -237,17 +256,18 @@ final class Surface3dPainter {
}
}
tris.sort(Comparator.comparingDouble(Tri::depth).reversed());
BasicStroke seam = new BasicStroke(0.4f);
for (Tri t : tris) {
g.setColor(t.color());
g.fill(t.path());
g.setStroke(seam);
g.draw(t.path());
}
if (spec.wireframe) {
g.setColor(new Color(0x80, 0x80, 0x80));
g.setStroke(new BasicStroke(0.5f));
for (Tri t : tris) {
g.setColor(t.color());
g.draw(t.path());
}
} else {
BasicStroke seam = new BasicStroke(0.4f);
for (Tri t : tris) {
g.setColor(t.color());
g.fill(t.path());
g.setStroke(seam);
g.draw(t.path());
}
}
@@ -257,6 +277,29 @@ final class Surface3dPainter {
rotX, rotY, depthScale, heightScale, persp, fit);
}
/** Каркасная ячейка: контур квада в экранных координатах + глубина центроида. */
private static Tri wireQuad(double u0, double u1, double v0, double v1,
double w00, double w01, double w11, double w10,
Color color, double rotX, double rotY,
double depthScale, double persp, Fit fit) {
double[][] pts = {{u0, v0, w00}, {u0, v1, w01}, {u1, v1, w11}, {u1, v0, w10}};
Path2D path = new Path2D.Double();
double depth = 0;
for (int i = 0; i < pts.length; i++) {
Node n = project(pts[i][0], pts[i][1], pts[i][2], rotX, rotY, depthScale, persp);
double x = n.x() * fit.scaleX() + fit.offX();
double y = n.y() * fit.scaleY() + fit.offY();
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
depth += n.depth();
}
path.closePath();
return new Tri(path, color, depth / pts.length);
}
/**
* Один треугольник ячейки: нормаль (и, как следствие, затемнение) считается
* по исходному треугольнику, а сам он режется плоскостями полос высот —
@@ -416,8 +459,9 @@ final class Surface3dPainter {
project(0.5, v, floorW, rotX, rotY, depthScale, persp), fit);
}
// сетка значений: левая стенка (от переднего левого ребра в глубину)
// и дальней стенка — обе рисует Word
if (valAxis.gridlines) {
// и дальней стенка — обе рисует Word; c:delete (§21.2.2.38) убирает ось
// целиком — сетка удалённой оси не рисуется.
if (valAxis.gridlines && !valAxis.deleted) {
for (double v = lo; v <= hi + unit / 2; v += unit) {
double w = ((v - lo) / span - 0.5) * heightScale;
line(g, project(-0.5, -0.5, w, rotX, rotY, depthScale, persp),
@@ -445,7 +489,7 @@ final class Surface3dPainter {
// Ось значений: левый край дальней стенки
DrawMlText.Style vs = valAxis.labelStyle;
if (vs != null) {
if (vs != null && !valAxis.deleted) {
double h = DrawMlText.textHeight(vs) + 2;
int i = 0;
for (double v = lo; v <= hi + unit / 2; v += unit) {
@@ -464,7 +508,7 @@ final class Surface3dPainter {
// Категории: переднее нижнее ребро пола
DrawMlText.Style cs = catAxis.labelStyle;
if (cs != null) {
if (cs != null && !catAxis.deleted) {
double h = DrawMlText.textHeight(cs) + 2;
for (int c = 0; c < nCat; c++) {
String label = c < spec.categories.size() ? spec.categories.get(c) : "";
@@ -485,7 +529,7 @@ final class Surface3dPainter {
// Ряды: правое нижнее ребро пола
DrawMlText.Style ss = serAxis.labelStyle;
if (ss != null) {
if (ss != null && !serAxis.deleted) {
double h = DrawMlText.textHeight(ss) + 2;
for (int r = 0; r < nSer; r++) {
String label = spec.series.get(r).name;
@@ -12,16 +12,19 @@ import static org.junit.jupiter.api.Assertions.*;
/**
* Объёмные декартовы графики (c:bar3DChart/line3DChart/area3DChart):
* колонки — связные прогоны цвета ряда по горизонтали, линия ряда —
* пиксели цвета, стена area — полупрозрачная заливка; c:shape≠box
* рисуется как box (документированное ограничение, тест его пинит).
* пиксели цвета, стена area — полупрозрачная заливка; c:shape (cone/coneToMax/
* cylinder/pyramid/pyramidToMax) рисует свою форму, per-ser c:shape переопределяет.
* Регрессия — Cartesian3dPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
class Cartesian3dPainterTest {
private static final Color ACCENT1 = new Color(0x4472C4);
private static final Color ACCENT2 = new Color(0xED, 0x7D, 0x31);
/** accent1 с альфой 0,55 поверх белого (стена area3D). */
private static final Color FILLED = new Color(152, 178, 222);
/** accent2 с альфой 0,55 поверх белого (верхняя полоса stacked area3D). */
private static final Color FILLED2 = new Color(245, 184, 142);
/** Прогоны тоньше этого — антиалиасинг рёбер/подписей, не столбцы. */
private static final int MIN_RUN_PX = 8;
@@ -67,23 +70,288 @@ class Cartesian3dPainterTest {
"полупрозрачной стены area3D не найдено");
}
/** c:shape="cylinder" рисуется как box — документированное ограничение. */
/** c:shape="cylinder" ≠ box — рендеры различаются попиксельно. */
@Test
void shape3d_cylinderRendersAsBox() {
void shape3d_cylinderDiffersFromBox() {
ChartSpec box = bar3dSpec(3);
box.shape3d = "box";
ChartSpec cylinder = bar3dSpec(3);
cylinder.shape3d = "cylinder";
BufferedImage a = render(box);
BufferedImage b = render(cylinder);
boolean differs = false;
for (int y = 0; y < a.getHeight() && !differs; y++) {
for (int x = 0; x < a.getWidth() && !differs; x++) {
differs = a.getRGB(x, y) != b.getRGB(x, y);
}
}
assertTrue(differs, "cylinder не отличается от box");
}
/** Конус вписан в габарит бокса — краски цвета ряда меньше, чем у бокса. */
@Test
void shape3d_coneHasLessInkThanBox() {
ChartSpec box = bar3dSpec(3);
box.shape3d = "box";
ChartSpec cone = bar3dSpec(3);
cone.shape3d = "cone";
assertTrue(countColor(render(cone), ACCENT1) < countColor(render(box), ACCENT1),
"конус не тоньше бокса по заливаемым пикселям");
}
/** coneToMax при всех значениях = максимуму (t=1) — остриё, попиксельно равен cone. */
@Test
void shape3d_coneToMaxAllMaxEqualsCone() {
ChartSpec cone = bar3dSpec(3);
cone.shape3d = "cone";
ChartSpec toMax = bar3dSpec(3);
toMax.shape3d = "coneToMax";
BufferedImage a = render(cone);
BufferedImage b = render(toMax);
for (int y = 0; y < a.getHeight(); y++) {
for (int x = 0; x < a.getWidth(); x++) {
assertEquals(a.getRGB(x, y), b.getRGB(x, y),
"shape3d не должен влиять на рендер (рисуются боксы)");
"coneToMax при t=1 должен совпадать с cone");
}
}
}
/** per-ser c:shape (MS-OI29500 §2.1.1545(b)): ряд cylinder поверх chart shape=box. */
@Test
void shape3d_serShapeOverridesChart() {
ChartSpec allBox = bar3dSpec(2);
allBox.shape3d = "box";
ChartSpec.Series second = new ChartSpec.Series();
second.values.add(4.0);
second.values.add(4.0);
allBox.series.add(second);
ChartSpec overridden = bar3dSpec(2);
overridden.shape3d = "box";
ChartSpec.Series secondCylinder = new ChartSpec.Series();
secondCylinder.values.add(4.0);
secondCylinder.values.add(4.0);
secondCylinder.shape3d = "cylinder";
overridden.series.add(secondCylinder);
BufferedImage a = render(allBox);
BufferedImage b = render(overridden);
boolean differs = false;
for (int y = 0; y < a.getHeight() && !differs; y++) {
for (int x = 0; x < a.getWidth() && !differs; x++) {
differs = a.getRGB(x, y) != b.getRGB(x, y);
}
}
assertTrue(differs, "c:shape ряда не переопределяет форму диаграммы");
}
/** Горизонтальная ориентация (barDir=bar) + cylinder — остаётся box (документировано). */
@Test
void shape3d_horizontalStaysBox() {
ChartSpec box = bar3dSpec(3);
box.shape3d = "box";
box.bar3dHorizontal = true;
ChartSpec cylinder = bar3dSpec(3);
cylinder.shape3d = "cylinder";
cylinder.bar3dHorizontal = true;
BufferedImage a = render(box);
BufferedImage b = render(cylinder);
for (int y = 0; y < a.getHeight(); y++) {
for (int x = 0; x < a.getWidth(); x++) {
assertEquals(a.getRGB(x, y), b.getRGB(x, y),
"горизонтальные колонки должны оставаться боксами");
}
}
}
/** §21.2.2.76: bar3D stacked — одна колонка на категорию, в ней оба цвета рядов. */
@Test
void bar3d_stacked_singleColumnTwoColors() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR3D;
spec.legendPos = null;
spec.grouping = "stacked";
ChartSpec.Series s1 = new ChartSpec.Series();
s1.values.add(3.0);
ChartSpec.Series s2 = new ChartSpec.Series();
s2.values.add(2.0);
spec.series.add(s1);
spec.series.add(s2);
BufferedImage img = render(spec);
boolean both = false;
for (int x = 0; x < img.getWidth() && !both; x++) {
boolean has1 = false;
boolean has2 = false;
for (int y = 0; y < img.getHeight(); y++) {
int rgb = img.getRGB(x, y);
has1 |= matches(rgb, ACCENT1);
has2 |= matches(rgb, ACCENT2);
}
both = has1 && has2;
}
assertTrue(both, "в stacked-колонке нет обоих цветов рядов");
}
/** percentStacked: суммы категорий 4 и 8 — верхушки колонок на одной высоте. */
@Test
void bar3d_percentStacked_levelsTops() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR3D;
spec.legendPos = null;
spec.grouping = "percentStacked";
ChartSpec.Series s1 = new ChartSpec.Series();
s1.values.add(3.0);
s1.values.add(6.0);
ChartSpec.Series s2 = new ChartSpec.Series();
s2.values.add(1.0);
s2.values.add(2.0);
spec.series.add(s1);
spec.series.add(s2);
BufferedImage img = render(spec);
int minX = img.getWidth();
int maxX = -1;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
if (matches(img.getRGB(x, y), ACCENT2)) {
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
}
}
}
assertTrue(maxX - minX > MIN_RUN_PX, "percentStacked-колонки не нарисованы");
int top1 = topAt(img, minX + 2);
int top2 = topAt(img, maxX - 2);
assertTrue(top1 >= 0 && top2 >= 0, "верхушки колонок не найдены");
assertEquals(top1, top2, 2,
"percentStacked: верхушки колонок на разной высоте: " + top1 + " vs " + top2);
}
/** Первая сверху строка пикселя ACCENT2 в столбце x (−1 — нет). */
private static int topAt(BufferedImage img, int x) {
for (int y = 0; y < img.getHeight(); y++) {
if (matches(img.getRGB(x, y), ACCENT2)) {
return y;
}
}
return -1;
}
/** §21.2.2.76: area3D stacked — на стене v=0 полосы обоих рядов. */
@Test
void area3d_stacked_bothBandsPresent() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.AREA3D;
spec.legendPos = null;
spec.grouping = "stacked";
ChartSpec.Series s1 = new ChartSpec.Series();
s1.values.add(2.0);
s1.values.add(3.0);
s1.values.add(2.5);
ChartSpec.Series s2 = new ChartSpec.Series();
s2.values.add(1.0);
s2.values.add(1.5);
s2.values.add(1.0);
spec.series.add(s1);
spec.series.add(s2);
BufferedImage img = render(spec);
assertTrue(countColor(img, FILLED) > 200, "нижняя полоса ряда 1 не нарисована");
assertTrue(countColor(img, FILLED2) > 200, "верхняя полоса ряда 2 не нарисована");
}
/** line3D + grouping=stacked — игнорируется (Word UI не предлагает 3-D Stacked Line):
* рендер попиксельно равен стандартному. */
@Test
void line3d_stackedGroupingIgnored() {
ChartSpec std = new ChartSpec();
std.type = ChartSpec.Type.LINE3D;
std.legendPos = null;
ChartSpec.Series s = new ChartSpec.Series();
s.values.add(1.0);
s.values.add(3.0);
s.values.add(2.0);
std.series.add(s);
ChartSpec stk = new ChartSpec();
stk.type = ChartSpec.Type.LINE3D;
stk.legendPos = null;
stk.grouping = "stacked";
ChartSpec.Series s2 = new ChartSpec.Series();
s2.values.add(1.0);
s2.values.add(3.0);
s2.values.add(2.0);
stk.series.add(s2);
BufferedImage a = render(std);
BufferedImage b = render(stk);
for (int y = 0; y < a.getHeight(); y++) {
for (int x = 0; x < a.getWidth(); x++) {
assertEquals(a.getRGB(x, y), b.getRGB(x, y),
"line3D не должен реагировать на c:grouping");
}
}
}
/** rAngAx=true (§21.2.2.136, MS-OI29500 §2.1.1516(b)) — c:perspective игнорируется:
* рендер perspective=30 попиксельно равен perspective=0; при rAngAx=false — различаются. */
@Test
void rAngAxTrue_perspectiveIgnored() {
ChartSpec a = bar3dSpec(3);
a.rightAngledAxes = true;
a.perspective = 30;
ChartSpec b = bar3dSpec(3);
b.rightAngledAxes = true;
b.perspective = 0;
BufferedImage ia = render(a);
BufferedImage ib = render(b);
for (int y = 0; y < ia.getHeight(); y++) {
for (int x = 0; x < ia.getWidth(); x++) {
assertEquals(ia.getRGB(x, y), ib.getRGB(x, y),
"при rAngAx=true c:perspective должен игнорироваться");
}
}
ChartSpec c = bar3dSpec(3);
c.rightAngledAxes = false;
c.perspective = 30;
ChartSpec d = bar3dSpec(3);
d.rightAngledAxes = false;
d.perspective = 0;
assertNotEquals(countColor(render(d), ACCENT1), countColor(render(c), ACCENT1),
"при rAngAx=false перспектива должна влиять на силуэт");
}
/** MS-OI29500 §2.1.1474(a): c:gapDepth — зазор полос рядов в глубину;
* больше зазор — тоньше колонка, меньше пикселей цвета ряда. */
@Test
void gapDepth_widerGapThinsColumns() {
ChartSpec tight = bar3dSpec(3);
tight.gapDepth = 0;
ChartSpec def = bar3dSpec(3);
ChartSpec wide = bar3dSpec(3);
wide.gapDepth = 400;
long tightPx = countColor(render(tight), ACCENT1);
long defPx = countColor(render(def), ACCENT1);
long widePx = countColor(render(wide), ACCENT1);
assertTrue(tightPx > defPx && defPx > widePx,
"c:gapDepth не управляет толщиной колонки: "
+ tightPx + "/" + defPx + "/" + widePx);
}
/** Подписи оси рядов (c:serAx, §21.2.2.175) — рисуются у bar3D для именованных рядов. */
@Test
void bar3d_seriesAxisLabelsDrawn() {
Color labelColor = new Color(0x59, 0x59, 0x59);
ChartSpec spec = bar3dSpec(2);
spec.series.get(0).name = "Ряд 1";
ChartSpec.Series s2 = new ChartSpec.Series();
s2.name = "Ряд 2";
s2.values.add(4.0);
s2.values.add(4.0);
spec.series.add(s2);
spec.serAxis = new ChartSpec.AxisSpec();
spec.serAxis.labelStyle = new DrawMlText.Style(9, false, false, labelColor, "carlito");
long labeled = countColor(render(spec), labelColor);
spec.series.get(0).name = null;
spec.series.get(1).name = null;
long bare = countColor(render(spec), labelColor);
assertTrue(labeled > bare, "подписи оси рядов не рисуются");
}
private static ChartSpec bar3dSpec(int nCat) {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR3D;
@@ -84,9 +84,14 @@ import org.docx4j.dml.chart.CTUpDownBar;
import org.docx4j.dml.chart.CTUpDownBars;
import org.docx4j.dml.chart.CTUnsignedInt;
import org.docx4j.dml.chart.CTValAx;
import org.docx4j.dml.chart.CTBarGrouping;
import org.docx4j.dml.chart.CTGrouping;
import org.docx4j.dml.chart.CTHPercent;
import org.docx4j.dml.chart.CTView3D;
import org.docx4j.dml.chart.STAxPos;
import org.docx4j.dml.chart.STBarDir;
import org.docx4j.dml.chart.STBarGrouping;
import org.docx4j.dml.chart.STGrouping;
import org.docx4j.dml.chart.STOfPieType;
import org.docx4j.dml.chart.STMarkerStyle;
import org.docx4j.dml.chart.STRadarStyle;
@@ -268,6 +273,20 @@ class ChartSpecTest {
assertFalse(spec.rightAngledAxes);
}
/** c:view3D/c:hPercent задан — парсится (MS-OI29500 §2.1.1481(c): высота = hPercent%
* от ширины); без элемента остаётся null → автомасштаб. */
@Test
void view3DHPercent_parsed() {
CTChart chart = new CTChart();
CTView3D v = new CTView3D();
CTHPercent hp = new CTHPercent();
hp.setVal(80);
v.setHPercent(hp);
chart.setView3D(v);
ChartSpec spec = ChartSpec.parse(spaceWith(chart), new DrawMlColor(null));
assertEquals(80.0, spec.hPercent);
}
@Test
void horizontalBarDirectionParsed() {
CTBarChart bar = new CTBarChart();
@@ -465,6 +484,30 @@ class ChartSpecTest {
assertEquals(List.of(new Color(0xAB, 0xCD, 0xEF), Color.GREEN), spec.bandColors);
}
/** §21.2.2.14: порядок полос задаёт c:idx, а не порядок в XML — bandFmts
* вразнобар (idx 1,0) сортируются, bandColors = [цвет idx0, цвет idx1]. */
@Test
void bandFmts_sortedByIdx() {
CTSurface3DChart surf = new CTSurface3DChart();
CTBandFmts fmts = new CTBandFmts();
CTBandFmt idx1 = new CTBandFmt();
idx1.setIdx(uint(1));
CTShapeProperties sp1 = new CTShapeProperties();
sp1.setSolidFill(fill("00FF00"));
idx1.setSpPr(sp1);
CTBandFmt idx0 = new CTBandFmt();
idx0.setIdx(uint(0));
CTShapeProperties sp0 = new CTShapeProperties();
sp0.setSolidFill(fill("FF0000"));
idx0.setSpPr(sp0);
fmts.getBandFmt().add(idx1);
fmts.getBandFmt().add(idx0);
surf.setBandFmts(fmts);
ChartSpec spec = new ChartSpec();
ChartSpec.readGroup(surf, spec, new DrawMlColor(null), List.of());
assertEquals(List.of(new Color(0xFF, 0, 0), new Color(0, 0xFF, 0)), spec.bandColors);
}
/** c:dPt без c:spPr/c:solidFill пропускается, валидная точка получает цвет. */
@Test
void dataPointFillAppliedAndIncompleteSkipped() {
@@ -811,6 +854,7 @@ class ChartSpecTest {
assertEquals(30, spec.rotX);
assertEquals(0, spec.rotY);
assertTrue(spec.rightAngledAxes);
assertNull(spec.hPercent, "без c:hPercent — автомасштаб");
}
/** c:marker без c:symbol — маркер есть, символ не задан; symbol=circle — маркер есть. */
@@ -1346,6 +1390,36 @@ class ChartSpecTest {
assertEquals(150, lineSpec.gapDepth, "без c:gapDepth — дефолт 150");
}
/** bar3D: c:grouping (CT_BarGrouping) и per-ser c:shape (MS-OI29500 §2.1.1545(b)). */
@Test
void bar3dGroupingAndSerShape_parsed() {
CTBar3DChart bar = new CTBar3DChart();
CTBarGrouping gr = new CTBarGrouping();
gr.setVal(STBarGrouping.STACKED);
bar.setGrouping(gr);
CTBarSer s = new CTBarSer();
CTShape shape = new CTShape();
shape.setVal(STShape.CYLINDER);
s.setShape(shape);
bar.getSer().add(s);
ChartSpec spec = new ChartSpec();
ChartSpec.readGroup(bar, spec, new DrawMlColor(null), List.of());
assertEquals("stacked", spec.grouping);
assertEquals("cylinder", spec.series.get(0).shape3d);
}
/** area3D: c:grouping (CT_Grouping) парсится. */
@Test
void area3dGrouping_parsed() {
CTArea3DChart area = new CTArea3DChart();
CTGrouping gr = new CTGrouping();
gr.setVal(STGrouping.PERCENT_STACKED);
area.setGrouping(gr);
ChartSpec spec = new ChartSpec();
ChartSpec.readGroup(area, spec, new DrawMlColor(null), List.of());
assertEquals("percentStacked", spec.grouping);
}
/** Автозаголовок OF_PIE — имя ряда (круговая семантика, как PIE). */
@Test
void autoTitleOfPieUsesSeriesName() {
@@ -208,6 +208,8 @@ class PiePainterTest {
spec.type = ChartSpec.Type.PIE3D;
spec.title = "Продажи";
spec.legendPos = "b";
// эталонный Word-документ написан с rAngAx=0 — иначе перспектива игнорируется (§21.2.2.136)
spec.rightAngledAxes = false;
ChartSpec.Series s = new ChartSpec.Series();
s.name = "Продажи";
for (double v : new double[]{8.2, 3.2, 1.4, 1.2}) {
@@ -318,6 +320,30 @@ class PiePainterTest {
assertNotEquals(orthoPx, perspPx, "перспектива не влияет на силуэт");
}
/** rAngAx=true (§21.2.2.136, MS-OI29500 §2.1.1516(b)) — c:perspective игнорируется. */
@Test
void rAngAxTrue_perspectiveIgnored() {
DrawMlColor colors = new DrawMlColor(null);
ChartSpec a = pie3dSpec();
a.rightAngledAxes = true;
a.perspective = 30;
ChartSpec b = pie3dSpec();
b.rightAngledAxes = true;
b.perspective = 0;
assertArrayEquals(toArray(ChartRenderer.render(b, 219.23, 149.08, colors)),
toArray(ChartRenderer.render(a, 219.23, 149.08, colors)),
"при rAngAx=true c:perspective должен игнорироваться");
ChartSpec c = pie3dSpec();
c.rightAngledAxes = false;
c.perspective = 30;
ChartSpec d = pie3dSpec();
d.rightAngledAxes = false;
d.perspective = 0;
assertNotEquals(countSaturated(ChartRenderer.render(d, 219.23, 149.08, colors)),
countSaturated(ChartRenderer.render(c, 219.23, 149.08, colors)),
"при rAngAx=false перспектива должна влиять на силуэт");
}
/** rotY=180: пирог развёрнут — торцы на месте, картинка отличается от rotY=0. */
@Test
void pie3dRotY180FlipsEndFaceOwner() {
@@ -436,6 +436,8 @@ class Surface3dPainterTest {
spec.rotX = 15;
spec.rotY = 20;
spec.perspective = 30;
// эталонный Word-документ написан с rAngAx=0 — иначе перспектива игнорируется (§21.2.2.136)
spec.rightAngledAxes = false;
spec.depthPercent = 100;
addSeries(spec, "Ряд 1", 4.3, 2.5, 3.5, 4.5);
addSeries(spec, "Ряд 2", 2.4, 4.4, 1.8, 2.8);
@@ -494,15 +496,19 @@ class Surface3dPainterTest {
"оборванный ряд должен рисоваться как дополненный нулями");
}
/** c:wireframe — поверх граней серая сетка рёбер. */
/** §21.2.2.230: c:wireframe — только каркас, без заливки граней: залитых
* пикселей резко меньше, чем у сплошной, но сам каркас на месте. */
@Test
void wireframeAddsSeams() {
void wireframe_noFillOnlyMesh() {
ChartSpec spec = surfaceSpec();
BufferedImage solid = paintSurface(spec);
spec.wireframe = true;
BufferedImage wire = paintSurface(spec);
assertTrue(countDarkGray(wire) > countDarkGray(solid),
"c:wireframe не добавил каркас");
int solidPx = painted(solid);
int wirePx = painted(wire);
assertTrue(wirePx > 100, "каркас не нарисован: " + wirePx);
assertTrue(wirePx < solidPx / 2,
"wireframe не убрал заливку: " + wirePx + " vs " + solidPx);
}
/** gridlines=false — напольной/стеновой сетки нет. */
@@ -556,6 +562,56 @@ class Surface3dPainterTest {
assertNotEquals(ortho, persp, "перспектива не влияет на силуэт");
}
/** rAngAx=true (§21.2.2.136, MS-OI29500 §2.1.1516(b)) — c:perspective игнорируется:
* рендер perspective=30 попиксельно равен perspective=0; при rAngAx=false — различаются. */
@Test
void rAngAxTrue_perspectiveIgnored() {
ChartSpec a = surfaceSpec();
a.rightAngledAxes = true;
a.perspective = 30;
ChartSpec b = surfaceSpec();
b.rightAngledAxes = true;
b.perspective = 0;
assertArrayEquals(toArray(paintSurface(b)), toArray(paintSurface(a)),
"при rAngAx=true c:perspective должен игнорироваться");
ChartSpec c = surfaceSpec();
c.rightAngledAxes = false;
c.perspective = 30;
ChartSpec d = surfaceSpec();
d.rightAngledAxes = false;
d.perspective = 0;
assertNotEquals(painted(paintSurface(d)), painted(paintSurface(c)),
"при rAngAx=false перспектива должна влиять на силуэт");
}
/** c:hPercent задан (MS-OI29500 §2.1.1481(c)): высота = hPercent% от ширины.
* Вписка равномерная, поэтому признак — аспект небелого bbox (высота/ширина):
* при 100 он заметно больше, чем при 50. */
@Test
void hPercent_explicitScalesHeight() {
ChartSpec tall = surfaceSpec();
tall.hPercent = 100.0;
ChartSpec low = surfaceSpec();
low.hPercent = 50.0;
double aTall = aspect(paintSurface(tall));
double aLow = aspect(paintSurface(low));
assertTrue(aTall > aLow * 1.3,
"c:hPercent не масштабирует высоту относительно ширины: "
+ aTall + " vs " + aLow);
}
/** c:delete=true (§21.2.2.38) — подписи удалённой оси значений не рисуются. */
@Test
void deletedAxis_hidesLabels() {
ChartSpec spec = surfaceSpec();
spec.valAxis.labelStyle = new DrawMlText.Style(9, false, false,
new Color(0x59, 0x59, 0x59), "carlito");
int with = painted(paintSurface(spec));
spec.valAxis.deleted = true;
int without = painted(paintSurface(spec));
assertTrue(without < with, "подписи удалённой оси значений остались");
}
private static BufferedImage paintSurface(ChartSpec spec) {
BufferedImage img = new BufferedImage(700, 400, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
@@ -586,26 +642,6 @@ class Surface3dPainterTest {
return n;
}
/** Каркасные рёбра 0x808080. */
private static int countDarkGray(BufferedImage img) {
int n = 0;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
int argb = img.getRGB(x, y);
if (((argb >>> 24) & 0xFF) < PAINTED_ALPHA_MIN) {
continue;
}
Color c = new Color(argb);
int spread = Math.max(Math.max(c.getRed(), c.getGreen()), c.getBlue())
- Math.min(Math.min(c.getRed(), c.getGreen()), c.getBlue());
if (spread <= 15 && Math.abs(c.getRed() - 0x80) <= 25) {
n++;
}
}
}
return n;
}
/** Линии сетки 0xD9D9D9. */
private static int countLightGray(BufferedImage img) {
int n = 0;
@@ -631,4 +667,29 @@ class Surface3dPainterTest {
img.getRGB(0, 0, img.getWidth(), img.getHeight(), a, 0, img.getWidth());
return a;
}
/** Аспект небелого bbox: высота/ширина по залитым пикселям. */
private static double aspect(BufferedImage img) {
int minX = Integer.MAX_VALUE;
int maxX = -1;
int minY = Integer.MAX_VALUE;
int maxY = -1;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
int argb = img.getRGB(x, y);
if (((argb >>> 24) & 0xFF) < PAINTED_ALPHA_MIN) {
continue;
}
Color c = new Color(argb);
if (c.getRed() > 245 && c.getGreen() > 245 && c.getBlue() > 245) {
continue;
}
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
}
return maxY < 0 ? 0 : (double) (maxY - minY + 1) / (maxX - minX + 1);
}
}