CAD practical programming part I C++ initiation and introduction to Gnurbs

Similar documents
Sources: On the Web: Slides will be available on:

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Appendix K Introduction to Microsoft Visual C++ 6.0

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Illustration 1: Diagram of program function and data flow

The programming language C. sws1 1

How to test and debug an ASP.NET application

Creating Database Tables in Microsoft SQL Server

arrays C Programming Language - Arrays

Informatica e Sistemi in Tempo Reale

AutoDWG DWGSee DWG Viewer. DWGSee User Guide

Code::Blocks Student Manual

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Data Tool Platform SQL Development Tools

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Beginner s Matlab Tutorial

Athena Knowledge Base

Hypercosm. Studio.

The C Programming Language course syllabus associate level

DWGSee Professional User Guide

Computer Programming C++ Classes and Objects 15 th Lecture

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

ECDL. European Computer Driving Licence. Spreadsheet Software BCS ITQ Level 2. Syllabus Version 5.0

Object Oriented Software Design

CS 103 Lab Linux and Virtual Machines

Exercise 4 Learning Python language fundamentals

Visual Basic 2010 Essentials

C++ INTERVIEW QUESTIONS

Qlik REST Connector Installation and User Guide

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Object Oriented Software Design

Tic, Tie & Calculate Quick Start Guide. Quick Start Guide

C++ Programming Language

Q N X S O F T W A R E D E V E L O P M E N T P L A T F O R M v Steps to Developing a QNX Program Quickstart Guide

Content Author's Reference and Cookbook

A computer running Windows Vista or Mac OS X

An Incomplete C++ Primer. University of Wyoming MA 5310

Getting Started using the SQuirreL SQL Client

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Visual Basic Programming. An Introduction

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Visual Studio 2008 Express Editions

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Lecture 2 Mathcad Basics

3 IDE (Integrated Development Environment)

Operating Systems. and Windows

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Xcode Project Management Guide. (Legacy)

13 Managing Devices. Your computer is an assembly of many components from different manufacturers. LESSON OBJECTIVES

Microsoft Visual Studio 2010 Instructions For C Programs

Creating Web Services Applications with IntelliJ IDEA

Xcode User Default Reference. (Legacy)

Embroidery Fonts Plus ( EFP ) Tutorial Guide Version

Top 72 Perl Interview Questions and Answers

Creating Custom Crystal Reports Tutorial

Waspmote IDE. User Guide

INTRODUCTION to ESRI ARCGIS For Visualization, CPSC 178

Quickstart Tutorial. Bradford Technologies, Inc. 302 Piercy Road, San Jose, California fax

IBM FileNet eforms Designer

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

Code Estimation Tools Directions for a Services Engagement

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Running your first Linux Program

2Creating Reports: Basic Techniques. Chapter

3. Programming the STM32F4-Discovery

Code::Block manual. for CS101x course. Department of Computer Science and Engineering Indian Institute of Technology - Bombay Mumbai

FIRST STEPS WITH SCILAB

Lecture 5: Java Fundamentals III

TUTORIAL 4 Building a Navigation Bar with Fireworks

The VB development environment


10 STEPS TO YOUR FIRST QNX PROGRAM. QUICKSTART GUIDE Second Edition

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

File Management Windows

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Moving from CS 61A Scheme to CS 61B Java

KPN SMS mail. Send SMS as fast as !

PCSpim Tutorial. Nathan Goulding-Hotta v0.1

RuleBender Tutorial

Installing Java. Table of contents

C++ Language Tutorial

Lab 1 Beginning C Program

Eventia Log Parsing Editor 1.0 Administration Guide

Install Java Development Kit (JDK) 1.8

Designing and Implementing Forms 34

Chapter One Introduction to Programming

Contents. Launching FrontPage Working with the FrontPage Interface... 3 View Options... 4 The Folders List... 5 The Page View Frame...

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

Visual C Tutorial

Microsoft Access 2010 Overview of Basics

Visualization with Excel Tools and Microsoft Azure

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Data Structures

Getting Started with Command Prompts

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

Chief Architect X6. Download & Installation Instructions. Chief Architect, Inc N. Mineral Dr. Coeur d Alene, Idaho

CS 106 Introduction to Computer Science I

Transcription:

CAD practical programming part I C++ initiation and introduction to Gnurbs Introduction to C++ Download the archive CAD_TP1_Code.zip on the course web page (http://www.cgeo.ulg.ac.be/cao). In the folder 1erMaster on the desktop, create a folder in your name. Then unzip the archive there. The archive contains three folders for each program that we will use in this lab. Getting Started with the Development Environment During these labs you will use the programming software Code::Blocks to edit the source code of your programs, compile the source (i.e. turn it into executable) and run your executable. For practical reasons, the programs written in C++ are often written using separate files. Therefore, development environments such as Code::Blocks propose to combine the source files of a program as a Project. Besides the list of source files involved, the project also contains instructions for compiling and executing. It can also ease the navigation into the source code. The first step before you start programming with Code::Blocks is to create the project. In order to start, go to the folder of the first example program ( example1 ). Although this is not very useful here because our current program consist in a single file, we will use CMake to generate the Code::Blocks Project. The procedure will remain the same for future programs. The advantage of CMake is that it can generate projects for several compilers (Code::Blocks, Borland C++, Visual Studio...) and several operating systems (Linux, Windows, Mac...) from the same source files. Creating the Project Start CMake: click on the CMake button on the menu on the left. In the input field Where is the source code enter the name of the directory where is your source code. Normally it is: /home/user/bureau/1ermaster/lastnames/example1 In the Where to build the binaries field, enter the same path and add /project at the end. It is in this directory that will be generated the Code::Blocks project. Then click Configure to start the configuration. Click Yes when CMake asks if the directory project should be created. In the window that appears select CodeBlocks Unix Makefiles in the drop-down menu. Then confirm by clicking Finish. 1

The configuration takes a few seconds, after which CMake displays several variables. Keep the default values. Confirm the values by clicking again on Configure and then Generate in order to generate the project. Your folder /home/user/bureau/1ermaster/lastnames/example1/project now contains a file named EXEMPLE1.cpb. This file is the Code::Blocks project generated by CMake. Open the project file. Development environment The opening of the project file triggers the display of the Code::Blocks development environment. A window similar to the one shown below appears. The main elements of the development environment are: The browser that allows you to list the source files and open them in the editor. For example, you can open the source file main.cpp (single file in this example program) to display it in the editor. The source code editor to modify it. Toolbars. You can for example select the target to compile or run and then compile and run the program. The Build target selector allows selection of a particular target to build. This is useful when a project contains several executables or if we want to build debugs versions of a given executable. The message window that display errors and compilation warnings. 2

As we will see, this example program is very simple. Before launching, it is mandatory to compile, which means converting the human-readable source code (text files) into machine code (executable file.exe). Before starting the compilation, select the target EXEMPLE1 in the menu Build target. To start the compilation, simply click on the button in the toolbar. Once the compilation is complete, the executable EXEMPLE1.exe is created in the directory /home/user/bureau/1ermaster/lastnames/example1/project. You can run it by clicking on the button located right next to the button Compile. The window shown on the right then opens. Description of the source code The program is very short; it only displays the text Hello World! on the screen and ends by returning the value 0. To study its running, return to the Code::Blocks and edit the file main.cpp. It contains a single function called main. main is the name given conventionally main function in C and C++. During the program execution, the main function is always the function that will be executed first. Execution occurs line by line, beginning with the first line of the main function. Its source code is the following: #include <iostream> int main() std::cout<<"hello world!"<<std::endl; return 0; It contains various elements: The file begins with the keyword include, preceded by the character #. This character # means that we call a special feature of the compiler, named the preprocessor. Before the compilation itself the preprocessor will scan all source files in search for texts to include, replace, concatenate, etc. Here the keyword include followed by a file named iostream means: include the code of the file iostream at this location of the current file main.cpp. The file iostream (for input/ouput stream ) is part of the C++ Standard Template Library (STL) and regroups several functions (and classes) for performing input and output operations on the screen and the keyboard. There are numerous other files in the STL providing useful other functions. The next keyword is int which means integer. It defines the type of the value returned by the function. Other basic (primitive) types exist in C/C++. Later we will use e.g. the type double corresponding to a floating point number in double precision. Then we have the function name main followed by the argument list () which is empty in this case. The function body is delimited by curly brackets. The implementation of the function begins with and ends with. 3

The line std::cout << Hello world! << std::endl; displays the text Hello world! in the console. std::cout is the standard output display flux ( std stands for standard ). std::endl indicates the need to put a new line after the string Hello world!. ( endl means end of line ) Note that the line code ends with a semicolon ;. Indeed, this line corresponds to one instruction and each instruction has to finish with a semicolon. If you forget the semicolon after one instruction, this will lead to a compilation error. The statement return 0; causes the end of the main function with the return value of 0, which is an integer as indicated at the beginning of the function. The end of the main marks the end of the program. How to add comments into the code: You can insert a comment line by starting a line with // // This is a comment on one line. The multi-line comments start with /* and end with */ /* These are comments on several lines. Comment 1... Comment 2...... Comment n... */ It is recommended to add comments describing your code in order to improve the readability of your prose to other people (and to yourself!) Changing the program To practice, we will modify the program to be able to orthogonalize two vectors. Vectors To use the vector in C++, you must first add at the beginning of the file main.cpp : #include <vector> Then in the main function, if you want to create a vector of double (double precision floating point number) called x and that has three components, use the following syntax: std::vector<double> x(3); 4

This syntax works with all types of data, for example, if you want to create a vector of integers, we replace double by int. At this point two major differences are to be emphasized in regards to the programming languages you are accustomed: The index of the first element of the vector is 0 (not 1 as in Matlab). Vector operations such as the scalar product, the addition, subtraction... of two vectors are not defined in C++ (not for std::vector< >). Therefore these operations must be done component-wise using a loop. After creating (declaring) the vector x, we have to initialize its components. Component are accessed with the [] and assigned with = x[0]= 1.5; x[1]= 2.3; x[2]=-1.0; Loops The C++ provides various types of loops. In this introduction, we will limit ourselves to the for loop. The generic syntax of a for loop is as follows: int i; for(i=0; i<10; i++)... The first line is simply a declaration of an integer variable i (which is the index of our loop). The for loop begins at the second line. i=0 means that we assign (initialize) the value 0 to i at the beginning of the loop. The instruction i<10 indicates that the loop will be repeated while i is strictly smaller than 10. And finally, i++ means that i will be incremented by one at each iteration of the loop (i++ is equivalent to i=i+1). As with functions, the content of the loop is enclosed by curly brackets. For example, if we want to compute the dot product of two vectors x and y with three components, we use the following instructions: double prosca=0; int i; for(i=0; i<3; i++) prosca += x[i]*y[i]; prosca double precision variable is declared and initialized to 0 at the first line. The loop then calculates the dot product component by component using the += operator to shorten the writing. The instruction: prosca += x[i]*y[i]; is in fact equivalent to: prosca = prosca + x[i]*y[i]; These two instructions are equivalent and mean: Set the new value of prosca as the old value of prosca plus the value of x[i]*y[i]. 5

An example for the whole code can be the following: Program 1 #include <iostream> #include <vector> int main() // The execution begins here // Declares two vectors x and y of length 3. std::vector<double> x(3), y(3); // Initializes vector x. x[0]= 1.5; x[1]= 2.3; x[2]=-1.0; // Initializes vector y. y[0]= 2.5; y[1]=-2.1; y[2]=-0.2; // Computes the dot product of two vectors x and y. double prosca=0; int i; for(i=0; i<3; i++) prosca += x[i]*y[i]; // Show the result. std::cout<< Dot product: <<prosca<<std::endl; // End of the execution Returns 0 ( everything went ok ) to the OS. return 0; 6

Global functions Functions are used to avoid code duplication. Using functions increases code readability and performances. For example, in program 1, the loop computing the dot product of two vectors should be put into a function. In so doing, we can use the same code for computing dot product between different vectors without copying it again and again. Application: modify program 1 by adding the following code before the main function. double prodscal(std::vector<double> a, std::vector<double> b) double prosca = 0; int i; int taille = a.size(); for(i=0; i<taille; i++) prosca += a[i]*b[i]; return prosca; As we can see, the definition of a global function is very similar to the main function. The main features of this function are the following: The signature of the function is: double prodscal(std::vector<double> a, std::vector<double> b) The signature contains three items: 1. The returned type. Here the function returns a scalar value of type double. 2. The name. The function s name is here prodscal 3. The list of arguments. Here, the function gets to arguments a and b which are std::vector of double. Functions with different signatures are considered to be different. It is then possible to define two different functions with the same name; as long as their signatures (returned value and/or list of arguments) are different. It is however recommended to define different functions with different names in order to avoid any confusion. The body of the function is delimited by braces. int taille = a.size(); allows to retrieve the size/length of vector a. return prosca; tells what is the returned value of the function. Here, it is the value computed in prosca. In the main function, we can now use the function prodscal instead of the loop: double prosca = prodscal(x, y); 7

Application: orthogonalization of two vectors. The orthogonalization of two vectors x and y is done by subtracting to y its projection on x: Where the projection p is: Implement this orthogonalization process and check at the end of the program that x and y are indeed orthogonal by recomputing their dot product. Tips: Use the above function prodscal for computing the dot product. Define a new function double norm(std::vector<double> x) which computes the euclidean norm of a vector. This function will use the function prodscal and the function double sqrt(double), which computes the square root of a number. You will need to add the line #include <cmath> at the beginning of the file. This file defines mathematical functions as sin, cos, tan, etc. Pointers and references In C++ two main mechanisms are used to store the address of a variable: pointers and references. Pointers Variables are stored in the RAM. To each variable an address is associated. A pointer is a variable that stores the address of another variable. RAM name : var value : 2 address : 0x3452ef34 name : p value : 0x3452ef34 address : 0xafd4e567 A pointer p to a variable of type type (int, double, std::vector ) is declared with the following syntax: type *p; 8

The pointer p is set to point to the variable var as follow: p = &var; Where the symbol & means get the address of var. Pointers must be handled with care. Indeed, uninitialized pointers can point anywhere in the RAM. Manipulating uninitialized pointers can lead to uncontrolled behavior and even destabilize the entire OS. It is therefore always a good idea to initialize a pointer. If the initialization value is not known, it is always possible to initialize the pointer to the NULL value. This value means: this pointer is pointing to nowhere. type *p = NULL; // Default value: p is pointing to nowhere. // Some code. p = &var; // p is pointing to variable var. The access to the value of var through the pointer p is done by dereferencing the pointer thanks to the dereference operator *. Here are some examples: double var=2; // Declares a variable of type double and set it to 2. double *p = &var; // p now points to var. std::cout<<*p<<std::endl; // Shows the value of var: 2. *p = 3; // var is now equal to 3. std::cout<<var<<std::endl;// Shows the value of var. std::cout<<p<<std::endl; //!! Shows the ADDRESS of var. Pointers are useful for avoiding the copy of arguments when they are passed to a function. For example, when the function prodscal is called, its arguments a and b are temporary copied. double prodscal(std::vector<double> a, std::vector<double> b) There are three main disadvantages to this approach: Increase in the RAM usage because of the copy of two vectors that can be potentially very long. Loss of computation time due to the copy of the two vectors. The function prodscal cannot modify the original vectors as it works with copies. RAM std::vector x Function prodscal std::vector a copy of x std::vector y std::vector b copy of y 9

Pointers can address these problems by using the following modified function prototype: double prodscal(std::vector<double> *a, std::vector<double> *b) The problems are then solved in the following way: Only pointers are copied. The increase in the RAM usage is only a few bits, regardless of the length of the vectors. Copying pointers is very fast. The function prodscal can now modify the original vectors. RAM std::vector x Function prodscal std::vector y *a *b However, the drawback is that pointers require changes in the implementation of the function. a.size() must be replaced by a->size() because the calling convention of a function by a pointer is different from the one used by a variable. a[i] and b[i] have to be replaced by (*a)[i] and (*b)[i] because it is necessary to dereference a pointer before using operators such as []. References References address the drawbacks of pointers and are more handy and transparent than pointers. A reference r to a variable var of type type is declared and initialized as follow: type &r = var; Note that, unlike pointers, a reference must always be initialized when declared. For accessing the value of var through its reference r, it is not necessary to dereference a reference. Technically, a reference is a dereferenced constant pointer. pointer: because, like pointers, a reference does not involve memory copy of the variable it refers to. constant: because, unlike pointers, a reference can only refer to one object and cannot be set to refer another object. dereferenced: because a reference does not need the dereference operator * for accessing the content of a variable. References can be seen as aliases of variables: the same memory content is referenced by two different names; as the two names Don Diego de la Vega and Zorro refer to the same person. 10

The above examples given for pointers can be translated for references as follows: double var=2; // Declares a variable of type double and set it to 2. double &r = var; // r now refers to var. std::cout<<r<<std::endl; // Shows the value of var: 2. r = 3; // var is now equal to 3. std::cout<<var<<std::endl;// Shows the value of var. std::cout<<r<<std::endl; //!! Shows the CONTENT of var. References can be used for passing arguments to a function with all the advantages of pointers and without the drawbacks of pointers. For example, the prototype of the function prodscal becomes: double prodscal(std::vector<double> &a, std::vector<double> &b) And that s it! No further changes are required in the body of the function. RAM std::vector x std::vector y Function prodscal kown as std::vector a kown as std::vector b Application: By starting from your last code for orthogonalizing two vectors, define a function orthogonalize which gets two vectors x and y passed by reference. At the end of the function, the argument y must be modified by the function orthogonalize. 11

GNURBS Gnurbs is a small software written in C++ that allows creating, visualizing and manipulating curves and surfaces. Adding features to this code is the topic of the next practical sessions. During this session, we will limit ourselves to a few simple exercises in order to better understand the organization of the code. Creating the Code::Blocks project and compiling. The first step is to create the Code::Blocks project and to compile a first executable. Gnurbs source code is included in the archive CAD_TP1_Code.zip. 1. Run CMake and change fields values Where is the source code and Where to build the binaries as follows: a. Where is the source code /home/user/bureau/1ermaster/lastnames/tp1/gnurbstp1 b. Where to build the binaries /home/user/bureau/1ermaster/lastnames/tp1/gnurbstp1/project 2. Then, click on Configure. Under Linux, CMake automatically locates the VTK libraries. On Windows it is necessary to change the value of the parameter VTK_DIR to C:/VTK/lib/cmake/vtk-6.1 3. Click again on Configure and then click Generate. 4. Open the Code::Blocks project created into the project folder. 5. Select the Build target curve-static corresponding to the example program. 6. Run the compilation. 7. Execute the example program. The executable example shows a Lagrange curve on the screen. Control points of this curve are aligned with each other. There are different ways of interactions with the graphical interface: Mouse: Left button: rotates the camera. Scroll wheel: zoom. Left click on a control point: move the control point. Keyboard: r: replace the camera at its default position. q: close the window. 12

Homework When writing codes, humans are error prone. Luckily, the compiler can catch most of these errors and tells humans where they are wrong. It is therefore important to understand the compiler messages. The following pieces of code contain errors. Try to detect and correct them with the help of the compiler. Warning: some errors will NOT be detected by the compiler. #include <iostream> int main() int a = 3; std::cout << A << std::endl; return 0; #include <iostream> int main() int a = 3 std::cout << a << std::endl; return 0; #include <iostream> int main() double x = 2; std::cout << "Square of x = " << sqr(x) << std::endl; return 0; double sqr(double a) return (a*a); #include <iostream> // No compilation error here, but the answer is wrong. // Can you guess why? int main() double x = 10e38+1000-10e38; std::cout << x << std::endl; return 0; #include <iostream> #include <vector> int main() // Segmentation fault* at the execution here. Why? //* Means out of memory access. std::vector<double> a; a[0] = 9.0; std::cout << a[0] << std::endl; return 0; 13

Main primitive types in C/C++ Type Description Typical bit width Typical range char character 1 byte -127 to 127 unsigned char unsigned character 1 byte 0 to 255 int integer 4 bytes -2,147,483,648 to 2,147,483,647 unsigned int unsigned integer 4 bytes 0 to 4,294,967,295 short int short integer 2 bytes -32,768 to 32,767 unsigned short int unsigned short integer 2 bytes 0 to 65,535 long int (64 bits systems only) unsigned long int (64 bits systems only) long integer 4 bytes 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 unsigned long integer 4 bytes 0 to 18,446,744,073,709,551,615 float floating number 4 bytes +/- 3.4 x 10 +/- 38 (~7 digits) double void double precision number empty or undefined(!) type 8 bytes +/- 1.7x 10 +/- 308 (~15 digits) not applicable How to navigate the STL: C++ Reference not applicable The web site C++ Reference (http://www.cplusplus.com/reference/, or just type C++ Reference in Google) is a comprehensive listing of all the C and C++ standard functions and classes. If you wonder how to use a given function or class, you can just look for it in this website. For example, by typing vector into the search field at the top of the page, you can see that the class vector<any_type> owns a function returning its size. We strongly recommend you to first refer to this web site when you have questions like Does that function exist? or What does that function? Moreover, this website shows numerous and easy to understand example of how using a given function/class. Where to learn more about C++? The website openclassroom (former site du zero ) provides extensive lessons for a lot of programming languages and is very well suited for beginners. See https://openclassrooms.com/courses/programmez-avec-le-langage-c for more information. 14