Example #1
0
        public static Bitmap CreateAutoSizedBitmap(
            DxfModel model,
            DxfLayout layout,
            ICollection <DxfViewport> viewports,
            Matrix4D transform,
            GraphicsConfig graphicsConfig,
            SmoothingMode smoothingMode,
            System.Drawing.Color backColor,
            Size maxSize)
        {
            BoundsCalculator boundsCalculator = new BoundsCalculator(graphicsConfig);

            boundsCalculator.GetBounds(model, layout, viewports, transform);
            Bounds3D bounds = boundsCalculator.Bounds;

            if (!bounds.Initialized)
            {
                return(ImageExporter.CreateEmptyBitmap(backColor, maxSize.Width, maxSize.Height));
            }
            int      num1           = maxSize.Width - 4;
            int      num2           = maxSize.Height - 4;
            Matrix4D scaleTransform = DxfUtil.GetScaleTransform(bounds.Corner1, bounds.Corner2, new WW.Math.Point3D(bounds.Corner1.X, bounds.Corner2.Y, 0.0), new WW.Math.Point3D(0.0, (double)num2, 0.0), new WW.Math.Point3D((double)num1, 0.0, 0.0), new WW.Math.Point3D(2.0, 2.0, 0.0));
            Matrix4D to2DTransform  = scaleTransform * transform;

            WW.Math.Vector3D vector3D = scaleTransform.Transform(bounds.Corner2) - scaleTransform.Transform(bounds.Corner1);
            int width  = System.Math.Min(maxSize.Width, (int)System.Math.Ceiling(System.Math.Abs(vector3D.X)) + 4);
            int height = System.Math.Min(maxSize.Height, (int)System.Math.Ceiling(System.Math.Abs(vector3D.Y)) + 4);

            return(ImageExporter.CreateBitmap(model, layout, viewports, graphicsConfig, smoothingMode, backColor, to2DTransform, width, height));
        }
Example #2
0
        private static Image <Bgra32> RenderToBitmap(DxfModel model)
        {
            var graphicsConfig = (GraphicsConfig)GraphicsConfig.AcadLikeWithWhiteBackground.Clone();

            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(model);
            Bounds3D bounds = boundsCalculator.Bounds;

            int      size      = 2000;
            Matrix4D transform = DxfUtil.GetScaleTransform(
                bounds.Min,
                bounds.Max,
                bounds.Center,
                new Point3D(0, size, 0),
                new Point3D(size, 0, 0),
                new Point3D(0.5d * size, 0.5d * size, 0)
                );

            Memory <Bgra32> memory = new Memory <Bgra32>();

            Image.WrapMemory <Bgra32>(memory, 10, 10);
            Image <Bgra32> bitmap = ImageExporter.CreateBitmap <Bgra32>(
                model, transform,
                graphicsConfig,
                //new GraphicsOptions(false),
                new Size(size, size));

            return(bitmap);
        }
Example #3
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            if (!model.GetShowReactionBoxes())
            {
                return(null);
            }
            var separation  = model.GetBondLength() / model.GetScale();
            var totalBounds = BoundsCalculator.CalculateBounds(reaction);

            if (totalBounds.IsEmpty)
            {
                return(null);
            }

            var diagram         = new ElementGroup();
            var foregroundColor = model.GetForegroundColor();

            diagram.Add(new RectangleElement(new Rect(totalBounds.Left - separation, totalBounds.Top - separation,
                                                      totalBounds.Right + separation, totalBounds.Bottom + separation),
                                             foregroundColor));
            if (reaction.Id != null)
            {
                diagram.Add(new TextElement(new Point((totalBounds.Left + totalBounds.Right) / 2, totalBounds.Top - separation),
                                            reaction.Id, foregroundColor));
            }
            return(diagram);
        }
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            if (!model.GetShowReactionBoxes())
            {
                return(null);
            }
            if (reaction.Reactants.Count == 0)
            {
                return(new ElementGroup());
            }

            double separation  = model.GetBondLength() / model.GetScale() / 2;
            var    totalBounds = BoundsCalculator.CalculateBounds(reaction.Reactants);

            ElementGroup diagram         = new ElementGroup();
            double       minX            = totalBounds.Left;
            double       minY            = totalBounds.Top;
            double       maxX            = totalBounds.Right;
            double       maxY            = totalBounds.Bottom;
            var          foregroundColor = model.GetForegroundColor();

            diagram.Add(new RectangleElement(new Rect(minX - separation, minY - separation, maxX + separation, maxY + separation), foregroundColor));
            diagram.Add(new TextElement(new Point((minX + maxX) / 2, minY - separation), "Reactants", foregroundColor));
            return(diagram);
        }
        public RectangleF GetBounds(PointF pos, AngularCalculator aCalc)
        {
            var hWidth  = _width / 2;
            var hHeight = _height / 2;

            var points = new List <PointF>
            {
                aCalc.Turn(new PointF(pos.X - hWidth, pos.Y - hHeight)),
                aCalc.Turn(new PointF(pos.X + hWidth, pos.Y - hHeight)),
                aCalc.Turn(new PointF(pos.X + hWidth, pos.Y + hHeight)),
                aCalc.Turn(new PointF(pos.X - hWidth, pos.Y + hHeight))
            };

            return(BoundsCalculator.CalculateBounds(points));
        }
Example #6
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            if (!model.GetShowReactionBoxes())
            {
                return(null);
            }
            if (reaction.Products.Count == 0)
            {
                return(new ElementGroup());
            }
            double distance    = model.GetBondLength() / model.GetScale() / 2;
            Rect?  totalBounds = null;

            foreach (var molecule in reaction.Products)
            {
                var bounds = BoundsCalculator.CalculateBounds(molecule);
                if (totalBounds == null)
                {
                    totalBounds = bounds;
                }
                else
                {
                    totalBounds = Rect.Union(totalBounds.Value, bounds);
                }
            }
            if (totalBounds == null)
            {
                return(null);
            }

            ElementGroup diagram         = new ElementGroup();
            var          foregroundColor = model.GetForegroundColor();

            diagram.Add(new RectangleElement(
                            new Rect(
                                totalBounds.Value.Left - distance,
                                totalBounds.Value.Top - distance,
                                totalBounds.Value.Right + distance,
                                totalBounds.Value.Bottom + distance),
                            foregroundColor));
            diagram.Add(new TextElement(
                            new Point(
                                (totalBounds.Value.Left + totalBounds.Value.Right) / 2,
                                totalBounds.Value.Top - distance),
                            "Products", foregroundColor));
            return(diagram);
        }
Example #7
0
        void ILeader.imethod_0(
            DrawContext context,
            IList <WW.Math.Point3D> points,
            IList <WW.Math.Point3D> polyline)
        {
            DxfEntity entity = this.dxfObjectReference_6.Value as DxfEntity;

            if (entity == null)
            {
                return;
            }
            WW.Math.Point3D point = points[points.Count - 1];
            Vector3D        zaxis = this.HorizontalDirection;

            zaxis.Normalize();
            if (this.hookLineDirection_0 == HookLineDirection.Same)
            {
                zaxis = -zaxis;
            }
            BoundsCalculator boundsCalculator = new BoundsCalculator(context.Config);
            Matrix4D         transpose        = DxfUtil.GetToWCSTransform(zaxis).GetTranspose();
            Matrix4D         matrix4D         = Transformation4D.Translation(-(Vector3D)point);

            boundsCalculator.GetBounds(context.Model, entity, transpose * matrix4D);
            Bounds3D bounds = boundsCalculator.Bounds;

            if (!bounds.Initialized)
            {
                return;
            }
            double z1   = bounds.Min.Z;
            double z2   = bounds.Max.Z;
            double num1 = 0.5 * (z1 + z2);
            bool   flag = this.dxfDimensionStyleOverrides_0.TextVerticalAlignment != DimensionTextVerticalAlignment.Above && this.dxfDimensionStyleOverrides_0.TextVerticalPosition >= -0.7 && this.dxfDimensionStyleOverrides_0.TextVerticalPosition <= 0.7;
            double num2 = this.dxfDimensionStyleOverrides_0.ScaleFactor;

            if (num2 == 0.0)
            {
                num2 = 1.0;
            }
            double num3 = this.dxfDimensionStyleOverrides_0.DimensionLineGap * num2;
            double num4 = !flag ? (num1 < 0.0 ? z1 : z2) : System.Math.Max(z1 - num3, 0.0);

            polyline.Add(point + zaxis * num4);
        }
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            var totalBoundsReactants = BoundsCalculator.CalculateBounds(reaction.Reactants);
            var totalBoundsProducts  = BoundsCalculator.CalculateBounds(reaction.Products);

            if (totalBoundsReactants == null || totalBoundsProducts == null)
            {
                return(null);
            }

            double separation      = model.GetBondLength() / model.GetScale();
            var    foregroundColor = model.GetForegroundColor();

            return(new ArrowElement(
                       new WPF::Point(totalBoundsReactants.Right + separation, totalBoundsReactants.CenterY()),
                       new WPF::Point(totalBoundsProducts.Left - separation, totalBoundsReactants.CenterY()),
                       1 / model.GetScale(), true, foregroundColor));
        }
Example #9
0
        public void CorrectlyCalculatesBounds(
            int posx, int posy,
            float pivotx, float pivoty,
            int sizex, int sizey,
            int startX, int endX,
            int startY, int endY)
        {
            Vector2  size  = new Vector2(sizex, sizey);
            Vector2  pos   = new Vector2(posx, posy);
            Vector2f pivot = new Vector2f(pivotx, pivoty);

            Rect rect = BoundsCalculator.Calculate(pos, pivot, size);

            Assert.AreEqual(startX, rect.XMin, "StartX");
            Assert.AreEqual(endX, rect.XMax, "EndX");
            Assert.AreEqual(startY, rect.YMin, "StartY");
            Assert.AreEqual(endY, rect.YMax, "EndY");
        }
Example #10
0
        internal void method_0(
            DxfTableContent tableContent,
            double width,
            double height,
            double rotation,
            double horizontalMargin,
            double verticalMargin)
        {
            DxfBlock valueObject = this.ValueObject as DxfBlock;

            if (valueObject == null)
            {
                this.dxfContentFormat_0.method_6(1.0);
            }
            else
            {
                DxfInsert dxfInsert = new DxfInsert(valueObject);
                foreach (DxfTableAttribute dxfTableAttribute in (List <DxfTableAttribute>) this.dxfTableAttributeCollection_0)
                {
                    if (dxfTableAttribute.AttributeDefinition != null)
                    {
                        DxfAttribute dxfAttribute1 = new DxfAttribute(dxfTableAttribute.AttributeDefinition);
                        dxfAttribute1.Text = dxfTableAttribute.Value;
                        DxfAttribute dxfAttribute2 = dxfAttribute1;
                        dxfAttribute2.AlignmentPoint1 = dxfAttribute2.AlignmentPoint1 - valueObject.BasePoint;
                        if (dxfAttribute1.AlignmentPoint2.HasValue)
                        {
                            DxfAttribute     dxfAttribute3   = dxfAttribute1;
                            WW.Math.Point3D? alignmentPoint2 = dxfAttribute3.AlignmentPoint2;
                            WW.Math.Vector3D basePoint       = valueObject.BasePoint;
                            dxfAttribute3.AlignmentPoint2 = alignmentPoint2.HasValue ? new WW.Math.Point3D?(alignmentPoint2.GetValueOrDefault() - basePoint) : new WW.Math.Point3D?();
                        }
                    }
                }
                BoundsCalculator boundsCalculator = new BoundsCalculator();
                boundsCalculator.GetBounds(tableContent.Model, (DxfEntity)dxfInsert);
                Bounds3D bounds    = boundsCalculator.Bounds;
                Matrix4D transform = Transformation4D.Translation(valueObject.BasePoint) * Transformation4D.RotateZ(rotation) * Transformation4D.Translation(-valueObject.BasePoint);
                bounds.Transform(transform);
                Vector2D vector2D = new Vector2D((width - 2.0 * horizontalMargin) / bounds.Delta.X, (height - 2.0 * verticalMargin) / bounds.Delta.Y);
                this.dxfContentFormat_0.BlockScale = System.Math.Min(vector2D.X, vector2D.Y);
            }
        }
Example #11
0
        /// <inheritdoc/>
        public IRenderingElement Generate(IReaction reaction, RendererModel model)
        {
            ElementGroup diagram = new ElementGroup();

            var color     = model.GetForegroundColor();
            var reactants = reaction.Reactants;

            // only draw + signs when there are more than one reactant
            if (reactants.Count > 1)
            {
                var    totalBoundsReactants = BoundsCalculator.CalculateBounds(reactants);
                var    bounds1 = BoundsCalculator.CalculateBounds(reactants[0]);
                double axis    = totalBoundsReactants.CenterY();
                foreach (var reactant in reaction.Reactants.Skip(1))
                {
                    var bounds2 = BoundsCalculator.CalculateBounds(reactant);
                    diagram.Add(MakePlus(bounds1, bounds2, axis, color));
                    bounds1 = bounds2;
                }
            }

            // only draw + signs when there are more than one products
            var products = reaction.Products;

            if (products.Count > 1)
            {
                var    totalBoundsProducts = BoundsCalculator.CalculateBounds(products);
                double axis    = totalBoundsProducts.CenterY();
                var    bounds1 = BoundsCalculator.CalculateBounds(reactants[0]);
                foreach (var product in reaction.Products.Skip(1))
                {
                    var bounds2 = BoundsCalculator.CalculateBounds(product);

                    diagram.Add(MakePlus(bounds1, bounds2, axis, color));
                    bounds1 = bounds2;
                }
            }
            return(diagram);
        }
Example #12
0
        public static Bitmap CreateAutoSizedBitmap(
            DxfModel model,
            Matrix4D transform,
            GraphicsConfig graphicsConfig,
            SmoothingMode smoothingMode)
        {
            BoundsCalculator boundsCalculator = new BoundsCalculator(graphicsConfig);

            boundsCalculator.GetBounds(model, transform);
            Bounds3D bounds = boundsCalculator.Bounds;

            if (!bounds.Initialized)
            {
                return(ImageExporter.CreateEmptyBitmap((System.Drawing.Color)graphicsConfig.BackColor, 1, 1));
            }
            WW.Math.Vector3D delta      = bounds.Delta;
            Matrix4D         transform1 = DxfUtil.GetScaleTransform(bounds.Min, bounds.Max, new WW.Math.Point3D(2.0, delta.Y + 2.0, 0.0), new WW.Math.Point3D(delta.X + 2.0, 2.0, 0.0)) * transform;
            int width  = (int)System.Math.Ceiling(delta.X) + 4;
            int height = (int)System.Math.Ceiling(delta.Y) + 4;

            return(ImageExporter.CreateBitmap(model, transform1, graphicsConfig, smoothingMode, width, height));
        }
Example #13
0
        public static Bitmap CreatePlotLayoutBitmap(
            Size maxSize,
            DxfModel model,
            DxfLayout layout,
            DxfViewportCollection viewports,
            GraphicsConfig config,
            SmoothingMode smoothingMode)
        {
            DxfLayout.PlotInfo plotInfo = layout.GetPlotInfo((double)maxSize.Width, (double)maxSize.Height, new Rectangle2D(0.0, 0.0, (double)(maxSize.Width - 1), (double)(maxSize.Height - 1)), false, true);
            Size     size;
            Matrix4D to2DTransform;

            if (plotInfo != null)
            {
                Rectangle2D printableArea = plotInfo.PrintableArea;
                size = new Size((int)System.Math.Ceiling(printableArea.Width), (int)System.Math.Ceiling(printableArea.Height));
                WW.Math.Point2D center = printableArea.Center;
                to2DTransform = Transformation4D.Translation((WW.Math.Vector3D)(new WW.Math.Point2D(0.5 * (double)(size.Width - 1), 0.5 * (double)(size.Height - 1)) - center)) * plotInfo.ToPaperTransform;
            }
            else
            {
                BoundsCalculator boundsCalculator = new BoundsCalculator();
                boundsCalculator.GetBounds(model, layout);
                Bounds3D bounds = boundsCalculator.Bounds;
                if (!bounds.Initialized)
                {
                    return((Bitmap)null);
                }
                WW.Math.Point3D  min      = bounds.Min;
                WW.Math.Point3D  max      = bounds.Max;
                WW.Math.Vector3D vector3D = max - min;
                WW.Math.Point3D  point3D  = new WW.Math.Point3D(min.X, min.Y, 0.0);
                double           scaling;
                to2DTransform = DxfUtil.GetScaleTransform(point3D, new WW.Math.Point3D(max.X, min.Y, 0.0), point3D, WW.Math.Point3D.Zero, new WW.Math.Point3D((double)(maxSize.Width - 1), (double)(maxSize.Height - 1), 0.0), WW.Math.Point3D.Zero, out scaling);
                size          = new Size((int)System.Math.Ceiling(vector3D.X * scaling), (int)System.Math.Ceiling(vector3D.Y * scaling));
            }
            return(ImageExporter.CreateBitmap(model, layout, (ICollection <DxfViewport>)viewports, config, smoothingMode, (System.Drawing.Color)config.BackColor, to2DTransform, size.Width, size.Height));
        }
Example #14
0
        internal Bounds3D method_1(DxfTable table)
        {
            DxfBlock valueObject = this.ValueObject as DxfBlock;

            if (valueObject == null)
            {
                return((Bounds3D)null);
            }
            DxfInsert dxfInsert = new DxfInsert(valueObject);

            foreach (DxfTableAttribute dxfTableAttribute in (List <DxfTableAttribute>) this.dxfTableAttributeCollection_0)
            {
                if (dxfTableAttribute.AttributeDefinition != null)
                {
                    DxfAttribute dxfAttribute1 = new DxfAttribute(dxfTableAttribute.AttributeDefinition);
                    dxfAttribute1.Text = dxfTableAttribute.Value;
                    DxfAttribute dxfAttribute2 = dxfAttribute1;
                    dxfAttribute2.AlignmentPoint1 = dxfAttribute2.AlignmentPoint1 - valueObject.BasePoint;
                    if (dxfAttribute1.AlignmentPoint2.HasValue)
                    {
                        DxfAttribute     dxfAttribute3   = dxfAttribute1;
                        WW.Math.Point3D? alignmentPoint2 = dxfAttribute3.AlignmentPoint2;
                        WW.Math.Vector3D basePoint       = valueObject.BasePoint;
                        dxfAttribute3.AlignmentPoint2 = alignmentPoint2.HasValue ? new WW.Math.Point3D?(alignmentPoint2.GetValueOrDefault() - basePoint) : new WW.Math.Point3D?();
                    }
                }
            }
            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(table.Content.Model, (DxfEntity)dxfInsert);
            Bounds3D bounds    = boundsCalculator.Bounds;
            Matrix4D transform = Transformation4D.Translation(valueObject.BasePoint) * Transformation4D.RotateZ(this.dxfContentFormat_0.Rotation) * Transformation4D.Translation(-valueObject.BasePoint);

            bounds.Transform(transform);
            return(bounds);
        }
Example #15
0
        private DxfInsert.Enum44 method_16(
            Matrix4D insertionTransform,
            DxfInsert.Interface46 drawHandler)
        {
            if (drawHandler.InsertCellDrawContext.Config.UseSpatialFilters)
            {
                DxfSpatialFilter spatialFilter = this.SpatialFilter;
                if (spatialFilter != null && spatialFilter.ClipBoundaryDisplayEnabled)
                {
                    Polygon2D clipPolygon = spatialFilter.GetClipBoundaryPolygon();
                    if (clipPolygon.Count < 3)
                    {
                        return(DxfInsert.Enum44.const_1);
                    }
                    if (clipPolygon.GetArea() < 0.0)
                    {
                        clipPolygon = clipPolygon.GetReverse();
                    }
                    Matrix4D         boundaryTransform     = spatialFilter.ClipBoundaryTransform;
                    Matrix4D         transform             = insertionTransform * this.Block.BaseTransformation * spatialFilter.InverseInsertionTransform;
                    Matrix4D         inverse1              = boundaryTransform.GetInverse();
                    Matrix4D         clipBoundaryTransform = transform * inverse1;
                    DxfInsert.Enum44 enum44;
                    if (clipPolygon.IsConvex())
                    {
                        List <BlinnClipper4D.ClipPlane> clipPlaneList = new List <BlinnClipper4D.ClipPlane>();
                        WW.Math.Point2D  point2D             = clipPolygon[clipPolygon.Count - 1];
                        WW.Math.Vector3D boundaryPlaneNormal = spatialFilter.ClipBoundaryPlaneNormal;
                        Matrix4D         inverse2            = transform.GetInverse();
                        inverse2.Transpose();
                        foreach (WW.Math.Point2D point in (List <WW.Math.Point2D>)clipPolygon)
                        {
                            Vector2D v = point - point2D;
                            BlinnClipper4D.ClipPlane clipPlane = new BlinnClipper4D.ClipPlane(WW.Math.Vector3D.CrossProduct(inverse1.TransformTo3D(v), boundaryPlaneNormal), inverse1.TransformTo3D(point));
                            clipPlane.TransformBy(transform, inverse2);
                            clipPlaneList.Add(clipPlane);
                            point2D = point;
                        }
                        BoundsCalculator boundsCalculator = new BoundsCalculator();
                        boundsCalculator.GetBounds(drawHandler.InsertCellDrawContext.Model, (IEnumerable <DxfEntity>) this.Block.Entities, insertionTransform * this.Block.BaseTransformation);
                        switch (new BlinnClipper4D((ICollection <BlinnClipper4D.ClipPlane>)clipPlaneList).TryIsInside(boundsCalculator.Bounds))
                        {
                        case InsideTestResult.Inside:
                            enum44 = DxfInsert.Enum44.const_2;
                            break;

                        case InsideTestResult.Outside:
                            enum44 = DxfInsert.Enum44.const_0;
                            break;

                        default:
                            enum44 = DxfInsert.Enum44.const_3;
                            break;
                        }
                        if (enum44 == DxfInsert.Enum44.const_3)
                        {
                            Class808 class808 = new Class808((ICollection <BlinnClipper4D.ClipPlane>)clipPlaneList);
                            class808.imethod_0(insertionTransform.GetInverse());
                            GraphicsConfig config = drawHandler.InsertCellDrawContext.Config;
                            ModelSpaceClippingTransformer clippingTransformer = new ModelSpaceClippingTransformer(Matrix4D.Identity, (Interface32)class808, config.ShapeFlattenEpsilon, config.ShapeFlattenEpsilonForBoundsCalculation);
                            drawHandler.InsertCellDrawContext.vmethod_0((IClippingTransformer)clippingTransformer);
                        }
                    }
                    else
                    {
                        Class455         class455         = new Class455(clipBoundaryTransform, clipPolygon, false);
                        BoundsCalculator boundsCalculator = new BoundsCalculator();
                        boundsCalculator.GetBounds(drawHandler.InsertCellDrawContext.Model, (IEnumerable <DxfEntity>) this.Block.Entities, insertionTransform * this.Block.BaseTransformation);
                        switch (class455.TryIsInside(boundsCalculator.Bounds))
                        {
                        case InsideTestResult.Inside:
                            enum44 = DxfInsert.Enum44.const_2;
                            break;

                        case InsideTestResult.Outside:
                            enum44 = DxfInsert.Enum44.const_0;
                            break;

                        default:
                            enum44 = DxfInsert.Enum44.const_3;
                            break;
                        }
                        if (enum44 == DxfInsert.Enum44.const_3)
                        {
                            Matrix4D inverse2 = insertionTransform.GetInverse();
                            class455.imethod_0(inverse2);
                            GraphicsConfig config = drawHandler.InsertCellDrawContext.Config;
                            ModelSpaceClippingTransformer clippingTransformer = new ModelSpaceClippingTransformer(Matrix4D.Identity, (Interface32)class455, config.ShapeFlattenEpsilon, config.ShapeFlattenEpsilonForBoundsCalculation);
                            drawHandler.InsertCellDrawContext.vmethod_0((IClippingTransformer)clippingTransformer);
                        }
                    }
                    if ((!spatialFilter.ClipBoundaryDisplayEnabled || drawHandler.InsertCellDrawContext.Model.Header.ExternalReferenceClippingBoundaryType == WW.Cad.Model.SimpleLineType.Off ? 0 : (this.IsEntityVisibleInContext(drawHandler.InsertCellDrawContext, true) ? 1 : 0)) != 0)
                    {
                        WW.Math.Geometry.Polyline3D polygon = new WW.Math.Geometry.Polyline3D(clipPolygon.Count);
                        foreach (WW.Math.Point2D point in (List <WW.Math.Point2D>)clipPolygon)
                        {
                            polygon.Add(clipBoundaryTransform.TransformTo3D(point));
                        }
                        polygon.Closed = true;
                        drawHandler.Draw(polygon);
                    }
                    return(enum44);
                }
            }
            return(DxfInsert.Enum44.const_1);
        }
Example #16
0
        private IRenderingElement Generate(IChemObjectSet <IAtomContainer> moleculeSet, RendererModel model)
        {
            var totalBounds = BoundsCalculator.CalculateBounds(moleculeSet);

            return(new RectangleElement(totalBounds, model.GetBoundsColor()));
        }
Example #17
0
        public void CreateInitialModelViewport()
        {
            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(this.Model);
            Bounds3D bounds = boundsCalculator.Bounds;

            if (!bounds.Initialized)
            {
                return;
            }
            DxfViewport dxfViewport = new DxfViewport();

            this.dxfViewportCollection_0.Add(dxfViewport);
            Vector2D vector2D = this.Model.Header.PaperSpaceLimitsMax - this.Model.Header.PaperSpaceLimitsMin;

            if (this.PlotRotation != PlotRotation.None && this.PlotRotation != PlotRotation.Half)
            {
                vector2D.X -= this.UnprintableMarginTop;
                vector2D.X -= this.UnprintableMarginBottom;
                vector2D.Y -= this.UnprintableMarginRight;
                vector2D.Y -= this.UnprintableMarginLeft;
            }
            else
            {
                vector2D.X -= this.UnprintableMarginRight;
                vector2D.X -= this.UnprintableMarginLeft;
                vector2D.Y -= this.UnprintableMarginTop;
                vector2D.Y -= this.UnprintableMarginBottom;
            }
            dxfViewport.Size = new Size2D(vector2D.X, vector2D.Y);
            WW.Math.Point2D point = this.Model.Header.PaperSpaceLimitsMin + vector2D / 2.0;
            switch (this.PlotRotation)
            {
            case PlotRotation.None:
                point.X += this.UnprintableMarginLeft;
                point.Y += this.UnprintableMarginBottom;
                break;

            case PlotRotation.QuarterCounterClockwise:
                point.X += this.UnprintableMarginTop;
                point.Y += this.UnprintableMarginRight;
                break;

            case PlotRotation.Half:
                point.X += this.UnprintableMarginRight;
                point.Y += this.UnprintableMarginTop;
                break;

            case PlotRotation.QuarterClockwise:
                point.X += this.UnprintableMarginBottom;
                point.Y += this.UnprintableMarginRight;
                break;
            }
            dxfViewport.Center = new WW.Math.Point3D(point, 0.0);
            WW.Math.Point3D  center   = bounds.Center;
            WW.Math.Vector3D vector3D = bounds.Delta * 1.02;
            dxfViewport.Direction  = WW.Math.Vector3D.ZAxis;
            dxfViewport.ViewCenter = (WW.Math.Point2D)bounds.Center;
            double num = vector3D.Y;
            double x   = vector3D.X;

            if (num > 1E-10)
            {
                if (vector2D.X / vector2D.Y < x / num)
                {
                    num *= x / (vector2D.X / vector2D.Y * num);
                }
            }
            else
            {
                num = vector2D.Y / vector2D.X * x;
            }
            dxfViewport.ViewHeight = num;
        }
        public void getDXFFormat(DxfModel model, string filename, string outfile)
        {
            try
            {
                string extension = System.IO.Path.GetExtension(filename);
                if (string.Compare(extension, ".dwg", true) == 0)
                {
                    model = DwgReader.Read(filename);
                }
                else
                {
                    model = DxfReader.Read(filename);
                }
            }
            catch (Exception e)
            {
                //Console.Error.WriteLine("Error occurred: " + e.Message);
                //Environment.Exit(1);
            }

            GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor);
            Size          maxSize  = new Size(500, 500);
            Bitmap        bitmap   =
                ImageExporter.CreateAutoSizedBitmap(
                    model,
                    graphics,
                    Matrix4D.Identity,
                    System.Drawing.Color.Black,
                    maxSize
                    );
            //string outfile = Path.GetFileNameWithoutExtension(Path.GetFullPath(filename));
            Stream stream = null;
            //string outfile = AppDomain.CurrentDomain.BaseDirectory + "Drill\\rockHistogram\\"+filename;

            BoundsCalculator boundsCalculator = new BoundsCalculator();

            boundsCalculator.GetBounds(model);
            Bounds3D  bounds    = boundsCalculator.Bounds;
            PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.A4);//设置为A4纸的大小
            // Lengths in inches.
            float pageWidth  = (float)paperSize.Width / 100f;
            float pageHeight = (float)paperSize.Height / 100f;
            float margin     = 0.2f; //值越小 model相对于pdf图幅越大
            // Scale and transform such that its fits max width/height
            // and the top left middle of the cad drawing will match the
            // top middle of the pdf page.
            // The transform transforms to pdf pixels.
            Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
                bounds.Corner1,
                bounds.Corner2,
                new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel)
                );

            using (stream = File.Create(outfile + ".pdf"))
            {
                PdfExporter pdfGraphics = new PdfExporter(stream);
                pdfGraphics.DrawPage(
                    model,
                    GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                    to2DTransform,
                    paperSize
                    );
                pdfGraphics.EndDocument();
            }

            /*
             * 可选的图片格式
             * stream = File.Create(outfile + ".png");
             * ImageExporter.EncodeImageToPng(bitmap, stream);
             *
             * stream = File.Create(outfile + ".tiff");
             * ImageExporter.EncodeImageToTiff(bitmap, stream);
             *
             * stream = File.Create(outfile + ".jpg");
             * ImageExporter.EncodeImageToJpeg(bitmap, stream);
             *
             * stream = File.Create(outfile + ".gif");
             * ImageExporter.EncodeImageToGif(bitmap, stream);
             *
             * stream = File.Create(outfile + ".bmp");
             * ImageExporter.EncodeImageToBmp(bitmap, stream);
             */
        }
Example #19
0
        public RectangleF GetBounds(PointF pos, AngularCalculator aCalc)
        {
            var points = GetBoundPointsList(pos, aCalc);

            return(BoundsCalculator.CalculateBounds(points));
        }
Example #20
0
        public void CalculateTest()
        {
            // 1. 指定した値が4つ未満のときは現在の値を使うこと。
            // 2. 上下左右の透明部を除いて計算すること。

            // (0, -1)、11×12 にしたい。
            var calculator1 = new BoundsCalculator(new int[] { 0, -1, 11 });
            // 現在の透明部を除いたウィンドウは、(0, 1)、10×12 とする。
            var extendedFrameBounds = new Rect
            {
                left   = 0,
                top    = 1,
                right  = 0 + 10,
                bottom = 1 + 12
            };
            // ウィンドウの上と右と下には 2px の透明部、左には透明部なしとする。
            var windowRect = new Rect
            {
                left   = extendedFrameBounds.left,
                top    = extendedFrameBounds.top - 2,
                right  = extendedFrameBounds.right + 2,
                bottom = extendedFrameBounds.bottom + 2
            };

            var(x1, y1, width1, height1) = calculator1.Calculate(windowRect, extendedFrameBounds);
            // 指定X=0、現在X=0、左透明部=0 なので、X=0。
            Assert.AreEqual(0, x1);
            // 指定Y=-1、現在Y=1、上透明部=2 なので、Y = -1 - 2 = -3。
            Assert.AreEqual(-3, y1);
            // 指定幅=11、現在幅=10、左透明部=0、右透明部=2 なので、幅 = 0 + 11 + 2 = 13。
            Assert.AreEqual(13, width1);
            // 指定高さ=なし、現在高さ=12、上透明部=2、下透明部=2 なので、高さ = 2 + 12 + 2 = 16。
            Assert.AreEqual(16, height1);

            // 3. -a オプションを付けたとき、下がスクリーンからはみ出すなら上へずらすこと。
            // 4. -a オプションを付けたとき、右がタスクバーに重なるなら左へずらすこと。

            // PrimaryScreen は (0, 0)、10×10。VirtualScreen は (0, 0)、20×20 とする。
            // タスクバーは PrimaryScreen の右側に 3px とする。したがって、WorkArea は (0, 0)、7×10 となる。
            double pW = 10, pH = 10;
            double vX = 0, vY = 0, vW = 20, vH = 20;
            double wX1 = 0, wY1 = 0, wW1 = 7, wH1 = 10;

            // 透明部を除いて 1×11 のウィンドウを、(7, 10) に配置するよう指定する。
            // しかし、下がスクリーンからはみ出すので、押し込んで (7, 9) になる。
            // さらに、右がタスクバーと重なるので、左へずらして (6, 9) になる。
            var calculator2 = new BoundsCalculator(new int[] { 7, 10, 1, 11 });

            calculator2.AddAdjustProcess(pW, pH, vX, vY, vW, vH, wX1, wY1, wW1, wH1);
            var(x2, y2, width2, height2) = calculator2.Calculate(windowRect, extendedFrameBounds);
            // 左透明部=0 なので、X = 6 のまま。
            Assert.AreEqual(6, x2);
            // 上透明部=2 なので、Y = 9 - 2 = 7。
            Assert.AreEqual(7, y2);
            // 左透明部=0、右透明部=2 なので、幅 = 0 + 1 + 2 = 3。
            Assert.AreEqual(3, width2);
            // 上透明部=2、下透明部=2 なので、高さ = 2 + 11 + 2 = 15。
            Assert.AreEqual(15, height2);

            // 5. 下がスクリーンからはみ出さないようにずらした結果、上がスクリーンからはみ出すことがないこと。
            // 6. 右がタスクバーに重ならないようにずらした結果、左がスクリーンからはみ出すことがないこと。

            // 透明部を除いて 9×21 のウィンドウを、(1, 10) に配置するよう指定する。
            // しかし、下がスクリーンからはみ出すので、押し込んで (1, -1) にしたいが、
            // 今度は上がはみ出すので、結局 (1, 0) になる。
            // さらに、右がタスクバーに重なるので、ずらして (-2, 0) にしたいが、
            // 今度は左がはみ出すので、結局 (0, 0) になる。
            // この結果、右がタスクバーと重なり、下がスクリーンからはみ出すが、これは対処しない。
            var calculator3 = new BoundsCalculator(new int[] { 1, 10, 9, 21 });

            calculator3.AddAdjustProcess(pW, pH, vX, vY, vW, vH, wX1, wY1, wW1, wH1);
            var(x3, y3, width3, height3) = calculator3.Calculate(windowRect, extendedFrameBounds);
            // 左透明部=0 なので、X = 0 のまま。
            Assert.AreEqual(0, x3);
            // 上透明部=2 なので、Y = 0 - 2 = -2。
            Assert.AreEqual(-2, y3);
            // 左透明部=0、右透明部=2 なので、幅 = 0 + 9 + 2 = 11。
            Assert.AreEqual(11, width3);
            // 上透明部=2、下透明部=2 なので、高さ = 2 + 21 + 2 = 25。
            Assert.AreEqual(25, height3);
        }
Example #21
0
        //Get All Booth Info for a given model
        public Stream GetBoothsInfo(Stream input)
        {
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection _nvc            = HttpUtility.ParseQueryString(body);
            string           _fileName          = _nvc["FileName"];
            string           _client_id         = _nvc["ClientId"];
            string           _show_id           = _nvc["ShowId"];
            string           _boothOutlineLayer = _nvc["BoothOutline"];
            string           _boothNumberLayer  = _nvc["BoothNumber"];
            DxfModel         _model             = ReadDxf("h://dxf_uploads//" + _client_id + " // " + _show_id + "//" + _fileName);
            BoundsCalculator _mBounds           = new BoundsCalculator();

            _mBounds.GetBounds(_model);
            Bounds3D _cBounds = _mBounds.Bounds;
            //get screen origin
            string _screenOrigin = GetScreenOrigin(_cBounds.ToString());

            //Empty List to attach all booth information
            List <Booth> _boothInfo = new List <Booth>();

            //Empty List to hold vertices of all Booths
            List <Point> _allVertices = new List <Point>();

            //loop over all Entites in a model
            foreach (DxfEntity _entity in _model.Entities)
            {
                if (_entity.Layer.ToString().Equals(_boothOutlineLayer, StringComparison.InvariantCultureIgnoreCase))
                //(_entity.Layer.ToString() == _boothOutlineLayer)
                {
                    if (_entity.EntityType.ToString() == "LWPOLYLINE" || _entity.EntityType.ToString() == "POLYLINE")
                    {
                        var     verticesTransformed = LwPolyline(_entity, _screenOrigin);
                        Booth   _booth        = PassBooth(_model, _boothNumberLayer, verticesTransformed, _screenOrigin);
                        Point[] verticesArray = VerticesToList(verticesTransformed).ToArray();
                        foreach (Point _vertex in verticesArray)
                        {
                            _allVertices.Add(_vertex);
                        }
                        _boothInfo.Add(_booth);
                    }
                    else if (_entity.EntityType.ToString() == "INSERT")
                    {
                        DxfInsert Insertentity = _entity as DxfInsert;
                        Matrix4D  transform    = Insertentity.BlockInsertionTransformations[0, 0] * Insertentity.Block.BaseTransformation;

                        DxfBlock block = Insertentity.Block;
                        foreach (DxfEntity lwEntity in block.Entities)
                        {
                            if (lwEntity.EntityType == "LWPOLYLINE")
                            {
                                DxfLwPolyline lwPolyline = lwEntity as DxfLwPolyline;
                                Matrix4D      _insertedPolylineTransform = transform * lwPolyline.Transform;
                                List <string> _newVertices = new List <string>();

                                //loop over all vertices in entity
                                foreach (DxfLwPolyline.Vertex vertex in lwPolyline.Vertices)
                                {
                                    _newVertices.Add(RemoveSpaces(_insertedPolylineTransform.Transform(vertex.Position).ToString()));
                                }
                                List <string> verticesTransformed = new List <string>();
                                foreach (string item in _newVertices)
                                {
                                    verticesTransformed.Add(TransformPoint(item, _screenOrigin));
                                }
                                Booth   _booth        = PassBooth(_model, _boothNumberLayer, verticesTransformed, _screenOrigin);
                                Point[] verticesArray = VerticesToList(verticesTransformed).ToArray();
                                foreach (Point _vertex in verticesArray)
                                {
                                    _allVertices.Add(_vertex);
                                }
                                _boothInfo.Add(_booth);
                            }
                        }
                    }
                }
            }
            Booth _boundaries = new Booth()
            {
                BOOTHNUMBER = "",
                INSERTPOINT = _screenOrigin,
                SHAPE       = "origin",
                SIZEX       = "",
                SIZEY       = ""
            };

            _boothInfo.Add(_boundaries);
            string gridline = FindGridLine(_allVertices.ToArray());

            string[] gridLine  = gridline.Split(',');
            Booth    _gridLine = new Booth()
            {
                BOOTHNUMBER = "",
                INSERTPOINT = "",
                SHAPE       = "Grid Line",
                SIZEX       = gridLine[0],
                SIZEY       = gridLine[1]
            };

            _boothInfo.Add(_gridLine);

            string boothInformation = JsonConvert.SerializeObject(_boothInfo);

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return(new MemoryStream(Encoding.UTF8.GetBytes(boothInformation)));

            //return JsonConvert.SerializeObject(_boothInfo);
        }
Example #22
0
        public void Export(string outfile)
        {
            //string outfile = sfd.FileName;//= Path.GetFileNameWithoutExtension(Path.GetFullPath(filename));
            Stream stream;

            BoundsCalculator boundsCalculator = new BoundsCalculator();
            boundsCalculator.GetBounds(model);
            Bounds3D bounds = boundsCalculator.Bounds;
            PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.Letter);
            // Lengths in inches.
            float pageWidth = (float)paperSize.Width / 100f;
            float pageHeight = (float)paperSize.Height / 100f;
            float margin = 0.5f;
            // Scale and transform such that its fits max width/height
            // and the top left middle of the cad drawing will match the
            // top middle of the pdf page.
            // The transform transforms to pdf pixels.
            Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
                bounds.Corner1,
                bounds.Corner2,
                new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel),
                new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel)
            );
            using (stream = File.Create(outfile))
            {
                PdfExporter pdfGraphics = new PdfExporter(stream);
                pdfGraphics.DrawPage(
                    model,
                    GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                    to2DTransform,
                    paperSize
                );
                pdfGraphics.EndDocument();
            }
        }
Example #23
0
        public static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                args = new string[2];
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test1.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test2.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test3.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test4.dwg";
                args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test5Insert.dwg";
                //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test6.dwg";
            }
            string format   = args[0];
            string filename = args[1];

            DxfModel model = null;

            try
            {
                string extension = Path.GetExtension(filename);
                if (string.Compare(extension, ".dwg", true) == 0)
                {
                    model = DwgReader.Read(filename);
                }
                else
                {
                    model = DxfReader.Read(filename);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error occurred: " + e.Message);
                Environment.Exit(1);
            }

            //foreach (var entityGroups in model.Entities.GroupBy(a => a.GetType()))
            //{

            //    Console.WriteLine(entityGroups.GetType());

            //    //if (typeof(DxfLine) == entityGroups.Key)
            //    //{
            //    //    foreach (var item in entityGroups)
            //    //    {
            //    //        Console.WriteLine(item.Color);

            //    //    }
            //    //}

            //}
            //FileStream fs = new FileStream("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\test1.txt", FileMode.Create);



            FindEntities(model.Entities);



            string json = JsonConvert.SerializeObject(cadEntities);

            File.WriteAllText("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\model.json", json);
            File.WriteAllText("D:\\Project\\cadtest\\node_modules\\@cadTestUbim\\res\\data\\dxfdata.json", json);

            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();

            KTCodes = ktls.ToArray();

            KTest = ktest.ToArray();

            DxfType = dxfType.ToArray();

            KInsert = kins.ToArray();

            KEC = kco.ToArray();

            KCIRCLE = kcircle.ToArray();

            //Console.ReadKey();
            string outfile = Path.GetDirectoryName(Path.GetFullPath(filename)) + "\\12";
            Stream stream;

            if (format == "pdf")
            {
                BoundsCalculator boundsCalculator = new BoundsCalculator();
                boundsCalculator.GetBounds(model);
                Bounds3D  bounds    = boundsCalculator.Bounds;
                PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.Letter);
                // Lengths in inches.
                float pageWidth  = (float)paperSize.Width / 100f;
                float pageHeight = (float)paperSize.Height / 100f;
                float margin     = 0.5f;
                // Scale and transform such that its fits max width/height
                // and the top left middle of the cad drawing will match the
                // top middle of the pdf page.
                // The transform transforms to pdf pixels.
                Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
                    bounds.Corner1,
                    bounds.Corner2,
                    new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                    new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                    new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel),
                    new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel)
                    );
                using (stream = File.Create(outfile + ".pdf"))
                {
                    PdfExporter pdfGraphics = new PdfExporter(stream);
                    pdfGraphics.DrawPage(
                        model,
                        GraphicsConfig.WhiteBackgroundCorrectForBackColor,
                        to2DTransform,
                        paperSize
                        );
                    pdfGraphics.EndDocument();
                }
            }
            else
            {
                GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor);
                Size          maxSize  = new Size(500, 500);
                Bitmap        bitmap   =
                    ImageExporter.CreateAutoSizedBitmap(
                        model,
                        graphics,
                        Matrix4D.Identity,
                        System.Drawing.Color.Black,
                        maxSize
                        );
                switch (format)
                {
                case "bmp":
                    using (stream = File.Create(outfile + ".bmp"))
                    {
                        ImageExporter.EncodeImageToBmp(bitmap, stream);
                    }
                    break;

                case "gif":
                    using (stream = File.Create(outfile + ".gif"))
                    {
                        ImageExporter.EncodeImageToGif(bitmap, stream);
                    }
                    break;

                case "tiff":
                    using (stream = File.Create(outfile + ".tiff"))
                    {
                        ImageExporter.EncodeImageToTiff(bitmap, stream);
                    }
                    break;

                case "png":
                    using (stream = File.Create(outfile + ".png"))
                    {
                        ImageExporter.EncodeImageToPng(bitmap, stream);
                    }
                    break;

                case "jpg":
                    using (stream = File.Create(outfile + ".jpg"))
                    {
                        ImageExporter.EncodeImageToJpeg(bitmap, stream);
                    }
                    break;

                default:
                    Console.WriteLine("Unknown format " + format + ".");
                    break;
                }
            }
        }
Example #24
0
        // For each layout, add a page to the PDF file.
        // Optionally specify a modelView (for model space only).
        // Optionally specify a layout.
        public static void AddLayoutToPdfExporter(
            PdfExporter pdfExporter, GraphicsConfig config, DxfModel model, DxfView modelView, DxfLayout layout
            )
        {
            Bounds3D    bounds;
            const float defaultMargin = 0.5f;
            float       margin        = 0f;
            PaperSize   paperSize     = null;
            bool        useModelView  = false;
            bool        emptyLayout   = false;

            if (layout == null || !layout.PaperSpace)
            {
                // Model space.
                BoundsCalculator boundsCalculator = new BoundsCalculator();
                boundsCalculator.GetBounds(model);
                bounds = boundsCalculator.Bounds;
                if (bounds.Initialized)
                {
                    if (bounds.Delta.X > bounds.Delta.Y)
                    {
                        paperSize = PaperSizes.GetPaperSize(PaperKind.A4Rotated);
                    }
                    else
                    {
                        paperSize = PaperSizes.GetPaperSize(PaperKind.A4);
                    }
                }
                else
                {
                    emptyLayout = true;
                }
                margin       = defaultMargin;
                useModelView = modelView != null;
            }
            else
            {
                // Paper space layout.
                Bounds2D plotAreaBounds = layout.GetPlotAreaBounds();
                bounds      = new Bounds3D();
                emptyLayout = !plotAreaBounds.Initialized;
                if (plotAreaBounds.Initialized)
                {
                    bounds.Update((Point3D)plotAreaBounds.Min);
                    bounds.Update((Point3D)plotAreaBounds.Max);

                    if (layout.PlotArea == PlotArea.LayoutInformation)
                    {
                        switch (layout.PlotPaperUnits)
                        {
                        case PlotPaperUnits.Millimeters:
                            paperSize = new PaperSize(Guid.NewGuid().ToString(), (int)(plotAreaBounds.Delta.X * 100d / 25.4d), (int)(plotAreaBounds.Delta.Y * 100d / 25.4d));
                            break;

                        case PlotPaperUnits.Inches:
                            paperSize = new PaperSize(Guid.NewGuid().ToString(), (int)(plotAreaBounds.Delta.X * 100d), (int)(plotAreaBounds.Delta.Y * 100d));
                            break;

                        case PlotPaperUnits.Pixels:
                            // No physical paper units. Fall back to fitting layout into a known paper size.
                            break;
                        }
                    }

                    if (paperSize == null)
                    {
                        if (bounds.Delta.X > bounds.Delta.Y)
                        {
                            paperSize = PaperSizes.GetPaperSize(PaperKind.A4Rotated);
                        }
                        else
                        {
                            paperSize = PaperSizes.GetPaperSize(PaperKind.A4);
                        }
                        margin = defaultMargin;
                    }
                }
            }

            if (!emptyLayout)
            {
                // Lengths in inches.
                float pageWidthInInches  = paperSize.Width / 100f;
                float pageHeightInInches = paperSize.Height / 100f;

                double   scaleFactor;
                Matrix4D to2DTransform;
                if (useModelView)
                {
                    to2DTransform = modelView.GetMappingTransform(
                        new Rectangle2D(
                            margin * PdfExporter.InchToPixel,
                            margin * PdfExporter.InchToPixel,
                            (pageWidthInInches - margin) * PdfExporter.InchToPixel,
                            (pageHeightInInches - margin) * PdfExporter.InchToPixel),
                        false);
                    scaleFactor = double.NaN; // Not needed for model space.
                }
                else
                {
                    to2DTransform = DxfUtil.GetScaleTransform(
                        bounds.Corner1,
                        bounds.Corner2,
                        new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d),
                        new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel),
                        new Point3D(new Vector3D(pageWidthInInches - margin, pageHeightInInches - margin, 0d) * PdfExporter.InchToPixel),
                        new Point3D(new Vector3D(pageWidthInInches / 2d, pageHeightInInches - margin, 0d) * PdfExporter.InchToPixel),
                        out scaleFactor
                        );
                }
                if (layout == null || !layout.PaperSpace)
                {
                    pdfExporter.DrawPage(model, config, to2DTransform, paperSize);
                }
                else
                {
                    pdfExporter.DrawPage(model, config, to2DTransform, scaleFactor, layout, null, paperSize);
                }
            }
        }