47
INDIRA COLLEGE OF ENGINEERING AND MANAGEMENT [S.E.Mech.] AutoLISP Lessons Compiled by Swapnil A. Kale & Sachin B. Gawade Department of Mechanical Engineering, ICEM

Autolisp Notes New By Swapnil A. Kale

Embed Size (px)

DESCRIPTION

S. E. Mechanical Engineering Course Subject

Citation preview

Page 1: Autolisp Notes New By Swapnil A. Kale

m

INDIRA COLLEGE OF ENGINEERING AND MANAGEMENT

[S.E.Mech.]

AutoLISP LessonsCompiled bySwapnil A. Kale & Sachin B. GawadeDepartment of Mechanical Engineering, ICEM

Page 2: Autolisp Notes New By Swapnil A. Kale

2Z:Swapnil A. Kale/MDCG/LISP/Notes

AutoLISPAN INTRODUCTION

Auto LISP is a dialect of the LISP programming languages (LIST processing ) . LISP is the oldest high-level programming language, second only to FORTRAN. LISP has been the language of choice for the artificial intelligence in robotics. It is built into Auto-cad.

It is an integral part of AutoCAD and can only be used after acquiring a through knowledge of this software since AutoCAD commands are used in the Auto LISP for drawing , without a familiarity with the AutoCAD commands, an auto LISP program cannot be constructed . it is based on the LISP programming language which is simple to learn and very powerful. Auto LISP closely resemble the syntax and convention of LISP. Auto LISP is subset of LISP, having many additional function specified to AutoCAD

What is program? A program is a list of instructions for your computer to carry out .

What you need? To program in LISP you will need a text editor capable of saving files in ASCII format, and AutoCAD to run *.lsp file you create.

Programming Phases

1) Problem defining 2) Requirements analysis3) Architecture4) Construction 5) System testing

Auto LISP is a powerful tool at the hands of a design engineer. Those who have some proficiency in AutoCAD know how it is possible to draw lines, curves, polyline, circle, spheren, boxen , and various other objects by using AutoCAD command prompt. All these may be parts of the drawing of a big engineering object. To draw a large object a user has to replicate several smaller object which is time consuming and monotonous. Consider another aspect. Say you have drawn the front view of a steam stop valve by AutoCAD. Now if it is required to draw the same object with some modification in dimension or shape or something else, you have to start a new and do almost the same repetitive job. To avoid such tedious works you can write a computer a program , which may to do all sorts of modifications. Auto LISP is such a high-level computer language supported by AutoCAD.

“Auto LISP programs are parametric. All functions are used in parenthesis (round brackets ’()’). All brackets should be evenly closed. Function and symbol names are not case sensitive and thus both upper and lower case letters can be used. The expressions can multiple lines.”

LISP CAN ONLY BE USED AFTER ACQUIRING A THOROUGH KNOWLEDGE OF AUTOCAD SOFTWARE.

Mr. Swapnil A. Kale

Department of Mechanical Engineering

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 3: Autolisp Notes New By Swapnil A. Kale

3Z:Swapnil A. Kale/MDCG/LISP/Notes

The AutoLISP environment

The AutoLISP environment is entered when AutoCAD receives a "(" symbol at the command line. When AutoCAD sees the opening parentheses, it runs the AutoLISP interpreter. The interpreter then evaluates, as a list, what is between the opening "(" symbol and the closing ")" symbol.

Data types

There are three basic data types in AutoLISP. They are functions, symbols, and lists.

Function: is the first item in every list. The remainder of the list is used as the parameters or arguments to the function. If the first item in the list is not a function you will receive an error message stating: "bad function."

Symbol: is what other programming languages call a variable, and from this point on when I refer to a variable I am really talking about a symbol. A symbol in LISP however can be a whole lot more than just a value, as a normal variable would hold. A symbol can contain a list or a function definition. A symbol has a value bound to it. If it has no binding it is said to be "nil". All symbols should be set to nil upon ending a program or encountering an error.

List: is anything that is not a symbol.

Errors

If an error occurs while running an AutoLISP program, the interpreter will return a trace of the function starting with the most recent function and continuing to the top of the program. This is handy for debugging. You should define your own error handler so the user doesn't have to see this and wonder what is going on.

Special characters

There are some characters in AutoLISP, like any language, which cannot be used under certain circumstances.

• Symbol names can contain any sequence of printable characters except the following:

( ) . ' " ;

• Certain characters terminate a symbol name or numeric constant, they are as follows:

( ) ' " ;

• A minus (-) sign can be used to signify negative integers or reals. • The plus (+) sign is optional when signifying positive integers or reals. • Literal strings are entered between double quotes (""). Within quotes strings, the backslash

(\) character may be used to enter control characters. The control characters are as follows:

• \\ Gives a normal backslash character.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 4: Autolisp Notes New By Swapnil A. Kale

4Z:Swapnil A. Kale/MDCG/LISP/Notes

• \" Gives a normal double quote character. • \e Gives an escape character. • \n Gives a new line character. • \r Gives a return character. • \t Gives the tab character. • \nnn Gives a character who’s octal code is nnn.

The single quote character can be used in place of the quote function such as:

'This is equivalent to (quote this)

Every comment in LISP must start with the semicolon character:

; This is a comment

Comments will be discussed in depth later in the lessons.

Lists:This function takes any number of expressions and makes a list out of them, and returns the

result. The expression can be integers, real numbers, strings, variable names or even other lists. The coordinate of a point is a commonly used list in AutoLISP. Coordinates can be 2-dimensional or 3-dimn. Let us see some examples.

2-dimensional coordinates: (10.5 30.98)3-dimensional coordinates: (10.5 30.98 50.84)

The following syntax is used to create lists:(Setq p (list 7 8 6)) here ‘p’ is assigned the value (7 8 6)Command: (Setq p (list 7 8 6)) returns (7 8 6)

An alternative method of writing a list is to use single quote: (quote (a b c)) or ‘(a b c) each of which returns (A B C),

‘(a b “c”) that returns (A B “c”)‘(a 5 “c”) that returns (A 5 “c”)

This signifies that (list a b c) & ‘(a b c) are same but there is a difference also. Take an example command: (setq a 100

b 200 c 300) returns 300

command: (setq pt (list a b c)) returns (100 200 300)command: (setq pt ‘(a b c)) returns (A B C)

so for the first expression, it returns (100 200 300), while fothe second it returns (A B C). That means evaluation is not done for the second case.

Here double quoted “c” which is returned as it is returned as it is, is an AutoLISP expression called string.List Functions:

Lets see the example,(Setq p (list 7 8 6)) here ‘p’ is assigned the value (7 8 6)car :

This function separates the first element out of a list.Syntax and command:

Command: (setq q(car p))7 ‘q’ is assigned the first element ‘7’ of the point ‘p’.cdr :

This function separates the remaining elements other than first. If the list is empty, “I hear and I forget. I see and I remember. I do and I understand." --

Confucius"

Page 5: Autolisp Notes New By Swapnil A. Kale

5Z:Swapnil A. Kale/MDCG/LISP/Notes

cdr returns nil.Syntaxand command:

Command:(setq t(cdr p))(8 6)’t’ is assigned the remaining elements(8 6) of ‘p’cadr:

This functions car & cdr can be used in a combined form to get the element of ‘p’. Suntax and command:Command: (setq u(car (cdr p)))8 ‘u’ is assigned the middle element 8 of ‘p’.

An trial programme to more understand list functions(defun c:BOX ( / pt1 pt2 pt3 pt4 )(setq pt1 (getpoint "Pick first corner: "))(setq pt3 (getcorner pt1 "Pick opposite corner: "))(setq pt2 (list (car pt3) (cadr pt1)))(setq pt4 (list (car pt1) (cadr pt3)))(Command "line" pt1 pt2 pt3 pt4 "c" ))

Running a Loaded Program

Once you have loaded the box program, you can run it at any time during the current editing session. However, once you exit AutoCAD the program is not saved with the file. You must re-load the program file in subsequent editing sessions before it can be used again. Now try running the program.

1. First, set the snap mode and the dynamic coordinate readout on.

2. Enter the word Box at the command prompt. You should get the following prompt:

Pick first corner:

3. If your screen is in text mode, use the F2 key to shift to the graphic screen. Move the cursor so that the coordinate readout reads 2.0000,3.0000 and pick that point. The next prompt appears:

Pick opposite corner:

4. Now move your cursor. A window follows the motion of your cursor (see figure 2.2). Move the corner of the window to the so that the coordinate 8.0000,6.000 is displayed on the coordinate readout then pick that point. The box is drawn and the Command prompt returns. Figure 2.3 gives you a general description of how this box program works.

Figure 2.2: The Getcorner window

Understanding How a Program Works

Up until now, you have been dealing with very simple AutoLISP expressions that perform simple tasks such as adding or multiplying numbers or setting system variables. Now that you know how to save AutoLISP code in a file, you can begin to create larger programs. The box program is really nothing more than a collection of expressions that are designed to work together to obtain specific results. In this section, we will examine the Box program to see how it works.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 6: Autolisp Notes New By Swapnil A. Kale

6Z:Swapnil A. Kale/MDCG/LISP/Notes

The Box program draws the box by first obtaining a corner point using Getpoint:

(setq pt1 (getpoint pt1 "Pick first corner: ''))

The user will see only the prompt portion of this expression:

Pick first corner:

Next, the opposite corner point is obtained using Getcorner (see Figure 2.3).

(setq pt3 (getcorner pt1 "Pick opposite corner: ''))

Again, the user only sees the prompt string:

Pick opposite corner:

Figure 2.3: The workings of the box program

You may recall that Getcorner will display a window as the user move the cursor. In this box program, this window allows the user to visually see the shape of the box before the opposite corner is selected (see figure 2.2). Once the second point is selected, the Box program uses the point coordinates of the first and opposite corners to derive the other two corners of the box. This is done by manipulating the known coordinates using Car, Cadr, and List (see Figure 2.4).

pt2 (list (car pt3) (cadr pt1)))

pt4 (list (car pt1) (cadr pt3)))

Figure 2.4: Using Car, Cadr, and List to derive the remaining box corners

Pt2 is derived by combining the X component of Pt3 with the Y component of Pt1. Pt 4 is derived from combining the X component of Pt1 with the Y component of Pt3 (see figure 2.5).

Figure 2.5: Using Car and Cadr to derive Pt2 and Pt4

Using AutoCAD Commands in AutoLISP

The last line in the box program:“I hear and I forget. I see and I remember. I do and I understand." --

Confucius"

Page 7: Autolisp Notes New By Swapnil A. Kale

7Z:Swapnil A. Kale/MDCG/LISP/Notes

(command "line'' pt1 pt2 pt3 pt4 "c'')

shows you how AutoCAD commands are used in an AutoLISP expression (see figure 2.6). Command is an AutoLISP function that calls standard AutoCAD commands. The command to be called following the Command function is enclosed in quotation marks. Anything in quotation marks after the Command function is treated as keyboard input. Variables follow, but unlike accessing variables from the command prompt, they do not have to be preceded by an exclamation point. The C enclosed in quotation marks at the end of the expression indicates a Close option for the Line command (see Figure 2.7.

Figure 2.6: Using AutoCAD commands in a function.

Figure 2.7: Variables help move information from one expression to another.

How to Create a Program

The box program is like a collection of expressions working together to perform a single task. Each individual expression performs some operation who's resulting value is passed to the next expression through the use of variables (see figure 2.8).

Assignment Function:Variable assignment is done through the function ‘setq’, concise form of ‘SET Quotes’. By

using this function, a value can be assigned to any variable.Syntax: (setq a 20) means an integer value is assigned to the variable ‘a’.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 8: Autolisp Notes New By Swapnil A. Kale

8Z:Swapnil A. Kale/MDCG/LISP/Notes

A partial list of AutoLISP functions

MATH FUNCTIONS THAT ACCEPT MULTIPLE ARGUMENTS

(+ number number ...) add(- number number ...) subtract(* number number ...) multiply(/ number number ...) divide(max number number ...) find largest of numbers given(min number number ...) find smallest of numbers given(rem number number ...) find the remainder of numbers

MATH FUNCTIONS THAT ACCEPT SINGLE ARGUMENTS

(1+ number) add 1(1© number) subtract 1(abs number) find the absolute value(exp nth) e raised to the nth power(expt number nth) number raised to the nth power(fix real) convert real to integer(float integer) convert integer to real(gcd integer integer) find greatest common denominator(log number) find natural log of number(sqrt number) find square root of number

FUNCTIONS FOR BINARY OPERATIONS

(~ integer) find logical bitwise NOT of integer(logand int. int. ...) find logical bitwise AND of integers(logior int. int. ...) find logical bitwise OR of integers(lsh int. bits) find logical bitwise shift of int.by bits

(terpri) :- This function prints a new line to the command line

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 9: Autolisp Notes New By Swapnil A. Kale

9Z:Swapnil A. Kale/MDCG/LISP/Notes

Lesson 1getpoiont setq defun command

at the command prompt, type : linecomputer response: from point

pick a point on the screencomputer response: to point

pick a point on the screencomputer response: to point

press Enter key

Above are the steps in AutoCAD to use the Aline@ command.

getpoint an AutoLisp function to request an input of a point. getpoint also echos a preassigned message.

In order to understand the use of getpoint and setq,

at the command prompt, type : (getpoint "Pick 1st point")computer response: Pick 1st point

pick a point on the screen

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 10: Autolisp Notes New By Swapnil A. Kale

10Z:Swapnil A. Kale/MDCG/LISP/Notes

setq an AutoLisp function to assign variables in AutoLisp.

In order to assign a point to a variable name for later retrievalat the command prompt, type: (setq A (getpoint "Pick 1st point"))computer response: Pick 1st point

pick a point on the screen

A point was picked, and the use of setq allows later retrieval of the point.In order to assure you did assign the point to the variable name Aat the command prompt, type: !Athe computer should print the co-ordinates of the point you picked last. The factorial symbol, ! , is used to get the value of any defined AutoLisp variables.

At the command prompt, type: (setq B (getpoint "Pick 2nd point"))computer response: Pick 2nd point

pick a point on the screen

The AutoLisp function command is used to call up a standard AutoCAD command. It should precede a standard AutoCAD command enclosed by a pair of double quotation marks. In order to see how this function works,

at the command prompt, type: (command "line" A B "")press Enter key

A line connecting two points, A and B, is drawn. The start point and end point of the line will be point A and point B respectively.

What you have done was to draw a line by means of AutoLisp function. AutoLisp could be executed line

by line, just like what you have done, but a formal AutoLisp routine to draw a line should be:

(defun c:line1 ()(setq A (getpoint "Pick 1st point"))(setq B (getpoint "Pick 2nd point"))(command "line" A B ""))

Use Note Pad, Word Pad, or any other available window version text-editor and type:

(defun c:line1 ()(setq A (getpoint "Pick 1st point"))(setq B (getpoint "Pick 2nd point"))(command "line" A B ""))

When done, save the file as “A:LINE1.LSP”

The file must be saved as text file.“I hear and I forget. I see and I remember. I do and I understand." --

Confucius"

Page 11: Autolisp Notes New By Swapnil A. Kale

11Z:Swapnil A. Kale/MDCG/LISP/Notes

Explanation of the lines typed:(defun is a standard way to start an AutoLisp programme.c: means to define a customized command; nothing to do with drive C:line1 the customized command will be known as line1() a pair of bracket means there will be variables in the programme and the

variables will stay in the memory after execution of the AutoLisp routine.) this is the closing bracket for the whole programme.

Minimize the text editor and return to AutoCAD,

Now is the time to load and run the AutoLisp routine, LINE1.LSP, you just typed.

at the command prompt type: (load "A:line1")computer will response: c:line1

now LINE1 becomes your customized command to draw a line. Whenever you want to use it to draw a line you could type LINE1

Improvement of above AutoLisp routine:-

Maximize the text editor and modify the file, line1.lsp to read:

(defun c:line1 ()(setq A (getpoint "Pick 1st point"))(setq B (getpoint "Pick 2nd point" A))(command "line" A B ""))

This modification will produce an elastic band originating from point A.Load the AutoLisp file again. Execute the file and appreciate the difference.

LINE1.LSP, though not a very practical file, does illustrate the principles of input and output in an AutoLisp programme. The best way to learn AutoLisp is by doing exercises. By applying the AutoLisp functions learned, you should be able to do the following tutorial.

Tutorial for Lesson 1:-

1. Write an AutoLisp routine which will ask the user to pick 5 points and then draw a 5 - vertice star.(STAR5.LSP)

2. Write an AutoLisp routine which will ask the user to pick 20 points and then the first picked point will joint all subsequently picked points.(BUSH.LSP)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 12: Autolisp Notes New By Swapnil A. Kale

12Z:Swapnil A. Kale/MDCG/LISP/Notes

Lesson 2getreal distance prompt terpri getint getstring

at the command prompt, type : (getreal "Type a number")computer response: Type a number

type a number and press Enter key

getreal an AutoLisp function to request an input of a real number from the user. It, like getpoint, also echos a predetermined message.

Most of the time we want to save the number under a variable name so that the value could be retrieved for use later. Thus, we have to combine setq and getreal together like the following:.

at the command prompt type: (setq A (getreal "Type a number "))type a number and press Enter key

in order to confirm that the number you typed is indeed stored under the variable name A,

at the command prompt type: !Acomputer response: [the number you typed in]

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 13: Autolisp Notes New By Swapnil A. Kale

13Z:Swapnil A. Kale/MDCG/LISP/Notes

The following example, LINECIR.LSP, asks for 2 points and a real number as input and then draws a line with 2 circles at its ends. It illustrates the use of the getreal. function.

The terpri function issues a carriage return.

The prompt function prints a predetermined message to the screen.Use Note Pad, Word Pad or any other Windows text editor and type the following file and then save as: A:LINECIR.LSPdefun c:linecir ()(setq A (getpoint "Pick 1st point"))(terpri) (setq B (getpoint "Pick 2nd point" A))(terpri)(setq R (getreal "Input radius"))(terpri)(command "line" A B "")(command "circle" A R)(command "circle" B R)(prompt "Thank you!"))

Above example use information input directly by the operator. A real number could be input directly by getreal or indirectly by the distance function. The distance function in AutoLisp will return a real number based on 2 input points. If we want the previous 2 circles to touch each other, we could use the distance function to obtain a real number and then calculate the required radii.

AutoLisp built-in mathematical feature is extremely useful in programming. AutoLisp perform calculations in the following formats:

Algebra format AutoLisp format4 + 5 (+ 4 5) 9 - 2 (- 9 2)2 x 4 (* 2 4)12 / 3 (/ 12 3)

Besides Algebraic functions, AutoLisp also support most of the trigonometrical functions too.

The following example draws 2 circles, radius of the smaller one will be half of the big one. Use Note Pad, Word Pad or any other Windows text editor to type the following file and then save as A:BSCIR.LSP

(defun c:bscir ()(setq A (getpoint "Pick 1st point"))(terpri)(setq B (getpoint "Pick 2nd point" A))(terpri)(setq D (distance A B))(setq R1 (/ D 3))(setq R2 (* R1 2))(command "circle" A R1)(command "circle" B R2)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 14: Autolisp Notes New By Swapnil A. Kale

14Z:Swapnil A. Kale/MDCG/LISP/Notes

(prompt "Thank you!"))

The above AutoLisp programme could be further improved by adding the layering command so that the big circle and small circle could be drawn on different layers. The proper input sequence to use the layer command should be found out before the AutoLisp programme is to be prepared..

(defun c:bscir2 ()(setq A (getpoint "Pick 1st point"))(terpri)(setq B (getpoint "Pick 2nd point" A))(terpri)(setq D (distance A B))(setq R1 (/ D 3))(setq R2 (* R1 2))(command "layer" "m" "smallcir" "c" "green" "" "")(command "circle" A R1)(command "layer" "m" "largecir" "c" "yellow" "" "")(command "circle" B R2)(prompt "Thank you!"))

Sometimes we need to input text to the programme. This could be done by the getstring function. When getstring function is used, even if the user type a number by the keyboard the number would be taken as a string in AutoLisp. Any mathematical performance on that input number will not work.Just like any other programming language real number and integer number should be distinguished. AutoLisp calculation could mix up integers and real numbers but for AutoCAD to work properly some of the input must be integer rather than real number. For example, in the Aarray@ operation, the number of rows and number of columns must be integers. The following examples demonstrates the use of getstring and getint functions.

Use Note Pad, Word Pad or any other Windows text editor and type FAN.LSP , COLARC.LSP AND CIRPAT :-

Save all the files in Drive A:

getstring an AutoLisp function to request an input of characters from the user. It, like getreal, also could echo a predetermined message.

FAN.LSP(defun c:fan ()(setq C (getstring "type a standard color: red, yellow, green, cyan, or blue "))(terpri)(setq D (getpoint "pick first point of line.."))(terpri)(setq E (getpoint "pick second point of line" D))(terpri)(command "color" C)(command "line" D E "")(command "array" "l" "" "p" D 50 160 "y"))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 15: Autolisp Notes New By Swapnil A. Kale

15Z:Swapnil A. Kale/MDCG/LISP/Notes

COLARC.LSP (defun c:colarc ()(setq C (getstring "type a standard color: red, yellow, green, cyan, or blue"))(terpri)(setq D (getpoint "pick first point of arc.."))(terpri)(setq E (getpoint "pick second point of arc.."))(terpri)(setq F (getpoint "pick third point of arc.."))(terpri)(command "color" C)(command "arc" D E F)(command "array" "l" "" "p" D 20 30 "y"))

getint an AutoLisp function to request an input of an integer from the user. It, like getreal, also echos a predetermined message.

CIRPAT LSP (defun c:cirpat ()(setq C (getstring "type a standard AutoCAD color: red, yellow, green, cyan or blue.."))(terpri)(setq D (getpoint "pick first point"))(terpri)(setq E (getpoint "pick second point"))(terpri)(setq F (getint "type a number larger than 10 :"))(command "color" C)(command "circle" "2P" D E)(command "array" "l" "" "p" D F 360 "y"))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 16: Autolisp Notes New By Swapnil A. Kale

16Z:Swapnil A. Kale/MDCG/LISP/Notes

Tutorial:Write an AutoLisp programme which will ask user to pick 2 points and then will draw 2 donuts touching each other; and also 2 circles each at the centers of donuts The inside radius of the donut will be half of that of the outside one. Radius of the circles to be 1/16 of the distance between the two picked points.Draw the donuts on the layer called tire and draw the circles on the layer called axle. File name to use: WHEEL2.LSP

Lesson 3getangle polar angle if nil

Prepare a grid layout as shown as right, using 10000 drawing units between grid lines. We are going to draw columns on this plan at intersection of grid lines..

Use Note Pad, Word Pad or any other Windows text editor to type the following file and then save as A:COLUMN.LSP

(defun c:column ()(setq CEN (getpoint "Centroid of column: ")) (terpri)(setq HOR (getreal "X Dimension of column: ")) (terpri)(setq VRT (getreal "Y Dimension of column: ")) (terpri)(setq ANG (getangle "Rotation angle of the X side: " CEN)) (terpri)(setq M (polar CEN (- ANG (/ pi 2)) (/ VRT 2)))(setq A (polar M (- ANG pi) (/ HOR 2)))(setq AM (angle A M))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 17: Autolisp Notes New By Swapnil A. Kale

17Z:Swapnil A. Kale/MDCG/LISP/Notes

(setq B (polar A AM HOR))(setq C (polar B (+ AM (/ pi 2)) VRT))(setq D (polar C (+ AM pi) HOR))(command "pline" A B C D "c"))

Exit text editor

Load the AutoLisp file, A:COLUMN.LSP

Computer should response by displaying C:COLUMN

COLUMN becomes your customized command.

at the command prompt, type : columncomputer response: Centroid of column

pick a point at the intersect of gridscomputer response: X dimension of columntype 1500

press Enter key computer response: Y dimensiontype 2000

press Enter key

computer response: Y dimensiontype 2000

press Enter key

computer response: Rotation angle of the X sideuse osnap Anear@ pick a point on the grid to

define orientation.

A column is drawn, nice and square to the grid. The ease to draw column by AutoLisp is obvious. This routine introduces the use of getangle, angle and polar.

getangle is the AutoLisp function that lets you find an angle by pointing to two points or bv entering the angle from the keyboard. Therefore, instead of picking two points, like what we have done, we could type the value of the angle through the keyboard.

polar is the AutoLisp function that derive a point at a given distance and angle from another known point.In the above example we based on the known point CEN with a known angle, pi /2, and a known distance, VER /2 to get the point M. By the same token, we based on M to get A, B, C and D.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 18: Autolisp Notes New By Swapnil A. Kale

18Z:Swapnil A. Kale/MDCG/LISP/Notes

angle is the AutoLisp function that measures the angle of two known points.The value of the angle returned by AutoLisp functions is always in radian. The angle to be used in the polar function should be in radian also. Therefore, if the angle obtained by AutoLisp functions is to be used in AutoCAD commands then the values of the angle should be converted from radian to degrees.

The next example, is an AutoLisp routine to draw a line with an arrow at both ends. It makes use of the polyline and polyline width features to prepare arrows and the line between arrows. Therefore, the steps to use Apline@ command and its width feature should be found out before preparing the AutoLisp routine.

It is very difficult to predetermine a good size for the arrows. Thus, in this programme we try to make the arrow size relative to the final plotting scale of the drawing. The if fuction is used here so that user needs to input the scale of drawing only once as long as the user remains in the same drawing. This programming technique is very useful whenever AutoLisp is used to draw entities which size should be relative to the scale of the drawing such as the insertion of direction symbols, or other graphical symbols on a drawing.

if The if function is followed by either two or three statements. The first statement after if is the condition to evaluate. The second statement is the step for the routine to execute if condition is true. The third statement, if exist, is the step for the routine to execute if condition is false.

nil in AutoLisp nil represent an empty set or non-existing condition.

Use Note Pad, Word Pad or any other Windows text editor to type the following file and then save as A:DARR.LSP

(defun c:DARR () (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")) ) (setq SPT (getpoint "Starting point")) (setq EPT (getpoint "End point" SPT)) (setq APT1 (polar SPT (angle SPT EPT) (* SC 2))) (setq APT2 (polar EPT (angle EPT SPT) (* SC 2))) (command "pline" SPT "w" 0.0 SC APT1 "w" 0.0 0.0 APT2 "w" SC 0.0 EPT ""))

Tutorial:1. When we prepare structural steel drawings, in order to

indicate a pinned joint connection between two main

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 19: Autolisp Notes New By Swapnil A. Kale

19Z:Swapnil A. Kale/MDCG/LISP/Notes

members we need to draw a line which is a little bit shorter than the two points we pick. Write an AutoLisp programme to do this. When activated the programme should prompt you to pick two points, then a line should be drawn with a gap between the ends of the line and the points picked. Size of the gap should be the same value as the scale of the drawing. If the scale is 1:100 , gap size is 100 or if the scale is 1:200 then the gap should be 200.

file name: SHORTER.LSP

2. Very similar to above, write a programme which will prompt for 2 points and then it will draw a line which will exceed the length between the two pickedpoints by a distance of SC at both ends. SC will be 100 for 1:100 or 50 for 1:50 scale drawingfile name: LONGER.LSP

3. Write an AutoLisp programme, in which the user needs to pick two points and a line with two arrows at one end (as shown by Fig. 3.6) will be drawn file:

FARARR.LSP.

Lesson 4getcorner graphscr list car cadr

At the command prompt, type: (setq A (getpoint "1st corner of rect"))computer response: 1st corner of rect

pick a point on the screen at bottom left computer response: [displays the co-ordinate of the point picked]At the command prompt, type: (setq C (getcorner "2nd corner of rectangle " A))computer response: 2nd corner of rect (and display an elastic rectangle)

pick a point on the screen at upper right

Now two points were input. These two points represent the diagonal corners of a rectangle.

getcorner the function to acquire a second point basing on a defined first point. and it provides the user with an elastic rectangle.

Points are variables with x and y coordinates. With the two diagonal points established, we try to get the x, y values and form the remaining points of the rectangle.Any variable with more than one value is called a list. Point A is a list because it contains x and y coordinates. Same does point C. We are going to combine x coordinate of A and y coordinate of C to form point B.

graphscr is the AutoLisp function to switch the computer to graphic mode, if it is in text mode.

car is the AutoLisp function to get the first element of a list.cadr is the AutoLisp function to get the 2nd element of a list.list is the AutoLisp function to group individual elements together.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 20: Autolisp Notes New By Swapnil A. Kale

20Z:Swapnil A. Kale/MDCG/LISP/Notes

At the command prompt, type: (setq B (list (car A) (cadr C)))computer response: [displays a set of coordinate for point B]

At the command prompt, type: (setq D (list (car C)(cadr A)))computer response: [displays a set of coordinate for point D] Now all points for the rectangle are defined.

at the command prompt, type : plinecomputer response: from pointtype: !Acomputer response: ARC/CLOSE/........../Width/<Endpoint of line>:type: wcomputer response: Starting width <0.050>type: 0.0computer response: Ending width <0.00>type: 0.0computer response: ARC/CLOSE/........../Width/<Endpoint of line>:type: !Bcomputer response: ARC/CLOSE/........../Width/<Endpoint of line>:type: !Ccomputer response: ARC/CLOSE/........../Width/<Endpoint of line>:type: !D

press Enter key

A rectangle is drawn. Now try to type the following file, rectan.lsp. Then, load the programme and see how it works.

(defun c:rectan () (graphscr) (setq A (getpoint "Pick corner of rectangle "))(terpri) (setq C (getcorner "2nd corner of rectangle " A))(terpri) (setq B (list (car A)(cadr C))) (setq D (list (car C)(cadr A))) (command "pline" A "w" 0.0 0.0 B C D "c") )

The next example will make full use of what you have learned to draw the symbol of a broken line. The programme uses the drawing scale to determine size of the broken symbol at the middle of the two picked points. It uses car and cadr to locate mid-pont of the symbol. From the mid-point it uses polar to find 4 other points then it uses pline to draw the complete broken line symbol.

Use a Windows text editor to type the following file, bline1.lsp:-

(defun c:bline1 ()(GRAPHSCR)(setq SC (getreal "scale of dwg. 1:"))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 21: Autolisp Notes New By Swapnil A. Kale

21Z:Swapnil A. Kale/MDCG/LISP/Notes

(setq BPT (getpoint "start point of break line "))(terpri)(setq EPT (getpoint BPT "point of break line "))(setq ANG (angle BPT EPT))(setq MPTX (/ (+ (car BPT) (car EPT)) 2))(setq MPTY (/ (+ (cadr BPT) (cadr EPT)) 2))(setq MPT (list MPTX MPTY))(setq PT1 (polar MPT (- ANG pi) (* SC 0.5)))(setq PT3 (polar MPT ANG (* SC 0.5)))(setq PT2 (polar MPT (+ ANG (/ pi 2)) (* SC 2)))(setq PT4 (polar MPT (- ANG (/ pi 2)) (* SC 2)))(command "pline" BPT "w" 0.0 0.0 PT1 PT2 PT4 PT3 EPT ""))

Tutorial

1. Write an AutoLisp

programme, in which when the user picks 2 diagonal points a rectangle with round corners will be drawn. Radius for the round corners will be 1/10th of the shorter side of the rectangle. See Fig. 4.3(Hints: use AutoLisp to draw a rectangle; find the shorter side and calculate for the fillet radius; use the polar function to determine points to be used for the fillet command.)

file:RECRND.LSP

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 22: Autolisp Notes New By Swapnil A. Kale

22Z:Swapnil A. Kale/MDCG/LISP/Notes

2. Write an AutoLisp programme to draw a rectangle and its shadow at its lower right side as shown on Fig. 4.4 Width of the shadow to be 1/25th of the length of the shorter side of the rectangle. file: RECSHD.LSP

Lesson 5repeat while getdist

All computer languages have loops to do repetitive jobs. In AutoLisp both the repeat and while function create loops to repeat a series of procedures.

repeat The function to repeat a series of procedure according to a specified number of times.

while The function to invoke a loop while a variable or expression is not nil or invalid.

getdist The function to request input as a real number, either through the keyboard or by pointing.

The following example demonstrate the usage of the repeat function. Once loaded and executed, it will ask user to pick two points and draw 5 concentric circles with decreasing radius. Each

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 23: Autolisp Notes New By Swapnil A. Kale

23Z:Swapnil A. Kale/MDCG/LISP/Notes

subsequent radius will be 50% of the previous one. And the circles are in different colors beginning with red (color 1).

Use a Windows text editor and type the following:-

(defun c:conc ()(setq A (getpoint "Pick center of circle "))(terpri)(setq R (getdist "Pick circum of outside circle" A))(terpri)(setq C 1)(repeat 5 (command "color" c) (command "circle" A R) (setq R (* R 0.5)) (setq C (+ C 1)) )(command "color" "bylayer"))

“bylayer” means the entity color will be same as the color of the layer on which it is drawn. The default feature for color is bylayer on the original acad.dwg. In order not to modify this feature, at the end of the programme, we try to return the drawing to have its entity color to be [email protected] while loop carries on and on as long as a specified condition is satisfied. The number of loops is not necessarily to be known. The following example bases on the previous one. It demonstrates the use of the while loop. The while loop will draw circles as long as the radius is larger than 0.1.

Use a Windows text editor and type the following:-

(defun c:conc2 ()(setq A (getpoint "Pick center of circle "))(terpri)(setq R (getdist "Pick circum of outside circle" A))(terpri)(setq C 1)(while (> R 0.1) (command "color" c) (command "circle" A R) (setq R (* R 0.5)) (setq C (+ C 1)) )(command "color" "bylayer")) Above examples show that repeat and while have their places. They are used at different situations.

The last example limits the smallest circle to be 0.1. Whether radius 0.1 is too small to see or not depends very much on the final plotting scale of the drawing. A better way would be to draw the smallest circle according to the final plotting scale. In 1:100 drawing 100 units will be represented by 1mm, and in 1:200 drawing, 200 will be represented by 1mm. In order to have the smallest circle visible its radius should be relative to the final plotting scale of the drawing. The next example uses the while loop to control the smallest circle to be drawn.

Save the previous AutoLisp file to another name, conc3.lsp, and revise it as follow:-

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 24: Autolisp Notes New By Swapnil A. Kale

24Z:Swapnil A. Kale/MDCG/LISP/Notes

(defun c:conc3 ()(setq A (getpoint "Pick center of circle "))(terpri)(setq R (getdist "Pick circum of outside circle" A))(terpri) (if (= SC nil) (setq SC (getreal "Scale of the dwg is 1: ")) ) (if (= COL nil) (setq COL 1) )(while (> R SC) (if (> COL 6) (setq COL 1) ) (command "color" COL) (command "circle" A R) (setq R (* R 0.5)) (setq COL (+ COL 1)) )(command "color" "bylayer"))

The outermost circle drawn by the above revised programme, conc3.lsp, may not be red unless it is the first time to use this programme in that drawing editor.Tutorial

1. Write an AutoLisp programme to draw steps. Input allowed: two points, one point at bottom of steps another point at top of last step; number of steps.

file: STEPS.LSP

2. Write an AutoLisp programme to draw a happy face. Allowed input would be only two points. The first point dictates the center of the face. The second point will define the circumference of the circle. Orientation of the happy face should be according to the angle defined by the two points picked.

file:HAPFACE.LSP

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 25: Autolisp Notes New By Swapnil A. Kale

25Z:Swapnil A. Kale/MDCG/LISP/Notes

Lesson 6getvar setvar rtos strcat strlen substr

progn strcase /=

In this lesson we are going to use AutoLisp to put text on the drawing. Many a time we need to know the coordinate of a point on the drawing. Nowadays due to the advance technology in land surveying most of the site plans are actually done with coordinates.AutoCAD is a very accurate software in this respect. After a designer drew a roadway on a topographical AutoCAD drawing, coordinates for all the important points such as BC( beginning of curve), EC(end of curve), PCC(point on compound curve) are actually known and readily available for surveyors to use for site layout.

The following example will write the coordinates of a selected point directly on the drawing. Whenever AutoCAD command Atext@ is used, it is good to define the text style to be used. If textstyle is not defined in the same programme, current text style of the drawing will be used and it may not be the right one for your programme.

getvar AutoLisp function to get the existing value of a system variable.setvar AutoLisp function to set an AutoCAD system variable.rtos AutoLisp function to convert a number or variable to a string.strcat AutoLisp function to joint two strings to become one string.

Use a Windows text editor to type the following file:-

(defun c:pid () (graphscr)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 26: Autolisp Notes New By Swapnil A. Kale

26Z:Swapnil A. Kale/MDCG/LISP/Notes

(if (= SC nil) (setq SC (getreal "Scale of the dwg is 1: ")) ) (setq B (getvar "blipmode")) (setvar "blipmode" 1) (setq C (getpoint "Select point for I.D. ")) (terpri) (setq ST1 (getpoint "Select point for beginning of text. ")) (terpri) (setq ANG (getangle "Rotation of text " ST1)) (terpri) (setq TS (* SC 2.5)) (command "style" "COOR" "SIMPLEX" TS 1.0 0.0 "n" "n" "n") (setq VDT (* 1.50 TS)) (setq ST2 (polar ST1 (- ANG (/ pi 2)) VDT)) (setq ANGD (/ (* ANG 180) pi)) (setq X (car C)) (setq Y (cadr C)) (setq EAST (rtos X )) (setq NORTH (rtos Y )) (setq ECOOR (strcat "E " EAST)) (setq NCOOR (strcat "N " NORTH)) (command "text" ST1 ANGD ECOOR) (command "text" ST2 ANGD NCOOR) (command "redraw") (setvar "blipmode" B))

The following example is an AutoLisp routine to do text along a circular path.

strlen This function returns an integer that is the number of characters in a string.substr

The function returns a substring of a string.e.g. (substr "abcde" 2) returns "bcde"

(substr "abcde" 2 1) returns "b"(substr "abcde" 3 2) returns "cd"

/= This not equal to.Use a Windows text editor and type the file as below:-

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 27: Autolisp Notes New By Swapnil A. Kale

27Z:Swapnil A. Kale/MDCG/LISP/Notes

(defun c:CURTEX ()(setq PT1 (getpoint "Pick the starting point of text"))(terpri)(setq PT2 (getpoint "Pick the center of arc for the text" PT1))(terpri)(setq TEX (getstring T "Please start to type the text...."))(terpri)(if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")))(setq TXZ (* SC 2.54))(setq STY (getvar "textstyle"))(if (/= STY "curtex") (command "style" "curtex" "complex" TXZ 1.0 0.0 "n" "n" "n"))(setq TXL (strlen TEX))(setq N 1)(repeat TXL(setq TTC (angle PT1 PT2))(setq RAD (distance PT1 PT2))(setq TAN (+ (/ pi 2) TTC))(setq TANG (* TAN 57.2958))(setq PT3 (polar PT1 TAN TXZ))(setq PT4 (polar PT2 (angle PT2 PT3) RAD))(setq CTX (substr TEX N 1))(command "text" PT1 TANG CTX)(setq PT1 PT4)(setq N (+ N 1))))

FIG. 6.2 shows the text done by CURTEX.LSP As we can see the spacing for some of the alphabets is not very well proportioned. There are certain letters, we have to pay extra attention to. The following AutoLisp programme bases on the previous one but spacings for the letters, m, i, and l are adjusted to make the text look better.

prognThis function evaluates each expression sequentially, usually used with the if function.

strcase This function evaluates all characters in a variable as uppercase.

(defun c:CURTEX2 ()(setq PT1 (getpoint "Pick the starting point of text"))(terpri)(setq PT2 (getpoint "Pick the center of arc for the text" PT1))(terpri)(setq TEX (getstring T "Please start to type the text...."))(terpri)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 28: Autolisp Notes New By Swapnil A. Kale

28Z:Swapnil A. Kale/MDCG/LISP/Notes

(if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")))(setq TXZ (* SC 2.54))(setq STY (getvar "textstyle"))(if (/= STY "curtex") (command "style" "curtex" "complex" TXZ 1.0 0.0 "n" "n" "n"))(setq TXL (strlen TEX))(setq N 1)(repeat TXL(setq TTC (angle PT1 PT2))(setq RAD (distance PT1 PT2))(setq TAN (+ (/ pi 2) TTC))(setq TANG (* TAN 57.2958))(setq PT3 (polar PT1 TAN TXZ ))(setq PT4 (polar PT2 (angle PT2 PT3) RAD))(setq CTX (substr TEX N 1))(command "text" PT1 TANG CTX) (if (= CTX "m") (progn (setq PT3 (polar PT1 TAN (* TXZ 1.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) ) (if (= CTX "l") (progn (setq PT3 (polar PT1 TAN (* TXZ 0.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) )(setq CHK (strcase CTX)) (if (= CHK "I") (progn (setq PT3 (polar PT1 TAN (* TXZ 0.5))) (setq PT4 (polar PT2 (angle PT2 PT3) RAD)) ) )(setq PT1 PT4)(setq N (+ N 1))))Tutorial:1. Write an AutoLisp programme which will prompt to pick up points and a line will connect

each subsequently picked points with the length of the line written at its side. The process will continue as long as points are being picked. file: LINETX.LSP

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 29: Autolisp Notes New By Swapnil A. Kale

29Z:Swapnil A. Kale/MDCG/LISP/Notes

2. Write an AutoLisp programme which will ask user to pick 2 points to define a rectangular area and input the verical load (e.g. 15KN/M); then it will start filling the defined area by downward arrows and put the vertical load value above the arrows.(As shown in Fig. 6.5) file: VLOADAR.LSP

3. Similar to above, write an AutoLisp programme which will ask user to pick 2 points to define a rectangular area and input the horizontal load (e.g. 15KN/M); then it will start filling the defined area by horizontal arrows and put the horizontal load value close to the arrows.(As shown in Fig. 6.6)

file: HLOADAR.LSP

4.. Write an AutoLisp programme which will draw the shape of horizontal triangular load (earth load). The input will be bottom and top of triangular load, end of the bottom arrow and value of force at bottom. (As shown in Fig. 6.7) file: TLOADAR.LSP

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 30: Autolisp Notes New By Swapnil A. Kale

30Z:Swapnil A. Kale/MDCG/LISP/Notes

Lesson 7Math & AutoLispor cons foreach

AutoLisp include all trigonometrical and mathematical functions. Using the built-in functions many geometrical shapes could be drawn easily by means of AutoLisp. The following example is an AutoLisp routine to draw a star of any specified vertices.The ability to write this kind of programme depends very much on the programmer=s mathematical and geometrical skill.

In order to write this programme, we need to understand how the angles within a polygon are related to each other.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 31: Autolisp Notes New By Swapnil A. Kale

31Z:Swapnil A. Kale/MDCG/LISP/Notes

In FIG. 7.1 < INCLAN = 360 NC Where NC = number of vertices (or sides)< ANIN = <INCLAN 2 Substended by half arc length< ANIN = <ANOUT + <ANOUT Exterior angle of a triangle

<ANOUT = <INCLAN 4

In PNT1 PNT2 CEN<PNT2 PNT1 CEN = ANOUT Bottom of issoc.<PNT2 CEN PNT1 = ANIN <s Subtended by equal arcs in same

use sine formula for PNT1 PNT2 CEN

IRAD / SIN (180 - ANIN - ANOUT) = SRAD / SIN ANOUT SRAD = SIN ANOUT * IRAD / SIN (180 - ANIN - ANOUT)

Where IRAD is the distance from CEN to PNT1SRAD is the distance from CEN TO PNT2

After PNT2 is established and connected to PNT1, command Amirror@ is used to form the second line. These two lines are then central-arrayed to complete the programme.

Use a text editor and type the following file:

(defun c:STAR () (graphscr) (setq NC (getint "Input number of vertices for the star ")) (setq CEN (getpoint "Centroid of star ")) (setq PNT1 (getpoint "One vertex of the star " cen)) (setq INCLAN (/ (* 2 pi) NC)) ;included angle at center (setq ANOUT (/ (/ (* 2 pi) NC) 4)) (setq ANIN (* 2 ANOUT)) (setq ANG (angle CEN PNT1)) (setq IRAD (distance CEN PNT1)) (setq SRAD (* IRAD (/ (sin ANOUT) (sin (- pi (+ ANOUT ANIN)))))) (setq PNT2 (polar CEN (+ ANG ANIN) SRAD)) (command "line" PNT1 PNT2 "" "mirror" PNT1 "" CEN PNT2 "") (setq INCLAND (* (/ INCLAN pi) 180)) (command "array" "l" PNT1 "" "c" CEN INCLAND NC "y"))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 32: Autolisp Notes New By Swapnil A. Kale

32Z:Swapnil A. Kale/MDCG/LISP/Notes

FIG. 7.2 Shows the stars drawn by this programme.

AutoLisp could be used to draw the graph of a equation. Programming for a graph would include: the evaluatin of X & Y coordinates, the combining of X & Y to form points, the construction of a list for all these calculated points, and finally use the Apline@ command and step through all the points in the list.

The following example uses AutoLisp to draw a graph :

Y = X2 5 for the range -10 < X < 10

To begin with, a list with all the calculated points is needed. The list has to be assigned a name. Here let us call it PNTLIST. Before the list has any calculated value, we always set it to nil in order to ensure it starts as an empty list.

(setq PNTLIST nil)

Before a calculation loop, the lower limit of X value should be specified.

(setq X -10)

or a condition function in AutoLisp

The while loop is then used to calculate the points, and to specify the upper limit of X

(while (or (< X 10) (= X 10)) ..... ....)

The equation Y = X2 5 in AutoLisp is:

(setq Y (/ (* X X) 5))

points are formed by using the list function.

(setq PNT (list X Y))

cons AutoLisp function to construct the list by adding new data to the list

(setq PNTLIST (cons PNT PNTLIST))

After each point is added to the list, increment of X is applied.(setq X (+ X 0.2))

After the list is completed, the following 4 lines work together to draw the polyline and fit the curve.

(command "pline")(foreach P PNTLIST (command P))(command "")(command "pedit" "l" "s" "w" 0.0 "x")

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 33: Autolisp Notes New By Swapnil A. Kale

33Z:Swapnil A. Kale/MDCG/LISP/Notes

foreach AutoLisp function to cause execution of a command on each element of a list.

The whole programme should read as the following:

(defun c:SQC ()(setq PNTLIST nil)(setq X -10)(while (or (< X 10) (= X 10)) (setq Y (/ (* X X) 5)) (setq PNT (list X Y)) (setq PNTLIST (cons PNT PNTLIST)) (setq X (+ X 0.2)))(command "pline")(foreach P PNTLIST (command P))(command "")(command "pedit" "l" "f" "w" 0.0 "x"))

Shell out and type the above programme.

The above method is a handy way to draw any graph for an explicit equation on a drawing. Coordinates of the points dictate where the curve will be drawn. But many a time we would like to put the curve at any convenient location on the drawing, regardless of the drawing global coordinate system. This could be done simply by using the UCS features of AutoCAD.

The above programme could be revised to read as follow:

(defun c:SQC ()(setq B (getpoint "Pick origin of graph.")) ;added line(setq PNTLIST nil)(setq X -10)(while (or (< X 10) (= X 10)) (setq Y (/ (* X X) 5)) (setq PNT (list X Y)) (setq PNTLIST (cons PNT PNTLIST)) (setq X (+ X 0.2)))(command "ucs" "o" B) ;added line(command "pline")(foreach P PNTLIST (command P))(command "")(command "pedit" "l" "f" "w" 0.0 "x")(command "ucs" "p") ;added line)

Now the programme will ask the user to pick a point which will be used as the origin (0,0) for the curve anywhere on the drawing.

Tutorial:

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 34: Autolisp Notes New By Swapnil A. Kale

34Z:Swapnil A. Kale/MDCG/LISP/Notes

1 Write an AutoLisp programme to draw the following curve on the drawing:-a) y = x3 / 5 for -5 < x < 5

b) Y=Cos X for 0 < X < 2 pi

c) Y=Sin X for 0 < X < 2 pi

d) Y=Sin2X for 0 <X < 2pi

e) Y=Sin X/2 for 0 < X < 2 pi

Lesson 8fix entlast

Fig. 8-1 is the building block for Fig. 8-2. The drawing of insulation is always necessary on architectural drawings. This AutoLisp makes use of an existing block inserted on the drawing with a scale calculated according to input from the user and then copied to fill a specified area. In this example, the object selection method, Alast@, is not used. Instead of Alast@, the AutoLisp function entlast is used. In object selection mode, Alast@ means the last entity created and visible on the screen. If the entity created last is outside the display area, then Alast@ will not select the entity you want. However, enlast will return the name of the last nondeleted main entity whether visible or not..

fix AutoLisp function to convert a real number to an integer.entlast AutoLisp function to return the name of the last nondeleted main entity.Use a text editor to type the following file:-

(defun c:insulate ()(setq a nil)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 35: Autolisp Notes New By Swapnil A. Kale

35Z:Swapnil A. Kale/MDCG/LISP/Notes

(setq PT1 (getpoint "Starting Point of Insulation "))(setq PT2 (getpoint PT1 "\nEnd Point of Insulation "))(setq THK (getdist PT1"\nThickness of insulation: "))(setq L1 (distance PT1 PT2)) (setq ANGR (angle PT1 PT2))(setq ANGD (* ANGR (/ 180. pi)))(setq NUM (/ L1 50))(setq NUM (fix NUM))(setq L2A (/ L1 NUM))(setq L2 50.0) ;original block is 50wide(setq FACTOR (/ L2A L2))(setq THKF (/ THK 75.0));original block is 75high(command "layer" "m" "AR-INSUL-RD" "c" "1" "" "")(command "insert" "insulate" PT1 FACTOR THKF ANGD)(setq N 1)(while (< N NUM) (setq E1 (entlast)) (setq PT3 (polar PT2 ANGR (* FACTOR L2))) (command "copy" E1 "" PT2 PT3) (setq PT2 PT3) (setq N (+ N 1)))(command "redraw"))

To understand the above example is very important, because this method could be used to prepare other useful graphics, for example, layer of gravel, layer of solid insulation, or corrugate steel plate section....etc.

Fig. 8-3 shows the fence symbol by AutoLisp. AutoCAD allows the preparation of linetype with a symbol as part of it. To prepare that kind of linetype you need to prepare a shape first. If you do not want to prepare a shape, the alternative is to use AutoLisp as shown by the example below:(defun c:fence ()(graphscr)(setq STY (getvar "textstyle"))(COMMAND "LAYER" "M" "ST-MISCL-YE" "C" "2" "" "") (if (= SC nil) (setq SC (getreal "Scale of dwg. 1: ")) ) (setq TXTSZ (* SC 1.0))(command "style" "fence" "simplex" TXTSZ 1.0 0.0 "n" "n" "n")(setq PT1 (getpoint "First point of fence ")) (terpri)(setq PT2 (getpoint "2nd point of fence" PT1)) (terpri)(while PT2(setq LL (* SC 1.0))(setq ANG1T2 (angle PT1 PT2))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Figure 8-3

Page 36: Autolisp Notes New By Swapnil A. Kale

36Z:Swapnil A. Kale/MDCG/LISP/Notes

(setq ANG2T1 (angle PT2 PT1))(setq ANG1T2D (* ANG1T2 57.29578))(setq LEN (distance PT1 PT2))(setq SEC (/ LEN (* LL 10.0)))(setq FSEC (fix SEC))(setq SECL (/ LEN FSEC))(setq PTALIST nil)(setq DLEN SECL)(repeat FSEC (setq PTA (polar PT1 ANG1T2 DLEN)) (setq PTALIST (cons PTA PTALIST)) (setq DLEN (+ SECL DLEN)))(foreach PTA PTALIST (setq PTA2 (polar PTA ang2T1 (- SECL TXTSZ ))) (setq PTA1 (polar PTA ang2T1 TXTSZ)) (command "text" "m" PTA ANG1T2D "X" ) (command "line" PTA1 PTA2 ""))(command "redraw")(setq PT1 PT2)(setq PT2 (getpoint "2nd point of fence" PT1)) (terpri))(setvar "textstyle" STY))

The above programme could be easily modified to include other text to indicate utility lines on the drawing. It is wise to make sure the steps and logics are fully understood.

Tutorial:

1. Draw the symbol of the section of a cut-off pipe and write an AutoLisp programme to fit the symbol to two selected points.

file: PEND.LSP

2. Write an AutoLisp programme to draw railway lines.file: RAIL.LSP

3. Write an AutoLisp programme to draw a symbol to represent an exhaust fan, as shown on Fig. 8-6. The user input will include the location for center of fan, and a point at the edge of fan only. Draw the grille and the blades on different layers. file: EXFAN.LSP

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 37: Autolisp Notes New By Swapnil A. Kale

37Z:Swapnil A. Kale/MDCG/LISP/Notes

LESSON 9entsel entget assoc ssget ssname sslength subst entmod cdr

Open a drawing named AENTITIES@ which consist of 3 lines and 2 layers, ROADEP and ROADCL.

At the command prompt, type: (setq a2 (entsel))

Computer response: Select object:pick the solid line at right of the centerline.

Computer response: (<Entity name: ba4540> (8.51974 2.20869 0.0)

entsel AutoLisp function to select an entity, and it returns the entity name and the coordinate of the point you picked.

On the drawing database all entities are identified by an alphanumeric name as shown above. It is by using this entity name we could tap into the information specific for that entity.

entget AutoLisp function to extract the entity list which contains all information neccessary to describe the entity on the drawing database.

At the command prompt, type (setq b2 (entget (car a2)))

Computer response: ((-1 . <Entity name: ba4540>) (0.@Line@))

Now all the information of the entity are assigned to the variable name, b2. When !b2 is type, the whole list will be displayed. Each item in the list is really in two parts. The first is a code number that tells the function of that entity=s aspect. Listed below are a few code numbers :-0 description6 line type name7 text style name8 layer name

assoc An AutoLisp function that searches for a sublist within any list. With an entity list, assoc uses the entity code number as key.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 38: Autolisp Notes New By Swapnil A. Kale

38Z:Swapnil A. Kale/MDCG/LISP/Notes

at command prompt type: (setq L1 (assoc 8 b2))

computer response: (8 . AROADEP@)

at the command prompt type: (setq L2 (cdr L1))

computer response: AROADEP@

As shown, by using entsel, entget, car, assoc and cdr we could find the layer name of a selected entity. Therefore, it would not be too complicate to write an AutoLisp to set the current layer to a selected entity.

Use text editor to type the following file:(defun c:setlayer () (graphscr) (setq A2 (entsel "Select object to set current layer: ")) (setq B2 (entget (car A2))) (setq L1 (assoc 8 B2)) (setq L2 (cdr L1)) (command "layer" "s" L2 ""))The above example uses entsel to select an object. When many entities have to be selected at the same time, the function to use should be ssget. Usually after ssget is used, the number of objects selected has to be known so that a repeat function could be used to perform a certain task for each of the selected entity. sslength is the function to find out how many selected entities are there. Each selected entity also carry an index which starts from 0. ssname followed by the variable name of a selected set and the index will secure the name of an entity on the drawing database.. Properties of an entity could be changed by changing the values of their sublist. subst and entmod are the functions to achieve this operation.

ssget AutoLisp function to select entities.

ssname AutoLisp function to secure the name of an entity.

sslength The function to determine the number of entities in a selection set.

subst AutoLisp command the substitutes on entity sublist for another within an entity list.

entmod AutoLisp function that updates the drawing database with the new entity list.Use a text editor to type the following file:

(defun c:chlayer () (graphscr) (prompt Aselect objects to change to another layer@) (setq A1 (ssget)) (terpri) (setq A2 (entsel "Select object in the right layer:")) (setq N (sslength A1)) (setq INDEX 0) (setq B2 (entget (car A2))) (setq D2 (assoc 8 B2))

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 39: Autolisp Notes New By Swapnil A. Kale

39Z:Swapnil A. Kale/MDCG/LISP/Notes

(repeat N (setq B1 (entget (ssname A1 INDEX))) (setq D1 (assoc 8 B1)) (setq B3 (subst D2 D1 B1)) (entmod B3) (setq INDEX (+ INDEX 1)) ))

The following is another example to use the AutoLisp functions just introduced.

cdr AutoLisp function that produces the second and remaining elements in a list.e.g. if a is a list (4 5 6 7), then (cdr a) will return (5 6 7).

(defun c:chtexth () (prompt Aselect the texts to be change...@) (setq A (ssget))(terpri) (setq TH (getreal "Enter new text height: ")) (setq N (sslength A)) (setq INDEX 0) (repeat N (setq B1 (entget (ssname A INDEX))) (setq INDEX (+ 1 INDEX)) (setq B (assoc 0 B1)) (if (= "TEXT" (cdr B)) (progn (setq C (assoc 40 B1)) (setq D (cons (car C) TH)) (setq B2 (subst D C B1)) (entmod B2) ) ) ))

Data Type Programme

; Assignment no-1

; data types

(defun c:data()

(setq a(getpoint "\n enter the co-ordinates")

b(getint"\n enter the integer value =")

c(getreal"\n enter the real value=")

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 40: Autolisp Notes New By Swapnil A. Kale

40Z:Swapnil A. Kale/MDCG/LISP/Notes

d(getstring "\n enter the text/ number=")

e(list 10 20 30 40 50 60 70 80 90 100 )

)

(print a)

(print b)

(print c)

(print d)

(print e)

)

Math Programme

;my program

;math

;sachin gawade

;date 17/08/2010

(defun c:math()

(setq a 10

b 50

c 12

d(+ a b c)

e(- b c)

f(* a b)

g(/ b a)

h(max a b c)

i(min a b c)

k(rem c a)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 41: Autolisp Notes New By Swapnil A. Kale

41Z:Swapnil A. Kale/MDCG/LISP/Notes

l(sqrt a)

n(log c)

o(sin i)

)

(princ d)

(princ e)

(princ f)

(princ g)

(princ h)

(princ i)

(princ k)

(princ l)

(princ n)

(princ o)

DataConversion

;my program

;data conversion

(defun c:data()

(setq a(getint"\n enter width:")

b(getreal"\n enter lenth:")

c(getint"\n enter height:")

h(fix a)

d(float b)

e(itoa a)

f(rtos b)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 42: Autolisp Notes New By Swapnil A. Kale

42Z:Swapnil A. Kale/MDCG/LISP/Notes

g(gcd a c)

i(list a)

j(list b)

p(log a)

q(exp a)

)

(princ h)

(princ d)

(princ e)

(princ f)

(princ g)

(princ i)

(princ j)

(princ p)

(princ q)

)

Descision Making (Using if Function)

;-----Program 6b

;----- Program on Descision Making (Using if Function)

(defun C:DECI2 ()

(setq l(getreal "\n Enter Length : ")

h(getreal "\n Enter Height : ")

)

(if (= h l)

(progn

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 43: Autolisp Notes New By Swapnil A. Kale

43Z:Swapnil A. Kale/MDCG/LISP/Notes

(prompt "The diagram is Square ")

(setq x(* h h))

(print x)

)

(progn

(prompt "The diagram is Rectangle ")

(setq x(* l h))

(print x))))

PROGRAM FOR LOOPING USING

;PROGRAM FOR LOOPING USING

(defun c:conrect()

(setq l(getreal "\n enter the length of rectangle"))

(setq h(getreal "\n enter the hight of rectangle"))

(setq pt1(list 0 0))

(setq n(getint "\n enter number of rectangles"))

(setq pt2(list(+ (car pt1) l) (+ (cadr pt1) h)))

(setq count 1)

(while (<= count n)

(command "rectangle" pt1 pt2)

(setq pt1(list (- (car pt1) 10) (- (cadr pt1) 10)))

(setq pt2(list (+ (car pt2) 10) (+ (cadr pt2) 10)))

(setq count(+ count 1))

)

(command "zoom" "e")

)

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 44: Autolisp Notes New By Swapnil A. Kale

44Z:Swapnil A. Kale/MDCG/LISP/Notes

I know – When I am teaching, I am learning more.

Questions on topic 71. Input the length of sides of triangle and check whether it forms a triangle or not. If it forms atriangle draw the triangle.2. Input the diameter of flange. According to diameter of the flange create no of holes on theflange.3. Input the end points of diagonal of the quadrilateral. Find out where it is square or rectangle. Ifit is a square or rectangle then draw the same. Assume base of quadrilateral is parallel to x-axis.4. Input the length of sides of triangle and find out which type of triangle it is and draw the same.5. Draw a circle and pick a point on the screen. Find out whether the point lies inside or outsidethe circle.6. Select a geometrical entity (line/circle). If it is line find the length angle of line. If it is a circle findradius and center points coordinate.7. Draw a circle. Select option for hatching (1/2). If it is 1, draw hatch using select object optionand if it is 2, then draw the hatch with pick point option.8. Draw an arc. Find out the included angle of the arc. Depending upon the angle decide the no ofdivision of the arc and divide the arc.9. Draw square and circle (inscribe of circumscribe). Find out who is circumscribing what accordingto dimension.10. Draw a line and pick a point on the line with mouse. Find out whether that point lie left or rightof the midpoint of the line.11. Find the summation of series like:Sum=x+x^2+x^3+x^4+…..Sum= x-x^2+x^3-x^4+…..Sum= x-x^2/2!+x^3/3!-x^4/4!+…..12. Input number of forces and find the resultant (magnitude and direction). Draw the forcepolygon.13. Input the number of sides and draw polygon. (create polygon command)14. Create polar array command for circle.15. Create rectangular array command for circle.16. Create multiple copy command for circle.17. Draw f(x) curve for given limits.18. Creating bill of material.19. Move the object, if the object is selected is not nil with entsel.20. Input x and y coordinates of n points and draw curve/line through them.21. Select multiple entities of various types with ssget and find the types of entities.1. Select line from screen and find coordinates of end points and length of line.Questions on topic 1-62. Select circle from screen and find coordinates of centre point, radius and area.3. Select entity with ssget and find the types of entities.4. Draw rectangle.5. Draw triangle.6. Draw hexagon.7. Input two strings from the user and perform various string operations.

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 45: Autolisp Notes New By Swapnil A. Kale

45Z:Swapnil A. Kale/MDCG/LISP/Notes

8. Input two points from the user and perform various list filtering operations.9. Find f(x) for two/three x values.10. Input height of equilateral triangle and find the length of side, area and perimeter. Draw the sametriangle.11. Input height and base of isosceles triangle and find the length of side, area and perimeter. Draw the same triangle.12. Input diagonal of square and find the length of side, area and perimeter. Draw the same triangle.13. Input area of equilateral triangle and find the length of side and perimeter. Draw the same triangle.15. Parametric program of nut, bolt, surface roughness symbols etc.16. Input two points from mouse and find distance and angle between the points.17. Using string and data conversion functions draw rectangle.18. Using string and data conversion functions draw hexagon.19. Using string and data conversion functions draw pentagon.20. Input string and number and perform various string functions.14. Input area of circle and find radius and perimeter. Draw the same circle.

References’

ABC’s of AutoLISP by George Omura

www.google.com

AutoLISP by T.K.Naskar

MDCG by F. Haideri

Visual LISP AutoDESK

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 46: Autolisp Notes New By Swapnil A. Kale

46Z:Swapnil A. Kale/MDCG/LISP/Notes

NOTICE FOR S.E. Mech. Engg. X AND Y Year - 2010-11

SUBJECT :- FINAL TERM WORK CONTENT

ASSIGNMENT NO 1

DRAWING ASPECTS WHAT IS CAD ? AUTOCAD ENTITIES WHAT AUTOCAD PROVIDES DRAWING AIDS, EDIT COMMANDS, DRAW COMMADS, MODIFY COMMANDS,

ASSIGNMENT NO 2

LAYER AND ITS ADVANTAGES, REGEN, REDRAW.

ASSIGNMENT NO 3

BLOCKS, SNAP, OSNAP,

ASSIGNMENT NO 4

SCRIPT FILE PROGRAMMING, ADVANTAGES AND LIMITATIONS , FLOW CHART

ASSIGNMENT NO 5

a) INTRODUCTION TO AUTOLISP WORKING WITH AUTOLISP USING LIST FUNCTION

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"

Page 47: Autolisp Notes New By Swapnil A. Kale

47Z:Swapnil A. Kale/MDCG/LISP/Notes

CREATING – PASSING INFORMATION – RUN PROGRAM – IN AUTOCAD AUTOLISP SUMMARY

b) DATA TYPE: - List, String, Real, Integer, File Descriptor, Object Name, PICK SETc) MATH FUNCTIONS:- All Functionsd) DATA CONVERSION:- Integer to real , Integer to string , integer to list, real to

integer Real to string, real to list

e) LIST FILTERING:- car , cdr , cadr , caddr f) PARAMETRIC PROGRAMMING:- g) LOOPING

f) FILE HANDELLING

“I hear and I forget. I see and I remember. I do and I understand." -- Confucius"