Loading coordinates into AutoCAD from txt. Importing coordinates from a text file into a nanoCAD drawing using the classic .NET API. Creating and setting up a working project

One of the most popular questions about programming for nanoCAD is “How can I import points from a text file?” This is not a difficult task, but a professional designer does not have to be a professional programmer, so we wrote this article in a “for beginners” style.

You can import coordinates into a drawing using any of the existing API types in nanoCAD. We decided to choose .NET and compare two similar APIs: the classic .NET API and the cross-CAD platform MultiCAD.NET API. Below the cut is the first part - importing points using the classic .NET API.

Given: text file with X, Y, Z coordinates of points, one point per line. The coordinates are separated by a space, the fractional separator is a dot.

Required: write an application that, using the IMPORTCOORDS command, requests a file name and imports the found coordinates into the current drawing space in the form of DatabaseServices.DBPoint objects. Object coordinates must be imported in the drawing's current User Coordinate System (UCS).

Creating and setting up a working project
To create the application we will need the following tools:
  • nanoCAD (version no lower than 3.5)
  • Microsoft Visual Studio 2008 (nanoCAD 3.5 - nanoCAD 5.0 ​​support loading .NET applications built on the .NET Framework 3.5).
And, of course, it is assumed that you know at least a little programming in C#. If not, welcome to the MSDN library.

Create a new project in Visual Studio with the following settings:

  • Project type: Visual C#
  • Template: Class Library
Thus, our application is a regular .NET assembly (DLL), which will subsequently be loaded into nanoCAD.
In the References tab we connect the following libraries included in the nanoCAD kit:
  • hostdbmgd.dll
  • hostmgd.dll
Now you can safely move on to writing the program itself.
Program structure
The implementation can be broken down into the following steps:
  1. Register the IMPORTCOORDS command.
  2. Get the current drawing database and command line editor.
  3. Request file name with coordinates.
  4. Open the file, read the lines with coordinates.
  5. Create DBPoint objects with individual coordinates. Convert their coordinates to the current user coordinate system.
  6. Add the created objects to the current drawing space (Model Space or Paper Space).
In order to register a command that will call our application in nanoCAD, before defining the method that will be called by this command, we need to declare an attribute and specify the name of the command. Please note that the method must have the public modifier:

Public void importCoords() ( ... )
Before continuing, I would like to stop and tell you in a nutshell what a “drawing database” is. A .dwg file is a database that has a strict structure, the main elements of which are tables (Symbol Tables), which contain all the objects of the drawing. These are not only the graphic objects that we see in the drawing (straight lines, arcs, points, etc.), but also many other objects that determine the contents and settings of the drawing. For example, the Layer Table contains all the layers that are in the drawing, the Linetype Table stores all line styles defined in the drawing, the UCS Table stores all coordinate systems created by the user for a given drawing, etc. Thus, creating a new drawing object means creating a corresponding database object.

So let's continue. First of all, we need to select the current one from all open documents and open its database. To do this, we get an object manager of all open documents, and then, with its help, a database with which we will continue to work.

DocumentCollection dm = Application.DocumentManager; Database db = dm.MdiActiveDocument.Database;
In order for our application to prompt for a file name, we need to obtain an Editor object and call a method that requests user input of a certain type (in our case, the file name):

// Get the command line editor Editor ed = dm.MdiActiveDocument.Editor; // Object for receiving the request result PromptFileNameResult sourceFileName; // Output the request to the command line and get the result sourceFileName = ed.GetFileNameForOpen("\nEnter the name of the coordinates file to be imported:"); if (sourceFileName.Status == PromptStatus.OK) ( ... )
Getting coordinates from a file is quite simple, using C# functionality for reading text files and working with string data types:

// Read the file, get the contents as an array of strings string lines = File.ReadAllLines(sourceFileName.StringResult); // For each line, write an array of substrings separated by a space (since, according to the problem, the space character acts as a coordinate separator). // This way we get an array of coordinates, only in text form, then we convert them into double numbers. string coordinate; foreach (string s in lines) ( coord = s.Split(new char ( " " )); double coordX = Convert.ToDouble(coord); double coordY = Convert.ToDouble(coord); double coordZ = Convert.ToDouble(coord ; )
Let's move on to creating graphic primitives (Entities). As noted above, in order to create any object (not just graphic) that will be stored in a drawing, it must be added to the drawing database, namely to the corresponding container object. So, for example, all layers are stored as entries in the Layer Table, which in this case is a container object for them. The general database structure is as follows:

Graphic primitives are stored in the database not directly, but in the structure of individual blocks, which in turn are entries in the Block Table. This is very convenient because this mechanism allows you to easily group objects into named blocks and manage them as a single whole. By the way, model space and sheet space in the database are also represented by separate blocks. Thus, for a graphic primitive, the container will be a separate block, which, in turn, will belong to the parent object - the table of blocks.

Since we are working with a database, it is necessary to ensure its integrity and protection in case some error occurs during program execution. A transaction mechanism is used for this purpose. Transactions combine a number of operations that are performed as a whole: if something goes wrong, the transaction is canceled, and the objects created as part of this transaction will not be added to the document. If all operations are completed successfully, then the transaction is confirmed and the objects are added to the database.

Armed with this knowledge, we can safely add “point” primitives to the current drawing space according to the coordinates that we read from the file.

Using (Transaction tr = db.TransactionManager.StartTransaction()) ( // You can do without the block table and get the block of the current drawing space directly from the object representing the database BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode. ForWrite); string lines = File.ReadAllLines(sourceFileName.StringResult); string coord; foreach (string s in lines) ( coord = s.Split(new char ( " " )); double coordX = Convert.ToDouble(coord); double coordY = Convert.ToDouble(coord); double coordZ = Convert.ToDouble(coord); new DBPoint(new Point3d(coordX, coordZ)); btr.AppendEntity(point); true); ) btr.Dispose(); tr.Commit();
The problem is practically solved. There is only one condition left to fulfill: point primitives must be created in the coordinates of the user coordinate system (UCS). It should be noted that primitives are stored in the drawing database in the World Coordinate System (WCS). Therefore, when creating primitives, it is necessary to perform the transformation: UCS->WCS. This is done using a custom coordinate system matrix:

Matrix3d ​​ucsMatrix = ed.CurrentUserCoordinateSystem;
Let's add a transformation:

( ... point.TransformBy(ucsMatrix.Inverse()); ... )
So, the program is completely written. What's next?

Loading the application into nanoCAD
The most enjoyable part remains - download the program into nanoCAD and admire the results of your work. As you remember, we created the working project as a class library, so after successful compilation, an assembly with the name of your project will be built. Open nanoCAD, write the NETLOAD command on the command line, select the built library from the list and load it. To run the program, simply enter the command name IMPORTCOORDS at the command prompt.
Import coordinates. Version 2.0
We will improve the first version of the application by adding several useful functions and user interface elements.

If the first version of the application “understood” a text file in which coordinates were separated only by spaces and a period was used as a decimal separator, now the application will be able to “recognize” coordinates separated by a tab, space or semicolon. As for the decimal separator, it can now be either a period or a comma; import will be carried out without taking into account regional settings. The IMPORTCOORDS command will now open a modal coordinate import dialog, in which the user can select a file and specify the desired coordinate import settings.

The general mechanism for importing coordinates and creating primitives remains virtually unchanged, but now this will happen within the form class, and the task of the IMPORTCOORDS command handler method is now reduced only to creating a form object and displaying the form on the screen in the form of a modal dialog:

Public void importCoords() ( Form form = new ImportForm(); HostMgd.ApplicationServices.Application.ShowModalDialog(form); )
After which control will be transferred to the window of the coordinates import form.

Application form
The application form includes the following elements:
  • Button to open a file
  • File open dialog
  • A group of checkboxes for selecting coordinate separator characters: tab, space, semicolon
  • Text field for previewing parsing of strings with coordinates
  • Button to import coordinates
  • Cancel button
Using these controls, the user can now specify the desired separator characters, check the result in the preview field (much like what is done in MS Excel when importing a text file) and initiate the import of coordinates:

AutoCAD Compatible
In conclusion, I would like to note that an application written for nanoCAD can be easily recompiled to work in AutoCAD. To do this you need to do the following:
  • In the References tab, connect the following libraries included in ObjectARX:
    • AcCoreMgd.dll
    • AcDbMgd.dll
    • AcMgd.dll
  • Add a conditional compilation directive to the application code to define the namespaces that will be used for compilation under nanoCAD or AutoCAD:
    #if ACAD using Autodesk.AutoCAD.ApplicationServices;
  • using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Geometry;

using Autodesk.AutoCAD.Runtime;

using Platform = Autodesk.AutoCAD;

using PlatformDb = Autodesk.AutoCAD; #else using HostMgd.ApplicationServices;

using HostMgd.EditorInput;

using Teigha.DatabaseServices;

using Teigha.Geometry;

using Teigha.Runtime;

using Platform = HostMgd;

using PlatformDb = Teigha; #endif Replace the platform-specific namespaces in your code with the aliases defined above: Platform and PlatformDb. Both versions of the project are available "

We present to your attention additional applications for connecting to AutoCAD software. All applications are distributed free of charge 1. Geo_Tools - a set of tools for topographers and surveyors, works as an add-on for AutoCAD (starting from AutoCAD 2008). When installing tools, the standard AutoCAD tool palette is replaced by geo_tools palettes, which should be taken into account by those who have filled the palette with their own tools or are using the standard one. Starting from version 2014.05.11, 21-47 does not replace, but is added to the standard palettes. -> If you don’t like the Geo_Tools set after deleting it, all changes will return to the standard one for AutoCAD. The toolbars and geo_tools ribbon are not touched. -> You can download version 2015.07 from the link Added support for AutoCAD 2016. "You can download version 2016.10 from the link added support for AutoCAD 2017. ")

You can download version 2017.10 from the link. Added the ability to specify a point import layer and insert blocks on points according to the description. Installation instructions: 1. Unpack and place the downloaded data in the folder " Replace the platform-specific namespaces in your code with the aliases defined above: Platform and PlatformDb. Both versions of the project are available C :\Program Files\geo_tools\" -> (note: for AutoCAD 2014-2016 this folder must be added to trusted sources: enter _options "

in the console, in the section

Files

Installation instructions: Trusted Locations (note: for AutoCAD 2014-2016 this folder must be added to trusted sources: enter _options ".

add line

c:\Program Files\geo_tools...

2. In the console enter " Installation instructions: Trusted Locations (note: for AutoCAD 2014-2016 this folder must be added to trusted sources: enter _options ".

_APPLOAD

The program helps in the design of as-built diagrams in construction, drawing deviations of measured points from the design position.

Download the application.


Program loads (imports) coordinates of points from files in *.txt, *.csv, * formats. tsv into Autocad version 2000-2013.

The file with coordinates for import can be generated manually, or using the GroundArc TSP program or other program.


Working with the program:

1. Launch the Point2CAD program:


If the file contains a header line with column designations (see example file No. 1, the first line “N X Y H”), then you need to set the “Skip the first line (header) in the source file” flag. If this is not done, Point2CAD will display an error message window.


By default, in Autocad the direction of the axes does not coincide with the geodetic ones; for this case, you need to set the flag “Swap X and Y (for correct import into AutoCAD)”.

2. Select files to import:


3. Convert the data by clicking the “Convert” button:


A message window will display the progress of the conversion process;

Documents with the *.src extension will appear in the folder with the source data;

4. To import point coordinates into Autocad, you need to launch Autocad and select the “Tool->Run Script” menu

Then specify the *.src document with coordinates resulting from the program


Then press the “Open” button. Points with coordinates from the loaded document will appear on the screen

I had to work with a variety of source data, but the point files received from the surveyors were always a particular pleasure. The reason for this is that you could get anything you wanted in them and in a completely unpredictable form. Therefore, very often I had to use the services of Excel, in order, for example, to throw out unnecessary columns or carry out arithmetic operations.

Everything would be fine, but after you save a text file (*.txt) in Excel, Civil will refuse to accept this file and will display No matching file format found. Although, if you check the data in Excel, you will see that all the data is correct and the columns are in the required form.

The reason for this is the tab that Excel inserts as a separator between columns when saving the file in txt format. Regardless of whether you choose Unicode text,DOS,Macintosh or Tab-delimited text files. Everywhere there will be a tab as a delimiter, but AutoCAD Civil 3D does not accept this tab. What to do?

First, I’ll tell you how to correctly import data from a text file into Excel. Naturally, when you press Open in Excel, the default setting is to open files with the extension *.xls, etc. Select All files and specify your txt, a window will appear like in Figure 1.


Choose With delimiters. If you immediately press Ready, then in our table all the data will fit in one column, for normal operation it is necessary to divide into columns, which means you need to indicate what is the separator, so click Further. In the new window you need to set what separator is space, as in Figure 2. Then you can press Ready. After this, you can perform the necessary actions and save the file in txt format.

Open your post-Excel file in Microsoft Word and turn on the display of invisible characters, this is what you should get:


Figure 3. Data display in MS Word

The arrow indicates that the delimiter is tab. The solution is simple - select the arrow icon and copy it. Then go to the search tab Replace. There in the line Find paste a tab from the clipboard, the cursor should jump. And in Replaced by put a space and you can safely replace everything. After this, Civil will treat this file as native.

You also need to mention the CSV extension, if you want to save in this format, then Excel will also surprise you. Instead of a comma delimiter, it inserts a semicolon. Accordingly, Civil also does not accept such a file. The solution is the same - replace the semicolon in Word with a comma or space.

What distinguishes effective fast AutoCAD courses from simple and long courses in AutoCAD? The main difference is that with effective ones you do not waste time cramming, you learn more easily and with pleasure, and after completing the courses you are able to apply your knowledge in practice.

Autocad is the most popular program for automating 2D design and 3D modeling. It is used all over the world. Today they cannot do without knowledge of this program:

  • Design engineers;
  • Architects;
  • Designers;
  • Builders;

and other specialists whose activities involve the development of projects.

If you're doing this kind of work and haven't taken an AutoCAD course yet, it's likely that you'll soon be written off as a professional.

The program interface is thought out to the smallest detail, all the necessary tools and functions are at hand, the development of a basic project is possible even with the first acquaintance with this program.

The required initial level of knowledge and skills to use the program is minimal.

But for a program of this class and such a wide field of application, the intuitive clarity of the interface turns out to be a paramount requirement, and an elementary set of operations is only the basis for mastering all its capabilities.

The logic of the work is almost indecently simple, but to work on a serious project in AutoCAD you need to develop a whole arsenal of tricks, multi-step standard solutions and preparations. Plus many settings and commercial products based on this program. You also need to understand them in order to gain the right to be called a design specialist.

As is already obvious, there is not so much theory in the learning process - everything is already designed for users without training or skills in working specifically with AutoCAD. What is the most convenient way to study it then?

AutoCAD video tutorials.

The AutoCAD video reveals the maximum capabilities of the program, and a professional teacher can literally explain the principles of developing even complex projects. After all, there is no need to agree on special terminology, there is no need for additional comments on the applied controls. In the video, AutoCAD appears as a simple and understandable tool.

AutoCAD provides the opportunity to develop and simulate a drawing or diagram of almost any complexity in a logical space. But the key word here is space in which you need to be able to navigate, which has its own characteristics. Video courses AutoCAD They allow, in parallel with the assimilation of information, to get used to meaningfully acting in a three-dimensional reference system and effectively operating with its capabilities.

My site gives you a unique opportunity to go through AutoCAD video courses, namely:

  1. B Free video lessons, articles, programs, mini-courses AutoCAD.
  2. ABOUT get acquainted with the catalog of my paid AutoCAD courses, thanks to which several thousand people, thanks to the Internet, have already mastered this program
  3. P watch AutoCAD video lessons and rare courses on this program, which are already collected in a special database.
  4. IN If you have any problems using the program, you can ask me questions.

And having passed my AutoCAD courses, you are guaranteed to learn:

  • Draw curves, polylines, shapes and learn how to create blocks in the program;
  • Work with layers;
  • Use tools for rapid design;
  • Make chamfers, arrays and mates;
  • Place dimensional chains;
  • Scale drawings
  • Build dynamic blocks
  • Understand attributes
  • Work with external links
  • Apply drawing file templates
  • Create interactive tables
  • Draw simple and complex drawings
  • Create simple and complex 3D models
  • Learn the intricacies of AutoCAD settings

and many many others