diff --git a/GdsGenerator/.gitignore b/GdsGenerator/.gitignore new file mode 100644 index 0000000..ca89e77 --- /dev/null +++ b/GdsGenerator/.gitignore @@ -0,0 +1 @@ +mine \ No newline at end of file diff --git a/GdsGenerator/Program.cs b/GdsGenerator/Program.cs index c2d97a4..5743b0f 100644 --- a/GdsGenerator/Program.cs +++ b/GdsGenerator/Program.cs @@ -1,4 +1,5 @@ using System.Numerics; +using GdsSharp.Lib; using GdsSharp.Lib.Builders; using GdsSharp.Lib.NonTerminals; using GdsSharp.Lib.NonTerminals.Elements; @@ -11,56 +12,53 @@ Version = 600 }; -var structure = new GdsStructure +var elements = new List { - Name = "Example structure", - Elements = - [ - // Generate a line from a Bézier curve with width 20. - // When using BuildPolygon the curve will be a GdsBoundaryElement. - new BezierBuilder() - .AddPoint(0, 0) - .AddPoint(0, 1000) - .AddPoint(1000, 1000) - .AddPoint(1000, 0) - .BuildPolygon(200), + // Generate a line from a Bézier curve with width 20. + // When using BuildPolygon the curve will be a GdsBoundaryElement. + new BezierBuilder() + .AddPoint(0, 0) + .AddPoint(0, 1000) + .AddPoint(1000, 1000) + .AddPoint(1000, 0) + .BuildPolygon(200), - // When using BuildLine the curve will be a GdsPathElement. - new BezierBuilder() - .AddPoint(-3000, 0) - .AddPoint(-3000, 1000) - .AddPoint(-2000, 1000) - .AddPoint(-2000, 0) - .BuildLine(200), + // When using BuildLine the curve will be a GdsPathElement. + new BezierBuilder() + .AddPoint(-3000, 0) + .AddPoint(-3000, 1000) + .AddPoint(-2000, 1000) + .AddPoint(-2000, 0) + .BuildLine(200), - // Create a rectangle - RectBuilder.CreateRect(-3100, -1000, 4200, 1000), + // Create a rectangle + RectBuilder.CreateRect(-3100, -1000, 4200, 1000), - // Create a circle - CircleBuilder.CreateCircle(-1000, 744, 350, 128), + // Create a circle + CircleBuilder.CreateCircle(-1000, 744, 350, 128), - // Create a polygon by manually specifying the points - new GdsElement + // Create a polygon by manually specifying the points + new() + { + Element = new GdsBoundaryElement { - Element = new GdsBoundaryElement - { - Points = - [ - new GdsPoint(-1250, 0), - new GdsPoint(-1250, 500), - new GdsPoint(-1000, 250), - new GdsPoint(-750, 500), - new GdsPoint(-750, 0), - new GdsPoint(-1250, 0) - ] - } + Points = + [ + new GdsPoint(-1250, 0), + new GdsPoint(-1250, 500), + new GdsPoint(-1000, 250), + new GdsPoint(-750, 500), + new GdsPoint(-750, 0), + new GdsPoint(-1250, 0) + ], + NumPoints = 6 } - ] + } }; // Use the path builder to create a path // Returns an IEnumerable of GdsElement because the path may be split into multiple elements -structure.Elements.AddRange( +elements.AddRange( new PathBuilder( 100f, new Vector2(-3100, -3300), @@ -98,9 +96,15 @@ // Build the path in sections of 200 vertices // This is the 'official' maximum number of vertices per element in GDSII // In practice, the number of vertices per element can be much higher - .Build(maxVertices: 200) + .Build(200) ); -file.Structures.Add(structure); +var structure = new GdsStructure +{ + Name = "Example structure", + Elements = elements +}; + +file.Structures = [structure]; using var write = File.OpenWrite("example.gds"); file.WriteTo(write); \ No newline at end of file diff --git a/GdsSharp.Benchmarks/BufferedStreamBenchmark.cs b/GdsSharp.Benchmarks/BufferedStreamBenchmark.cs new file mode 100644 index 0000000..c0bcc3f --- /dev/null +++ b/GdsSharp.Benchmarks/BufferedStreamBenchmark.cs @@ -0,0 +1,104 @@ +using BenchmarkDotNet.Attributes; +using GdsSharp.Lib; +using GdsSharp.Lib.Builders; +using GdsSharp.Lib.NonTerminals; +using GdsSharp.Lib.NonTerminals.Elements; + +namespace GdsSharp.Benchmarks; + +public class BufferedStreamBenchmark +{ + + [GlobalSetup] + public void Setup() + { + var file = new GdsFile + { + LibraryName = "Test", + PhysicalUnits = 1e-6, + UserUnits = 1, + }; + + var structure = new GdsStructure + { + Name = "My structure", + }; + + var pb = new PathBuilder(1000f); + for (var i = 0; i < 1000; i++) + { + pb.Straight(1000, vertices: 10000); + } + + structure.Elements = pb.Build(); + file.Structures = new[] { structure }; + + using var fs = new FileStream("example.gds", FileMode.Create, FileAccess.Write); + file.WriteTo(fs); + } + + [GlobalCleanup] + public void Cleanup() + { + File.Delete("example.gds"); + } + + private Stream _stream = null!; + + [IterationSetup] + public void IterationSetup() + { + _stream = new FileStream("example.gds", FileMode.Open, FileAccess.Read); + } + + [IterationCleanup] + public void IterationCleanup() + { + _stream.Dispose(); + } + + [Benchmark] + public GdsFile NoBuffer() + { + var file = GdsFile.From(_stream); + + file.Structures = file.Structures.ToList(); + foreach(var structure in file.Structures) + { + structure.Elements = structure.Elements.ToList(); + foreach (var element in structure.Elements) + { + if (element is not {Element: GdsBoundaryElement b}) continue; + + b.Points = b.Points.ToList(); + } + } + + return file; + } + + + [Benchmark] + [Arguments(4*1024)] + [Arguments(32*1024)] + public GdsFile Buffer(int size) + { + var bufferedStream = new BufferedStream(_stream, size); + + var file = GdsFile.From(bufferedStream); + + file.Structures = file.Structures.ToList(); + foreach(var structure in file.Structures) + { + structure.Elements = structure.Elements.ToList(); + foreach (var element in structure.Elements) + { + if (element is not {Element: GdsBoundaryElement b}) continue; + + b.Points = b.Points.ToList(); + } + } + + return file; + } +} \ No newline at end of file diff --git a/GdsSharp.Benchmarks/FloatToIntBenchmark.cs b/GdsSharp.Benchmarks/FloatToIntBenchmark.cs new file mode 100644 index 0000000..a3dfcec --- /dev/null +++ b/GdsSharp.Benchmarks/FloatToIntBenchmark.cs @@ -0,0 +1,59 @@ +using BenchmarkDotNet.Attributes; + +namespace GdsSharp.Benchmarks; + +public class FloatToIntBenchmark +{ + private readonly float[] _xs = new float[1000]; + private readonly float[] _ys = new float[1000]; + + [GlobalSetup] + public void Setup() + { + var random = new Random(); + for (int i = 0; i < _xs.Length; i++) + { + _xs[i] = (float)random.NextDouble() * 1000; + _ys[i] = (float)random.NextDouble() * 1000; + } + } + + [Benchmark] + public IntPoint[] FloatToIntRound() + { + var points = new IntPoint[_xs.Length]; + for (int i = 0; i < _xs.Length; i++) + { + points[i] = new IntPoint + { + X = (int)MathF.Round(_xs[i]), + Y = (int)MathF.Round(_ys[i]) + }; + } + + return points; + } + + [Benchmark] + public IntPoint[] FloatToIntAdd() + { + var points = new IntPoint[_xs.Length]; + for (int i = 0; i < _xs.Length; i++) + { + points[i] = new IntPoint + { + X = (int)(_xs[i] + 0.5f), + Y = (int)(_ys[i] + 0.5f) + }; + } + + return points; + } + + + public struct IntPoint + { + public int X; + public int Y; + } +} \ No newline at end of file diff --git a/GdsSharp.Benchmarks/GdsSharp.Benchmarks.csproj b/GdsSharp.Benchmarks/GdsSharp.Benchmarks.csproj new file mode 100644 index 0000000..f3fab56 --- /dev/null +++ b/GdsSharp.Benchmarks/GdsSharp.Benchmarks.csproj @@ -0,0 +1,38 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GdsSharp.Benchmarks/Program.cs b/GdsSharp.Benchmarks/Program.cs new file mode 100644 index 0000000..af5ba4f --- /dev/null +++ b/GdsSharp.Benchmarks/Program.cs @@ -0,0 +1,3 @@ +using BenchmarkDotNet.Running; + +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); \ No newline at end of file diff --git a/GdsSharp.Lib.Test/AssemblyInfo.cs b/GdsSharp.Lib.Test/AssemblyInfo.cs new file mode 100644 index 0000000..4952ec1 --- /dev/null +++ b/GdsSharp.Lib.Test/AssemblyInfo.cs @@ -0,0 +1 @@ +[assembly: Parallelizable(ParallelScope.All)] \ No newline at end of file diff --git a/GdsSharp.Lib.Test/Assets/gds3d_example.gds b/GdsSharp.Lib.Test/Assets/gds3d_example.gds new file mode 100644 index 0000000..b0a73e0 Binary files /dev/null and b/GdsSharp.Lib.Test/Assets/gds3d_example.gds differ diff --git a/GdsSharp.Lib.Test/GdsParserTests.cs b/GdsSharp.Lib.Test/GdsParserTests.cs index cb9d291..81cffda 100644 --- a/GdsSharp.Lib.Test/GdsParserTests.cs +++ b/GdsSharp.Lib.Test/GdsParserTests.cs @@ -1,4 +1,6 @@ using System.Reflection; +using GdsSharp.Lib.Lexing; +using GdsSharp.Lib.NonTerminals.Elements; namespace GdsSharp.Lib.Test; @@ -8,15 +10,15 @@ public class GdsParserTests [TestCase("inv.gds2")] [TestCase("nand2.gds2")] [TestCase("xor.gds2")] - // [TestCase("osu018_stdcells.gds2")] + [TestCase("gds3d_example.gds")] public void TestParserDoesntCrash(string manifestFile) { - var fileStream = + using var fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"GdsSharp.Lib.Test.Assets.{manifestFile}") ?? throw new NullReferenceException(); - var tokenizer = new GdsTokenizer(fileStream); - var tokens = tokenizer.Tokenize(); - var parser = new GdsParser(tokens); + using var stream = new GdsTokenStream(fileStream); + var parser = new GdsParser(stream); var file = parser.Parse(); + file.Materialize(); } } \ No newline at end of file diff --git a/GdsSharp.Lib.Test/GdsSharp.Lib.Test.csproj b/GdsSharp.Lib.Test/GdsSharp.Lib.Test.csproj index 41d1284..db81684 100644 --- a/GdsSharp.Lib.Test/GdsSharp.Lib.Test.csproj +++ b/GdsSharp.Lib.Test/GdsSharp.Lib.Test.csproj @@ -30,7 +30,8 @@ - + + diff --git a/GdsSharp.Lib.Test/GdsTokenizerTests.cs b/GdsSharp.Lib.Test/GdsTokenizerTests.cs deleted file mode 100644 index 2a95e81..0000000 --- a/GdsSharp.Lib.Test/GdsTokenizerTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System.Reflection; -using GdsSharp.Lib.Terminals.Records; - -namespace GdsSharp.Lib.Test; - -public class GdsTokenizerTests -{ - private Stream _stream1 = null!; - private Stream _stream2 = null!; - private Stream _stream3 = null!; - private Stream _stream4 = null!; - - [SetUp] - public void SetUp() - { - _stream1 = Assembly.GetExecutingAssembly().GetManifestResourceStream("GdsSharp.Lib.Test.Assets.example.cal") ?? - throw new NullReferenceException(); - _stream2 = Assembly.GetExecutingAssembly().GetManifestResourceStream("GdsSharp.Lib.Test.Assets.inv.gds2") ?? - throw new NullReferenceException(); - _stream3 = Assembly.GetExecutingAssembly().GetManifestResourceStream("GdsSharp.Lib.Test.Assets.nand2.gds2") ?? - throw new NullReferenceException(); - _stream4 = Assembly.GetExecutingAssembly().GetManifestResourceStream("GdsSharp.Lib.Test.Assets.xor.gds2") ?? - throw new NullReferenceException(); - } - - [Test] - public void TokenizeDoesntCrashOnExample1() - { - var tokenizer = new GdsTokenizer(_stream1); - var tokens = tokenizer.Tokenize().ToList(); - Assert.That(tokens, Has.Count.EqualTo(76)); - - Assert.That(tokens.FirstOfType().Value, Is.EqualTo(5)); - - Assert.Multiple(() => - { - var bgnLib = tokens.FirstOfType(); - Assert.That(bgnLib.LastModificationTimeYear, Is.EqualTo(98)); - Assert.That(bgnLib.LastModificationTimeMonth, Is.EqualTo(8)); - Assert.That(bgnLib.LastModificationTimeDay, Is.EqualTo(25)); - Assert.That(bgnLib.LastModificationTimeHour, Is.EqualTo(15)); - Assert.That(bgnLib.LastModificationTimeMinute, Is.EqualTo(53)); - Assert.That(bgnLib.LastModificationTimeSecond, Is.EqualTo(12)); - Assert.That(bgnLib.LastAccessTimeYear, Is.EqualTo(98)); - Assert.That(bgnLib.LastAccessTimeMonth, Is.EqualTo(8)); - Assert.That(bgnLib.LastAccessTimeDay, Is.EqualTo(25)); - Assert.That(bgnLib.LastAccessTimeHour, Is.EqualTo(15)); - Assert.That(bgnLib.LastAccessTimeMinute, Is.EqualTo(53)); - Assert.That(bgnLib.LastAccessTimeSecond, Is.EqualTo(12)); - }); - - Assert.That(tokens.FirstOfType().Value, Is.EqualTo("TEMPEGS.DB")); - - Assert.That(tokens.FirstOfType().UserUnits, Is.EqualTo(0.01)); - Assert.That(tokens.FirstOfType().PhysicalUnits, Is.EqualTo(1e-08)); - - Assert.Multiple(() => - { - var bgnStr = tokens.FirstOfType(); - Assert.That(bgnStr.CreationTimeYear, Is.EqualTo(98)); - Assert.That(bgnStr.CreationTimeMonth, Is.EqualTo(8)); - Assert.That(bgnStr.CreationTimeDay, Is.EqualTo(25)); - Assert.That(bgnStr.CreationTimeHour, Is.EqualTo(15)); - Assert.That(bgnStr.CreationTimeMinute, Is.EqualTo(53)); - Assert.That(bgnStr.CreationTimeSecond, Is.EqualTo(12)); - Assert.That(bgnStr.LastModificationTimeYear, Is.EqualTo(98)); - Assert.That(bgnStr.LastModificationTimeMonth, Is.EqualTo(8)); - Assert.That(bgnStr.LastModificationTimeDay, Is.EqualTo(25)); - Assert.That(bgnStr.LastModificationTimeHour, Is.EqualTo(15)); - Assert.That(bgnStr.LastModificationTimeMinute, Is.EqualTo(53)); - Assert.That(bgnStr.LastModificationTimeSecond, Is.EqualTo(12)); - }); - - Assert.That(tokens.FirstOfType().Value, Is.EqualTo("AAP")); - - Assert.Multiple(() => - { - var xy = tokens.FirstOfType(); - Assert.That(xy.Coordinates[0], Is.EqualTo((-920000, 452000))); - Assert.That(xy.Coordinates[1], Is.EqualTo((656500, 765500))); - Assert.That(xy.Coordinates[2], Is.EqualTo((175000, -174000))); - Assert.That(xy.Coordinates[3], Is.EqualTo((-756000, -198000))); - Assert.That(xy.Coordinates[4], Is.EqualTo((-920000, 452000))); - }); - - Assert.Multiple(() => - { - var strans = tokens.FirstOfType(); - Assert.That(strans.Reflection, Is.False); - Assert.That(strans.AbsoluteMagnification, Is.False); - Assert.That(strans.AbsoluteAngle, Is.False); - }); - - Assert.That(tokens.FirstOfType().Value, Is.EqualTo(1875)); - - Assert.Multiple(() => - { - var presentation = tokens.FirstOfType(); - Assert.That(presentation.FontNumber, Is.Zero); - Assert.That(presentation.VerticalPresentation, Is.EqualTo(2)); - Assert.That(presentation.HorizontalPresentation, Is.Zero); - }); - } - - [Test] - public void TokenizeDoesntCrashOnExample2() - { - var tokenizer = new GdsTokenizer(_stream2); - var tokens = tokenizer.Tokenize().ToList(); - Assert.That(tokens, Has.Count.EqualTo(425)); - } - - [Test] - public void TokenizeDoesntCrashOnExample3() - { - var tokenizer = new GdsTokenizer(_stream3); - var tokens = tokenizer.Tokenize().ToList(); - Assert.That(tokens, Has.Count.EqualTo(1229)); - } - - [Test] - public void TokenizeDoesntCrashOnExample4() - { - var tokenizer = new GdsTokenizer(_stream4); - var tokens = tokenizer.Tokenize().ToList(); - Assert.That(tokens, Has.Count.EqualTo(1229)); - } -} \ No newline at end of file diff --git a/GdsSharp.Lib.Test/GdsWriterTests.cs b/GdsSharp.Lib.Test/GdsWriterTests.cs index 76c7efb..2702c11 100644 --- a/GdsSharp.Lib.Test/GdsWriterTests.cs +++ b/GdsSharp.Lib.Test/GdsWriterTests.cs @@ -1,4 +1,5 @@ using System.Reflection; +using GdsSharp.Lib.Lexing; using GdsSharp.Lib.Terminals; using GdsSharp.Lib.Terminals.Abstractions; using GdsSharp.Lib.Terminals.Records; @@ -29,21 +30,20 @@ public void TestWriterWritesHeaders() [TestCase("inv.gds2")] [TestCase("nand2.gds2")] [TestCase("xor.gds2")] - // [TestCase("osu018_stdcells.gds2")] + [TestCase("gds3d_example.gds")] public void TestWriterWritesIdentical(string manifestFile) { - var streamIn = new MemoryStream(); - var streamOut = new MemoryStream(); + using var streamIn = new MemoryStream(); + using var streamOut = new MemoryStream(); - var fileStream = + using var fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"GdsSharp.Lib.Test.Assets.{manifestFile}") ?? throw new NullReferenceException(); fileStream.CopyTo(streamIn); fileStream.Position = 0; - var parser = new GdsTokenizer(fileStream); - var tokens = parser.Tokenize().ToList(); - GdsWriter.Write(tokens, streamOut); + using var tokenStream = new GdsTokenStream(fileStream); + GdsWriter.Write(tokenStream, streamOut); // remove padding var bytesIn = streamIn.ToArray(); diff --git a/GdsSharp.Lib.Test/IntegrationTests.cs b/GdsSharp.Lib.Test/IntegrationTests.cs index 3c7804e..2b93397 100644 --- a/GdsSharp.Lib.Test/IntegrationTests.cs +++ b/GdsSharp.Lib.Test/IntegrationTests.cs @@ -1,5 +1,7 @@ using System.Reflection; using FluentAssertions; +using GdsSharp.Lib.Lexing; +using GdsSharp.Lib.NonTerminals.Elements; namespace GdsSharp.Lib.Test; @@ -9,25 +11,27 @@ public class IntegrationTests [TestCase("inv.gds2")] [TestCase("nand2.gds2")] [TestCase("xor.gds2")] - // [TestCase("osu018_stdcells.gds2")] + [TestCase("gds3d_example.gds")] public void TestRoundTrip(string manifestFile) { - var fileStream = + using var fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"GdsSharp.Lib.Test.Assets.{manifestFile}") ?? throw new NullReferenceException(); - - var tokenizer = new GdsTokenizer(fileStream); - var tokens = tokenizer.Tokenize().ToList(); - - var parser = new GdsParser(tokens); + using var tokenStream = new GdsTokenStream(fileStream); + var parser = new GdsParser(tokenStream); var file = parser.Parse(); - - var tokenWriter = new GdsTokenWriter(file); - var tokensNew = tokenWriter.Tokenize().ToList(); - - var parserNew = new GdsParser(tokensNew); + + using var ms = new MemoryStream(); + file.WriteTo(ms); + ms.Position = 0; + + using var tokenStreamNew = new GdsTokenStream(ms); + var parserNew = new GdsParser(tokenStreamNew); var fileNew = parserNew.Parse(); - + + file.Materialize(); + fileNew.Materialize(); + file.Should().BeEquivalentTo(fileNew); } } \ No newline at end of file diff --git a/GdsSharp.Lib.Test/VectorExtensionsTests.cs b/GdsSharp.Lib.Test/VectorExtensionsTests.cs index baf97ba..df5639f 100644 --- a/GdsSharp.Lib.Test/VectorExtensionsTests.cs +++ b/GdsSharp.Lib.Test/VectorExtensionsTests.cs @@ -2,11 +2,8 @@ namespace GdsSharp.Lib.Test; -[TestFixture] public class VectorExtensionsTests { - private const float TwoPi = 2 * MathF.PI; - [Test] public void Rotate_Rotate90Degrees_CorrectResult() { diff --git a/GdsSharp.Lib/Abstractions/GdsStreamOperator.cs b/GdsSharp.Lib/Abstractions/GdsStreamOperator.cs index f1a15b5..d7defa7 100644 --- a/GdsSharp.Lib/Abstractions/GdsStreamOperator.cs +++ b/GdsSharp.Lib/Abstractions/GdsStreamOperator.cs @@ -14,7 +14,7 @@ public class GdsStreamOperator /// static GdsStreamOperator() { - var assembly = Assembly.GetAssembly(typeof(GdsTokenizer)); + var assembly = Assembly.GetAssembly(typeof(GdsStreamOperator)); if (assembly is null) throw new InvalidOperationException("Could not get assembly"); // Get compiled activator for all records diff --git a/GdsSharp.Lib/Binary/GdsBinaryReader.cs b/GdsSharp.Lib/Binary/GdsBinaryReader.cs index 7ece0b5..06d69e1 100644 --- a/GdsSharp.Lib/Binary/GdsBinaryReader.cs +++ b/GdsSharp.Lib/Binary/GdsBinaryReader.cs @@ -6,7 +6,7 @@ namespace GdsSharp.Lib.Binary; public class GdsBinaryReader : BinaryReader { - public GdsBinaryReader(Stream input) : base(input) + public GdsBinaryReader(Stream input) : base(input, Encoding.UTF8, true) { } @@ -69,4 +69,10 @@ public string ReadAsciiString(int length) while (str.EndsWith('\0')) str = str[..^1]; // Remove trailing nulls return str; } + + protected override void Dispose(bool disposing) + { + // Do nothing, we don't want to close the stream + // Somehow setting leaveOpen to true does not work. + } } \ No newline at end of file diff --git a/GdsSharp.Lib/Builders/BezierBuilder.cs b/GdsSharp.Lib/Builders/BezierBuilder.cs index ff17132..bd41691 100644 --- a/GdsSharp.Lib/Builders/BezierBuilder.cs +++ b/GdsSharp.Lib/Builders/BezierBuilder.cs @@ -125,7 +125,8 @@ public GdsElement BuildPolygon(int width, int numVertices = 64) { Element = new GdsBoundaryElement { - Points = offsetPoints.ToList() + Points = offsetPoints.ToList(), + NumPoints = offsetPoints.Length } }; diff --git a/GdsSharp.Lib/Builders/CircleBuilder.cs b/GdsSharp.Lib/Builders/CircleBuilder.cs index d107616..9afed01 100644 --- a/GdsSharp.Lib/Builders/CircleBuilder.cs +++ b/GdsSharp.Lib/Builders/CircleBuilder.cs @@ -61,7 +61,8 @@ public static GdsElement CreateCircle(int x, int y, int radius, int numPoints = Points = pointsPerSector .Select(kvp => kvp.Key % 2 == 0 ? kvp.Value : kvp.Value.Reverse()) .SelectMany(p => SampleEquidistant(p, numPoints / 8)) - .ToList() + .ToList(), + NumPoints = numPoints } }; diff --git a/GdsSharp.Lib/Builders/PathBuilder.cs b/GdsSharp.Lib/Builders/PathBuilder.cs index a254803..58ac6ab 100644 --- a/GdsSharp.Lib/Builders/PathBuilder.cs +++ b/GdsSharp.Lib/Builders/PathBuilder.cs @@ -1,7 +1,6 @@ using System.Numerics; using GdsSharp.Lib.NonTerminals; using GdsSharp.Lib.NonTerminals.Elements; -using SoftCircuits.Collections; namespace GdsSharp.Lib.Builders; @@ -124,73 +123,47 @@ public IEnumerable Build(int maxVertices = 200) { if (maxVertices < 4) throw new ArgumentException("maxVerticesPerElement must be at least 4 to form a valid polygon.", nameof(maxVertices)); + + var ap = GetPathPoints(); - var allPoints = GetPolygonPoints().ToList(); - - var currentIndex = 0; - while (currentIndex < allPoints.Count / 2) + foreach (var points in ap.Chunk(maxVertices/2)) { - // Check how much we can fit in this element - var numPoints = Math.Min(maxVertices, (allPoints.Count/2 - currentIndex)*2) / 2; - numPoints = Math.Max(2, numPoints); + var allPoints = new GdsPoint[points.Length * 2]; + for(var i = 0; i < points.Length; i++) + { + allPoints[i] = new GdsPoint(points[i].Point + points[i].Width * points[i].Normal); + allPoints[allPoints.Length - i - 1] = new GdsPoint(points[i].Point - points[i].Width * points[i].Normal); + } + - // Get the points from the up and down leg of the polygon - var pointsUp = allPoints.GetRange(currentIndex, numPoints); - var pointsDown = allPoints.GetRange(allPoints.Count - currentIndex - numPoints, numPoints).ToList(); - pointsUp.AddRange(pointsDown); - yield return new GdsElement { Element = new GdsBoundaryElement { - Points = pointsUp + Points = allPoints.ToList(), + NumPoints = allPoints.Length, } }; - - // Make sure we start at the last point of the previous element - currentIndex += numPoints-1; - } - } - - /// - /// Builds a polygon from the path. - /// - /// - private IEnumerable GetPolygonPoints() - { - var segments = GetPathPoints(); - - List meshUp = new(); - List meshDown = new(); - - foreach (var (_, points) in segments) - foreach (var (point, normal, width) in points) - { - meshUp.Add(new GdsPoint(point + normal * width / 2)); - meshDown.Insert(0, new GdsPoint(point - normal * width / 2)); } - - return meshUp.Concat(meshDown); } - /// /// Generates a list of points for each segment in the path. /// /// List of points per segment. - private OrderedDictionary> GetPathPoints() + protected IEnumerable GetPathPoints() { - var points = new OrderedDictionary>(); var position = _initialPosition; var heading = _initialHeading; var currentWidth = _initialWidth; + var unitYAngle = Vector2.UnitY.Angle(); + foreach (var segment in _pathSegments) { - var segmentPoints = new List(); - Vector2? lastPosition = null; Vector2? lastHeading = null; + var rotationAngle = unitYAngle - heading.Angle(); for (var i = 0; i <= segment.Vertices; i++) { var t = i / (float)segment.Vertices; @@ -201,7 +174,6 @@ private OrderedDictionary> GetPathPoints() var width = segment.Width?.Invoke(t); // Correct the point and derivative for the heading - var rotationAngle = Vector2.UnitY.Angle() - heading.Angle(); point = point.Rotate(-rotationAngle); derivative = derivative.Rotate(-rotationAngle); @@ -210,18 +182,14 @@ private OrderedDictionary> GetPathPoints() currentWidth = width ?? currentWidth; var normal = new Vector2(-derivative.Y, derivative.X); - segmentPoints.Add(new GdsPathPoint(point + position, normal, currentWidth)); + yield return new GdsPathPoint(point + position, normal, currentWidth); } if (lastPosition.HasValue) position += lastPosition.Value; if (lastHeading.HasValue) heading = lastHeading.Value; - - points.Add(segment, segmentPoints); } - - return points; } /// @@ -231,7 +199,7 @@ private OrderedDictionary> GetPathPoints() /// Function that defines the derivative of the segment. /// Function that defines the width of the segment. /// Number of vertices of the segment. - private record struct GdsPathSegment(Func Path, Func Derivative, Func? Width, int Vertices); + protected record struct GdsPathSegment(Func Path, Func Derivative, Func? Width, int Vertices); /// /// Represents a single point in the path. @@ -239,5 +207,5 @@ private record struct GdsPathSegment(Func Path, FuncThe coordinates of the point. /// The normal of the point. /// The width at the point. - private record struct GdsPathPoint(Vector2 Point, Vector2 Normal, float Width); + protected record struct GdsPathPoint(Vector2 Point, Vector2 Normal, float Width); } \ No newline at end of file diff --git a/GdsSharp.Lib/Builders/RectBuilder.cs b/GdsSharp.Lib/Builders/RectBuilder.cs index 63eaf1d..0f146fb 100644 --- a/GdsSharp.Lib/Builders/RectBuilder.cs +++ b/GdsSharp.Lib/Builders/RectBuilder.cs @@ -29,7 +29,8 @@ public static GdsElement CreateRect(int x, int y, int width, int height) new(x + width, y + height), new(x, y + height), new(x, y) - } + }, + NumPoints = 5 } }; diff --git a/GdsSharp.Lib/Extensions.cs b/GdsSharp.Lib/Extensions.cs index 96e7bed..2b3df9e 100644 --- a/GdsSharp.Lib/Extensions.cs +++ b/GdsSharp.Lib/Extensions.cs @@ -3,18 +3,8 @@ namespace GdsSharp.Lib; -public static class Extensions +public static class GdsExtensions { - public static List AsGdsPoints(this List<(int x, int y)> coordinates) - { - return coordinates.ConvertAll(c => new GdsPoint(c.x, c.y)); - } - - public static List<(int x, int y)> AsTuplePoints(this List coordinates) - { - return coordinates.ConvertAll(c => (c.X, c.Y)); - } - /// /// Rotates a vector by the given angle in radians. /// diff --git a/GdsSharp.Lib/GdsBoundingBox.cs b/GdsSharp.Lib/GdsBoundingBox.cs new file mode 100644 index 0000000..d4c6e4f --- /dev/null +++ b/GdsSharp.Lib/GdsBoundingBox.cs @@ -0,0 +1,48 @@ +namespace GdsSharp.Lib; + +public readonly struct GdsBoundingBox +{ + public GdsPoint Min { get; } + public GdsPoint Max { get; } + + public bool IsEmpty => Min is { X: 0, Y: 0 } && Max is { X: 0, Y: 0 }; + + public GdsBoundingBox(GdsPoint min, GdsPoint max) + { + Min = min; + Max = max; + } + + public GdsBoundingBox(IEnumerable points) + { + if (!points.Any()) return; + + Min = new GdsPoint(int.MaxValue, int.MaxValue); + Max = new GdsPoint(int.MinValue, int.MinValue); + + foreach (var point in points) + { + Min = new GdsPoint(Math.Min(Min.X, point.X), Math.Min(Min.Y, point.Y)); + Max = new GdsPoint(Math.Max(Max.X, point.X), Math.Max(Max.Y, point.Y)); + } + } + + public GdsBoundingBox(IEnumerable boundingBoxes) + { + if (!boundingBoxes.Any()) return; + + Min = new GdsPoint(int.MaxValue, int.MaxValue); + Max = new GdsPoint(int.MinValue, int.MinValue); + + foreach (var boundingBox in boundingBoxes) + { + Min = new GdsPoint(Math.Min(Min.X, boundingBox.Min.X), Math.Min(Min.Y, boundingBox.Min.Y)); + Max = new GdsPoint(Math.Max(Max.X, boundingBox.Max.X), Math.Max(Max.Y, boundingBox.Max.Y)); + } + } + + public static GdsBoundingBox operator *(GdsBoundingBox a, double b) + { + return new GdsBoundingBox(new GdsPoint(a.Min.X * b, a.Min.Y * b), new GdsPoint(a.Max.X * b, a.Max.Y * b)); + } +} \ No newline at end of file diff --git a/GdsSharp.Lib/GdsFile.cs b/GdsSharp.Lib/GdsFile.cs new file mode 100644 index 0000000..f6137d7 --- /dev/null +++ b/GdsSharp.Lib/GdsFile.cs @@ -0,0 +1,70 @@ +using GdsSharp.Lib.Lexing; +using GdsSharp.Lib.NonTerminals; +using GdsSharp.Lib.NonTerminals.Enum; + +namespace GdsSharp.Lib; + +public class GdsFile +{ + public short Version { get; set; } = 5; + public required string LibraryName { get; set; } + public DateTime LastModificationTime { get; set; } = DateTime.Now; + public DateTime LastAccessTime { get; set; } = DateTime.Now; + public List ReferencedLibraries { get; set; } = new(); + public List Fonts { get; set; } = new(); + public string? AttributeDefinitionFile { get; set; } + public short Generations { get; set; } = 3; + public required double UserUnits { get; set; } + public required double PhysicalUnits { get; set; } + public GdsFormatType FormatType { get; set; } = GdsFormatType.GdsArchive; + public IEnumerable Structures { get; set; } = new List(); + + public GdsStructure? GetStructure(string name) + { + return Structures.FirstOrDefault(s => s.Name == name); + } + + public static GdsFile From(Stream stream) + { + using var tokenStream = new GdsTokenStream(stream); + var parser = new GdsParser(tokenStream); + return parser.Parse(); + } + + public void WriteTo(Stream stream) + { + var tokenWriter = new GdsTokenWriter(this); + GdsWriter.Write(tokenWriter.Tokenize(), stream); + } + + /// + /// Materializes all structures in the GDS file. + /// + public void Materialize() + { + var structures = Structures.ToList(); + foreach (var structure in structures) + { + structure.Materialize(); + } + + Structures = structures; + } + + /// + /// Gets the bounding box of a structure. + /// Note that currently rotation and other transformations are not taken into account. + /// Note that text elements are not taken into account. + /// + /// The name of the structure. + /// The bounding box of the structure. + /// Thrown when the structure with the given name is not found. + public GdsBoundingBox GetBoundingBox(string structureName) + { + var structure = GetStructure(structureName); + if (structure == null) + throw new KeyNotFoundException($"Structure with name '{structureName}' not found."); + + return structure.GetBoundingBox(GetStructure); + } +} \ No newline at end of file diff --git a/GdsSharp.Lib/GdsParser.cs b/GdsSharp.Lib/GdsParser.cs index bd280f4..ad19981 100644 --- a/GdsSharp.Lib/GdsParser.cs +++ b/GdsSharp.Lib/GdsParser.cs @@ -1,7 +1,9 @@ -using GdsSharp.Lib.NonTerminals; +using GdsSharp.Lib.Lexing; +using GdsSharp.Lib.NonTerminals; using GdsSharp.Lib.NonTerminals.Abstractions; using GdsSharp.Lib.NonTerminals.Elements; using GdsSharp.Lib.NonTerminals.Enum; +using GdsSharp.Lib.Terminals; using GdsSharp.Lib.Terminals.Abstractions; using GdsSharp.Lib.Terminals.Records; @@ -9,12 +11,11 @@ namespace GdsSharp.Lib; public class GdsParser { - private readonly Queue _queue; - private int _tokenOffset; + private readonly GdsTokenStream _queue; - public GdsParser(IEnumerable tokens) + public GdsParser(GdsTokenStream tokens) { - _queue = new Queue(tokens); + _queue = tokens; } /// @@ -24,18 +25,15 @@ public GdsParser(IEnumerable tokens) /// If the token stream is invalid. public GdsFile Parse() { - var header = Get(); - var bgnLib = Get(); - var libName = Get(); - var refLibs = GetOrDefault(); - var fonts = GetOrDefault(); + var header = Get().Record; + var bgnLib = Get().Record; + var libName = Get().Record; + var refLibs = GetOrDefault()?.Record; + var fonts = GetOrDefault()?.Record; // var attrTable = ExpectOrDefault(); - var generations = GetOrDefault(); - var format = IsNext() ? Get() : null; - var units = Get(); - - var structures = new List(); - while (_queue.Peek() is not GdsRecordNoData { Type: GdsRecordNoDataType.EndLib }) structures.Add(ParseGdsStructure()); + var generations = GetOrDefault()?.Record; + var format = GetOrDefault()?.Record; + var (units, unitsReference) = Get(); var file = new GdsFile { @@ -46,7 +44,8 @@ public GdsFile Parse() LastAccessTime = new DateTime(bgnLib.LastAccessTimeYear, bgnLib.LastAccessTimeMonth, bgnLib.LastAccessTimeDay, bgnLib.LastAccessTimeHour, bgnLib.LastAccessTimeMinute, bgnLib.LastAccessTimeSecond), PhysicalUnits = units.PhysicalUnits, - UserUnits = units.UserUnits + UserUnits = units.UserUnits, + Structures = ParseStructures(unitsReference.Offset + unitsReference.Header.Length) }; if (refLibs is not null) @@ -61,8 +60,6 @@ public GdsFile Parse() if (format is not null) file.FormatType = (GdsFormatType)format.Value; - file.Structures = structures; - return file; } @@ -74,13 +71,13 @@ public GdsFile Parse() /// Expected token type. /// Peeked token of type . /// If peeked token is not of expected type. - private T Peek() + private (T Record, GdsTokenReference reference) Peek() where T : IGdsRecord { - var token = _queue.Peek(); - if (token is not T record) throw new ParseException(typeof(T), token, _tokenOffset); + var reference = _queue.Peek(); + if (reference.Record is not T record) throw new ParseException(typeof(T), reference.Record, reference.Offset); - return record; + return (record, reference); } /// @@ -89,14 +86,13 @@ private T Peek() /// Expected token type. /// Next token of type . /// If next token is not of expected type. - private T Get() + private (T Record, GdsTokenReference Reference) Get() where T : IGdsRecord { - var token = _queue.Dequeue(); - _tokenOffset++; - if (token is not T record) throw new ParseException(typeof(T), token, _tokenOffset); + var reference = _queue.Dequeue(); + if (reference.Record is not T record) throw new ParseException(typeof(T), reference.Record, reference.Offset); - return record; + return (record, reference); } /// @@ -108,12 +104,12 @@ private T Get() /// Next token of type , or if next token is not of expected /// type. /// - private T? GetOrDefault() + private (T Record, GdsHeader Header)? GetOrDefault() where T : IGdsRecord { - if (!IsNext()) return default; - _tokenOffset++; - return (T)_queue.Dequeue(); + if (!IsNext()) return null; + var reference = _queue.Dequeue(); + return ((T)reference.Record, reference.Header); } /// @@ -124,7 +120,7 @@ private T Get() private bool IsNext() where T : IGdsRecord { - return _queue.Peek() is T; + return _queue.Peek().Record is T; } /// @@ -135,8 +131,8 @@ private bool IsNext() /// If next token is not of expected type. private void GetNoData(GdsRecordNoDataType type) { - var token = Get(); - if (token.Type != type) throw new ParseException(type, token.Type, _tokenOffset); + var reference = Get(); + if (reference.Record.Type != type) throw new ParseException(type, reference.Record.Type, reference.Reference.Offset); } /// @@ -165,14 +161,14 @@ private GdsProperty ParseGdsProperty() { return new GdsProperty { - Attribute = Get().Value, - Value = Get().Value + Attribute = Get().Record.Value, + Value = Get().Record.Value }; } private GdsStrans ParseTransformation() { - var strans = Get(); + var strans = Get().Record; var returnObj = new GdsStrans { @@ -181,10 +177,10 @@ private GdsStrans ParseTransformation() AbsoluteMagnification = strans.AbsoluteMagnification }; - if (GetOrDefault() is { } mag) + if (GetOrDefault()?.Record is { } mag) returnObj.Magnification = mag.Value; - if (GetOrDefault() is { } angle) + if (GetOrDefault()?.Record is { } angle) returnObj.Angle = angle.Value; return returnObj; @@ -193,16 +189,16 @@ private GdsStrans ParseTransformation() private GdsBoxElement ParseGdsBoxElement() { GetNoData(GdsRecordNoDataType.Box); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var layer = Get(); - var boxType = Get(); - var xy = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var layer = Get().Record; + var boxType = Get().Record; + var xy = Get().Record; var elem = new GdsBoxElement { BoxType = boxType.Value, Layer = layer.Value, - Points = xy.Coordinates.AsGdsPoints() + Points = xy.Coordinates.ToList() }; FillElement(elem, flags, plex); @@ -213,16 +209,16 @@ private GdsBoxElement ParseGdsBoxElement() private GdsNodeElement ParseGdsNodeElement() { GetNoData(GdsRecordNoDataType.Node); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var layer = Get(); - var nodeType = Get(); - var xy = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var layer = Get().Record; + var nodeType = Get().Record; + var xy = Get().Record; var elem = new GdsNodeElement { Layer = layer.Value, - Points = xy.Coordinates.AsGdsPoints(), + Points = xy.Coordinates.ToList(), NodeType = nodeType.Value }; @@ -234,23 +230,23 @@ private GdsNodeElement ParseGdsNodeElement() private GdsTextElement ParseGdsTextElement() { GetNoData(GdsRecordNoDataType.Text); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var layer = Get(); - var textType = Get(); - var presentation = GetOrDefault(); - var pathType = GetOrDefault(); - var width = GetOrDefault(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var layer = Get().Record; + var textType = Get().Record; + var presentation = GetOrDefault()?.Record; + var pathType = GetOrDefault()?.Record; + var width = GetOrDefault()?.Record; var transformation = IsNext() ? ParseTransformation() : null; - var xy = Get(); - var str = Get(); + var xy = Get().Record; + var str = Get().Record; var elem = new GdsTextElement { Text = str.Value, Layer = layer.Value, TextType = textType.Value, - Points = xy.Coordinates.AsGdsPoints() + Points = xy.Coordinates.ToList() }; FillElement(elem, flags, plex); @@ -274,18 +270,18 @@ private GdsTextElement ParseGdsTextElement() private GdsArrayReferenceElement ParseGdsArrayReferenceElement() { GetNoData(GdsRecordNoDataType.Aref); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var name = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var name = Get().Record; var transformation = IsNext() ? ParseTransformation() : null; - var colRow = Get(); - var xy = Get(); + var colRow = Get().Record; + var xy = Get().Record; var elem = new GdsArrayReferenceElement { Columns = colRow.NumCols, Rows = colRow.NumRows, - Points = xy.Coordinates.AsGdsPoints(), + Points = xy.Coordinates.ToList(), // TODO StructureName = name.Value }; @@ -299,16 +295,16 @@ private GdsArrayReferenceElement ParseGdsArrayReferenceElement() private GdsStructureReferenceElement ParseGdsStructureReferenceElement() { GetNoData(GdsRecordNoDataType.Sref); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var name = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var name = Get().Record; var transformation = IsNext() ? ParseTransformation() : null; - var xy = Get(); + var xy = Get().Record; var elem = new GdsStructureReferenceElement { StructureName = name.Value, - Points = xy.Coordinates.AsGdsPoints() + Points = xy.Coordinates.ToList() // TDOO }; FillElement(elem, flags, plex); @@ -321,19 +317,19 @@ private GdsStructureReferenceElement ParseGdsStructureReferenceElement() private GdsPathElement ParseGdsPathElement() { GetNoData(GdsRecordNoDataType.Path); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var layer = Get(); - var dataType = Get(); - var pathType = GetOrDefault(); - var width = GetOrDefault(); - var xy = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var layer = Get().Record; + var dataType = Get().Record; + var pathType = GetOrDefault()?.Record; + var width = GetOrDefault()?.Record; + var xy = Get().Record; var elem = new GdsPathElement { DataType = dataType.Value, Layer = layer.Value, - Points = xy.Coordinates.AsGdsPoints() + Points = xy.Coordinates.ToList() // TODO }; FillElement(elem, flags, plex); @@ -348,17 +344,18 @@ private GdsPathElement ParseGdsPathElement() private GdsBoundaryElement ParseGdsBoundaryElement() { GetNoData(GdsRecordNoDataType.Boundary); - var flags = GetOrDefault(); - var plex = GetOrDefault(); - var layer = Get(); - var dataType = Get(); - var xy = Get(); + var flags = GetOrDefault()?.Record; + var plex = GetOrDefault()?.Record; + var layer = Get().Record; + var dataType = Get().Record; + var xy = Get().Record; var elem = new GdsBoundaryElement { DataType = dataType.Value, Layer = layer.Value, - Points = xy.Coordinates.AsGdsPoints() + Points = xy.Coordinates, + NumPoints = xy.NumPoints }; FillElement(elem, flags, plex); @@ -368,7 +365,7 @@ private GdsBoundaryElement ParseGdsBoundaryElement() private GdsElement ParseGdsElement() { - var token = Peek(); + var (token, reference) = Peek(); IGdsElement elem = token.Type switch { @@ -379,11 +376,11 @@ private GdsElement ParseGdsElement() GdsRecordNoDataType.Sref => ParseGdsStructureReferenceElement(), GdsRecordNoDataType.Path => ParseGdsPathElement(), GdsRecordNoDataType.Boundary => ParseGdsBoundaryElement(), - _ => throw new ParseException(token.Type, _tokenOffset) + _ => throw new ParseException(token.Type, reference.Offset) }; var properties = new List(); - while (_queue.Peek() is not GdsRecordNoData { Type: GdsRecordNoDataType.EndEl }) properties.Add(ParseGdsProperty()); + while (_queue.Peek().Record is not GdsRecordNoData { Type: GdsRecordNoDataType.EndEl }) properties.Add(ParseGdsProperty()); GetNoData(GdsRecordNoDataType.EndEl); @@ -394,15 +391,33 @@ private GdsElement ParseGdsElement() }; } + private IEnumerable ParseElements(long offset) + { + var oldPosition = _queue.SetPosition(offset); + try + { + while (_queue.Peek().Record is not GdsRecordNoData { Type: GdsRecordNoDataType.EndStr }) + yield return ParseGdsElement(); + GetNoData(GdsRecordNoDataType.EndStr); + } + finally + { + _queue.SetPosition(oldPosition); + } + } + private GdsStructure ParseGdsStructure() { - var bgnStr = Get(); - var name = Get(); + var bgnStr = Get().Record; + var (name, reference) = Get(); - var elements = new List(); - while (_queue.Peek() is not GdsRecordNoData { Type: GdsRecordNoDataType.EndStr }) elements.Add(ParseGdsElement()); + var elements = ParseElements(reference.Offset + reference.Header.Length); + + // Skip elements until the end of the structure + while (_queue.Dequeue().Record is not GdsRecordNoData { Type: GdsRecordNoDataType.EndStr }) + { + } - GetNoData(GdsRecordNoDataType.EndStr); return new GdsStructure { Name = name.Value, @@ -414,5 +429,20 @@ private GdsStructure ParseGdsStructure() }; } + private IEnumerable ParseStructures(long position) + { + var oldPosition = _queue.SetPosition(position); + try + { + while (_queue.Peek().Record is not GdsRecordNoData { Type: GdsRecordNoDataType.EndLib }) + yield return ParseGdsStructure(); + GetNoData(GdsRecordNoDataType.EndLib); + } + finally + { + _queue.SetPosition(oldPosition); + } + } + #endregion } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/GdsPoint.cs b/GdsSharp.Lib/GdsPoint.cs similarity index 83% rename from GdsSharp.Lib/NonTerminals/GdsPoint.cs rename to GdsSharp.Lib/GdsPoint.cs index 3a3d776..36f8524 100644 --- a/GdsSharp.Lib/NonTerminals/GdsPoint.cs +++ b/GdsSharp.Lib/GdsPoint.cs @@ -1,8 +1,8 @@ using System.Numerics; -namespace GdsSharp.Lib.NonTerminals; +namespace GdsSharp.Lib; -public struct GdsPoint +public readonly struct GdsPoint { public GdsPoint(int x, int y) { @@ -20,8 +20,14 @@ public GdsPoint(float x, float y) Y = (int)MathF.Round(y); } - public int X { get; set; } - public int Y { get; set; } + public GdsPoint(double x, double y) + { + X = (int)Math.Round(x); + Y = (int)Math.Round(y); + } + + public readonly int X; + public readonly int Y; public static GdsPoint operator +(GdsPoint a, GdsPoint b) => new(a.X + b.X, a.Y + b.Y); public static GdsPoint operator -(GdsPoint a, GdsPoint b) => new(a.X - b.X, a.Y - b.Y); @@ -38,4 +44,9 @@ public GdsPoint(float x, float y) public static GdsPoint operator *(int a, GdsPoint b) => new(a * b.X, a * b.Y); public static GdsPoint operator /(int a, GdsPoint b) => new(a / b.X, a / b.Y); public static GdsPoint operator %(int a, GdsPoint b) => new(a % b.X, a % b.Y); + + public override string ToString() + { + return $"({X}, {Y})"; + } } \ No newline at end of file diff --git a/GdsSharp.Lib/GdsSharp.Lib.csproj b/GdsSharp.Lib/GdsSharp.Lib.csproj index b0ca84d..56f7bb3 100644 --- a/GdsSharp.Lib/GdsSharp.Lib.csproj +++ b/GdsSharp.Lib/GdsSharp.Lib.csproj @@ -11,13 +11,19 @@ README.md LICENSE true - https://github.com/BorisGerretzen/GdsSharp + https://github.com/BorisGerretzen/GdsSharp.git Boris Gerretzen GDSII, calma, eda, photomask, lithography, ic + A C# library for reading, editing, and writing Calma GDSII files. git - + + true + true + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + + True @@ -29,8 +35,4 @@ - - - - diff --git a/GdsSharp.Lib/GdsTokenizer.cs b/GdsSharp.Lib/GdsTokenizer.cs deleted file mode 100644 index 568f968..0000000 --- a/GdsSharp.Lib/GdsTokenizer.cs +++ /dev/null @@ -1,47 +0,0 @@ -using GdsSharp.Lib.Abstractions; -using GdsSharp.Lib.Binary; -using GdsSharp.Lib.Terminals; -using GdsSharp.Lib.Terminals.Abstractions; - -namespace GdsSharp.Lib; - -public class GdsTokenizer : GdsStreamOperator -{ - private readonly GdsBinaryReader _reader; - - public GdsTokenizer(Stream stream) - { - _reader = new GdsBinaryReader(stream); - } - - /// - /// Tokenizes the stream. - /// - /// Cancellation token. - /// IEnumerable of the found tokens. - /// If an invalid record code is found or lengths mismatch. - public IEnumerable Tokenize(CancellationToken token = default) - { - while (!token.IsCancellationRequested && _reader.BaseStream.Position < _reader.BaseStream.Length) - { - var currentHeader = new GdsHeader(); - ((IGdsSimpleRead)currentHeader).Read(_reader, currentHeader); - - // Stop when padding is reached - if (currentHeader is { Code: 0, Length: 0 }) yield break; - - // Get record - if (!Activators.TryGetValue(currentHeader.Code, out var activator)) - throw new InvalidOperationException( - $"Could not find activator for code 0x{currentHeader.Code:X} ({currentHeader.Code}) at position 0x{_reader.BaseStream.Position:X} ({_reader.BaseStream.Position})"); - var record = activator.Invoke(); - - if (record is IGdsReadableRecord readableRecord) readableRecord.Read(_reader, currentHeader); - if (record.GetLength() != currentHeader.NumToRead) - throw new InvalidOperationException( - $"Record length mismatch at position 0x{_reader.BaseStream.Position:X} ({_reader.BaseStream.Position}), expected {currentHeader.NumToRead}, got {record.GetLength()}"); - - yield return record; - } - } -} \ No newline at end of file diff --git a/GdsSharp.Lib/GdsWriter.cs b/GdsSharp.Lib/GdsWriter.cs index 830e68f..d2dc23b 100644 --- a/GdsSharp.Lib/GdsWriter.cs +++ b/GdsSharp.Lib/GdsWriter.cs @@ -2,7 +2,7 @@ using GdsSharp.Lib.Binary; using GdsSharp.Lib.Terminals; using GdsSharp.Lib.Terminals.Abstractions; - +using GdsSharp.Lib.Terminals.Records; namespace GdsSharp.Lib; public class GdsWriter : GdsStreamOperator diff --git a/GdsSharp.Lib/Lexing/GdsTokenReference.cs b/GdsSharp.Lib/Lexing/GdsTokenReference.cs new file mode 100644 index 0000000..5e35233 --- /dev/null +++ b/GdsSharp.Lib/Lexing/GdsTokenReference.cs @@ -0,0 +1,6 @@ +using GdsSharp.Lib.Terminals; +using GdsSharp.Lib.Terminals.Abstractions; + +namespace GdsSharp.Lib.Lexing; + +public record GdsTokenReference(GdsHeader Header, IGdsRecord Record, long Offset); \ No newline at end of file diff --git a/GdsSharp.Lib/Lexing/GdsTokenStream.cs b/GdsSharp.Lib/Lexing/GdsTokenStream.cs new file mode 100644 index 0000000..5fa82fb --- /dev/null +++ b/GdsSharp.Lib/Lexing/GdsTokenStream.cs @@ -0,0 +1,131 @@ +using System.Collections; +using GdsSharp.Lib.Abstractions; +using GdsSharp.Lib.Binary; +using GdsSharp.Lib.Terminals; +using GdsSharp.Lib.Terminals.Abstractions; +using GdsSharp.Lib.Terminals.Records; + +namespace GdsSharp.Lib.Lexing; + +public class GdsTokenStream : GdsStreamOperator, IDisposable, IEnumerable +{ + private readonly GdsBinaryReader _reader; + + public GdsTokenStream(Stream stream) + { + _reader = new GdsBinaryReader(stream); + } + + /// + public void Dispose() + { + _reader.Dispose(); + GC.SuppressFinalize(this); + } + + /// + public IEnumerator GetEnumerator() + { + GdsTokenReference? element; + while ((element = Read()) != null) yield return element.Record; + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Peeks at the next item in the queue. + /// + /// Next item in the queue. + /// If queue is empty. + public GdsTokenReference Peek() + { + var position = _reader.BaseStream.Position; + try + { + return Dequeue(); + } + finally + { + SetPosition(position); + } + } + + /// + /// Dequeues the next item in the queue. + /// + /// Next item in the queue. + /// If queue is empty. + public GdsTokenReference Dequeue() + { + var element = Read(); + if (element is null) throw new InvalidOperationException("No more items in the queue."); + return element; + } + + /// + /// Sets the position of the reader. + /// + /// Position in the stream. + /// Old position. + public long SetPosition(long position) + { + var oldPosition = _reader.BaseStream.Position; + _reader.BaseStream.Position = position; + return oldPosition; + } + + private GdsTokenReference? Read() + { + var pos = _reader.BaseStream.Position; + if (pos == _reader.BaseStream.Length) return null; + + var header = new GdsHeader(); + ((IGdsSimpleRead)header).Read(_reader, header); + + // Stop when padding is reached + if (header is { Code: 0, Length: 0 }) return null; + + // Get record + if (!Activators.TryGetValue(header.Code, out var activator)) + throw new InvalidOperationException( + $"Could not find activator for code 0x{header.Code:X} ({header.Code}) at position 0x{_reader.BaseStream.Position:X} ({_reader.BaseStream.Position})"); + var record = activator.Invoke(); + + switch (record) + { + case GdsRecordXy xy: + xy.NumPoints = header.NumToRead / 8; + xy.Coordinates = ReadGdsPoints(_reader.BaseStream.Position, header); + _reader.BaseStream.Position += header.NumToRead; + break; + case IGdsReadableRecord readableRecord: + readableRecord.Read(_reader, header); + break; + } + + if (record.GetLength() != header.NumToRead) + throw new InvalidOperationException( + $"Record length mismatch at position 0x{_reader.BaseStream.Position:X} ({_reader.BaseStream.Position}), expected {header.NumToRead}, got {record.GetLength()}"); + + return new GdsTokenReference(header, record, pos); + } + + private IEnumerable ReadGdsPoints(long offset, GdsHeader header) + { + var oldPosition = _reader.BaseStream.Position; + try + { + _reader.BaseStream.Position = offset; + for (var i = 0; i < header.NumToRead / 8; i++) + yield return new GdsPoint(_reader.ReadInt32(), _reader.ReadInt32()); + } + finally + { + _reader.BaseStream.Position = oldPosition; + } + } +} \ No newline at end of file diff --git a/GdsSharp.Lib/GdsTokenWriter.cs b/GdsSharp.Lib/Lexing/GdsTokenWriter.cs similarity index 94% rename from GdsSharp.Lib/GdsTokenWriter.cs rename to GdsSharp.Lib/Lexing/GdsTokenWriter.cs index 9d83c54..8281a56 100644 --- a/GdsSharp.Lib/GdsTokenWriter.cs +++ b/GdsSharp.Lib/Lexing/GdsTokenWriter.cs @@ -5,7 +5,7 @@ using GdsSharp.Lib.Terminals.Abstractions; using GdsSharp.Lib.Terminals.Records; -namespace GdsSharp.Lib; +namespace GdsSharp.Lib.Lexing; public class GdsTokenWriter { @@ -49,8 +49,12 @@ public IEnumerable Tokenize() yield return new GdsRecordUnits { PhysicalUnits = _file.PhysicalUnits, UserUnits = _file.UserUnits }; - foreach (var records in _file.Structures.SelectMany(TokenizeStructure)) yield return records; - + foreach (var structure in _file.Structures) + { + foreach (var record in TokenizeStructure(structure)) + yield return record; + } + yield return new GdsRecordNoData { Type = GdsRecordNoDataType.EndLib }; } @@ -125,7 +129,7 @@ private IEnumerable TokenizeTextElement(GdsTextElement textElement) foreach (var record in TokenizeTransform(textElement.Transformation)) yield return record; - yield return new GdsRecordXy { Coordinates = textElement.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = textElement.Points, NumPoints = textElement.Points.Count }; yield return new GdsRecordString { Value = textElement.Text }; } @@ -137,7 +141,7 @@ private IEnumerable TokenizeBoxElement(GdsBoxElement boxElement) yield return new GdsRecordBoxType { Value = boxElement.BoxType }; - yield return new GdsRecordXy { Coordinates = boxElement.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = boxElement.Points, NumPoints = boxElement.Points.Count}; } private IEnumerable TokenizeNodeElement(GdsNodeElement nodeElement) @@ -148,7 +152,7 @@ private IEnumerable TokenizeNodeElement(GdsNodeElement nodeElement) yield return new GdsRecordNodeType { Value = nodeElement.NodeType }; - yield return new GdsRecordXy { Coordinates = nodeElement.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = nodeElement.Points, NumPoints = nodeElement.Points.Count}; } private IEnumerable TokenizeArrayReferenceElement(GdsArrayReferenceElement arrayReferenceElement) @@ -163,7 +167,7 @@ private IEnumerable TokenizeArrayReferenceElement(GdsArrayReferenceE yield return new GdsRecordColRow { NumCols = (short)arrayReferenceElement.Columns, NumRows = (short)arrayReferenceElement.Rows }; - yield return new GdsRecordXy { Coordinates = arrayReferenceElement.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = arrayReferenceElement.Points, NumPoints = arrayReferenceElement.Points.Count }; } private IEnumerable TokenizeStructureReferenceElement(GdsStructureReferenceElement element) @@ -176,7 +180,7 @@ private IEnumerable TokenizeStructureReferenceElement(GdsStructureRe foreach (var record in TokenizeTransform(element.Transformation)) yield return record; - yield return new GdsRecordXy { Coordinates = element.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = element.Points, NumPoints = element.Points.Count}; } private IEnumerable TokenizePathElement(GdsPathElement element) @@ -191,7 +195,7 @@ private IEnumerable TokenizePathElement(GdsPathElement element) if (element.Width != 0) yield return new GdsRecordWidth { Value = element.Width }; - yield return new GdsRecordXy { Coordinates = element.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = element.Points, NumPoints = element.Points.Count}; } private IEnumerable TokenizeBoundaryElement(GdsBoundaryElement element) @@ -202,7 +206,7 @@ private IEnumerable TokenizeBoundaryElement(GdsBoundaryElement eleme yield return new GdsRecordDataType { Value = element.DataType }; - yield return new GdsRecordXy { Coordinates = element.Points.AsTuplePoints() }; + yield return new GdsRecordXy { Coordinates = element.Points, NumPoints = element.NumPoints}; } private IEnumerable TokenizeElement(GdsElement element) @@ -246,7 +250,8 @@ private IEnumerable TokenizeStructure(GdsStructure structure) yield return new GdsRecordStrName { Value = structure.Name }; - foreach (var record in structure.Elements.SelectMany(TokenizeElement)) yield return record; + foreach (var record in structure.Elements.SelectMany(TokenizeElement)) + yield return record; yield return new GdsRecordNoData { Type = GdsRecordNoDataType.EndStr }; } diff --git a/GdsSharp.Lib/NonTerminals/Abstractions/IGdsElement.cs b/GdsSharp.Lib/NonTerminals/Abstractions/IGdsElement.cs index 10e5f28..f60356e 100644 --- a/GdsSharp.Lib/NonTerminals/Abstractions/IGdsElement.cs +++ b/GdsSharp.Lib/NonTerminals/Abstractions/IGdsElement.cs @@ -1,3 +1,5 @@ +using GdsSharp.Lib.NonTerminals.Elements; + namespace GdsSharp.Lib.NonTerminals.Abstractions; public interface IGdsElement @@ -5,4 +7,19 @@ public interface IGdsElement bool ExternalData { get; set; } bool TemplateData { get; set; } int PlexNumber { get; set; } + + /// + /// Materializes the children of the element. + /// In practice only used for to materialize the points. + /// + virtual void Materialize() + { + } + + /// + /// Calculates the bounding box of the element. + /// + /// Maps structure names to structure objects. + /// The bounding box of the element. + GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider); } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsArrayReferenceElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsArrayReferenceElement.cs index fb0baf2..6a3ad6b 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsArrayReferenceElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsArrayReferenceElement.cs @@ -12,4 +12,17 @@ public class GdsArrayReferenceElement : IGdsElement public bool ExternalData { get; set; } public bool TemplateData { get; set; } public int PlexNumber { get; set; } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + var structure = structureProvider(StructureName); + if (structure == null) + throw new KeyNotFoundException($"Structure with name '{StructureName}' not found."); + + var boundingBox = structure.GetBoundingBox(structureProvider); + if (boundingBox.IsEmpty) return boundingBox; + var boundingBoxes = Points.Select(p => new GdsBoundingBox(p + boundingBox.Min, p + boundingBox.Max)); + return new GdsBoundingBox(boundingBoxes); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsBoundaryElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsBoundaryElement.cs index fc38f88..ef7616f 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsBoundaryElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsBoundaryElement.cs @@ -5,9 +5,22 @@ namespace GdsSharp.Lib.NonTerminals.Elements; public class GdsBoundaryElement : IGdsLayeredElement { public short DataType { get; set; } - public List Points { get; set; } = new(); + public IEnumerable Points { get; set; } = new List(); + public required int NumPoints { get; set; } public bool ExternalData { get; set; } public bool TemplateData { get; set; } public int PlexNumber { get; set; } public short Layer { get; set; } + + /// + public void Materialize() + { + Points = Points.ToList(); + } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + return new GdsBoundingBox(Points); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsBoxElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsBoxElement.cs index ce8e6d6..4578a96 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsBoxElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsBoxElement.cs @@ -15,4 +15,10 @@ public class GdsBoxElement : IGdsLayeredElement public bool TemplateData { get; set; } public int PlexNumber { get; set; } public short Layer { get; set; } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + return new GdsBoundingBox(Points); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsElement.cs index 65af966..977e1b2 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsElement.cs @@ -6,4 +6,12 @@ public class GdsElement { public required IGdsElement Element { get; set; } public List Properties { get; set; } = new(); + + /// + /// Materializes the element. + /// + public void Materialize() + { + Element.Materialize(); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsNodeElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsNodeElement.cs index ae645d2..398400d 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsNodeElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsNodeElement.cs @@ -10,4 +10,10 @@ public class GdsNodeElement : IGdsLayeredElement public bool TemplateData { get; set; } public int PlexNumber { get; set; } public short Layer { get; set; } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + return new GdsBoundingBox(Points); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsPathElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsPathElement.cs index 158a479..81d11d4 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsPathElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsPathElement.cs @@ -14,4 +14,30 @@ public class GdsPathElement : IGdsLayeredElement public bool TemplateData { get; set; } public int PlexNumber { get; set; } public short Layer { get; set; } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + var segments = Points.Zip(Points.Skip(1)); + var coordinates = segments + .Select(segment => + { + var (start, end) = segment; + var dx = end.X - start.X; + var dy = end.Y - start.Y; + return (start, end, dy, dy: -dx); + }) + .SelectMany(row => + { + return new[] + { + new GdsPoint(row.start.X + row.dy * Width / 2, row.start.Y + row.dy * Width / 2), + new GdsPoint(row.start.X - row.dy * Width / 2, row.start.Y - row.dy * Width / 2), + new GdsPoint(row.end.X - row.dy * Width / 2, row.end.Y - row.dy * Width / 2), + new GdsPoint(row.end.X + row.dy * Width / 2, row.end.Y + row.dy * Width / 2) + }; + }); + + return new GdsBoundingBox(coordinates); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsStructureReferenceElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsStructureReferenceElement.cs index 8bd2bf0..99886e6 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsStructureReferenceElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsStructureReferenceElement.cs @@ -10,4 +10,17 @@ public class GdsStructureReferenceElement : IGdsElement public bool ExternalData { get; set; } public bool TemplateData { get; set; } public int PlexNumber { get; set; } + + /// + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + var structure = structureProvider(StructureName); + if (structure == null) + throw new KeyNotFoundException($"Structure {StructureName} not found"); + + var boundingBox = structure.GetBoundingBox(structureProvider); + if (boundingBox.IsEmpty) return boundingBox; + var boundingBoxes = Points.Select(p => new GdsBoundingBox(p + boundingBox.Min, p + boundingBox.Max)); + return new GdsBoundingBox(boundingBoxes); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/Elements/GdsTextElement.cs b/GdsSharp.Lib/NonTerminals/Elements/GdsTextElement.cs index 23325cf..f350941 100644 --- a/GdsSharp.Lib/NonTerminals/Elements/GdsTextElement.cs +++ b/GdsSharp.Lib/NonTerminals/Elements/GdsTextElement.cs @@ -19,4 +19,9 @@ public class GdsTextElement : IGdsLayeredElement public bool TemplateData { get; set; } public int PlexNumber { get; set; } public short Layer { get; set; } + + public GdsBoundingBox GetBoundingBox(GdsStructure.StructureProvider structureProvider) + { + return new GdsBoundingBox(); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/GdsFormatType.cs b/GdsSharp.Lib/NonTerminals/Enum/GdsFormatType.cs similarity index 71% rename from GdsSharp.Lib/NonTerminals/GdsFormatType.cs rename to GdsSharp.Lib/NonTerminals/Enum/GdsFormatType.cs index b039189..2ff6437 100644 --- a/GdsSharp.Lib/NonTerminals/GdsFormatType.cs +++ b/GdsSharp.Lib/NonTerminals/Enum/GdsFormatType.cs @@ -1,4 +1,4 @@ -namespace GdsSharp.Lib.NonTerminals; +namespace GdsSharp.Lib.NonTerminals.Enum; public enum GdsFormatType { diff --git a/GdsSharp.Lib/NonTerminals/GdsFile.cs b/GdsSharp.Lib/NonTerminals/GdsFile.cs deleted file mode 100644 index c92590c..0000000 --- a/GdsSharp.Lib/NonTerminals/GdsFile.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace GdsSharp.Lib.NonTerminals; - -public class GdsFile -{ - public short Version { get; set; } = 5; - public required string LibraryName { get; set; } - public DateTime LastModificationTime { get; set; } = DateTime.Now; - public DateTime LastAccessTime { get; set; } = DateTime.Now; - public List ReferencedLibraries { get; set; } = new(); - public List Fonts { get; set; } = new(); - public string? AttributeDefinitionFile { get; set; } - public short Generations { get; set; } = 3; - public required double UserUnits { get; set; } - public required double PhysicalUnits { get; set; } - public GdsFormatType FormatType { get; set; } = GdsFormatType.GdsArchive; - public List Structures { get; set; } = new(); - - public static GdsFile From(Stream stream) - { - var tokenizer = new GdsTokenizer(stream); - var tokens = tokenizer.Tokenize(); - var parser = new GdsParser(tokens); - return parser.Parse(); - } - - public void WriteTo(Stream stream) - { - var tokenWriter = new GdsTokenWriter(this); - var tokens = tokenWriter.Tokenize(); - GdsWriter.Write(tokens, stream); - } -} \ No newline at end of file diff --git a/GdsSharp.Lib/NonTerminals/GdsStructure.cs b/GdsSharp.Lib/NonTerminals/GdsStructure.cs index f18f7a2..231be1a 100644 --- a/GdsSharp.Lib/NonTerminals/GdsStructure.cs +++ b/GdsSharp.Lib/NonTerminals/GdsStructure.cs @@ -4,8 +4,35 @@ namespace GdsSharp.Lib.NonTerminals; public class GdsStructure { + public delegate GdsStructure? StructureProvider(string structureName); + public required string Name { get; set; } public DateTime CreationTime { get; set; } = DateTime.Now; public DateTime ModificationTime { get; set; } = DateTime.Now; - public List Elements { get; set; } = new(); + public IEnumerable Elements { get; set; } = new List(); + + /// + /// Materializes all elements in the structure. + /// + public void Materialize() + { + var elements = Elements.ToList(); + foreach (var element in elements) + { + element.Materialize(); + } + + Elements = elements; + } + + /// + /// Calculates the bounding box of the structure. + /// + /// Maps structure names to structure objects. + /// Bounding box of the structure. + public GdsBoundingBox GetBoundingBox(StructureProvider structureProvider) + { + var boundingBoxes = Elements.Select(e => e.Element.GetBoundingBox(structureProvider)); + return new GdsBoundingBox(boundingBoxes); + } } \ No newline at end of file diff --git a/GdsSharp.Lib/ParseException.cs b/GdsSharp.Lib/ParseException.cs index d7e53cc..984dd36 100644 --- a/GdsSharp.Lib/ParseException.cs +++ b/GdsSharp.Lib/ParseException.cs @@ -4,15 +4,15 @@ namespace GdsSharp.Lib; public class ParseException : Exception { - public ParseException(Type expected, object actual, int offset) : base($"Expected token {expected.Name} but found {actual.GetType().Name} at offset {offset}.") + public ParseException(Type expected, object actual, long offset) : base($"Expected token {expected.Name} but found {actual.GetType().Name} at offset {offset:X} ({offset}).") { } - public ParseException(GdsRecordNoDataType expected, GdsRecordNoDataType actual, int offset) : base($"Expected token {expected} but found {actual} at offset {offset}.") + public ParseException(GdsRecordNoDataType expected, GdsRecordNoDataType actual, long offset) : base($"Expected token {expected} but found {actual} at offset {offset:X} ({offset}).") { } - public ParseException(GdsRecordNoDataType unexpected, int offset) : base($"Unexpected token {unexpected} at offset {offset}.") + public ParseException(GdsRecordNoDataType unexpected, long offset) : base($"Unexpected token {unexpected} at offset {offset:X} ({offset}).") { } } \ No newline at end of file diff --git a/GdsSharp.Lib/Terminals/Records/GdsRecordNoData.cs b/GdsSharp.Lib/Terminals/Records/GdsRecordNoData.cs index e4030ed..0b759c8 100644 --- a/GdsSharp.Lib/Terminals/Records/GdsRecordNoData.cs +++ b/GdsSharp.Lib/Terminals/Records/GdsRecordNoData.cs @@ -8,6 +8,7 @@ public struct GdsRecordNoData : IGdsWriteableRecord public required GdsRecordNoDataType Type { get; init; } public ushort Code => (ushort)Type; + public string CodeHex => Code.ToString("X4"); public ushort GetLength() { diff --git a/GdsSharp.Lib/Terminals/Records/GdsRecordXy.cs b/GdsSharp.Lib/Terminals/Records/GdsRecordXy.cs index 304b73e..fe96f4d 100644 --- a/GdsSharp.Lib/Terminals/Records/GdsRecordXy.cs +++ b/GdsSharp.Lib/Terminals/Records/GdsRecordXy.cs @@ -1,31 +1,32 @@ using GdsSharp.Lib.Binary; +using GdsSharp.Lib.NonTerminals; using GdsSharp.Lib.Terminals.Abstractions; namespace GdsSharp.Lib.Terminals.Records; -public class GdsRecordXy : IGdsReadableRecord, IGdsWriteableRecord +public class GdsRecordXy : IGdsWriteableRecord { - public List<(int X, int Y)> Coordinates { get; set; } = new(); - - public void Read(GdsBinaryReader reader, GdsHeader header) + public required IEnumerable Coordinates { get; set; } + public required int NumPoints { get; set; } + + public GdsRecordXy() { - var numCoordinates = header.NumToRead / 8; - for (var i = 0; i < numCoordinates; i++) Coordinates.Add((reader.ReadInt32(), reader.ReadInt32())); + Coordinates = new List(); } - + public ushort Code => 0x1003; public ushort GetLength() { - return (ushort)(Coordinates.Count * 8); + return (ushort)(NumPoints * 8); } public void Write(GdsBinaryWriter writer) { - foreach (var (x, y) in Coordinates) + foreach (var point in Coordinates) { - writer.Write(x); - writer.Write(y); + writer.Write(point.X); + writer.Write(point.Y); } } } \ No newline at end of file diff --git a/GdsSharp.sln b/GdsSharp.sln index 929fb3b..e19b2c4 100644 --- a/GdsSharp.sln +++ b/GdsSharp.sln @@ -8,6 +8,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "_build", "build\_build.cspr EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GdsGenerator", "GdsGenerator\GdsGenerator.csproj", "{90695895-33A3-4C42-A733-F3A90E27A69F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GdsSharp.Benchmarks", "GdsSharp.Benchmarks\GdsSharp.Benchmarks.csproj", "{B7DCE78E-B318-4D94-BB6B-40D7025CE396}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -28,5 +30,9 @@ Global {90695895-33A3-4C42-A733-F3A90E27A69F}.Debug|Any CPU.Build.0 = Debug|Any CPU {90695895-33A3-4C42-A733-F3A90E27A69F}.Release|Any CPU.ActiveCfg = Release|Any CPU {90695895-33A3-4C42-A733-F3A90E27A69F}.Release|Any CPU.Build.0 = Release|Any CPU + {B7DCE78E-B318-4D94-BB6B-40D7025CE396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7DCE78E-B318-4D94-BB6B-40D7025CE396}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7DCE78E-B318-4D94-BB6B-40D7025CE396}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7DCE78E-B318-4D94-BB6B-40D7025CE396}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/LICENSE b/LICENSE index ee9ed41..153d416 100644 --- a/LICENSE +++ b/LICENSE @@ -1,504 +1,165 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! \ No newline at end of file + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/README.md b/README.md index c988da2..3ae6a8e 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![NuGet](https://img.shields.io/nuget/v/GdsSharp.svg)](https://www.nuget.org/packages/GdsSharp/)\ A library for reading, editing, and writing [Calma GDSII](https://en.wikipedia.org/wiki/GDSII) files. +The library supports reading and writing in a streaming fashion so it can handle large files. Some helpers are also provided for drawing shapes like circles and Bézier curves. Additionally, a path builder is included to create parameterized paths with multiple segments. diff --git a/build/_build.csproj.DotSettings b/build/_build.csproj.DotSettings index eb3f4c2..c815d36 100644 --- a/build/_build.csproj.DotSettings +++ b/build/_build.csproj.DotSettings @@ -17,6 +17,8 @@ False <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> True True True @@ -25,4 +27,5 @@ True True True - True + True + True