Skip to content
Draft
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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,18 @@ ko: Cut a clip에서 표시한 프레임을 목록으로 보고 메모를 달아
en: Cut a clip lists a video's marked frames with a note each, and exports them as one PDF or a folder of PNGs
ko: 설정 → 테마의 진행 링 카드에서 링을 보여 주는 시간(5·10·15초 또는 항상)을 고를 수 있어요
en: The progress ring's time at the cursor (5, 10, 15 seconds or Always) can be set in Settings → Theme
ko: 모델 공간에 도면 틀(표제란)을 여러 개 나란히 그린 CAD 도면을 PDF로 바꾸면 틀마다 한 페이지가 돼요
en: A CAD drawing with several sheet frames side by side in model space becomes one PDF page per frame
-->

- **One PDF page per sheet frame in model space** (#535). A DWG or DXF drawn only in model space, with several title-block
frames side by side, used to become one PDF page holding all of them. When the drawing has no layouts of its own,
each frame is now a page, top row first and left to right. A frame is a closed rectangle, or a title block
inserted as a block, the size of an ISO (A4–A0) or ANSI (A–E) sheet in the drawing's units, at 1:1 or a usual
drawing scale such as 1:100 or 1/4" = 1'-0". A frame inside another is part of it. With fewer than two frames,
model space stays one page as before, and drawings with layouts still get a page per layout. Pages use the
preset's paper size, like layout pages.

- **Grayscale PDFs** (#1930). The **Grayscale** preset on a PDF used to give back the PDF in colour. It now
comes out gray: text stays text you can select, shapes stay sharp, pictures become gray and notes stay notes, with
no page turned into a picture. Page ranges, splitting, compression and PDF/A work on the gray file. This needs
Expand Down
8 changes: 8 additions & 0 deletions docs/ENGINES.md
Original file line number Diff line number Diff line change
Expand Up @@ -1414,6 +1414,14 @@ and writes the files; Filee's own renderer draws them with SkiaSharp (one drawin
PDF stays one page of model space. Not followed: twisted views (drawn untwisted), views from another direction
than the top (drawn from the top), layers frozen per viewport, non-rectangular viewports and the layout's plot
settings (paper size, plot scale). Images and SVG stay one picture of model space.
- PDF of a model-space drawing with several sheet frames side by side (#535): when there are no layouts of the drawing's
own (as above), every frame is a page, top row first and left to right. A frame is a closed, straight,
axis-aligned four-corner LWPOLYLINE, or a block reference (not an array) whose block's largest such rectangle is
one, whose size is an ISO A4–A0 or ANSI A–E sheet (either way round) in the drawing's `$INSUNITS` (unitless: tried
as millimetres and as inches) at 1:1 or a usual drawing scale (metric 1:2 to 1:10000, imperial 1/4" = 1'-0" and
the like), within 1 %. Frames on hidden layers, and a frame inside another, don't count; fewer than two frames
keep one page of model space. Each page is drawn like a viewport at 1:1 onto its frame (plus 0.25 % room for
the border line), clipped to it, on the preset's paper size. Frames made of separate LINEs aren't found.
- SVG: the drawing's aspect ratio with a 420 mm (A3) long edge at 96 px/inch, white background, text as `<text>`.
- Images: the same page rendered at the preset's render resolution (150 dpi → 2480 px on the long edge, at most
12 000 px / 80 MP), then the preset's image options (resize, grayscale, quality, DPI) as for other images.
Expand Down
6 changes: 6 additions & 0 deletions src/Filee.Engines/Cad/CadConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<d
var sheets = step.To == "pdf" ? CadSceneBuilder.BuildLayouts(document, cancellationToken) : [];
if (sheets.Count > 0)
_logger.LogInformation("{File}: {Count} layout(s), one PDF page each", step.InputPath, sheets.Count);
// Without layouts of its own, sheet frames side by side in model space are a page each (#535).
else if (step.To == "pdf" && scene.Space == "model" && CadSceneBuilder.BuildFrames(document) is { Count: > 0 } frames)
{
sheets = frames;
_logger.LogInformation("{File}: {Count} sheet frames in model space, one PDF page each", step.InputPath, sheets.Count);
}
if (scene.Items.Count == 0 && sheets.Count == 0)
throw new InvalidDataException(scene.Skipped.Count > 0
? $"The drawing only contains objects Filee cannot draw ({string.Join(", ", scene.Skipped.Keys)})."
Expand Down
164 changes: 164 additions & 0 deletions src/Filee.Engines/Cad/CadSceneBuilder.Frames.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Title-block frames drawn side by side in model space (#535): with no layouts of its own, a drawing whose model space
// holds several sheet frames prints one PDF page per frame, each like a viewport onto model space at 1:1.

using ACadSharp;
using ACadSharp.Entities;
using ACadSharp.Tables;
using ACadSharp.Types.Units;

namespace Filee.Engines.Cad;

internal sealed partial class CadSceneBuilder
{
/// <summary>Standard sheets in millimetres, short side first: ISO A4–A0 and ANSI A–E.</summary>
private static readonly (double Short, double Long)[] Sheets =
[
(210, 297), (297, 420), (420, 594), (594, 841), (841, 1189),
(215.9, 279.4), (279.4, 431.8), (431.8, 558.8), (558.8, 863.6), (863.6, 1117.6),
];

/// <summary>
/// Drawing scales a frame may be drawn at (model units per sheet unit): metric ones and the imperial architectural
/// ones (1/4" = 1'-0" is 48).
/// </summary>
private static readonly double[] FrameScales =
[
1, 2, 2.5, 4, 5, 8, 10, 12, 16, 20, 24, 25, 32, 40, 48, 50, 64, 75, 96, 100, 125, 128, 150, 192, 200, 250, 300,
384, 400, 500, 600, 1000, 1250, 2000, 2500, 5000, 10000,
];

/// <summary>How far a size may be off a sheet or a scale and still count as one.</summary>
private const double FrameTolerance = 0.01;

/// <summary>
/// One sheet per sheet frame in model space, in reading order (top row first, then left to right). A frame is a
/// closed rectangle, or a block reference whose largest closed rectangle is, the size of a standard sheet at a
/// common drawing scale in the drawing's units; one inside another is part of it. Empty with fewer than two
/// frames, so the whole of model space stays one page.
/// </summary>
public static List<LayoutSheet> BuildFrames(CadDocument document)
{
var millimetres = UnitMillimetres(document.Header?.InsUnits ?? UnitsType.Unitless);
var frames = new List<Box2>();
foreach (var entity in document.ModelSpace.Entities)
{
if (entity.Layer is { } layer && !IsShown(layer))
continue;
var box = entity switch
{
LwPolyline polyline => RectangleOf(polyline, Affine3.Identity),
Insert insert => FrameOf(insert),
_ => null,
};
if (box is { } b && IsSheet(b, millimetres) && !frames.Any(f => Same(f, b)))
frames.Add(b);
}
frames.RemoveAll(inner => frames.Any(outer => !Same(outer, inner) && Contains(outer, inner)));
if (frames.Count < 2)
return [];

// Rows: a frame whose centre is level with a row's first frame joins that row.
var rows = new List<List<Box2>>();
foreach (var frame in frames.OrderByDescending(f => (f.MinY + f.MaxY) / 2))
{
var centre = (frame.MinY + frame.MaxY) / 2;
if (rows.Count > 0 && centre >= rows[^1][0].MinY && centre <= rows[^1][0].MaxY)
rows[^1].Add(frame);
else
rows.Add([frame]);
}
return [.. rows.SelectMany(r => r.OrderBy(f => f.MinX)).Select((frame, i) =>
{
// A little room around the frame, so its own border isn't clipped to half its width.
var margin = Math.Max(frame.Width, frame.Height) * 0.0025;
var view = Box2.Empty;
view.Add(new Vec2(frame.MinX - margin, frame.MinY - margin));
view.Add(new Vec2(frame.MaxX + margin, frame.MaxY + margin));
var centre = new Vec2((frame.MinX + frame.MaxX) / 2, (frame.MinY + frame.MaxY) / 2);
return new LayoutSheet($"Frame {i + 1}", new CadScene(), [new ViewportView(view, centre, 1)]);
})];
}

/// <summary>Millimetres per drawing unit, or null for a unitless drawing (tried as millimetres and as inches).</summary>
private static double? UnitMillimetres(UnitsType units) => units switch
{
UnitsType.Millimeters => 1,
UnitsType.Centimeters => 10,
UnitsType.Decimeters => 100,
UnitsType.Meters => 1000,
UnitsType.Inches => 25.4,
UnitsType.Feet => 304.8,
_ => null,
};

private static bool IsSheet(Box2 box, double? millimetres)
{
var (shortSide, longSide) = (Math.Min(box.Width, box.Height), Math.Max(box.Width, box.Height));
if (shortSide <= 0)
return false;
foreach (var unit in millimetres is { } mm ? new[] { mm } : new[] { 1, 25.4 })
{
foreach (var sheet in Sheets)
{
var scale = longSide * unit / sheet.Long;
if (Math.Abs(shortSide * unit / sheet.Short - scale) <= scale * FrameTolerance
&& FrameScales.Any(s => Math.Abs(scale - s) <= s * FrameTolerance))
return true;
}
}
return false;
}

/// <summary>The frame of a block reference: its block's largest closed rectangle, placed like the reference.</summary>
private static Box2? FrameOf(Insert insert)
{
if (insert.Block is not { } block || insert.RowCount > 1 || insert.ColumnCount > 1)
return null;
var basePoint = block.BlockEntity?.BasePoint ?? default;
var placement = Affine3.Ocs(insert.Normal)
.Multiply(Affine3.Translation(insert.InsertPoint))
.Multiply(Affine3.RotationZ(insert.Rotation))
.Multiply(Affine3.Scale(insert.XScale, insert.YScale, insert.ZScale))
.Multiply(Affine3.Translation(new Vec3(-basePoint.X, -basePoint.Y, -basePoint.Z)));
return block.Entities.OfType<LwPolyline>()
.Where(p => p.Layer is null || IsShown(p.Layer))
.Select(p => RectangleOf(p, placement))
.Where(b => b is not null)
.MaxBy(b => b!.Value.Width * b.Value.Height);
}

/// <summary>The box of a closed, straight, axis-aligned four-cornered polyline after <paramref name="transform"/>.</summary>
private static Box2? RectangleOf(LwPolyline polyline, Affine3 transform)
{
var points = polyline.Vertices.Select(v => v.Location).ToList();
if (points.Count == 5 && points[0].Equals(points[4]))
points.RemoveAt(4);
else if (!polyline.IsClosed)
return null;
if (points.Count != 4 || polyline.Vertices.Any(v => v.Bulge != 0))
return null;
var m = transform.Multiply(Affine3.Ocs(polyline.Normal));
var corners = points.Select(p => m.Point(new Vec3(p.X, p.Y, polyline.Elevation))).ToList();
var box = Box2.Empty;
foreach (var corner in corners)
box.Add(corner);
var snap = Math.Max(box.Width, box.Height) * 1e-6;
// Every corner sits on the box's corners: a rectangle, not a rhombus or a turned one.
return box.Width > 0 && box.Height > 0
&& corners.All(c => (Math.Abs(c.X - box.MinX) <= snap || Math.Abs(c.X - box.MaxX) <= snap)
&& (Math.Abs(c.Y - box.MinY) <= snap || Math.Abs(c.Y - box.MaxY) <= snap))
&& corners.Distinct().Count() == 4
? box
: null;
}

private static bool Same(Box2 a, Box2 b)
{
var snap = Math.Max(a.Width, a.Height) * 1e-6;
return Math.Abs(a.MinX - b.MinX) <= snap && Math.Abs(a.MinY - b.MinY) <= snap
&& Math.Abs(a.MaxX - b.MaxX) <= snap && Math.Abs(a.MaxY - b.MaxY) <= snap;
}

private static bool Contains(Box2 outer, Box2 inner) =>
inner.MinX >= outer.MinX && inner.MaxX <= outer.MaxX && inner.MinY >= outer.MinY && inner.MaxY <= outer.MaxY;
}
152 changes: 152 additions & 0 deletions tests/Filee.Engines.Tests/CadFrameTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// CAD → PDF with one page per title-block frame in model space (#535): a drawing without layouts of its own whose
// model space holds several sheet frames side by side prints each frame as a page, in reading order.

using ACadSharp;
using ACadSharp.Entities;
using ACadSharp.Objects;
using ACadSharp.Tables;
using ACadSharp.Types.Units;
using CSMath;
using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Cad;
using PdfSharp.Pdf.IO;

namespace Filee.Engines.Tests;

public class CadFrameTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
private static LwPolyline Rectangle(double x, double y, double width, double height) =>
new(new LwPolyline.Vertex(x, y), new LwPolyline.Vertex(x + width, y), new LwPolyline.Vertex(x + width, y + height),
new LwPolyline.Vertex(x, y + height))
{ IsClosed = true };

/// <summary>
/// A millimetre drawing with three A3 frames: two in the top row, one below the first. The second holds an A4 frame
/// of its own (a detail, not a sheet), and every frame has a line inside.
/// </summary>
private static CadDocument ThreeA3Frames()
{
var doc = new CadDocument();
doc.Header.InsUnits = UnitsType.Millimeters;
var layer = new Layer("Frames") { Color = CadBuilder.Visible };
doc.Layers.Add(layer);
foreach (var (x, y) in new[] { (0.0, 297.0), (420.0, 297.0), (0.0, 0.0) })
{
CadBuilder.Add(doc, layer, Rectangle(x, y, 420, 297));
CadBuilder.Add(doc, layer, new Line(new XYZ(x + 20, y + 20, 0), new XYZ(x + 200, y + 150, 0)));
}
CadBuilder.Add(doc, layer, Rectangle(440, 310, 297, 210)); // A4 landscape, inside the second frame
return doc;
}

private static (double, double, double, double) Frame(LayoutSheet sheet)
{
var view = Assert.Single(sheet.Viewports);
Assert.Equal(1, view.Scale);
return (Math.Round(view.ViewCenter.X, 3), Math.Round(view.ViewCenter.Y, 3), Math.Round(view.Frame.Width, 3), Math.Round(view.Frame.Height, 3));
}

[Fact]
public void Each_frame_is_a_sheet_in_reading_order_and_one_inside_another_is_not()
{
var sheets = CadSceneBuilder.BuildFrames(ThreeA3Frames());

// Top row left to right, then the row below; each view is the frame with a hair of room around it.
Assert.Equal([(210.0, 445.5), (630.0, 445.5), (210.0, 148.5)], sheets.Select(s => (Frame(s).Item1, Frame(s).Item2)));
Assert.All(sheets, s => Assert.Equal((422.1, 299.1), (Frame(s).Item3, Frame(s).Item4)));
Assert.All(sheets, s => Assert.Empty(s.Paper.Items));
}

[Fact]
public async Task A_model_space_drawing_with_an_empty_layout_prints_a_page_per_frame()
{
// Layout1 holds only the viewport AutoCAD added when its tab was first opened: still no layouts of its own.
var doc = ThreeA3Frames();
var layout = doc.Layouts.Single(l => l.Name == "Layout1");
layout.AssociatedBlock.Entities.Add(new Viewport
{
Center = new XYZ(210, 148.5, 0),
Width = 200,
Height = 150,
ViewCenter = new XY(50, 50),
ViewHeight = 150,
});
Assert.Empty(CadSceneBuilder.BuildLayouts(doc, TestContext.Current.CancellationToken));

var dxf = CadBuilder.SaveDxf(doc, fx.NewFolder(), "frames.dxf");
var job = await fx.ConvertAsync([dxf], new Preset { TargetFormat = "pdf" });

Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
using var document = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
Assert.Equal(3, document.PageCount);
foreach (var page in document.Pages)
{
// A3 landscape, the preset's default page.
Assert.Equal(420 / 25.4 * 72, page.Width.Point, 0.5);
Assert.Equal(297 / 25.4 * 72, page.Height.Point, 0.5);
}
// Each page shows its frame's own line, low on the left, and nothing of the frames next to it up on the right.
for (var page = 0; page < 3; page++)
{
Assert.True(CadLayoutTests.Blue(job.Outputs.Single(), page, 0.1, 0.5, 0.45, 0.9) > 20, $"page {page + 1}: the frame's line");
Assert.Equal(0, CadLayoutTests.Blue(job.Outputs.Single(), page, 0.6, 0.05, 0.95, 0.2));
}
}

[Fact]
public void Rectangles_that_are_no_sheet_leave_one_page()
{
var doc = new CadDocument();
doc.Header.InsUnits = UnitsType.Millimeters;
var layer = new Layer("Rooms") { Color = CadBuilder.Visible };
doc.Layers.Add(layer);
CadBuilder.Add(doc, layer, Rectangle(0, 0, 100, 37));
CadBuilder.Add(doc, layer, Rectangle(200, 0, 250, 80));
CadBuilder.Add(doc, layer, Rectangle(500, 0, 420 * 3.3, 297 * 3.3)); // A3's shape at no drawing scale
CadBuilder.Add(doc, layer, Rectangle(0, 2000, 297 * 3.3, 420 * 3.3));
// One real frame alone is one page as before.
CadBuilder.Add(doc, layer, Rectangle(0, -1000, 420, 297));

Assert.Empty(CadSceneBuilder.BuildFrames(doc));
}

[Fact]
public void Title_block_references_in_an_inch_drawing_are_frames()
{
// ANSI B (17 × 11 in) title blocks placed twice: at 1:1, and turned a quarter and at 1/4" = 1'-0" (48).
var doc = new CadDocument();
doc.Header.InsUnits = UnitsType.Inches;
var layer = new Layer("Title") { Color = CadBuilder.Visible };
doc.Layers.Add(layer);
var block = new BlockRecord("TITLE-B");
block.Entities.Add(Rectangle(0, 0, 17, 11));
block.Entities.Add(Rectangle(12, 0, 5, 2)); // the title box: smaller, so not the frame
doc.BlockRecords.Add(block);
CadBuilder.Add(doc, layer, new Insert(block) { InsertPoint = new XYZ(0, 0, 0) });
CadBuilder.Add(doc, layer, new Insert(block) { InsertPoint = new XYZ(1000, 0, 0), XScale = 48, YScale = 48, Rotation = Math.PI / 2 });

var sheets = CadSceneBuilder.BuildFrames(doc);

Assert.Equal(2, sheets.Count);
var big = sheets.Single(s => s.Viewports[0].Frame.Width < s.Viewports[0].Frame.Height).Viewports[0];
Assert.Equal((1000 - 11 * 48 / 2.0, 17 * 48 / 2.0), (Math.Round(big.ViewCenter.X, 6), Math.Round(big.ViewCenter.Y, 6)));
// In millimetres the same frames are 17 × 11 mm, which is no sheet.
doc.Header.InsUnits = UnitsType.Millimeters;
Assert.Empty(CadSceneBuilder.BuildFrames(doc));
}

[Fact]
public void A_unitless_drawing_matches_iso_sheets_in_millimetres_at_a_scale()
{
var doc = new CadDocument();
doc.Header.InsUnits = UnitsType.Unitless;
var layer = new Layer("Frames") { Color = CadBuilder.Visible };
doc.Layers.Add(layer);
// Two A1 frames at 1:100.
CadBuilder.Add(doc, layer, Rectangle(0, 0, 84100, 59400));
CadBuilder.Add(doc, layer, Rectangle(90000, 0, 84100, 59400));

Assert.Equal(2, CadSceneBuilder.BuildFrames(doc).Count);
}
}
2 changes: 1 addition & 1 deletion tests/Filee.Engines.Tests/CadLayoutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public async Task Images_and_svg_stay_one_picture_of_model_space()
}

/// <summary>Blue pixels of a rendered page in a box given as fractions of the page.</summary>
private static int Blue(string pdf, int page, double left, double top, double right, double bottom)
internal static int Blue(string pdf, int page, double left, double top, double right, double bottom)
{
using var bitmap = Conversion.ToImage(File.ReadAllBytes(pdf), page, null, new RenderOptions(Dpi: 40, BackgroundColor: SKColors.White));
var count = 0;
Expand Down
Loading