chart: ofPie по Word — «Other»-сектор, две связи c:serLines, центрирование пары #46

Merged
pjandro merged 1 commits from fix/ofpie-secondary-pie into main 2026-10-25 19:25:00 +03:00
6 changed files with 359 additions and 80 deletions
Showing only changes of commit 3d77cc5034 - Show all commits
+3 -3
View File
File diff suppressed because one or more lines are too long
@@ -18,8 +18,9 @@ import java.util.Set;
* MS-OI29500 §2.1.1554a/b): auto/pos — последние ceil(n/3) (или splitPos) * MS-OI29500 §2.1.1554a/b): auto/pos — последние ceil(n/3) (или splitPos)
* точек, val/percent — точки ниже splitPos, cust — c:secondPiePt. * точек, val/percent — точки ниже splitPos, cust — c:secondPiePt.
* Вторичных точек нет → обычная круговая через {@link PiePainter}. * Вторичных точек нет → обычная круговая через {@link PiePainter}.
* c:serLines — связи от обода главного пирога (эффективный угол точки в * «Other»-сектор (MS-OI29500 §2.1.1507(a)) замыкает главный пирог и обращён к
* «хвостовом» секторе) до середины вторичного сектора/сегмента. * вторичной диаграмме; c:serLines — ровно две связи от границ «Other»-сектора
* к вторичному пирогу/столбцу (MS-OI29500 §2.1.1545(a)).
* *
* Регрессия — OfPiePainterTest, фикстура samples/chart-types.docx * Регрессия — OfPiePainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages). * (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
@@ -32,6 +33,10 @@ final class OfPiePainter {
/** Доля области построения под диаметр главного пирога (Word-эмпирика). */ /** Доля области построения под диаметр главного пирога (Word-эмпирика). */
private static final double MAIN_FIT = 0.72; private static final double MAIN_FIT = 0.72;
/** Зазор между пирогами как доля диаметра главного (Word-эмпирика,
* калибровка — OfPiePainterTest). */
private static final double GAP_FIT = 0.25;
/** c:ofPieType="bar" — вторичная часть столбчатая (§21.2.2.134). */ /** c:ofPieType="bar" — вторичная часть столбчатая (§21.2.2.134). */
private static final String SECONDARY_BAR = "bar"; private static final String SECONDARY_BAR = "bar";
@@ -58,50 +63,64 @@ final class OfPiePainter {
return; return;
} }
double totalSecondary = 0;
for (int i : secondary) {
totalSecondary += s.values.get(i);
}
double wedgeSweep = 360.0 * totalSecondary / total;
double primarySweep = 360.0 - wedgeSweep;
// «Other»-сектор обращён к вторичной диаграмме (центр — 3 часа);
// MS-OI29500 §2.1.1507(a). Для OF_PIE firstSliceAng всегда 0 —
// CT_OfPieChart (§A.5.1) не содержит c:firstSliceAng; слагаемое
// оставлено для аддитивной семантики.
double mainStart = spec.firstSliceAng + 90.0 - primarySweep - wedgeSweep / 2.0;
double d1 = MAIN_FIT * Math.min(box.getWidth(), box.getHeight()); double d1 = MAIN_FIT * Math.min(box.getWidth(), box.getHeight());
double d2 = d1 * spec.secondPieSize / 100.0; double d2 = d1 * spec.secondPieSize / 100.0;
double gap = 0.10 * d1; double gap = GAP_FIT * d1;
if (d1 + gap + d2 > box.getWidth()) { if (d1 + gap + d2 > box.getWidth()) {
double k = box.getWidth() / (d1 + gap + d2); double k = box.getWidth() / (d1 + gap + d2);
d1 *= k; d1 *= k;
d2 *= k; d2 *= k;
gap *= k; gap *= k;
} }
// Пара пирогов центрирована горизонтально (как в Word).
double cy = box.getY() + box.getHeight() / 2.0; double cy = box.getY() + box.getHeight() / 2.0;
double cx1 = box.getX() + d1 / 2.0; double startX = box.getX() + (box.getWidth() - (d1 + gap + d2)) / 2.0;
double cx2 = box.getX() + d1 + gap + d2 / 2.0; double cx1 = startX + d1 / 2.0;
double cx2 = startX + d1 + gap + d2 / 2.0;
double secondaryLeft = startX + d1 + gap;
double totalSecondary = 0; // Главный пирог: первичные точки от mainStart, затем «Other»-сектор
for (int i : secondary) { // (MS-OI29500 §2.1.1507(a)); цвет — следующий в ротации палитры за
totalSecondary += s.values.get(i); // последней точкой (Word — tint-последовательность поверх accent1..6,
} // палитра конвертера плоская — ближайшее приближение).
// Регрессия — OfPiePainterTest#otherSlice_mainPieClosed.
// Главный пирог: только первичные точки, углы от c:firstSliceAng. double angle = mainStart;
double angle = spec.firstSliceAng;
double primarySweep = 0;
for (int i = 0; i < s.values.size(); i++) { for (int i = 0; i < s.values.size(); i++) {
Double v = s.values.get(i); Double v = s.values.get(i);
if (v == null || v <= 0 || secondary.contains(i)) { if (v == null || v <= 0 || secondary.contains(i)) {
continue; continue;
} }
double sweep = 360.0 * v / total; double sweep = 360.0 * v / total;
drawSector(g, s, i, palette, cx1, cy, d1 / 2.0, angle, sweep); drawSector(g, s.fillAt(i, palette), s, cx1, cy, d1 / 2.0, angle, sweep);
angle += sweep; angle += sweep;
primarySweep += sweep;
} }
Color otherFill = s.fill != null ? s.fill
: palette.get(s.values.size() % palette.size());
drawSector(g, otherFill, s, cx1, cy, d1 / 2.0, angle, wedgeSweep);
double secondaryLeft = box.getX() + d1 + gap;
if (SECONDARY_BAR.equalsIgnoreCase(spec.ofPieType)) { if (SECONDARY_BAR.equalsIgnoreCase(spec.ofPieType)) {
drawSecondaryBar(g, s, palette, secondary, totalSecondary, drawSecondaryBar(g, s, palette, secondary, totalSecondary,
secondaryLeft, cy, d1, d2); secondaryLeft, cy, d1, d2);
} else { } else {
drawSecondaryPie(g, spec, s, palette, secondary, totalSecondary, drawSecondaryPie(g, s, palette, secondary, totalSecondary,
cx2, cy, d2); cx2, cy, d2, mainStart);
} }
if (spec.serLines) { if (spec.serLines) {
drawSerLines(g, spec, s, secondary, total, totalSecondary, drawSerLines(g, spec, cx1, cy, d1, cx2, d2, secondaryLeft,
primarySweep, cx1, cy, d1, cx2, cy, d2, secondaryLeft); mainStart, primarySweep, wedgeSweep);
} }
} }
@@ -153,14 +172,20 @@ final class OfPiePainter {
return out; return out;
} }
private static void drawSecondaryPie(Graphics2D g, ChartSpec spec, ChartSpec.Series s, /**
* Вторичный пирог: сектора в порядке индексов от эффективного угла
* главного пирога (= конец «Other»-сектора, 90° + wedgeSweep/2) — замер
* по эталону Excel. Регрессия —
* OfPiePainterTest#secondaryPie_slicesInDataOrderFromWedgeEnd.
*/
private static void drawSecondaryPie(Graphics2D g, ChartSpec.Series s,
List<Color> palette, Set<Integer> secondary, List<Color> palette, Set<Integer> secondary,
double totalSecondary, double cx, double cy, double totalSecondary, double cx, double cy,
double d2) { double d2, double startDeg) {
double angle = spec.firstSliceAng; double angle = startDeg;
for (int i : orderedIndices(secondary)) { for (int i : orderedIndices(secondary)) {
double sweep = 360.0 * s.values.get(i) / totalSecondary; double sweep = 360.0 * s.values.get(i) / totalSecondary;
drawSector(g, s, i, palette, cx, cy, d2 / 2.0, angle, sweep); drawSector(g, s.fillAt(i, palette), s, cx, cy, d2 / 2.0, angle, sweep);
angle += sweep; angle += sweep;
} }
} }
@@ -181,56 +206,46 @@ final class OfPiePainter {
} }
/** /**
* Связи c:serLines: от обода главного пирога на эффективном угле точки * Связи c:serLines: ровно две линии от границ «Other»-сектора главного
* (первичные сектора + накопленная доля вторичных в «хвостовом» секторе) * пирога к вторичной диаграмме (MS-OI29500 §2.1.1545(a) — «the series
* до внешней середины её вторичного сектора/сегмента. * lines connect the secondary pie or column to the other slice»). Для
* pie — к ободу вторичного на 270°±wedgeSweep (полуразнос относительно
* 9 часов — Word-эмпирика); для bar — к левым верхнему/нижнему углам
* столбца. Регрессия — OfPiePainterTest#serLines_twoConnectors.
*/ */
private static void drawSerLines(Graphics2D g, ChartSpec spec, ChartSpec.Series s, private static void drawSerLines(Graphics2D g, ChartSpec spec,
Set<Integer> secondary, double total, double cx1, double cy, double d1,
double totalSecondary, double primarySweep, double cx2, double d2, double secondaryLeft,
double cx1, double cy1, double d1, double mainStart, double primarySweep,
double cx2, double cy2, double d2, double wedgeSweep) {
double secondaryLeft) {
g.setColor(SER_LINE_COLOR); g.setColor(SER_LINE_COLOR);
g.setStroke(new BasicStroke(0.75f)); g.setStroke(new BasicStroke(0.75f));
boolean bar = "bar".equalsIgnoreCase(spec.ofPieType); double r1 = Math.toRadians(mainStart + primarySweep);
double wedgeWidth = 360.0 * totalSecondary / total; double r2 = Math.toRadians(mainStart + primarySweep + wedgeSweep);
double acc = 0; double x1 = cx1 + d1 / 2.0 * Math.sin(r1);
double secAngle = spec.firstSliceAng; double y1 = cy - d1 / 2.0 * Math.cos(r1);
double stackTop = cy2 - d1 / 2.0; double x2 = cx1 + d1 / 2.0 * Math.sin(r2);
double w = d2 / 2.0; double y2 = cy - d1 / 2.0 * Math.cos(r2);
for (int i : orderedIndices(secondary)) { if (SECONDARY_BAR.equalsIgnoreCase(spec.ofPieType)) {
double share = s.values.get(i) / totalSecondary; g.draw(new Line2D.Double(x1, y1, secondaryLeft, cy - d1 / 2.0));
double mainAngle = spec.firstSliceAng + primarySweep g.draw(new Line2D.Double(x2, y2, secondaryLeft, cy + d1 / 2.0));
+ (acc + share / 2.0) * wedgeWidth;
double mrad = Math.toRadians(mainAngle);
double mx = cx1 + d1 / 2.0 * Math.sin(mrad);
double my = cy1 - d1 / 2.0 * Math.cos(mrad);
double tx;
double ty;
if (bar) {
double h = d1 * share;
tx = secondaryLeft + w;
ty = stackTop + h / 2.0;
stackTop += h;
} else { } else {
double mid = Math.toRadians(secAngle + 360.0 * share / 2.0); double t1 = Math.toRadians(270.0 + wedgeSweep);
tx = cx2 + d2 / 2.0 * Math.sin(mid); double t2 = Math.toRadians(270.0 - wedgeSweep);
ty = cy2 - d2 / 2.0 * Math.cos(mid); g.draw(new Line2D.Double(x1, y1,
} cx2 + d2 / 2.0 * Math.sin(t1), cy - d2 / 2.0 * Math.cos(t1)));
secAngle += 360.0 * share; g.draw(new Line2D.Double(x2, y2,
acc += share; cx2 + d2 / 2.0 * Math.sin(t2), cy - d2 / 2.0 * Math.cos(t2)));
g.draw(new Line2D.Double(mx, my, tx, ty));
} }
} }
/** Один сектор: углы Word — от 12 часов по часовой, обводка как у PiePainter. */ /** Один сектор: углы Word — от 12 часов по часовой, обводка как у PiePainter. */
private static void drawSector(Graphics2D g, ChartSpec.Series s, int i, private static void drawSector(Graphics2D g, Color fill, ChartSpec.Series s,
List<Color> palette, double cx, double cy, double cx, double cy, double radius,
double radius, double startDeg, double sweepDeg) { double startDeg, double sweepDeg) {
Arc2D.Double arc = new Arc2D.Double(cx - radius, cy - radius, 2 * radius, 2 * radius, Arc2D.Double arc = new Arc2D.Double(cx - radius, cy - radius, 2 * radius, 2 * radius,
90.0 - startDeg, -sweepDeg, Arc2D.PIE); 90.0 - startDeg, -sweepDeg, Arc2D.PIE);
g.setColor(s.fillAt(i, palette)); g.setColor(fill);
g.fill(arc); g.fill(arc);
Color outline = s.outlineNoFill ? null Color outline = s.outlineNoFill ? null
: s.outlineColor != null ? s.outlineColor : Color.WHITE; : s.outlineColor != null ? s.outlineColor : Color.WHITE;
@@ -11,9 +11,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
/** /**
* Генератор фикстуры {@code samples/chart-types.docx}: 10 диаграмм: 9 типов, * Генератор фикстуры {@code samples/chart-types.docx}: 11 диаграмм: 9 типов,
* которых POI не пишет (scatter, bubble, radar, stock, ofPie, bar3D, * которых POI не пишет (scatter, bubble, radar, stock, ofPie, bar3D,
* area3D, line3D, surface2D), + lineChart с c:grouping=stacked — chart-XML * area3D, line3D, surface2D), + ofPie pie-вариант + lineChart с
* c:grouping=stacked — chart-XML
* литералами по ECMA-376 §21.2 * литералами по ECMA-376 §21.2
* (фикстура проходит docs/standards/validate-fixtures.py). Регрессия — * (фикстура проходит docs/standards/validate-fixtures.py). Регрессия —
* WordPdfConverterTest#chartTypes_allTypesRenderAsImages. * WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
@@ -37,7 +38,8 @@ public final class ChartTypesDocxGenerator {
List<String> titles = List.of( List<String> titles = List.of(
"Точечная", "Пузырьковая", "Лепестковая", "Биржевая", "Точечная", "Пузырьковая", "Лепестковая", "Биржевая",
"Кольцевая-доля", "Объёмная с столбцами", "Объёмная с областями", "Кольцевая-доля", "Объёмная с столбцами", "Объёмная с областями",
"Объёмная с линиями", "Поверхность", "График с накоплением"); "Объёмная с линиями", "Поверхность", "График с накоплением",
"Вторичная круговая");
List<String> charts = new ArrayList<>(); List<String> charts = new ArrayList<>();
charts.add(scatter()); charts.add(scatter());
charts.add(bubble()); charts.add(bubble());
@@ -49,6 +51,7 @@ public final class ChartTypesDocxGenerator {
charts.add(line3d()); charts.add(line3d());
charts.add(surface()); charts.add(surface());
charts.add(stackedLine()); charts.add(stackedLine());
charts.add(ofPiePie());
StringBuilder body = new StringBuilder(); StringBuilder body = new StringBuilder();
body.append("<w:p><w:r><w:t>Типы диаграмм</w:t></w:r></w:p>"); body.append("<w:p><w:r><w:t>Типы диаграмм</w:t></w:r></w:p>");
@@ -171,6 +174,15 @@ public final class ChartTypesDocxGenerator {
+ "</c:ofPieChart>"; + "</c:ofPieChart>";
} }
private static String ofPiePie() {
return "<c:ofPieChart><c:ofPieType val=\"pie\"/><c:varyColors val=\"1\"/>"
+ ser("Доли", cat("Север", "Юг", "Восток", "Запад", "Центр"),
num("40", "25", "18", "10", "7"))
+ "<c:splitType val=\"pos\"/><c:splitPos val=\"2\"/>"
+ "<c:serLines/>"
+ "</c:ofPieChart>";
}
private static String bar3d() { private static String bar3d() {
return "<c:bar3DChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/><c:varyColors val=\"0\"/>" return "<c:bar3DChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/><c:varyColors val=\"0\"/>"
+ ser("План", cat("Q1", "Q2", "Q3"), num("5", "9", "7")) + ser("План", cat("Q1", "Q2", "Q3"), num("5", "9", "7"))
@@ -171,9 +171,10 @@ class WordPdfConverterTest {
/** /**
* Фикстура chart-types.docx (создана вручную, chart-XML литералами — POI * Фикстура chart-types.docx (создана вручную, chart-XML литералами — POI
* эти типы не пишет): все десять типов — точечная, пузырьковая, * эти типы не пишет): все одиннадцать — точечная, пузырьковая,
* лепестковая, биржевая, кольцевая-доля, три объёмных декартовых, * лепестковая, биржевая, кольцевая-доля, три объёмных декартовых,
* поверхность и график с накоплением (c:grouping=stacked, §21.2.2.76) — * поверхность, график с накоплением (c:grouping=stacked, §21.2.2.76)
* и pie-вариант кольцевой-доли (c:ofPieType="pie") —
* рендерятся в растр, а не удаляются с warn. * рендерятся в растр, а не удаляются с warn.
* Регрессия — WordPdfConverterTest#chartTypes_allTypesRenderAsImages. * Регрессия — WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
*/ */
@@ -183,8 +184,8 @@ class WordPdfConverterTest {
String text = norm(pdfText(pdf)); String text = norm(pdfText(pdf));
assertTrue(text.contains("Типы диаграмм"), "пропал текст: " + text); assertTrue(text.contains("Типы диаграмм"), "пропал текст: " + text);
assertEquals(10, distinctImageCount(pdf), assertEquals(11, distinctImageCount(pdf),
"каждый из 10 графиков должен стать PNG-вставкой"); "каждый из 11 графиков должен стать PNG-вставкой");
} }
/** /**
@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -18,10 +19,15 @@ class OfPiePainterTest {
private static final Color ACCENT1 = new Color(0x4472C4); private static final Color ACCENT1 = new Color(0x4472C4);
private static final Color ACCENT2 = new Color(0xED7D31); private static final Color ACCENT2 = new Color(0xED7D31);
private static final Color ACCENT4 = new Color(0xFF, 0xC0, 0x00);
private static final Color ACCENT5 = new Color(0x5B, 0x9B, 0xD5);
/** «Цветной» px — разброс каналов (как в пиксельных тестах chart-пейнтеров). */ /** «Цветной» px — разброс каналов (как в пиксельных тестах chart-пейнтеров). */
private static final int GRAY_MAX_SPREAD = 25; private static final int GRAY_MAX_SPREAD = 25;
/** Склейка разорванных антиалиасингом интервалов одного объекта (px). */
private static final int MERGE_GAP_PX = 3;
/** cust-разбиение: заданные точки — во вторичном кластере справа. */ /** cust-разбиение: заданные точки — во вторичном кластере справа. */
@Test @Test
void custSplit_movesListedPointsToSecondary() { void custSplit_movesListedPointsToSecondary() {
@@ -74,6 +80,115 @@ class OfPiePainterTest {
"c:serLines не нарисована"); "c:serLines не нарисована");
} }
/** «Other»-сектор замыкает главный пирог (MS-OI29500 §2.1.1507(a)). */
@Test
void otherSlice_mainPieClosed() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
assertTrue(countColor(img, ACCENT5) > 3000,
"главный пирог не замкнут «Other»-сектором (§2.1.1507(a))");
}
/** Центр «Other»-сектора — 3 часа: сектор обращён ко вторичной (§2.1.1507(a)). */
@Test
void otherWedge_facesRight() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
double[] other = centroid(img, ACCENT5, 0);
double[] left = saturatedCentroid(img, 0, img.getWidth() / 2);
assertTrue(other[0] > left[0], "«Other»-сектор не справа от первичных секторов");
assertTrue(Math.abs(other[1] - img.getHeight() / 2.0) < 0.2 * img.getHeight(),
"центр «Other»-сектора не на 3 часах");
}
/** c:serLines — ровно две связи от границ «Other»-сектора (§2.1.1545(a)). */
@Test
void serLines_twoConnectors() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.add(5.0);
// accent3 (A5A5A5) совпал бы с цветом serLines по допуску — перекрашиваем точку 2
spec.series.get(0).pointFills.put(2, new Color(0, 0xB0, 0x50));
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
assertEquals(2, runsAt(img, gapMid(img), OfPiePainter.SER_LINE_COLOR),
"в разрыве между тортами должно быть ровно 2 связи");
assertTrue(countColor(img, OfPiePainter.SER_LINE_COLOR) < 3000,
"c:serLines рисуется веером, а не двумя связями (§2.1.1545(a))");
}
/** Связи крепятся к левому ободу вторичного пирога, а не к серединам секторов. */
@Test
void serLines_attachToLeftRimOnly() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.add(5.0);
spec.series.get(0).pointFills.put(2, new Color(0, 0xB0, 0x50));
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
double[] center = saturatedCentroid(img, gapMid(img) + 1, img.getWidth());
assertTrue(maxXOfColor(img, OfPiePainter.SER_LINE_COLOR) <= center[0] + 3,
"связи уходят за вертикаль центра вторичного пирога");
}
/** Вторичный пирог: сектора в порядке данных от конца «Other»-сектора. */
@Test
void secondaryPie_slicesInDataOrderFromWedgeEnd() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.clear();
spec.series.get(0).values.addAll(List.of(40.0, 25.0, 18.0, 10.0, 7.0));
spec.secondPiePts.add(3);
spec.secondPiePts.add(4);
BufferedImage img = render(spec);
int mid = gapMid(img);
double[] center = saturatedCentroid(img, mid + 1, img.getWidth());
double[] s3 = centroid(img, ACCENT4, mid + 1);
double[] s4 = centroid(img, ACCENT5, mid + 1);
assertEquals(226.5, angleDeg(center[0], center[1], s3[0], s3[1]), 20.0,
"сектор точки 3 не на биссектрисе 226.5° (старт не от конца «Other»?)");
assertEquals(46.5, angleDeg(center[0], center[1], s4[0], s4[1]), 20.0,
"сектор точки 4 не на биссектрисе 46.5° (старт не от конца «Other»?)");
}
/** Пара пирогов центрирована горизонтально (как в Word). */
@Test
void pairCentered_horizontally() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
int leftGap = saturatedMinX(img);
int rightGap = img.getWidth() - 1 - saturatedMaxX(img);
assertTrue(Math.abs(leftGap - rightGap) < 0.1 * img.getWidth(),
"пара не центрирована: left=" + leftGap + ", right=" + rightGap);
}
/** bar-вариант: связи к левым углам столбца, ровно две (§2.1.1545(a)). */
@Test
void serLines_bar_attachToBarLeftCorners() {
ChartSpec spec = ofPieSpec("cust", null);
spec.ofPieType = "bar";
spec.series.get(0).values.clear();
spec.series.get(0).values.addAll(List.of(40.0, 25.0, 18.0, 10.0, 7.0));
spec.secondPiePts.add(3);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
int barLeft = rightMinX(img);
assertTrue(maxXOfColor(img, OfPiePainter.SER_LINE_COLOR) <= barLeft + 3,
"связи уходят в столбец, а не крепятся к его левому краю");
assertEquals(2, runsAt(img, gapMid(img), OfPiePainter.SER_LINE_COLOR),
"в разрыве должно быть ровно 2 связи");
}
private static ChartSpec ofPieSpec(String splitType, Double splitPos) { private static ChartSpec ofPieSpec(String splitType, Double splitPos) {
ChartSpec spec = new ChartSpec(); ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.OF_PIE; spec.type = ChartSpec.Type.OF_PIE;
@@ -125,11 +240,7 @@ class OfPiePainterTest {
int max = -1; int max = -1;
for (int y = 0; y < img.getHeight(); y++) { for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) { for (int x = 0; x < img.getWidth(); x++) {
int rgb = img.getRGB(x, y); if (saturated(img.getRGB(x, y))) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
if (Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) > GRAY_MAX_SPREAD) {
min = Math.min(min, x); min = Math.min(min, x);
max = Math.max(max, x); max = Math.max(max, x);
} }
@@ -150,6 +261,146 @@ class OfPiePainterTest {
return n; return n;
} }
/** Насыщенный px — разброс каналов > GRAY_MAX_SPREAD (серый/белый/чёрный — нет). */
private static boolean saturated(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) > GRAY_MAX_SPREAD;
}
/** Средний px цвета c среди x ≥ xFrom. */
private static double[] centroid(BufferedImage img, Color c, int xFrom) {
double sx = 0;
double sy = 0;
long n = 0;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = xFrom; x < img.getWidth(); x++) {
if (matches(img.getRGB(x, y), c)) {
sx += x;
sy += y;
n++;
}
}
}
assertTrue(n > 100, "нет пикселей цвета " + c);
return new double[]{sx / n, sy / n};
}
/** Центроид насыщенных px в полосе xFrom ≤ x < xTo. */
private static double[] saturatedCentroid(BufferedImage img, int xFrom, int xTo) {
double sx = 0;
double sy = 0;
long n = 0;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = xFrom; x < xTo; x++) {
if (saturated(img.getRGB(x, y))) {
sx += x;
sy += y;
n++;
}
}
}
assertTrue(n > 100, "нет насыщенных пикселей в полосе");
return new double[]{sx / n, sy / n};
}
private static boolean columnHasSaturated(BufferedImage img, int x) {
for (int y = 0; y < img.getHeight(); y++) {
if (saturated(img.getRGB(x, y))) {
return true;
}
}
return false;
}
/** Середина наибольшего внутреннего разрыва (столбцы без насыщенных px). */
private static int gapMid(BufferedImage img) {
int w = img.getWidth();
int bestA = -1;
int bestLen = 0;
int a = -1;
for (int x = 0; x <= w; x++) {
boolean empty = x < w && !columnHasSaturated(img, x);
if (empty && a < 0) {
a = x;
}
if (!empty && a >= 0) {
if (a > 0 && x < w && x - a > bestLen) {
bestLen = x - a;
bestA = a;
}
a = -1;
}
}
assertTrue(bestLen > 0, "нет внутреннего разрыва между тортами");
return bestA + bestLen / 2;
}
/** Первый насыщенный столбец правее разрыва. */
private static int rightMinX(BufferedImage img) {
for (int x = gapMid(img); x < img.getWidth(); x++) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("правее разрыва нет насыщенных пикселей");
}
/** Число y-интервалов цвета c в колонке x (склейка зазоров ≤ 3 px). */
private static int runsAt(BufferedImage img, int x, Color c) {
int runs = 0;
int gap = MERGE_GAP_PX + 1;
for (int y = 0; y < img.getHeight(); y++) {
if (matches(img.getRGB(x, y), c)) {
if (gap > MERGE_GAP_PX) {
runs++;
}
gap = 0;
} else {
gap++;
}
}
return runs;
}
private static int maxXOfColor(BufferedImage img, Color c) {
int max = -1;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = img.getWidth() - 1; x > max; x--) {
if (matches(img.getRGB(x, y), c)) {
max = x;
break;
}
}
}
return max;
}
private static int saturatedMinX(BufferedImage img) {
for (int x = 0; x < img.getWidth(); x++) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("нет насыщенных пикселей");
}
private static int saturatedMaxX(BufferedImage img) {
for (int x = img.getWidth() - 1; x >= 0; x--) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("нет насыщенных пикселей");
}
/** Word-угол точки (x, y) от центра: 0 = 12 часов, по часовой. */
private static double angleDeg(double cx, double cy, double x, double y) {
double a = Math.toDegrees(Math.atan2(x - cx, cy - y));
return a < 0 ? a + 360 : a;
}
private static boolean matches(int rgb, Color c) { private static boolean matches(int rgb, Color c) {
return Math.abs(((rgb >> 16) & 0xFF) - c.getRed()) <= 24 return Math.abs(((rgb >> 16) & 0xFF) - c.getRed()) <= 24
&& Math.abs(((rgb >> 8) & 0xFF) - c.getGreen()) <= 24 && Math.abs(((rgb >> 8) & 0xFF) - c.getGreen()) <= 24