Manual/ro

From FreeCAD Documentation
Revision as of 09:30, 9 October 2018 by Luc (talk | contribs)

Aceasta est o primă schiță de Manual de FreeCAD în limba română.

Cuprinde părțile esențiale Pagina principală a documentației wiki (Legăturile în roșu nu sunt valide). Aici est pagina principală a Help on-line. Acest manual este special destinat printării ca o carte. Conținutul poate să se schimbe, urmând mersul modificărilor aduse de către contributori pe wiki (Aceste pagini nu au link-uri directe).

Sunt mai multe părți deja traduse în limba română, pentru început amintim Tutorialele

revenim la schița de Manual

Un salt de pagină este prevăzut după fiecare rubrică. Mascați sau nu Cuprinsul, înainte de printare puteți verifica afișarea prin "Previzualizare".





Manuale de Ateliere

Instalarea

Instalarea sub Windows


Feature list
Install on Linux

Standard Installation

The easiest way to install the latest stable version of FreeCAD is to use the installer, see the Download page.

Daca doriți sa descărcați versiunea pe 64 de biți sau versiunea aflată acum în dezvoltare (care ar putea fi instabilă) vizitați pagina de descărcări.

Dupa ce fișierul .msi (Microsoft Installer) a fost descarcat, doar faceți dublu-click pe el pentru a începe instalarea.

Mai jos sunt descrise opțiunile de instalare. Daca pare complicat nu va ingrijorați! Cei mai mulți utilizatori nu vor avea nevoie de nimic mai mult decat fișierul de mai sus .msi și articolul Primii pasi!

Installation for all users of the Windows system

By default FreeCAD will be installed for the user that executes the installer. If this user only has user permissions, the default installation path is:

C:\Users\<username>\AppData\Local\Programs\FreeCAD X.YY

If the installer is executed by an admin user, or you execute it as admin, you can choose if FreeCAD should be installed for all users of the system or just for you. The default is for all users.

If installed for all users, the default installation path is:

C:\Program Files\FreeCAD X.YY

Silent Installation

To install FreeCAD silently, you can execute the installer from the command line:

FreeCAD-~.exe /S

Default settings will be used for all options. A custom installation path can be specified in this manner:

FreeCAD-~.exe /S /D=A path to FreeCAD with spaces

By default, even with silent installations, there will be a short popup when the installer is checked for corruption. This so-called cyclic redundancy check only takes a few seconds at most. To disable this corruption check:

FreeCAD-~.exe /S /NCRC

Note that this /NCRC flag is not recommended since the corruption check assures that the installer was e.g. completely downloaded.

Chocolatey

Using the Chocolatey package manager is currently not recommended as that repository is no longer kept up-to-date.

Dezinstalarea

Folosind

To uninstall FreeCAD it is preferable to use the Windows tools for uninstalling software. Alternatively you can execute the uninstaller directly. This is the file:

Uninstall-FreeCAD.exe

You can find it in the folder where FreeCAD is installed.

The uninstaller can also be executed silently using the command line:

Uninstall-FreeCAD.exe /S

Note that (silent) uninstallation will fail if there is a running instance of FreeCAD, even if that instance is not the version being uninstalled.


Feature list
Install on Linux

Instalarea sub Unix/Linux


Overview

The installation of FreeCAD on most well-known Linux systems is endorsed by the community, and FreeCAD is available via the package manager on those systems. The FreeCAD team also provides some:

Ubuntu and Ubuntu-based systems

Many Linux distributions are based on Ubuntu and share its repositories. Besides official variants (Kubuntu, Lubuntu and Xubuntu), there are non official derivatives like Linux Mint, Voyager and others. The installation options below (Expand) should be compatible with these systems.

Official version

FreeCAD is available from the Ubuntu Universe repository, and can be installed via the Software Center or from the terminal:

sudo apt install freecad

Note: the Ubuntu Universe package may be outdated as the packaging may lag behind the latest stable source code. In this case, it is suggested to install the package from the -stable PPA below. In addition, installing the -daily package can be done to test the development branch.

Stable PPA version

Warning: The FreeCAD PPA is currently unmaintained and looking for volunteers. Please use an alternative (snap, appimage) until the issue is fixed!

Personal Package Archive (PPA) for the stable FreeCAD release is maintained by the FreeCAD community on Launchpad. The Launchpad repository is called FreeCAD Stable Releases .

GUI

Install the stable PPA via the Graphical User Interface (GUI):

1. Navigate to Ubuntu Software → Software & Updates → Software Sources → Other Software
2. Click on Add, then copy and paste the following line
ppa:freecad-maintainers/freecad-stable
3. Add the source, close the dialog, and reload your software sources, if asked.

Now you can find and install the last stable FreeCAD version from the Ubuntu Software Center.

CLI

Install the stable PPA via the Command Line Interface (CLI):

1. Add the PPA to your software sources:
sudo add-apt-repository ppa:freecad-maintainers/freecad-stable
2. Retrieve the updated package lists:
sudo apt update
3. Then install FreeCAD along with its offline documentation:
sudo apt install freecad freecad-doc

Note: due to packaging problems, in certain versions of Ubuntu the freecad-doc package has collided with the installation of FreeCAD or one of its dependencies; if this is the case, remove the freecad-doc package, and only install the freecad package. If the freecad-doc package doesn't exist, then ignore it.

Checking Installation

4. Once you have the stable PPA added to your sources using one of the above methods, the freecad package will install this PPA version over the one provided by the Ubuntu Universe repository. You can see the available versions with the following apt-cache command:
apt-cache policy freecad
The output should look similar to the following (of course the version info will vary):
freecad:
  Installed: (none)
  Candidate: 2:0.18.4+dfsg1~201911060029~ubuntu18.04.1
  Version table:
     2:0.18.4+dfsg1~201911060029~ubuntu18.04.1 500
        500 http://ppa.launchpad.net/freecad-maintainers/freecad-stable/ubuntu bionic/main amd64 Packages
     0.16.6712+dfsg1-1ubuntu2 500
        500 http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
ubuntu@ubuntu:~$ apt-cache policy freecad-doc
5. Invoke the stable (PPA) version of FreeCAD from the GUI or CLI. The latter method is as follows:
./freecad

Development PPA (Daily)

As FreeCAD is in constant development, you may wish to install the daily package to keep with the latest improvements and bug fixes. The repository is also hosted on Launchpad and is called freecad-daily.

This version is compiled daily from the official master repository. Please beware that although it will contain new features and bug fixes, it may also have newer bugs, and be unstable.

Add the daily PPA to your software sources, update the package lists, and install the daily package:

sudo add-apt-repository ppa:freecad-maintainers/freecad-daily
sudo apt-get update
sudo apt-get install freecad-daily

Every day you can update to the latest daily:

sudo apt-get update
sudo apt-get install freecad-daily

Note: in some cases new code or dependencies added to FreeCAD will cause packaging errors; if this happens, a daily package may not be generated until the maintainers manually fix the problems. If you wish to continue testing the latest code, you should get the source code and compile FreeCAD directly; for instructions see compiling.

Run the daily (PPA) version of FreeCAD:

freecad-daily

Note: it is possible to install both the -stable and -daily packages in the same system. This is useful if you wish to work with a stable version, and still be able to test the latest features in development. Notice that the executable for the daily version is freecad-daily, but for the stable version it is just freecad.

Debian and other Debian-based systems

Since Debian Lenny, FreeCAD is available directly from the Debian software repositories and can be installed via synaptic or simply with:

sudo apt-get install freecad

OpenSUSE

FreeCAD is typically installed with YAST (abbr. Yet another Setup Tool) the Linux operating system setup and configuration tool, or in any terminal/console (root rights required) with:

zypper install FreeCAD

Note: This procedure only covers the installation of officially released stable FreeCAD program versions, depending on the installed links to the program package repositories of your OS version. The openSUSE package may be outdated as the packaging may lag behind the latest stable source code. In this case, it is suggested to install the package manually from the below indicated (Expand) source repositories.

A vast release program for FreeCAD package builds are offered. Please visit for a survey:

Survey of repositories on openSUSE

Generally for selecting the correct openSUSE distribution needed it is necessary to click on the particular View button.

Stable

The stable package version: Stable repositories on openSUSE. The correct openSUSE distribution version must be selected in the lower part of the web page.

Note: openSUSE has several options to choose from when downloading FreeCAD. To view these options, visit Survey of stable repositories on openSUSE.

Development

Latest development releases AKA unstable: Unstable repositories listings on openSUSE

It is recommended to grab the binary packages directly. Then select the correct distribution for your installed openSUSE OS.

Gentoo

FreeCAD can be built/installed simply by issuing:

emerge freecad

Fedora

FreeCAD has been included in the official Fedora packages since Fedora 20. It can be installed from the command line with:

sudo dnf install freecad

On older Fedora releases, that was:

sudo yum install freecad

The gui packages managers can also be used. Search for "freecad". The official release package version tends to be well behind the FreeCAD releases. Package: freecad shows the versions included in the Fedora repositories over time and versions.

More current versions can be obtained by downloading one of the .AppImagereleases from the github repository. These work fine on Fedora.

If you want to keep up with the absolute latest daily builds, FreeCAD is also available on copr. To install the build from there, in a terminal session, enter:

sudo dnf copr enable @freecad/nightly
sudo dnf install freecad

That leaves the copr repository active, so

sudo dnf upgrade

or equivalent, will update to the latest FreeCAD build, along with updates from any of the other active repos. If you want something a bit more stable, you can disable @freecad/nightly again after the initial install. The copr repository only keeps builds from the past 2 weeks. This is not a solution if you want to pick a specific older version.

Instructions are also available on compile FreeCAD yourself, including a script specifically for Fedora. With a minor change, to checkout the specific commit from git, any version since about FreeCAD 0.15 can be built on any distribution since Fedora 21.

Arch

Installing FreeCAD on Arch Linux and derivatives (ex. Manjaro):

pacman -S freecad

Other

If you find out that your system features FreeCAD but is not documented in this page, please tell us on the forum!

Many alternative, non-official FreeCAD packages are available on the net, for example for systems like slackware or fedora. A search on the net can quickly give you some results.

Installing on other Linux/Unix systems

Many common Linux distros now include a precompiled FreeCAD as part of the standard packages. This is often out of date, but is a place to start. Check the standard package managers for your system. One of the following (partial) list of commands could install the official version of FreeCAD for your distro from the terminal. These probably need administrator privileges.

apt-get install freecad
dnf install freecad
emerge freecad
slackpkg install freecad
yum install freecad
zypper install freecad
pacman -Sy freecad

The package name is case sensitive, so try `FreeCAD` as well as `freecad`. If that does not work for you, either because your package manager does not have a precompiled FreeCAD version available, or because the available version is too old for your needs, you can try installing the Flatpak or Snap packages (these work on most x86_64 Linux distributions) or try downloading one of the .AppImage releases from the github repository. These also tend to work on most x86_64 Linux distributions, without any special installation. Just make sure the downloaded file is marked as executable, then run it.

If that still is not good enough, and you cannot locate another source of a precompiled package for your situation, you will need to compile FreeCAD yourself.

Next Step

Head to Getting started once installation is complete.


Instalarea sub Mac


FreeCAD poate fi instalat in Mac OS X intr-un singur pas folosind programul de instalare.

If you would like to download a development version, which may be unstable, see the Weekly builds download page.

You can also use a package manager such as HomeBrew to keep your software updated. Instructions to install HomeBrew can be seen here. When HomeBrew installed you can simply install FreeCAD through your bash terminal with

brew install --cask freecad

and to use the latest version available on HomeBrew you may run

brew install freecad

If there are any issues with the HomeBrew Cask or Formula you may report them to here.

Această pagină descrie utilizarea și caracteristicile instalatorului FreeCAD. De asemenea, include instrucțiuni de dezinstalare. După ce ați instalat, puteți get started!

Instalarea simpla

Programul de instalare FreeCAD este furnizat ca pachet app (.app) inclus în fișierul imagine

a disk ului.

The FreeCAD installer is provided as a app package (.app) enclosed in a disk image file.

Cea mai recenta versiune se poate descarca din pagina de Download. Odata descarcat fisierul imagine al disk ului, apoi glisați-l în Application folder sau orice alt folder doriți

Et voila! Faceți doar click pe app pentru a lansa FreeCAD. Dacă întâlniți acest mesaj "FreeCAD can't be open as it is from unidentified developer. " Deschideți folderul (Application) și click dreapta pe app apoi click deschideți și acceptați deschiderea applicației.

Dezinstalarea

Încă nu există un program de dezinstalare pentru FreeCAD. Pentru a înlătura complet programul și toate componentele instalate trageți următoarele fișiere și directoare în coșul de Gunoi:

  • In /Applications:
    • FreeCAD

Asta-i tot.


Install on Unix/ro
Getting started/ro

Introducere în FreeCAD


Cuvânt înainte

FreeCAD este o aplicaţie parametrică de modelare CAD/CAE. A fost creată în principal pentru desen tehnic, dar de asemenea serveşte tuturor nevoilor de modelare a unor obiecte 3D, cu precizie maximă şi control asupra etapelor de modelare.

FreeCAD se află încă în stadii incipiente de dezvoltare, și oferă o listă largă (și în dezvoltare) de features. Unele capabilități lipsesc încă comparativ cu soluțiile comerciale și le puteți găsi insuficient dezvoltate pentru a le utiliza în mediul industrial. Cu toate acestea, există o comunitate de utilizatori etuziaști community , și puteți găsi deja many examples de proiecte de calitate dezvoltate cu FreeCAD.

Ca toate proiectele open source, proiectul FreeCAD nu este doar o modalitate de a lucra pentru dezvoltatorii săi. Depinde mult de comunitatea sa să crească, să câștige experiență și să se stabilizeze (să se fixeze bug-urile). Nu uitați acest lucru când începeți să utilizați FreeCAD, dacă vă place, puteți influența direct proiectul help!

See also:

Instalare

Mai întâi de toate, descărcați și instalați FreeCAD. Consultați pagina Download pentru informații despre versiunile și actualizările curente și pagina Installing pentru instrucțiuni de instalare. Există pachete de instalare gata pentru Windows (.msi), Debian și Ubuntu (.deb), openSUSE (.rpm) și Mac OSX. FreeCAD este disponibil la administratorii pachetelor de la mai multe distribuții Linux. Este disponibil și un executabil standalone AppImage, care va funcționa pe cele mai recente sisteme Linux pe 64 de biți. Deoarece FreeCAD este open-source, poți descărca și codul sursă și compila pe tine însuți.

Explorarea aplicației FreeCAD

  1. Vederea 3D, afișează conținutul documentului
  2. Vizualizarea arborescentă, care prezintă ierarhia și istoricul construcțiilor tuturor obiectelor din document
  3. properties editor, care vă permite să vizualizați și să modificați proprietățile obiectelor selectate,
  4. Vizualizarea raportului (sau fereastra de ieșire), în care FreeCAD imprimă mesaje, avertismente și erori
  5. Consola python, în care sunt tipărite toate comenzile executate de FreeCAD și unde puteți introduce codul python
  6. workbench selector, unde selectați atelierul de lucru activ

Conceptul principal din spatele interfeței FreeCAD este că este separat în ateliere. Un Atelier de lucru este o colecție de instrumente pentru o anumită sarcină, cum ar fi plase/rețele de discretizare meshes, sau desen 2D objects, sau constrained sketches. Puteți schimba atelierul de lucru curent cu selectorul de bibliotecă de lucru (6). Poți customize Instrumentele incluse în fiecare atelier de lucru, adăugați unelte de la alte ateliere de lucru sau chiar unelte create de noi, pe care le numim macros. Punctele de pornire utilizate pe scară largă sunt PartDesign Workbench and Part Workbench.

Când porniți FreeCAD pentru prima dată, vi se prezintă centrul de pornire. Iată cum arată acesta pentru versiunea 0.16

Pagina de Start vă permite să vă îndreptaţi rapid către unul atelierele obişnuite, să deschideţi fişierele folosite recent sau să citiţi cele mai noi ştiri din lumea FreeCAD. Puteţi schimba atelierul implicit cu opţiunea Preferinţe din meniul "Editare".

Navigarea în spatiul 3D

FreeCAD vă oferă mai multe moduri de navigare cu mouse-ul diferite, ceea ce schimbă felul în care mouse-ul Dvs. interacţionează cu obiectele reprezentate 3D şi cu însuşi felul de vizualizare. Unul dintre ele este făcut anume pentru touchpads, unde nu se foloseşte butonul din mijloc. Următorul tabel descrie modul implicit, numit Navigare CAD (puteţi schimba rapid modul de navigare curent prin clic cu butonul drept pe un o porţiune goală din spaţiul 3D):

Exista moduri de vizualizare predefinite (de sus, din fata, etc) ce se schimba folosind meniul Vizualizare, comenzile din bara de unelte Vizualizare sau scurtaturile numerice (1, 2, etc...) . Făcând clic dreapta pe un obiect sau pe o zonă goală a vizualizării 3D, aveți acces rapid la unele operații comune, cum ar fi setarea unei anumite vizualizări sau localizarea unui obiect în vizualizarea tip Arbore.

Primii paşi în FreeCAD

Aplicația FreeCAD este de a vă permite să realizați modele 3D de înaltă precizie, să păstrați controlul strict al acestor modele (să reveniți la istoricul de modelare și să modificați parametrii) și să construiți aceste modele (prin imprimare 3D, prelucrare CNC sau chiar în construcții civile). Prin urmare, este foarte diferit de alte aplicații 3D realizate în alte scopuri, cum ar fi filmul de animație sau jocurile de noroc. Curba de învățare poate fi abruptă, mai ales dacă acesta este primul dvs. contact cu modelarea 3D. Dacă vă înpotmoliți într-un anumit moment, nu uitați că există o comunitate prietenoasă a utilizatorilor de pe forumul FreeCAD care ar putea să vă aducă în cel mai scurt timp pe linia de plutire.

Atelierul pe care îl veți utiliza în FreeCAD depinde de tipul de lucru pe care trebuie să-l faceți: Dacă intenționați să lucrați pe modele mecanice sau, mai general, la orice obiecte la scară redusă, probabil veți dori să încercați PartDesign Workbench. Dacă veți lucra în 2D, atunci veți comuta pe Draft Workbench, sau pe Sketcher Workbench dacă aveți nevoie de constrângeri. Dacă veți dori să faceți construcții civile, atunci lansați Arch Workbench. Dacă lucrați cu proiectarea navelor , există un atelier specializat pentru dvs Ship Workbench. Iar dacă veniți din lumea OpenSCAD, încercați atelierul OpenSCAD Workbench..

Puteți comuta atelirele în orice moment, și de asemenea customize atelierul favorit pentru a adăuga scule de la alte atelire.

Folosirea panourilor Proiectare componente (PartDesign) şi Schiţă

Atelierul PartDesign Workbench a fost creat special pentru a făuri obiecte complexe, pornind de la forme simple, prin adăugarea sau înlăturarea unor piese (pe care le numim "funcţii"), până la obţinerea obiectului în final. Toate funcţiile aplicate pe parcursul procesului de modelare sunt păstrate într-o mică fereastră numită Vizualizare Combo, care conţine şi celelalte obiecte din documentul Dvs. Practic, un obiect realizat cu "Proiectare componente" reprezintă o succesiune de operaţii, fiecare aplicată la lucrul produs în faza precedentă, astfel încât ele formează un lanţ prelung. În "Vizualizare Combo", vedeţi obiectul finalizat, dar el poate fi expandat astfel încât să-i regăsiţi toate stările precedente, să le modificaţi parametrii, schimbări care vor actualiza în mod automat aspectul final al obiectului.

Atelierul PartDesign utilizează intens un alt atelier de lucru, Sketcher Workbench. vă permite să desenați figuri 2D, care sunt definite prin aplicarea Constrângerilor la forma 2D. De exemplu, puteți trage un dreptunghi și puteți seta dimensiunea unei părți aplicând o constrângere de lungime pe una din laturi. Această parte nu mai poate fi redimensionată (cu excepția cazului în care constrângerea este modificată).

Aceste forme 2D realizate cu sketcher-ul sunt folosite foarte mult în bara de lucru PartDesign, de exemplu pentru a crea volume 3D sau pentru a desena zone pe fețele obiectului dvs. care vor fi apoi scoase din volumul principal. Acesta este un flux de lucru tipic PartDesign:

  1. Creați o schiță nouă
  2. Desenați o formă închisă (asigurați-vă că toate punctele sunt legate)
  3. Închideți schița
  4. Extindeți schița într-un solid 3D utilizând instrumentul de blocare
  5. Selectați o față a solidului
  6. Creați o a doua schiță (de data aceasta va fi desenată pe fața selectată)
  7. Desenați o formă închisă
  8. Închideți schița
  9. Creați un buzunar din a doua schiță, pe primul obiect

Care vă dă un obiect ca acesta:

În orice moment, puteți selecta schițele originale și le puteți modifica sau puteți schimba parametrii de extrudare ai operațiilor de blocare sau buzunar, care vor actualiza obiectul final.

Lucrând cu atelierele Desen 2D și Arhitectură

Atelierele Draft Workbench și Arch Workbench se comporta un pic diferit fata de celelalte ateliere de mai sus, deși urmează aceleași reguli, care sunt comune tuturor FreeCAD-urilor. Pe scurt, în timp ce Sketcher și PartDesign sunt create în primul rând pentru a proiecta piese unice, Draft și Arch sunt făcute pentru a vă ușura munca atunci când lucrați cu mai multe obiecte mai simple.

Atelierul Draft Workbench vă oferă instrumente 2D cumva similare cu ceea ce puteți găsi în aplicațiile tradiționale 2D CAD cum ar fiAutoCAD. Totuși, desenarea 2D fiind departe de domeniul FreeCAD, nu vă așteptați să găsiți acolo o gamă completă de instrumente care oferă aceste aplicații dedicate. Majoritatea instrumentelor de proiectare funcționează nu numai într-un plan 2D, ci și în întreg spațiul 3D și beneficiază de sisteme speciale de ajutor, cum ar fi Work planes și object snapping.

Atelierul Arch Workbench adaugă BIM tools to FreeCAD, permițându-vă să construiți modele arhitecturale cu obiecte parametrice. Baza de lucru Arch se bazează extensiv pe alte module cum ar fi Draft și Sketcher. Toate instrumentele de proiectare sunt de asemenea prezente în Atelierul de lucru Arch și majoritatea instrumentelor Arch utilizează sistemele Helper desen 2D (Draft).

Un flux de lucru tipic cu atelierele de lucru Arch și Draft ar putea fi:

  1. Desenați câteva linii cu ajutorul instrumentului Draft Line
  2. Selectați fiecare linie și apăsați instrumentul Perete pentru a construi un perete pe fiecare dintre ele
  3. Alăturați pereții selectând-i și apăsând instrumentul Arch Add
  4. Creați un obiect tip pardoseală și mutați pereții în el din vizualizarea Arbore
  5. Creați un obiect construit și mutați podeaua în el din vizualizarea Arbore
  6. Creați o fereastră făcând clic pe instrumentul Fereastră, selectați o presetare în panoul său, apoi faceți clic pe o față a unui perete
  7. Adăugați cotele prin setarea inițială a planului de lucru, dacă este necesar, apoi utilizând instrumentul Draft Dimension

Ceea ce vă va aduce asta:

Mai mult în pagina Tutorials.

Script

Any user can develop their own new features for FreeCAD and make them available to the FreeCAD community as an addon.

There are three types of addons:

  • Macros: short snippet of Python code that provides a new tool or functionality in a single file ending with .FCMacro.
  • Workbenches: collections of Python files that provide related Gui Commands (tools) centered around a particular topic.
  • Preference Packs: distributable collections of user preferences.

Scripting

Iar, la sfârşit, să remarcăm că una dintre cele mai puternice caracteristici ale FreeCAD este mediul creat de script-programare. De la consola integrata Python (sau oricare alt script extern Python) se poate controla aproape orice parte a programului, se pot crea si modifica geometrii, se poate modifica reprezentarea obiectelor in scena 3D sau accesa si modifica interfata FreeCAD. Script-urile Python pot fi folosite si in macroinstructiuni, ceea ce furnizeaza o metoda usoara de creare a comenzilor personalizate.

Ce e nou


Install on Mac/ro
Mouse Model/ro

Lucrul cu FreeCAD

Navigarea 3D


Overview

Modelul mouse-ului in FreeCAD este constituit din comenzi folosite la navigarea spațiului 3D și interacțiunea cu obiectele afișate. In versiunea actuală există trei moduri diferite de navigare. Modul implicit este numit "Navigare CAD" și este foarte simplu și practic, dar FreeCAD are două stiluri alternative modelate dupa navigarea în Inventor si Blender.

For more information about selecting objects see Selection methods.

For more information about manipulating objects see Std TransformManip.

Selecting a navigation style

  • In dialogul pentru preferinte, secțiunea Afișare, tab-ul Vizualizare 3D;
  • Click-dreapta în spațiul liber în zona de vizualizare 3D, selectând Stil de navigare în meniul contextual.

Available navigation styles

With all navigation styles, unless selecting objects from a sketch in edit mode, you must hold Ctrl to select multiple objects.

Navigare Tip Blender

The Blender navigation style was modeled after Blender.

Blender Navigation a fost modelat după Blender. Anterior nu a existat o panoramare cu mouse-ul și a fost necesară utilizarea tastei SHIFT pentru a panorama vederea. Acest lucru s-a schimbat în 2016, cu o adăugare de caracteristici. Pentru a panorama vizualizarea, puteți apăsa acum butoanele mouse-ului stânga și dreapta și trageți în vizualizare.

Select Pan Zoom Rotate view
Shift+
Press the left mouse button over an object you want to select. Hold Shift and the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, and then move the pointer.

Use the mouse wheel to zoom in and out. Hold the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, and then move the pointer. |Zoom_text=Use the mouse wheel to zoom in and out. |Rotate_view_text=Hold the middle mouse button, then move the pointer. }}

CAD navigation

Navigare CAD (implicita)

Acesta este modul de navigare implicit și permite utilizatorului un control simplu al vizualizării; nu este nevoie de folosirea tastaturii decât pentru selecție multiplă.

Selectare Translatie Zoom Rotire
pentru selectie pentru translatie pentru a mari sau micsora pentru a roti vizualizarea
Apasati butonul stanga al mouse-ului deasupra obiectului de selectat. Apasarea tastei CTRL permite selectarea mai multor obiecte. Apasati butonul din mijloc si miscati mouse-ul pentru a translata vizualizarea. Folositi rotita mouse-ului pentru a mari sau micsora. Apasati mai intai butonul din mijloc al mouse-ului, tineti-l apasat si apasati butonul stanga al mouse-ului si mutati-l in directia dorita. Functioneaza ca o bila ce se roteste in jurul centrului. Daca eliberati butoanele inainte de a inceta miscarea vizualizarea va continua sa se roteascain jurul centrului, daca aceasta caracteristica e activata. Dublu-click folosind butonul mijlociu pe oricare parte a unui obiect seteaza noul centru de rotatie si panorameaza pe acest punct.


Select Pan Zoom Rotate view
First method
Rotate view
Alternate method
Press the left mouse button over an object you want to select.

Holding down Ctrl allows the selection of multiple objects.

Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Clicking the middle mouse button re-centers the view on the location of the cursor.

Hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

The cursor location when the middle mouse button is pressed determines the center of rotation. Rotation works like spinning a ball which rotates around its center. If the buttons are released before you stop the mouse motion, the view continues spinning, if this is enabled.

A double click with the middle mouse button sets a new center of rotation.

Hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

With this method the middle mouse button may be released after the right mouse button is held pressed.

Users who use the mouse with their right hand may find this method easier than the first method.

Ctrl+ Ctrl+Shift+ Shift+
Pan mode: hold the Ctrl key, press the right mouse button once, then move the pointer. introduced in version 0.17 Zoom mode: hold the Ctrl and Shift keys, press the right mouse button once, then move the pointer. introduced in version 0.17 Rotate mode: hold the Shift key, press the right mouse button once, then move the pointer. introduced in version 0.17
Select Pan Zoom Rotate view
First method
Rotate view
Alternate method
Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Clicking the middle mouse button re-centers the view on the location of the cursor.

Hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

If the buttons are released before you stop the mouse motion, the view continues spinning, if this is enabled.

A double click with the middle mouse button sets a new center of rotation.

Hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

With this method the middle mouse button may be released after the right mouse button is held pressed.

Users who use the mouse with their right hand may find this method easier than the first method.

Ctrl+ Ctrl+Shift+ Shift+
Pan mode: hold the Ctrl key, press the right mouse button once, then move the pointer. Zoom mode: hold the Ctrl and Shift keys, press the right mouse button once, then move the pointer. Rotate mode: hold the Shift key, press the right mouse button once, then move the pointer.

Navigarea prin Gesturi(v0.16)

This style was tailored for use with a touchscreen and pen. Nevertheless, it can also be used with a mouse, and is recommended for use when using a Mac with a trackpad.

Acest stil de navigare a fost adaptat pentru utilizarea cu touchscreen și stiloul, dar este foarte ușor de utilizat cu mouse-ul.

Select Pan Zoom Rotate view Tilt view
Press the left mouse button over an object you want to select. Hold the right mouse button, then move the pointer. Use the mouse wheel to zoom in and out. Hold the left mouse button, then move the pointer.

In Sketcher and other edit modes, this behavior is disabled. Hold Alt when pressing the mouse button to enter rotation mode.

To set the camera's focus point for rotation, click a point with the middle mouse button. Alternatively, aim the cursor at a point and press H on the keyboard.

Hold both left and right mouse buttons, and then move the pointer sideways.
Tap to select. Drag with two fingers.

Alternatively, tap and hold, then drag. This simulates the pan with the right mouse button.

Drag two fingers (pinch) closer or farther apart. Drag with one finger to rotate.

Hold Alt when in the Sketcher.

Rotate the imaginary line formed by two touch points.

On v0.18 this method is disabled by default. To enable, go to Edit → Preferences → Display, and untick "Disable touchscreen tilt gesture" checkbox.

Alternatively, tap and hold, then drag. This simulates the pan with the right mouse button. |Zoom_text=Use the mouse wheel to zoom in and out. |Zoom_gesture_text=Drag two fingers (pinch) closer or farther apart. |Rotate_view_text=Hold the left mouse button, then move the pointer. In Sketcher and other edit modes, this behavior is disabled. Hold Alt when pressing the mouse button to enter rotation mode.

To set the camera's focus point for rotation, click a point with the middle mouse button. Alternatively, aim the cursor at a point and press H on the keyboard. |Rotate_view_gesture_text=Drag with one finger to rotate.

Hold Alt when in the Sketcher. |Tilt_view_text=Hold both left and right mouse buttons, then move the pointer sideways. |Tilt_view_gesture_text=Rotate the imaginary line formed by two touch points.

This method is disabled by default. To enable, go to Edit → Preferences → Display → Navigation, and uncheck the "Disable touchscreen tilt gesture" checkbox. }}

Navigare tip Maya

In Maya-Gesture Navigation, panning, zooming, and rotating the view require the Alt key together with a mouse button; therefore, a three-button mouse is required. It's also possible to use gestures as this style was developed over the Gesture navigation style.

În navigația Maya-Gesture, toate mișcările de vizualizare sunt activate prin apăsarea butonului ALT și a butonului mouse-ului, astfel încât să fie necesar un mouse cu 3 butoane pentru a utiliza corect acest mod de navigare. Alternativ, este posibil să utilizați gesturi, deoarece acest mod a fost dezvoltat în modul normal de navigare prin gesturi.

Select Pan Zoom Rotate view
Alt+ Alt+ Alt+
Press the left mouse button over an object you want to select. Hold Alt and the middle mouse button, then move the pointer. Hold Alt and the right mouse button, then move the pointer.

Alternatively, use the mouse wheel to zoom in and out.

Hold Alt and the left mouse button, then move the pointer.

Alternatively, use the mouse wheel to zoom in and out. |Rotate_view_text=Hold Alt and the left mouse button, then move the pointer. }}

OpenCascade navigation

The OpenCascade navigation style was modeled after OpenCascade.

Select Pan Zoom Rotate view
Ctrl+ Ctrl+ Ctrl+


Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Alternatively, hold Ctrl and the left mouse button, then move the pointer.

Hold Ctrl and the right mouse button, then move the pointer.

OpenInventor navigation

Navigare Tip Inventor

In acest tip de navigare modelată după Open Inventor (a nu se confunda cu Autodesk Inventor) nu exista selectie cu mouse-ul. Pentru selectare trebuie apasată tasta CTRL.

Selectare Translatie Zoom Rotire
ctrl +pentru selectare pentru translatie pentru marire sau micsorare sau pentru marire sau micsorare pentru a roti
Tineti CTRL apasat si apasati butonul stanga al mouse-ului deasupra unui obiect ce doriti sa fie selectat. Faceti click cu butonul stanga al mouse-ului si miscati obiectul. Folositi rotita mouse-ului pentru marire si micsorare sau apasati si tinei butonul din mijloc si apasati butonul din stnga. Faceti click si trageti folosind butonul stanga al mouse-ului pentru a roti


Select Pan Zoom Rotate view
{{{Shift}}}+
Hold Ctrl, then press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Alternatively, hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

Hold the left mouse button, then move the pointer.

This style is not based on Autodesk Inventor.

Select Pan Zoom Rotate view
Shift+
Hold Shift, then press the left mouse button over an object you want to select.

Hold Ctrl instead to select multiple objects.

Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out.

Alternatively, hold the middle mouse button, then press and hold the left mouse button, then move the pointer.

Hold the left mouse button, then move the pointer.

OpenSCAD navigation

The OpenSCAD navigation style was modeled after OpenSCAD.

introduced in version 0.20

Select Pan Zoom Rotate view
Shift+
Press the left mouse button over an object you want to select.

version 0.21 and below Hold Ctrl and Shift when pressing the mouse button to drag an object in a sketch in edit mode.

Hold the right mouse button, then move the pointer. Hold the middle mouse button, then move the pointer.

Alternatively, hold Shift and the right mouse button, then move the pointer.

Hold the left mouse button, then move the pointer.

Alternatively, and when a sketch is in edit mode, hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

Revit navigation

The Revit navigation style was modeled after Revit.

Select Pan Zoom Rotate view
Shift+


Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer.

Alternatively, hold both left and right mouse buttons, then move the pointer.

Use the mouse wheel to zoom in and out. Hold Shift and the middle mouse button, then move the pointer.

Alternatively, hold the middle mouse button, then press and hold the right mouse button, then move the pointer.

TinkerCAD navigation

The TinkerCAD navigation style was modeled after TinkerCAD.

introduced in version 0.20

Select Pan Zoom Rotate view
Press the left mouse button over an object you want to select. Hold the middle mouse button, then move the pointer. Use the mouse wheel to zoom in and out. Press the right mouse button, then move the pointer.

Navigarea cu Touchpad-ul

With the Touchpad navigation style, panning, zooming, and rotating the view require a modifier key together with the touchpad. This style can also be used with a mouse.

În Navigatorul cu touchpad, nici panningul, nici zoom-ul, nici rotirea vizualizării nu sunt operații numai pentru mouse (sau doar touchpad).

Select Pan Zoom Rotate view
Shift+ PageUp, PageDown Alt+
Press the left mouse button over an object you want to select. Hold Shift, then move the pointer. Use PageUp and PageDown to zoom in and out. Hold Alt, then move the pointer.
Ctrl+Shift+ Shift+
Alternatively, hold Shift and Ctrl, then move the pointer. Alternatively, hold Shift and the left button, then move the pointer.

Suport Hardware

FreeCAD suportă și un număr de dispozitive 3D.

Probleme la Mac OS X

Recent am primit rapoarte pe forum de la utilizatorii de Mac la care acele combinații de taste și butoane de mouse nu funcționează conform așteptărilor. Din păcate, niciunul dintre dezvoltatori nu deține un Mac, nici ceilalți contributori obișnuiți. Avem nevoie de ajutorul tău pentru a determina ce butoane și combinații de taste ale mouse-ului funcționează astfel încât să putem actualiza acest

Developing a custom navigation

The tutorial Adding a new mouse navigation option to FreeCAD orients developers who want to develop a custom mouse navigation option. Familiarity with the C++ syntax is required.


Getting started/ro
Document structure/ro

Documentul în FreeCAD


Un document FreeCAD conține toate obiectele din scenă. Poate conține grupuri și obiecte realizate cu oricare atelier.Ca urmare atelierele pot fi schimbate fără a părăsi documentul. Conținutul documentului este cel salvat pe disc. Mai multe documente pot fi deschise în acelasi timp și mai multe vizualizări al aceluiași document pot fi deschise în același timp.

In ineriorul documentului obiectele pot fi mutate in grupuri si au un nume unic. Administrarea obiectelor, a grupurilor de obiecte si a numelor obiectelor se face in primul rand dn vizualizarea arborescenta. Toate acestea pot fi realizate ca orice altceva in FreeCAD, folosind script-uri Python. In vizualizarea arborescenta se pot crea grupuri, muta obiecte in grupuri, sterge obiecte sau grupuri folosind meniul contextual (click dreapta cu mouse-ul). Redenumirea obiectelor se face cu dublu-click pe obiect. Este posibil sa existe si alte actiuni permise in functie de tipul obiectului si paleta curenta.

Obiectele din documentul FreeCAD pot avea diferite tipuri. Fiecare atelier poate crea propriile tipuri de obiecte, de exemplu Atelierul Plase creează obiecte plasă, atelierul |atelierul Piese poate crea piese, Atelierul desen2D poate crea și el piese, etc.

Daca este cel putin un document deschis in FreeCAD, atunci exact un document este activ. Acesta este documentul care apare in vizualizarea 3D curenta, documentul cu care lucrati in mod curent.

Aplicatia si Interfata cu Utilizatorul

Ca orice altceva in FreeCAD, partea de interfața grafică a utilizatorului (GUI) este separată de partea de aplicație (App). Acest lucru este adevărat și pentru documente. Acestea sunt și ele alcătuite din două părți: partea de aplicație, ce conține obiecte, și partea de vizualizare, ce conține reprezentarea grafica a obiectelor.

Gândiți-vă la aceasta arhitectură ca la două spații unde obiectele sunt definite. Parametrii constructivi (este un cub? un con? ce dimensiuni are?) sunt stocați in partea de App, pe când reprezentarea grafică (liniile au culoarea neagră? fațetele sunt albastre?) este stocată în partea GUI. De ce aceasta separare? Pentru că FreeCAD poate fi folosit și without

fără interfața grafică, de exemplu în interiorul altor programe, și trebuie să putem manipula obiectele chiar dacă nimic nu este desenat pe ecran.

O alta parte ce este stocată în partea de grafică sunt vizualizările 3D. Un document poate avea mai multe vizualizări deschise în același timp astfel ca să puteți examina conținutul documentului din mai multe puncte de vedere în același timp. Poate doriți să vedeți în același timp imaginea de sus și din față în același timp? In acest caz trebuie să folosiți două vizualizări stocate în partea grafică ce pot fi create în meniul Vizualizare sau prin click-dreapta pe un tab de vizualizare.

Scripturi

Documentele pot fi ușor create, accesate și modificate de la interpretorul Python . De exemplu:

FreeCAD.ActiveDocument

O sa dea documentul curent

FreeCAD.ActiveDocument.Blob

O sa acceseze un document numit "Blob" inauntrul documentului activ

FreeCADGui.ActiveDocument

O sa dea partea grafica asociata cu documentul activ

FreeCADGui.ActiveDocument.Blob

O sa acceseze partea grafica a obiectului "Blob"

FreeCADGui.ActiveDocument.ActiveView

O sa dea vizualizarea activa


Definirea preferințelor utilizatorului


Introduction

Dialogul de editare a preferintelor se poate activa folosind meniul Edit menu → Preferences.

Functionalitatea FreeCAD este impartita in diverse module, fiecare modul fiind responsabil pentru functionarea unei anumite palete. Aplicatia foloseste o tehnica numita incarcare intarziata, ceea ce inseamna ca incarcarea componentelor are loc doar atuni cand e nevoie efectiv de ele. Poate ati observat ca atunci cand selectati o paleta din bara de unelte, acea paleta si toate componentele asociate cu ea sunt incarcate in acel moment. Aceasta include si preferintele in dialogul de editare.

To preserve resources, FreeCAD does not automatically load all available workbenches. See Workbenches for more information. For a list of workbench related preferences see Workbench related preferences.

Fără nici un modul încărcat veți avea acces la secțiunile de configurare responsabile pentru setări generale ale aplicației și ale afișării.

Dacă faceți clic pe butonul Reset din colțul din stânga jos al oricărui afișaj de preferințe, setați all din preferințele FreeCAD la valorile lor implicite.

Some advanced preferences can only be changed in the Parameter editor. The Fine-tuning page lists some of them.

Preferințe generale

Cand porniți FreeCAD fără nici un atelier încărcat veți avea un numar minim de preferințe de editat. Pe măsura ce încărcați module adiționale, secțiuni noi apar în fereastra de dialog, permițând configurarea parametrilor atelierelor încărcate.

In version 0.21 and below the seventh tab, Help, is only available if the Help Addon has been installed.

General

On the General tab you can specify the following:

Name Description
Language Language of the application's user interface.
Default unit system Unit system for all parts of the application. introduced in version 1.0: Used as the default for the document unit system of new documents.
Number of decimals The number of decimals that should be shown for numbers and dimensions.
Ignore project unit system and use default introduced in version 1.0 If checked, project unit systems are ignored and do not override the default unit system.
Minimum fractional inch The minimum fractional inch that should be shown for numbers and dimensions. Only available for unit systems with fractional inches.
Number format introduced in version 0.20 Specifies the number format. The options are:
  • Operating system: The decimal separator defined by the operating system is used.
  • Selected language: The decimal separator of the selected FreeCAD interface language is used.
  • C/POSIX: A point is used as the decimal separator.
Substitute decimal separator introduced in version 0.20 If checked, the numerical keypad decimal separator will be substituted with the separator defined by the Number format setting. introduced in version 0.21: Notice that if this preference is enabled, using the numerical keypad decimal separator will always print a dot/period in the Python console and the Macro editor.
Theme Specifies a theme to customize the appearance of the user interface.
Size of toolbar icons Specifies the size of the toolbar icons. The options are:
  • Small (16px)
  • Medium (24px)
  • Large (32px)
  • Extra large (48px)
Tree view mode Defines how the tree view is shown in the user interface (restart required). The options are:
  • Combo View: Combines the tree view and the property view into one panel.
  • TreeView and PropertyView: Splits the tree view and the property view into separate panels.
  • Both: Shows all three panels. version 0.21 and below
Size of recent file list Specifies how many files should be listed in the recent files list.

Optionally, imported files can be excluded from this list, and exported files can be included. See Fine-tuning.

Enable tiled background If checked, the background of FreeCAD's main window will by default consist of tiles of this image:

This option only has an effect if no Style sheet is selected.

The image can be changed by adding the folders Gui/Images in the folder:

%APPDATA%/FreeCAD (on Windows),

$HOME/.FreeCAD (on Linux) or

$HOME/Library/Preferences/FreeCAD (on macOS).

Place a file named background.png in the Images folder, and uncheck/check this option to see the changed file.

Enable splash screen at start up If checked, a splash screen is shown when starting FreeCAD.

The splash screen image can be changed by placing a file named splash_image.png in the Images folder already mentioned under Enable tiled background.

Enable cursor blinking If checked the text cursor in the Python console and the Macro editor will blink.
Activate overlay handling introduced in version 1.0 If checked, docked windows can be handled as transparent overlays.
Preference packs introduced in version 0.20 Lists the available preference packs and also allows you to import, save, manage and revert them.

Document

On the Document tab you can specify the following:

Name Description
Create new document at start up If checked, FreeCAD will create a new document when started.
Document save compression level Specifies the compression level for FCStd files. FCStd files are ZIP-compressed files. Therefore you can rename their suffix .FCStd to .zip and open them with a ZIP archive program.
Using Undo/Redo on documents If checked, all changes in documents are stored so that they can be undone/redone.
Maximum Undo/Redo steps Specifies how many Undo/Redo steps should be recorded.
Allow aborting recomputation If checked, recomputations can be aborted by pressing Esc. This may slightly increase the recomputation time.
Run AutoRecovery at startup If there is a recovery file available FreeCAD will automatically run a file recovery when it is started. This way files can be restored if a crash occurred.
Save AutoRecovery information every Specifies how often a recovery file is written.
Save thumbnail into project file when saving document If checked, a thumbnail will be stored when the document is saved. The thumbnail will for example be shown in the list of recent files in the Start Workbench. It is possible to select a Size between 128×128 and 512×512 pixels for the thumbnail. Common sizes are powers of two: 128, 256, 512.
Add the program logo to the generated thumbnail If checked, the FreeCAD program logo will be added to the thumbnail.
Maximum number of backup files to keep when resaving document If checked, backup files will be kept when saving the document. You can specify the number of backup files to keep. Backup files are previously saved versions of the document. The first backup file will have the file suffix .FCStd1, the second .FCStd2 and so on.
Use date and FCBak extension If checked, backup files will get the extension .FCbak and their file names get a date suffix according to the specified Date format. For a description of the date format see Date & time formats cheatsheet.

With the default settings a backup file will for example get this name TD-Cube.20200315-215654.FCBak (original filename is TD-Cube.FCStd).

Allow duplicate object labels in one document If checked, objects can have the same label.
Disable partial loading of external linked objects If partial loading of external linked objects is enabled, only the referenced objects and their dependencies will be loaded when the linked document is auto opened together with the main document. Such a partially loaded document cannot be edited. Double click the document icon in the tree view to reload it in full. A more detailed explanation of this feature can be found on the Assembly3 documentation page.
Author name All created documents will get the specified author name. Keep the author field blank if you do not want to include this information. If the option Set on save is checked, the field Last modified by will be set to the specified author when saving the file. This field can be viewed using the File → Project information menu option.
Company All created documents will get the specified company name.
Default license Specifies the license for new documents. For predefined licenses the License URL will automatically be set accordingly. Select Other for a custom license.
License URL Specifies an URL describing the license selected in Default license.

Selection

On the Selection tab you can specify the following:

Name Description
Auto switch to the 3D view containing the selected item Enables the Tree view SyncView mode.
Auto expand tree item when the corresponding object is selected in 3D view Enables the Tree view SyncSelection mode.
Preselect the object in 3D view when mouse over the tree item Enables the Tree view PreSelection mode.
Record selection in tree view in order to go back/forward using navigation button Enables the Tree view RecordSelection mode.
Add checkboxes for selection in document tree Each Tree view item will get a checkbox. This is for example useful for selecting multiple items on a touchscreen.

Cache

These preferences are related to the cache directory where FreeCAD stores temporary files.

On the Cache tab (introduced in version 0.20) you can specify the following:

Name Description
Location Specifies the path of the cache directory.
Check periodically at program start Controls the frequency with which the directory size is checked. The options are:
  • Always
  • Daily
  • Weekly
  • Monthly
  • Yearly
  • Never
Cache size limit Specifies the maximum size of the directory. You will be notified if a check is performed and the size exceeds this value. The options are:
  • 100 MB
  • 300 MB
  • 500 MB
  • 1 GB
  • 2 GB
  • 3 GB
Current cache size Shows the current size of the directory, if available. Press the Check now... button to update the value.

Notification Area

These preferences control the Notification Area and its notifications.

On the Notification Area tab (introduced in version 0.21) you can specify the following:

Name Description
Enable Notification Area If checked, the Notification Area will appear in the status bar.
Enable non-intrusive notifications If checked, non-intrusive notifications will appear next to the Notification Area in the status bar.
Errors If checked, errors will appear in the Notification Area.
Warnings If checked, warnings will appear in the Notification Area.
Maximum Duration Maximum duration during which notifications are shown (unless mouse buttons are clicked).
Minimum Duration Minimum duration (idem).
Maximum Number of Notifications Maximum number of notifications shown simultaneously.
Notification width Width of the Notification Area in pixels.
Hide when other window is activated If checked, open notifications will disappear when another window is activated.
Do not show when inactive If checked, notifications will not appear if the FreeCAD window is not the active window.
Maximum Messages (0 = no limit) The maximum number of messages kept in the list. Set to 0 for no limit.
Auto-remove User Notifications If checked, notifications will be removed from the message list when the Maximum Duration has elapsed.

Report view

These preferences control the behavior of the Report view. This panel can be opened using the View → Panels → Report view menu option.

On the Report view tab you can specify the following:

Name Description
Record normal messages If checked, normal messages will be recorded. They will be displayed in the Report view with the color set in Normal messages.
Record log messages If checked, log messages will be recorded. They will be displayed in the Report view with the color set in Log messages.
Record warnings If checked, warnings will be recorded. They will be displayed in the Report view with the color set in Warnings.
Record error messages If checked, error messages will be recorded. They will be displayed in the Report view with the color set in Errors.
Show report view on error If checked, the Report view will be shown automatically when an error is recorded.
Show report view on warning If checked, the Report view will be shown automatically when a warning is recorded.
Show report view on normal message If checked, the Report view will be shown automatically when a normal message is recorded.
Show report view on log message If checked, the Report view will be shown automatically when a log message is recorded.
Include a timecode for each entry If checked, each message and warning will receive a timecode.
Normal messages Specifies the font color for normal messages.
Log messages Specifies the font color for log messages.
Warnings Specifies the font color for warning messages.
Errors Specifies the font color for error messages.
Redirect internal Python output to report view If checked, internal Python output will be redirected from the Python console to the Report view.
Redirect internal Python errors to report view If checked, internal Python error messages will be redirected from the Python console to the Report view.

Help

On the Help tab you can specify the following:

Name Description
Help location Specifies the location of the Help files. The options are:
  • Online: Enter the URL or leave blank to use the automatic GitHub URL.
Translation suffix: If https://wiki.freecad.org/ is used, a language suffix can be specified. Use for example fr for the French translation. Must be blank for the GitHub URL.
  • From disk location: Enter the path where the downloaded FreeCAD documentation can be found. To download the documentation select the offline-documentation addon from the Workbenches list in the Addon Manager.
Display Specifies where the documentation should be displayed. The options are:
  • In a new FreeCAD tab: The documentation is displayed on a new tab in the Main view area.
  • In your default web browser: The documentation is displayed in the default web browser.
  • In a separate, embeddable, dialog: The documentation is displayed in a separate dialog. This dialog can be docked on top of the Combo view for example.
Custom stylesheet Specifies an optional custom stylesheet. Not used for the Wiki URL.

Setările afișajului

This preferences section has three standard tabs: 3D View, Navigation and Colors. A fourth tab, Mesh view, is added if the Mesh Workbench has been loaded.

3D View

On the 3D View tab you can specify the following:

Name Description
Show coordinate system in the corner If checked, the main coordinate system will be shown in the lower right corner of the 3D view.

The Relative size (introduced in version 0.20) defines the size of the representation as a percentage of the view size (the minimum of its height and width).

Show axis cross by default If checked, the axis cross will be shown by default in the 3D view.
Show counter of frames per second If checked, the time needed for the last operation and the resulting frame rate will be shown in the lower left corner of the 3D view.
Use software OpenGL If checked, OpenGL will use the CPU instead of the GPU. This option is useful for troubleshooting graphics card and driver problems. Changing this option requires a restart of the application.
Use OpenGL VBO (Vertex Buffer Object) If checked, Vertex Buffer Objects (VBO) will be used. A VBO is an OpenGL feature that provides methods for uploading vertex data (position, normal vector, color, etc.) to the graphics card. VBOs offer substantial performance gains because the data resides in the graphics memory rather than the system memory and so it can be rendered directly by the GPU. For more background info see Understanding OpenGL Objects.
Render Cache "Render Cache" or "Render Acceleration" is explained in more detail in FreeCAD assembly3 render-caching. The options are:
  • Auto: Let Coin3D decide where to cache (default).
  • Distributed: Manually turn on cache for all view provider root nodes.
  • Centralized: Manually turn off cache in all nodes of all view providers, and only cache at the scene graph root node. This offers the fastest rendering speed, but slower response to any scene changes.
Anti-Aliasing Specifies if and what type of multisample anti-aliasing is used
Transparent objects Specifies the render type of transparent objects. The options are:
  • One pass: Rendering is done in one pass (default). This can lead to triangular artifacts. If these occur the type Backface pass can be used to avoid them.
  • Backface pass: Rendering is done in two passes. Back-facing polygons are rendered in the first pass and front-facing polygons in the second pass.
Marker size Specifies the size of vertices (points) in the Sketcher Workbench. The clickable area of points can be additionally enlarged by increasing the Pick radius.
Pick radius (px) Sets the area for picking elements in the 3D view. Larger value makes it easier to pick things, but can make some small features impossible to select.
Eye to eye distance for stereo modes Specifies the eye-to-eye distance used for stereo projections. The specified value is a factor that will be multiplied with the bounding box size of the 3D object that is currently displayed.
Backlight color If checked, backlight is enabled with the defined color. Backlight is used for rendering the back sides of faces. Usually, you don't see them in solids, unless you slice one with a clipping plane, or if the faces aren't oriented correctly. It is only used for objects whose Lighting property (on the View tab) is set to One side. If disabled, the back side of the faces of those objects will be black.

The related Intensity setting specifies the intensity of the backlight.

Camera type Specifies the camera projection type. The options are:

Navigation

On the Navigation tab you can specify the following:

Name Description
Navigation cube If checked, the Navigation cube will be shown in the 3D view.

Steps by turn defines the number of steps required for a full rotation when using the Navigation cube rotation arrows.

If Rotate to nearest is checked, the 3D view is rotated to the nearest most logical position, based on the current orientation of the cube, when a cube face is clicked. Else clicking a face will always result in the same rotation. introduced in version 0.20

Cube size defines the size of the cube. introduced in version 0.20

Color sets the base color for all elements. introduced in version 0.21

Corner defines where the Navigation cube is displayed in the 3D view. The options are:

  • Top left
  • Top right
  • Bottom left
  • Bottom right

Font name specifies the font used for the cube's texts. introduced in version 0.21

Font size sets the size of the font used for the cube's texts. introduced in version 0.21

3D Navigation Specifies a mouse navigation style. To see the details of each style, select it and then press the Mouse... button.
Orbit style Specifies the rotation orbit style used when in rotation mode. The options are:
  • Turntable: Moving the mouse will divide the rotation in steps, rotations around the different axes are performed sequentially.
  • Trackball: Rotations around the different axes are performed simultaneously.
  • Free Turntable: Like Trackball, but if possible the rotation axis is kept collinear with the global 3D view axis. introduced in version 0.21
Rotation mode Defines the rotation center. The options are:
  • Window center
  • Drag at cursor
  • Object center
Default camera orientation Specifies the camera orientation for new documents. This setting is also used by the Std ViewHome command.
Camera zoom Affects the initial camera zoom level for new documents. The value you set is the diameter of a sphere that fits in 3D view. The default is 100 mm. It also sets the initial size of origin features (base planes in new PartDesign Bodies and Std Parts).
Enable animation If checked, and 3D Navigation is set to CAD, rotations can be animated. If the mouse is moved while the scroll wheel and the right mouse button are pressed, the view is rotated. If one keeps the mouse moving while releasing the right mouse button, the rotation will continue. To end this animation left-click with the mouse.
Zoom at cursor If checked, zoom operations will be performed at the position of the mouse pointer. Otherwise zoom operations will be performed at the center of the current view. The Zoom step defines how much will be zoomed. A zoom step of 1 means a factor of 7.5 for every zoom step.
Invert zoom If checked, the direction of zoom operations will be inverted.
Disable touchscreen tilt gesture If checked, and 3D Navigation is set to Gesture, the tilting gesture will be disabled for pinch-zooming (two-finger zooming).
Enable rotation center indication If checked, the rotation center of the view is shown when dragging. introduced in version 1.0

Colorate

On the Colors tab you can specify the following:

Name Description
Enable preselection highlighting If checked, preselection is turned on and the specified color will be used for it. Preselection means that for example edges of objects will be highlighted while hovering over them with the mouse to indicate they can be selected.
Enable selection highlighting If checked, selection highlighting is turned on and the specified color will be used for it.
Simple color If selected, the background of the 3D view will have the specified color.
Linear gradient If selected, the background of the 3D view will have a vertical color gradient defined by the specified Top and Bottom colors. if enabled, a Middle color can also be specified. Press the button (introduced in version 0.21) to switch the top and bottom colors.
Radial gradient introduced in version 0.21 If selected, the background of the 3D view will have a radial color gradient defined by the specified Central and End colors. if enabled, a Midway color can also be specified. Press the button to switch the central and end colors.
Object being edited Specifies the background color for objects in the tree view that are currently edited.
Active container Specifies the background color for active containers in the tree view. For example an active PartDesign Body will get this color.

Mesh view

This tab is only available if the Mesh Workbench has been loaded.

On the Mesh view tab you can specify the following:

Name Description
Default mesh color Specifies the default face color.
Default line color Specifies the default line color.
Mesh transparency Specifies the default mesh transparency.
Line transparency Specifies the default line transparency.
Two-side rendering If checked, the default value for the VizualizareLighting property is Two side instead of One side. Two side means the color of the interior side of faces is the same as the color of the exterior side. One side means their color is either the backlight color, if enabled, or black.
Show bounding-box for highlighted or selected meshes If checked, the default value for the VizualizareSelection Style property is BoundBox instead of Shape. BoundBox means a highlighted bounding box is displayed if meshes are highlighted or selected. Shape means the shape itself is then highlighted.
Define normal per vertex If checked, Phong shading is used, otherwise flat shading. Shading defines the appearance of surfaces. With flat shading the surface normals are not defined per vertex. This leads to an unrealistic appearance for curved surfaces. While Phong shading leads to a more realistic, smoother appearance.
Crease angle The crease angle is a threshold angle between two faces. It can only be set if the option Define normal per vertex is used.
If face angle ≥ crease angle, facet shading is used.
If face angle < crease angle, smooth shading is used.

Workbenches

This preferences section has a single tab: Available Workbenches.

Available Workbenches

These preferences control workbench loading.

On the Available Workbenches tab you can specify the following:

Name Description
Workbench list The list displays all installed workbenches. The list can be reordered by drag and drop (introduced in version 0.21) and sorted by right-clicking the list and selecting Sort alphabetically (introduced in version 1.0). The order of the list also determines the order of the Workbench selector.
  • introduced in version 0.21: First checkbox in each row: If checked, the workbench will be available in the Workbench selector in the next FreeCAD session. The start up workbench cannot be unchecked. Unchecked workbenches are moved to the bottom of the list.
  • Auto-load: If checked, the workbench will auto-load when FreeCAD starts. Loading more workbenches will make the start up slower, but switching between workbenches that have already been loaded is faster.
  • Load: Press this button to load the workbench in the current FreeCAD session.
Start up workbench The workbench that is activated when FreeCAD starts.
Workbench selector position introduced in version 0.21 Defines where the Workbench selector appears. The options are:
  • Toolbar: In a dedicated toolbar.
  • Left corner: In the left corner of the menubar.
  • Right corner: In the right corner of the menubar.
Remember active workbench by tab If checked, FreeCAD will remember and restore the workbench that was active for each tab in the Main view area.

Python

This preferences section (introduced in version 0.21) has three tabs: Macro, Python console and Editor.

Macro

On the Macro tab you can specify the following:

Name Description
Run macros in local environment If checked, variables defined by macros are created as local variables, otherwise as global Python variables.
Macro path Specifies the path for macro files.
Record GUI commands If checked, recorded macros will also contain user interface commands.
Record as comment If checked, recorded macros will also contain user interface commands, but as comments. This is useful if you don't want to execute these commands when running the macro, but do want to see what has been done while recording.
Show script commands in python console If checked, the commands executed by macro scripts are shown in the Python console. This console can be opened using the View → Panels → Python console menu option.
Size of recent macro list Controls the number of recent macros to display in the menu.
Shortcut count Controls the number of recent macros that get dynamically assigned shortcuts.
Keyboard Modifiers Controls which keyboard modifiers are used for the shortcuts, example Ctrl+Shift+ creates shortcuts in the form of Ctrl+Shift+1, Ctrl+Shift+2, etc.

Python console

These preferences control the behavior of the Python console. This console can be opened using the View → Panels → Python console menu option.

Note that the color and font settings for the console are defined on the Editor tab.

On the Python console tab (introduced in version 0.20) you can specify the following:

Name Description
Enable word wrap If checked, words will be wrapped if they exceed the available horizontal space in the console.
Enable block cursor If checked, the cursor will have a block shape.
Save history If checked, Python history is saved across sessions.

Editor

These preferences control the behavior of the Macro editor. This editor can be opened using the Macro → Macros... → Edit or Create menu option.

The color and font settings are also used by the Python console.

On the Editor tab you can specify the following:

Name Description
Enable line numbers If checked, the code lines will be numbered.
Enable block cursor If checked, the cursor will have a block shape.
Tab size Specifies the tabulator raster (how many spaces). If it is for example set to 6, pressing Tab will jump to character 7 or 13 or 19 etc., depending on the current cursor position. This setting is only used if Keep tabs is selected.
Indent size Specifies how many spaces will be inserted when pressing Tab. This setting is only used if Insert spaces is selected.
Keep tabs If selected, pressing Tab will insert a tabulator with the raster defined by Tab size.
Insert spaces If selected, pressing Tab will insert the amount of spaces defined by Indent size.
Display Items Specifies the code type the color and font settings will be applied to. The result can be checked in the Preview field.
Family Specifies the font family that should be used for the selected code type.
Size Specifies the font size that should be used for the selected code type.
Color Specifies the color that should be used for the selected code type.

Addon Manager

This preferences section has a single tab: Addon manager options.

Addon manager options

These preferences control the behavior of the Addon manager.

On the Addon manager options tab (introduced in version 0.20) you can specify the following:

Name Description
Automatically check for updates at start (requires git) If checked, the Addon manager will check for updates when it is launched. Git must be installed for this to work.
Download Macro metadata (approximately 10MB) If checked, macro metadata is downloaded for display in the Addon manager's main addon listing. This data is cached locally.
Cache update frequency Controls the frequency with which the locally cached addon availability and metadata information is updated. The options are:
  • Manual (no automatic updates)
  • Daily
  • Weekly
Hide Addons marked Python 2 Only If checked, addons marked as "Python 2 Only" are not included in the listing. These addons are unlikely to work in the current FreeCAD version.
Hide Addons marked Obsolete If checked, addons marked as "Obsolete" are not included in the listing.
Hide Addons that require a newer version of FreeCAD If checked, addons that require a newer FreeCAD version are not included in the listing.
Custom repositories Custom repositories can be specified here.

To add a repository press the button. Both the Repository URL and the Branch, typically master or main, must be specifies in the dialog that opens. introduced in version 0.21

To remove a repository select it in the list and press the button. introduced in version 0.21

Proxy The Addon manager includes experimental support for proxies requiring authentication, set up as user-defined proxies.
Python executable (optional) The Addon manager attempts to determine the Python executable that should be used for the automatic pip-based installation of Python dependencies. To override this selection, the path to the executable can be set here.
git executable (optional) The Addon manager attempts to determine the git executable. To override this selection, the path to the executable can be set here. introduced in version 0.21
Show option to change branches (requires git) If checked, the Addon manager provides an interface on the addon's details screen that allows switching which git branch is currently checked out. This is intended for advanced users only, as it is possible that a non-primary-branch version of an addon may result in instability and compatibility issues. Git must be installed for this to work. Use with caution.
Disable git (fall back to ZIP downloads only) If checked, git downloads are disabled. introduced in version 0.21
Addon developer mode If checked, Addon manager options intended for developers of addons are activated. introduced in version 0.21

Import-Export

The Import-Export preferences affect how files are imported and exported. They are described on the Import Export Preferences page.

Workbench related preferences

Preferences for the built-in workbenches are linked below. These links are also listed in Category:Preferences. Some workbenches have no preferences.

Modulul de schiță are ecranul său preferințe

Scripting

See also: FreeCAD Scripting Basics.

For a scripting example see Std DlgParameter.

Related


Personalizarea interfeței


Introduction

Deoarece interfaţa FreeCAD se bazează pe setul de unelte moderne din bibliotecile Qt, ea beneficiază de o structurare avansată. Ferestrele, meniurile, barele de unelte şi alte instrumente pot fi modificate, mutate, distribuite intre panouri, scurtaturile pot fi personalizate si macroinstructiunile pot fi inregistrate si redate. Fereastra de personalizare se acceseaza din meniul Tools -> Customize

introduced in version 0.21: The Workbenches tab is no longer available. Its functionality has been moved to the Available Workbenches tab in the Workbenches section of the Preferences Editor.

Usage

  1. The commands available in the Customize dialog box depend on the workbenches that have been loaded in the current FreeCAD session. So you should first load all workbenches whose commands you want to have access to.
  2. There are several ways to invoke the Std DlgCustomize command:
    • Select the Tools → Customize... option from the menu.
    • Right-click a toolbar area and choose Customize... from the context menu.
  3. The Customize dialog box opens. For more information see Options.
  4. The Help button starts the Std WhatsThis command.
  5. Press the Close button to close the dialog box.

Options

In the Customize dialog box the following tabs are available:

Keyboard

The Keyboard tab

On this tab custom keyboard shortcuts can be defined. Shortcuts for macro commands can be defined on the Macros tab.

Search

You can search for commands by entering at least 3 characters of their menu text or name in the search field. The search is case-insensitive.

It is also possible to search for shortcuts:

  • In the search field special keys in shortcuts must be entered as strings. For example to search for commands that use Ctrl in their shortcut enter ctrl (4 letters).
  • Add parenthesis to search for single character shortcuts, for example: (c).
  • Add a comma and space between the characters of multi-character shortcuts, for example: g, b, b.

Add a shortcut

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
    • Optionally click the Command, Shortcut or Default column headings to reorder the list.
    • Optionally drag the splitter to the right of the panel to resize it.
  3. The Current shortcut box displays the current short cut, if available.
  4. Enter a new shortcut in the New shortcut input box. Shortcuts can be up to 4 inputs long. Each input is either a single character, a combination of one or more special keys or a combination of one or more special keys and a character. Use Backspace to correct mistakes.
  5. Other active commands (see Notes) that already use the shortcut will be listed in the Shortcut priority list.
  6. Press the Assign button to assign the new shortcut.
  7. If the Shortcut priority list contains more than one command: optionally change its order by selecting individual commands and pressing the Up button or the Down button. If active commands share the same shortcut, the shortcut will trigger the one that is highest in the list.

Remove a shortcut

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
  3. Press the Clear button.

Restore a default shortcut

  1. Select a command category from the Category dropdown list.
  2. Select a command from the Commands panel.
  3. Press the Reset button.

Restore all default shortcuts

  1. Press the Reset All button.

Notes

  • Shortcuts only work for active commands. Active commands are commands that appear in the standard menu, or in the menu of the active workbench, or commands that appear in a visible toolbar.

Top

Toolbars

The Toolbars tab

On this tab custom toolbars can be created and modified.

Search

See Keyboard.

Select the workbench

  1. In the dropdown list on the right select the workbench whose custom toolbars you want to modify. The Global option is there for custom toolbars that should be available in all workbenches.

Create a toolbar

  1. Press the New... button.
  2. Enter a name in the dialog box that opens.
  3. Press the OK button.
  4. The new toolbar will appear in the panel on the right.

Rename a toolbar

  1. Select a toolbar in the panel on the right.
  2. Press the Rename... button.
  3. Enter a new name in the dialog box that opens.
  4. Press the OK button.

Delete a toolbar

  1. Select a toolbar in the panel on the right.
  2. Press the Delete button.

Disable a toolbar

  1. Uncheck the checkbox in front of the toolbar name in the panel on the right.
  2. A disabled toolbar will be invisible in the FreeCAD interface.

Add a command

  1. At least one custom toolbar is required. See Create a toolbar.
  2. Select the correct toolbar in the panel on the right. If no toolbar is selected, the command will be added to the first toolbar in the list.
  3. Select a command category from the Category dropdown list. Macro commands that have been set up on the Macros tab appear in the Macros category.
  4. Select a command from the Commands panel, or select <Separator> to add a separator (a line between two toolbar buttons).
    • Optionally drag the splitter to the right of the panel to resize it.
  5. Press button.

Remove a command

  1. If required, expand the toolbar in the panel on the right.
  2. Select a command.
  3. Press button.

Change a command position

  1. If required, expand the toolbar in the panel on the right.
  2. Select a command.
  3. Press the button or the button.
  4. Optionally repeat this until the command is in the correct position.

Notes

  • Toolbars belonging to the current workbench are updated immediately, but after disabling/re-enabling a toolbar a workbench change is required (switch to a different workbench and then switch back).
  • To update global toolbars a workbench change (if commands have been added or removed) or a restart (if the order of a toolbar has changed or a toolbar was renamed) is required.

Top

Macros

The Macros tab

On this tab macro commands can be set up. Once set up, they can be added to custom toolbars. Macros installed with the Addon Manager are set up automatically, and added to a Global toolbar (see Toolbars), if you confirm the Add button popup during the installation process.

If you want to use a macro downloaded from a different source you will have to install it manually. See How to install macros for more information. Note that FreeCAD uses a dedicated folder for macros and only macros in that folder can be set up. Use the Std DlgMacroExecute command to find this folder on your system.

Add a macro command

  1. In the Macro dropdown list select a macro.
  2. Enter a Menu text. This will be the name used to identify the macro command and will also appear in the toolbar if there is no icon.
  3. Optionally enter a Tool tip. This text will appear near the location of the mouse when you hover the toolbar icon.
  4. Optionally enter a Status text. This text will appear in the status bar when you hover the toolbar icon.
  5. Optionally enter the wiki page for the macro, if available, in the What's this input box. Enter the page name, not the full URL.
  6. Optionally enter a shortcut in the Accelerator input box. See Keyboard for more information.
  7. To add an icon:
    1. Press the Pixmap ... button.
    2. The Choose Icon dialog box opens.
    3. If required press the Icon folders... button to add an icon folder.
    4. Select an icon from the panel. The Choose Icon dialog box closes automatically.
  8. Press the Add button.
  9. The macro command appears in the panel on the left.
  10. The macro command can now be selected on the Toolbars tab.

Remove a macro command

  1. Select the macro command in the panel on the left.
  2. Press the Remove button.

Change a macro command

  1. Double-click the macro command in the panel on the left.
  2. Make the required changes. Note that you cannot remove the icon, you can only replace it.
  3. Press the Replace button.

Top

Spaceball Motion

This tab is blank if no Spaceball is detected. See: 3Dconnexion input devices.

Top

Spaceball Buttons

This tab is blank if no Spaceball is detected. See: 3Dconnexion input devices.

Top

Themes

FreeCAD supports complete theming of the interface, via .qss stylesheets. The qss format is very similar to the css format used in web pages, it basically adds methods to reference the different widgets and elements of the Qt interface. You can change the default theme (which simply takes the style defined by your desktop system) by selecting a style sheet in the FreeCAD preferences.

You can also create your own theme if you are not satisfied with the themes that are bundled with FreeCAD, for example by editing an existing style sheet. Your new style must be placed in a specific folder for it to be found by FreeCAD:

  • %APPDATA%/FreeCAD/Gui/Stylesheets (on Windows). The %APPDATA% folder can be retrieved by entering App.getUserAppDataDir() in the Python console.
  • $HOME/.FreeCAD/Gui/Stylesheets (on Linux).
  • $HOME/Library/Application Support/FreeCAD/Gui/Stylesheets (on macOS).

Top

Addons

Addons from the Addon Manager offer yet another way to customize the user interface. Several Preference Packs to change the theme are available.

In the Workbenches category of the Addon Manager some addons by user triplus can be found:

Top

Preferences Editor/ro
Property/ro

Proprietățile obiectelor


Introduction

O proprietate este o informație ca un șir de caractere sau un text care este atașat unui document FreeCAD sau unui obiect dintr-un document. Proprietățile pot fi vizualizate și modificate prin Property editor.

Proprietățile joacă un rol foarte important în FreeCAD, deoarece a fost proiectat să funcționeze cu obiecte parametrice, care sunt obiecte definite numai prin proprietățile lor.

Obiecte personalizate scripted objects în FreeCAD pot avea următoarele tipuri de proprietăți:

Boolean
 Float
 FloatList
 FloatConstraint
 Angle
 Distance
 Integer
 IntegerConstraint
 Percent
 Enumeration
 IntegerList
 String
 StringList
 Link
 LinkList
 Matrix
 Vector
 VectorList
 Placement
 PlacementLink
 Color
 ColorList
 Material
 Path
 File
 FileIncluded
 PartShape
 FilletContour
 Circle

Properties play a very important role in FreeCAD. As objects in FreeCAD are "parametric", this means that their behavior is defined by their properties, and how these properties are used as input for their class methods. See also FeaturePython Custom Properties and PropertyLink: InList and OutList

All property types

Custom scripted objects can use any of the property types defined in the base system:

Name Unit (if any) Remark
Acceleration m/s^2
AmountOfSubstance mol
Angle °
Area m^2
Bool
BoolList
Color
ColorList
CurrentDensity A/m^2 introduced in version 0.21
Density kg/m^3
Direction
DissipationRate m^2/s^3 introduced in version 0.21
Distance m
DynamicViscosity Pa*s introduced in version 0.21
ElectricalCapacitance F introduced in version 0.21
ElectricalConductance S introduced in version 0.21
ElectricalConductivity S/m introduced in version 0.21
ElectricalInductance H introduced in version 0.21
ElectricalResistance Ohm introduced in version 0.21
ElectricCharge C introduced in version 0.21
ElectricCurrent A introduced in version 0.21
ElectricPotential V introduced in version 0.20
Enumeration
ExpressionEngine
File
FileIncluded
Float
FloatConstraint
FloatList
Font
Force N
Frequency Hz
HeatFlux W/m^2 introduced in version 0.21
Integer
IntegerConstraint
IntegerList
IntegerSet
InverseArea 1/m^2 introduced in version 0.21
InverseLength 1/m introduced in version 0.21
InverseVolume 1/m^3 introduced in version 0.21
KinematicViscosity m^2/s introduced in version 0.21
Length m
Link
LinkChild
LinkGlobal
LinkHidden
LinkList
LinkListChild
LinkListGlobal
LinkListHidden
LinkSub
LinkSubChild
LinkSubGlobal
LinkSubHidden
LinkSubList
LinkSubListChild
LinkSubListGlobal
LinkSubListHidden
LuminousIntensity cd introduced in version 0.21
MagneticFieldStrength A/m introduced in version 0.21
MagneticFlux Wb or V*s introduced in version 0.21
MagneticFluxDensity T introduced in version 0.21
Magnetization A/m introduced in version 0.21
Map
Mass kg introduced in version 0.21
Material
MaterialList
Matrix
PartShape a Part property, is accessed as
Part::PropertyPartShape
Path
Percent
PersistentObject
Placement
PlacementLink
PlacementList
Position
Power W introduced in version 0.21
Precision
Pressure Pa
PythonObject
Quantity
QuantityConstraint
Rotation
ShearModulus Pa introduced in version 0.21
SpecificEnergy m^2/s^2 or J/kg introduced in version 0.21
SpecificHeat J/kg/K introduced in version 0.21
Speed m/s
Stiffness m/s^2
Stress Pa introduced in version 0.21
String
StringList
Temperature K introduced in version 0.21
ThermalConductivity W/m/K introduced in version 0.21
ThermalExpansionCoefficient 1/K introduced in version 0.21
ThermalTransferCoefficient W/m^2/K introduced in version 0.21
Time s introduced in version 0.21
UltimateTensileStrength Pa introduced in version 0.21
UUID
VacuumPermittivity s^4*A^2 / (m^3*kg)
Vector
VectorDistance
VectorList
Velocity m/s introduced in version 0.21
Volume l or m^3
VolumeFlowRate l/s or m^3/s introduced in version 0.21
VolumetricThermalExpansionCoefficient 1/K introduced in version 0.21
Work J introduced in version 0.21
XLink
XLinkList
XLinkSub
XLinkSubList
YieldStrength Pa introduced in version 0.21
YoungsModulus Pa introduced in version 0.21

Internally, the property name is prefixed with App::Property:

App::PropertyBool
App::PropertyFloat
App::PropertyFloatList
...

Remember that these are property types. A single object may have many properties of the same type, but with different names.

For example:

obj.addProperty("App::PropertyFloat", "Length")
obj.addProperty("App::PropertyFloat", "Width")
obj.addProperty("App::PropertyFloat", "Height")

This indicates an object with three properties of type "Float", named "Length", "Width", and "Height", respectively.

Scripting

See also: FreeCAD scripting basics

A scripted object is created first, and then properties are assigned.

obj = App.ActiveDocument.addObject("Part::Feature", "CustomObject")

obj.addProperty("App::PropertyFloat", "Velocity", "Parameter", "Body speed")
obj.addProperty("App::PropertyBool", "VelocityEnabled", "Parameter", "Enable body speed")

In general, Data properties are assigned by using the object's addProperty() method. On the other hand, View properties are normally provided automatically by the parent object from which the scripted object is derived.

For example:

  • Deriving from App::FeaturePython provides only 4 View properties: "Display Mode", "On Top When Selected", "Show In Tree", and "Visibility".
  • Deriving from Part::Feature provides 17 View properties: the previous four, plus "Angular Deflection", "Bounding Box", "Deviation", "Draw Style", "Lighting", "Line Color", "Line Width", "Point Color", "Point Size", "Selectable", "Selection Style", "Shape Color", and "Transparency".

Nevertheless, View properties can also be assigned using the view provider object's addProperty() method.

obj.ViewObject.addProperty("App::PropertyBool", "SuperVisibility", "Base", "Make the object glow")

Source code

In the source code, properties are located in various src/App/Property* files.

They are imported and initialized in src/App/Application.cpp.

#include "Property.h"
#include "PropertyContainer.h"
#include "PropertyUnits.h"
#include "PropertyFile.h"
#include "PropertyLinks.h"
#include "PropertyPythonObject.h"
#include "PropertyExpressionEngine.h"


Lucrul cu ateliere


FreeCAD, la fel ca multe aplicații de design moderne, precum Revit sau CATIA, se bazează pe conceptul de Workbench. Un atelier poate fi considerat un set de instrumente special grupate pentru o anumită sarcină. Într-un atelier de mobilier tradițional, veți avea o masă de lucru pentru persoana care lucrează cu lemn, un altul pentru cel care lucrează cu piese de metal și poate un al treilea pentru tipul care montează toate piesele împreună.

În FreeCAD, se aplică același concept. Instrumentele sunt grupate în ateliere în funcție de sarcinile cu care sunt legate.

Când treceți de la un atelier la altul, se schimbă instrumentele disponibile pe interfață. Barele de instrumente, barele de comandă și, eventual, alte părți ale interfeței comută la noul tabel de lucru, dar conținutul scenei dvs. nu se schimbă. Ați putea, de exemplu, să începeți desenarea unor forme 2D cu Workbench Draft, apoi să lucrați mai departe pe ele cu Workbench Part.

Rețineți că uneori un Workbench este denumit "Modul". Cu toate acestea, atelierele de lucru și modulele sunt entități diferite. Un modul este orice extensie a FreeCAD, în timp ce un Workbench este o configurație GUI specială care grupează câteva bare de instrumente și meniuri. De obicei, fiecare modul conține propriul său Workbench, de unde și utilizarea încrucișată a numelui.

Ateliere încorporate

Current

Următoarele ateliere sunt disponibile pentru fiecare instalare FreeCAD:

  • Std Base. This is not really a workbench, but rather a category of 'standard' commands and tools that can be used in all workbenches.
  • The CAM Workbench is used to produce G-Code instructions. This workbench was called "Path Workbench" in version 0.21 and below.
  • The FEM Workbench provides Finite Element Analysis (FEA) workflow.
  • The Inspection Workbench is made to give you specific tools for examination of shapes. Still in the early stages of development.
  • The Part Workbench for working with geometric primitives and boolean operations.
  • The Reverse Engineering Workbench is intended to provide specific tools to convert shapes/solids/meshes into parametric FreeCAD-compatible features.

Obsolete

The following workbenches are no longer included after version 0.21:

  • The Start Workbench allows you to quickly jump to one of the most common workbenches.

The following workbenches are no longer included after version 0.20:

Ateliere externe

Atelierele de lucru FreeCAD sunt ușor de programat în Python, prin urmare, mulți oameni dezvoltă ateliere suplimentare în afara grupului principal de dezvoltatori FreeCAD.

Pagina external workbenches conține câteva informații și tutoriale despre unele dintre ele, iar proiectul FreeCAD Addons are ca scop colectarea acestora și facilitarea instalării acestora în cadrul FreeCAD .


Property editor/ro
PartDesign Workbench/ro

Lucrul cu ochiuri de plasă de discretizare


Mesh workbench icon

Introduction

Introducere

Atelierul Plase Mesh Workbench se ocupă de mesh triangle. Plasele/Mesh-urile sunt un tip special de obiect 3D, compuse din fațete triunghiulare legate de marginile lor și de colțurile lor (numite și vârfuri).

Multe aplicații 3D utilizează ochiurile de plasă ca tip principal de obiect 3D, cum ar fi sketchup, Blender , Maya sau 3D Studio Max, utilizează plase ca primă alegere de elecție. Deoarece plasele sunt obiecte foarte simple, conținând numai vârfuri (puncte), muchii și fațete (triunghiulare), ele sunt foarte ușor de creat, modificat, subdivizat, întins și ușor de trecut de la o aplicație la alta fără nici o pierdere. În plus, deoarece conțin date foarte simple, aplicațiile 3D pot gestiona, de obicei, cantități foarte mari din acestea fără nici o problemă. Din aceste motive, plasele sunt adesea tipul de obiect 3D preferat pentru aplicații care se ocupă cu filmele, animația și crearea imaginilor.

Cu toate acestea, în domeniul rețelelor de inginerie există o mare limitare: ele sunt doar realizate din suprafețe și nu au informații despre masă, deci nu se comportă ca solide. Aceasta înseamnă că toate operațiunile de bază pentru solide, cum ar fi adunarea sau scăderea, sunt dificil de realizat pe ochiuri de plasă. Mesh Workbench este util să importați date 3D în format de plase, să le analizați, să detectați erorile și, în final, să le convertiți într-un solid, pentru a fi utilizate cu Part Workbench.

Instrumente

Modulul de plase are în prezent o interfață foarte simplă, toate funcțiile sale fiind grupate în intrarea din meniul Mesh

Analiza

  • Close hole: Fills selected holes in mesh objects.
  • Add triangle: Adds faces along a boundary of an open mesh object.

Boolean

  • Union: Realizează o uniune/fuziun e cu plase
  • Intersection: Realizează o intersecție/common de plase
    • Difference: Realizează o diferență/cut de plase
  • Merge: Creates a mesh object by combining the meshes of two or more mesh objects.
  • Unwrap mesh: Creates a flat representation of a mesh object.
  • Unwrap face: Creates a flat representation of a face of a shape object.

Preferences

There are some export preferences related to Mesh Formats but these are not used by commands belonging to this workbench. They are used by the Std Export command.

Mesh Workbench preferences can be found in the following categories of the Preferences Editor:

Legături


Lucrul cu Atelierul Piesa


Part workbench icon

Introduction

Introducere

Capacitățile de modelare a solidelor ale FreeCAD se bazează pe kernelul Open Cascade Technology (OCCT), un sistem CAD de calitate profesionistă, care oferă crearea și manipularea geometriei avansate 3D.

A more detailed discussion of Part workbench versus Part Design workbench can be found here: Part and Part Design.

Atelierul Piese permite utilizatorului să acceseze și să utilizeze obiectele și funcțiile OCCT. Obiectele piese, spre deosebire de Mesh objects, sunt mai complexe și, prin urmare, permit operații mai avansate cum ar fi operațiile booleene coerente, istoricul modificărilor și comportamentul parametric.

Part objects are more complex than mesh objects created with the Mesh Workbench, as they permit more advanced operations like coherent boolean operations, modifications history, and parametric behaviour.

The Part Workbench is the basic layer that exposes the OCCT drawing functions to all workbenches in FreeCAD.

Instrumente

Instrumentele sunt toate amplasate în meniul Part

Primitive

Acestea sunt instrumente pentru crearea de obiecte primitive grafice.

  • Caseta: Deseneaza o caseta prin specificarea dimensiunile sale
  • Cilindru: Deseneaza un cilindru prin specificarea dimensiunile sale
  • Sfera: Deseneaza o sfera prin specificarea dimensiunile sale
  • Con: Deseneaza un con prin specificarea dimensiunile sale
  • Tor: Deseneaza un tor (inel) prin specificarea dimensiunile sale
  • Creaza primitive: Unealta pentru crearea primitivelor geometrice bazate pe parametrii
  • Creaza forme: Unealta pentru crearea formelor complexe din primitive geometrice bazate pe parametrii
  • Cone: Creates a cone.
  • Tube: Creates a tube.
  • Create primitives...: A tool to create one of the following primitives:
    • Plane: Creates a plane.
    • Box: Creates a box. This object can also be created with the Box tool.
    • Cylinder: Creates a cylinder. This object can also be created with the Cylinder tool.
    • Cone: Creates a cone. This object can also be created with the Cone tool.
    • Sphere: Creates a sphere. This object can also be created with the Sphere tool.
    • Ellipsoid: Creates a ellipsoid.
    • Torus: Creates a torus. This object can also be created with the Torus tool.
    • Prism: Creates a prism.
    • Wedge: Creates a wedge.
    • Helix: Creates a helix.
    • Spiral: Creates a spiral.
    • Circle: Creates a circular arc.
    • Ellipse: Creates an elliptical arc.
    • Point: Creates a point.
    • Line: Creates a line.
    • Regular polygon: Creates a regular polygon.

Modificarea obiectelor

Acestea sunt unelte pentru modificarea obiectelor existente. Ele permit alegerea obiectelor cu care se lucrează.

  • Extrudare: Extrudeaza fetele plane ale unui obiect
  • Rotatie: Creaza un obiect prin rotirea altui obiect in jurul unei axe
  • Simetrizare: Simetrizează obiectul selectat fata de un plan
  • Panglica: Rotunjeste marginile unui obiect
  • Tesire: Teseste marginile unui obiect
  • Ruled Surface:
  • Mansardare: Uneste un profil de altul
  • Baleiere: Baleiază unul sau mai multe profile de-a lungul unei cai
  • Revolve: Creates a solid by revolving an object (not a solid) around an axis.
  • Mirror: Mirrors the selected object across a mirror plane.
  • Fillet: Fillets (rounds) edges of an object.
  • Chamfer: Chamfers edges of an object.
  • Loft: Lofts from one profile to another.
  • Sweep: Sweeps one or more profiles along a path.
  • Section: Creates a section by intersecting an object with a section plane.
  • Offset tools:
    • 3D Offset: Construiește o formă paralelă la o anumită distanță față de original.
    • 2D Offset: Construiește o polilinie paralelă la o anumită distanță față de original, sau enlarges/shrinks o fațetă plană. (v0.17)
  • Thickness: Golește un solid, lăsând deschideri lângă fațetele selectate.
  • Attachment: Attaches an object to another object.

Boolean

These tools perform boolean operations.

  • Boolean: Efectueaza operatii logice asupra obiectelor.
  • Cut: Cuts (subtracts) one object from another.
  • Fuse: Fuses (unions) two or more objects.
  • Common: Extracts the common (intersection) part of two objects.
  • Join features: funcții booleene inteligente pentru obiecte de pus în perete (de ex țevi) (v0.16)
    • Connect: Conectează interiorul obiectelor (v0.16)
    • Embed: Include un obiect din perete într-un alt obiect din perete(v0.16)
    • Cutout: Crează o tăietură într-un peretele unui obiect pentru un alt obiect de pus în perete (v0.16)
  • Splitting tools: (v0.17)
    • Boolean fragments: face toate piesele care pot fi obținute prin operații booleene între obiecte (v0.17)
    • Slice a part: instrument pentru a separa forme prin intersecția cu alte forme
    • Slice: Separă un obiect în piese prin intersecții cu un alt obiect(v0.17)
    • XOR:

elimină spațiul partajat de un număr par de obiecte (versiunea simetrică a Cut) (v0.17)

Measure

Alte Instrumente

  • Import: Imports from *.IGES, *.STEP, or *.BREP files.
  • Export: Exports to *.IGES, *.STEP, or *.BREP files.

Context menu items

  • Appearance: Determines the appearance of a whole object (color, transparency etc.).

Preferințe

Scripting

Tutorials


Lucrul cu Atelierul Desen 3 D


The Drawing Workbench is no longer included after version 0.20.
The TechDraw Workbench is its more advanced replacement.
Drawing workbench icon

Introducere

Modulul de desenare vă permite să puneți lucrul 3D pe hârtie. Adică, pentru a afișa vizualizările modelelor dvs. într-o fereastră 2D și pentru a insera acea fereastră într-un desen, de exemplu o foaie cu graniță, un titlu și logo-ul dvs. și, în final, să tipăriți această foaie.

Instrumente

Unelte pentru crearea, configurarea si exportul foilor de desen 2D

  • Annotation: Adaugă o adnotare în foaia de desen curent
  • Clip: Adaugă un grup de clipuri în foaia de desen curent
  • Open Browser: Deschide o previzualizare a foii curente din browser
  • Ortho Views: Creează automat vederi ortografice ale unui obiect
  • Symbol: Adaugă conținutul unui fișier SVG ca simbol în foaie de desen curentă
  • Draft View: Inserează o vizualizare specială a unui obiect selectat în foaia de desen curent
  • Spreadsheet View: Inserts a view of a selected spreadsheet in the current drawing sheet
  • Project Shape: Creează o proiecție a obiectului selectat (Sursă) în vizualizarea 3D.
  • Notă Note:

Instrumentul Draft View este utilizat în special pentru a plasa obiecte 2D Draft pe hârtie. Acesta are câteva capabilități adiționale și suportă obiecte specifice ca de ex: Draft dimensions.

Flux de lucru

Documentul conține un obiect 3D (Schenkel) din care dorim să realizăm un desen. Prin urmare, este creată o "pagină". O pagină este instanțiată dintr-un șablon, de exemplu șablonul "A3_Landscape". Șablonul este un document SVG care poate conține un cadru de pagină, un logo și alte elemente.

În această pagină putem introduce una sau mai multe vizualizări. Fiecare vizualizare are o poziție pe pagină (Proprietăți X, Y), un factor de scară (Scala proprietății) și proprietăți suplimentare. De fiecare dată când pagina sau vizualizarea sau obiectul referință se modifică, pagina este regenerată și actualizarea paginii este actualizată.

Scrip-Programare

În prezent, fluxul de lucru al interfeței grafice cu utilizatorul este foarte limitat, astfel încât API-ul de scripting este mai interesant.

Consultați pagina Drawing API example pentru o descriere a funcțiilor utilizate pentru a crea pagini de desen și vizualizări.

Șabloane

FreeCAD este livrat împreună cu un set de șabloane implicite, dar puteți găsi mai multe în pagina Drawing templates .

Extensii la Atelierul de Desen 3D

Unele note despre partea de programare a modulului de desen vor fi adăugate la pagina Drawing Documentation . Acest lucru va ajuta să intelegeți rapid modul în care funcționează modulul de desen, permițând programatorilor sa înceapă rapid programarea pentru aceasta.

Tutoriale

Macros

  • Macro Automatic drawing: Allows the user to get the view of his object in a drawing with 4 different position (front,top,iso,right). Needs some modification to be perfectly effective.
  • Macro CartoucheFC: This GUI macro to fill simply all fields of the cartridge of the plan implementation worksheet FreeCAD, the format of the date and the symbol of the projection mode adapt to the EU region or US selected.
  • Macro CartoucheFC 2: This GUI macro to fill simply all fields of the cartridge model 2 of the plan implementation worksheet FreeCAD.
  • Macro CartoucheFC Full: This GUI macro to fill simply all fields of the cartridge Misc templates Full of the plan implementation worksheet FreeCAD, the format of the date and the symbol of the projection mode adapt to the EU region or US selected.
  • Macro Corner shapes wizard/update: Pops up a dialog asking for the dimensions of your corner piece, then creates the object in the document and creates a page view with top, front and lateral views of the piece.

External links


Lucrul cu Atelierul de Rrandare


The Raytracing Workbench is no longer included after version 0.20.
The external Render Workbench should be used instead.
Raytracing workbench icon

Introducere

Atelierul de Randare Raytracing Workbench

este folosit pentru a genera imagini fotorealiste ale modelelor dvs., făcându-le  o randare exterioară.

The Raytracing Workbench is used to generate photorealistic images of your models by processing them with an external renderer.

Atelierul de Randare funcționează împreună cu modulele templates, care sunt fișiere de proiect care definesc o scenă pentru modelul dvs. 3D. Puteți localiza luminile și geometria, cum ar fi avioanele de la sol și conține, de asemenea, suporturi pentru poziția camerei și pentru informațiile materiale ale obiectelor din scenă. Proiectul poate fi apoi exportat într-un fișier gata de redare sau poate fi redat direct în cadrul FreeCAD.

În mod obișnuit, sunt susținute două tipuri de randare: povray și luxrender. Pentru a putea randa direct din FreeCAD, cel puțin unul dintre aceste programe trebuiesc instalate pe sistemul dvs., iar calea trebuie să fie configurată în preferințele FreeCAD Raytracing. Totuși dacă nici un program de randare nu este instalat, veți putea să exportați un fișier scenă care poate fi folosit ulterior.

The Raytracing workbench is essentially obsolete. New development is happening in the Render Workbench, which is intended as its replacement. This workbench is fully programmed in Python so it is much easier to extend than the current workbench which is programmed in C++. Nevertheless, the information in this page is generally useful for the new workbench, as both modules work basically in the same way.

Flux de lucru tipic

  1. Creați sau deschideți un proiect FreeCAD, adăugați unele obiecte Part-based (mesh-urile nu sunt acceptate în prezent)
  2. Creați un proiect Raytracing (cu luxrender sau povray)
  3. Selectați obiectele pe care doriți să le adăugați la proiectul raytracing și adăugați-le la proiect cu instrumentul "Inserați o piesă"
  4. Exportați sau afișați direct



Workflow of the Raytracing Workbench; atelierul de lucru pregătește un fișier de proiect dintr-un șablon dat și apoi apelează un program extern pentru a produce randarea reală a scenei. Programul de randare extern poate fi folosit independent de FreeCAD.

Instrumente

Instrumente de Proiect

Acestea sunt instrumentele principale pentru exportul lucrării dvs. 3D la programe de randare externe.

  • New PovRay project: Inserează un nou proiect PovRay project în document
  • New LuxRender project: Inserează un nou proiect LuxRender în document
  • Insert part: Introduceți o imagine a unei părți într-un proiect de proiectare
  • Reset camera: Potrivește poziția camerei unui proiect de proiectare la vizualizarea curentă
  • Export project: Exportă un proiect raytracing unui fișier de scenă pentru randarea într-un renderer extern
  • Render: Proiectarea unui proiect de raytracing cu un renderer extern

Utilități

Acestea sunt instrumente de ajutor pentru a efectua sarcini specifice în mod manual.

Preferințe

  • Preferences: Preferințele disponibile pentru instrumentele Raytracing.

Tutorials

Crearea manuală a unui fișier povray

Instrumentele utilitare descrise mai sus vă permit să exportați vizualizarea 3D curentă și întregul conținut al acestuia într-un fișier Povray. În primul rând, trebuie să încărcați sau să creați datele CAD și să poziționați orientarea 3D în orientarea dorită. Apoi alegeți "Utilities-> Export View ..." din meniul raytracing.

Vi se va solicita o locație pentru salvarea fișierului * .pov rezultat. După asta, poți să o deschizi Povray and render:

Ca de obicei, prin randare poți face poze mari și frumoase:

Script-Programare

A se vedea Raytracing API example pentru informații asupra scrierii programelor de scene.

Legături

POVRay

Luxrender

Viitoare posibile randări de implementat

Export către Kerkythea

Deși exportul direct către fișierul Kerkythea XML-File-Format nu este încă acceptat, puteți să exportați Obiectele ca Fișiere Mesh (.obj) și apoi să le importați în Kerkythea.

  • dacă folosiți Kerkythea pentru Linux, nu uitați să instalați pachetul WINE (necesar pentru Kerkythea pentru Linux)
  • puteți să vă transformați modelele cu ajutorul Atelierul Plase în plase și apoi să le exportați ca fișiere .obj
  • Dacă plasa dvs. la exportare a dus la erori (modificări de normale, găuri ...), vă puteți încerca norocul cu studio netfabb studio
Gratuit pentru uz personal, disponibil pentru Windows, Linux și Mac OSX.
Dispune de instrumente de reparații standard care vă vor repara modelul în majoritatea cazurilor.
  • un alt program bun pentru analiza / repararea ochiului este Meshlab
Open Source, disponibil pentru Windows, Linux și Mac OSX.
Dispune de instrumente de reparații standard care vă vor repara modelul în majoritatea cazurilor (găuri de umplere, re-orientare de normale etc.)
  • puteți utiliza "make compound" și apoi "face o singură copie" sau puteți fuziona solide pentru a le grupa înainte de a converti în plase cu ochiuri
  • nu uitați să setați în Kerkythea un factor de import de 0.001 pentru obj-modeler, deoarece Kerkythea se așteaptă ca fișierul obj să fie în m (dar unitățile standard-scheme în FreeCAD sunt mm)
În cadrul ferestrelor Windows 7 Kerkythea pe 64 de biți nu pare să poată salva aceste setări.
Așa că nu uitați să faceți acest lucru de fiecare dată când porniți Kerkythea
  • dacă importați mai multe obiecte în Kerkythea, puteți folosi comanda "File>Merge" în Kerkythea

Development

These pages refer to the new workbench, programmed in Python, meant to replace the current Raytracing Workbench.


Lucrul cu Atelierul Imagine


The Image Workbench is no longer included after version 0.20.
Its functionality has been integrated in Std Base. See Std Import and Std ViewLoadImage.
Image workbench icon

Introducere

Atelierul Imagine Image Workbench gestionează diferite tipuri de bitmap images și vă permite să le deschideți în FreeCAD.

Instrumente

  • Open: open an image on a new viewport.
  • Import to plane: import an image to a plane in the 3D view.
  • Scaling: scale an image imported to a plane.

Funcționalități

  • Atelierul Imagine vă permite de asemenea să importați o imagine într-un plan spațial 3D al FreeCAD cu Image Import, cu al doilea buton al atelierului Imagine.
  • Imaginea importată poate fi atașată la o schiță a uneia dintre cele trei planuri (XY / XZ / YZ) cu ​​offset pozitiv sau negativ.
  • Această funcție este disponibilă numai dacă ați deschis un document FreeCAD.
  • The image can be moved in 3D-space by editing the placement in the Property editor.
  • The major use is tracing over the image, in order to generate a new part while using the image as a template.
  • The image is imported with 1 pixel = 1mm.
 * The recommendation is to have the imported image at a reasonable resolution.
  • Imaginea poate fi scalată prin editarea valorilor "XSize" și "YSize" înProperty editor.
  • Imaginea poate fi mutată prin editarea valorilor X/Y/Z-în Property editor.
  • Imaginea poate fi rotită în jurul unei axe utilizând Property editor.

Workflow

Flux de lucru

O utilizare importantă a acestui atelier de lucru este urmărirea imaginii, cu ajutorul instrumentelor Draft sau Sketcher, pentru a genera un corp solid bazat pe contururile imaginii.

Tip:
Urmărirea cu elemente de schiță peste o imagine funcționează cel mai bine dacă imaginea are o mică (negativă) decalare față de planul de schiță.
Puteți seta o decalare de -0,1 mm la import sau mai târziu, prin editarea destinației de plasare a imaginii.

Decalajul imaginii poate fi setat în timpul importului sau poate fi modificat mai târziu prin proprietățile sale.


Raytracing Workbench/ro
Draft Workbench/ro

Lucrul cu modul Desen 2 D


Draft workbench icon

Introduction

Introducere

Atelierul Draft vă permite desenarea rapidă a unor obiecte bidimensionale în documentul curent şi oferă mai multe unelte pentru modificarea lor ulterioară. De asemenea, oferă instrumente pentru a defini un plan de lucru, o rețea și un sistem de ancorare pentru a controla precis poziția geometriei dvs.

Obiectele create 2D pot fi folosite pentru redactarea generală într-un mod similar cu Inkscape sau Autocad. Aceste forme 2D pot fi de asemenea utilizate ca componente de bază ale obiectelor 3D create cu alte ateliere de lucru, de exemplu, Part și Arch Workbench. Este, de asemenea, posibilă transformarea de obiecte Draft în Sketches, ceea ce înseamnă că formele pot fi de asemenea utilizate cu PartDesign Workbench pentru crearea de corpuri solide.

The Draft Workbench also provides tools to define a working plane, a grid, and a snapping system to precisely control the position of geometry.

FreeCAD este în primul rând o aplicație de modelare 3D și, prin urmare, instrumentele sale 2D nu sunt la fel de avansate ca în cazul altor programe de desenare. Dacă obiectivul dvs. principal este producerea de desene complexe 2D și fișiere DXF și nu aveți nevoie de modelare 3D, vă recomandăm să luați în considerare un program software dedicat pentru redactarea tehnică, cum ar fi LibreCAD, QCad, TurboCad, ș.a.m.d.

The image shows the grid aligned with the XY plane.
On the left, in white, several planar objects.
On the right a non-planar Draft Wire used as the Path Object of a Draft PathArray.

Drafting

  • Line: creates a straight line.
  • Polyline: creates a polyline (also called wire), a sequence of several connected line segments.
  • Fillet: creates a fillet, a rounded corner, or a chamfer, a straight edge, between two Draft Lines.
  • Arc tools:
  • Arc: creates a circular arc from a center, a radius, a start angle and an aperture angle.
  • Arc by 3 points: creates a circular arc from three points that define its circumference.
  • Circle: creates a circle from a center and a radius.
  • Ellipse: creates an ellipse from two points defining a rectangle in which the ellipse will fit.
  • Rectangle: creates a rectangle from two points.
  • Polygon: creates a regular polygon from a center and a radius.
  • B-spline: creates a B-spline curve from several points.
  • Bézier tools:
  • Point: creates a simple point.
  • Facebinder: creates a surface object from selected faces.
  • ShapeString: creates a compound shape that represents a text string.

Annotation

  • Text: creates a multi-line text at a given point.
  • Dimension: creates a linear dimension, a radial dimension or an angular dimension.
  • Label: creates a multi-line text with a 2-segment leader line and an arrow.
  • Annotation styles...: allows you to define styles that affect the visual properties of annotation-like objects.

Modification

  • Move: moves or copies selected objects from one point to another.
  • Rotate: rotates or copies selected objects around a center point by a given angle.
  • Scale: scales or copies selected objects around a base point.
  • Mirror: creates mirrored copies from selected objects.
  • Offset: offsets each segment of a selected object over a given distance, or creates an offset copy of the selected object.
  • Trimex: trims or extends a selected object.
  • Stretch: stretches objects by moving selected points.
  • Clone: creates linked copies, clones, of selected objects.
  • Array tools:
  • Array: creates an orthogonal array from a selected object. It can optionally create a Link array.
  • Polar array: creates an array from a selected object by placing copies along a circumference. It can optionally create a Link array.
  • Circular array: creates an array from a selected object by placing copies along concentric circumferences. It can optionally create a Link array.
  • Path array: creates an array from a selected object by placing copies along a path.
  • Point array: creates an array from a selected object by placing copies at the points from a point compound.
  • Edit: puts selected objects in Draft Edit mode. In this mode the properties of objects can be edited graphically.
  • Subelement highlight: temporarily highlights selected objects, or the base objects of selected objects.
  • Upgrade: upgrades selected objects.

Draft Tray

The Draft Tray allows selecting the working plane, defining style settings, toggling construction mode, and specifying the active layer or group.

  • Select plane: defines the current Draft working plane. Also available in the menu: Draft → Utilities → Select Plane.
  • Set style: sets the default style for new objects. Also available in the menu: Draft → Utilities → Set style.
  • Toggle construction mode: switches Draft construction mode on or off. Also available in the menu: Draft → Utilities → Toggle construction mode.

Draft annotation scale widget

With the Draft annotation scale widget the Draft annotation scale can be specified.

Draft snap widget

The Draft snap widget can be used as an alternative for the Draft snap toolbar.

Draft snap toolbar

The Draft snap toolbar allows selecting the active snap options. The buttons belonging to active options stay depressed. For general information about snapping see: Draft Snap.

  • Snap lock: enables or disables snapping globally.
  • Snap angle: snaps to the special cardinal points on circular edges, at multiples of 30° and 45°.
  • Snap extension: snaps to an imaginary line that extends beyond the endpoints of straight edges.
  • Snap parallel: snaps to an imaginary line parallel to straight edges.
  • Snap special: snaps to special points defined by the object.
  • Snap near: snaps to the nearest point on faces and edges.
  • Snap ortho: snaps to imaginary lines that cross the previous point at multiples of 45°.
  • Snap grid: snaps to the intersections of grid lines.

Utilitare

Additional tools

O serie de instrumente suplimentare sunt oferite de un meniu Draft → Utilities, sau cu clic-dreapta în meniul contextual, în funcţie de obiectele selectate:

  • Heal: heals problematic Draft objects found in very old files.

Caracteristici suplimentare

  • Coordinates:

introduceți coordonatele în loc să faceți clic pe vizualizarea 3D pentru a defini un nou punct.

limitați pointerul la mișcări orizontale sau verticale în raport cu un punct anterior.

plasați noi puncte pe locuri speciale pe obiecte existente sau pe grilă.

Tree view context menu

The following additional options are available in the Tree view context menu:

Default options

For most Draft objects the following option is available:

If there is an active document the context menu contains an additional sub-menu:

  • Utilities: a subset of the tools available in the main Draft Utilities menu.

Layer container options

For a Draft LayerContainer these additional options are available:

Layer options

For a Draft Layer these additional options are available:

Text options

For a Draft Text and a Draft Label that contains one or more hyperlinks, to a local or remote file or an URL, this additional option is available:

  • Open hyperlinks: the hyperlinks are opened in the appropriate application (as defined by the OS). There is a warning in the case of multiple hyperlinks. introduced in version 1.0

Wire options

For a Draft Line and a Draft Wire this additional option is available:

  • Flatten: flattens the wire on the current Draft working plane. This option does not work properly in version 0.19 and below.

Working plane proxy options

For a Draft WorkingPlaneProxy these additional options are available:

  • Write objects state: updates the VizualizareVisibility Map property of the working plane proxy with the current visibility state of objects in the document.

3D view context menu

The following additional options are available in the 3D view context menu:

Default options

If there is an active document the context menu contains one additional sub-menu:

  • Utilities: a subset of the tools available in the main Draft Utilities menu.

Text options

See above.

Obsolete tools

  • Array: creates an orthogonal array from a selected object. The created array can be turned into a polar array or a circular array by changing its DateArray Type property. Not available in version 0.21 and above.
  • Drawing: inserts views of selected objects into a drawing page. Not available in version 0.21 and above.

Preferințe

  • Preferences: Preferințe disponibile în Atelierul Draft Workbench.
  • Import-Export Preferences: preferințele disponibile pentru importul și exportul în diferite formate de fișiere.

Formate de fişiere

Atelierul Desen 2D (Draft) înzestrează FreeCAD cu importul şi exportul următoarele formate de fişiere:

Unit tests

See also: Test Workbench.

To run the unit tests of the workbench execute the following from the operating system terminal:

freecad -t TestDraft

Script

Instrumentele de proiectare pot fi utilizate în macros și din consola Python.

The workbench includes a module to create samples of all objects in a new document.

Use this to test that all objects are produced correctly:

import drafttests.draft_test_objects as dto
doc = dto.create_test_file()

Inspecting the code of this module can help to understand the programming interface.

Tutorials


Biblioteci de Fișiere și Macrocomenzi

Macros


Introduction

Macrocomenzile reprezintă o modalitate convenabilă de a crea acțiuni complexe în FreeCAD. Pur și simplu înregistrați acțiunile, salvați-le sub un nume și repetați-le ori de câte ori doriți. Deoarece macrocomenzile sunt în realitate o listă de comenzi python, puteți să le editați și să creați scripturi foarte complexe.

While Python scripts normally have the .py extension, FreeCAD macros should have the .FCMacro extension. A collection of macros written by experienced users is found in the macros recipes page.

See the Power users hub to learn more about the Python programming language, and about writing macros. In particular, you should start with these pages:

Cum funcționează

Dacă activați consola de ieșire (Meniu Editare -> Preferences -> General -> Macros -> Afișează comenzi script în consola python), veți vedea că în FreeCAD, fiecare acțiune pe care o faceți, de exemplu apăsând un buton generează o comandă python. Aceste comenzi sunt ceea ce poate fi înregistrat într-o macrocomandă. Instrumentul principal pentru realizarea macrocomenzilor este bara de scule a macroco-urilor: . Pe bara aveți 4 butoane: Înregistrare, oprire înregistrarea, editare și rularea macro-ul curent.

Enable the console output in the menu Edit → Preferences → Python → Macro → Show scripts commands in python console. You will see that in FreeCAD, every action you do, such as pressing a button, outputs a Python command. Those commands are what can be recorded in a macro. The main tool for making macros is the macros toolbar: . On it you have 4 buttons: Record, stop recording, edit and play the current macro.

Este foarte simplu de utilizat: Apăsați butonul de înregistrare, vi se va cere să dați un nume macro, apoi efectuați unele acțiuni. Când ați terminat, faceți clic pe butonul de oprire și acțiunile dvs. vor fi salvate. Acum puteți accesa dialogul macro cu butonul de editare:

Acolo puteți gestiona macrocomenzile, puteți șterge, edita, duplica, instala sau crea altele noi de la zero. Dacă editați o macrocomandă, aceasta va fi deschisă într-o fereastră de editor unde puteți modifica codul acesteia. Noile macrocomenzi pot fi instalate folosind butonul Addons ... care se leagă de Addon Manager.

Exemplu

Apăsați butonul de înregistrare, dați un nume, să zicem "cilindru 10x10", apoi, în Part Workbench, creați un cilindru cu raza = 10 și înălțimea = 10. Apoi apăsați butonul "stop recording". În dialogul de editare a macrocomenzilor, puteți vedea codul python care a fost înregistrat și, dacă doriți, modificați-l. Pentru a executa macrocomanda, apăsați butonul de execuție din bara de instrumente în timp ce macro-ul dvs. este în editor. Sunt întotdeauna salvate pe disc, astfel încât orice schimbare pe care o faceți sau orice macro nouă pe care o creați, va fi întotdeauna disponibilă data viitoare când porniți FreeCAD.

Press the record button, give a name, let's say "cylinder 10x10", then, in the Part Workbench, create a cylinder with radius = 10 and height = 10. Then, press the "stop recording" button. In the edit macros dialog, you can see the python code that has been recorded, and, if you want, make alterations to it. To execute your macro, simply press the execute button on the toolbar while your macro is in the editor. You macro is always saved to disk, so any change you make, or any new macro you create, will always be available next time you start FreeCAD.

Personalizare

Desigur, nu este practic să încărcați o macrocomandă în editor pentru a o folosi. FreeCAD oferă o modalitate mai bună de a utiliza macrocomanda, cum ar fi atribuirea unei comenzi rapide de la tastatură sau introducerea unei intrări în meniu. Odată ce ați creat macrocomanda, puteți face acest lucru prin meniul Instrumente -> Personalizare:

Of course it is not practical to load a macro in the editor in order to use it. FreeCAD provides much better ways to use your macro, such as assigning a keyboard shortcut to it or putting an entry in the menu. Once your macro is created, all this can be done via the Tools → Customize menu.

Customize ToolbarsÎn acest fel, puteți face ca macrocomanda să devină un instrument real, la fel ca orice instrument standard FreeCAD. Acest lucru, adăugat la puterea scripting-ului Python în cadrul FreeCAD, face posibilă adăugarea ușoară a propriilor instrumente la interfață. Citiți pagina Scripting dacă doriți să aflați mai multe despre scrierea Python ...

See Customize Toolbars for a more detailed description.

Crearea de macrocomenzi fără înregistrare

How to install macros De asemenea, puteți copia / lipi direct codul python într-o macrocomandă, fără a înregistra acțiunea GUI. Pur și simplu creați o macrocomandă nouă, editați-o și inserați-vă codul. Apoi puteți salva macro-ul dvs. în același mod în care salvați un document FreeCAD. Data viitoare când porniți FreeCAD, macroul va apărea sub elementul "Macro instalat" din meniul Macro.

You can also directly copy/paste python code into a macro, without recording GUI action. Simply create a new macro, edit it, and paste your code. You can then save your macro the same way as you save a FreeCAD document. Next time you start FreeCAD, the macro will appear under the "Installed Macros" item of the Macro menu.

See How to install macros for a more detailed description.

Depozitul de Macrocomenzi

Vizitați pagina Macros recipes pentru a alege unele macrocomenzi utile pentru a adăuga instalarea FreeCAD.

There are two main places for macros. The first one is the official peer-reviewed macro repository on GitHub. The second one is the Macros recipes page from which you can pick some useful macros to add to your FreeCAD installation. Macros from both repositories can be installed via the Addon Manager directly from FreeCAD.

You can manually install extensions, however, it is much simpler to just use the Addon Manager.


Standard Menu/ro
Introduction to Python/ro

Introducere în Python


Introduction

Acesta este un scurt tutorial pentru cei nou veniți în Python. Python is an open-source, multiplatform programming language. Python are mai multe caracteristici care o fac foarte diferită de alte limbaje și este foarte accesibil utilizatorilor noi ca tine:

  • A fost special conceput pentru a fi ușor de citit de ființe umane, și de aceea este foarte ușor de învățat și de înțeles.
  • Este un limbaj interpretat, este faptul că, spre deosebire de limbajele compilate cum ar fi C, programul nu trebuie să fie compilate înainte de a fi executat. Codul pe care îl scrieți, dacă doriți. Pentru că puteți merge încet, pas cu pas, este extrem de ușor de a învăța și de a găsi erori în cod.
  • Poate fi încorporat în alte programe pentru a fi folosit ca limbaj de scripting. FreeCAD are un interpretor Python încorporat; puteți scrie cod Python în freecad, Aceasta va Manipulează părți ale freecad, de exemplu, pentru a crea geometrie. Acest lucru este extrem de puternic, în loc de doar clic pe butonul închidere a Etichetat „creați sferă“ pe care unii ARE program de coduri; tu ai libertatea de a construi cu ușurință propriul instrument, care crează exact geometria dorită, într-o formă de și manieră pe care programatorul nu o putea prevedea.
  • Este extensibil, vă puteți conecta cu ușurință la funcționalitatea dvs. De exemplu,sunt modulele care permit Python-ului să citească și să scrie imagini jpg pentru a comunica cu Twitter, pentru a programa sarcinile care trebuie efectuate de sistemul de operare, etc.

Vă recomandăm cu tărie să introduceți fragmentele de cod de mai jos într-un interpret Python. Pentru multe dintre exemplele noastre, punctul important este linia după execuția codului, rezultatul. Și acum la muncă! Rețineți că următoarea este o introducere simplificată și, în nici un caz, un tutorial complet. Dar sperăm că după această lectură ați dobândit bazele necesare pentru a cunoaște și exploata mai profund mecanismele FreeCad.

Interpretorul

De obicei, când scrieți programe de calculator, deschideți pur și simplu un editor de text sau mediul de programare special (care este, de obicei, un editor de text cu mai multe instrumente suplimentare), scrieți programul, apoi compilați și executați. În mod obișnuit, au fost făcute una sau mai multe erori la intrare, astfel încât programul dvs. nu va funcționa. S-ar putea să primiți chiar și un mesaj de eroare care să vă spună ce sa întâmplat. Apoi, reveniți la editorul de text, corectați greșelile, executați din nou, repetând până când programul dvs. funcționează așa cum doriți.

Întregul proces, în Python, poate fi făcut transparent în interiorul interpretrului Python. Interpretorul este o fereastră Python cu un prompt de comandă, unde puteți introduce pur și simplu codul Python. Dacă instalați Python pe computerul dvs. (descărcați-l din Python website dacă sunteți pe Windows sau Mac, instalați-l din depozitul de pachete dacă sunteți pe GNU / Linux), veți avea un interpretor Python în meniul de pornire. Însă FreeCAD are și un interpretor Python în fereastra inferioară:

(Dacă nu o aveți, click pe View --> Panels --> Python console.)

Interpretorul arată versiune Python, apoi un simbol >>> , care este promptul comenzii, chiar așa, unde introduceți codul Python. Scrierea unui cod în interpretor este simplă: o linie este o instrucțiune. Când apăsați Enter, linia de cod va fi executată (după ce a fost compilată instant și netransparent pentru user). De exemplu, încercați să scrieți acest lucru:

print("hello")

print este un cuvânt cheie în Python care înseamnă ca, bineînțeles, că printezi ceva pe ecran. Când apeși Enter, operația este executată , și mesajul "hello" este afișat. Dacă faci o greșeală, să scriem de exemplu:

print(hello)

Python îți va spune că nu știe ce este hello . Ghilimelele " spun despre conținut că este un șir de caractere, care pur și simplu în jargonul informatic înseamnă o bucată de test. Fără ghilimele ", comanda de afișare a lui hello, acesta nu este recunoscut ca fiind un text , ci ca un cuvânt comandă special rezervat în Python.Important este că obțineți imediat o notificare de eroare. Apăsând săgeata sus (sau, în interpretorul FreeCAD CTRL+Săgeată sus), puteți merge înapoi la ultima comandă și să o scrieți corect.

Interpretorul Python dispune de asemenea de un sistem integrat de help. Încercați să tastați:

help("print")

Veți obține o descriere lungă și completă a tot ceea ce poate face comanda ”print”.

Acum că stăpânim total interpretorul nostru , putem începe lucrurile serioase.

Top

Varibile

Desigur, tipărirea lui "hello" nu este foarte interesantă. Mai interesant este să imprimați lucruri pe care nu le cunoșteați înainte sau să lăsați Python să le găsească pentru dvs. Aici vine conceptul de variabilă. O variabilă este pur și simplu o valoare pe care o stocați sub un nume. De exemplu, tastați:

a = "hello"
print(a)

Presupun că ați înțeles ce sa întâmplat, am "salvat" șirul "hello" într-o variabilă care poartă numele "a". Acum, "a" nu mai este un nume necunoscut! Putem să o folosim oriunde, de exemplu în comanda de afișare pe ecran. Putem folosi orice nume dorim, trebuie doar să urmați câteva reguli simple, cum ar fi nu folosiți spații sau punctuație. De exemplu, am putea scrie:

hello = "my own version of hello"
print(hello)

Vedeți? acum hello nu mai este un cuvânt nedefinit. Dacă, printr-un ghinion teribil, alegem un nume care există deja în Python? Să presupunem că dorim să stocăm șirul nostru sub numele "print":

myVariable = "hello"
print(myVariable)
myVariable = "good bye"
print(myVariable)

Noi am schimbat valoarea myVariable. Putem copia de asemenea variabile:

var1 = "hello"
var2 = var1
print(var2)

Rețineți că este important să oferiți nume descriptive variabilelor dvs. După un timp, nu vă veți aminti ce reprezintă variabila numită "a". Dar dacă l-ați numit, de exemplu, myWelcomeMessage, îți vei aminti cu ușurință scopul. Plus codul dvs. este un pas mai aproape de a fi auto-documentare.

Cazul este foarte important. myVariable nu este aceeași cu myvariable, diferența dintre majuscule / minuscule 'v' . Dacă trebuia să introduceți "print myvariable", s-ar întoarce cu o eroare pentru că nu a fost definită.

Top

Numere

Desigur, trebuie să știți că programarea este utilă pentru a trata toate tipurile de date, și mai ales numere, nu numai șiruri de text. Un lucru este important, Python trebuie să știe cu ce fel de date are de-a face. Am văzut în exemplul nostru de afișarea a lui ”hello”, că comanda de afișare a recunoscut șirul de caractere "hello". Acest lucru se datorează faptului că prin utilizarea ghilimelelor " ", am spus în mod specific că această comanda de afișare va trata un șir de caractere alfabetice (text).

Întotdeauna putem verifica tipul de date al unei variabile folosind cuvântul cheie special Python type():

myVar = "hello"
type(myVar)

Aceasta ne va spune că conținutul lui myVar este 'str', scurt pentru șir în jargonul Python. De asemenea, avem și alte tipuri de date de bază, cum ar fi numere întregi (integer) și cu virgulă flotantă (float)

firstNumber = 10
secondNumber = 20
print(firstNumber + secondNumber)
type(firstNumber)

Acest lucru este mult mai interesant, nu-i așa? Acum avem un calculator puternic! Uită-te la cât de bine funcționează, Python știe că 10 și 20 sunt numere întregi. Deci, ele sunt stocate ca "int", iar Python poate face cu ele tot ce poate face cu numere întregi. Uită-te la rezultatele de acest lucru:

firstNumber = "10"
secondNumber = "20"
print(firstNumber + secondNumber)

Vedeți? L-am forțat pe Python să considere că cele două variabile nu sunt numere, ci simple piese de text. Python poate adăuga două bucăți de text împreună, dar nu va încerca să afle nici o sumă. Dar am vorbit despre numere întregi. Există și numere cu virgulă. Diferența este că numerele întregi nu au o parte zecimală, în timp ce numerele cu virgulă flotantă pot avea o parte zecimală:

var1 = 13
var2 = 15.65
print("var1 is of type ", type(var1))
print("var2 is of type ", type(var2))

Int și Floats pot fi amestecate fără probleme:

total = var1 + var2
print(total)
print(type(total))

Desigur, totalul are zecimale, nu? Apoi, Python a decis automat că rezultatul este un număr cuzecimale. În mai multe cazuri, cum ar fi acesta, Python decide automat ce tip este de utilizat. În alte cazuri, nu. De exemplu:

varA = "hello 123"
varB = 456
print(varA + varB)

Acest lucru ne va da o eroare, varA este un șir și varB este un int, iar Python nu știe ce să facă. Cu toate acestea, putem forța Python să convertească între tipuri:

varA = "hello"
varB = 123
print(varA + str(varB))

Acum, ambele sunt șiruri, operația funcționează! Rețineți că am "convetit" varB în șir la momentul afișării, dar nu am schimbat varB în sine. Dacă vrem să transformăm varB permanent într-un șir, ar trebui să o facem așa:

varB = str(varB)

Putem de asemenea să utilizăm int() și float() pentru a converti în întreg și cu virgulă mobilă dacă dorim:

varA = "123"
print(int(varA))
print(float(varA))

Probabil că ați observat că în această secțiune am folosit comanda de afișare în mai multe moduri. Am tipărit variabile, sume, mai multe lucruri separate prin virgule și chiar rezultatul altor comenzi Python, cum ar fi type(). Poate că ați văzut de asemenea că făcând aceste două comenzi,

type(varA)
print(type(varA))

avem exact același rezultat. Asta pentru că suntem în interpretor și totul este afișat automat. Când scriem programe mai complexe care rulează în afara interpretorului, nu se vor imprima automat, deci va trebui să folosim comanda de afișare. De acum încolo, haideți să-l oprim aici, va merge mai repede. Deci putem scrie pur și simplu:

myVar = "hello friends"
myVar

Top

Liste/matrici

Un alt tip de date interesant este formată de către liste. O listă este pur și simplu o colecție de alte date. În același mod în care definim un șir de text folosind "", definim o listă folosind []:

myList = [1, 2, 3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

Vedeți că poate conține orice tip de date. Listele sunt foarte utile deoarece puteți grupa împreună variabilele. Puteți face apoi tot felul de lucruri din cadrul grupului, de exemplu, numărarea acestora:

len(myOtherList)

sau recuperarea unui articol dintr-o listă:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

Veți vedea că în timp ce comanda len () returnează numărul total de elemente dintr-o listă, poziția lor din listă începe cu 0. Primul element dintr-o listă este întotdeauna la poziția 0, așa că în "myOtherList", "Bob" va fi în poziția 2. Putem face mult mai mult cu listele, puteți citi here, ca de exemplu sortarea conținutului, ștergerea sau adăugarea elementelor.

Un lucru amuzant și interesant este acela că: un șir de text este foarte asemănător cu o listă de caractere! Încercați să faceți acest lucru:

myvar = "hello"
len(myvar)
myvar[2]

De obicei, ceea ce puteți face cu listele se poate face și cu șiruri de caractere. De fapt, atât listele cât și șirurile sunt secvențe pe care Python le vede în aceeași manieră.

Outside strings, ints, floats and lists, există mai multe tipuri de date încorporate, cum ar fi dictionaries, sau care le puteți crea ca pe propriile tipuri de date cu classes.

Top

Indentation

O mare utilizare rece a listelor este, de asemenea, navigarea prin ele și să facă ceva cu fiecare element. De exemplu, uitați-vă la acest lucru:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
    print(dalton + " Dalton")

Am iterat(jargonul informatic) prin lista noastră cu comanda "for ... in ..." și am făcut ceva cu fiecare dintre ele. Rețineți sintaxa specială: comanda for se termină cu : indicând că următorul lucru va fi un bloc al uneia sau mai multor comenzi. În interpretor, imediat după ce ați introdus linia de comandă care se termină cu:, promptul de comandă se va schimba la ... Notați sintaxa particulară a buclei , comanda se termină cu un " : " ceea ce indică lui Python că urmarea va fi un bloc de una sau mai multe comenzi.

Cum va ști Python câte linii vor fi executate în interiorul buclei FOR ... IN ? Pentru asta, Python utilizează indentare. Adică liniile următoare nu vor începe imediat. Veți începe cu un spațiu gol sau mai multe spații goale sau un tab sau câteva tabs. Alte limbaje de programare utilizează alte metode, cum ar fi punerea totul în paranteză etc. Atâta timp cât scrieți liniile următoare cu aceeași indentare same , ele vor fi considerate parte a blocului for-in. Dacă începeți o linie cu 2 spații și următoarea cu 4, va exista o eroare. Când ați terminat, scrieți o altă linie fără indentare sau apăsați pe Enter pentru a reveni din blocul for-in.

Indentarea este cool, deoarece ajută la lizibilitatea programului. Dacă utilizați indentări mari (de exemplu, utilizați tabs în loc de spații deoarece este mai mare), atunci când scrieți un program mare, veți avea o imagine clară a ceea ce este executat în interiorul a buclei for-in. Vom vedea că comenzile, altele decât cele for-in, pot avea și blocuri de cod.

Comenzile for-in pot fi folosite pentru mai multe lucruri care trebuie efectuate mai mult decât o dată. Acesta poate fi, de exemplu, combinat cu comanda range():

serie = range(1, 11)
total = 0
print("sum")
for number in serie:
    print(number)
    total = total + number
print("----")
print(total)

(Dacă ați executat exemplele de cod într-un interpretor prin copy and paste, veți găsi că blocul anterior de text vă va arunca o eroare în față. În schimb, copiați la sfârșitul blocului indentat, adică sfârșitul liniei "" total = total + number "și apoi lipiți la interpretor păsați pe <enter> până până la dispariția promptului cu trei puncte și codul se execută Apoi, copiați ultimele două linii în interpretor urmate de una sau mai multe <enter> ar trebui să apară răspunsul final.)

Dacă veți tasta în interpretor help(range) veți vedea:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Aici parantezele pătrate denotă un parametru opțional. Totuși tot ce se așteptă este să fie numere întregi. Mai jos vom forța parametrii domeniului să fie un număr întreg folosind int()

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the step parameter to be an integer using int():

number = 1000
for i in range(0, 180 * number, int(0.5 * number)):
    print(float(i) / number)

Sau lucruri mai complexe ca de exemplu:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
    print(alldaltons[n], " is Dalton number ", n)

Vedeți că și comanda range () are acea particularitate ciudată că începe cu 0 (dacă nu specificați numărul de început) și că ultimul său număr va fi unul mai mic decât numărul de sfârșit pe care îl specificați. Aceasta este, bineînțeles, așa pentru că funcționează bine cu alte comenzi Python. De exemplu:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
    print(alldaltons[n])

O altă utilizare interesantă a blocurilor indentate este cu comanda if. IF execută un bloc de cod numai dacă o anumită condiție este îndeplinită, de exemplu:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
    print("We found that Dalton!!!")

Desigur, aceasta va imprima întotdeauna prima propoziție, dar încercați să înlocuiți a doua linie prin:

if "Lucky" in alldaltons:

Apoi nimic nu este afișat. De asemenea, putem specifica o altă afirmație

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
    print("We found that Dalton!!!")
else:
    print("Such Dalton doesn't exist!")

Top

Funcții

Sunt câteva comenzi standard standard Python commands. În versiunea actuală a Python, există aproximativ 30, iar noi deja știm mai multe dintre ele. Dar imaginați-vă dacă am putea să ne inventăm propriile comenzi? Ei bine, putem, și este extrem de ușor. De fapt, majoritatea modulelor suplimentare pe care le puteți conecta la instalarea dvs. Python faceți exact acest lucru, adăugând comenzi pe care le puteți utiliza. O comandă personalizată în Python se numește o funcție și se face astfel:

def printsqm(myValue):
    print(str(myValue) + " square meters")

printsqm(45)

Extrem de simplu: comanda def () definește o nouă funcție. Dă-i un nume, iar în paranteză definiți argumente pe care le vom folosi în funcția noastră. Argumentele sunt date care vor fi transmise funcției. De exemplu, uitați-vă la comanda len (). Dacă scrieți len () singur, Python vă va spune că are nevoie de un argument. Asta este, vrei len () ceva, nu? Apoi, de exemplu, veți scrie len (myList) și veți obține lungimea myList. Ei bine, lista mea este un argument să-l treci la funcția len (). Funcția len () este definită astfel încât să știe ce să facă cu ceea ce este transmis acesteia. La fel cum am făcut aici.

Numele "myValue" poate fi orice, și va fi utilizat numai în interiorul funcției rexpective. Este doar un nume pe care îl oferiți argumentului, astfel încât să puteți face ceva cu el, dar servește și pentru a spune funcției câte argumente să așteptați. De exemplu, dacă faceți acest lucru:

printsqm(45, 34)

Va exista o eroare. Funcția noastră a fost programată să primească un singur argument, dar a primit două, 45 și 34. Am putea să facem ceva în felul următor:

def sum(val1, val2):
    total = val1 + val2
    return total

myTotal = sum(45, 34)

Am făcut o funcție care primește două argumente, le însumează și returnează acea valoare. Returnarea a ceva este foarte utilă, deoarece putem face ceva cu rezultatul, cum ar fi stocarea în variabila myTotal. Bineînțeles, din moment ce suntem în interpretor și totul este afișat, faci:

Top

Module

Acum că avem o idee completă de cum lucrează Python, vom avea nevoie de un ultim lucru: Cum să lucrăm cu fișiere și cu module.

Până acum, am scris linii de instrucțiuni Python în linie în interpretor, nu-i așa? Dacă am putea scrie câteva rânduri împreună și le-am fi executat imediat? Cu siguranță ar fi mai ușor să facem lucruri mai complexe. Și ne-am putea salva munca. Și asta este extrem de ușor. Pur și simplu deschideți un editor de text (cum ar fi notepad-ul din Windows, sub Linux: gedit, emacs sau vi) și scrieți toate liniile dvs. Python, la fel cum le scrieți în interpretor, cu indentări etc. , Apoi salvați fișierul undeva, de preferință cu o extensie .py. Asta e, aveți un program Python complet. Desigur, există editori mult mai buni decât notepad-ul, dar aceasta este doar să vă arătăm că un program Python nu este altceva decât un fișier text.

Pentru a face Python să execute acel program, există sute de moduri. În Windows, pur și simplu faceți clic dreapta pe fișierul dvs., deschideți-l cu Python și executați-l. Dar o puteți executa și din interpretorul Python. Pentru aceasta, interpretorul trebuie să știe unde este programul dvs. .py. În FreeCAD, cel mai simplu mod este să plasați programul într-un loc în care interpretul Python al FreeCAD îl cunoaște în mod implicit, ca de exemplu FreeCAD's bin folder, sau orice folder Mod. (In Linux, aveți probabil un director /home/<username>/.FreeCAD/Mod, haideți să-i adăugăm un subdirector to that called scripts unde vom pune fișierul text.) Presupunem că scriem fișierul de maniera:

def sum(a,b):
    return a + b

print("myTest.py succesfully loaded")

Și noi salvăm asta ca pe myTest.py în direcotrul nostru FreeCAD/bin directory (sau în Linux la /home/<username>/.FreeCAD/Mod/scripts.) Acum , hai să pornim FreeCAD, și în fereastra interpretorului, scrie :

import myTest

fără extensia .py . Aceasta va executa pur și simplu conținutul fișierului, linie cu linie, ca și cum l-am fi scris în interpret. Se va crea funcția sumă, iar mesajul va fi imprimat. Există o mare diferență: comanda de import este făcută nu numai pentru a executa programe scrise în fișiere, ca și pentru ale noastre, dar și pentru a încărca funcțiile din interior, astfel încât acestea să devină disponibile în interpretor. Fișierele care conțin funcții, precum cele ale noastre, sunt numite module.

În mod normal când scrii o funcție sum() in interpreter, noi o executăm simplu ca:

sum(14, 45)

La el am făcut și noi. Atunci când importăm un modul care conține funcția sum(), sintaxa este puțin diferită. Noi facem:

myTest.sum(14, 45)

Asta e, modulul este importat ca un "container", și cu toate funcțiile sale în interior. Acest lucru este extrem de util, deoarece putem importa o mulțime de module și să păstrăm totul bine organizat. Deci, practic, oriunde vedeți something.somethingElse, cu punct între, asta înseamnă că somethingElse este în interiorul lui something.

De asemenea, putem importa funcția sum() direct în spațiul principal al interpretorului, astfel:

from myTest import *
sum(12, 54)

Practic, toate modulele se comportă așa. Importați un modul, apoi puteți utiliza funcțiile sale: module.function(argument). Aproape toate modulele fac acest lucru: definesc funcții, noi tipuri de date și clase pe care le puteți utiliza în interpretor sau în propriile module Python, deoarece nimic nu vă împiedică să importați alte module în modulul dvs.!

Un ultim lucru extrem de util. Cum știm ce module avem, ce funcții există și cum să le folosim (adică, ce argumente au nevoie)? Am văzut deja că Python are o funcție help(). Face:

help("modules")

Ne va da o lista cu toate modulele disponibile. Acum putem introduce q pentru a ieși din ajutorul interactiv și pentru a importa oricare dintre ele. Putem chiar să răsfoim conținutul lor cu comanda dir()

import math
dir(math)

Vom vedea toate funcțiile conținute în modulul de matematică, precum și lucruri ciudate named __doc__, __file__, __name__. The __doc__ is extrem de utili, este un text de comentariu. Orice funcție a unui modul binefăcut are a __doc__ that care explică cum se folosește. De exemplu, vedem că este o funcție sin în interiorul modului de matematică. Vreți să știți cum se folosește?

print(math.sin.__doc__)

(Este posibil să nu fie evident, dar din ambele părți ale docului există două caractere subliniate.)

Și în cele din urmă o bombonică: Când lucrăm la un modul nou sau existent, este mai bine să înlocuiți extensia de fișier cu py cum ar fi: myModule.FCMacro => myModule.py. Vrem adesea să o testeze astfel încât să o încărcăm ca mai sus.

import importlib
importlib.reload(myTest)

Cu toate acestea, există două alternative: în cadrul macro-ului se utilizează funcțiile exec sau execfile ale lui Python.

exec(open("C:/PathToMyMacro/myMacro.FCMacro").read())

Top

Începeți cu FreeCAD

Ei bine, cred că acum aveți o idee bună despre modul în care funcționează Python și puteți începe să explorați ce oferă FreeCAD. Funcțiile Python ale FreeCAD sunt bine organizate în diferite module. Unele dintre ele sunt deja încărcate (importate) când porniți FreeCAD. Deci, pur și simplu

dir()

Top

Notes

  • FreeCAD was originally designed to work with Python 2. Since Python 2 reached the end of its life in 2020, future development of FreeCAD will be done exclusively with Python 3, and backwards compatibility will not be supported.
  • Much more information about Python can be found in the official Python tutorial and the official Python reference.

Top

Macros
Python scripting tutorial


Programarea script Python in FreeCAD

FreeCAD este construit de la zero pentru a fi controlat total de scripturile Python. Aproape toate componentele FreeCAD, cum ar fi interfața, conținutul scenelor și chiar reprezentarea acestui conținut în vizualizările 3D, sunt accesibile din interpretorul Python încorporat sau din propriile dvs. scripturi. Drept urmare, FreeCAD este probabil una dintre aplicațiile de inginerie cele mai profunde disponibile astăzi.

FreeCAD is built from scratch to be totally controlled by Python scripts. Almost all parts of FreeCAD, such as the interface, the scene contents, and even the representation of this content in the 3D views, are accessible from the built-in Python interpreter or from your own scripts. As a result, FreeCAD is probably one of the most deeply customizable engineering applications available today.

Dacă nu sunteți familiarizat cu Python, vă recomandăm să căutați tutoriale pe internet și să vă aruncați o privire rapidă asupra structurii sale. Python este un limbaj de programare foarte ușor de învățat, mai ales pentru că poate fi rulat în interiorul unui interpretor, unde comenzile simple, chiar până la finalizarea programelor, pot fi executate în zbor fără a fi nevoie să compilați nimic. FreeCAD are un interpretor Python încorporat. Dacă nu vedeți fereastra etichetată "Consola Python" așa cum se arată mai jos, o puteți activa sub consola View -> Panels -> Python pentru a deschide interpretorul.

Interpretorul

Din interpretor, puteți accesa toate modulele Python instalate de sistem, precum și modulele FreeCAD încorporate și toate modulele FreeCAD suplimentare instalate ulterior. Imaginea de mai jos prezintă interpretorul Python:

From the interpreter, you can access all your system-installed Python modules, as well as the built-in FreeCAD modules, and all additional FreeCAD modules you installed later. The screenshot below shows the Python interpreter:

The FreeCAD Python interpreter

Din interpretor, puteți executa codul Python și puteți naviga prin clasele și funcțiile disponibile. FreeCAD oferă un browser al claselor foarte util pentru explorarea noii tale lumi FreeCAD: Când introduceți numele unei clase cunoscute, urmată de un punct (adică doriți să adăugați ceva din acea clasă), se deschide o fereastră de browser de clasă, unde puteți naviga între subclasele și metodele disponibile. Când selectați ceva, este afișat un text de ajutor asociat (dacă există):

The FreeCAD class browser

Așa că, începeți aici tastând App. ori Gui. și priviți ce e tâmplă. O altă modalitate mai generală de a explora conținutul modulelor și claselor este utilizarea comenenzii Python'print dir()'. De exemplu, tastați print dir() și veți obține o listă a tuturor modulelor încărcat curent în FreeCAD. print dir(App) vă va arăta tot ceea ce este în interiorul modulelro App, etc.

O altă caracteristică utilă a interpretului este posibilitatea de a reveni prin istoria comenzilor și de a recupera o linie de cod pe care ați introdus-o deja mai devreme. Pentru a naviga prin istoricul comenzilor, trebuie doar să le utilizați CTRL+UP or CTRL+DOWN.

Dacă faceți clic dreapta în fereastra interpretului, aveți și alte câteva opțiuni, cum ar fi copierea întregului istoric (util atunci când doriți să experimentați lucrurile înainte de a face un script complet al acestora) sau introduceți un nume de fișier cu cale completă.

Top

Python Help

În meniul de ajutor al FreeCAD veți găsi o intrare intitulată "Ajutor Python", care va deschide o fereastră de browser care conține o documentație completă, generată în timp real, a tuturor modulelor Python disponibile pentru interpretorul FreeCAD, inclusiv modulele Python și FreeCAD încorporate , modulele instalate în sistem și modulele suplimentare FreeCAD. Documentația disponibilă depinde de efortul fiecărui dezvoltator de module în documentarea codului său, dar, de obicei, modulele Python au o reputație de a fi destul de bine documentate. Fereastra FreeCAD trebuie să rămână deschisă pentru ca acest sistem de documentare să funcționeze.

In the FreeCAD Help menu, you'll find an entry labeled Automatic python modules documentation, which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work. The entry Python scripting documentation will give you a quick link to the Power users hub wiki section.

Top

Module integrate

Deoarece FreeCAD este proiectat să ruleze fără o interfață grafică de utilizator (GUI), aproape toate funcționalitățile sale sunt separate în două grupuri: funcționalitatea Core, numită "App", și funcționalitatea GUI, numită "Gui". Deci, cele două module principale FreeCAD încorporate se numesc App și Gui. Aceste două module pot fi accesate, de asemenea, din scripturile din afara interpretului, prin numele "FreeCAD" și respectiv "FreeCADGui".

Since FreeCAD is designed so that it can also be run without a Graphical User Interface (GUI), almost all its functionality is separated into two groups: Core functionality, named App, and GUI functionality, named Gui. These two modules can also be accessed from scripts outside of the interpreter, by the names FreeCAD and FreeCADGui respectively.

  • In App module, veți găsi totul în legătură cu aplicația în sine, cum ar fi metodele de deschidere sau închidere a fișierelor și documentelor, cum ar fi setarea documentului activ sau listarea conținutului acestuia.
  • In Gui module, veți găsi instrumente pentru accesarea și gestionarea elementelor Gui, cum ar fi Atelierele de lucru și barele lor de instrumente și, mai interesant, reprezentarea grafică a conținutului FreeCAD.

Afișarea întregului conținut al acestor module este o sarcină puțin contraproductivă, deoarece acestea cresc destul de repede cu dezvoltarea FreeCAD. Dar cele două instrumente de navigare furnizate (browserul de clasă și Python help) vă vor oferi, în orice moment, o documentație completă și actualizată a acestor module.

Top

Obiectele App și Gui

Așa cum am spus, în FreeCAD, totul este separat între nucleu și reprezentare. Aceasta include și obiectele 3D. Puteți accesa definirea proprietăților obiectelor (numite funcții în FreeCAD) prin modulul App și modificați modul în care sunt reprezentate pe ecran prin modulul Gui. De exemplu, un cub are proprietăți care îl definesc (cum ar fi lățimea, lungimea, înălțimea) stocate într-un obiect App și proprietăți de reprezentare (cum ar fi culoarea fețetelor, modul de desenare) stocate într-un obiect Gui corespunzător.

As already mentioned, in FreeCAD everything is separated into core and representation. This includes the 3D objects. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it (like width, length, height) that are stored in an App object, and representation properties (like faces color, drawing mode) that are stored in a corresponding Gui object.

Acest mod de a face lucrurile permite o gamă largă de utilizări, cum ar fi ca algoritmii să funcționeze numai pe partea de definire a caracteristicilor, fără a avea nevoie să aibă grijă de nicio parte vizuală sau chiar să redirecționeze conținutul documentului la o aplicație non-grafică ca liste, foi de calcul sau analiza elementului finit.

Pentru fiecare obiect App din document, există un obiect Gui corespunzător. De fapt documentul în sine are atât obiecte App cât și obiecte Gui. Acest lucru, desigur, este valabil numai când rulați FreeCAD cu interfața sa completă. În versiunea de linie de comandă nu există nici o interfață grafică, astfel încât numai obiectele App sunt disponibile. Rețineți că partea Gui a obiectelor este re-generată de fiecare dată când un obiect App este marcat ca fiind "pentru a fi recalculat" (de exemplu, când unul dintre parametrii lui se modifică), astfel încât modificările pe care le-ați fi putut face direct la obiectul Gui pot fi pierdute.

Pentru a acesa partea App a unui obiect oarecare, scrieți:

myObject = App.ActiveDocument.getObject("ObjectName")

unde "ObjectName" este numele obiectului dvs. Puteți de asemenea tasta:

myObject = App.ActiveDocument.ObjectName

Pentru a accesa partea Gui a aceluiași obiect, scrieți:

myViewObject = Gui.ActiveDocument.getObject("ObjectName")

unde "ObjectName" este numele obeictului duvs. Puteți de asemena tasta:

myViewObject = App.ActiveDocument.ObjectName.ViewObject

Dacă nu aveți nici un GUI (de exemplul sunten în modul linie-de-comandă), ultima linie va returna 'None'.

Top

Obiectele Documentului

În FreeCAD, toată munca dvs. se află în interiorul Documentelor. Un document conține geometria și poate fi salvat într-un fișier. Mai multe documente pot fi deschise în același timp. Documentul, ca geometria conținută în interior, are obiecte App și Gui. Obiectul App conține definițiile de geometrie reale, în timp ce obiectul Gui conține vederile diferite ale documentului. Puteți deschide mai multe ferestre, fiecare vizionând munca dvs. cu un alt factor de zoom sau unghi de vedere diferit. Aceste viziuni fac parte din obiectul Gui al documentului dvs.

In FreeCAD all your work resides inside documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. The App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or from a different direction. These views are all part of your document's Gui object.

Pentru a accesa partea App a documentului curent deschis (activ), scrieți:

myDocument = App.ActiveDocument

Pentru a crea un nou documente, scrieți:

myDocument = App.newDocument("Document Name")

Pentru a accesa partea Gui documentul deschis (activ), tastați:

myGuiDocument = Gui.ActiveDocument

Pentru a accesa vederea curentă, scrieți:

myView = Gui.ActiveDocument.ActiveView

Top

Utilizarea de module adiționale

Modulele FreeCAD și FreeCADGui sunt singurele responsabile pentru crearea și gestionarea obiectelor din documentul FreeCAD. Ele nu fac de fapt nimic, cum ar fi crearea sau modificarea geometriei. Aceasta deoarece această geometrie poate fi de mai multe tipuri și astfel este gestionată de module suplimentare, fiecare responsabil pentru gestionarea unui anumit tip de geometrie. De exemplu, Part Workbench utilizează kernelul OpenCascade și, prin urmare, este capabil să creeze și să manipuleze B-rep type geometry, ceea ce este construit pentru OpenCascade. Modul Mesh Workbench poate construi și modifica obiecte tip plase. În acest fel, FreeCAD este capabil să gestioneze o mare varietate de tipuri de obiecte, care pot coexista în același document, iar noi tipuri pot fi adăugate cu ușurință în viitor.

The FreeCAD and FreeCADGui modules are only responsible for creating and managing objects in the FreeCAD document. They don't actually do anything more such as creating or modifying geometry. This is because that geometry can be of several types, and therefore requires additional modules, each responsible for managing a certain geometry type. For example, the Part Workbench, using the OpenCascade kernel, is able to create and manipulate BRep type geometry. Whereas the Mesh Workbench is able to build and modify mesh objects. In this manner FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types can easily be added in the future.

Top

Crearea obiectelor

Fiecare modul are propriul mod de a trata geometria sa, dar un lucru pe care, de obicei, pot să-l facă este să creeze obiecte în document. Dar documentul FreeCAD este, de asemenea, conștient de tipurile de obiecte disponibile furnizate de module:

Each module has its own way of dealing with geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:

FreeCAD.ActiveDocument.supportedTypes()

vă va lista toate obiectele posibile pe care le puteți crea. De exemplu, să creăm o plasă (tratată de modulul Mesh/Plasă) și o Piesă (tratată de modulul Part/Piesă):

myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "myMeshName")
myPart = FreeCAD.ActiveDocument.addObject("Part::Feature", "myPartName")

Primul argument este tipul de obiect, al doilea este numele obiectului. Cele două obiecte arată aproape la fel: nu conțin încă nicio geometrie și majoritatea proprietăților lor sunt aceleași când le inspectați cu dir(myMesh) și dir(myPart). Cu o excepție, myMesh are o proprietate "Mesh" și "Part" are o proprietate "Shape". Acesta este locul în care sunt stocate datele de Plasă și Piesă. De exemplu, să creăm un cub Part și să îl stocăm în obiectul myPart:

import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube

Puteți încerca să stocați cubul în interiorul proprietății Mesh-ului obiectului myMesh, va veni o eroare în care se plânge despre tipul greșit. Aceasta se datorează faptului că aceste proprietăți sunt făcute pentru a stoca numai un anumit tip. În proprietatea MyMesh a Mesh, puteți salva numai chestii create cu modulul Mesh. Rețineți că majoritatea modulelor au, de asemenea, o comandă rapidă pentru a adăuga geometria lor la document:

import Part
cube = Part.makeBox(2, 2, 2)
Part.show(cube)

Top

Modificarea obiectelor

Modificarea unui obiect este făcută în același mod:

Modifying an object is done in the same way:

import Part
cube = Part.makeBox(2, 2, 2)
myPart.Shape = cube

Acum, să schimbăm forma printr-o formă mai mare:

biggercube = Part.makeBox(5, 5, 5)
myPart.Shape = biggercube

Top

Interogarea obiectelor

Puteți să vă uitați mereu la tipul de obiect ca acesta:

You can always look at the type of an object like this:

myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
print(myObj.TypeId)

sau să știm dacă un obiect este derivat dintr-unul dintre cele de bază (Part Feature, Mesh Feature, etc):

print(myObj.isDerivedFrom("Part::Feature"))

Acum puteți începe să jucați cu FreeCAD! Pentru a vedea ce puteți face cu Part Workbench, citiți pagina Pare scripting, sau pagina Mesh Scriptingpentru a lucra cu Mesh Workbench.Rețineți că, deși modulele Parte și Mesh sunt cele mai complete și utilizate pe scară largă, alte module cum ar fi Draft Workbench au, de asemenea, scripting APIs care vă pate fi utili.Pentru o listă completă a fiecărui modul și a instrumentelor disponibile, vizitați secțiunea Category:API.

Top

Python scripting tutorial
Mesh Scripting


Introducere

Înainte de toate trebuie să importați un modul Mesh:

To get access to the Mesh module you have to import it first:

import Mesh

Creație și Încărcare

Pentru a crea un obiectr vid Plasă utilizați construcția standard:

To create an empty mesh object just use the standard constructor:

mesh = Mesh.Mesh()

Puteți crea un obiect din fișierul

mesh = Mesh.Mesh("D:/temp/Something.stl")

Sau o creați dintr-un set de triunghiuri descris de către punctele de colț:

triangles = [
# triangle 1
[-0.5000, -0.5000, 0.0000], [0.5000, 0.5000, 0.0000], [-0.5000, 0.5000, 0.0000],
#triangle 2
[-0.5000, -0.5000, 0.0000], [0.5000, -0.5000, 0.0000], [0.5000, 0.5000, 0.0000],
]
meshObject = Mesh.Mesh(triangles)
Mesh.show(meshObject)

Mesh-Kernel are grijă de o structură topologică corectă a datelor prin sortare

împreună a punctelor și marginilor coincidente.

Top

Modelare

Pentru a crea geometrii obișnuite, puteți utiliza scriptul Python BuildRegularGeoms.py.

To create regular geometries you can use one of the create*() methods. A torus, for instance, can be created as follows:

m = Mesh.createTorus(8.0, 2.0, 50)
Mesh.show(m)

Primii doi parametri definesc razele toroidului, iar al treilea parametru este un factor de subeșantionare pentru câte triunghiuri sunt create. Cu cât această valoare este mai mare cu atât este mai lină și cu cât este mai groasă corpul. Clasa Mesh oferă un set de funcții booleene care pot fi utilizate în scopuri de modelare. Oferă uniune, intersecție și diferență de două obiecte de plasă.

The Mesh module also provides three Boolean methods: union(), intersection() and difference():

m1, m2              # are the input mesh objects
m3 = Mesh.Mesh(m1)  # create a copy of m1
m3.unite(m2)        # union of m1 and m2, the result is stored in m3
m4 = Mesh.Mesh(m1)
m4.intersect(m2)    # intersection of m1 and m2
m5 = Mesh.Mesh(m1)
m5.difference(m2)   # the difference of m1 and m2
m6 = Mesh.Mesh(m2)
m6.difference(m1)   # the difference of m2 and m1, usually the result is different to m5

În cele din urmă, un exemplu complet al intersecției între o sferă și un cilindru care intersectează sfera.

import FreeCAD, Mesh
cylA = Mesh.createCylinder(2.0, 10.0, True, 1.0, 36)
cylB = Mesh.createCylinder(1.0, 12.0, True, 1.0, 36)
cylB.Placement.Base = (FreeCAD.Vector(-1, 0, 0)) # move cylB to avoid co-planar faces
pipe = cylA
pipe = pipe.difference(cylB)
pipe.flipNormals() # somehow required
doc = FreeCAD.ActiveDocument
obj = d.addObject("Mesh::Feature", "Pipe")
obj.Mesh = pipe
doc.recompute()

Top

Odds and Ends

O extensie (deși greu de folosit) de scripting Mesh sunt script-urile de testare a Mesh-Module. În această unitate se fac toate testele de compilare și sunt manipulate toate proprietățile și atributele. Cine are curaj îndeajuns, poate privi la Unit Test module.

An extensive, though hard to use, source of mesh related scripting are the unit test scripts of the Mesh module. In these unit tests literally all methods are called and all properties/attributes are tweaked. So if you are bold enough, take a look at the Unit Test module.

See also Mesh API

Top


Introducere

Aici vă vom explica cum să controlați Part Workbench direct de la interpretorul FreeCAD Python sau de la orice script extern. Elementele de bază despre programarea script datelor topologice sunt descrise în Part Module Explaining the concepts. fiți siguri că a-ți răsfoit secțiunea Scripting și paginile FreeCAD Scripting Basics dacă aveți nevoie de mai multe informații despre cum funcționaează programarea python in FreeCAD.

Here we will explain to you how to control the Part module directly from the FreeCAD Python interpreter, or from any external script. Be sure to browse the Scripting section and the FreeCAD Scripting Basics pages if you need more information about how Python scripting works in FreeCAD. If you are new to Python, it is a good idea to first read the Introduction to Python.

See also

Class Diagram

Aceasta Unified Modeling Language (UML) o trecere în revistă a celor mai importante clase a modului Piese:

Python classes of the Part module
Python classes of the Part module

This is a Unified Modeling Language (UML) overview of the most important classes of the Part module: Python classes of the Part module

Top

Geometrie

Obiectele geometrice reprezintă blocul de construcție al tuturor obiectelor topologice:

  • Geom Clasă de bază a obiectelor geometrice
  • Line o linie dreaptă în 3D, definită de punctul de plecare și de cel de sosire
  • Circle Cerc sau arc de cerc definit prin centru și punctele de start și de finiș
  • ...... Și în curând mai multe

The geometric objects are the building blocks of all topological objects:

  • Geom Base class of the geometric objects.
  • Line A straight line in 3D, defined by starting point and end point.
  • Circle Circle or circle segment defined by a center point and start and end point.
  • Etc.

Top

Topologie

Următoarele date topologice sunt disponibile:

  • Compound Un grup al oricărui tip de obiect topologic.
  • Compsolid Un solid compozit este un set de solide conectate prin fațetele lor. Extinde noțiunile de WIRE și SHELL la solide.
  • Solid O partea a spațiului limitată de cochilii. Are trei dimensiuni
  • Shell Un set da fațete conectate prin muchiile lor. O cochilie poate fi deschisă sau închisă.
  • Face In 2D este o parte a unui plan; in 3D este o parte a unei suprafețe.

Geometria sa este constrânsă(tăiată) de contururi. Este bidimensională.

  • Wire Un set de margini conectate prin vârfurile lor. Poate fi un contur deschis sau închis, în funcție de faptul dacă marginile sunt legate sau nu.
  • Edge Un element topologic corespunzător unei curbe reținute. O margine este în general limitată de vârfuri. Este unidimensională.
  • Vertex Un element topologic corespunzător unui punct. Are dimensiune zero.
  • Shape Un termen generic care acoperă toate cele de mai sus.

The following topological data types are available:

  • Compound A group of any type of topological objects.
  • Compsolid A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids.
  • Solid A part of space limited by shells. It is three dimensional.
  • Shell A set of faces connected by their edges. A shell can be open or closed.
  • Face In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional.
  • Wire A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not.
  • Edge A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension.
  • Vertex A topological element corresponding to a point. It has zero dimension.
  • Shape A generic term covering all of the above.

Top

Exemplul rapid: crearea unei topologii simple

Wire

Acum vom crea o topologie construind-o din geometrie mai simplă. Ca studiu de caz, folosim o parte din imaginea din care face parte patru vârfuri, două cercuri și două linii.

Top

Crearea Geometriei

Mai întâi trebuie să creăm părțile geometrice distincte ale acestui fir. Și trebuie să avem grijă de vârfurile părților geometrice se se afle în aceeași poziție. Altfel, mai târziu, s-ar putea să nu fim capabil să conectăm părțile geometrice la o topologie!

First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices.

Așa creăm primul dintre puncte:

import FreeCAD as App
import Part
V1 = App.Vector(0, 10, 0)
V2 = App.Vector(30, 10, 0)
V3 = App.Vector(30, -10, 0)
V4 = App.Vector(0, -10, 0)

Top

Arc

Circle


Pentru a crea un arc de cerc vom face un punct ca reper și vom crea arcul de cerc prin trei puncte:

VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
VC2 = App.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)

Top

Linie

Line


Segmentul de linie poate fi creat foarte simplu din punctele:

L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)

Top

Punem totul laolaltă

Ultimul pas este de a conecta elementele geometrice de bază împreună într-o forma topologică:

The last step is to put the geometric base elements together and bake a topological shape:

S1 = Part.Shape([C1, L1, C2, L2])

Top

Facem o prismă

Acum extrudem firul într-o direcție și facem o formă 3D :

Now extrude the wire in a direction and make an actual 3D shape:

W = Part.Wire(S1.Edges)
P = W.extrude(App.Vector(0, 0, 10))

Top

Afișăm totul

Part.show(P)

Top

Crearea formelor de bază

Puteți crea cu ușurință obiecte topologice de bază cu ajutorul funcției "Make ... ()" metode de la modulul Part:

You can easily create basic topological objects with the make...() methods from the Part module:

b = Part.makeBox(100, 100, 100)
Part.show(b)

Câteva metode disponibile de make...() :

  • makeBox(l,w,h): Construirea unui paralelipiped localizat în punctul p orientat în direcția d având dimensiunile (l,w,h)
  • makeCircle(radius): Construirea cercului cu o rază dată
  • makeCone(radius1,radius2,height): Construirea unui con cu (raza1,raza2,înălțime)
  • makeCylinder(radius,height): Construirea unui cilindru cunoscând raza și înălțimea.
  • makeLine((x1,y1,z1),(x2,y2,z2)): Construirea unei linii între 2 puncte
  • makePlane(length,width): construirea unui plan cunoscând lungimea și lățimea
  • makePolygon(list): construirea unui poligon având o listă de puncte
  • makeSphere(radius): Construirea unei sfere de rază dată
  • makeTorus(radius1,radius2): construirea unui torus cuoscând raza 1 și raza 2

Vezi pagina Part API pentru o listă completa a metodelor disponibile în modulul Part.

Top

Importare modulelor necesare

Mai întâi trebuie să importăm modulul Part astfel încât să putem folosi conținutul său în Python. De asemenea, vom importa modulul Base din interiorul modulului FreeCAD:

First we need to import the FreeCAD and Part modules so we can use their contents in Python:

import FreeCAD as App
import Part

Top

Crearea unui Vector

Vectorssunt una dintre cele mai importante piese de informații când construim forme geometrice. Acestea conțin 3 numere de obicei (dar nu este obligatoriu întotdeauna) coordonatele carteziene x, y și z. Creați un vector ca acesta:

Vectors are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this:

myVector = App.Vector(3, 2, 0)

Tocmai am creat un vector la coordonatele x = 3, y = 2, z = 0. În modulul Part, vectorii sunt folosiți peste tot. Formele de Piese utilizează de asemenea un alt tip de punct reprezentare, numită Vertex, care nu este nimic altceva decât un container pentru un vector. Accesați vectorul unui vârf ca acesta:

myVertex = myShape.Vertexes[0]
print(myVertex.Point)
> Vector (3, 2, 0)

Top

Crearea unei muchii

O margine nu este altceva decât o linie cu două vârfuri:

An edge is nothing but a line with two vertices:

edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]

Notă: De asemenea, puteți crea o margine definită de doi vectori:

vec1 = App.Vector(0, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()

Puteți găsi lungimea și centrul unei muchii astfel:

edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)

Top

Afișarea formei pe ecran

Până acum, am creat un obiect de margine, dar nu apare nicăieri pe ecran. Acest lucru se datorează faptului că doar am manipulat obiectele de tip python aici. Scena 3D FreeCAD afișează doar ceea ce îi spui să afișeze. Pentru a face acest lucru, folosim acest lucru simplu Pentru a realiza asta, utilizăm această metodă simplă:

So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:

Part.show(edge)

Un obiect va fi creat în documentul nostru FreeCAD, și forma noastră "muchie" va fi atribuită. Utilizați acest lucru când este timpul să vă afișați creație pe ecran.

Top

Crearea unui fir/contur/polilinie

Un fir este o linie multi-margine și poate fi creat dintr-o listă de margini sau chiar o listă de fire:

A wire is a multi-edge line and can be created from a list of edges or even a list of wires:

edge1 = Part.makeLine((0, 0, 0), (10, 0, 0))
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0))
wire1 = Part.Wire([edge1, edge2]) 
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0))
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0))
wire2 = Part.Wire([edge3, edge4])
wire3 = Part.Wire([wire1, wire2])
wire3.Edges
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)

Part.show(wire3) va afișa cele 4 margini care compun firul/polilinia noastră. alte informațiile utile pot fi ușor recuperate:

wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False

Top

Crearea unei Fațete

Doar fațetele create de firele/poliliniile închise vor fi valide. În acest exemplu, wire3 este un contur închis dar wire2 nu este un contur închis(vezi mai sus)

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above):

face = Part.Face(wire3)
face.Area
> 99.99999999999999
face.CenterOfMass
> Vector (5, 5, 0)
face.Length
> 40.0
face.isValid()
> True
sface = Part.Face(wire2)
sface.isValid()
> False

Numai fațetele vor avea o arie, poliliniile și muchiile nu posedă așa ceva.

Top

Crearea unui Cerc

Un cerc poate fi creat pur și simplu astfel:

A circle can be created like this:

circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))

Dacă vreți să îl creați la o anumită poziție și într-o anumită direcție:

ccircle = Part.makeCircle(10, App.Vector(10, 0, 0), App.Vector(1, 0, 0))
ccircle.Curve
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))

cercul va fi creat la distanța 10 unități de la axa x și va fi orientat spre axa x. Notă: makeCircle acceptă numai Base.Vector () pentru poziție și normal, dar nu tuple. Puteți, de asemenea, să creați o parte a cercului dând unghiul de pornire și unghiul de capăt ca de exemplu:

from math import pi
arc1 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)

Ambele atât arc1 cât și arc2 vor face un cerc. Trebuie introduse unghiuri în grade, dacă aveți radiani pur și simplu le convertiți folosind formula: grade = radiani * 180 / PI sau folosind modulul matematic al lui python (după importul efectuat matematica, desigur):

import math
degrees = math.degrees(radians)

Top

Crearea unui Arc de-a lungul punctelor

Din păcate, nu există nicio funcție makeArc, dar avem funcția Part.Arc pentru a crea un arc de-a lungul a trei puncte. Practic, putem să ne imaginăm un arc de cerc atașat la un punct de plecare, trecând printr-un punct central și terminându-se într-un punct final. Part.Arc creează un obiect arc pe care .toShape() trebuie apelat pentru a obține un obiect muchie, în același mod ca atunci când utilizați Part.LineSegment în loc de Part.makeLine.

Unfortunately there is no makeArc() function, but we have the Part.Arc() function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's toShape() function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine.

arc = Part.Arc(App.Vector(0, 0, 0), App.Vector(0, 5, 0), App.Vector(5, 5, 0))
arc
> <Arc object>
arc_edge = arc.toShape()
Part.show(arc_edge)

Arc only accepts Base.Vector() for points but not tuples. arc_edge is what we want which we can display using Part.show(arc_edge). You can also obtain an arc by using a portion of a circle:

from math import pi
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)

Arcurile sunt muchii valide, ca liniile. Deci, ele pot fi folosite și în polilinii/contururi/fire.

Top

Crearea unui poligon

Un poligon este o polilinie simplă cu multiple segemente de linii drepte. funcția makePolygon ia o listă de puncte și creează o polilinie de-a lungul acestor puncte:

A polygon is simply a wire with multiple straight edges. The makePolygon() function takes a list of points and creates a wire through those points:

lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])

Top

Crearea unei curbe Bezier

Curbele Bézier sunt folosite pentru a modela curbele netede folosind o serie de repere (puncte de control) și cu un numar mare de reprezentari la precizie (fluiditatea curbei). Funcția de mai jos face Part.BezierCurve dintr-o serie de puncte FreeCAD.Vector. (Notă: indicele primului reper începe de la 1, și nu de la 0.)

Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve() from a series of FreeCAD.Vector() points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0.

def makeBCurveEdge(Points):
   geomCurve = Part.BezierCurve()
   geomCurve.setPoles(Points)
   edge = Part.Edge(geomCurve)
   return(edge)

Top

Crearea unui Plan

A Plane este o suprafață simplă rectangulară. Meteoda pentru crearea unuia este aceasta: makePlane(length,width,[start_pnt,dir_normal]). Implicit start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Utilizând dir_normal = Vector(0,0,1) va crea un plan pe axa z, în timp ce dir_normal = Vector(1,0,0) va crea planul pe axa x:

A Plane is a flat rectangular surface. The method used to create one is makePlane(length, width, [start_pnt, dir_normal]). By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction:

plane = Part.makePlane(2, 2)
plane
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.Vector(0, 1, 0))
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)

BoundBox este un cuboid care înconjoară planul cu o diagonală începând de la (3.0.0) și se termină la (5.0.2). Aici grosimea BoundBox în axa y este zero, deoarece forma noastră este complet plană.

Notă: makePlane acceptă doar Base.Vector() pentru start_pnt and dir_normal dar nu și tuplele

Top

Crearea unei elipse

Pentru a crea o elipsă sunt mai multe căi:

There are several ways to create an ellipse:

Part.Ellipse()

Crează o elipsă cu raza mare 2 și cu raza mică 1 cu centrul în (0,0,0)

Part.Ellipse(Ellipse)

Creațo p copie a elipsei date

Part.Ellipse(S1, S2, Center)

Creează o elipsă centrat pe punctul central, unde planul elipsa este definită de Centrul, S1 și S2, axa sa principală este definită de Centru și S1, semiaxa sa majoră este distanța dintre centrul și S1, iar semiaxa sa minoră este distanța dintre S2 și axa principală.

Part.Ellipse(Center, MajorRadius, MinorRadius)

Creează o elipsă cu semiaxa majoră și cu o semiaxă minoră MajorRadius and MinorRadius, și localizată în planul definit de către Center și normala (0,0,1)

eli = Part.Ellipse(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.Vector(0, 0, 0))
Part.show(eli.toShape())

În codul de mai sus am trecut S1, S2 și centrul. În mod similar cu Arc, Ellipse creează, de asemenea, un obiect de elipsă, dar nu margine, așa că trebuie să convertiți-l în margine folosind toShape () pentru afișare.

Notă: Doar Arc aceptă Base.Vector() pentru puncte dar nu pentru tuple

eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())

pentru constructorul Ellipse de mai sus am trecut centrul, MajorRadius and MinorRadius

Top

Crearea unui Tor

Folosind metoda makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]). Implicit avem pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360. Considerați un tor ca pe un mic cerca care baliază de-a lungul unu cerc mare. Radius1 este raza cercului mare , iar radius2 este raza cercului mic, pnt este centrul torului și dir este direcția normalei. angle1 and angle2 sunt unghiurile în radiani pentru cercul mic, ultimul parametru -unghiul este pentru a face o secțiune în tor:

Using makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus:

torus = Part.makeTorus(10, 2)

Codul de deasupra va crea un tor cu diametrul 20(raza 10) și grosimea 4 (raza cercului mic 2)

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)

codul de mai sus va crea o felie de tor

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 360, 180)

Codul de mai sus va crea un semtor, numai ultimul parametru este schimbat adică unghiul și unghiurile rămase sunt implicite. Dând unghiul 180 va a crea tor de la 0 la 180, adică un jumătate de tor.

Top

Crearea unui paralelipiped sau cuboid

Utilizând makeBox(length,width,height,[pnt,dir]). Implicit pnt=Vector(0,0,0) and dir=Vector(0,0,1)

Using makeBox(length, width, height, [pnt, dir]). By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1).

box = Part.makeBox(10, 10, 10)
len(box.Vertexes)
> 8

Top

Crearea unei sfere

Utilizând makeSphere(radius,[pnt, dir, angle1,angle2,angle3]). Implicit avem pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 and angle3=360. angle1 și angle2 sunt verticala minimă și verticala maximă ale sferei, angle3 diametrul sferei.

Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter.

sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)

Top

Crearea unui cilindru

Utilizând makeCylinder(radius,height,[pnt,dir,angle]). Implicat avem pnt=Vector(0,0,0),dir=Vector(0,0,1) și angle=360

Using makeCylinder(radius, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

cylinder = Part.makeCylinder(5, 20)
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Top

Crearea unui Con

Utilizând makeCone(radius1,radius2,height,[pnt,dir,angle]). Implicit avem pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360

Using makeCone(radius1, radius2, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Top

Modificarea Formelor geometrice

Sunt mai multe moduri de a modifica forme. Unele sunt operații simple de transformare cum ar fi mișcările sau formele rotative, altele sunt mai complexe, cum ar fi unirea și scăderea unei forme de alta. Țineți cont de asta

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.

Top

Operații de Transformare

Translatarea unei forme

Translatarea estr de fapt actul de mutarea a unei forme dintr-un loc în altul. Orice formă (muchie, fațetă, cube, etc...) poate fi translată în același mod:

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way:

myShape = Part.makeBox(2, 2, 2)
myShape.translate(App.Vector(2, 0, 0))

Aceasta va muta forma noastră "myShape" 2 unități in direcția x .

Top

Rotația unei forme

Pentru a roti o formă, aveți nevoie de uncentru de rotație, axa, și unghiul de rotație:

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:

myShape.rotate(App.Vector(0, 0, 0),App.Vector(0, 0, 1), 180)

Codul de mai sus va roti forma cu 180 degrees în jurul axei Z .

Top

Transformările generice cu matrici

O matrice este o modalitate foarte convenabilă de a stoca transformările în lumea reală 3D. Într-o singură matrice, puteți defini valorile de translația, rotirea și scalarea care trebuie aplicate unui obiect. De exemplu:

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example:

myMat = App.Matrix()
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)

Notă: Matricile FreeCAD lucrează în radiani. De altfel, aproape toate operațiile de matrice care iau un vector pot lua de asemenea 3 numere, astfel încât cele două linii fac același lucru:

myMat.move(2, 0, 0)
myMat.move(App.Vector(2, 0, 0))

Atunci când matricea noastră este definită, o putem aplica formei noastre. FreeCAD oferă 2 metode pentru a face acest lucru: transformShape() and transformGeometry(). Diferența este că, cu prima, sunteți siguri că nu vor avea loc deformări (a se vedea "scalarea unei forme" de mai jos). Deci, putem aplica transformarea noastră astfel:

myShape.transformShape(myMat)

ori

myShape.transformGeometry(myMat)

Top

Scalarea unei forme geometrice

Scalarea unei forme este o operațiune mai periculoasă deoarece, spre deosebire de translație sau rotație, scalarea neuniformă (cu valori diferite pentru x, y și z) poate modifica structura formei. De exemplu, scalarea unui cerc cu o valoare mai mare pe orizontală decât pe verticală îl va transforma într-o elipsă, care se comportă matematic foarte diferit. Pentru scalare, noi nu putem folosi transformShape, trebuie să folosimtransformGeometry():

Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the transformShape(), we must use transformGeometry():

myMat = App.Matrix()
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)

Top

Operații Booleene

Subtraction

Scăderea unei forme de la alta se numește "tăiat" în jargonul OCC/FreeCAD și se face astfel:

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:

cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)

Top

Intersection

În același mod, intersecția dintre două forme este denumită "comună" și se face pe aici:

The same way, the intersection between two shapes is called "common" and is done this way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)

Top

Union

Unionea este numită "fuse" și lucrează în același mod:

Union is called "fuse" and works the same way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)

Top

Section

O secțiune este intersecția dintre o formă solidă și o formă plană. Va returna o curbă de intersecție, un compus cu margini

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges.

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section.Wires
> []
section.Edges
> [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, 
 <Edge  object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, 
 <Edge object at 0D8F4BB0>]

Top

Extrusion

Extrudarea este actul de "împingere" a unei forme plate într-o anumită direcție care are ca rezultat un corp solid. Gândiți-vă la un cerc devenind un tub prin "împingerea lui":

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out":

circle = Part.makeCircle(10)
tube = circle.extrude(App.Vector(0, 0, 2))

Dacă cercul dvs. este gol, veți obține un tub gol. Dacă cercul dvs. este de fapt un disc, cu o față plină, veți obține un cilindru solid:

wire = Part.Wire(circle)
disc = Part.Face(wire)
cylinder = disc.extrude(App.Vector(0, 0, 2))

Top

Explorarea formelor

Puteți explora ușor structura datelor topologice:

You can easily explore the topological data structure:

import Part
b = Part.makeBox(100, 100, 100)
b.Wires
w = b.Wires[0]
w
w.Wires
w.Vertexes
Part.show(w)
w.Edges
e = w.Edges[0]
e.Vertexes
v = e.Vertexes[0]
v.Point

Dacă tastați liniile de mai sus în interpretul python, veți câștiga o bună înțelegere a structurii obiectelor Part. Aici, comanda makeBox () a creat o formă solidă. Acest solid, ca toate componentele solide, conține fațete. Fețele conțin întotdeauna polilinii, care sunt liste de margini care delimitează fața. Fiecare față are cel puțin o polilinie închisă (poate avea mai multe dacă fața are una sau mai multe găuri). În polilinie, putem privi la fiecare margine separat, iar în interiorul fiecărei margini, putem vedea vârfurile. Liniile drepte au doar două vârfuri, evident.

Top

Analiza muchiei

În cazul unei muchii, care este o curbă arbitrară, este cel mai probabil să doriți a face o discretizare. În FreeCAD marginile sunt parametrizate după lungimile lor. Asta înseamnă ca puteți parcurge o margine/curba pe lungimea ei:

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length:

import Part
box = Part.makeBox(100, 100, 100)
anEdge = box.Edges[0]
print(anEdge.Length)

Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 100.

anEdge.tangentAt(0.0)          # tangent direction at the beginning
anEdge.valueAt(0.0)            # Point at the beginning
anEdge.valueAt(100.0)          # Point at the end of the edge
anEdge.derivative1At(50.0)     # first derivative of the curve in the middle
anEdge.derivative2At(50.0)     # second derivative of the curve in the middle
anEdge.derivative3At(50.0)     # third derivative of the curve in the middle
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.curvatureAt(50.0)       # the curvature
anEdge.normalAt(50)            # normal vector at that position (if defined)

Top

Utilizarea selecție

Aici vedem acum modul în care putem folosi selecția utilizată de utilizator în vizualizator. Mai întâi de toate, creăm o casetă și o afișează în vizualizator

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer.

import Part
Part.show(Part.makeBox(100, 100, 100))
Gui.SendMsgToActiveView("ViewFit")

Selectați acum unele fețe sau margini. Cu acest script puteți itera toate obiectele selectate și sub-elementele acestora:

for o in Gui.Selection.getSelectionEx():
    print(o.ObjectName)
    for s in o.SubElementNames:
        print("name: ", s)
        for s in o.SubObjects:
            print("object: ", s)

Selectați unele margini și acest progrămel script va calcula lungimea:

length = 0.0
for o in Gui.Selection.getSelectionEx():
    for s in o.SubObjects:
        length += s.Length

print("Length of the selected edges: ", length)

Top

Exemplul complet : Sticla OCC (Open CASCADE Technology)

Un exemplu tipic găsiți în OpenCasCade Technology Tutorial Este cum se construiește o sticlă. Acesta este un exercițiu bun și pentru FreeCAD. De fapt, puteți urma exemplul nostru de mai jos și pagina OCC simultan, veți înțelege cum sunt implementate structurile OCC în FreeCAD. Scenariul complet de mai jos este, de asemenea, inclus în instalarea FreeCAD (în interiorul folderului Mod/Part) și poate fi apelat de la interpretul python prin tastarea:

A typical example found on the OpenCasCade Technology website is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the Python interpreter by typing:

import Part
import MakeBottle
bottle = MakeBottle.makeBottle()
Part.show(bottle)

Top

Programul script complet

aici este programul script complet MakeBottle:

For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.

import FreeCAD as App
import Part, math

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)
    myBody = myBody.fuse(myNeck)

    return myBody

el = makeBottleTut()
Part.show(el)

Top

Explicații detaliate

import FreeCAD as App
import Part, math

Vom avea, desigur, modulul Part, dar și modulul FreeCAD.Base, care conține structuri de bază FreeCAD precum vectori și matrice.

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

Aici definim funcția makeBottle. Această funcție poate fi apelată fără argumente, așa cum am făcut mai sus, caz în care valorile implicite pentru lățime, înălțime, și grosime vor fi utilizate. Apoi, definim câteva puncte care vor fi utilizate pentru construirea profilului de bază.

...
    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

Aici definim geometria: un arc, format din 3 puncte și două segmente de linie, formate din câte 2 puncte.

...
    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

Vă amintiți diferența dintre geometrie și forme? Aici construim forme geometrice ale construcției noastre. 3 margini (marginile pot fi drepte sau curbate), apoi o poliline realizează acele trei margini.

...
    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

Până acum am construit doar o jumătate de profil. Mai ușor decât construirea întregului profil în același mod, putem doar să simetrizăm ceea ce am făcut și să lipim ambele jumătăți împreună. Așadar, vom crea mai întâi o matrice. O matrice este o modalitate foarte comună de a aplica transformări la obiecte din lumea 3D, deoarece poate conține într-o singură structură toate transformările de bază pe care obiectele 3D le pot suferi (mișcare, rotire și scalare). Aici, după ce creăm matricea, o oglindim și creăm o copie a poliliniei noastre cu matricea de transformare aplicată. Acum avem două polilinii și putem face o a treia polilinie din ele, deoarece poliliniile sun nt de fapt liste de margini.

...
    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

Acum că avem o polilinie închisă, aceasta poate fi transformat într-o fațetă. Odată ce avem o fațetă, o putem extruda. În acest fel, am făcut de fapt un solid. Apoi aplicăm o mică și frumoasă (pilire) rotunjire la obiectul nostru pentru că ne pasă de un design bun, nu-i așa?

...
    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)

Apoi, corpul sticlei noastre este făcută, mai avem nevoie să creăm un gât. Deci noi face un nou solid, cu un cilindru.

...
    myBody = myBody.fuse(myNeck)

Funcționarea siguranței, care în alte aplicații este uneori numită uniune, este foarte puternică. Va avea grijă de lipirea a ceea ce trebuie lipit și de a elimina părțile care trebuie să fie eliminate.

...
    return myBody

Apoi, ne întoarcem Piesa noastră solidă ca rezultat al funcției noastre.

el = makeBottleTut()
Part.show(el)

În final, numim funcția definită și facem piesa vizibilă.

Top

Paralelipiped găurit

Aici este un exemplul de construcție a unui paralelipiped găurit.

Here is a complete example of building a pierced box.

Construcția este realizată dintr-un capăt în altul iar când paralelipipedul este terminat, acesta este găurit cu un cilindru.

import FreeCAD as App
import Part, math

size = 10
poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)])

face1 = Part.Face(poly)
face2 = Part.Face(poly)
face3 = Part.Face(poly)
face4 = Part.Face(poly)
face5 = Part.Face(poly)
face6 = Part.Face(poly)
     
myMat = App.Matrix()

myMat.rotateZ(math.pi / 2)
face2.transformShape(myMat)
face2.translate(App.Vector(size, 0, 0))

myMat.rotateZ(math.pi / 2)
face3.transformShape(myMat)
face3.translate(App.Vector(size, size, 0))

myMat.rotateZ(math.pi / 2)
face4.transformShape(myMat)
face4.translate(App.Vector(0, size, 0))

myMat = App.Matrix()

myMat.rotateX(-math.pi / 2)
face5.transformShape(myMat)

face6.transformShape(myMat)               
face6.translate(App.Vector(0, 0, size))

myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])   
mySolid = Part.makeSolid(myShell)

myCyl = Part.makeCylinder(2, 20)
myCyl.translate(App.Vector(size / 2, size / 2, 0))

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)

Top

Încărcare și salvare

Există mai multe moduri de a vă salva munca în modulul Part. Puteți bineînțeles salvați documentul FreeCAD, dar puteți salva și un obiect piesă/Part direct la formatele CAD obișnuite, cum ar fi BREP, IGS, STEP și STL.

There are several ways to save your work. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL.

Salvarea unei forme într-un fișier este ușoară. Există metode disponibile exportBrep(), exportIges(), exportStl() și exportStep() pentru toate obiectele de formă. Deci, faci:

import Part
s = Part.makeBox(10, 10, 10)
s.exportStep("test.stp")

acest lucru va salva caseta noastră într-un fișier STEP. Pentru a încărca un BREP, IGES sau STEP, pur și simplu faceți contrariul:

import Part
s = Part.Shape()
s.read("test.stp")

Pentru a converti un fișier .stp în .igs este simplu :

import Part
 s = Part.Shape()
 s.read("file.stp")       # incoming file igs, stp, stl, brep
 s.exportIges("file.igs") # outbound file igs

Top

Mesh Scripting
Mesh to Part


Conversia obiectelor Piese în Plasă

Conversia obiectelor de nivel superior, cum ar fi Part shell în obiecte mai simple, cum ar fi meshes este o operație simplă, în care toate fațetele unui obiect Piesă i se aplică o discretizarea în triunghiur. Rezultatul acestei discretizări(tessellation) este apoi folosit pentru a construi o plasă: (să presupunem că documentul nostru conține un obiect de piesă)

import Mesh

obj = FreeCADGui.Selection.getSelection()[0] # a Part object must be preselected
shp = obj.Shape
faces = []

triangles = shp.tessellate(1) # the number represents the precision of the tessellation
for tri in triangles[1]:
    face = []
    for i in tri:
        face.append(triangles[0][i])
    faces.append(face)

m = Mesh.Mesh(faces)
Mesh.show(m)

Alternative example:

import Mesh
import MeshPart

obj = FreeCADGui.Selection.getSelection()[0] # a Part object must be preselected
shp = obj.Shape

mesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature", "Mesh")
mesh.Mesh = MeshPart.meshFromShape(
        Shape=shp,
        LinearDeflection=0.01,
        AngularDeflection=0.025,
        Relative=False)

Convertirea Plaselor în obiecte Part

Convertirea ochiurilor de plasă în obiecte piese este o operație extrem de importantă în lucrul cu CAD, pentru că de multe ori primiți date 3D în format de ochiuri de plasă de la alte persoane sau ieșite din alte aplicații. Meshurile sunt foarte practice pentru a reprezenta geometria liberă și pentru scenele vizuale mari, deoarece este foarte ușoară, dar pentru CAD, în general, preferăm obiecte de nivel mai înalt care transportă mult mai multe informații, cum ar fi ideea de solid sau fațetele făcute din curbe în loc de triunghiuri.

Convertirea ochiurilor de plasă în obiecte de nivel superior (manipulate de Part Workbench în FreeCAD) nu este o operație ușoară. Mesh-urile pot fi realizate din mii de triunghiuri (de exemplu, atunci când sunt generate de un scanner 3D) și având solide realizate din același număr de fețe ar fi extrem de greu de manipulat. Deci, în general, doriți să optimizați obiectul când faceți conversia.

FreeCAD oferă în prezent două metode pentru a transforma Plasele în obiecte piese (Part). Prima metodă este o conversie simplă, directă, fără optimizare:

import Mesh
import Part

mesh = Mesh.createTorus()
shape = Part.Shape()
shape.makeShapeFromMesh(mesh.Topology, 0.05) # the second arg is the tolerance for sewing
solid = Part.makeSolid(shape)
Part.show(solid)

Cea de-a doua metodă oferă posibilitatea de a considera aspectul ochiurilor de plasă coplanare atunci când unghiul dintre ele este sub o anumită valoare. Acest lucru permite construirea unor forme mai simple: (să presupunem că documentul nostru conține un obiect Mesh)

import Mesh
import Part
import MeshPart

obj = FreeCADGui.Selection.getSelection()[0] # a Mesh object must be preselected
mesh = obj.Mesh
segments = mesh.getPlanarSegments(0.00001) # use rather strict tolerance here
faces = []

for i in segments:
    if len(i) > 0:
        # a segment can have inner holes
        wires = MeshPart.wireFromSegment(mesh, i)
        # we assume that the exterior boundary is that one with the biggest bounding box
        if len(wires) > 0:
            ext = None
            max_length=0
            for i in wires:
                if i.BoundBox.DiagonalLength > max_length:
                    max_length = i.BoundBox.DiagonalLength
                    ext = i

            wires.remove(ext)
            # all interior wires mark a hole and must reverse their orientation, otherwise Part.Face fails
            for i in wires:
                i.reverse()

            # make sure that the exterior wires comes as first in the list
            wires.insert(0, ext)
            faces.append(Part.Face(wires))

solid = Part.Solid(Part.Shell(faces))
Part.show(solid)



Introduction

Geometria care apare în vizualizările 3D ale FreeCAD este redată de biblioteca Coin3D. Coin3D este o implementare satandard a OpenInventor.Software-ul openCascade oferă, de asemenea, aceeași funcționalitate, dar s-a hotărât, încă de la începuturile FreeCAD, să nu se folosească de vizualizatorul openCascade încorporat ci mai degrabă să se treacă la software-ul coin3D mai performant. O modalitate bună de a învăța despre această bibliotecă este cartea Open Inventor Mentor.

Description

OpenInventor este de fapt un limbaj de descriere a scenei 3D. Scena descrisă în openInventor este apoi redată în OpenGL pe ecran. Coin3D are grijă să facă acest lucru, astfel încât programatorul nu are nevoie să se ocupe de apelurile complexe openGL, ci doar să-l furnizeze cu un cod OpenInventor valabil. Marele avantaj este că OpenInventor este un standard foarte bine cunoscut și bine documentat.

Una din marile servicii pe care FreeCAD le face pentru dvs. este de a traduce în mod deschis informația geometriei OpenCascade în limbajul openInventor.

OpenInventor descrie o scenă 3D sub formă de ascenegraph, like the one below:

image from Inventor mentor

Un scenograf openInventor descrie tot ce face parte dintr-o scenă 3D, cum ar fi geometria, culorile, materialele, luminile etc., și organizează toate datele într-o structură convenabilă și clară. Totul poate fi grupat în sub-structuri, permițându-vă să vă organizați conținutul scenei cât de mult vă place. Iată un exemplu de fișier openInventor:

#Inventor V2.0 ascii
 
Separator { 
    RotationXYZ {	
       axis Z
       angle 0
    }
    Transform {
       translation 0 0 0.5
    }
    Separator {	
       Material {
          diffuseColor 0.05 0.05 0.05
       }
       Transform {
          rotation 1 0 0 1.5708
          scaleFactor 0.2 0.5 0.2
       }
       Cylinder {
       }
    }
}

După cum puteți vedea, structura este foarte simplă. Utilizați separatoare pentru a vă organiza datele în blocuri, un pic asemănător cu modul cum ați organiza fișierele în foldere. Fiecare afirmație afectează ce urmează, de exemplu primele două elemente ale separatorului rădăcină sunt o rotație și o translație, ambele afectează următorul element, care este un separator. În acest separator se definește un material și o altă transformare. Cilindrul nostru va fi astfel afectat de ambele transformări, cel care a fost aplicat direct la acesta și cel aplicat separatorului părinte.

De asemenea, avem multe alte tipuri de elemente pentru organizarea scenei noastre, cum ar fi grupuri, switch-uri sau adnotări. Putem defini materiale foarte complexe pentru obiectele noastre, cu culori, texturi, moduri de umbrire și transparență. De asemenea, putem defini lumini, camere de luat vederi și chiar mișcări. Este posibil chiar să încorporați fragmente de script-uri în fișierele openInventor, pentru a defini comportamente mai complexe.

Dacă sunteți interesat să aflați mai multe despre openInventor, mergeți direct la cele mai faimoase referințe ale sale Inventor mentor.

În FreeCAD, în mod normal, nu trebuie să interacționăm direct cu scenograful openInventor. Fiecare obiect dintr-un document FreeCAD, fiind o plasă, o formă a unei piese sau orice altceva, devine automat convertit în codul openInventor și inserat în descrierea grafică a scenei principală pe care îl vedeți într-o vizualizare 3D. Această descriere grafică este actualizat continuu când faceți modificări, adăugați sau eliminați obiecte în document. De fapt, fiecare obiect (în spațiul App) are un furnizor de vizualizare (un obiect corespunzător în spațiul Gui), responsabil pentru emiterea codului openInventor.

Dar există multe avantaje pentru a putea accesa scenegraful direct. De exemplu, putem schimba temporar aspectul unui obiect sau putem adăuga obiecte în scenă care nu au o existență reală în documentul FreeCAD, cum ar fi geometria construcției, ajutoarele, sugestii grafice sau unelte cum ar fi manipulatorii sau informații pe ecran .

FreeCAD dispune de mai multe instrumente pentru a vedea sau a modifica codul openInventor. De exemplu, următorul cod python va afișa reprezentarea openInventor a unui obiect selectat:

obj = FreeCAD.ActiveDocument.ActiveObject
viewprovider = obj.ViewObject
print viewprovider.toString()

Dar avem, de asemenea, un modul python care permite accesul complet la tot ceea ce gestionează Coin3D, cum ar fi descrierea grafică a scenei FreeCAD. Deci, citiți mai departe Pivy.

Coding examples

See Coin3d snippets courtesy of MariwanJ's research for the Design456 Workbench. The code repository can be found at https://github.com/MariwanJ/COIN3D_Snippet.

Top

Mesh to Part/ro
Pivy/ro


Introduction

Pivy este o bibliotecă de coduri care servește drept punte între Python și coin Coin3d, biblioteca de randare 3D utilizată de către FreeCAD. Atunci când este importat într-un interpretor python care rulează, Pivy permite dialogul direct și imediat cu orice procedură Coin3d care rulează scenegraphs, ca dexemplu vizualizările FreeCAD 3D , sau chiar creare unora noi. Pivy este inclus în pachetul standard de instalare FreeCAD .

When imported in a running Python interpreter, Pivy allows us to communicate directly with any running Coin scenegraph, such as the 3D view, or even to create new ones. Pivy is not required to compile FreeCAD, but it is required at runtime when running Python-based workbenches that create shapes on screen, like Draft and Arch. Because of this, Pivy is normally installed when installing a distribution of FreeCAD.

Biblioteca coin este împărțită în mai multe piese, coin însuși, este pentru manipularea scripturilor și legăturilor pentru mai multe sisteme GUI, cum ar fi ferestrele sau, ca în cazul nostru, qt. Modulele respective sunt disponibile și pentru piv, în funcție de situația în care sunt prezente în sistem. Modulul coin este întotdeauna prezent și este ceea ce vom folosi oricum, deoarece nu va trebui să ne pese de ancorarea afișajului nostru 3D în orice interfață, deoarece este deja făcută de cpătre FreeCAD. Tot ce trebuie să facem este:

from pivy import coin

Accesarea și modificarea unui scene grafice 3D

Am văzut în pagina Scenegraph cum Coin organizează o scenă tipică. Tot ce este afișat 3D în FreeCAD este construit și festionat de către Coin. Avem o rădăcină, iar toate obiectele de pe ecran sunt copiii lui.legat prin noduri

Free cad are un mod facil de a accede la radacina unei scene 3D:

sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph()
print(sg)

Radăcina scenei va fi :

<pivy.coin.SoSelection; proxy of <Swig Object of type 'SoSelection *' at 0x360cb60> >

Putrem inspecta imediat copii scenei noastre:

for node in sg.getChildren():
    print(node)

Unele dintre aceste noduri, cum ar fi SoSeparators sau SoGroups, pot avea proprii copii. Lista completă a obiectelor disponibile pentru programul Coin poate fi găsită în official coin documentation.

Acum să încercăm să adăugăm ceva la scenă (proiect). Vom adăuga un frumos cub roșu:

col = coin.SoBaseColor()
col.rgb = (1, 0, 0)
cub = coin.SoCube()
myCustomNode = coin.SoSeparator()
myCustomNode.addChild(col)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)

și aici este (frumosul ) nostru cub roșu. Acum. hai să încerca aceasta:

col.rgb = (1, 1, 0)

Ai văzut? Totul este încă accesibil și editabil din voleu. Nu este nevoie să recalculați sau să reproiectați nimic, Coin are grijă de tot. Puteți adăuga ceea ce doriți la scenă (proiectul), schimbați proprietățile, ascundeți obiecte, expuneți temporar obiecte, faceți ceva. Desigur, acest lucru afectează numai afișarea vizualizării 3D. Afișarea documentului deschis este recalculată de FreeCAD și recalculează un obiect atunci când trebuie să fie. Deci, dacă modificați aspectul unui obiect existent în FreeCAD, aceste modificări se vor pierde dacă obiectul este recalculat sau când redeschideți fișierul.

Un lucru, pentru a lucra cu scripturile în scenariile tale, poți, când este necesar, să accesezi câteva proprietăți ale nodurilor pe care le-ai adăugat. De exemplu, dacă vrem să mutăm cubul, am fi adăugat un nod SoTranslation la nodul nostru personalizat și,el ar fi arătat astfel:

col = coin.SoBaseColor()
col.rgb = (1, 0, 0)
trans = coin.SoTranslation()
trans.translation.setValue([0, 0, 0])
cub = coin.SoCube()
myCustomNode = coin.SoSeparator()
myCustomNode.addChild(col)
myCustomNode.addChild(trans)
myCustomNode.addChild(cub)
sg.addChild(myCustomNode)

Rețineți că într-un scenariu openInventor, ordinea este importantă. Un nod afectează ceea ce urmează, astfel încât să puteți spune ceva de genul: culoarea roșie, cubul, culoarea galbenă, sfera și veți obține un cub roșu și o sferă galbenă. Dacă am adăugat traducerea la nodul nostru personalizat existent, acesta va veni după cub și nu îl va afecta. Dacă am fi introdus-o

trans.translation.setValue([2, 0, 0])

Și cubul nostru ar sări 2 unități la dreapta. În cele din urmă, eliminarea a ceva se face cu:

sg.removeChild(myCustomNode)

Top

Utilizarea mecanismului de trecere în argument a unei alte funcții

La callback mechanism, Un mecanism de Callback este sistem care permite unei bilbioteci pe caer o utilizați , ca de ex bilbioteca Coin de a trece în argumente a unei alte funcții pentru l'Objet Python în curs de execuție. Acest lucru este extrem de util, deoarece în acest mod coin vă poate avertiza dacă un anumit eveniment apare în scenă. Coin poate vedea lucruri foarte diferite, cum ar fi poziția mouse-ului, clicurile pe un buton al mouse-ului, tastele de tastatură care sunt apăsate și multe alte lucruri.

FreeCAD are o modalitate ușoară de a utiliza aceste callbacks:

from pivy import coin

class ButtonTest:
    def __init__(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.callback = self.view.addEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), self.getMouseClick) 

    def getMouseClick(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == coin.SoMouseButtonEvent.DOWN:
            print("Alert!!! A mouse button has been improperly clicked!!!")
            self.view.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), self.callback)

ButtonTest()

Callback-ul a fost pornit de la un obiect, deoarece obiectul trebuie să ruleze în continuare când apare apelul invers. Vezi de asemenea complete list a posibilelor evenimente și parametrii lor, sau în official coin documentation.

Top

Documentație

Din păcate, pivy nu dispune încă de o documentație potrivită, dar deoarece există o traducere exactă a lui coin, puteți utilizat în toată securitatea documetația de referință a lui coin, și utilizați stilul Python în locul stilului c ++ ( par exemple SoFile::getClassTypeId() en c++, serait SoFile.getClassId() en pivy ) c++ style (for example SoFile::getClassTypeId() would in pivy be SoFile.getClassId())

In C++:

SoFile::getClassTypeId()

In Pivy:

SoFile.getClassId()

Older

These links provide reference documentation for Coin v3.x. The differences with v4.x are minimal, so they may still be useful.

Top

Scenegraph/ro
PySide/ro


PySide

PySide este un instrument Python multiplatformă obligatoriu pentru a crea GUI în QT. FreeCAD utilizează PySide pentru toate GUI (Graphic User Interface) în interiorul Python. PySide este o alternativă la pachetul PyQt folosit anterior de FreeCAD pentru GUI. PySide are o licență mai permisivă. A se vedea Differences Between PySide and PyQt for more information on the differences.

When you install FreeCAD, you should get both Qt and PySide as part of the package. If you are compiling yourself then you must verify that these two libraries are installed in order for FreeCAD to run correctly. Of course, PySide will only work if Qt is present.

In the past, FreeCAD used PyQt, another Qt binding for Python, but in 2013 (commit 1dc122dc9a) the project migrated to PySide because it has a more permissible License.

For more information see:

Examples created with PySide. Left: a simple dialog. Right: a more complex dialog with graphs.

PySide in FreeCAD with Qt5

FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility.

Normally, the PySide module provides support for Qt4, while PySide2 provides support for Qt5. However, in FreeCAD there is no need to use PySide2 directly, as a special PySide module is included to handle Qt5.

This PySide module is located in the Ext/ directory of an installation of FreeCAD compiled for Qt5.

/usr/share/freecad/Ext/PySide

This module just imports the necessary classes from PySide2, and places them in the PySide namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as we use the single PySide module.

PySide2.QtCore -> PySide.QtCore
PySide2.QtGui -> PySide.QtGui
PySide2.QtSvg -> PySide.QtSvg
PySide2.QtUiTools -> PySide.QtUiTools

The only unusual aspect is that the PySide2.QtWidgets classes are placed in the PySide.QtGui namespace.

PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox

Top

Examples of PySide use

Acestea împart subiectul în 3 părți, diferențiate după nivelul de cunoaștere a PySide, Python și FreeCAD. Prima pagină are o imagine de ansamblu și un material de referință care oferă o descriere a PySide și modul în care sunt setate împreună, în timp ce a doua și a treia pagină sunt în mare parte exemple de cod la diferite niveluri.

Intenția este ca paginile asociate să furnizeze un cod Python simplu pentru a rula PySide, astfel încât utilizatorul care lucrează la o problemă să poată copia cu ușurință codul, să-l lipsească în munca proprie, să-l adapteze după cum este necesar și să se întoarcă la rezolvarea problemelor cu FreeCAD. Sperăm că nu trebuie să meargă pe Internet în căutarea răspunsurilor la problemele PySide. În același timp, această pagină nu are intenția de a înlocui diferitele tutoriale și site-uri de referință PySide disponibile pe web.

Top

Documentation

There are some differences in handling of widgets in Qt4 (PySide) and Qt5 (PySide2). The programmer should be aware of these incompatibilities, and should consult the official documentation if something doesn't seem to work as expected on a given platform. Nevertheless, Qt4 is considered obsolete, so most development should target Qt5 and Python 3.

The PySide documentation refers to the Python-style classes; however, since Qt is originally a C++ library, the same information should be available in the corresponding C++ reference.

Top

Pivy
Scripted objects


Introduction

Pe lângă tipurile obișnuite de obiecte, cum ar fi adnotările, plasele și obiectele de piese, FreeCAD oferă, de asemenea, uimitoare posibilitate de a scrie scriptul obeictelor 100% Python, numite caracteristici Python. Aceste obiecte se vor comporta exact ca orice alt obiect FreeCAD și vor fi salvate și restaurate automat la salvarea / încărcarea fișierelor.

O particularitate care trebuie înțeleasă, aceste obiecte sunt salvate în fișiere FreeCAD FcStd cu modului python json module. Acest modul transformă un obiect python în șir de caractere(test), permițându-l să fie adăugat la fișierul salvat. Odată încărcat, modulul json utilizează șirul de caracter pentru a recrea obiectul original, cu condiția ca acesta să aibă acces la codul sursă care a creat obiectul. Aceasta înseamnă că dacă salvați un astfel de obiect personalizat și îl deschideți pe o mașină unde codul python care a generat obiectul nu este prezent, obiectul nu va fi recreat. Dacă distribuiți astfel de obiecte ale altora, va trebui să distribuiți în totalitate scriptul python care a creat-o împreună.

Note: It is possible to pack python code inside a FreeCAD file using json serializing with an App::PropertyPythonObject, but that code can never directly be run, and therefore has little use for our purpose here.

Caracteristicile Python respectă aceeași regulă ca toate funcțiile FreeCAD: ele sunt separate în părți App(application) și GUI(interfață grafică). Partea de aplicație, Object App, definește geometria obiectului nostru, în timp ce partea GUI, definește modul în care obiectul va fi afișat pe ecran. Instrumentul View Provider Objet, ca oricare altă caracteristică FreeCAD, este disponibil numai când rulați FreeCAD în propriul GUI. Există mai multe proprietăți și metode disponibile pentru a construi obiectul. Proprietățile trebuie să fie oricare dintre tipurile de proprietăți predefinite oferite de FreeCAD și vor apărea în fereastra de vizualizare a proprietății, astfel încât acestea să poată fi editate de utilizator. În acest fel, obiectele FeaturePython (au toate proprietățile Python) sunt cu adevărat și în totalitate parametrice. Puteți defini proprietăți pentru Obiect și ViewObject separat.

Basic example

Exemplu de bază

Următorul exemplu poate fi găsit in fișierul src/Mod/TemplatePyMod/FeaturePython.py, împreună cu alte exemple:

'''Examples for a feature class and its view provider.'''

import FreeCAD, FreeCADGui
from pivy import coin

class Box:
    def __init__(self, obj):
        '''Add some custom properties to our box feature'''
        obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box").Length = 1.0
        obj.addProperty("App::PropertyLength", "Width", "Box", "Width of the box").Width = 1.0
        obj.addProperty("App::PropertyLength", "Height", "Box", "Height of the box").Height = 1.0
        obj.Proxy = self

    def onChanged(self, fp, prop):
        '''Do something when a property has changed'''
        FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")

    def execute(self, fp):
        '''Do something when doing a recomputation, this method is mandatory'''
        FreeCAD.Console.PrintMessage("Recompute Python Box feature\n")

class ViewProviderBox:
    def __init__(self, obj):
        '''Set this object to the proxy object of the actual view provider'''
        obj.addProperty("App::PropertyColor","Color", "Box", "Color of the box").Color = (1.0, 0.0, 0.0)
        obj.Proxy = self

    def attach(self, obj):
        '''Setup the scene sub-graph of the view provider, this method is mandatory'''
        self.shaded = coin.SoGroup()
        self.wireframe = coin.SoGroup()
        self.scale = coin.SoScale()
        self.color = coin.SoBaseColor()

        data=coin.SoCube()
        self.shaded.addChild(self.scale)
        self.shaded.addChild(self.color)
        self.shaded.addChild(data)
        obj.addDisplayMode(self.shaded, "Shaded");
        style=coin.SoDrawStyle()
        style.style = coin.SoDrawStyle.LINES
        self.wireframe.addChild(style)
        self.wireframe.addChild(self.scale)
        self.wireframe.addChild(self.color)
        self.wireframe.addChild(data)
        obj.addDisplayMode(self.wireframe, "Wireframe");
        self.onChanged(obj,"Color")

    def updateData(self, fp, prop):
        '''If a property of the handled feature has changed we have the chance to handle this here'''
        # fp is the handled feature, prop is the name of the property that has changed
        l = fp.getPropertyByName("Length")
        w = fp.getPropertyByName("Width")
        h = fp.getPropertyByName("Height")
        self.scale.scaleFactor.setValue(float(l), float(w), float(h))
        pass

    def getDisplayModes(self,obj):
        '''Return a list of display modes.'''
        modes=[]
        modes.append("Shaded")
        modes.append("Wireframe")
        return modes

    def getDefaultDisplayMode(self):
        '''Return the name of the default display mode. It must be defined in getDisplayModes.'''
        return "Shaded"

    def setDisplayMode(self,mode):
        '''Map the display mode defined in attach with those defined in getDisplayModes.\
                Since they have the same names nothing needs to be done. This method is optional'''
        return mode

    def onChanged(self, vp, prop):
        '''Here we can do something when a single property got changed'''
        FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
        if prop == "Color":
            c = vp.getPropertyByName("Color")
            self.color.rgb.setValue(c[0], c[1], c[2])

    def getIcon(self):
        '''Return the icon in XPM format which will appear in the tree view. This method is\
                optional and if not defined a default icon is shown.'''
        return """
            /* XPM */
            static const char * ViewProviderBox_xpm[] = {
            "16 16 6 1",
            "   c None",
            ".  c #141010",
            "+  c #615BD2",
            "@  c #C39D55",
            "#  c #000000",
            "$  c #57C355",
            "        ........",
            "   ......++..+..",
            "   .@@@@.++..++.",
            "   .@@@@.++..++.",
            "   .@@  .++++++.",
            "  ..@@  .++..++.",
            "###@@@@ .++..++.",
            "##$.@@$#.++++++.",
            "#$#$.$$$........",
            "#$$#######      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            " #$#$$$$$#      ",
            "  ##$$$$$#      ",
            "   #######      "};
            """

    def dumps(self):
        '''When saving the document this object gets stored using Python's json module.\
                Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
                to return a tuple of all serializable objects or None.'''
        return None

    def loads(self,state):
        '''When restoring the serialized object from document we have the chance to set some internals here.\
                Since no data were serialized nothing needs to be done here.'''
        return None

def makeBox():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Box")
    Box(a)
    ViewProviderBox(a.ViewObject)

makeBox()

Things to note

If your object relies on being recomputed as soon as it is created, you must do this manually in the __init__ function as it is not called automatically. This example does not require it because the onChanged method of the Box class has the same effect as the execute function, but the examples below rely on being recomputed before anything is displayed in the 3D view. In the examples, this is done manually with ActiveDocument.recompute() but in more complex scenarios you need to decide where to recompute either the whole document or the FeaturePython object.

This example produces a number of exception stack traces in the report view window. This is because the onChanged method of the Box class is called each time a property is added in __init__. When the first one is added, the Width and Height properties don't exist yet and so the attempt to access them fails.

An explanation of __getstate__ and __setstate__ which have been replaced by dumps and loads is in the forum thread obj.Proxy.Type is a dict, not a string.

obj.addProperty(...) returns obj, so that the value of the property can be set on the same line:

obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box").Length = 1.0

Which is equivalent to:

obj.addProperty("App::PropertyLength", "Length", "Box", "Length of the box")
obj.Length = 1.0

Other more complex example

Alte exemple mai complexe

Acest exemplu ne face să utilizăm Part Workbench pentru a crea un octahedron, apoi crează reprezentarea sa coin cu pivy.

Primul este însuși obiectul Document:

import FreeCAD, FreeCADGui, Part
import pivy
from pivy import coin

class Octahedron:
  def __init__(self, obj):
     "Add some custom properties to our box feature"
     obj.addProperty("App::PropertyLength","Length","Octahedron","Length of the octahedron").Length=1.0
     obj.addProperty("App::PropertyLength","Width","Octahedron","Width of the octahedron").Width=1.0
     obj.addProperty("App::PropertyLength","Height","Octahedron", "Height of the octahedron").Height=1.0
     obj.addProperty("Part::PropertyPartShape","Shape","Octahedron", "Shape of the octahedron")
     obj.Proxy = self

  def execute(self, fp):
     # Define six vetices for the shape
     v1 = FreeCAD.Vector(0,0,0)
     v2 = FreeCAD.Vector(fp.Length,0,0)
     v3 = FreeCAD.Vector(0,fp.Width,0)
     v4 = FreeCAD.Vector(fp.Length,fp.Width,0)
     v5 = FreeCAD.Vector(fp.Length/2,fp.Width/2,fp.Height/2)
     v6 = FreeCAD.Vector(fp.Length/2,fp.Width/2,-fp.Height/2)

     # Make the wires/faces
     f1 = self.make_face(v1,v2,v5)
     f2 = self.make_face(v2,v4,v5)
     f3 = self.make_face(v4,v3,v5)
     f4 = self.make_face(v3,v1,v5)
     f5 = self.make_face(v2,v1,v6)
     f6 = self.make_face(v4,v2,v6)
     f7 = self.make_face(v3,v4,v6)
     f8 = self.make_face(v1,v3,v6)
     shell=Part.makeShell([f1,f2,f3,f4,f5,f6,f7,f8])
     solid=Part.makeSolid(shell)
     fp.Shape = solid

  # helper mehod to create the faces
  def make_face(self,v1,v2,v3):
     wire = Part.makePolygon([v1,v2,v3,v1])
     face = Part.Face(wire)
     return face

Apoi, avem obiectul furnizorului de vizualizare, responsabil pentru afișarea obiectului în scena 3D:

class ViewProviderOctahedron:
  def __init__(self, obj):
     "Set this object to the proxy object of the actual view provider"
     obj.addProperty("App::PropertyColor","Color","Octahedron","Color of the octahedron").Color=(1.0,0.0,0.0)
     obj.Proxy = self

  def attach(self, obj):
     "Setup the scene sub-graph of the view provider, this method is mandatory"
     self.shaded = coin.SoGroup()
     self.wireframe = coin.SoGroup()
     self.scale = coin.SoScale()
     self.color = coin.SoBaseColor()

     self.data=coin.SoCoordinate3()
     self.face=coin.SoIndexedFaceSet()

     self.shaded.addChild(self.scale)
     self.shaded.addChild(self.color)
     self.shaded.addChild(self.data)
     self.shaded.addChild(self.face)
     obj.addDisplayMode(self.shaded,"Shaded");
     style=coin.SoDrawStyle()
     style.style = coin.SoDrawStyle.LINES
     self.wireframe.addChild(style)
     self.wireframe.addChild(self.scale)
     self.wireframe.addChild(self.color)
     self.wireframe.addChild(self.data)
     self.wireframe.addChild(self.face)
     obj.addDisplayMode(self.wireframe,"Wireframe");
     self.onChanged(obj,"Color")

  def updateData(self, fp, prop):
     "If a property of the handled feature has changed we have the chance to handle this here"
     # fp is the handled feature, prop is the name of the property that has changed
     if prop == "Shape":
        s = fp.getPropertyByName("Shape")
        self.data.point.setNum(6)
        cnt=0
        for i in s.Vertexes:
           self.data.point.set1Value(cnt,i.X,i.Y,i.Z)
           cnt=cnt+1

        self.face.coordIndex.set1Value(0,0)
        self.face.coordIndex.set1Value(1,1)
        self.face.coordIndex.set1Value(2,2)
        self.face.coordIndex.set1Value(3,-1)

        self.face.coordIndex.set1Value(4,1)
        self.face.coordIndex.set1Value(5,3)
        self.face.coordIndex.set1Value(6,2)
        self.face.coordIndex.set1Value(7,-1)

        self.face.coordIndex.set1Value(8,3)
        self.face.coordIndex.set1Value(9,4)
        self.face.coordIndex.set1Value(10,2)
        self.face.coordIndex.set1Value(11,-1)

        self.face.coordIndex.set1Value(12,4)
        self.face.coordIndex.set1Value(13,0)
        self.face.coordIndex.set1Value(14,2)
        self.face.coordIndex.set1Value(15,-1)

        self.face.coordIndex.set1Value(16,1)
        self.face.coordIndex.set1Value(17,0)
        self.face.coordIndex.set1Value(18,5)
        self.face.coordIndex.set1Value(19,-1)

        self.face.coordIndex.set1Value(20,3)
        self.face.coordIndex.set1Value(21,1)
        self.face.coordIndex.set1Value(22,5)
        self.face.coordIndex.set1Value(23,-1)

        self.face.coordIndex.set1Value(24,4)
        self.face.coordIndex.set1Value(25,3)
        self.face.coordIndex.set1Value(26,5)
        self.face.coordIndex.set1Value(27,-1)

        self.face.coordIndex.set1Value(28,0)
        self.face.coordIndex.set1Value(29,4)
        self.face.coordIndex.set1Value(30,5)
        self.face.coordIndex.set1Value(31,-1)

  def getDisplayModes(self,obj):
     "Return a list of display modes."
     modes=[]
     modes.append("Shaded")
     modes.append("Wireframe")
     return modes

  def getDefaultDisplayMode(self):
     "Return the name of the default display mode. It must be defined in getDisplayModes."
     return "Shaded"

  def setDisplayMode(self,mode):
     return mode

  def onChanged(self, vp, prop):
     "Here we can do something when a single property got changed"
     FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
     if prop == "Color":
        c = vp.getPropertyByName("Color")
        self.color.rgb.setValue(c[0],c[1],c[2])

  def getIcon(self):
     return """
        /* XPM */
        static const char * ViewProviderBox_xpm[] = {
        "16 16 6 1",
        "    c None",
        ".   c #141010",
        "+   c #615BD2",
        "@   c #C39D55",
        "#   c #000000",
        "$   c #57C355",
        "        ........",
        "   ......++..+..",
        "   .@@@@.++..++.",
        "   .@@@@.++..++.",
        "   .@@  .++++++.",
        "  ..@@  .++..++.",
        "###@@@@ .++..++.",
        "##$.@@$#.++++++.",
        "#$#$.$$$........",
        "#$$#######      ",
        "#$$#$$$$$#      ",
        "#$$#$$$$$#      ",
        "#$$#$$$$$#      ",
        " #$#$$$$$#      ",
        "  ##$$$$$#      ",
        "   #######      "};
        """

  def dumps(self):
     return None

  def loads(self,state):
     return None

În cele din urmă, odată ce obiectul și obiectul său de vedere sunt definite, trebuie doar să le numim (clasa Octahedron și codul clasei viewprovider pot fi copiate direct în consola Python FreeCAD):

FreeCAD.newDocument()
a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron")
Octahedron(a)
ViewProviderOctahedron(a.ViewObject)

Making objects selectable

Crearea de obiecte selectabile

Dacă doriți să faceți obiectul selectabil sau cel puțin o parte a acestuia, făcând clic pe el în fereastra de vizualizare, trebuie să includeți forma geometriei sale în interiorul unui nod SoFCSelection. Dacă obiectul are o reprezentare complexă, cu widget-uri, adnotări etc., poate doriți să includeți doar o parte a acestuia într-o selecție SoFCSelecție. Tot ceea ce este un SoFCSelection este scanat constant de FreeCAD pentru a detecta selectia / preselectarea, deci ar fi bine să nu incercați a o supraincarca cu scanări inutile. Iată un exemplu de ceea ce ați face pentru a include o self.face din exemplul de mai sus :

Once the parts of the scenegraph that are to be selectable are inside SoFCSelection nodes, you then need to provide two methods to handle the selection path. The selection path can take the form of a string giving the names of each element in the path, or of an array of scenegraph objects. The two methods you provide are getDetailPath, which converts from a string path to an array of scenegraph objects, and getElementPicked, which takes an element which has been clicked on in the scenegraph and returns its string name (note, not its string path).

Here is the molecule example above, adapted to make the elements of the molecule selectable:

class Molecule:
    def __init__(self, obj):
        ''' Add two point properties '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0)

        obj.Proxy = self

    def onChanged(self, fp, prop):
        if prop == "p1" or prop == "p2":
            ''' Print the name of the property that has changed '''
            fp.Shape = Part.makeLine(fp.p1,fp.p2)

    def execute(self, fp):
        ''' Print a short message when doing a recomputation, this method is mandatory '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

class ViewProviderMolecule:
    def __init__(self, obj):
        ''' Set this object to the proxy object of the actual view provider '''
        obj.Proxy = self
        self.ViewObject = obj
        sep1=coin.SoSeparator()
        sel1 = coin.SoType.fromName('SoFCSelection').createInstance()
        # sel1.policy.setValue(coin.SoSelection.SHIFT)
        sel1.ref()
        sep1.addChild(sel1)
        self.trl1=coin.SoTranslation()
        sel1.addChild(self.trl1)
        sel1.addChild(coin.SoSphere())
        sep2=coin.SoSeparator()
        sel2 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel2.ref()
        sep2.addChild(sel2)
        self.trl2=coin.SoTranslation()
        sel2.addChild(self.trl2)
        sel2.addChild(coin.SoSphere())
        obj.RootNode.addChild(sep1)
        obj.RootNode.addChild(sep2)
        self.updateData(obj.Object, 'p2')
        self.sel1 = sel1
        self.sel2 = sel2

    def getDetailPath(self, subname, path, append):
        vobj = self.ViewObject
        if append:
            path.append(vobj.RootNode)
            path.append(vobj.SwitchNode)

            mode = vobj.SwitchNode.whichChild.getValue()
            if mode >= 0:
                mode = vobj.SwitchNode.getChild(mode)
                path.append(mode)
                sub = Part.splitSubname(subname)[-1]
                if sub == 'Atom1':
                    path.append(self.sel1)
                elif sub == 'Atom2':
                    path.append(self.sel2)
                else:
                    path.append(mode.getChild(0))
        return True

    def getElementPicked(self, pp):
        path = pp.getPath()
        if path.findNode(self.sel1) >= 0:
            return 'Atom1'
        if path.findNode(self.sel2) >= 0:
            return 'Atom2'
        raise NotImplementedError

    def updateData(self, fp, prop):
        "If a property of the handled feature has changed we have the chance to handle this here"
        # fp is the handled feature, prop is the name of the property that has changed
        if prop == "p1":
            p = fp.getPropertyByName("p1")
            self.trl1.translation=(p.x,p.y,p.z)
        elif prop == "p2":
            p = fp.getPropertyByName("p2")
            self.trl2.translation=(p.x,p.y,p.z)

    def dumps(self):
        return None

    def loads(self,state):
        return None

def makeMolecule():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Molecule")
    Molecule(a)
    ViewProviderMolecule(a.ViewObject)
    FreeCAD.ActiveDocument.recompute()

Working with simple shapes

Lucrul cu forme simple

Dacă obiectul dvs. parametric emite doar o formă simplă, nu este necesar să utilizați un obiect furnizor de vizualizare(view provider object). Forma va fi afișată utilizând reprezentarea standard a formelor din FreeCAD:

import FreeCAD as App
import FreeCADGui
import FreeCAD
import Part
class Line:
    def __init__(self, obj):
        '''"App two point properties" '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(1,0,0)
        obj.Proxy = self

    def execute(self, fp):
        '''"Print a short message when doing a recomputation, this method is mandatory" '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
Line(a)
a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification)
FreeCAD.ActiveDocument.recompute()

Același cod utilizând ViewProviderLine

import FreeCAD as App
import FreeCADGui
import FreeCAD
import Part

class Line:
    def __init__(self, obj):
         '''"App two point properties" '''
         obj.addProperty("App::PropertyVector","p1","Line","Start point")
         obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(100,0,0)
         obj.Proxy = self

    def execute(self, fp):
        '''"Print a short message when doing a recomputation, this method is mandatory" '''
        fp.Shape = Part.makeLine(fp.p1,fp.p2)

class ViewProviderLine:
   def __init__(self, obj):
      ''' Set this object to the proxy object of the actual view provider '''
      obj.Proxy = self

   def getDefaultDisplayMode(self):
      ''' Return the name of the default display mode. It must be defined in getDisplayModes. '''
      return "Flat Lines"

a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
Line(a)
ViewProviderLine(a.ViewObject)
App.ActiveDocument.recompute()

Scenegraph Structure

You may have noticed that the examples above construct their scenegraphs in slightly different ways. Some use obj.addDisplayMode(node, "modename") while others use obj.SwitchNode.getChild(x).addChild(y).

Each feature in a FreeCAD document is based the following scenegraph structure:

RootNode
 \- SwitchNode
     \- Shaded
      - Wireframe
      - etc

The SwitchNode displays only one of its children, depending on which display mode is selection in FreeCAD.

The examples which use addDisplayMode are constructing their scenegraphs solely out of coin3d scenegraph elements. Under the covers, addDisplayMode adds a new child to the SwitchNode; the name of that node will match the display mode it was passed.

The examples which use SwitchNode.getChild(x).addChild also construct part of their geometry using functions from the Part workbench, such as fp.Shape = Part.makeLine(fp.p1,fp.p2). This constructs the different display mode scenegraphs under the SwitchNode; when we later come to add coin3d elements to the scenegraph, we need to add them to the existing display mode scenegraphs using addChild rather than creating a new child of the SwitchNode.

When using addDisplayMode() to add geometry to the scenegraph, each display mode should have its own node which is passed to addDisplayMode(); don't reuse the same node for this. Doing so will confuse the selection mechanism. It's okay if each display mode's node has the same geometry nodes added below it, just the root of each display mode needs to be distinct.

Here is the above molecule example, adapted to be drawn only with Coin3D scenegraph objects instead of using objects from the Part workbench:

import Part
from pivy import coin

class Molecule:
    def __init__(self, obj):
        ''' Add two point properties '''
        obj.addProperty("App::PropertyVector","p1","Line","Start point")
        obj.addProperty("App::PropertyVector","p2","Line","End point").p2=FreeCAD.Vector(5,0,0)

        obj.Proxy = self

    def onChanged(self, fp, prop):
        pass

    def execute(self, fp):
        ''' Print a short message when doing a recomputation, this method is mandatory '''
        pass

class ViewProviderMolecule:
    def __init__(self, obj):
        ''' Set this object to the proxy object of the actual view provider '''
        self.constructed = False
        obj.Proxy = self
        self.ViewObject = obj

    def attach(self, obj):
        material = coin.SoMaterial()
        material.diffuseColor = (1.0, 0.0, 0.0)
        material.emissiveColor = (1.0, 0.0, 0.0)
        drawStyle = coin.SoDrawStyle()
        drawStyle.pointSize.setValue(10)
        drawStyle.style = coin.SoDrawStyle.LINES
        wireframe = coin.SoGroup()
        shaded = coin.SoGroup()
        self.wireframe = wireframe
        self.shaded = shaded

        self.coords = coin.SoCoordinate3()
        self.coords.point.setValues(0, 2, [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0)])
        wireframe += self.coords
        wireframe += drawStyle
        wireframe += material
        shaded += self.coords
        shaded += drawStyle
        shaded += material

        g = coin.SoGroup()
        sel1 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel1.style = 'EMISSIVE_DIFFUSE'
        p1 = coin.SoType.fromName('SoIndexedPointSet').createInstance()
        p1.coordIndex.set1Value(0, 0)
        sel1 += p1
        g += sel1
        wireframe += g
        shaded += g

        g = coin.SoGroup()
        sel2 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel2.style = 'EMISSIVE_DIFFUSE'
        p2 = coin.SoType.fromName('SoIndexedPointSet').createInstance()
        p2.coordIndex.set1Value(0, 1)
        sel2 += p2
        g += sel2
        wireframe += g
        shaded += g

        g = coin.SoGroup()
        sel3 = coin.SoType.fromName('SoFCSelection').createInstance()
        sel3.style = 'EMISSIVE_DIFFUSE'
        p3 = coin.SoType.fromName('SoIndexedLineSet').createInstance()
        p3.coordIndex.setValues(0, 2, [0, 1])
        sel3 += p3
        g += sel3
        wireframe += g
        shaded += g

        obj.addDisplayMode(wireframe, 'Wireframe')
        obj.addDisplayMode(shaded, 'Shaded')

        self.sel1 = sel1
        self.sel2 = sel2
        self.sel3 = sel3
        self.constructed = True
        self.updateData(obj.Object, 'p2')

    def getDetailPath(self, subname, path, append):
        vobj = self.ViewObject
        if append:
            path.append(vobj.RootNode)
            path.append(vobj.SwitchNode)

            mode = vobj.SwitchNode.whichChild.getValue()
            FreeCAD.Console.PrintWarning("getDetailPath: mode {} is active\n".format(mode))
            if mode >= 0:
                mode = vobj.SwitchNode.getChild(mode)
                path.append(mode)
                sub = Part.splitSubname(subname)[-1]
                print(sub)
                if sub == 'Atom1':
                    path.append(self.sel1)
                elif sub == 'Atom2':
                    path.append(self.sel2)
                elif sub == 'Line':
                    path.append(self.sel3)
                else:
                    path.append(mode.getChild(0))
        return True

    def getElementPicked(self, pp):
        path = pp.getPath()
        if path.findNode(self.sel1) >= 0:
            return 'Atom1'
        if path.findNode(self.sel2) >= 0:
            return 'Atom2'
        if path.findNode(self.sel3) >= 0:
            return 'Line'
        raise NotImplementedError

    def updateData(self, fp, prop):
        "If a property of the handled feature has changed we have the chance to handle this here"
        # fp is the handled feature, prop is the name of the property that has changed
        if not self.constructed:
            return
        if prop == "p1":
            p = fp.getPropertyByName("p1")
            self.coords.point.set1Value(0, p)
        elif prop == "p2":
            p = fp.getPropertyByName("p2")
            self.coords.point.set1Value(1, p)

    def getDisplayModes(self, obj):
        return ['Wireframe', 'Shaded']

    def getDefaultDisplayMode(self):
        return 'Shaded'

    def setDisplayMode(self, mode):
        return mode

    def dumps(self):
        return None

    def loads(self,state):
        return None

def makeMolecule():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Molecule")
    Molecule(a)
    b=ViewProviderMolecule(a.ViewObject)
    a.touch()
    FreeCAD.ActiveDocument.recompute()
    return a,b

a,b = makeMolecule()

Part Design scripted objects

When making scripted objects in Part Design the process is similar to the scripted objects discussed above, but with a few additional considerations. We must handle 2 shape properties, one for the shape we see in the 3D view and another for the shape used by the pattern tools, such as polar pattern features. The object shapes also needs to be fused to any existing material already in the Body (or cut from it in the case of Subtractive features). And we must account for the placement and attachment of our objects a little bit differently.

Part Design scripted solid object features should be based on either PartDesign::FeaturePython, PartDesign::FeatureAdditivePython, or PartDesign::FeatureSubtractivePython rather than Part::FeaturePython. Only the Additive and Subtractive variants can be used in pattern features, and if based on Part::FeaturePython when the user drops the object into a Part Design Body it becomes a BaseFeature rather than being treated by the Body as a native Part Design object. Note: all of these are expected to be solids, so if you are making a non-solid feature it should be based on Part::FeaturePython or else the next feature in the tree will attempt to fuse to as a solid and it will fail.

Here is a simple example of making a Tube primitive, similar to the Tube primitive in Part Workbench except this one will be a Part Design solid feature object. For this we will 2 separate files: pdtube.FCMacro and pdtube.py. The .FCMacro file will be executed by the user to create the object. The .py file will hold the class definitions, imported by the .FCMacro. The reason for doing it this way is to maintain the parametric nature of the object after restarting FreeCAD and opening a document containing one of our Tubes.

First, the class definition file:

# -*- coding: utf-8 -*-
#classes should go in pdtube.py
import FreeCAD, FreeCADGui, Part
class PDTube:
    def __init__(self,obj):
        obj.addProperty("App::PropertyLength","Radius1","Tube","Radius1").Radius1 = 5
        obj.addProperty("App::PropertyLength","Radius2","Tube","Radius2").Radius2 = 10
        obj.addProperty("App::PropertyLength","Height","Tube","Height of tube").Height = 10
        self.makeAttachable(obj)
        obj.Proxy = self

    def makeAttachable(self, obj):

        if int(FreeCAD.Version()[1]) >= 19:
            obj.addExtension('Part::AttachExtensionPython')
        else:
            obj.addExtension('Part::AttachExtensionPython', obj)

        obj.setEditorMode('Placement', 0) #non-readonly non-hidden

    def execute(self,fp):
        outer_cylinder = Part.makeCylinder(fp.Radius2, fp.Height)
        inner_cylinder = Part.makeCylinder(fp.Radius1, fp.Height)
        if fp.Radius1 == fp.Radius2: #just make cylinder
            tube_shape = outer_cylinder
        elif fp.Radius1 < fp.Radius2:
            tube_shape = outer_cylinder.cut(inner_cylinder)
        else: #invert rather than error out
            tube_shape = inner_cylinder.cut(outer_cylinder)

        if not hasattr(fp, "positionBySupport"):
            self.makeAttachable(fp)
        fp.positionBySupport()
        tube_shape.Placement = fp.Placement

        #BaseFeature (shape property of type Part::PropertyPartShape) is provided for us
        #with the PartDesign::FeaturePython and related classes, but it might be empty
        #if our object is the first object in the tree.  it's a good idea to check
        #for its existence in case we want to make type Part::FeaturePython, which won't have it

        if hasattr(fp, "BaseFeature") and fp.BaseFeature != None:
            if "Subtractive" in fp.TypeId:
                full_shape = fp.BaseFeature.Shape.cut(tube_shape)
            else:
                full_shape = fp.BaseFeature.Shape.fuse(tube_shape)
            full_shape.transformShape(fp.Placement.inverse().toMatrix(), True) #borrowed from gears workbench
            fp.Shape = full_shape
        else:
            fp.Shape = tube_shape
        if hasattr(fp,"AddSubShape"): #PartDesign::FeatureAdditivePython and
                                      #PartDesign::FeatureSubtractivePython have this
                                      #property but PartDesign::FeaturePython does not
                                      #It is the shape used for copying in pattern features
                                      #for example in making a polar pattern
            tube_shape.transformShape(fp.Placement.inverse().toMatrix(), True)
            fp.AddSubShape = tube_shape

class PDTubeVP:
    def __init__(self, obj):
        '''Set this object to the proxy object of the actual view provider'''
        obj.Proxy = self

    def attach(self,vobj):
        self.vobj = vobj

    def updateData(self, fp, prop):
        '''If a property of the handled feature has changed we have the chance to handle this here'''
        pass

    def getDisplayModes(self,obj):
        '''Return a list of display modes.'''
        modes=[]
        modes.append("Flat Lines")
        modes.append("Shaded")
        modes.append("Wireframe")
        return modes

    def getDefaultDisplayMode(self):
        '''Return the name of the default display mode. It must be defined in getDisplayModes.'''
        return "Flat Lines"

    def setDisplayMode(self,mode):
        '''Map the display mode defined in attach with those defined in getDisplayModes.\
                Since they have the same names nothing needs to be done. This method is optional'''
        return mode

    def onChanged(self, vp, prop):
        '''Here we can do something when a single property got changed'''
        #FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n")
        pass

    def getIcon(self):
        '''Return the icon in XPM format which will appear in the tree view. This method is\
                optional and if not defined a default icon is shown.'''
        return """
            /* XPM */
            static const char * ViewProviderBox_xpm[] = {
            "16 16 6 1",
            "   c None",
            ".  c #141010",
            "+  c #615BD2",
            "@  c #C39D55",
            "#  c #000000",
            "$  c #57C355",
            "        ........",
            "   ......++..+..",
            "   .@@@@.++..++.",
            "   .@@@@.++..++.",
            "   .@@  .++++++.",
            "  ..@@  .++..++.",
            "###@@@@ .++..++.",
            "##$.@@$#.++++++.",
            "#$#$.$$$........",
            "#$$#######      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            "#$$#$$$$$#      ",
            " #$#$$$$$#      ",
            "  ##$$$$$#      ",
            "   #######      "};
            """

    def dumps(self):
        '''When saving the document this object gets stored using Python's json module.\
                Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
                to return a tuple of all serializable objects or None.'''
        return None

    def loads(self,state):
        '''When restoring the serialized object from document we have the chance to set some internals here.\
                Since no data were serialized nothing needs to be done here.'''
        return None

And now the macro file to create the object:

# -*- coding: utf-8 -*-

#pdtube.FCMacro
import pdtube
#above line needed if the class definitions above are place in another file: PDTube.py
#this is needed if the tube object is to remain parametric after restarting FreeCAD and loading
#a document containing the object

body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody")
if not body:
    FreeCAD.Console.PrintError("No active body.\n")
else:
    from PySide import QtGui
    window = FreeCADGui.getMainWindow()
    items = ["Additive","Subtractive","Neither additive nor subtractive"]
    item,ok =QtGui.QInputDialog.getItem(window,"Select tube type","Select whether you want additive, subtractive, or neither:",items,0,False)
    if ok:
        if item == items[0]:
            className = "PartDesign::FeatureAdditivePython"
        elif item == items[1]:
            className = "PartDesign::FeatureSubtractivePython"
        else:
            className = "PartDesign::FeaturePython" #not usable in pattern features, such as polar pattern

        tube = FreeCAD.ActiveDocument.addObject(className,"Tube")
        pdtube.PDTube(tube)
        pdtube.PDTubeVP(tube.ViewObject)
        body.addObject(tube) #optionally we can also use body.insertObject() for placing at particular place in tree

Available object types

The list of all object types you can create with FreeCAD.ActiveDocument.addObject() can be obtained with FreeCAD.ActiveDocument.supportedTypes(). Only object types with a name ending in Python can be used for scripted objects. These are listed here (for FreeCAD v0.21):

  • App::DocumentObjectGroupPython
  • App::FeaturePython
  • App::GeometryPython
  • App::LinkElementPython
  • App::LinkGroupPython
  • App::LinkPython
  • App::MaterialObjectPython
  • App::PlacementPython
  • Part::CustomFeaturePython
  • Part::FeaturePython
  • Part::Part2DObjectPython
  • Path::FeatureAreaPython
  • Path::FeatureAreaViewPython
  • Path::FeatureCompoundPython
  • Path::FeaturePython
  • Path::FeatureShapePython
  • Sketcher::SketchObjectPython
  • TechDraw::DrawComplexSectionPython
  • TechDraw::DrawLeaderLinePython
  • TechDraw::DrawPagePython
  • TechDraw::DrawRichAnnoPython
  • TechDraw::DrawTemplatePython
  • TechDraw::DrawTilePython
  • TechDraw::DrawTileWeldPython
  • TechDraw::DrawViewPartPython
  • TechDraw::DrawViewPython
  • TechDraw::DrawViewSectionPython
  • TechDraw::DrawViewSymbolPython
  • TechDraw::DrawWeldSymbolPython

Available methods

See FeaturePython methods for the complete reference.

Available properties

Proprietăți disponibile

Proprietățile sunt adevăratele pietre de temelie ale obiectelor FeaturePython. Prin intermediul acestora, utilizatorul va putea să interacționeze și să vă modifice obiectul. După crearea unui nou obiect FeaturePython din documentul dvs. (obj = FreeCAD.ActiveDocument.addObject ("App :: FeaturePython", "Box")), puteți obține o listă a proprietăților disponibile prin emiterea:

obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Box")
obj.supportedProperties()

Veți obține o listă cu proprietățile disponibile:

Când adăugați proprietăți obiectelor dvs. personalizate, aveți grijă de acestea:

  • Nu utilizați caractere "<" sau ">" în descrierile de proprietăți (care ar sparge fragmente de cod în fișierul xml.fcstd)
  • Proprietățile sunt stocate în ordine alfabetică într-un fișier .fcstd. Toate proprietățile ale căror nume vine după ”Shape” sunt așezate în ordine alfabetică . Dacă aveți o formă în proprietățile dvs., și cum orice proprietate al cărei nume vine după "Shape", se poate să aveți parte de comportamente ciudate.

The properties are defined in the PropertyStandard C++ header file.

Property types

Tipuri de proprietăți

Implicit proprietățile pot fi actualizate. Este posibil să se facă proprietățile numai pentru citire, de exemplu în cazul în care cineva dorește să afișeze rezultatul unei metode. De asemenea, este posibilă ascunderea proprietății. Tipul de proprietate poate fi setat utilizând

obj.setEditorMode("MyPropertyName", mode)

unde mode este un int scurt care poate fi definit ca:

 0 -- modul imolicit, read and write
 1 -- read-only
 2 -- hidden

The mode can also be set using a list of strings, e.g. obj.setEditorMode("Placement", ["ReadOnly", "Hidden"]).

EditorModes nu sunt definite la reîncărcarea fișierului FreeCAD. Acest lucru ar putea fi făcut prin funcția the __setstate__ function. Vezi http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=10#p108072. Folosind setEditorMode proprietățile sunt citite numai în PropertyEditor. S-ar putea schimba încă de la Python. Pentru a le face să citească doar setarea trebuie să fie transmisă direct în interiorul funcției addProperty. A s vedea http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=20#p109709 for an example.

Using the direct setting in the addProperty function, you also have more possibilities. In particular, an interesting one is mark a property as an output property. This way FreeCAD won't mark the feature as touched when changing it (so no need to recompute).

Example of output property (see also https://forum.freecadweb.org/viewtopic.php?t=24928):

obj.addProperty("App::PropertyString", "MyCustomProperty", "", "", 8)

The property types that can be set at last parameter of the addProperty function are:

  0 -- Prop_None, No special property type
  1 -- Prop_ReadOnly, Property is read-only in the editor
  2 -- Prop_Transient, Property won't be saved to file
  4 -- Prop_Hidden, Property won't appear in the editor
  8 -- Prop_Output, Modified property doesn't touch its parent container
 16 -- Prop_NoRecompute, Modified property doesn't touch its container for recompute
 32 -- Prop_NoPersist, Property won't be saved to file at all

The property types are defined in the PropertyContainer C++ header file.

Available extensions

The list of available extensions can be obtained with grep -RI EXTENSION_PROPERTY_SOURCE_TEMPLATE in the repository of the source code and is given here (for FreeCAD v0.21).

For objects:

  • App::GeoFeatureGroupExtensionPython
  • App::GroupExtensionPython
  • App::LinkBaseExtensionPython
  • App::LinkExtensionPython
  • App::OriginGroupExtensionPython
  • Part::AttachExtensionPython
  • TechDraw::CosmeticExtensionPython

For view objects:

  • Gui::ViewProviderExtensionPython
  • Gui::ViewProviderGeoFeatureGroupExtensionPython
  • Gui::ViewProviderGroupExtensionPython
  • Gui::ViewProviderOriginGroupExtensionPython
  • PartGui::ViewProviderAttachExtensionPython
  • PartGui::ViewProviderSplineExtensionPython

There exist other extensions but they do not work as-is:

  • App::ExtensionPython
  • TechDrawGui::ViewProviderCosmeticExtensionPython
  • TechDrawGui::ViewProviderDrawingViewExtensionPython
  • TechDrawGui::ViewProviderPageExtensionPython
  • TechDrawGui::ViewProviderTemplateExtensionPython

Informație suplimentară

Există câteva subiecte foarte interesante pe forum despre obiectele script:

Additional pages:

Interesting forum threads about scripted objects:

În plus față de exemplele prezentate aici puteți să vă aruncați o privire în codul sursă FreeCAD src/Mod/TemplatePyMod/FeaturePython.py for more examples.


PySide
Embedding FreeCAD


Introduction

FreeCAD are capacitatea uimitoare de a fi importabil ca modul python în alte programe sau într-o consolă python autonomă, împreună cu toate modulele și componentele sale. Este posibil chiar să importați interfața grafică GUI-ul FreeCAD ca modul python - cu some restrictions, dar cu anumite restricții.

Utilizarea FreeCAD fără interfață grafică/GUI

O primă aplicație directă, ușoară și utilă pe care o puteți face este importul documentelor FreeCAD în programul dvs. În următorul exemplu, vom importa geometria pieselor unui document FreeCAD în blender. Iată scenariul complet. Sper că veți fi impresionat de simplitatea sa:

FREECADPATH = '/usr/lib/freecad-python3/lib/' # path to your FreeCAD.so or FreeCAD.pyd file,
# for Windows you must either use \\ or / in the path, using a single \ is problematic
# FREECADPATH = 'C:\\FreeCAD\\bin'
import Blender, sys
sys.path.append(FREECADPATH)
 
def import_fcstd(filename):
   try:
       import FreeCAD
   except ValueError:
       Blender.Draw.PupMenu('Error%t|FreeCAD library not found. Please check the FREECADPATH variable in the import script is correct')
   else:
       scene = Blender.Scene.GetCurrent()
       import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':
               shape = ob.Shape
               if shape.Faces:
                   mesh = Blender.Mesh.New()
                   rawdata = shape.tessellate(1)
                   for v in rawdata[0]:
                       mesh.verts.append((v.x,v.y,v.z))
                   for f in rawdata[1]:
                       mesh.faces.append.append(f)
                   scene.objects.new(mesh,ob.Name)
       Blender.Redraw()

def main():
   Blender.Window.FileSelector(import_fcstd, 'IMPORT FCSTD', 
                        Blender.sys.makename(ext='.fcstd'))    
 
# This lets you import the script without running it
if __name__=='__main__':
   main()

Prima parte importantă este să vă asigurați că Python va găsi biblioteca noastră FreeCAD. Odată ce o găsește, toate modulele FreeCAD, cum ar fi Part, pe care o vom folosi, vor fi disponibile automat. Așa că luăm pur și simplu variabila sys.path, care este unde Python caută module și adăugăm calea FreCAD.Lib. Această modificare este doar temporară și se va pierde atunci când închidem interpretorul nostru python. Un alt mod ar putea fi să faceți o legătură cu biblioteca dvs. FreeCAD într-una din căile de căutare python. Am păstrat calea într-o constantă (FREECADPATH) astfel încât un alt utilizator al scriptului îi va fi mai ușor să configureze propriul sistem

FREECADPATH = 'C:\\FreeCAD\\bin' # path to your FreeCAD.so or FreeCAD.pyd file
import sys
sys.path.append(FREECADPATH)

Odată ce suntem siguri că biblioteca este încărcată (secvența try/except), acum putem lucra cu FreeCAD, la fel ca și cum am fi în interiorul interpretului Python al FreeCAD. Deschidem documentul FreeCAD care ne este transmis prin funcția principală main() și facem o listă a obiectelor sale. Apoi, pe măsură ce alegem doar să ne pese de geometria piesei, verificăm dacă proprietatea Type a fiecărui obiect conține "Part", apoi o mozaicăm (tessellation).

import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':

Mozaicarea (Tessellation) produce o listă de vârfuri(vertex) și o listă de fasțete definite de indici de vârfuri. Acest lucru este perfect, deoarece este exact același mod în care programul Blender definește ochiurile de plasă. Deci, sarcina noastră este ridicol de simplă, adăugăm ambele conținuturi ale listelor la vârfurile și fețetele unei rețele de tip Blender. Când totul este realizat, noi redesenăm ecranul și gata ”c'est fini” !

if ob.Type[:4] == 'Part':
               shape = ob.Shape
               if shape.Faces:
                   mesh = Blender.Mesh.New()
                   rawdata = shape.tessellate(1)
                   for v in rawdata[0]:
                       mesh.verts.append((v.x,v.y,v.z))
                   for f in rawdata[1]:
                       mesh.faces.append.append(f)
                   scene.objects.new(mesh,ob.Name)
       Blender.Redraw()

Bineînțeles, ați văzut că acest script este foarte simplu (de fapt am făcut unul mai avansat aici here),ați putea dori să-l extindeți, de exemplu importarea obiectelor de tip plasă, sau importarea ”Part Geometry” care nu are fațete sau importul altor formate de fișiere pe care FreeCAD le poate citi. De asemenea, ați putea dori să exportați forme geometrice într-un document FreeCAD, care se poate face în același mod. S-ar putea să doriți, de asemenea, să construiți un dialog, astfel încât utilizatorul să poată alege ce să importe, etc.... Frumusețea tuturor acestor lucruri constă de fapt că l-ai lăsat pe FreeCAD să efectueze în totalitate, prezentându-și în același timp rezultatele în programul pe care l-ai ales .

Note: checkout Headless FreeCAD for running FreeCAD without the GUI.

Utilizarea FreeCAD cu interfață grafică(GUI)

De la versiunea 4.2 cu Qt are capacitatea de a încorpora plugin-urile dependente de Qt-GUI în aplicații gazdă non-Qt și de a partaja bucla evenimentului gazdei.

Mai presus de toate, pentru FreeCAD, aceasta înseamnă că poate fi importat dintr-o altă aplicație cu interfața sa completă de utilizator (GUI) și în consecință aplicația gazdă controlează pe deplin FreeCAD.

Tot codul python pentru a obține aceasta are numai 2 linii

import FreeCADGui 
FreeCADGui.showMainWindow()

Dacă aplicația se bazează pe Qt, atunci aceasta soluție ar trebui să funcționeze pe toate platformele suportate de către Qt . Cu toate acestea, gazda ar trebui să conecteze aceeași versiune QT ca și FreeCAD, deoarece altfel ați putea obține erori de execuție neașteptate.

Cu toate acestea, pentru aplicațiile non-Qt există câteva limitări pe care trebuie să le cunoașteți. Această soluție probabil nu funcționează împreună cu toate celelalte seturi de instrumente(toolkit). Pentru Windows funcționează atât timp cât aplicația gazdă este compatibilă și se bazează direct pe Win32 sau pe orice alt set de instrumente care utilizează intern API-ul Win32, cum ar fi wxWidgets, MFC sau WinForms. Pentru ca aceasta să funcționeze sub X11(Linux), aplicația gazdă trebuie să conecteze biblioteca "glib".

Notă, pentru orice aplicație consolă această soluție, această soluție, nu va funcționa deoarece nu este o funcționare în buclă de evenimente (event loop running) în acest sistem.

Avertismente

Deși este posibil să importați FreeCAD la un interpretor extern Python, acesta este un scenariu de utilizare obișnuit și necesită o atenție deosebită. În general, este mai bine să folosiți Python inclus în FreeCAD, via o linia de comandă sau ca pe un subproces. Vedeți Start up and Configuration pentru mai multe informații asupra ultimelor două opțiuni.

Deoarece modulul FreeCAD Python este compilat din C ++ (mai degrabă decât de a fi un modul Python pur), acesta poate fi importat numai de la un interpretorul Python compatibil. În general, acest lucru înseamnă că interpretorul Python trebuie să fie compilat cu același compilator C, cum a fost cel folosit pentru a construi FreeCAD. Informații despre compilatorul folosit pentru a construi un interpretor Python (inclusiv cel construit cu FreeCAD), pot fi găsite la:

>>> import sys
>>> sys.version
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'

Related



Introduction

Această pagină conține exemple, extrase, fragmente de cod Python de la FreeCAD, colectate din experiențele utilizatorilor și discuțiile pe forumuri. Citește și folosește-o ca un început pentru scripturile tale ...

Snippets

Un fișier tipic InitGui.py

Fiecare modul trebuie să conțină, pe lângă fișierul modulului principal, un fișier InitGui.py, responsabil pentru înserarea modulului GUI principal. Acesta este un exemplu simplu.

Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

class ScriptWorkbench (Workbench): 
    MenuText = "Scripts"
    def Initialize(self):
        import Scripts # assuming Scripts.py is your module
        list = ["Script_Cmd"] # That list must contain command names, that can be defined in Scripts.py
        self.appendToolbar("My Scripts",list) 
        
Gui.addWorkbench(ScriptWorkbench())

Top

Un fișier modul tipic

Acesta este un exemplu al unui fișier modul principal, care conține tot ceea ce face modul dvs. Acesta este fișierul Scripts.py invocat în exemplul anterior. Puteți să aveți toate comenzile personalizate aici.

This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

import FreeCAD, FreeCADGui 
 
class ScriptCmd: 
   def Activated(self): 
       # Here your write what your ScriptCmd does...
       FreeCAD.Console.PrintMessage('Hello, World!')
   def GetResources(self): 
       return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} 
       
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())

Top

Importul unui nou tip de fișier

Efectuarea unui import pentru un nou tip de fișier în FreeCAD este ușoară. FreeCAD nu ia în considerare că importați orice date într-un document deschis, pentru că nu puteți deschide direct un nou tip de fișier. Deci, ceea ce trebuie să faceți este să adăugați noua extensie de fișiere în lista de extensii cunoscute a FreeCAD și să scrieți codul care va citi fișierul și va crea obiectele FreeCAD pe care le doriți:

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

Această linie trebuie adăugată în fișierul InitGui.py pentru a adăuga noua extensie de fișier în listă de extensii:

# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")

Then in the Import_Ext.py file:

def open(filename): 
   doc=App.newDocument()
   # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
   doc.recompute()

Pentru a exporta documentul la unele tipuri de fișiere noi funcționează în același mod, cu excepția faptului că utilizați:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

Top

Adăugarea unei linii (segment)

O linie este definită doar de 2 puncte.

A line simply has 2 points.

import Part,PartGui 
doc=App.activeDocument() 
# add a line element to the document and set its points 
l=Part.LineSegment()
l.StartPoint=(0.0,0.0,0.0)
l.EndPoint=(1.0,1.0,1.0)
doc.addObject("Part::Feature","Line").Shape=l.toShape() 
doc.recompute()

Top

Adăugarea unui poligon

Un poligon este pur și simplu un set de segmente de linie conectate (o polilinie în AutoCAD). Nu este obligatoriu să fie închisă.

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

import Part, PartGui 
doc = App.activeDocument()
n = list() 

# create a 3D vector, set its coordinates and add it to the list 
v = App.Vector(0,0,0) 
n.append(v) 
v = App.Vector(10,0,0) 
n.append(v) 
#... repeat for all nodes 

# Create a polygon object and set its nodes 
p = doc.addObject("Part::Polygon","Polygon") 
p.Nodes = n 
doc.recompute()

Top

Adăugarea și îndepărtarea unui obiect într-un grup

doc=App.activeDocument() 
grp=doc.addObject("App::DocumentObjectGroup", "Group") 
lin=doc.addObject("Part::Feature", "Line")
grp.addObject(lin) # adds the lin object to the group grp
grp.removeObject(lin) # removes the lin object from the group grp

Notă: Puteți chiar să adăugați un alt grup la un grup...

Top

Adăugarea unei plase

import Mesh
doc=App.activeDocument()
# create a new empty mesh
m = Mesh.Mesh()
# build up box out of 12 facets
m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0)
m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0)
m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0)
m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0)
m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)
# scale to a edge langth of 100
m.scale(100.0)
# add the mesh to the active document
me=doc.addObject("Mesh::Feature","Cube")
me.Mesh=m

Top

Adăugarea unui cerc sau a unui arc de cerc

import Part
doc = App.activeDocument()
c = Part.Circle() 
c.Radius=10.0  
f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature 
f.Shape = c.toShape() # Assign the circle shape to the shape property 
doc.recompute()

Top

Accesarea și schimbarea reprezentării unui obiect

Fiecare obiect dintr-un document FreeCAD are un obiect vederii asociat, care stochează toți parametrii care definesc proprietățile obiectului, cum ar fi culoarea, lățimea liniei etc.

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how that object appears: i.e. color, linewidth, etc... See also List the components of an object snippet below

gad = Gui.activeDocument() # access the active document containing all 
                           # view representations of the features in the
                           # corresponding App document 

v = gad.getObject("Cube")  # access the view representation to the Mesh feature 'Cube' 
v.ShapeColor               # prints the color to the console 
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white

Top

Replace the form of mouse with one image

import PySide2
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QColor, QPixmap, QImage, QPainter, QCursor
from PySide2.QtCore import Qt

myImage = QtGui.QPixmap("Complete_Path_to_image.bmp")
cursor = QtGui.QCursor(myImage)
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(cursor))

Top

Replace the form of mouse with one image (cross) include

The image is created by Gimp exported in a .XPM file. Copy and use the code between the bracket "{" code to copy "}"

import PySide2
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QColor, QPixmap, QImage, QPainter, QCursor
from PySide2.QtCore import Qt

cross32x32Icon = [
"32 32 2 1",
" 	c None",
".	c #FF0000",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                                ",
"............... . ..............",
"                                ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               ",
"                .               "
]

myImage = QtGui.QPixmap(cross32x32Icon)
cursor = QtGui.QCursor(myImage)
QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(cursor))

Top

Observe camera change in the 3D viewer via Python

This can be done adding a Node sensor to the camera:

from pivy import coin
def callback(*args):
    cam, sensor = args
    print()
    print("Cam position : {}".format(cam.position.getValue().getValue()))
    print("Cam rotation : {}".format(cam.orientation.getValue().getValue()))

camera_node = Gui.ActiveDocument.ActiveView.getCameraNode()
node_sensor = coin.SoNodeSensor(callback, camera_node)
node_sensor.attach(camera_node)

Top

Observarea evenimentelor mouse-ului în vizualizatorul 3D via Python

Cadrul Inventor permite adăugarea unuia sau mai multor noduri de apel invers(callback) la scena grafică vizualizată. În mod implicit, în FreeCAD, un nod de apel invers este instalat per vizualizator(fereastra de afișare grafică), ceea ce permite adăugarea funcțiilor globale sau statice C ++. Metode de legarea adecvată sunt furnizate de Python, pentru a permite utilizarea acestei tehnici plecând de la codul Python.

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

App.newDocument()
v=Gui.activeDocument().activeView()
 
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
   def logPosition(self, info):
       down = (info["State"] == "DOWN")
       pos = info["Position"]
       if (down):
           FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
       
o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)


Acum, alegeți undeva în zona din ecran (suprafață de lucru)vizualizatorul 3D și observați mesajele din fereastra de ieșire. Pentru a termina observația, trebuie doar să sunați

v.removeEventCallback("SoMouseButtonEvent",c)

Următoarele tipuri de evenimente sunt suportate

  • SoEvent -- orice tip de evenimente
  • SoButtonEvent -- toate evenimentele butoanele /rotiță mouse
  • SoLocation2Event -- evenimente mișcări 2D (mișcările normale ale mouse-lui)
  • SoMotion3Event -- evenimentele mișcări 3D (normale pentru spaceball)
  • SoKeyboardEvent -- evenimente de tastare a tastelor cu săgeți sus/jos
  • SoMouseButtonEvent -- evenimentul de tastare și eliberare a butoanelor mouse
  • SoSpaceballButtonEvent -- evenimentul de tastare și eliberare a butoanelor spaceball

Funcțiile Python care pot fi înregistrate cu addEventCallback() așteaptă definirea unei bilbioteci. Funcție de modul în care evenimentul survine , biblioteca poate dispunde diferite taste. Este alocată câte o tastă pentru fiecare eveniment:

În funcție de eveniment, dicționarul poate conține diferite taste alocate.

Pentru toate evenimentele are tastele:

  • Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
  • Time -- timpul curent ca șir de caractere
  • Position -- tuple de două numere întregi, reprezentând poziția mouse-ului
  • ShiftDown -- un indicator boolean, adevărat dacă Shift a fost apăsat altfel fals
  • CtrlDown -- un indicator boolean, adevărat dacă Ctrl a fost apăsat altfel fals
  • AltDown -- un indicator boolean, adevărat dacă Alt a fost apăsat altfel fals

Pentru toate evenimentele gen apăsare de buton, adică evenimente de tip tastatură, mouse sau spațiu

  • State -- Un șir text dacă butonul este 'UP' , 'DOWN' dacă butonul este jos, sau pentru orice alt caz 'UNKNOWN'

pentru evenimentele tip apăsare tastatură:

  • Key -- caracterul tastei apăsate

pentru evenimente buton de mouse

  • Button -- Butonul apăsat, poate lua valorile BUTTON1, ..., BUTTON5 sau oricare dintre ele

pentru evenimente tip spaceball:

  • Button -- butonul apăsat poate lua valorile, BUTTON1, ..., BUTTON7 sau oricare dintre ele ANY

Și în sfârșit, evenimentele legate de deplasare:

  • Translation -- o tuplă de trei numere cu virgulă float()
  • Rotation -- un quaternion pentru rotație, adică o tuplă de patru valori exprimate cu virgulă float()

Top

Afișați tastele apăsate și evenimentele comenzi

Această macrocomandă afișează în vizualizarea raportului tastele apăsate și comanda tuturor evenimentelor

This macro displays in the report view the keys pressed and all events command

App.newDocument()
v=Gui.activeDocument().activeView()
class ViewObserver:
   def logPosition(self, info):
       try:
           down = (info["Key"])
           FreeCAD.Console.PrintMessage(str(down)+"\n") # here the character pressed
           FreeCAD.Console.PrintMessage(str(info)+"\n") # list all events command
           FreeCAD.Console.PrintMessage("_______________________________________"+"\n")
       except Exception:
           None
 
o = ViewObserver()
c = v.addEventCallback("SoEvent",o.logPosition)

#v.removeEventCallback("SoEvent",c) # remove ViewObserver

Top

Manipularea de scene grafice în Python

De asemenea, este posibil să se afișeze și să se schimbe scen în programul Python, cu modulul "pivy" - în combinație cu Coin.

It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

from pivy.coin import *                # load the pivy module
view = Gui.ActiveDocument.ActiveView   # get the active viewer
root = view.getSceneGraph()            # the root is an SoSeparator node
root.addChild(SoCube())
view.fitAll()

API-ul Python API-ul de tip pivy este creat folosind instrumentul SWIG. Pe măsură ce folosim în FreeCAD niște noduri scrise automat, pe care nu le puteți crea direct în Python. Cu toate acestea, este posibil să creați un nod prin numele său intern. Un exemplu de tipul "SoFCSelection" poate fi creată cu:

type = SoType.fromName("SoFCSelection")
node = type.createInstance()

Top

Adăugarea și eliminarea obiectelor în / de la scena de grafică

Adăugarea de noi noduri în scena grafică poate fi făcută astfel. Aveți grijă să adăugați mereu un SoSeparator pentru a conține proprietățile formei geometrice, coordonatele și informațiile despre material ale aceluiași obiect. Următorul exemplu adaugă o linie roșie de la (0,0,0) până la (10,0,0):

Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

from pivy import coin
sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
co = coin.SoCoordinate3()
pts = [[0,0,0],[10,0,0]]
co.point.setValues(0,len(pts),pts)
ma = coin.SoBaseColor()
ma.rgb = (1,0,0)
li = coin.SoLineSet()
li.numVertices.setValue(2)
no = coin.SoSeparator()
no.addChild(co)
no.addChild(ma)
no.addChild(li)
sg.addChild(no)

Pentru a șerge pe acesta, este cimplu:

sg.removeChild(no)

Top

Salvați sceneGraph cu o rotație într-o serie de 36 fișiere în axele X Y Z

View the code snippet by expanding this section

import math
import time
from FreeCAD import Base
from pivy import coin

size=(1000,1000)
dirname = "C:/Temp/animation/"
steps=36
angle=2*math.pi/steps

matX=Base.Matrix()
matX.rotateX(angle)
stepsX=Base.Placement(matX).Rotation

matY=Base.Matrix()
matY.rotateY(angle)
stepsY=Base.Placement(matY).Rotation

matZ=Base.Matrix()
matZ.rotateZ(angle)
stepsZ=Base.Placement(matZ).Rotation

view=Gui.ActiveDocument.ActiveView
cam=view.getCameraNode()
rotCamera=Base.Rotation(*cam.orientation.getValue().getValue())

# this sets the lookat point to the center of circumsphere of the global bounding box
view.fitAll()

# the camera's position, i.e. the user's eye point
position=Base.Vector(*cam.position.getValue().getValue())
distance=cam.focalDistance.getValue()

# view direction
vec=rotCamera.multVec(Base.Vector(0,0,-1))

# this is the point on the screen the camera looks at
# when rotating the camera we should make this point fix
lookat=position+vec*distance

# around x axis
for i in range(steps):
    rotCamera=stepsX.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"x-%d.png" % i,*size)

# around y axis
for i in range(steps):
    rotCamera=stepsY.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"y-%d.png" % i,*size)

# around z axis
for i in range(steps):
    rotCamera=stepsZ.multiply(rotCamera)
    cam.orientation.setValue(*rotCamera.Q)
    vec=rotCamera.multVec(Base.Vector(0,0,-1))
    pos=lookat-vec*distance
    cam.position.setValue(pos.x,pos.y,pos.z)
    Gui.updateGui()
    time.sleep(0.3)
    view.saveImage(dirname+"z-%d.png" % i,*size)

Top

Adăugarea de widget-uri personalizate la interfață

Puteți crea widget-uri personalizate cu designerul Qt, le puteți transforma într-un script python și apoi le puteți încărca în interfața FreeCAD cu PySide.

You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PySide.

Codul python produs de compilatorul Ui python (instrumentul care convertește fișierele qt-designer .ui în codul python), în general, arată astfel (este simplu, puteți, de asemenea, să îl codificați direct în Python):

class myWidget_Ui(object):
    def setupUi(self, myWidget):
        myWidget.setObjectName("my Nice New Widget")
        myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget
 
        self.label = QtGui.QLabel(myWidget) # creates a label
        self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
        self.label.setObjectName("label") # sets its name, so it can be found by name

    def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets
        myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))

Apoi, tot ce trebuie să faceți este să creați o referință la fereastra Qt FreeCAD, să-i inserați un widget personalizat în ea și să transferați codul Ui al acestui widget pe care tocmai l-am făcut:

app = QtGui.qApp
FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
# FCmw = FreeCADGui.getMainWindow() # use this line if the 'addDockWidget' error is declared
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget
myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Top

Adăugarea unui tab în vizualizarea Combo

Următorul cod vă permite să adăugați o filă în FreeCAD ComboView, pe lângă filele "Project" și "Tasks". De asemenea, utilizează modulul uic pentru a încărca un fișier ui direct în acea filă.

The following code allows you to add a tab to the Combo view, separate from the preexisting "Model" and "Tasks" tabs. It also uses the uic module to load an UI file directly in that tab.

# create new Tab in ComboView
from PySide import QtGui,QtCore
#from PySide import uic

def getMainWindow():
   "returns the main window"
   # using QtGui.qApp.activeWindow() isn't very reliable because if another
   # widget than the mainwindow is active (e.g. a dialog) the wrong widget is
   # returned
   toplevel = QtGui.qApp.topLevelWidgets()
   for i in toplevel:
       if i.metaObject().className() == "Gui::MainWindow":
           return i
   raise Exception("No main window found")

def getComboView(mw):
   dw=mw.findChildren(QtGui.QDockWidget)
   for i in dw:
       if str(i.objectName()) == "Combo View":
           return i.findChild(QtGui.QTabWidget)
       elif str(i.objectName()) == "Python Console":
           return i.findChild(QtGui.QTabWidget)
   raise Exception ("No tab widget found")

mw = getMainWindow()
tab = getComboView(getMainWindow())
tab2=QtGui.QDialog()
tab.addTab(tab2,"A Special Tab")

#uic.loadUi("/myTaskPanelforTabs.ui",tab2)
tab2.show()
#tab.removeTab(2)

Top

Activați sau dezactivați o fereastră

This script give the ability to manipulate the UI from the Python console to show/hide different components in the FreeCAD interface such as:

from PySide import QtGui
mw = FreeCADGui.getMainWindow()
dws = mw.findChildren(QtGui.QDockWidget)

# objectName may be :
# "Report view"
# "Tree view"
# "Property view"
# "Selection view"
# "Combo View"
# "Python console"
# "draftToolbar"

for i in dws:
  if i.objectName() == "Report view":
    dw = i
    break

va = dw.toggleViewAction()
va.setChecked(True)        # True or False
dw.setVisible(True)        # True or False

Top

Deschiderea unei pagini web personalizate

import WebGui
WebGui.openBrowser("http://www.example.com")

Top

Obținerea conținutului HTML al unei pagini Web deschise

from PySide import QtGui,QtWebKit
a = QtGui.qApp
mw = a.activeWindow()
v = mw.findChild(QtWebKit.QWebFrame)
html = unicode(v.toHtml())
print( html)

Top

Recuperați și utilizați coordonatele a 3 puncte sau obiecte selectate

# -*- coding: utf-8 -*-
# the line above to put the accentuated in the remarks
# If this line is missing, an error will be returned
# extract and use the coordinates of 3 objects selected
import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base, Console
sel = FreeCADGui.Selection.getSelection() # " sel " contains the items selected
if len(sel)!=3 :
  # If there are no 3 objects selected, an error is displayed in the report view
  # The \r and \n at the end of line mean return and the newline CR + LF.
  Console.PrintError("Select 3 points exactly\r\n")
else :
  points=[]
  for obj in sel:
    points.append(obj.Shape.BoundBox.Center)

  for pt in points:
    # display of the coordinates in the report view
    Console.PrintMessage(str(pt.x)+"\r\n")
    Console.PrintMessage(str(pt.y)+"\r\n")
    Console.PrintMessage(str(pt.z)+"\r\n")

  Console.PrintMessage(str(pt[1]) + "\r\n")

Top

Listarea tuturor obeictelor

# -*- coding: utf-8 -*-
import FreeCAD,Draft
# List all objects of the document
doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects
#App.Console.PrintMessage(str(objs) + "\n")
#App.Console.PrintMessage(str(len(FreeCAD.ActiveDocument.Objects)) + " Objects"  + "\n")

for obj in objs:
    a = obj.Name                                             # list the Name  of the object  (not modifiable)
    b = obj.Label                                            # list the Label of the object  (modifiable)
    try:
        c = obj.LabelText                                    # list the LabeText of the text (modifiable)
        App.Console.PrintMessage(str(a) +" "+ str(b) +" "+ str(c) + "\n") # Displays the Name the Label and the text
    except:
        App.Console.PrintMessage(str(a) +" "+ str(b) + "\n") # Displays the Name and the Label of the object

#doc.removeObject("Box") # Clears the designated object

Top

Listează dimensiunile unui obiect, având în vedere numele acestuia

for edge in FreeCAD.ActiveDocument.MyObjectName.Shape.Edges: # replace "MyObjectName" for list
    print( edge.Length)

Top

Funcția rezidentă cu acțiunea clicului mouse-ului

Here with SelObserver on a object select

# -*- coding: utf-8 -*-
# causes an action to the mouse click on an object
# This function remains resident (in memory) with the function "addObserver(s)"
# "removeObserver(s) # Uninstalls the resident function
class SelObserver:
    def setPreselection(self,doc,obj,sub):                # Preselection object
        App.Console.PrintMessage(str(sub)+ "\n")          # The part of the object name

    def addSelection(self,doc,obj,sub,pnt):               # Selection object
        App.Console.PrintMessage("addSelection"+ "\n")
        App.Console.PrintMessage(str(doc)+ "\n")          # Name of the document
        App.Console.PrintMessage(str(obj)+ "\n")          # Name of the object
        App.Console.PrintMessage(str(sub)+ "\n")          # The part of the object name
        App.Console.PrintMessage(str(pnt)+ "\n")          # Coordinates of the object
        App.Console.PrintMessage("______"+ "\n")

    def removeSelection(self,doc,obj,sub):                # Remove the selection
        App.Console.PrintMessage("removeSelection"+ "\n")

    def setSelection(self,doc):                           # Set selection
        App.Console.PrintMessage("setSelection"+ "\n")

    def clearSelection(self,doc):                         # If click on the screen, clear the selection
        App.Console.PrintMessage("clearSelection"+ "\n")  # If click on another object, clear the previous object
s =SelObserver()
FreeCADGui.Selection.addObserver(s)                       # install the function mode resident
#FreeCADGui.Selection.removeObserver(s)                   # Uninstall the resident function

Other example with ViewObserver on a object select or view

App.newDocument()
v=Gui.activeDocument().activeView()
 
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
   def __init__(self, view):
       self.view = view
   
   def logPosition(self, info):
       down = (info["State"] == "DOWN")
       pos = info["Position"]
       if (down):
           FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
           pnt = self.view.getPoint(pos)
           FreeCAD.Console.PrintMessage("World coordinates: " + str(pnt) + "\n")
           info = self.view.getObjectInfo(pos)
           FreeCAD.Console.PrintMessage("Object info: " + str(info) + "\n")

o = ViewObserver(v)
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)

Top

Display the active document

class DocObserver:                      # document Observer
    def slotActivateDocument(self,doc):
        print(doc.Name)

obs=DocObserver()
App.addDocumentObserver(obs)
#App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

To remove the observer call:

App.removeDocumentObserver(obs)                 # desinstalle la fonction residente

Top

căutarea și selecția tuturor elementelor de sub cursor

from pivy import coin
import FreeCADGui

def mouse_over_cb( event_callback):
    event = event_callback.getEvent()
    pos = event.getPosition().getValue()
    listObjects = FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo((int(pos[0]),int(pos[1])))
    obj = []
    if listObjects:
        FreeCAD.Console.PrintMessage("\n *** Objects under mouse pointer ***")
        for o in listObjects:
            label = str(o["Object"])
            if not label in obj:
                obj.append(label)
        FreeCAD.Console.PrintMessage("\n"+str(obj))


view = FreeCADGui.ActiveDocument.ActiveView

mouse_over = view.addEventCallbackPivy( coin.SoLocation2Event.getClassTypeId(), mouse_over_cb )

# to remove Callback :
#view.removeEventCallbackPivy( coin.SoLocation2Event.getClassTypeId(), mouse_over)

####
#The easy way is probably to use FreeCAD's selection.
#FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo(mouse_coords)

####
#you get that kind of result :
#'Document': 'Unnamed', 'Object': 'Box', 'Component': 'Face2', 'y': 8.604081153869629, 'x': 21.0, 'z': 8.553047180175781

####
#You can use this data to add your element to FreeCAD's selection :
#FreeCADGui.Selection.addSelection(FreeCAD.ActiveDocument.Box,'Face2',21.0,8.604081153869629,8.553047180175781)

Top

Lista componentelor unui obiect

This function list the components of an object and extracts:

  • this object its XYZ coordinates,
  • its edges and their lengths center of mass and coordinates
  • its faces and their center of mass
  • its faces and their surfaces and coordinates
# -*- coding: utf-8 -*-
# This function list the components of an object
# and extract this object its XYZ coordinates,
# its edges and their lengths center of mass and coordinates
# its faces and their center of mass
# its faces and their surfaces and coordinates
# 8/05/2014

import Draft,Part
def detail():
    sel = FreeCADGui.Selection.getSelection()   # Select an object
    if len(sel) != 0:                           # If there is a selection then
        Vertx=[]
        Edges=[]
        Faces=[]
        compt_V=0
        compt_E=0
        compt_F=0
        pas    =0
        perimetre = 0.0   
        EdgesLong = []

        # Displays the "Name" and the "Label" of the selection
        App.Console.PrintMessage("Selection > " + str(sel[0].Name) + "  " + str(sel[0].Label) +"\n"+"\n")

        for j in enumerate(sel[0].Shape.Edges):                                     # Search the "Edges" and their lengths
            compt_E+=1
            Edges.append("Edge%d" % (j[0]+1))
            EdgesLong.append(str(sel[0].Shape.Edges[compt_E-1].Length))
            perimetre += (sel[0].Shape.Edges[compt_E-1].Length)                     # calculates the perimeter

            # Displays the "Edge" and its length
            App.Console.PrintMessage("Edge"+str(compt_E)+" Length > "+str(sel[0].Shape.Edges[compt_E-1].Length)+"\n")

            # Displays the "Edge" and its center mass
            App.Console.PrintMessage("Edge"+str(compt_E)+" Center > "+str(sel[0].Shape.Edges[compt_E-1].CenterOfMass)+"\n")

            num = sel[0].Shape.Edges[compt_E-1].Vertexes[0]
            Vertx.append("X1: "+str(num.Point.x))
            Vertx.append("Y1: "+str(num.Point.y))
            Vertx.append("Z1: "+str(num.Point.z))
            # Displays the coordinates 1
            App.Console.PrintMessage("X1: "+str(num.Point[0])+" Y1: "+str(num.Point[1])+" Z1: "+str(num.Point[2])+"\n")

            try:
                num = sel[0].Shape.Edges[compt_E-1].Vertexes[1]
                Vertx.append("X2: "+str(num.Point.x))
                Vertx.append("Y2: "+str(num.Point.y))
                Vertx.append("Z2: "+str(num.Point.z))
            except:
                Vertx.append("-")
                Vertx.append("-")
                Vertx.append("-")
            # Displays the coordinates 2
            App.Console.PrintMessage("X2: "+str(num.Point[0])+" Y2: "+str(num.Point[1])+" Z2: "+str(num.Point[2])+"\n")

            App.Console.PrintMessage("\n")
        App.Console.PrintMessage("Perimeter of the form  : "+str(perimetre)+"\n") 

        App.Console.PrintMessage("\n")
        FacesSurf = []
        for j in enumerate(sel[0].Shape.Faces):                                      # Search the "Faces" and their surface
            compt_F+=1
            Faces.append("Face%d" % (j[0]+1))
            FacesSurf.append(str(sel[0].Shape.Faces[compt_F-1].Area))

            # Displays 'Face' and its surface
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Surface "+str(sel[0].Shape.Faces[compt_F-1].Area)+"\n")

            # Displays 'Face' and its CenterOfMass
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Center  "+str(sel[0].Shape.Faces[compt_F-1].CenterOfMass)+"\n")

            # Displays 'Face' and its Coordinates
            FacesCoor = []
            fco = 0
            for f0 in sel[0].Shape.Faces[compt_F-1].Vertexes:                        # Search the Vertexes of the face
                fco += 1
                FacesCoor.append("X"+str(fco)+": "+str(f0.Point.x))
                FacesCoor.append("Y"+str(fco)+": "+str(f0.Point.y))
                FacesCoor.append("Z"+str(fco)+": "+str(f0.Point.z))

            # Displays 'Face' and its Coordinates
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Coordinate"+str(FacesCoor)+"\n")

            # Displays 'Face' and its Volume
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Volume  "+str(sel[0].Shape.Faces[compt_F-1].Volume)+"\n")
            App.Console.PrintMessage("\n")

        # Displays the total surface of the form
        App.Console.PrintMessage("Surface of the form    : "+str(sel[0].Shape.Area)+"\n")

        # Displays the total Volume of the form
        App.Console.PrintMessage("Volume  of the form    : "+str(sel[0].Shape.Volume)+"\n")

detail()

Top

Lista PropertiesList

import FreeCADGui
from FreeCAD import Console
o = App.ActiveDocument.ActiveObject
op = o.PropertiesList
for p in op:
    Console.PrintMessage("Property: "+ str(p)+ " Value: " + str(o.getPropertyByName(p))+"\r\n")

Top

Adăugarea unei proprietăți "Comentariu"

import Draft
obj = FreeCADGui.Selection.getSelection()[0]
obj.addProperty("App::PropertyString","GComment","Draft","Font name").GComment = "Comment here"
App.activeDocument().recompute()

Top

Căutarea și extracția datelor

Example de cautare și decodare a informației despre un obiect.

Fiecare secțiune este independentă și este separată de diezi "############" poate fi copiată direct în consola Python sau într-o macrocomandă sau poate folosi această macrocomandă. Descrierea macrocomenzii în comentariu.

Afișajul se face în fereastra "View Report" (View > Views > View report)

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
 
# Exemples de recherche et de decodage d'informations sur un objet
# Chaque section peut etre copiee directement dans la console Python ou dans une macro ou utilisez la macro tel quel
# Certaines commandes se repetent seul l'approche est differente
# L'affichage se fait dans la Vue rapport : Menu Affichage > Vues > Vue rapport
#
# Examples of research and decoding information on an object
# Each section can be copied directly into the Python console, or in a macro or uses this macro
# Certain commands as repeat alone approach is different
# Displayed in Report view: View > Views > report view
#
# rev:30/08/2014:29/09/2014:17/09/2015 22/11/2019 30/12/2022
 
from FreeCAD import Base
import DraftVecUtils, Draft, Part

##################################################################################
# info in the object

box = App.ActiveDocument.getObject('Box')                                 # object 
####
print(dir(box))                                                           # all options disponible in the object
####
print(box.Name)                                                           # object name
####
print(box.Content)                                                        # content of the object in XML format
##################################################################################
#
# example of using the information listed
#
# search the name of the active document 
mydoc = FreeCAD.activeDocument().Name                                     # Name of active Document
App.Console.PrintMessage("Active docu    : "+(mydoc)+"\n")
##################################################################################

# search the document name and the name of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_FullName = sel[0].FullName                                         # file Name and Name of the object selected
App.Console.PrintMessage("object_FullName: "+(object_FullName)+"\n")
##################################################################################

# search the label of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_Label = sel[0].Label                                               # Label of the object (modifiable)
App.Console.PrintMessage("object_Label   : "+(object_Label)+"\n")
##################################################################################

#TypeID object FreeCAD selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
App.Console.PrintMessage("sel            : "+str(sel[0])+"\n\n")          # sel[0] first object selected
##################################################################################

# search the Name of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
object_Name  = sel[0].Name                                                # Name of the object (not modifiable)
App.Console.PrintMessage("object_Name    : "+str(object_Name)+"\n\n")
##################################################################################

# search the Sub Element Name of the sub object selected
try:
    SubElement = FreeCADGui.Selection.getSelectionEx()                    # sub element name with getSelectionEx()
    element_ = SubElement[0].SubElementNames[0]                           # name of 1 element selected
    App.Console.PrintMessage("elementSelec   : "+str(element_)+"\n\n")            
except:
    App.Console.PrintMessage("Oups"+"\n\n")            
##################################################################################

# give the length of the subObject selected
SubElementLength = Gui.Selection.getSelectionEx()[0].SubObjects[0].Length # sub element or element name with getSelectionEx()
App.Console.PrintMessage("SubElement length: "+str(SubElementLength)+"\n")# length
##################################################################################

# list the edges and the coordinates of the object[0] selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
i = 0
for j in enumerate(sel[0].Shape.Edges):                                   # list all Edges
    i += 1
    App.Console.PrintMessage("Edges n : "+str(i)+"\n")
    a = sel[0].Shape.Edges[j[0]].Vertexes[0]
    App.Console.PrintMessage("X1             : "+str(a.Point.x)+"\n")     # coordinate XYZ first point
    App.Console.PrintMessage("Y1             : "+str(a.Point.y)+"\n")     #
    App.Console.PrintMessage("Z1             : "+str(a.Point.z)+"\n")     #
    try:
        a = sel[0].Shape.Edges[j[0]].Vertexes[1]
        App.Console.PrintMessage("X2             : "+str(a.Point.x)+"\n") # coordinate XYZ second point
        App.Console.PrintMessage("Y2             : "+str(a.Point.y)+"\n") #
        App.Console.PrintMessage("Z2             : "+str(a.Point.z)+"\n") #
    except:
        App.Console.PrintMessage("Oups"+"\n")    
App.Console.PrintMessage("\n")    
##################################################################################

# give the sub element name, length, coordinates, BoundBox, BoundBox.Center, Area of the SubObjects selected
try:
    SubElement = FreeCADGui.Selection.getSelectionEx()                                        # sub element name with getSelectionEx()
    subElementName = Gui.Selection.getSelectionEx()[0].SubElementNames[0]                     # sub element name with getSelectionEx()
    App.Console.PrintMessage("subElementName : "+str(subElementName)+"\n")
    
    subObjectLength = Gui.Selection.getSelectionEx()[0].SubObjects[0].Length                  # sub element Length
    App.Console.PrintMessage("subObjectLength: "+str(subObjectLength)+"\n\n")
    
    subObjectX1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.x         # sub element coordinate X1
    App.Console.PrintMessage("subObject_X1   : "+str(subObjectX1)+"\n")
    subObjectY1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.y         # sub element coordinate Y1
    App.Console.PrintMessage("subObject_Y1   : "+str(subObjectY1)+"\n")
    subObjectZ1 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[0].Point.z         # sub element coordinate Z1
    App.Console.PrintMessage("subObject_Z1   : "+str(subObjectZ1)+"\n\n")

    try:
        subObjectX2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.x     # sub element coordinate X2
        App.Console.PrintMessage("subObject_X2   : "+str(subObjectX2)+"\n")
        subObjectY2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.y     # sub element coordinate Y2
        App.Console.PrintMessage("subObject_Y2   : "+str(subObjectY2)+"\n")
        subObjectZ2 = Gui.Selection.getSelectionEx()[0].SubObjects[0].Vertexes[1].Point.z     # sub element coordinate Z2
        App.Console.PrintMessage("subObject_Z2   : "+str(subObjectZ2)+"\n\n")
    except:
        App.Console.PrintMessage("Oups"+"\n\n")            

    subObjectBoundBox = Gui.Selection.getSelectionEx()[0].SubObjects[0].BoundBox              # sub element BoundBox coordinates
    App.Console.PrintMessage("subObjectBBox  : "+str(subObjectBoundBox)+"\n")
    
    subObjectBoundBoxCenter = Gui.Selection.getSelectionEx()[0].SubObjects[0].BoundBox.Center # sub element BoundBoxCenter
    App.Console.PrintMessage("subObjectBBoxCe: "+str(subObjectBoundBoxCenter)+"\n")
    
    surfaceFace = Gui.Selection.getSelectionEx()[0].SubObjects[0].Area                        # Area of the face selected
    App.Console.PrintMessage("surfaceFace    : "+str(surfaceFace)+"\n\n")
except:
    App.Console.PrintMessage("Oups"+"\n\n")            
##################################################################################

# give the area of the object
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
surface = sel[0].Shape.Area                                               # Area object complete
App.Console.PrintMessage("surfaceObjet   : "+str(surface)+"\n\n")
##################################################################################

# give the Center Of Mass and coordinates of the object
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
CenterOfMass = sel[0].Shape.CenterOfMass                                  # Center of Mass of the object
App.Console.PrintMessage("CenterOfMass   : "+str(CenterOfMass)+"\n")
App.Console.PrintMessage("CenterOfMassX  : "+str(CenterOfMass[0])+"\n")   # coordinates [0]=X [1]=Y [2]=Z
App.Console.PrintMessage("CenterOfMassY  : "+str(CenterOfMass[1])+"\n")   # or CenterOfMass.x, CenterOfMass.y, CenterOfMass.z
App.Console.PrintMessage("CenterOfMassZ  : "+str(CenterOfMass[2])+"\n\n")
##################################################################################

# list the all faces of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
for j in enumerate(sel[0].Shape.Faces):                                   # List alles faces of the object
    App.Console.PrintMessage("Face           : "+str("Face%d" % (j[0]+1))+"\n")
App.Console.PrintMessage("\n\n")
##################################################################################

# give the volume of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
volume_ = sel[0].Shape.Volume                                             # Volume of the object
App.Console.PrintMessage("volume_        : "+str(volume_)+"\n\n")
##################################################################################
 
# give the BoundBox of the oject selected all type
objs = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
if len(objs) >= 1:                                                         # serch the object type
    if hasattr(objs[0], "Shape"):
        s = objs[0].Shape
    elif hasattr(objs[0], "Mesh"):      # upgrade with wmayer thanks #http://forum.freecadweb.org/viewtopic.php?f=13&t=22331
        s = objs[0].Mesh
    elif hasattr(objs[0], "Points"):
        s = objs[0].Points

boundBox_= s.BoundBox                                                     # BoundBox of the object
App.Console.PrintMessage("boundBox_      : "+str(boundBox_)+"\n")         # 
 
boundBoxLX   = boundBox_.XLength                                          # Length x boundBox rectangle
boundBoxLY   = boundBox_.YLength                                          # Length y boundBox rectangle
boundBoxLZ   = boundBox_.ZLength                                          # Length z boundBox rectangle

boundBoxXMin = boundBox_.XMin                                             # coordonate XMin
boundBoxYMin = boundBox_.YMin                                             # coordonate YMin
boundBoxZMin = boundBox_.ZMin                                             # coordonate ZMin
boundBoxXMax = boundBox_.XMax                                             # coordonate XMax
boundBoxYMax = boundBox_.YMax                                             # coordonate YMax
boundBoxZMax = boundBox_.ZMax                                             # coordonate ZMax

boundBoxDiag= boundBox_.DiagonalLength                                    # Diagonal Length boundBox rectangle
boundBoxCenter = boundBox_.Center                                         # BoundBox Center
boundBoxCenterOfGravity = boundBox_.CenterOfGravity                       # BoundBox CenterOfGravity

App.Console.PrintMessage("boundBoxLX     : "+str(boundBoxLX)+"\n")
App.Console.PrintMessage("boundBoxLY     : "+str(boundBoxLY)+"\n")
App.Console.PrintMessage("boundBoxLZ     : "+str(boundBoxLZ)+"\n\n")

App.Console.PrintMessage("boundBoxXMin   : "+str(boundBoxXMin)+"\n")
App.Console.PrintMessage("boundBoxYMin   : "+str(boundBoxYMin)+"\n")
App.Console.PrintMessage("boundBoxZMin   : "+str(boundBoxZMin)+"\n")
App.Console.PrintMessage("boundBoxXMax   : "+str(boundBoxXMax)+"\n")
App.Console.PrintMessage("boundBoxYMax   : "+str(boundBoxYMax)+"\n")
App.Console.PrintMessage("boundBoxZMax   : "+str(boundBoxZMax)+"\n\n")

App.Console.PrintMessage("boundBoxDiag   : "+str(boundBoxDiag)+"\n")
App.Console.PrintMessage("boundBoxCenter : "+str(boundBoxCenter)+"\n")

App.Console.PrintMessage("boundBox Center of Gravity : "+str(boundBoxCenterOfGravity )+"\n\n")

##################################################################################

# give the complete placement of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement                                               # Placement Vector XYZ and Yaw-Pitch-Roll
App.Console.PrintMessage("Placement      : "+str(pl)+"\n")
##################################################################################

# give the placement Base (xyz) of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Base                                          # Placement Vector XYZ
App.Console.PrintMessage("PlacementBase  : "+str(pl)+"\n\n")
##################################################################################
 
# give the placement Base (xyz) of the object selected
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
oripl_X = sel[0].Placement.Base[0]                                        # decode Placement X
oripl_Y = sel[0].Placement.Base[1]                                        # decode Placement Y
oripl_Z = sel[0].Placement.Base[2]                                        # decode Placement Z

# same 
#oripl_X = sel[0].Placement.Base.x                                        # decode Placement X
#oripl_Y = sel[0].Placement.Base.y                                        # decode Placement Y
#oripl_Z = sel[0].Placement.Base.z                                        # decode Placement Z
 
App.Console.PrintMessage("oripl_X        : "+str(oripl_X)+"\n")
App.Console.PrintMessage("oripl_Y        : "+str(oripl_Y)+"\n")
App.Console.PrintMessage("oripl_Z        : "+str(oripl_Z)+"\n\n")
##################################################################################

# give the placement rotation of the object selected (x, y, z, angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
rotation = sel[0].Placement.Rotation                                      # decode Placement Rotation
App.Console.PrintMessage("rotation              : "+str(rotation)+"\n\n")
##################################################################################

# give the placement rotation of the object selected (x, y, z, angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Rotation                                      # decode Placement Rotation other method
App.Console.PrintMessage("Placement Rot         : "+str(pl)+"\n\n")
##################################################################################

# give the rotation of the object selected (angle rotation)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
pl = sel[0].Shape.Placement.Rotation.Angle                                # decode Placement Rotation Angle
App.Console.PrintMessage("Placement Rot Angle   : "+str(pl)+"\n\n")
##################################################################################

# give the rotation.Q of the object selected (angle rotation in Radian) for convert: math.degrees(angleInRadian)
sel = FreeCADGui.Selection.getSelection()                                 # select object with getSelection()
Rot   = sel[0].Placement.Rotation.Q                                       # Placement Rotation Q
App.Console.PrintMessage("Rot           : "+str(Rot)+ "\n")
 
Rot_0 = sel[0].Placement.Rotation.Q[0]                                    # decode Placement Rotation Q
App.Console.PrintMessage("Rot_0         : "+str(Rot_0)+ " rad ,  "+str(180 * Rot_0 / 3.1416)+" deg "+"\n") # or math.degrees(angle)
 
Rot_1 = sel[0].Placement.Rotation.Q[1]                                    # decode Placement Rotation 1
App.Console.PrintMessage("Rot_1         : "+str(Rot_1)+ " rad ,  "+str(180 * Rot_1 / 3.1416)+" deg "+"\n") # or math.degrees(angle)
 
Rot_2 = sel[0].Placement.Rotation.Q[2]                                    # decode Placement Rotation 2
App.Console.PrintMessage("Rot_2         : "+str(Rot_2)+ " rad ,  "+str(180 * Rot_2 / 3.1416)+" deg "+"\n") # or math.degrees(angle)

Rot_3 = sel[0].Placement.Rotation.Q[3]                                    # decode Placement Rotation 3
App.Console.PrintMessage("Rot_3         : "+str(Rot_3)+"\n\n")

Rot_Axis = sel[0].Placement.Rotation.Axis                                 # Placement Rotation .Axis
App.Console.PrintMessage("Rot_Axis      : "+str(Rot_Axis)+ "\n")
 
Rot_Angle = sel[0].Placement.Rotation.Angle                               # Placement Rotation .Angle
App.Console.PrintMessage("Rot_Angle     : "+str(Rot_Angle)+ "\n\n")
##################################################################################

# give the rotation of the object selected toEuler (angle rotation in degrees)
sel = FreeCADGui.Selection.getSelection()                             # select object with getSelection()
angle   = sel[0].Shape.Placement.Rotation.toEuler()                   # angle Euler
App.Console.PrintMessage("Angle          : "+str(angle)+"\n")
Yaw   = sel[0].Shape.Placement.Rotation.toEuler()[0]                  # decode angle Euler Yaw (Z) lacet (alpha)
App.Console.PrintMessage("Yaw            : "+str(Yaw)+"\n")
Pitch = sel[0].Shape.Placement.Rotation.toEuler()[1]                  # decode angle Euler Pitch (Y) tangage (beta)
App.Console.PrintMessage("Pitch          : "+str(Pitch)+"\n")
Roll  = sel[0].Shape.Placement.Rotation.toEuler()[2]                  # decode angle Euler Roll (X) roulis (gamma)
App.Console.PrintMessage("Roll           : "+str(Roll)+"\n\n")

rot = App.Rotation()
rot.setYawPitchRoll(45,45,0)
print("Angle: ", rot.Angle)
print("Axis: ", rot.Axis)
print("RawAxis: ", rot.RawAxis)
print("YawPitchRoll: ", rot.getYawPitchRoll())
print("Rotation: ", rot)
print("Quaternion: ", rot.Q)

##################################################################################

# find Midpoint of the selected line
import Draft, DraftGeomUtils
sel = FreeCADGui.Selection.getSelection()
vecteur = DraftGeomUtils.findMidpoint(sel[0].Shape.Edges[0])              # find Midpoint
App.Console.PrintMessage(vecteur)
Draft.makePoint(vecteur)
##################################################################################

Top

Căutarea Manuală a unui element având eticheta sa

# Extract the coordinate X,Y,Z and Angle giving the label (here "Cylindre")
App.Console.PrintMessage("Base.x       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.x)+"\n")
App.Console.PrintMessage("Base.y       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.y)+"\n")
App.Console.PrintMessage("Base.z       : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Base.z)+"\n")
App.Console.PrintMessage("Base.Angle   : "+str(FreeCAD.ActiveDocument.getObjectsByLabel("Cylindre")[0].Placement.Rotation.Angle)+"\n\n")
##################################################################################

PS: De obiecei unghiurile sunt dat în Radian, pentru a face conversia :

  1. angle in Degrees to Radians :
    • Angle in radian = pi * (angle in degree) / 180
    • Angle in radian = math.radians(angle in degree)
  2. angle in Radians to Degrees :
    • Angle in degree = 180 * (angle in radian) / pi
    • Angle in degree = math.degrees(angle in radian)

Top

Coordonate Carteziene

Acest cod afișează coordonatele cartesiene ale elementului selectat.

Modificați valoarea "numberOfPoints" dacă doriți o precizie mai mare sau mai mică

numberOfPoints = 100                                                         # Decomposition number (or precision you can change)
selectedEdge = FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy() # select one element
points  = selectedEdge.discretize(numberOfPoints)                            # discretize the element
i=0
for p in points:                                                             # list and display the coordinates
    i+=1
    print( i, " X", p.x, " Y", p.y, " Z", p.z)

Altă metodă de afișarea a "Int" și "Float"

import Part
from FreeCAD import Base

c=Part.makeCylinder(2,10)        # create the circle
Part.show(c)                     # display the shape

# slice accepts two arguments:
#+ the normal of the cross section plane
#+ the distance from the origin to the cross section plane. Here you have to find a value so that the plane intersects your object
s=c.slice(Base.Vector(0,1,0),0)  # 

# here the result is a single wire
# depending on the source object this can be several wires
s=s[0]

# if you only need the vertexes of the shape you can use
v=[]
for i in s.Vertexes:
    v.append(i.Point)

# but you can also sub-sample the section to have a certain number of points (int) ...
p1=s.discretize(20)
ii=0
for i in p1:
    ii+=1
    print( i )                                             # Vector()
    print( ii, ": X:", i.x, " Y:", i.y, " Z:", i.z )       # Vector decode
Draft.makeWire(p1,closed=False,face=False,support=None)    # to see the difference accuracy (20)

## uncomment to use
#import Draft
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # first transform the DWire in Wire         "downgrade"
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # second split the Wire in single objects   "downgrade"
#
##Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"


# ... or define a sampling distance (float)
p2=s.discretize(0.5)
ii=0
for i in p2:
    ii+=1
    print( i )                                             # Vector()
    print( ii, ": X:", i.x, " Y:", i.y, " Z:", i.z )       # Vector decode 
Draft.makeWire(p2,closed=False,face=False,support=None)  # to see the difference accuracy (0.5)

## uncomment to use
#import Draft
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # first transform the DWire in Wire         "downgrade"
#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True)  # second split the Wire in single objects   "downgrade"
#
##Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"

Top

Selectați toate obiectele în document

import FreeCAD
for obj in FreeCAD.ActiveDocument.Objects:
    print( obj.Name )                               # display the object Name
    objName = obj.Name
    obj = App.ActiveDocument.getObject(objName)
    Gui.Selection.addSelection(obj)                 # select the object

Top

Selectarea fațetei unui obiect

# select one face of the object
import FreeCAD, Draft
App=FreeCAD
nameObject = "Box"                             # objet
faceSelect = "Face3"                           # face to selection
loch=App.ActiveDocument.getObject(nameObject)  # objet
Gui.Selection.clearSelection()                 # clear all selection
Gui.Selection.addSelection(loch,faceSelect)    # select the face specified
s = Gui.Selection.getSelectionEx()
#Draft.makeFacebinder(s)                       #

Top

Get the normal vector of a face of an object by Name object and number Face (r.Q)

## normal of a face by giving the number of the face and the name of the object (rotation Q with yL, uV) = (App.Vector (x, y, z), angle))
## normal d'une face en donnant le numero de la face et le nom de l'objet (rotation Q avec yL, uV) = (App.Vector(x, y, z),angle))
from FreeCAD import Vector

numero_Face = 2      # number of the face searched (begin 0, 1, 2, 3 .....)
nomObjet    = "Box"  # object name
yL = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].CenterOfMass
uv = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].Surface.parameter(yL)

nv = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].normalAt(uv[0], uv[1])
direction = yL.sub(nv + yL)
print("Direction  : ",direction)

r = App.Rotation(App.Vector(0,0,1),direction)
print("Rotation   : ", r)
print("Rotation Q : ", r.Q)

Top

Get the normal vector of a face of an object by Name object and number of Face

numero_Face = 2       # number of the face searched (begin 0, 1, 2, 3 .....)
nomObjet    = "Box"   # object name
normal      = Gui.ActiveDocument.getObject(nomObjet).Object.Shape.Faces[numero_Face].normalAt(0,0)
print("Face"+str(numero_Face), " : ", normal)

Top

Get the normal vector of an object selected and number of Face

## normal of a face by giving the number of the face of the selected object
selectionObjects = FreeCADGui.Selection.getSelection()     
numero_Face = 3    # numero de la face recherchee
normal = selectionObjects[0].Shape.Faces[numero_Face].normalAt(0,0)
print(normal)
# selectionne la face numerotee
Gui.Selection.clearSelection()
Gui.Selection.addSelection(selectionObjects[0],"Face"+str(numero_Face))

Top

Determinarea vectorului normal() la o suprafață

Acest exemplu arată modul de găsire a vectorului normal() a unei suprafețe prin căutarea parametrilor u, v ai unui punct de pe suprafață și folosirea parametrilor u, v pentru a găsi vectorul normal()

def normal(self):
   ss=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy()#SubObjects[0] is the edge list
   points  = ss.discretize(3.0)#points on the surface edge, 
             #this example just use points on the edge for example. 
             #However point is not necessary on the edge, it can be anywhere on the surface. 
   face=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[1]
   for pp in points:
      pt=FreeCAD.Base.Vector(pp.x,pp.y,pp.z)#a point on the surface edge
      uv=face.Surface.parameter(pt)# find the surface u,v parameter of a point on the surface edge
      u=uv[0]
      v=uv[1]
      normal=face.normalAt(u,v)#use u,v to find normal vector
      print( normal)
      line=Part.makeLine((pp.x,pp.y,pp.z), (normal.x,normal.y,normal.z))
      Part.show(line)

Top

Get the normal vector of the face and create a line at the point mouse clicked

import PySide2
import Draft, Part, FreeCAD, FreeCADGui
import FreeCADGui as Gui
from FreeCAD import Base

FreeCAD.ActiveDocument.openTransaction("Tyty")    # memorise les actions (avec annuler restore)
selectedFace = FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0]
pointClick = FreeCADGui.Selection.getSelectionEx()[0].PickedPoints[0]

########## section direction
plr = FreeCAD.Placement()
yL = pointClick
uv = selectedFace.Surface.parameter(yL)
nv = direction = selectedFace.normalAt(uv[0], uv[1])
r = App.Rotation(App.Vector(0,0,1),nv)
plr.Rotation.Q = r.Q
plr.Base = pointClick
########## section direction

line = Draft.make_wire([App.Vector(0.0,0.0,0.0), App.Vector(0.0,0.0,20.0)] )    # create line
line.Placement=plr
FreeCAD.ActiveDocument.recompute()
print( "Direction (radian) : ",direction )    # direction in radian

Top

Get the normal vector of a surface from a STL file

def getNormal(cb):
    if cb.getEvent().getState() == coin.SoButtonEvent.UP:
        pp = cb.getPickedPoint()
        if pp:
            vec = pp.getNormal().getValue()
            index = coin.cast(pp.getDetail(), "SoFaceDetail").getFaceIndex()
            print("Normal: {}, Face index: {}".format(str(vec), index))

from pivy import coin
meth=Gui.ActiveDocument.ActiveView.addEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), getNormal)

you are done then run for quit:

Gui.ActiveDocument.ActiveView.removeEventCallbackPivy(coin.SoMouseButtonEvent.getClassTypeId(), meth)

Top

Crearea unui obiect față de poziția Camerei foto

# create one object of the position to camera with "getCameraOrientation()"
# the object is still facing the screen
import Draft

plan = FreeCADGui.ActiveDocument.ActiveView.getCameraOrientation()
plan = str(plan)
###### extract data
a    = ""
for i in plan:
    if i in ("0123456789e.- "):
        a+=i
a = a.strip(" ")
a = a.split(" ")
####### extract data

#print( a)
#print( a[0])
#print( a[1])
#print( a[2])
#print( a[3])

xP = float(a[0])
yP = float(a[1])
zP = float(a[2])
qP = float(a[3])

pl = FreeCAD.Placement()
pl.Rotation.Q = (xP,yP,zP,qP)         # rotation of object
pl.Base = FreeCAD.Vector(0.0,0.0,0.0) # here coordinates XYZ of Object
rec = Draft.makeRectangle(length=10.0,height=10.0,placement=pl,face=False,support=None) # create rectangle
#rec = Draft.makeCircle(radius=5,placement=pl,face=False,support=None)                   # create circle
print( rec.Name)

aici avem același sod simplificat

import Draft
pl = FreeCAD.Placement()
pl.Rotation = FreeCADGui.ActiveDocument.ActiveView.getCameraOrientation()
pl.Base = FreeCAD.Vector(0.0,0.0,0.0)
rec = Draft.makeRectangle(length=10.0,height=10.0,placement=pl,face=False,support=None)

Top

Citirea și Scrierea unei Expresii

import Draft
doc = FreeCAD.ActiveDocument

pl=FreeCAD.Placement()
pl.Rotation.Q=(0.0,-0.0,-0.0,1.0)
pl.Base=FreeCAD.Vector(0.0,0.0,0.0)
obj = Draft.makeCircle(radius=1.0,placement=pl,face=False,support=None)    # create circle

print( obj.PropertiesList )                                                  # properties disponible in the obj

doc.getObject(obj.Name).setExpression('Radius', u'2mm')                    # modify the radius
doc.getObject(obj.Name).setExpression('Placement.Base.x', u'10mm')         # modify the placement 
doc.getObject(obj.Name).setExpression('FirstAngle', u'90')                 # modify the first angle
doc.recompute()

expressions = obj.ExpressionEngine                                         # read the expression list
print( expressions)

for i in expressions:                                                      # list and separate the data expression
    print( i[0]," = ",i[1])

Top

Create a Sketch on a Surface in PartDesign

This snippet can be useful, if you want to create a sketch on a surface in PartDesign from inside a macro. Note, that body might be None, if no active body is selected and that the Selection might be empty.

body = Gui.ActiveDocument.ActiveView.getActiveObject('pdbody')
first_selection = Gui.Selection.getSelectionEx()[0]

feature = first_selection.Object
face_name = first_selection.SubElementNames[0]

sketch = App.ActiveDocument.addObject('Sketcher::SketchObject','MySketch')
body.addObject(sketch)
sketch.MapMode = 'FlatFace'
sketch.Support = (feature, face_name)

App.ActiveDocument.recompute()

Top

How to Simulate a Mouse Click at a given Coordinate

The position is relative to the GL widget. See forum thread.

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets

mw = Gui.getMainWindow()
gl = mw.findChild(QtWidgets.QOpenGLWidget)
me = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(800,300), QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier)

app = QtWidgets.QApplication.instance()
app.sendEvent(gl, me)

If you have a 3d point and want to get the 2d point on the opengl widget then use this:

from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets
from FreeCAD import Base

x, y, z, = 10,10,10
v = Gui.ActiveDocument.ActiveView
point3d = Base.Vector(x, y, z)
point2d = v.getPointOnScreen(point3d)
size = v.getSize()
coordX = point2d[0]
coordY = size[1] - point2d[1]

me = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, QtCore.QPoint(coordX,coordY), QtCore.Qt.LeftButton, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier)

Top

How to create a face with holes using Python API

This snippet demonstrates how to create a face with internal holes through the Python API. See forum thread.

import FreeCAD, Part

# Create poles that will define the Face
pts = [(-2, 2, 0),
       (0, 2, 1),
       (2, 2, 0),
       (2, -2, 0),
       (0, -2, 1),
       (-2, -2, 0)]

bs = Part.BSplineCurve()
bs.buildFromPoles(pts, True)  # True makes this periodic/closed

# Make the Face from the curve
myFace = Part.makeFilledFace([bs.toShape()])

# Create geometry for holes that will be cut in the surface
hole0 = Part.Geom2d.Circle2d(FreeCAD.Base.Vector2d(0,0), 1.0)
hole1 = Part.Geom2d.Circle2d(FreeCAD.Base.Vector2d(0,1.5), 0.1)

edge0 = hole0.toShape(myFace)
edge1 = hole1.toShape(myFace)
wireb = Part.Wire(bs.toShape())
wire0 = Part.Wire(edge0)
wire1 = Part.Wire(edge1)

# Cut holes in the face
myFace.cutHoles([wire0])
myFace.validate()  # This is required
myFace.cutHoles([wire1])
myFace.validate()

Part.show(myFace)

Top

Close and restart FreeCAD

import PySide2 
from PySide2 import QtWidgets, QtCore, QtGui

def restart_freecad():
    """Shuts down and restarts FreeCAD"""

    args = QtWidgets.QApplication.arguments()[1:]
    if FreeCADGui.getMainWindow().close():
        QtCore.QProcess.startDetached(
            QtWidgets.QApplication.applicationFilePath(), args
        )

Top

Coin3D

See Coin3d snippets

Top

Related

Top


Introduction

Această pagină arată modul în care se poate construi cu ușurință o funcționalitatea avansată în Python. În acest exercițiu, vom construi un nou instrument care atrage o linie. Acest instrument poate fi apoi legat la o comandă FreeCAD și această comandă poate fi apelată de orice element al interfeței, cum ar fi un element de meniu sau un buton din bara de unelte.

Scriptul Principal

Mai întâi vom scrie un script care conține toate funcționalitățile noastre. Apoi, vom salva acest lucru într-un fișier și îl vom importa în FreeCAD, astfel încât toate clasele și funcțiile pe care le scriem vor fi disponibile pentru FreeCAD. Deci, lansați editorul de text preferat și tastați următoarele rânduri:

First we will write a script containing all our functionality. Then we will save this in a file and import it in FreeCAD to make all its classes and functions available. Launch your favorite code editor and type the following lines:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def __init__(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Top

Explicații detaliate

import Part, FreeCADGui
from pivy.coin import *

În Python, atunci când doriți să utilizați funcții dintr-un alt modul, trebuie să-l importați. În cazul nostru, vom avea nevoie de funcții de la Part Workbench, pentru crearea liniei și de la modulul Gui (FreeCADGui), pentru a accesa vizualizarea 3D. De asemenea, avem nevoie de conținutul complet al bibliotecii de monede, astfel încât să putem folosi direct toate obiectele precum coin, SoMouseButtonEvent, (eveniment mouse) etc ...

class line:

Aici definim clasa noastră principală. De ce folosim o clasă și nu o funcție? Motivul este că avem nevoie ca instrumentul nostru să rămână "în viață" în timp ce așteptăm ca utilizatorul să facă clic pe ecran. O funcție se termină atunci când sarcina sa a fost făcută, dar un obiect (o clasă definește un obiect) rămâne în viață până când este distrus.

"""This class will create a line after the user clicked 2 points on the screen"""

În Python, fiecare clasă sau funcție poate avea o descriere. Acest lucru este util în particular în FreeCAD, deoarece atunci când veți apela acea clasă în interpret, descrierea va fi afișată ca o sugestie .

def __init__(self):

Clasele Python întotdeauna trebuie să conțină o funcție __init__function, care este executată atunci când clasa este apelată să creeze un obiect. Deci, vom pune aici tot ce vrem să se întâmple atunci când instrumentul nostru de linie începe(este apelat).

self.view = FreeCADGui.ActiveDocument.ActiveView

Într-o clasă, de obicei, este de dorit să adăugați "self" înaintea unui nume de variabilă, astfel încât să fie ușor accesibilă tuturor funcțiilor din interiorul și din afara clasei respective. Aici vom folosi self.view pentru a accesa și manipula vizualizarea 3D activă.

self.stack = []

Aici vom crea o listă goală care va conține punctele în 3D trimise de funcția getpoint.

self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

Acesta este un punct/parte importantă: Deoarece că este vorba de o o scenă coin3D, FreeCAD folosește mecanismul de apel invers, care permite unei funcții să fie apelată de fiecare dată când se întâmplă un anumit eveniment scenă. În cazul nostru, creăm un apel invers pentru evenimentele SoMouseButtonEvent și îl legăm la funcția getpoint. Acum, de fiecare dată când este apăsat sau eliberat un buton mouse-ului, funcția GetPoint va fi executată.

Rețineți că există, de asemenea, o alternativă la addEventCallbackPivy() numită addEventCallback() care exclude utilizarea pivy. Dar, din moment ce pivu este o modalitate foarte eficientă și naturală de a accesa orice parte a scenei coin, este mult mai bine să o utilizați cât de mult puteți!

Top

def getpoint(self, event_cb):

Acum definim funcția GetPoint, care va fi executată atunci când un buton al mouse-ului este apăsat într-o vizualizare 3D. Această funcție va primi un argument, pe care îl vom numi event_cb. De la acest apel al evenimentului, putem accesa obiectul eveniment, care conține mai multe informații -mai multe informații pe această pagină (modul infohere).

if event.getState() == SoMouseButtonEvent.DOWN:

Funcția GetPoint va fi apelată când un buton al mouse-ului este apăsat sau eliberat. Dar vrem să alegem un punct 3D numai atunci când este presat (altfel am obține două puncte foarte aproape unul de celălalt). Așa că trebuie să verificăm asta

pos = event.getPosition()

Aici găsim coordonatele cursorului mouse-ului pe ecran

point = self.view.getPoint(pos[0], pos[1])

Această funcție ne dă un vector FreeCAD (x, y, z) ale punctului care se află pe planul focal, chiar sub cursorul mouse-ului. Dacă vă aflați într-o vizualizare a camerei foto, imaginați-vă camera trece prin cursorul mouse-ului și atinge planul focal. Acesta este punctul nostru 3D. Dacă suntem în vedere ortogonală, raza este paralelă cu direcția de vizualizare.

self.stack.append(point)

Noi adăugăm elementul nostru nou în stivă/morman

if len(self.stack) == 2:

Avem toate punctele necesare? dacă da, atunci să tragem linia!

l = Part.LineSegment(self.stack[0], self.stack[1])

Aici folosim funcția line() din Part Workbench care a creat o linie din două vectori FreeCAD. Tot ceea ce creăm și modificăm în interiorul modulului Part, rămâne în modulul Part. Deci, până acum, am creat o piesă tip linie. Nu este legat de niciun obiect al documentului nostru activ, deci nu apare nimic pe ecran.

shape = l.toShape()

Documentul FreeCAD poate accepta decât forme din modulul Part Module. Formele sunt cel mai generic tip al Part Module. Deci, trebuie să convertim linia noastră într-o formă înainte de a o adăuga la document.

Part.show(shape)

Modulul Part Module are o funcție foarte utilă show(), care creează un obiect nou în document și se leagă la o formă. De asemenea, am putea să avem un nou obiect în primul document, apoi să-l legăm manual la formă.

self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

Deoarece am terminat cu linia noastră, să eliminăm mecanismul de apel invers, care consumă cicluri CPU prețioase.

Top

Testing & Using the script

Acum, hai să salvăm scriptul într-un loc unde interpretul Python de la FreeCAD îl va găsi. Când importați module, interpretorul va căuta în următoarele locuri: căile de instalare python, directorul bin FreeCAD și toate directoarele modulelor FreeCAD. Deci, cea mai bună soluție este să creați un director nou într-unul din FreeCAD Mod directories și să salvați scriptul în el. De exemplu, să facem un director "MyScripts" și să salvăm scriptul nostru ca "exercise.py".

Now let's save our script in a folder where the FreeCAD Python interpreter can find it. When importing modules, the interpreter will look in the following places: the Python installation paths, the FreeCAD bin folder, and all FreeCAD Mod (module) folders. So the best solution is to create a new folder in one of the Mod folders. Let's create a MyScripts folder there and save our script in it as exercise.py.

Acum, totul este gata, să începem FreeCAD, să creăm un nou document și, în interpretorul python, să tastăm:

import exercise

Dacă nu apare niciun mesaj de eroare, înseamnă că scriptul nostru de exerciții exercise a fost încărcat. Acum îi putem verifica conținutul cu:

dir(exercise)

Comanda dir() este o comandă python încorporată care listează/enumeră conținutul unui modul. Putem vedea că clasa noastră class line() este aici, așteptându-ne. Acum, să o testăm:

'line' in dir(exercise)

Now let's test it:

exercise.line()

Apoi, faceți dublu clic în vizualizarea 3D, și bingo, aici este linia noastră! Pentru a face din nou, doar tastați exercise.line() din nou, și din nou și din nou ... Vă simțiți minunat, nu-i așa?

Top

Înregistrarea scriptului în interfața FreeCAD

Acum, pentru ca noul nostru instrument de trasat linii să fie foarte cool, ar trebui să aibă un buton pe interfață, deci să nu trebuiescă să tastăm toate acele lucruri de fiecare dată. Cea mai ușoară cale este să ne transformăm noul director MyScripts într-un atelier de lucru complet FreeCAD. Este ușor, tot ce este necesar este să plasați un fișier numit InitGui.py în directorul MyScripts. InitGui.py va conține instrucțiunile pentru a crea un nou atelier de lucru și va adăuga noul instrument. În plus, va trebui să transformăm un pic codul nostru de exerciții, astfel încât instrumentul line() este recunoscut ca o comandă oficială FreeCAD. Să începem prin a face un fișier InitGui.py și scrieți următorul cod în el:

For our new line tool to be really useful, and to avoid having to type all that stuff, it should have a button in the interface. One way to do this is to transform our new MyScripts folder into a full FreeCAD workbench. This is easy, all that is needed is to put a file called InitGui.py inside the MyScripts folder. InitGui.py will contain the instructions to create a new workbench, and add our new tool to it. Besides that we will also need to change our exercise code a bit, so the line() tool is recognized as an official FreeCAD command. Let's start by creating an InitGui.py file, and writing the following code in it:

class MyWorkbench (Workbench):

    MenuText = "MyScripts"

    def Initialize(self):
        import exercise
        commandslist = ["line"]
        self.appendToolbar("My Scripts", commandslist)

Gui.addWorkbench(MyWorkbench())

Până acum, ar fi trebuit să fi înțeles deja scriptul de mai sus, mă gândesc eu: Creați o nouă clasă pe care o numiți MyWorkbench. Îi vom da un titlu (MenuText) și vom defini o funcție Initialize() care va fi executată atunci când atelierul de lucru este încărcat în FreeCAD. În această funcție, încărcăm conținutul fișierului de exerciții și adăugăm comenzile FreeCAD găsite în interiorul unei liste de comenzi. Apoi, facem o bară de instrumente numită "Scripturile mele" și îi atribuim comenzile noastre. În prezent, desigur, avem doar un singur instrument, astfel că lista noastră de comenzi conține doar un singur element. Apoi, odată ce atelierul nostru de lucru este gata, îl adăugăm la interfața principală.

Dar acest lucru nu va funcționa, deoarece o comandă FreeCAD trebuie să fie formatată într-un anumit mod de lucru. Deci, va trebui să transformăm puțin instrumentul nostru line(). Noul nostu script exercise.py va arăta cam așa:

import FreeCADGui, Part
from pivy.coin import *

class line:

    """This class will create a line after the user clicked 2 points on the screen"""

    def Activated(self):
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.stack = []
        self.callback = self.view.addEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.getpoint)

    def getpoint(self, event_cb):
        event = event_cb.getEvent()
        if event.getState() == SoMouseButtonEvent.DOWN:
            pos = event.getPosition()
            point = self.view.getPoint(pos[0], pos[1])
            self.stack.append(point)
            if len(self.stack) == 2:
                l = Part.LineSegment(self.stack[0], self.stack[1])
                shape = l.toShape()
                Part.show(shape)
                self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)

    def GetResources(self):
        return {'Pixmap': 'path_to_an_icon/line_icon.png', 'MenuText': 'Line', 'ToolTip': 'Creates a line by clicking 2 points on the screen'}

FreeCADGui.addCommand('line', line())

Ceea ce am făcut aici? noi am transformat funcția noastră __init__() function într-o funcție Activated(), deoarece atunci când comenzile FreeCAD sunt executate, ele execută automat funcția Activated(). Am adăugat, de asemenea, o funcție GetResources (), care informează FreeCAD unde poate găsi o pictogramă pentru instrument și care va fi numele și sugestia/indicația instrumentului nostru. Orice imagine jpg, png sau svg va funcționa ca o pictogramă/iconiță, poate fi orice dimensiune, dar este mai bine să utilizați o dimensiune care este aproape de aspectul final, cum ar fi 16x16, 24x24 sau 32x32. Apoi, adăugăm class line() ca o comandă oficială FreeCAD cu metoda addCommand().

Asta este, vrem să reporniți FreeCAD și vom avea un nou atelier de lucru cu noul nostru instrument linie line!

Top

Deci vrei mai mult?

Dacă ți-a plăcut acest exercițiu, de ce să nu încerci să îmbunătățești acest mic instrument? Sunt multe lucruri care pot fi făcute, ca de exemplu:

  • Adăugați comentarii utilizatorilor: până acum am făcut un instrument foarte subțire îmbrăcat, utilizatorul ar putea fi un pic pierdut atunci când îl utilizează. Așadar, am putea adăuga comentarii, spunându-i ce să facă în continuare. De exemplu, puteți emite mesaje către consola FreeCAD. ”Aruncați o privire” în modulul FreeCAD.Console
  • Adăugați posibilitatea de a introduce manual coordonatele punctelor 3D. Uitați-vă la funcția python input(), de exemplu,
  • Adăugați posibilitatea de a adăuga mai mult de 2 puncte
  • Adăugați evenimente pentru alte lucruri: Acum verificăm doar evenimentele butonului mouse-ului, dacă am face și ceva când mouse-ul este mutat, cum ar fi afișarea coordonatelor curente?
  • Dați un nume obiectului creat și multe alte lucruri.

Nu ezitați să vă scrieți întrebările sau ideile pe forum!

Don't hesitate to ask questions or share ideas on the forum!

Top


Introduction

In această pagină vă vom expune cum se construiește o casetă de dialog Qt Dialog cu Qt Designer, Qt's instrumentul oficial pentru proiectarea interfețelor, apoi se convertesc în codul Pytohn, ca mai apoi să fie utilizat în interiorul FreeCAD. Voi presupune în exemplul acesta că știți cum se editează și se rulează deja scripturile Python și că puteți face lucruri simple într-o fereastră terminală, cum ar fi navigarea, etc. Trebuie să fi instalat, firește, pyqt.

In this example, the entire interface is defined in Python. Although this is possible for small interfaces, for larger interfaces the recommendation is to load the created .ui files directly into the program.

Two general methods to create interfaces, by including the interface in the Python file, or by using .ui files.

Proiectarea dialogului

In aplicațiile CAD , proiectarea unei bune interfețe user UI (User Interface) este foarte importantă. Despre tot ce va face utilizatorul va fi prin intermediul unei interfețe: citirea casetelor de dialog, apăsarea butoanelor, alegerea între pictograme etc. De aceea este foarte important să vă gândiți cu atenție la ceea ce doriți să faceți, cum doriți să se comporte utilizatorul, și cum va fi fluxul de activități al acțiunii dvs.

In CAD applications, designing a good UI (User Interface) is very important. About everything the user will do will be through some piece of interface: reading dialog boxes, pressing buttons, choosing between icons, etc. So it is very important to think carefully to what you want to do, how you want the user to behave, and how will be the workflow of your action.

Există câteva concepte pe care trebuie să le cunoașteți atunci când proiectați interfața:

  • Modal/non-modal dialogs: Un dialog modal apare în fața ecranului, oprind acțiunea ferestrei principale, forțând utilizatorului să răspundă la dialog, în timp ce un dialog non-modal nu vă oprește să lucrați pe fereastra principală. În unele cazuri, prima este mai bună, în alte cazuri nu.
  • Identificarea cerințelor și a opțiunilor: Asigurați-vă că utilizatorul știe ce trebuie să facă. Etichetați totul cu o descriere adecvată, utilizați sfaturi pentru sfaturi, etc.
  • Separarea comenzilor de parametrii: Aceasta se face de obicei cu butoanele și câmpurile de introducere a textului. Utilizatorul știe că dacă faceți clic pe un buton veți produce o acțiune în timp ce modificați o valoare în interiorul unui câmp de text, veți schimba un parametru undeva. În prezent, totuși, utilizatorii cunosc de obicei bine ce este un buton, ce este un câmp de intrare etc. Setul de instrumente de interfață pe care îl folosim, Qt, este un set de instrumente de ultimă oră și nu ne vom teme prea mult despre clarificarea lucrurilor, deoarece vor fi deja foarte clare de la sine.

Deci, acum că am definit bine ce vom face, este timpul să deschidem designerul qt. Să proiectăm un dialog foarte simplu, după cum urmează:

Apoi, vom folosi acest dialog în FreeCAD pentru a produce un plan dreptunghiular. S-ar putea să nu fie foarte util să produci planuri dreptunghiulare, dar va fi ușor să le schimbi mai târziu pentru a face lucruri mai complexe. Când îl deschideți, Designer Qt arată astfel:

Este foarte simplu de utilizat. În bara din stânga aveți elemente care pot fi trase pe widget(toate instrumentele). În partea dreaptă aveți panouri care afișează tot felul de proprietăți editabile ale elementelor selectate. Deci, începeți cu crearea unui widget nou. Selectați "Dialog fără butoane", deoarece nu dorim butoanele implicite Ok / Cancel. Apoi trageți pe widget-ul 3 etichete , unul pentru titlu, unul pentru scrierea "Înălțime" și unul pentru scrierea "Lățime". Etichetele sunt simple texte care apar pe widget-ul dvs., doar pentru a informa utilizatorul. Dacă selectați o etichetă, în partea dreaptă vor apărea mai multe proprietăți pe care le puteți modifica dacă doriți, cum ar fi stilul fontului, dimensiune a, etc.

Rețineți că selectăm aici niște controale foarte simple, dar Qt are mai multe opțiuni, de exemplu, ați putea folosi Spinboxes în loc de LineEdits, etc ... Aruncați o privire la ceea ce este disponibil, veți avea cu siguranță alte idei.

Este vorba despre tot ce trebuie să facem în Qt Designer. Un ultim lucru, totuși, să redenumim toate elementele noastre cu nume mai ușor, deci va fi mai ușor să le identificăm în scenariile noastre:

Traducerea dialogului nostru în python

Acum, hai să salvăm widget-ul undeva. Acesta va fi salvat ca un fișier .ui, pe care îl vom converti cu ușurință în scriptul python cu pyuic. Sub Windows, programul pyuic este livrat cu pyqt (pentru a fi verificat), sub Linux probabil că va trebui să îl instalați separat plecând de la managerul de pachete (pe sistemele bazate pe debian, face parte din pachetul pyqt4-dev-tools). Pentru a face conversia, va trebui să deschideți o fereastră de terminal (sau sub Windows o fereastră cu prompt de comandă ), să navigați la locul unde ați salvat fișierul .ui și să emiteți/tastați:

pyuic mywidget.ui > mywidget.py

În Windows pyuic.py este localizat in "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" Pentru conversie creați un batch file numit "compQt4.bat:

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" -x %1.ui > %1.py

In consola Dos tastează fără extensie

compQt4 myUiFile

In macOS, you can retrieve the appropriate version (the same that is used internally in FreeCAD 0.19) of QT and Pyside with these commands (pip required)

python3 -m pip install pyqt5
python3 -m pip install pySide2

This will install uic in the folder "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/uic", and Designer in "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/Designer.app". For convenience you can create a link of uic in /usr/local/bin to be able to call it simply with uic -g python ... instead of typing the whole path of the program, and a link to Designer to retrieve it in the mac's Applications folder with

sudo ln -s /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/uic /usr/local/bin
ln -s /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PySide2/Designer.app /Applications

In Linux : to do

Deoarece FreeCAD s-a depărtat treptat de PyQt după versiunea 0.13, în favoarea PySide (Alegeți-vă PySide install building/building PySide), pentru a face fișierul bazat pe PySide acum trebuie să utilizați:

pyside-uic mywidget.ui -o mywidget.py

In Windows uic.py este localizat in "C:\Python27\Lib\site-packages\PySide\scripts\uic.py" Pentru a crea un fișier batch "compSide.bat":

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PySide\scripts\uic.py" %1.ui > %1.py

In consola Dos tastați fără extensie

compSide myUiFile

Into Linux : to do

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PySide\scripts\uic.py" %1.ui > %1.py

In the DOS console type without extension

compSide myUiFile

Into Linux : to do

Pe unele sisteme programul este numit pyuic4 în loc de pyuic. Acest lucru va transforma pur și simplu fișierul .ui într-un script python. Dacă deschidem fișierul mywidget.py, conținutul său este foarte ușor de înțeles:

from PySide import QtCore, QtGui

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(187, 178)
        self.title = QtGui.QLabel(Dialog)
        self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))
        self.title.setObjectName("title")
        self.label_width = QtGui.QLabel(Dialog)
        ...

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

   def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.title.setText(QtGui.QApplication.translate("Dialog", "Plane-O-Matic", None, QtGui.QApplication.UnicodeUTF8))
        ...

După cum vedeți, are o structură foarte simplă: este creată o clasă numită Ui_Dialog, care stochează elementele de interfață ale widget-ului nostru. Această clasă are două metode, una pentru configurarea widget-ului și una pentru traducerea conținutului său, care este parte din mecanismul general Qt pentru traducerea elementelor de interfață. Metoda de configurare creează pur și simplu, unul câte unul, widget-urile așa cum le-am definit în Qt Designer și le stabilește opțiunile așa cum am decis mai devreme. Apoi, întreaga interfață este tradusă și, în sfârșit, sloturile se conectează (vom vorbi despre asta mai târziu).

Acum putem crea un nou widget și putem folosi această clasă pentru a crea interfața sa. Putem vedea deja widget-ul nostru în acțiune, punând fișierul mywidget.py într-un loc în care va fi găsit de către FreeCAD (în directorul bin FreeCAD sau în oricare dintre subdirectoarele Mod) și, în interpretul Python FreeCAD, facem:

from PySide import QtGui
import mywidget
d = QtGui.QWidget()
d.ui = mywidget.Ui_Dialog()
d.ui.setupUi(d)
d.show()

Și dialogul nostru va apărea! Rețineți că interpretorul nostru Python funcționează încă, avem o fereastră de dialog nemodal. Deci, pentru a o închide, putem (în afară de a face clic pe iconița/pictograma ei apropiată, desigur) să facem:

d.hide()

Hai să facem ceva cu fereastra noastră de dialog

Acum, că putem afișa și ascunde fereasta noastră de dialog, trebuie doar să adăugăm o ultimă parte: Să faci ceva! Dacă explorați un pic designerul Qt, veți descoperi rapid o întreagă secțiune numită "semnale și sloturi". Practic, funcționează astfel: elementele de pe widget-urile dvs. (în terminologia Qt, aceste elemente sunt ele însele widget-uri) pot trimite semnale. Aceste semnale diferă în funcție de tipul de widget. De exemplu, un buton poate trimite un semnal atunci când este apăsat și când este eliberat. Aceste semnale pot fi conectate la sloturi, care pot fi funcționalități speciale ale altor widgeturi (de exemplu, un dialog are un slot "închis" la care puteți conecta semnalul de la un buton de închidere) sau pot fi funcții personalizate. Documentația PyQt Reference Documentation afișează toate widgeturile qt, ce pot face ele și ce semnale pot trimite etc.

Ceea ce vom face aici este crearea unei noi funcții care va crea un plan definit pe înălțime și lățime și pentru conectarea acelei funcții la semnalul emis de butonul apăsat "Creare!". Deci, să începem cu importul modulelor noastre FreeCAD, punând următoarea linie în partea de sus a scriptului, unde deja importăm QtCore și QtGui:

import FreeCAD, Part

Apoi, hai să adăugăm o nouă funție la a noastră Ui_Dialog class:

def createPlane(self):
    try:
        # first we check if valid numbers have been entered
        w = float(self.width.text())
        h = float(self.height.text())
    except ValueError:
        print("Error! Width and Height values must be valid numbers!")
    else:
        # create a face from 4 points
        p1 = FreeCAD.Vector(0,0,0)
        p2 = FreeCAD.Vector(w,0,0)
        p3 = FreeCAD.Vector(w,h,0)
        p4 = FreeCAD.Vector(0,h,0)
        pointslist = [p1,p2,p3,p4,p1]
        mywire = Part.makePolygon(pointslist)
        myface = Part.Face(mywire)
        Part.show(myface)
        self.hide()

Apoi, trebuie să informăm Qt pentru a conecta butonul la funcție, plasând următoarea linie înainte QtCore.QMetaObject.connectSlotsByName(Dialog):

QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)

Aceasta, după cum vedeți, conectează semnalul pressed() pus de obiectul creat (butonul "Creare!"), Într-un slot numit createPlane, pe care tocmai l-am definit. Gata, asta e! Acum, ca tușă finală, putem adăuga o mică funcție pentru a crea dialogul, va fi mai ușor de apelat. În afara clasei Ui_Dialog, să adăugăm acest cod:

class plane():
   def __init__(self):
       self.d = QtGui.QWidget()
       self.ui = Ui_Dialog()
       self.ui.setupUi(self.d)
       self.d.show()

(Python amintește: the __init__ method of a class este executată automat ori de câte ori este creat un obiect nou!) Apoi, de la FreeCAD, avem nevoie doar de:

import mywidget
myDialog = mywidget.plane()

Et voila ... Acum puteți încerca tot felul de lucruri, cum ar fi de exemplu inserarea widget-ului în interfața FreeCAD (consultați pagina Code snippets) sau realizarea unor instrumente personalizate mult mai avansate, utilizând alte elemente pe widgetul tău.

Scriptul complet

Acesta este scriptul complet, pentru referințe:

# Form implementation generated from reading ui file 'mywidget.ui'
#
# Created: Mon Jun  1 19:09:10 2009
#      by: PyQt4 UI code generator 4.4.4
# Modified for PySide 16:02:2015 
# WARNING! All changes made in this file will be lost!

from PySide import QtCore, QtGui
import FreeCAD, Part 

class Ui_Dialog(object):
   def setupUi(self, Dialog):
       Dialog.setObjectName("Dialog")
       Dialog.resize(187, 178)
       self.title = QtGui.QLabel(Dialog)
       self.title.setGeometry(QtCore.QRect(10, 10, 271, 16))
       self.title.setObjectName("title")
       self.label_width = QtGui.QLabel(Dialog)
       self.label_width.setGeometry(QtCore.QRect(10, 50, 57, 16))
       self.label_width.setObjectName("label_width")
       self.label_height = QtGui.QLabel(Dialog)
       self.label_height.setGeometry(QtCore.QRect(10, 90, 57, 16))
       self.label_height.setObjectName("label_height")
       self.width = QtGui.QLineEdit(Dialog)
       self.width.setGeometry(QtCore.QRect(60, 40, 111, 26))
       self.width.setObjectName("width")
       self.height = QtGui.QLineEdit(Dialog)
       self.height.setGeometry(QtCore.QRect(60, 80, 111, 26))
       self.height.setObjectName("height")
       self.create = QtGui.QPushButton(Dialog)
       self.create.setGeometry(QtCore.QRect(50, 140, 83, 26))
       self.create.setObjectName("create")

       self.retranslateUi(Dialog)
       QtCore.QObject.connect(self.create,QtCore.SIGNAL("pressed()"),self.createPlane)
       QtCore.QMetaObject.connectSlotsByName(Dialog)

   def retranslateUi(self, Dialog):
       Dialog.setWindowTitle("Dialog")
       self.title.setText("Plane-O-Matic")
       self.label_width.setText("Width")
       self.label_height.setText("Height")
       self.create.setText("Create!")
       print("tyty")
   def createPlane(self):
       try:
           # first we check if valid numbers have been entered
           w = float(self.width.text())
           h = float(self.height.text())
       except ValueError:
           print("Error! Width and Height values must be valid numbers!")
       else:
           # create a face from 4 points
           p1 = FreeCAD.Vector(0,0,0)
           p2 = FreeCAD.Vector(w,0,0)
           p3 = FreeCAD.Vector(w,h,0)
           p4 = FreeCAD.Vector(0,h,0)
           pointslist = [p1,p2,p3,p4,p1]
           mywire = Part.makePolygon(pointslist)
           myface = Part.Face(mywire)
           Part.show(myface)

class plane():
  def __init__(self):
      self.d = QtGui.QWidget()
      self.ui = Ui_Dialog()
      self.ui.setupUi(self.d)
      self.d.show()

Crearea unui dialog cu butoane

Relevant links


Line drawing function
Licence

Dezvoltarea aplicațiilor în FreeCAD


Licențe utilizate sub FreeCAD

FreeCAD utilizează două licențe diferite, una pentru aplicația în sine și una pentru documentație:

See FreeCAD's debian copyright file pentru mai multe detalii despre licențele utilizate de diferitele componente open source găsite în FreeCAD

Impactul licențelor

Mai jos este o explicație mai prietenoasă despre ceea ce înseamnă licența LGPL pentru dvs.:

All users

Toți utilizatorii

Toți utilizatorii pot folosi, copia, modifica, redistribui, FreeCAD în mod gratuit, fără nici o restricție. Copia dvs. de FreeCAD este a dvs., precum și fișierele pe care le produceți cu FreeCAD.Nu sunteți obligați să actualizeze FreeCAD după un anumit timp. nici să schimbați utlizarea FreeCAD. Utilizarea FreeCAD nu le obligă la nici un fel de contract sau obligație.

Codul sursă al FreeCAD este public și poate fi inspectat. Prin urmare, este posibil să verificați că nu se fac lucruri fără știrea dvs., de exemplu prin trimiterea datelor dvs. private undeva.

Professional users

Utilizatorii Profesionali

Utilizatorii profesionali pot folosi FreeCAD în mod liber, pentru orice fel de muncă privată, comercială sau instituțională. Orice versiune de FreeCAD poate fi instalată și instalată oriunde, de ori câte ori doriți. Puteți de asemenea să modificați și să adaptați FreeCAD pentru scopurile dvs. fără nici o restricție. Cu toate acestea, nu puteți face dezvoltatorii FreeCAD răspunzători pentru orice daune comerciale sau pierderi care pot rezulta din utilizarea FreeCAD.

Open-source software developers

Deavoltatorii Open Source

Puteți utiliza FreeCAD ca bază pentru a vă dezvolta propria aplicație sau o puteți extinde prin crearea de module noi pentru aceasta. Dacă FreeCAD este încorporat în propria dvs. aplicație, aveți posibilitatea să alegeți dintre licența GPL sau LGPL sau orice altă licență compatibilă cu LGPL pentru a permite utilizarea muncii dvs. în software-ul proprietar sau nu. Dacă dezvoltați un modul care să fie folosit ca extensie și nu includeți codul FreeCAD în el, puteți alege orice licență dorită. Cu toate acestea, dacă doriți să o utilizați cât de mult puteți, este o idee bună să utilizați aceeași licență ca FreeCAD în sine, astfel încât să poată fi accesată mai ușor în alte module viitoare sau chiar în FreeCAD.

Closed-source software developers

Commercial developers

Puteți utiliza FreeCAD ca bază pentru propria aplicație și nu sunteți forțați să creați aplicația dvs. ca open source. Cu toate acestea, LGPL necesită două elemente de bază: 1) să informeze în mod clar utilizatorii că aplicația dvs. utilizează FreeCAD și FreeCAD este licențiată de LGPL și 2) să vă separați în mod clar propria aplicație de componentele FreeCAD. Acest lucru se face de obicei printr-o legătură dinamică cu componentele FreeCAD, permițând utilizatorilor să o modifice sau să pună la dispoziția utilizatorilor codul sursă al FreeCAD, precum și modificările aduse de dvs la acesta. Veți primi sprijin de la dezvoltatorii FreeCAD, atâta timp cât acest ajutor nu este pe o ”stradă cu sens unic”.

1) You must clearly inform your users that your application is using FreeCAD and that FreeCAD is LGPL.

2) The LGPL license also stipulate your users must be able to swap your modified FreeCAD component with the original FreeCAD equivalent. That is would be done by dynamically linking to the FreeCAD components, so users are allowed to change it. However, this is often hard to achieve by today's requirements. At FreeCAD, we understand that the important point here is to not restrict the freedom given to FreeCAD users by the LGPL license. So an equivalent to dynamic linking is to offer the choice to your users, by making your users aware of the possibility to use FreeCAD for free. This can be done in a number of ways.

If any of the two conditions above are unacceptable to you or cannot be implemented, then you must make your FreeCAD component LGPL too and release the source code with all the modifications you made to it.

There is a special case called derivatives, which is when you publish basically a "rebranded" version of FreeCAD. Derivatives which are not open-source are prohibited by the LGPL license. The FreeCAD community is active and efficient in finding rebranded versions, reporting them to the platforms where they were found and exposing them until they are taken down.

Files

Fișiere

Modelele și alte fișiere create cu FreeCAD nu sunt supuse niciunei licențe menționate mai sus și nu sunt legate de nici un fel de restricție sau de proprietate. Fișierele dvs. sunt cu adevărat ale tale. Puteți seta proprietarul fișierului și puteți specifica propriile condiții de licență pentru fișierele pe care le produceți în cadrul FreeCAD, prin meniul Fișier -> Informații despre proiect.

The FreeCAD logo is a trademark owned by the FPA (FreeCAD project association). This means the FPA is the sole body authorized to say who has the right to use the FreeCAD logo or not. The logo files, which are part of the FreeCAD source code or available elsewhere, for example on this wiki, are still all under the same licenses as the rest of FreeCAD (LGPL for the source code and Creative Commons for this wiki). You are still free to use the FreeCAD logo anywhere, on the same terms as the rest of FreeCAD, which means, basically, that you must use it to reference FreeCAD, and not use it, for example, for your own product, or any other way that is not referencing FreeCAD.

Statement of the main developer

Declarația dezvoltatorului principal

Știu că discuția despre "dreptul" licenței pentru open source a ocupat o parte semnificativă a lățimii de bandă a internetului și acesta este motivul pentru care, în opinia mea, FreeCAD ar trebui să aibă fie sub această licență LGPL.

Am ales licențele LGPL și GPL pentru proiect, știu că există pro și anti LGPL și vă voi da câteva motive pentru această decizie.

FreeCAD este un amestec între o bibliotecă și o aplicație, deci GPL ar fi un pic mai puternic pentru aceasta. Aceasta ar împiedica scrierea de module comerciale pentru FreeCAD deoarece ar preveni legarea cu bibliotecile de bază FreeCAD. Puteți să întrebați de ce module comerciale ? Prin urmare, Linux este un bun exemplu. Ar fi Linux atât de reușit dacă Biblioteca GNU C ar fi GPL și, prin urmare, ar împiedica legarea aplicațiilor non-GPL? Și totuși, îmi place libertatea Linuxului și doresc să pot utiliza driverul grafic NVIDIA 3D. Înțeleg și accept motivul pentru care NVIDIA nu dorește să dea codul driverului. Muncim toți pentru întreprinderi/firme, și avem nevoie de bani, trebuie să cumpărăm cel puțin alimente... Deci, pentru mine, coexistența open source și a a programelor proprietar nu este un lucru rău, atunci când se supune regulilor LGPL. Aș dori să văd un programator care scrie procesul de import/export Catia pentru FreeCAD și să-l distribuie gratuit sau pentru niște bani. Nu-mi place să-l forțez să dea mai mult decât vrea el. Nu ar fi bine nici pentru el nici pentru FreeCAD.

Această decizie se face numai pentru nucleul sistemul FreeCAD. Fiecare scriitor al unui modul de aplicație poate lua propria decizie.

Jürgen Riegel

—15 October 2006


Dialog creation
Tracker


Licence
Bug Triage
In February 2022 FreeCAD bug tracking was migrated to GitHub Issues. The Mantis bug tracker described below is now in read-only mode.
link=https://freecadweb.org/tracker/MantisBT is the bugtracker framework FreeCAD uses
link=https://freecadweb.org/tracker/MantisBT is the bugtracker framework FreeCAD uses

Tracker este locul pentru aː raporta bug-uri (eroare sau disfuncționalitate neprevăzută) , trimiteți cereri de funcționalități, patch-uri sau cereți să vă îmbinați codul corector propriu dacă ați dezvoltat ceva folosind Git. Dispozitivul de urmărire este împărțit în Ateliere "Workbenches", așa că vă rugăm să fiți preciși și să vă înscrieți cererea în subsecțiunea corespunzătoare. În caz de îndoială, lăsați-o în secțiunea "FreeCAD".


Flux de lucru recomandat

După cum se arată în diagrama de mai sus, înainte de a crea tichete, vă rugăm să căutați mereu în forumurile și bugtracker pentru a afla dacă problema dvs. este o problemă cunoscută. Acest lucru economisește o mulțime de timp / muncă pentru dezvoltatori și voluntari care ar putea petrece timpul respectiv, făcând chiar mai minunat acest FreeCAD.

Raportarea erorilor

Dacă credeți că ați găsit un bug (disfuncționalitate sau eroare), sunteți binevenit să îl raportați atâta timp cât ați urmat pas cu pas următoarele elemente:

  • Asigurați-vă că utilizați cea mai recentă versiune de FreeCAD. NOTEː eroarea dumneavoastră ar putea fi deja rezolvată în versiunea în Dezvoltare(instabilă). Utilizatorii medii utilizează varianta stabilă a FC.
  • Asigurați-vă ca bug-ul este un adevărat bug, asta e, câteodată ar putea să meargă dar să nu fie. Asigurați-vă că aceeași eroare nu a fost raportată înainte , căutând în bugtracker și forum.
    • Nu uitațiː dacă nu sunteți siguri , vă rog nu ezitați să explicați problema/bug-ul pe Help forum și întrebați ce este de făcut.
    • Notăː înainte de a posta pe forum vă rugăm citiți Forum Guidelines.
  • Descrieți cât mai clar posibil problema, și cum poate fi reprodusă. Dacă noi nu putem verifica eroarea, nu putem să o rezolvăm.
    • Aceasta înseamnă raportarea într-un mod clar, bine formatat, pas cu pas astefel încât și un amator să o poată reproduce.
    • Recomandatː Screenshots a erorii este de asemenea foarte folositor a fi inclus. Useri de Windows: vp rugăm nu atașați capturi de ecran în Word sau format PDF. Utilizați instrumentul Windows Snipping pentru a salva captura ca imagine PNG.
    • Recomandatː Chiar mai bine, un Animated gif or Screencast ar crește posibilitatea de areproduce problema.
  • Adaugați un exemplul de fișier FreeCAD (.FCStd file) astfel ca devs/testers să poată reproduce ușor eroarea/disfuncționalitatea.
    • Vă rugăm nu arhivați fișierul *.FCStd, este deja zipped.
    • Atașametnele fișierului sunt limitatea ca mărime. Dacă fișierul dvs *.FCStd este prea marea pentru a fi atașat, puteți utiliza online storage service (multe sunt gratuite ca de exemplu Google Drive, Microsoft OneDrive, Dropbox).
  • Includeți toate informațiile din butonul "Copy to Clipboard" în dialogul Help (menu) -> About FreeCAD. fiți siguri că datele dumneavoastră includ versiunile de OCC ori OCE .
  • Vă rugăm completați un raport separat pentru fiecare bug.
  • Dacă eroarea dvs cauzează un crash in FreeCAD și sunteți pe un sistem care permite aceasta,încercați să rulați un debug backtrace și să atașați said trace la ticket. Aceasta poate salva devs foarte mult timp pentru a ținti sursa prăbușirii/crash-ului. Vezi Debugging pentru mai multe detalii.

Solicitarea de funcționalități

Dacă doriți să apară ceva în FreeCAD, care încă nu este implementat, it nu este un bug și o solicitarea de funcționalitate.

  1. IMPORTANTː Înainte de a solicita a funcționalitate potențială Feature Request please be certain that you are the first one doing so by searching the forums and the bugtracker. Dacă ați ajuns la concluzia că nu există token/tichete / discuții pre-existente, următorul pas este ...
  2. Începeți un fir de discuții de forum pentru a discuta despre cererea dvs. cu comunitatea prin Open Discussion forum.
  3. Odată ce comunitatea este de acord că aceasta este o caracteristică valabilă, puteți deschide un token/tiket pe tracker(file it under feature request instead of bug).
  • NOTE #1 Pentru a păstra lucrurile organizate, nu uitați să conectați adresa URL a firului la tichet și numărul (ca legătură) în firul de pe forum.
  • NOTE #2 Rețineți că nu există garanții că dorința dvs. va fi îndeplinită.
FreeCAD Bugtracker report page - use the dropdown to correctly designate what the ticket is

Propunerea de îmbunătățiri

In cazul în care ați realizat un program de corectare a unei erori/disfuncționalități, o extensie sau orice altceva care poate fi de uz public în FreeCAD, creați un patch utilizând instrumentul Git diff și trimiteți-o pe același bug tracker (ca pe un patch).

Solicitarea fuzionare

(Same guidelines as Submiting patches)

Dacă ați creat o modificarea (git branch) conținând schimbări pe care le-ați dori să fie topite/fuzionate în codul FreeCAD, puteți solicita ca ramura dvs. să fie revizuită și integrată în cazul în care dezvoltatorii FreeCAD sunt de acord cu aceasta. Mai întâi trebuie să vă publicați modificarea într-un depozit public git (github, gitlab, bitbucket, sourceforge etc ...) și apoi să dați URL-ul modificării dvs în cererea dvs. de fuziune.

MantisBT sfaturi și Trucuri

MantisBT Markup

MantisBT (Mantis Bug Tracker) are propria marcă.

  • @mention - funcționează ca pe GitHub unde, dacă adăugați prefixul "@" la un nume de utilizator, acesta va primi un e-mail pe care a fost "menționat" într-un thread de tichet
  • #1234 - Prin adăugarea unei etichete de tip hash tag în fața unui număr, va fi prezentată o comandă rapidă către un link către un alt bilet în MantisBT.
    Note: Dacă survolați cu mouse-ul peste un bilet, acesta vă va afișa rezumatul + dacă biletul este închis, acesta va fi blocat ca#1234.
  • ~5678 - o comandă rapidă care face legătura cu o notă de bug în cadrul unui bilet. Acest lucru poate fi folosit pentru răspunsul cuiva în cadrul firului. Fiecare persoană va avea un număr unic de postare #### la numele de utilizator. Dacă priviți imaginea din exemplu, veți observa că comanda rapidă face referire la numărul ticket number:comment number al biletului menționat
  • <del></del> - Utilizând această etichetă aceasta va strikeout text.
  • <code></code> - pentru a prezenta o linie sau un bloc de cod, utilizați această etichetă și aceasta o va colora și o va diferenția elegant.

MantisBT BBCode

În plus față de mai sus Tracker/MantisBT ̠Markup are de asemenea posibilitatea să utilizeze formatul BBCode. Pentru o listă completă, vezi BBCode plus plugin page. aici este o listă a etichetelor BBCode suportateː
[img][/img] - Images
[url][/url] - Links
[email][/email] - Email addresses
[color=red][/color] - Colored text
[highlight=yellow][/highlight] - Highlighted text
[size][/size] - Font size
[list][/list] - Lists
[list=1][/list] - Numbered lists (number is starting number)
[*] - List items
[b][/b] - Bold
[u][/u] - underline
[i][/i] - Italic
[s][/s] - Strikethrough
[left][/left] - Left align
[center][/center] - Center
[right][/right] - Right align
[justify][/justify] - Justify
[hr] - Horizontal rule
[sub][/sub] - Subscript
[sup][/sup] - Superscript
[table][/table] - Table
[table=1][/table] - Table with border of specified width
[tr][/tr] - Table row
[td][/td] - Table column
[code][/code] - Code block
[code=sql][/code] - Code block with language definition
[code start=3][/code] - Code block with line numbers starting at number
[quote][/quote] - Quote by *someone* (no name)
[quote=name][/quote] - Quote by *name*

MantisBT <=> GitHub Markup

Mai jos sunt cuvintele cheie speciale pentru plugin-ul MantisBT Source-Integration, care vor face legătura cu repo-ul FreeCAD GitHub. Vezi Tracker#GitHub_and_MantisBT.

  • c:FreeCAD:git commit hash: - c stands for 'commit'. FreeCAD stands for the FreeCAD GitHub repo. 'git commit hash' is the specific git commit hash to reference. Note: the trailing colon is necessary. Exampleː cːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • d:FreeCAD:git commit hash: - similar to the above, d stands for 'diff' which will provide a Diff view of the commit. Exampleː dːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • p:FreeCAD:pullrequest: - similar to the above, p stands for Pull Request. Exampleː pːFreeCADː498ː

MantisBT <=> GitHub Markup

Below are special MantisBT Source-Integration plugin keywords which will link to the FreeCAD GitHub repo. See GitHub and MantisBT.

  • c:FreeCAD:git commit hash: - c stands for 'commit'. FreeCAD stands for the FreeCAD GitHub repo. 'git commit hash' is the specific git commit hash to reference. Note: the trailing colon is necessary. Exampleː cːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • d:FreeCAD:git commit hash: - similar to the above, d stands for 'diff' which will provide a Diff view of the commit. Exampleː dːFreeCADː709d2f325db0490016807b8fa6f49d1c867b6bd8ː
  • p:FreeCAD:pullrequest: - similar to the above, p stands for Pull Request. Exampleː pːFreeCADː498ː

GitHub și MantisBT

FreeCAD bugtracker are un plug-in numit Source Integration care în principiu care, în esență, leagă atât repo-ul FreeCAD GitHub cât și tracker-ul nostru MantisBT. El facilitează urmărirea și asocierea git commits cu tichetele lor MantisBT. 'Pluginul Source Integration scanează mesajele de git commits pentru anumite cuvinte cheie pentru a executa următoarele acțiuni:'

Notă Cuvintele cheie de mai jos trebuie adăugate în git commit message și nu în subiectul PR

Referința distantă a unui tichet

Folosind acest model, se va asocia automat o comanda git cu un ticket ( 'Notă:' acest lucru nu va închide biletul.)Formatul MantisBT va recunoaște:

  • bug #1234
  • bugs #1234, #5678
  • issue #1234
  • issues #1234, #5678
  • report #1234
  • reports #1234, #5678

For the inquisitive here is the regex MantisBT uses for this operation:
/(?:bugs?|issues?|reports?)+\s*:?\s+(?:#(?:\d+)[,\.\s]*)+/i

Rezolvarea la distanță a unui tichet

Formatul MantisBT va recunoaște:

  • fix #1234
  • fixed #1234
  • fixes #1234
  • fixed #1234, #5678
  • fixes #1234, #5678
  • resolve #1234
  • resolved #1234
  • resolves #1234
  • resolved #1234, #5678
  • resolves #1234, #5678

For the inquisitive here is the regex MantisBT uses for this operation:
/(?:fixe?d?s?|resolved?s?)+\s*:?\s+(?:#(?:\d+)[,\.\s]*)+/i


Licence
Bug Triage


Acest articol explică pas cu pas how to compile FreeCAD on Windows.

Premise

Compiling FreeCAD on Windows requires several tools and libraries.

Programe necesare

  • Git Aici sunt câteva dintre alternative ca GitCola, Tortoise Git, și altele.
  • CMake versiunea 2.x.x sau Cmake 3.x.x
  • Python >2.5 (Acest lucru este necesar numai dacă NU utilizați Libpack. Libpack este livrat încpând cu Python(2.7.x) potrivit pentru compilarea și rularea FreeCAD)
  • A compiler. FreeCAD is tested with Visual Studio (MSVC)—other compilers may work, but instructions for use are not included here. Fore more details, see the section Compiler below.
  • Git (There are also GUI frontends available for Git, see the next section.)
  • CMake version 3.11.x or newer.
    Hint: Choosing the option Add CMake to the system PATH for all users when installing CMake will make CMake accessible from the Windows command prompt, which can be useful.
  • The LibPack. This is a single package containing all of the libraries necessary to compile FreeCAD on Windows. Download the version of the LibPack that corresponds to the version of FreeCAD you want to compile. To compile FreeCAD 0.20 download the LibPack version 2.6, for FreeCAD 0.19 download the LibPack version 1.0. Extract the LibPack to a convenient location. (If your computer does not recognize the .7z extension, you must install the program 7-zip.)
    Note: It is highly recommended to compile FreeCAD with the compiler version the LibPack is designed for. For example, you might run into problems compiling FreeCAD 0.20 using MSVC 2017 because the LibPack is designed to be built with MSVC 2019 or newer.
    To update your LibPack later, see the section Updating the LibPack.

Optional programs

  • A GUI frontend for Git. There are several frontends available, see this list. The main benefit of a frontend is that you don't have to learn the Git commands to get the source code of FreeCAD or to send patches to the GitHub repository of FreeCAD.

In the following we describe source code handling using the TortoiseGit frontend. This frontend integrates directly into Windows file explorer and has a large user community to get help in case you have problems.

  • NSIS is used to generate the FreeCAD Windows installer.

Codul sursă

Utilizați Git (de preferință)

Now you can get the source code of FreeCAD:

Using a frontend

When using the Git frontend TortoiseGit:

  1. Create a new folder where the source code will be downloaded.
  2. Right-click on this folder in the Windows file explorer and select Git Clone in the context menu.
  3. A dialog will appear. In it, enter the URL for the FreeCAD Git repository

https://github.com/FreeCAD/FreeCAD.git

and click OK.

The latest source code will be downloaded from the FreeCAD Git repository and the folder will be tracked by Git.

Using the command line

Pentru a crea o ramură de urmărire locală și pentru a descărca codul sursă, trebuie să deschideți un terminal (promp de comandă) și cd(change directory) în directorul pe care doriți să plasați codul sursă, apoi tastați:

git clone https://github.com/FreeCAD/FreeCAD.git

Compilator

Sub Windows, compilatorul implicit este MS Visual Studio. CI utilizează versiunea din 2013.

The default (recommended) compiler is MS Visual Studio (MSVC). Though it may be possible to use other compilers, for example gcc via Cygwin or MinGW, it is not tested or covered here.

You can get a free version of MSVC (for individual usage) by downloading the Community edition of MS Visual Studio.

Pentru cei care doresc să evite instalarea imensului Visual Studio pentru simplul scop de a avea un compilator, vezi CompileOnWindows - Reducing Disk Footprint.

Note: Although the Community edition of MSVC is free, to use the IDE for more than a 30-day trial period you must create a Microsoft account. If you will only compile using the command line, you don't need the IDE and thus no Microsoft account.

As a free and OpenSource alternative IDE you can use KDevelop. You can use KDevelop to modify and write C++ code but must use the command line to compile.

Configurarea căii de sistem

În interiorul căii dvs. de sistem, asigurați-vă că setați căile corecte la următoarele programe:

  • git (not tortoiseGit, but git.exe) Acest lucru este necesar pentru ca Cmake să actualizeze în mod corespunzător informațiile despre versiunea "Despre FreeCAD".h fișierul care permite FreeCAD să raporteze versiunea corespunzătoare din About FreeCAD din meniul de ajutor.
  • În mod opțional, puteți include Libpack în calea dvs. de sistem. Acest lucru este util dacă intenționați să construiți mai multe configurații / versiuni ale FreeCAD, va trebui să copiați mai puține fișiere după cum este explicat mai târziu în procesul de rulare.

Optionally you can include the paths to some folders to the system PATH variable. This is helpful if you want to access programs in these folders from the command line/powershell or if you want special programs to be found by the compiler or CMake. Besides this, adding folders to the PATH might be necessary if you did not use the corresponding options when installing the program.

  • You can include the folder of your LibPack in your system PATH variable. This is useful if you plan to build multiple configurations/versions of FreeCAD.
  • If you did not use the option to add CMake to the PATH while installing it, add its installation folder

C:\Program Files\CMake\bin to the PATH.

  • If you did not use the option to add TortoiseGit to the PATH while installing it, add its installation folder

C:\Program Files\TortoiseGit\bin to the PATH.

Pentru a adăuga la cale asitemului dvs:

Configurare cu CMake

Once you have all of the necessary tools, libraries, and FreeCAD source code, you are ready to begin the configuration and compilation process. This process will proceed in five steps:

  1. Run CMake once to examine your system and begin the configuration progress (this will report that it failed).
  2. Adjust necessary CMake settings to set the locations of the LibPack and enable Qt5.
  3. Re-run CMake to finalize the configuration (this time it should succeed).
  4. Use CMake to generate the Visual Studio build system.
  5. Use Visual Studio to build FreeCAD.

CMake

First, configure the build environment using CMake:

  1. Open the CMake GUI
  2. Specify the source folder of FreeCAD.
  3. Specify a build folder. This can be build in the folder you cloned the repo because this path is ignored by git. Do not use the source folder. CMake will create this folder if it does not exist.
  4. Click Configure.
  5. In the dialog that appears specify the generator you want to use: in most cases you will use the defaults in this dialog. For the standard MS Visual Studio use Visual Studio xx 2yyy where xx is the compiler version and 2yyy the year of its release. It is recommended to use the default option Use default native compilers.

Note: It is important to specify the correct bit variant. If you have the 64-bit variant of the LibPack you must also use the x64 compiler.

Aceasta va începe configurarea și ar trebui să eșueze deoarece locația FREECAD_LIBPACK_DIR is unset.

  • Expand the FREECAD category and set FREECAD_LIBPACK_DIR to the correct location
  • Check FREECAD_USE_EXTERNAL_PIVY
  • Optionally Check FREECAD_USE_FREETYPE this is required to use the Draft WB's Shape String functionality
  • Click Configure again
  • There should be no errors
  • Click Generate
  • Close CMake
  • Copy libpack\bin folder into the new build folder CMake created

If it fails with the message that Visual Studio could not be found, the CMake support in MSVC is not yet installed. To do this:

  1. Open the MSVC IDE
  2. Use the menu Tools → Get Tools and Features
  3. In the Workloads tab enable Desktop development with C++
  4. On the right side you should now see that the component Visual C++ tools for CMake will be installed.
  5. Install it.

If it fails with a message about the wrong Python version or missing Python, then:

  1. Use the "Search:" box in CMake to search for the string "Python"
  2. If you see there a path like C:/Program Files/Python38/python.exe, CMake recognized the Python that is already installed on your PC, but that version is not compatible with the LibPack. Since the LibPack includes a compatible version of Python, modify the following Python settings in CMake to its paths (assuming the LibPack is in the folder D:/FreeCAD-build/FreeCADLibs_2_8_x64_VC2019):

If there is no error about Visual Studio or Python, everything is fine, but CMake does not yet know all necessary settings. Therefore now:

  1. Search in CMake for the variable FREECAD_LIBPACK_DIR and specify the location of the LibPack folder you downloaded earlier.
  2. (If building FreeCAD 0.19) Search for the variable BUILD_QT5 and enable this option.
  3. (If planning on running directly from the build folder such as for debugging) Search for and enable the following options:
    • FREECAD_COPY_DEPEND_DIRS_TO_BUILD
    • FREECAD_COPY_LIBPACK_BIN_TO_BUILD
    • FREECAD_COPY_PLUGINS_BIN_TO_BUILD
  4. Click Configure again.

There should now be no errors. If you continue to encounter errors that you cannot diagnose, visit the Install/Compile forum on the FreeCAD forum website. If CMake proceeded correctly, click on Generate. After this is done you can close CMake and start the compilation of FreeCAD using Visual Studio. However, for the first compilation keep it open in case you want or need to change some options for the build process.

Opțiuni pentru compilarea Proceselor

Sistemul de compilare CMake ne oferă o mult mai mare flexibilitate în procesul de compilare. Asta înseamnă că putem porni și dezactiva câteva funcționalități sau module. Este într-un fel ca compilarea kernel-ului Linux. Aveți o mulțime de comutatoare pentru a determina procesul de compilare.

Iată descrierea unora dintre aceste switch-uri. Probabil că se vor schimba mult în viitor pentru că vrem să creștem flexibilitatea compilării mult mai mult.

Link table
Variable name Description Default
FREECAD_LIBPACK_USE Switch the usage of the FreeCAD LibPack on or off On Win32 on, otherwise off
FREECAD_LIBPACK_DIR Directory where the LibPack is FreeCAD SOURCE dir
FREECAD_BUILD_GUI Build FreeCAD with all Gui related modules ON
FREECAD_BUILD_CAM Build the CAM module, experimental! OFF
FREECAD_BUILD_INSTALLER Create the project files for the Windows installer. OFF
FREECAD_BUILD_DOXYGEN_DOCU Create the project files for source code documentation. OFF
FREECAD_MAINTAINERS_BUILD Switch on stuff needed only when you do a Release build. OFF

Compilarea FreeCAD

În funcție de configurația actuală, procesul de construire a FreeCAD va fi ușor diferit. Acest lucru se datorează diferențelor dintre versiunile de software disponibile pentru fiecare sistem de operare.

Depending on your compiler, the process for building FreeCAD will be slightly different. In the following sections known workflows are described. If you are building with Qt Creator, jump to Building with Qt Creator (outdated), otherwise proceed directly:

Building from cmd.exe command line

If you want build from the command line, CMake output will show you the proper command to run (which depends on the configured release directory). But this command will produce a Debug build which does not work on Windows and results in a Numpy import error in FreeCAD (which is a known issue but hard to fix). You need to specify the --config Release option to force a Release build:

cmake --build E:/release --config Release

Please note that setting CMake variables like CMAKE_BUILD_TYPE does not have any effect, only specifying the --config option as shown above works.

Building with Visual Studio 15 (2017) or newer

Release Build

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Release.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build.

This will now take quite a long time.

To compile a ready-to use FreeCAD, compile the target INSTALL, see the section Running and installing FreeCAD.

If you don't get any errors you are done. Congratulations! You can exit MSVC or keep it open.

Important: Since Visual Studio 17.4 you cannot use the code optimization that is on by default for the target SketcherGui. If you do, angle constraints will be misplaced in sketches. To fix this, right-click on this target in the MSVC solution explorer and select the last entry Properties in the context menu. In the appearing dialog go to C/C++ → Optimization and there disable the setting Optimization. Finally build the target ALL_BUILD again.

Debug Build

For a debug build it is necessary that the Python is used that is included in the LibPack. To assure this:

  1. Search in the CMake GUI for "Python"
  2. If you see there a path like C:/Program Files/Python38/python.exe, CMake recognized the Python that is installed on your PC and not the one of the LibPack. In this case adapt these different Python settings in CMake to this (assuming the LibPack is in the folder D:\FreeCAD-build\FreeCADLibs_12.5.2_x64_VC17):

As prerequisite for the debug build, you need to do this:

  1. Copy the content of the LibPack folder bind to the bin folder of the FreeCAD build folder (overwrite the existing files).
  2. Copy the content of the LibPack folder libd to the lib folder of the FreeCAD build folder.

Now you can compile:

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Debug.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build in the context menu.

This will now take quite a long time.

If there were no compilation errors, and if the FREECAD_COPY_* options mentioned in the CMake Configuration step above were enabled, you can start the debug build:

  1. Right-click on the target FreeCADMain and then choose Set as Startup Project in the context menu.
  2. Finally click in the toolbar on the button with the green triangle named Local Windows Debugger.

This will start the debug build of FreeCAD and you can use the MSVC IDE to debug it.

Video Resource

An English language tutorial that begins with configuration in CMake Gui and continues to the `Build` command in Visual Studio 16 2019 is available unlisted on YouTube at Tutorial: Build FreeCAD from source on Windows 10.

Compilare cu Qt Creator

Installation and configuration of Qt Creator

  • Download and install Qt Creator
  • Tools -> Options -> Text Editor -> Behavior tab:
    • File Encodings -> Default Encodings:
    • Set to: ISO-8859-1 /...csISOLatin1 (Certain characters create errors/warnings with Qt Creator if left set to UTF-8. This seems to fix it.)
  • Tools -> Options -> Build & Run:
    • CMake tab
      • Fill Executable box with path to cmake.exe
    • Kits tab
      • Name: MSVC 2008
      • Compiler: Microsoft Visual C++ Compiler 9.0 (x86)
      • Debugger: Auto detected...
      • Qt version: None
    • General tab
      • Uncheck: Always build project before deploying it
      • Uncheck: Always deploy project before running it
  • Download and install Qt Creator
  • Tools → Options → Text Editor → Behavior tab:
    • File Encodings → Default Encodings:
    • Set to: ISO-8859-1 /...csISOLatin1 (Certain characters create errors/warnings with Qt Creator if left set to UTF-8. This seems to fix it.)
  • Tools → Options → Build & Run:
    • CMake tab
      • Fill Executable box with path to cmake.exe
    • Kits tab
      • Name: MSVC 2008
      • Compiler: Microsoft Visual C++ Compiler 9.0 (x86)
      • Debugger: Auto detected...
      • Qt version: None
    • General tab
      • Uncheck: Always build project before deploying it
      • Uncheck: Always deploy project before running it

Import project and Build

  • File -> Open File or Project
  • Open CMakeLists.txt which is in the top level of the source
  • This will start CMake
  • Choose build directory and click next
  • Set generator to NMake Generator (MSVC 2008)
  • Click Run CMake. Follow the instructions depicted above to configure CMake to your liking.
  • File → Open File or Project
  • Open CMakeLists.txt which is in the top level of the source
  • This will start CMake
  • Choose build directory and click next
  • Set generator to NMake Generator (MSVC 2008)
  • Click Run CMake. Follow the instructions depicted above to configure CMake to your liking.

Now FreeCAD can be built

  • Build -> Build All
  • This will take a long time...

Once complete, it can be run: There are 2 green triangles at the bottom left. One is debug. The other is run. Pick whichever you want.

Command line build

Here an example how to build FreeCAD from the Command line:

The steps how to compile from the command line depends on the compiler. For MSVC 2017 the steps are:

  1. In Windows start menu go to Visual Studio 2017 → Visual Studio Tools and choose Developer Command Prompt for VS 2017
  2. Change to your build folder.
  3. Execute the command
msbuild ALL_BUILD.vcxproj /p:Configuration=Release

or

msbuild INSTALL.vcxproj /p:Configuration=Release

These steps can also be automaized. Here is for example a solution for MSVC 2017:

  1. Download the script compile-FC.txt.
  2. Rename it to compile-FC.bat
  3. In Windows file explorer Shift+Right-click on your build folder and use from the context menu Command prompt here.
  4. Execute the command
compile-FC install

Instead of calling compile-FC with the option install you can also use debug or release:

debug   - compile FreeCAD in debug configuration

release - compile FreeCAD in release configuration

install    - compile FreeCAD in release configuration and create an install setup

Running and installing FreeCAD

There are 2 methods to run the compiled FreeCAD:

Method 1: You execute the FreeCAD.exe that you find in your build folder in the subfolder bin

Method 2: You build the target INSTALL

Method 2 is the simpler one because it automatically assures that all libraries needed to run the FreeCAD.exe are in the correct folder. The FreeCAD.exe and the libraries will be output in the folder you specified in the CMake variable CMAKE_INSTALL_PREFIX.

For Method 1 you need to enable the FREECAD_COPY_* options mentioned in the CMake Configuration step above.

Troubleshooting

When running FreeCAD you may encounter missing DLLs when using certain workbenches or features of workbenches. The error message in FreeCAD's console will not tell you what DLL is missing. To find this out you must use an external tool:

import os
os.system(r"~\DependenciesGui.exe")

Note: Instead of the ~ you must specify the full path to the DependenciesGui.exe on your system.

  • Now drag in the *.pyd file of the workbench with which you get missing DLLs reported.

Updating the build

FreeCAD is very actively developed. Therefore its source code changes almost daily. New features are added and bugs are fixed. To benefit from these source code changes, you must rebuild your FreeCAD. This is done in two steps:

  1. Updating the source code
  2. Recompilation

Updating the source code

Using a frontend

When using the Git frontend TortoiseGit:

  1. Right-click on your FreeCAD source code folder in the Windows file explorer and select Pull in the context menu.
  2. A dialog will appear. Select there what development branch you want to get. master is the main branch. Therefore use this unless you want to compile a special new feature from a branch that has not yet been merged to master. (For more about Git branches, see Git development process.)

Finally click OK.

Using the command line

Open a terminal (command prompt) and switch there to your source directory. Then type:

git pull https://github.com/FreeCAD/FreeCAD.git master

where master the the name of the main development branch. If you want to get code from another branch, use its name instead of master.

Recompilation

  1. Open the MSVC IDE by double-clicking either on the file FreeCAD.sln or on the file ALL_BUILD.vcxproj in your build folder.
  2. Continue with step 2 from the section Building with Visual Studio 15 2017.

Updating the LibPack

If a new major version of a third-party dependency like Open Cascade is released, or if a third-party dependency has important bug fixes, a new LibPack is released. You can find the latest version here.

To update your LibPack the following recipe is best practice:

  1. Delete the bin folder in your build folder.
  2. Switch to your local LibPack folder and delete everything there.
  3. Extract the content of the new LibPack ZIP file into the existing, but now empty, local LibPack folder.
  4. Open CMake and there press the button Configure and then the button Generate. This recreates the bin folder you just deleted and also copies the new LibPack files into it.
  5. In CMake click the button Open Project and the MSVC IDE will open.
  6. In the MSVC IDE build the target INSTALL.

Tools

In order to join the FreeCAD development you should compile and install the following tools:

Qt Designer plugin

FreeCAD uses Qt as toolkit for its user interface. All dialogs are setup in UI-files that can be edited using the program Qt Designer that is part of any Qt installation and also included in the LibPack. FreeCAD has its own set of Qt widgets to provide special features like adding a unit to input fields and to set preferences properties.

Compilation

The plugin cannot be loaded by the Qt Designer if it was compiled using another Qt version than the one your Qt Designer/Qt Creator is based on. Therefore the plugin must be compiled together with FreeCAD:

  • In the CMake options (see this section above) enable the option BUILD_DESIGNER_PLUGIN and reconfigure.
  • open MSVC and build the target FreeCAD_widgets

As result you will get the plugin file 'FreeCAD_widgets.dll in the folder
~\src\Tools\plugins\widget\Release

Installation

To install the plugin, copy the DLL either to:

  • If you use the LibPack: to the folder
    ~\FreeCADLibs_2_8_x64_VC2019\plugins\designer
  • If you have a full Qt installation: you can choose between the folder
    C:\Qt\5.15.2\msvc2019_64\plugins\designer
    or
    C:\Qt\5.15.2\msvc2019_64\bin\designer (you must first create the designer subfolder.)
    (adapt the paths to your installation!).

Finally (re)start Qt Designer and check its menu Help → Plugins. If the plugin FreeCAD_widgets.dll is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must compile the DLL by yourself.

If you prefer using Qt Creator instead of Qt Designer, the plugin file must be placed in this folder:
C:\Qt\Qt5.15.2\Tools\QtCreator\bin\plugins\designer
Then (re)start Qt Creator, switch to the mode Design and then check the menu Tools → Form Editor → About Qt Designer Plugins. If the plugin FreeCAD_widgets.dll is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must compile the DLL by yourself.

Thumbnail Provider

FreeCAD has the feature to provide preview thumbnails for *.FCStd files. That means that in the Windows file explorer *.FCStd files are shown with a screenshot of the model it contains. To provide this feature, FreeCAD needs to have the file FCStdThumbnail.dll installed to Windows.

Installation

The DLL is installed this way:

  1. Download this ZIP file and extract it.
  2. Open a Windows command prompt with administrator privileges (these privileges are a requirement).
  3. Change to the folder where the DLL is.
  4. Execute this command
    regsvr32 FCStdThumbnail.dll

So check if it works, assure that in FreeCAD the preferences option Save thumbnail into project file when saving document is enabled and save a model. Then view in Windows Explorer the folder of the saved model using a symbol view. You should now see a screenshot of the model in the folder view.

Compilation

To compile the FCStdThumbnail.dll

  1. Change to the FreeCAD source folder
    ~\src\Tools\thumbs\ThumbnailProvider
  2. Open the CMake GUI
  3. Specify there as source folder the one you are currently in.
  4. Use the same folder as build folder.
  5. Click Configure
  6. In the appearing dialog, specify the generator according to the one you want to use. For the standard MS Visual Studio use Visual Studio xx 2yyy where xx is the compiler version and 2yyy the year of its release. It is recommended to use the default option Use default native compilers.
    Note: It is important to specify the correct bit variant. If you have the 64bit variant of LibPack you must also use the x64 compiler.
  7. Click on Generate.
  8. You should now have the file ALL_BUILD.vcxproj in the folder ~\src\Tools\thumbs\ThumbnailProvider. Double-click on it and the MSVC IDE will open.
  9. In the toolbar of the MSVC IDE assure that you use the compilation target Release.
  10. There is a window called Solution Explorer. Right-click there on ALL_BUILD and then choose Build.
  11. As result you should now have a FCStdThumbnail.dll in the folder ~\src\Tools\thumbs\ThumbnailProvider\release that you can install as described above.

Compiling Open Cascade

The LibPack comes with a version of Open Cascade that is suitable for general use. However, under some circumstances you may wish to compile against an alternate version of Open Cascade, such as one of their official releases, or a patched fork.

When compiling Open Cascade for FreeCAD note that there is no guarantee that FreeCAD will work with all versions of Open Cascade. Note also that when you are using the Netgen library, you must use the a NetGen version that it approved to compile with the Open Cascade version you like to compile.

To compile:

  • Then open the CMake GUI to configure the build system in a similar manner to building FreeCAD. These CMake options have to be set (or explicitly not set):
Variable name Description Default
3RDPARTY_DIR The path to 3rdparty components. It is recommended to use the folder as input where your used LibPack is. Explicitly leave this field empty. empty
3RDPARTY_DOXYGEN_EXECUTABLE The path to the executable of the 3rdparty component Doxygen. It is recommended to install Doxygen. CMake will then find it automatically. empty
3RDPARTY_FREETYPE_DIR The path to the necessary 3rdparty component Freetype. It is recommended to use the folder as input where your used LibPack is. empty
3RDPARTY_RAPIDJSON_DIR Only available if USE_RAPIDJSON is used. The path to the 3rdparty component RapidJSON. It is recommended NOT to use an existing LibPack folder as input. You can use the RapidJSOn folder from a LibPack, but copy it to a new folder and use this new folder as input. empty
3RDPARTY_TCL_DIR The path to the necessary 3rdparty component TCL. It is recommended NOT to use an existing LibPack folder as input. Take for example one of these releases, extract it and take this as input folder for CMake. empty
3RDPARTY_TK_DIR The path to the necessary 3rdparty component TK. It is recommended NOT to use an existing LibPack folder as input. Take for example one of these releases, extract it and take this as input folder for CMake. empty
3RDPARTY_VTK_DIR Only available if USE_VTK is used. The path to the necessary 3rdparty component VTK. It is recommended to use the folder as input where your used LibPack is. If you use another folder please assure that you don't use VTK 9.x or newer. empty
BUILD_RELEASE_DISABLE_EXCEPTIONS Disables exception handling for release builds. For FreeCAD you must set it to OFF. ON
INSTALL_DIR The output folder when building the target INSTALL. If the build was successful, take the files from this folder to update your LibPack. Windows default program installation folder
INSTALL_DIR_BIN The output subfolder for the DLL when building the target INSTALL. You must change it to bin win64/vc14/bin
INSTALL_DIR_LIB The output subfolder for the .lib files when building the target INSTALL. You must change it to lib win64/vc14/lib
USE_RAPIDJSON To compile Open Cascade with support for RapidJSON. Enabling this is mandatory in order to get support for the file format glTF. OFF
USE_VTK To compile Open Cascade with support for VTK. Enabling this is optimal. You can use this to build Open Cascade's VTK bridge. OFF
  • Open the project in Visual Studio and first build the ALL_BUILD and then INSTALL targets in the Release mode.
  • Repeat building the two targets in the Debug mode.

To build FreeCAD using the self-compiled Open Cascade, you must do the following:

  • Copy all folders from the INSTALL_DIR to your LibPack folder (overwrite the existing files)
  • Switch to the LibPack folder and go there to the subfolder cmake
  • Open there the file OpenCASCADEDrawTargets.cmake with a text editor
  • Search there for absolute paths to your LibPack folder and remove them. So e.g. the absolute path
    D:/FreeCADLibs_12.5.4_x64_VC17/lib/freetype.lib
    becomes just
    freetype.lib
  • Do the same for the file OpenCASCADEVisualizationTargets.cmake

Compiling Netgen

The LibPack comes with a version of Netgen that will was tested to be build with the Open Cascade version of the LibPack. The problem is that every new release of Netgen changes the API. Also every new release of Open Cascade does the same. Therefore one cannot just easily change the Netgen version.

However, you might build Netgen nevertheless. This is an easy task:

  • First obtain the Netgen source code, either directly from Netgen 's git repository.
  • Then open the CMake GUI to configure the build system in a similar manner to building FreeCAD. These CMake options have to be set:
Variable name Description Default
CMAKE_INSTALL_PREFIX The output folder when building the target INSTALL. If the build was successful, take the files from this folder to update your LibPack. C:/netgen
OpenCasCade_DIR The path to the CMake files of Open Cascade. If you built Open Cascade as described in the section Compiling Open Cascade you can use the subfolder cmake of there folder you used as INSTALL_DIR. If not, use the subfolder cmake of your LibPack. Note hereby that the LibPack must then already contain a proper Open Cascade build. Independent what folder you use, you must now also create there a subfolder lib and copy in the files freetype.lib and freetyped.lib from your LibPack. empty
USE_GUI set it to OFF ON
USE_NATIVE_ARCH set it to OFF; this is only necessary important to support older CPU that don't have the AVX2 instruction set ON
USE_OCC set it to ON OFF
USE_PYTHON set it to OFF ON
USE_SUPERBUILD set it to OFF ON
ZLIB_INCLUDE_DIR The path to the necessary 3rdparty component zlib. It is recommended to use the folder as input where your used LibPack is. empty
ZLIB_LIBRARY_DEBUG The path to the ZLib file zlibd.lib. It is located in the subfolder lib of your LibPack folder. empty
ZLIB_LIBRARY_RELEASE The path to the ZLib file zlib.lib. It is located in the subfolder lib of your LibPack folder. empty
  • Additionally you need to add a new CMake entry:

name: CMAKE_DEBUG_POSTFIX, type: string, content: _d
This assures that he file names of the debug libraries get another name than the release libraries and can later not be accidentally exchanged.

  • Press the Configure button in CMake to generate the *.cmake files.
  • Only necessary if older CPU should be supported that don't have the AVX2 instruction set:
    • Search your Netgen build folder for the file netgen-targets.cmake and open it with a text editor. Remove the setting ;/arch:AVX2 in the Option INTERFACE_COMPILE_OPTIONS.
    • Press the Configure button in CMake again.
  • Press the Generate button in CMake.
  • Open the project in Visual Studio and first build the ALL_BUILD and then INSTALL targets in the Release mode.
  • Repeat building the two targets in the Debug mode.

To build FreeCAD using the self-compiled Netgen, you must do the following:

  • Copy all folders from the CMAKE_INSTALL_PREFIX to your LibPack folder (overwrite the existing files)

References

A se vedea și



There is an experimental FreeCAD Docker container that is being tested for FreeCAD development. Read more about it at Compile on Docker

Overview

On recent Linux distributions, FreeCAD is generally easy to build, since all dependencies are usually provided by the package manager. It basically involves 3 steps:

  1. Getting the FreeCAD source code
  2. Getting the dependencies or packages that FreeCAD depends on
  3. Configure with cmake and compile with make

Below, you'll find detailed explanations of the whole process, some build scripts, and particularities you might encounter. If you find anything wrong or out of date in the text below (Linux distributions change often), or if you use a distribution which is not listed, discuss the issue in the forum, and help us correct it.

General workflow to compile FreeCAD from source. The third party dependencies must be in the system, as well as the FreeCAD source code itself. CMake configures the system so that with a single make instruction the entire project is compiled.

Getting the source

Git

The best way to get the code is to clone the read-only Git repository. For this you need the git program which can be easily installed in most Linux distributions. It can also be obtained from the official website.

Git can be installed via the following command:

sudo apt install git

The following command will place a copy of the latest version of the FreeCAD source code in a new directory called freecad-source.

git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad-source

For more information on using Git and contributing code to the project, see Source code management.

Source archive

Alternatively you can download the source as an archive, a .zip or .tar.gz file, and unpack it in the desired directory.

Getting the dependencies

To compile FreeCAD you have to install the requisite dependencies mentioned in Third Party Libraries; the packages that contain these dependencies are listed below for different Linux distributions. Please note that the names and availability of the libraries will depend on your particular distribution; if your distribution is old, some packages may be unavailable of have a different name. In this case, look in the older and non-conventional distributions section below.

Once you have all the dependencies installed, proceed to compile FreeCAD.

Please note that FreeCAD's source code is around 500 MB in size; it may be three times as big if you clone the Git repository with its entire modification history. Getting all dependencies may require downloading 500 MB or more of new files; when these files are unpacked they may require 1500 MB or more in space. Also beware that the compilation process may generate up to 1500 MB of additional files as the system copies and modifies the entire source code. Therefore, be sure you have enough free space in your hard drive, at least 4 GB, when attempting compilation.

Debian and Ubuntu

On Debian-based systems (Debian, Ubuntu, Mint, etc.) it is quite easy to get all needed dependencies installed. Most of the libraries are available via apt or the Synaptic package manager.

If you already installed FreeCAD from the official repositories, you can install its build dependencies with this single line of code in a terminal:

sudo apt build-dep freecad

Alternatively, replace freecad with freecad-daily to install the build dependencies for the main development branch. You'll need to have the freecad-stable/freecad-daily PPAs added to your software sources.

However, if the version of FreeCAD in the repositories is old, the dependencies may be the wrong ones to compile a recent version of FreeCAD. Therefore, please verify that you have installed the following packages.

These packages are essential for any sort of compilation to succeed:

  • build-essential, installs the C and C++ compilers, the C development libraries, and the make program.
  • cmake, essential tool to configure the source of FreeCAD. You may also wish to install cmake-gui and cmake-curses-gui for a graphical option.
  • libtool, essential tools to produce shared libraries.
  • lsb-release, the standard base reporting utility is normally already installed in a Debian system, and allows you to programmatically distinguish between a pure Debian installation or a variant, such as Ubuntu or Linux Mint. Do not remove this package, as many other system packages may depend on it.

Compilation of FreeCAD uses the Python language, and it's also used at runtime as a scripting language. If you are using a Debian based distribution the Python interpreter is normally already installed.

  • python3
  • swig, the tool that creates interfaces between C++ code and Python.

Please check that you have Python 3 installed. Python 2 was obsoleted in 2019, so new development in FreeCAD is not tested with this version of the language.

The Boost libraries need to be installed:

  • libboost-dev
  • libboost-date-time-dev
  • libboost-filesystem-dev
  • libboost-graph-dev
  • libboost-iostreams-dev
  • libboost-program-options-dev
  • libboost-python-dev
  • libboost-regex-dev
  • libboost-serialization-dev
  • libboost-thread-dev

The Coin libraries need to be installed:

  • libcoin80-dev, for Debian Jessie, Stretch, Ubuntu 16.04 to 18.10, or
  • libcoin-dev, for Debian Buster, Ubuntu 19.04 and newer, as well as for Ubuntu 18.04/18.10 with the freecad-stable/freecad-daily PPAs added to your software sources.

Several libraries that deal with mathematics, triangulated surfaces, sorting, meshes, computer vision, cartographic projections, 3D visualization, the X11 Window system, XML parsing, and Zip file reading:

  • libeigen3-dev
  • libgts-bin
  • libgts-dev
  • libkdtree++-dev
  • libmedc-dev
  • libopencv-dev or libcv-dev
  • libproj-dev
  • libvtk7-dev or libvtk6-dev
  • libx11-dev
  • libxerces-c-dev
  • libyaml-cpp-dev
  • libzipios++-dev

Python 2 and Qt4

This is not recommended for newer installations as both Python 2 and Qt4 are obsolete. As of version 0.20, FreeCAD no longer supports them.

To compile FreeCAD for Debian Jessie, Stretch, Ubuntu 16.04, using Python 2 and Qt4, install the following dependencies.

  • qt4-dev-tools
  • libqt4-dev
  • libqt4-opengl-dev
  • libqtwebkit-dev
  • libshiboken-dev
  • libpyside-dev
  • pyside-tools
  • python-dev
  • python-matplotlib
  • python-pivy
  • python-ply
  • python-pyside

Python 3 and Qt5

To compile FreeCAD for Debian Buster, Ubuntu 19.04 and newer, as well as Ubuntu 18.04/18.10 with the freecad-stable/freecad-daily PPAs added to your software sources, install the following dependencies.

  • qtbase5-dev
  • qttools5-dev
  • qt5-default (if compiling 0.20 on a machine that still has Qt4)
  • libqt5opengl5-dev
  • libqt5svg5-dev
  • qtwebengine5-dev
  • libqt5xmlpatterns5-dev
  • libqt5x11extras5-dev
  • libpyside2-dev
  • libshiboken2-dev
  • pyside2-tools
  • pyqt5-dev-tools
  • python3-dev
  • python3-matplotlib
  • python3-packaging
  • python3-pivy
  • python3-ply
  • python3-pyside2.qtcore
  • python3-pyside2.qtgui
  • python3-pyside2.qtsvg
  • python3-pyside2.qtwidgets
  • python3-pyside2.qtnetwork
  • python3-pyside2.qtwebengine
  • python3-pyside2.qtwebenginecore
  • python3-pyside2.qtwebenginewidgets
  • python3-pyside2.qtwebchannel
  • python3-pyside2uic

OpenCascade kernel

The OpenCascade kernel is the core graphics library to create 3D shapes. It exists in an official version OCCT, and a community version OCE. The community version is no longer recommended, as it's outdated.

For Debian Buster and Ubuntu 18.10 and newer, as well as Ubuntu 18.04 with the freecad-stable/freecad-daily PPAs added to your software sources, install the official packages.

  • libocct*-dev
    • libocct-data-exchange-dev
    • libocct-draw-dev
    • libocct-foundation-dev
    • libocct-modeling-algorithms-dev
    • libocct-modeling-data-dev
    • libocct-ocaf-dev
    • libocct-visualization-dev
  • occt-draw

For Debian Jessie, Stretch, Ubuntu 16.04 and newer, install the community edition packages.

  • liboce*-dev
    • liboce-foundation-dev
    • liboce-modeling-dev
    • liboce-ocaf-dev
    • liboce-ocaf-lite-dev
    • liboce-visualization-dev
  • oce-draw

You may install the libraries individually, or using asterisk expansion. Change occ for oce if you want to install the community libraries.

sudo apt install libocct*-dev

Optional packages

Optionally you can also install these extra packages:

  • libsimage-dev, to make Coin support additional image file formats.
  • doxygen and libcoin-doc (or libcoin80-doc for older systems), if you intend to generate source code documentation.
  • libspnav-dev, for 3D input devices support, like the 3Dconnexion "Space Navigator" or "Space Pilot".
  • checkinstall, if you intend to register your installed files into your system's package manager, so you can uninstall it later.

Single command for Python 3 and Qt5

Requires Pyside2 available in Debian buster and the freecad-stable/freecad-daily PPAs.

sudo apt install cmake cmake-gui libboost-date-time-dev libboost-dev libboost-filesystem-dev libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev libboost-python-dev libboost-regex-dev libboost-serialization-dev libboost-thread-dev libcoin-dev libeigen3-dev libgts-bin libgts-dev libkdtree++-dev libmedc-dev libocct-data-exchange-dev libocct-ocaf-dev libocct-visualization-dev libopencv-dev libproj-dev libpyside2-dev libqt5opengl5-dev libqt5svg5-dev qtwebengine5-dev libqt5x11extras5-dev libqt5xmlpatterns5-dev libshiboken2-dev libspnav-dev libvtk7-dev libx11-dev libxerces-c-dev libzipios++-dev occt-draw pyside2-tools python3-dev python3-matplotlib python3-packaging python3-pivy python3-ply python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qtsvg python3-pyside2.qtwidgets python3-pyside2.qtnetwork python3-pyside2.qtwebengine python3-pyside2.qtwebenginecore python3-pyside2.qtwebenginewidgets python3-pyside2.qtwebchannel python3-markdown python3-git python3-pyside2uic qtbase5-dev qttools5-dev swig libyaml-cpp-dev

NOTE: On some versions of Ubuntu and some versions of Qt, you will get an error that python3-pyside2uic cannot be found -- on those systems you can safely omit it. On Ubuntu 20.04 you will need to add pyqt5-dev-tools. More information can be found in this forum discussion.

Single command for Python 2 and Qt4

This is not recommended for newer installations as both Python 2 and Qt4 are obsolete.

sudo apt install cmake debhelper dh-exec dh-python libboost-date-time-dev libboost-dev libboost-filesystem-dev libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev libboost-python-dev libboost-regex-dev libboost-serialization-dev libboost-thread-dev libcoin80-dev libeigen3-dev libgts-bin libgts-dev libkdtree++-dev libmedc-dev libocct-data-exchange-dev libocct-ocaf-dev libocct-visualization-dev libopencv-dev libproj-dev libpyside-dev libqt4-dev libqt4-opengl-dev libqtwebkit-dev libshiboken-dev libspnav-dev libvtk6-dev libx11-dev libxerces-c-dev libzipios++-dev lsb-release occt-draw pyside-tools python-dev python-matplotlib python-pivy python-ply swig

Ubuntu 16.04 users please see also the compilation discussion in the forum: Compile on Linux (Kubuntu): CMake can't find VTK.

Raspberry Pi

Follow the same steps as in Debian and Ubuntu.

There are problems reported when trying to compile in Raspberry PI OS 32-bit with Python 3 and Qt5, but the combination Python 3 and Qt4 seems to work for older versions of FreeCAD (with minor issues).

For newer versions of FreeCAD (>= 0.20) the compilation with Py3/Qt5 is successful if the operating system installed is Raspberry Pi OS 64-bit or Ubuntu 20.04.

Due to different issues with Qt, in Ubuntu 20.04 the normal PySide tools won't be found.

E: Unable to locate package python3-pyside2uic

In this case, we can install the packages from PyQt and create symbolic links to the needed tools.

sudo apt-get install pyqt5-dev
sudo apt-get install pyqt5-dev-tools
cd /usr/bin/
ln -s pyrcc5 pyside2-rcc
ln -s pyuic5 pyside2-uic

Now compilation may proceed.

cd freecad-build/
cmake ../freecad-source -DBUILD_QT5=ON -DPYTHON_EXECUTABLE=/usr/bin/python3 -DUSE_PYBIND11=ON
make -j2

The -j option to make should not be more than 3 because the Raspberry Pi has limited memory. It will take several hours to compile, so it is better to do it overnight.

More information, FreeCAD and Raspberry Pi 4.

Fedora

There is a bug in cmake distributed by Fedora 34/35 which results in cmake failing to find the opencascade libraries. This can easily be fixed by making one minor change to the top level cmake file of opencascade installed on Fedora. Details here: https://bugzilla.redhat.com/show_bug.cgi?id=2083568.

Near the top of the file OpenCASCADEConfig.cmake, change the following line to use REAL_PATH(). This fixes a bug introduced by the use of a symlink from /lib to /usr/lib of Fedora, which causes cmake to fail.

This file is usually installed in /usr/lib64/cmake/opencascade/OpenCASCADEConfig.cmake.

get_filename_component (OpenCASCADE_INSTALL_PREFIX "${OpenCASCADE_INSTALL_PREFIX}" PATH)

change this to:

file (REAL_PATH ${OpenCASCADE_INSTALL_PREFIX} OpenCASCADE_INSTALL_PREFIX)

This trivial change needs to be made inside the build directory once cmake has been run and failed. Re-running cmake will then correctly detect the OCCT libraries in the normal way.

Fedora38/39

Now install Python 3.11. This includes a notable change in how Python initializes when running a program. As a result FreeCAD fails to find OpenCamLib, meaning 3D Surface and Waterline are not available in the CAM Workbench. This was fixed in the master branch on 20th Mar 2024 (Pull request #13059).

You need the following packages:

  • gcc-c++ (or possibly another C++ compiler?)
  • cmake
  • doxygen
  • swig
  • gettext
  • dos2unix
  • desktop-file-utils
  • libXmu-devel
  • freeimage-devel
  • mesa-libGLU-devel
  • opencascade-devel
  • openmpi-devel
  • python3
  • python3-devel
  • python3-pyside2
  • python3-pyside2-devel
  • pyside2-tools
  • boost-devel
  • tbb-devel
  • eigen3-devel
  • qt-devel
  • qt5-qtwebengine-devel
  • qt5-qtxmlpatterns
  • qt5-qtxmlpatterns-devel
  • qt5-qtsvg-devel
  • qt5-qttools-static
  • ode-devel
  • xerces-c
  • xerces-c-devel
  • opencv-devel
  • smesh-devel
  • Coin3
  • Coin3-devel
  • yaml-cpp

(April 2021, Coin4 and Coin4-devel are available) (if coin2 is the latest available for your version of Fedora, use packages from http://www.zultron.com/rpm-repo/)

  • SoQt-devel
  • freetype
  • freetype-devel
  • vtk
  • vtk-devel
  • med
  • med-devel

And optionally:

  • libspnav-devel (for 3Dconnexion devices support like the Space Navigator or Space Pilot)
  • python3-pivy (https://bugzilla.redhat.com/show_bug.cgi?id=458975 Pivy is not mandatory but needed for the Draft Workbench)
  • python3-markdown (for the Addon Manager to display native markdown)
  • python3-GitPython (for the Addon Manager to use git to checkout and update workbenches and macros)

To install all dependencies at once (tested on fedora 36 and 37):

sudo dnf install gcc-c++ cmake doxygen swig gettext dos2unix desktop-file-utils libXmu-devel freeimage-devel mesa-libGLU-devel opencascade-devel openmpi-devel python3 python3-devel python3-pyside2 python3-pyside2-devel pyside2-tools boost-devel tbb-devel eigen3-devel qt-devel qt5-qtwebengine-devel qt5-qtxmlpatterns qt5-qtxmlpatterns-devel qt5-qtsvg-devel qt5-qttools-static ode-devel xerces-c xerces-c-devel opencv-devel smesh-devel Coin3 Coin3-devel SoQt-devel freetype freetype-devel vtk vtk-devel med med-devel libspnav-devel python3-pivy python3-markdown python3-GitPython yaml-cpp

Gentoo

Easiest way to check which packages are needed to compile FreeCAD is to check via portage:

emerge -pv freecad

This should give a nice list of extra packages that you need installed on your system.

If FreeCAD is not available on portage, it is available on the waebbl overlay. The issue tracker on the waebbl overlay Github may help guide through some issues you may come across. The overlay provides freecad-9999, which you can choose to compile, or simply use to get the dependencies.

layman -a waebbl

openSUSE

Tumbleweed

The following commands will install the packages required for building FreeCAD with Qt5 and Python 3.

zypper in --no-recommends -t pattern devel_C_C++ devel_qt5

zypper in libqt5-qtbase-devel libqt5-qtsvg-devel libqt5-qttools-devel boost-devel swig libboost_program_options-devel libboost_mpi_python3-devel libboost_system-devel libboost_program_options-devel libboost_regex-devel libboost_python3-devel libboost_thread-devel libboost_system-devel libboost_headers-devel libboost_graph-devel python3 python3-devel python3-matplotlib python3-matplotlib-qt5 python3-pyside2 python3-pyside2-devel python3-pivy gcc gcc-fortran cmake occt-devel libXi-devel opencv-devel libxerces-c-devel Coin-devel SoQt-devel freetype2-devel eigen3-devel libode6 vtk-devel libmed-devel hdf5-openmpi-devel openmpi2-devel netgen-devel freeglut-devel libspnav-devel f2c doxygen dos2unix glew-devel yaml-cpp

The following command will install Qt Creator and the GNU Project Debugger.

zypper in libqt5-creator gdb

If any packages are missing, then you can check the Tumbleweed "FreeCAD.spec" file on the Open Build Service.

Also, check to see if there are any patches you need to apply (such as 0001-find-openmpi2-include-files.patch).

Leap

If there is a difference between the available packages on Tumbleweed and Leap, then you can read the Leap "FreeCAD.spec" file on the Open Build Service to determine the required packages.

See piano_jonas unofficial "Compile On openSUSE" guide.

Arch Linux

You will need the following libraries from the official repositories:

  • boost
  • cmake
  • coin
  • curl
  • desktop-file-utils
  • eigen
  • gcc-fortran
  • git
  • glew
  • hicolor-icon-theme
  • jsoncpp
  • libspnav
  • med
  • nlohmann-json
  • opencascade
  • pyside2-tools
  • pyside2
  • python-matplotlib
  • python-netcdf4
  • python-packaging
  • python-pivy
  • qt5-svg
  • qt5-tools
  • qt5-webengine
  • shared-mime-info
  • shiboken2
  • swig
  • utf8cpp
  • verdict
  • xerces-c
  • yaml-cpp
sudo pacman -S --needed boost cmake coin curl desktop-file-utils eigen gcc-fortran git glew hicolor-icon-theme jsoncpp libspnav med nlohmann-json opencascade pyside2-tools pyside2 python-matplotlib python-netcdf4 python-packaging python-pivy qt5-svg qt5-tools qt5-webengine shared-mime-info shiboken2 swig utf8cpp xerces-c yaml-cpp

Note: Since version 5.0.1 of the openmpi package the binary libmpi_cxx.so stopped being shipped, this breaks the compilation with the current CMake process. To fix this you need to downgrade the package, see this forum post.

Older and non-conventional distributions

On other distributions, we have very few feedback from users, so it might be harder to find the required packages.

Try first locating the required libraries mentioned in third party libraries in your package manager. Beware that some of them might have a slightly different package name; search for name, but also libname, name-dev, name-devel, and similar. If that is not possible try compiling those libraries yourself.

FreeCAD requires the GNU g++ compiler version equal or above 3.0.0, as FreeCAD is mostly written in C++. During the compilation some Python scripts are executed, so the Python interpreter has to work properly. To avoid any linker problems it is also a good idea to have the library paths in the LD_LIBRARY_PATH variable or in the ld.so.conf file. This is already done in modern Linux distributions, but may need to be set in older ones.

Pivy

Pivy (Python wrappers to Coin3d) is not needed to build FreeCAD or to start it, but it is needed as a runtime dependency by the Draft Workbench. If you are not going to use this workbench, you won't need Pivy. However, do notice that the Draft Workbench is used internally by other workbenches, like Arch and BIM, so Pivy needs to be installed to use these workbenches as well.

By November 2015 the obsolete version of Pivy included with the FreeCAD source code will no longer compile on many systems. This isn't a big problem as normally you should get Pivy from your distribution's package manager; if you cannot find Pivy, you may have to compile it yourself, see Pivy compilation instructions.

Debug symbols

In order to troubleshoot crashes in FreeCAD, it is useful to have the debug symbols of important dependency libraries such as Qt. For this, try installing the dependency packages that end with -dbg, -dbgsym, -debuginfo or similar, depending on your Linux distribution.

For Ubuntu, you may have to enable special repositories to be able to see and install these debug packages with the package manager. See Debug Symbol Packages for more information.

Compile FreeCAD

Building FreeCAD 0.20 requires at least Python3.6 and Qt 5.9.

FreeCAD uses CMake as its main build system, as it's available on all major operating systems. Compiling with CMake is usually very simple and happens in two steps.

  1. CMake checks that every needed program and library is present on your system, and generates a Makefile that is configured for the second step. FreeCAD has several configuration options to choose from, but it comes with sensible defaults. Some alternatives are detailed below.
  2. The compilation itself, which is done with the program make, which generates the FreeCAD executables.

Since FreeCAD is a large application, compiling the entire source code can take anywhere from 10 minutes to one hour, depending on your CPU and the number of CPU cores used for compilation.

Building

To build simply create a build directory, build. Then from this build directory point cmake to the right source folder. You can use cmake-gui or ccmake instead of cmake in the instructions below as well. Once cmake finishes configuring the environment, use make to start the actual compilation.

# from your freecad source folder:
mkdir build
cd build
cmake ../
make -j$(nproc --ignore=2)

The -j option of make controls how many jobs (files) are compiled in parallel. The nproc program prints the number of CPU cores in your system; by using it together with the -j option you can choose to process as many files as you have cores, in order to speed up overall compilation of the program. In the example above, it will use all cores in your system except two; this will keep your computer responsive for other uses while compilation proceeds in the background. The FreeCAD executable will eventually appear in the build/bin directory. See also Compiling (speeding up) to improve compilation speed.

Resolving cmake issues

If you have done a build before and get stuck on a dependency that is not recognized or can't seem to be resolved, try the following:

  • Delete the contents of the build directory before running cmake again. FreeCAD is a rapidly moving target, you may be tripping over cached cmake information that points at an older version than the new repository head can use. Clearing the cache may allow cmake to recover and recognize the version you actually need.
  • If cmake complains about missing a specific file, use a tool such as "apt-file search", or its equivalent in other package systems, to discover what package that file belongs to and install it. Bear in mind that you are likely to need the -dev version of the package that carries header or config files files required for FreeCAD to use the package.

Compiling against GNU libc 2.34 and later

GNU libc 2.34 introduces a change to the library that can cause builds on some Linux systems to fail with an error like:

No rule to make target '/usr/lib/x86_64-linux-gnu/libdl.so

To resolve this, a symbolic link must be manually created from the (now empty) system-installed libdl.so.* to the location your compiler says it is looking for the file. For example (if the actual installed copy of libdl.so on your system is /usr/lib/x86_64-linux-gnu/libdl.so.2):

sudo ln -s /usr/lib/x86_64-linux-gnu/libdl.so.2 /usr/lib/x86_64-linux-gnu/libdl.so

Adapt the command for the structure of your system by searching for libdl.so* and linking it to the appropriate location.

How to repair your source code directory

If you accidentally performed a compilation inside the source code directory, or added strange files, and would like to restore the contents to only the original source code, you can perform the following steps.

> .gitignore
git clean -df
git reset --hard HEAD

The first line clears the .gitignore file. This ensures that the following clean and reset commands will affect everything in the directory and will not ignore items matching the expressions in .gitignore. The second line deletes all files and directories that are not tracked by the git repository; then the last command will reset any changes to tracked files, including the first command which cleared the .gitignore file.

If you do not clear the source directory, subsequent runs of cmake may not capture new options to the system if the code changes.

Configuration

By passing different options to cmake, you can change how FreeCAD is compiled. The syntax is as follows.

cmake -D <var>:<type>=<value> $SOURCE_DIR

Where $SOURCE_DIR is the directory that contains the source code. The <type> may be omitted in most cases. The space after the -D option may also be omitted.

For example, to avoid building the FEM Workbench:

cmake -D BUILD_FEM:BOOL=OFF ../freecad-source
cmake -DBUILD_FEM=OFF ../freecad-source

All possible variables are listed in the InitializeFreeCADBuildOptions.cmake file, located in the cMake/FreeCAD_Helpers directory. In this file, search for the word option to get to the variables that can be set, and see their default values.

# ==============================================================================
# =================   All the options for the build process    =================
# ==============================================================================

option(BUILD_FORCE_DIRECTORY "The build directory must be different to the source directory." OFF)
option(BUILD_GUI "Build FreeCAD Gui. Otherwise you have only the command line and the Python import module." ON)
option(FREECAD_USE_EXTERNAL_ZIPIOS "Use system installed zipios++ instead of the bundled." OFF)
option(FREECAD_USE_EXTERNAL_SMESH "Use system installed smesh instead of the bundled." OFF)
...

Alternatively, use the command cmake -LH to list the current configuration, and thus all variables that can be changed. You may also install and use cmake-gui to launch a graphical interface showing all the variables that can be modified. In the next sections we list some of the more relevant options that you may want to use.

For a Debug build

Create a Debug build to troubleshoot crashes in FreeCAD. Beware that with this build the Sketcher becomes very slow with complex sketches.

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Debug ../freecad-source

For a Release build

Create a Release build to test code that doesn't crash. A Release build will run much faster than a Debug build.

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Release ../freecad-source

Building against Python 3 and Qt5

Support for Python 2 and Qt4 has been removed in FreeCAD 0.20 and it is not necessary to explicitly enable Qt5 and Python 3 if compiling the latest versions. Qt6 support is currently in development and does not work yet. Unless you plan on assisting with the Qt6 migration effort, FREECAD_QT_VERSION should be left at "Auto" (the default) or explicitly set to "5".

For 0.20 and 0.21_dev:

cmake ../freecad-source

Note that when switching between 0.20 and the 0.21_dev builds, it may be necessary to delete CMakeCache.txt prior to running cmake.

Building for a specific Python version

If the default python executable in your system is a symbolic link to Python 2, cmake will try to configure FreeCAD for this version. You must then choose another version of Python by giving the path to a specific executable:

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 ../freecad-source

If that doesn't work, you may have to define additional variables pointing to the desired Python libraries and include directories:

cmake -DPYTHON_EXECUTABLE=/usr/bin/python3.6 \
    -DPYTHON_INCLUDE_DIR=/usr/include/python3.6m \
    -DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.6m.so \
    -DPYTHON_PACKAGES_PATH=/usr/lib/python3.6/site-packages/ \
    ../freecad-source

It is possible to have several independent versions of Python in the same system, so the locations and version numbers of your Python files will depend on your particular Linux distribution. Use python3 -V to display the version of Python that you are using currently; only the first two numbers are necessary; for example, if the result is Python 3.6.8, you need to specify the directories that relate to the 3.6 version. If you don't know the right directories, try searching for them with the locate command.

locate python3.6

You may use python3 -m site in a terminal to determine the site-packages directory, or dist-packages for Debian systems.

Some components of FreeCAD, such as PySide, try to autodetect the most recent Python version installed on your system, which might fail if it is different from what you entered above. Adding the following cMake option might solve the issue:

-DPython3_FIND_STRATEGY=LOCATION

Building with Qt Creator against Python 3 and Qt5

1. Launch Qt Creator.

2. Click on Open Project.

3. Navigate to the directory where the source code is, freecad-source/, and choose the topmost CMakeLists.txt file.

4. By selecting the file, it will automatically run cmake on it, but it may fail if the appropriate options aren't correctly set.

5. Go to Projects → Build & Run → Imported Kit → Build → Build Settings → CMake. Set the appropriate build directory, build/.

6. Set the appropriate variables in the Key-Value dialog, of types String and Bool.

PYTHON_EXECUTABLE=/usr/bin/python3

7. If the variables do not load the project correctly, you may have to go to Projects → Manage Kits → Kits → Default (or Imported Kit or similar) → CMake Configuration. Then press Change, and add the appropriate configuration as described above. You may have to add more variables about the Python paths, if the system Python is not found.

PYTHON_EXECUTABLE:STRING=/usr/bin/python3.7
PYTHON_INCLUDE_DIR:STRING=/usr/include/python3.7m
PYTHON_LIBRARY:STRING=/usr/lib/x86_64-linux-gnu/libpython3.7m.so
PYTHON_PACKAGES_PATH:STRING=/usr/lib/python3.7/site-packages

7.1. Press Apply, then OK.

7.2. Make sure the rest of the options are correctly set, for example, Qt version should be a present version installed in the system, like Qt 5.9.5 in PATH (qt5).

Press Apply, then OK to close the configuration.

The cmake program should run automatically again, and it should fill the entire Key-Value dialog with all the variables that can be configured.

8. Go to Projects → Build & Run → Imported Kit → Run → Run Settings → Run → Run Configuration and choose FreeCADMain to compile the graphical version of FreeCAD, or FreeCADMainCMD to compile only the command line version.

9. Finally, go to the menu Build → Build Project "FreeCAD". If this is a new compilation, it should take several minutes, inclusive hours, depending on the number of processors that you have available.

Qt designer plugin

If you want to develop Qt code for FreeCAD, you'll need the Qt Designer plugin that provides all custom widgets of FreeCAD.

Go into an auxiliary directory of the source code, the run qmake with the indicated project file to create a Makefile; then run make to compile the plugin.

cd freecad-source/src/Tools/plugins/widget
qmake plugin.pro
make

If you are compiling for Qt5, make sure the qmake binary is the one for this version, so that the resulting Makefile contains the necessary information for Qt5.

cd freecad-source/src/Tools/plugins/widget
$QT_DIR/bin/qmake plugin.pro
make

where $QT_DIR is the directory that stores Qt binary libraries, for example, /usr/lib/x86_64-linux-gnu/qt5.

The library created is libFreeCAD_widgets.so, which needs to be copied to $QT_DIR/plugins/designer.

sudo cp libFreeCAD_widgets.so $QT_DIR/plugins/designer

External or internal Pivy

Previously, a version of Pivy was included in the source code of FreeCAD (internal). If you wanted to use your system's copy of Pivy (external), you needed to use -DFREECAD_USE_EXTERNAL_PIVY=1.

Using external Pivy became the default during development of FreeCAD 0.16, therefore this option does not need to be set manually anymore.

Doxygen documentation

If you have Doxygen installed you can build the source code documentation. See source documentation for instructions.

Additional documentation

The source code of FreeCAD is very extensive, and with CMake it's possible to configure many options. Learning to use CMake fully may be useful to choose the right options for your particular needs.

Making a debian package

If you plan to build a Debian package out of the sources you need to install certain packages first:

sudo apt install dh-make devscripts lintian

Go to the FreeCAD directory and call

debuild

Once the package is built, you can use lintian to check if the package contains errors

lintian freecad-package.deb

*.deb package with checkinstall

The Debian script checkinstall allows to create a *.deb package that can be installed and removed with the standard dpkg commands. It may need to be installed first (on Ubuntu use sudo apt install checkinstall). It's interactive and asks for the required information providing helpful defaults. During the process the package is installed and a *.deb file and a backup archive are created.

It's a good idea to define a name and a short description for the package. The name must be entered to uninstall it again and the desription will be listed by dpkg -l. The default name "build" is not very informative.

Example:

cd freecad-source/build
cmake ..
make
sudo checkinstall                                  # e.g. name=freecad-test1

The result is a *.deb file in the build folder. checkinstall will install the build by default. This is how you can install or uninstall it:

cd freecad-source/build
ls | grep freecad
        freecad-test1_20220814-1_amd64.deb
sudo dpkg -i freecad-test1_20220814-1_amd64.deb   # install
dkpg -l | grep freecad                            # find by name
sudo dpkg -r freecad-test1                        # uninstall by name

Updating the source code

The CMake system allows you to intelligently update the source code, and only recompile what has changed, making subsequent compilations faster.

Move to the location where the FreeCAD source code was first downloaded, and pull the new code:

cd freecad-source
git pull

Then move into the build directory where the code was compiled initially, and run cmake specifying the present directory (denoted by a dot); then trigger the re-compilation with make.

cd ../freecad-build
cmake .
make -j$(nproc --ignore=2)

Uninstalling the source code

In case the compiled source code was installed with sudo make install (for Debian) the files were copied to the /usr/local folder into several subfolders. For uninstallation the file install_manifest.txt can be used. It has been created into the build folder during compilation and contains all installed files. As long as this file exists, the installation can be uninstalled.

cd freecad-source/freecad-build
xargs sudo rm < install_manifest.txt

Troubleshooting

For 64 bit systems

When building FreeCAD for 64-bit there is a known issue with the OpenCASCADE (OCCT) 64-bit package. To get FreeCAD running properly you might need to run the configure script and set additional CXXFLAGS:

./configure CXXFLAGS="-D_OCC64"

For Debian based systems this option is not needed when using the pre-built OpenCASCADE packages because these ones set the proper CXXFLAGS internally.

Automatic build scripts

Here is all what you need for a complete build of FreeCAD. It's a one-script-approach and works on a freshly installed Linux distribution. The commands will ask for the root password for installation of packages and new online repositories. These scripts should run on 32 and 64 bit versions. They are written for different versions, but are also likely to run on a later version with or without major changes.

If you have such a script for your preferred distribution, please discuss it on the FreeCAD forum so we can incorporate it.

Ubuntu

These scripts provide a reliable way to install the correct set of dependencies required to build and run FreeCAD on Ubuntu. They make use of the Ubuntu personal package archives (PPA), and should work on any version of Ubuntu targeted by the PPA. The freecad-daily PPA targets recent versions of Ubuntu, while the freecad-stable PPA targets officially supported versions of Ubuntu.

This script installs the daily compiled snapshot of FreeCAD and its dependencies. It adds the daily repository, gets the dependencies to build this version, and installs the required packages. Afterwards it proceeds to pull the source code into a particular directory, creates a build directory and changes into it, configures the compilation environment with cmake, and finally builds the entire program with make. Save the script to a file, make it executable, and run it, but don't use sudo; superuser privileges will be asked only for selected commands.

#!/bin/sh
sudo add-apt-repository --enable-source ppa:freecad-maintainers/freecad-daily && sudo apt-get update
sudo apt-get build-dep freecad-daily
sudo apt-get install freecad-daily

git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad-source
mkdir freecad-build
cd freecad-build
cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 -DFREECAD_USE_PYBIND11=ON ../freecad-source
make -j$(nproc --ignore=2)

If you wish, you can uninstall the pre-compiled version of FreeCAD (freecad-daily) while leaving the dependencies in place, however, leaving this package installed will allow the package manager to keep its dependencies up to date as well; this is mostly useful if you intend to follow the development of FreeCAD, and constantly update and compile the sources from the Git repository.

The previous script assumes that you want to compile the latest version of FreeCAD, so you are using the "daily" repository to get the dependencies. However, you can instead get the build dependencies of the "stable" version for your current Ubuntu release. If this is the case, replace the top part of the previous script with the following instructions. For Ubuntu 12.04, omit --enable-source from the command.

#!/bin/sh
sudo add-apt-repository --enable-source ppa:freecad-maintainers/freecad-stable && sudo apt-get update
sudo apt-get build-dep freecad
sudo apt-get install libqt5xmlpatterns5-dev   # Needed for 0.20; should go away on next packaging update 
sudo apt-get install freecad

Once you install the freecad package from the freecad-stable repository, it will supersede the FreeCAD executable that is available from the Universe Ubuntu repository. The executable will be named simply freecad, and not freecad-stable.

openSUSE

No external Repositories are needed to compile FreeCAD. However, there is an imcompatability with python3-devel which needs to be removed. FreeCAD can be compiled from GIT

# install needed packages for development
sudo zypper install gcc cmake OpenCASCADE-devel libXerces-c-devel \
python-devel libqt4-devel python-qt4 Coin-devel SoQt-devel boost-devel \
libode-devel libQtWebKit-devel libeigen3-devel gcc-fortran git swig
 
# create new dir, and go into it
mkdir FreeCAD-Compiled 
cd FreeCAD-Compiled
 
# get the source
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git free-cad
 
# Now you will have a subfolder in this location called free-cad. It contains the source
 
# make another dir for compilation, and go into it
mkdir FreeCAD-Build1
cd FreeCAD-Build1 
 
# build configuration 
cmake ../free-cad
 
# build FreeCAD
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Since you are using git, next time you wish to compile you do not have to clone everything, just pull from git and compile once more

# go into free-cad dir created earlier
cd free-cad
 
# pull
git pull
 
# get back to previous dir
cd ..
 
# Now repeat last few steps from before.
 
# make another dir for compilation, and go into it
mkdir FreeCAD-Build2
cd FreeCAD-Build2
 
# build configuration 
cmake ../free-cad
 
# build FreeCAD
# Note: to speed up build use all CPU cores: make -j$(nproc)
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Debian Squeeze

# get the needed tools and libs
sudo apt-get install build-essential python libcoin60-dev libsoqt4-dev \
libxerces-c2-dev libboost-dev libboost-date-time-dev libboost-filesystem-dev \
libboost-graph-dev libboost-iostreams-dev libboost-program-options-dev \
libboost-serialization-dev libboost-signals-dev libboost-regex-dev \
libqt4-dev qt4-dev-tools python2.5-dev \
libsimage-dev libopencascade-dev \
libsoqt4-dev libode-dev subversion cmake libeigen2-dev python-pivy \
libtool autotools-dev automake gfortran
 
# checkout the latest source
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git freecad
 
# go to source dir
cd freecad
 
# build configuration 
cmake .
 
# build FreeCAD
# Note: to speed up build use all CPU cores: make -j$(nproc)
make
 
# test FreeCAD
cd bin
./FreeCAD -t 0

Fedora 27/28/29

Posted by user [PrzemoF] in the forum.

#!/bin/bash

ARCH=$(arch)

MAIN_DIR=FreeCAD
BUILD_DIR=build

#FEDORA_VERSION=27
#FEDORA_VERSION=28
FEDORA_VERSION=29

PACKAGES="gcc cmake gcc-c++ boost-devel zlib-devel swig eigen3 qt-devel \
shiboken shiboken-devel pyside-tools python-pyside python-pyside-devel xerces-c \
xerces-c-devel OCE-devel smesh graphviz python-pivy python-matplotlib tbb-devel \
 freeimage-devel Coin3 Coin3-devel med-devel vtk-devel"

FEDORA_29_PACKAGES="boost-python2 boost-python3 boost-python2-devel boost-python3-devel"

if [ "$FEDORA_VERSION" = "29" ]; then
    PACKAGES="$PACKAGES $FEDORA_29_PACKAGES"
fi

echo "Installing packages required to build FreeCAD"
sudo dnf -y install $PACKAGES
cd ~
mkdir $MAIN_DIR || { echo "~/$MAIN_DIR already exist. Quitting.."; exit; }
cd $MAIN_DIR
git clone --recurse-submodules https://github.com/FreeCAD/FreeCAD.git
mkdir $BUILD_DIR || { echo "~/$BUILD_DIR already exist. Quitting.."; exit; }
cd $BUILD_DIR
cmake ../FreeCAD 
make -j$(nproc)

Arch using AUR

Arch User Repository (AUR) is a collection user made recipes to build packages which are not officially supported by distribution maintainers / community. They are usually safe. You can see who maintain the package and for how long he did. It is recommended to check construction files. Also non open source software are available in this area even if maintained by the official owning company.

Prerequisite : git

Steps :

  1. Open a terminal. Optionally create a directory eg. mkdir git. Optionally change directory eg. cd git.
  2. Clone the AUR repository : git clone https://aur.archlinux.org/freecad-git.git
  3. Enter AUR repository folder : cd freecad-git
  4. Compile using Arch makepkg : makepkg -s. The -s or --syncdeps flag will also install required dependencies.
  5. Install created package : makepkg --install or double click on the pkgname-pkgver.pkg.tar.xz inside your file browser.

To update FreeCAD to latest build just repeat from step 3. Update AUR repository when there is some breaking change in the recipe or new features using git checkout -f inside the folder.



There is an experimental FreeCAD Docker container that is being tested for FreeCAD development. Read more about it at Compile on Docker

Overview

Această pagină descrie modul de compilare a celei mai recente surse FreeCAD pe macOS X. Latest înseamnă cel mai recent angajament al filialei principale a depozitului Github al FreeCAD.

These instructions have been tested on macOS Catalina with standard XCode 11.6. It is known to work on macOS BigSur Beta with XCode 12.0 beta. If you plan to use XCode Beta, please be sure to download Command Line Tools add on through a dmg package to workaround some libz dependency issues.

Această pagină servește ca un început rapid și nu intenționează să fie cuprinzătoare în ceea ce privește descrierea tuturor opțiunilor de compilare disponibile.

If you just want to evaluate the latest pre-release build of FreeCAD, you can download pre-built binaries from here.

Instalați cerințele preliminare

Următorul software trebuie instalat pentru a sprijini procesul de construire.

The following software must be installed to support the build process.

Managerul de pachete Homebrew

Homebrew este un manager de pachete de linie de comandă pentru MacOS. The Homebrew main page furnizează o linie de comandă de instalare pe care pur și simplu o inserați într-o fereastră de terminal.

Homebrew is a command line based package manager for macOS. The Homebrew main page provides an installation command line that you simply paste into a terminal window.

CMake

CMake este un instrument de complilare care construiește o configurație de complilare bazată pe variabilele pe care le specificați. Apoi, emiteți comanda "make" pentru a compila configurația respectivă. The command-line version of CMake is automatically installed as part of the Homebrew installation, above. If you prefer to use a GUI version of CMake, you can download it from here.

CMake is a build tool that generates a build configuration based on variables you specify. You then issue the 'make' command to actually build that configuration. The command-line version of CMake is automatically installed as part of the Homebrew installation, above. If you prefer to use a GUI version of CMake, you can download it from here.

Instalarea dependențelor

FreeCAD menține un "robinet" al Homebrew care instalează formulele și dependențele necesare. Eliberați următoarele comenzi de brew în terminalul dvs.

FreeCAD maintains a Homebrew 'cask' which installs the required formulas and dependencies. Issue the following brew commands in your terminal.

brew tap freecad/freecad
brew install eigen
brew install --only-dependencies freecad

Notes:

  1. 'brew install' may take quite a while, so you may want go grab a beverage. :-)

Alternately, you can install the individual dependencies manually by installing the following packages using brew install ...:

  • cmake
  • swig
  • boost
  • boost-python3
  • eigen
  • gts
  • vtk
  • xerces-c
  • qt@5 - Only Qt5 is currently supported, support for Qt6 is a work-in-progress
  • opencascade
  • doxygen
  • pkgconfig
  • coin3d - Note that as of this writing (Nov. 2022) this will install an unusable version of pyside@2 as a dependency.

There are several packages that are only available when you have tapped the freecad cask: you must do that (brew tap freecad/freecad). Due to some historical bug workarounds, at the time of this writing (Nov. 2022) the versions of PySide2 and Shiboken2 installed by Homebrew are not usable because they force the use of Py_Limited_API, which FreeCAD does not support. It is expected that this workaround will be removed in the coming months, but in the meantime you must use the FreeCAD cask versions of PySide and Shiboken. Use brew install ..., install the following packages:

  • freecad/freecad/pyside2@5.15.5
  • freecad/freecad/shiboken2@5.15.5
  • freecad/freecad/med-file
  • freecad/freecad/netgen

You will also need to "link" PySide and Shiboken:

brew link freecad/freecad/pyside2@5.15.5 freecad/freecad/shiboken2@5.15.5

In some cases the packages installed by Homebrew do not use the same Python version: for example, at the time of this writing PySide2 uses Python 3.10, but boost-python3 uses Python 3.11. While it is possible to "roll back" the more advanced version (so that in this case boost-python3 uses Python 3.10) this is an advanced operation, and in many cases it is best to wait for an update to the other package. If you want to pursue that path anyway, look at the "brew extract" command, which you can use to extract a formula into a new cask (typically freecad/freecad). You can then edit that formula as needed.

You will need to set the path to Qt: Qt5 is currently supported, while support for Qt6 is a work-in-progress. Set FREECAD_QT_VERSION to "Auto" or "5" to select Qt5 (the default). On the command line, use something like:

cmake \
  -DCMAKE_BUILD_TYPE="Release" \
  -DPYTHON_EXECUTABLE="/usr/local/bin/python3" \
  -DQt5_DIR="/usr/local/Cellar/qt@5/5.15.7/lib/cmake/Qt5" \
  -DPySide2_DIR="/usr/local/Cellar/pyside2@5.15.5/5.15.5/lib/cmake/PySide2-5.15.5" \
  -DShiboken2_DIR="/usr/local/Cellar/shiboken2@5.15.5/5.15.5_1/lib/cmake/Shiboken2-5.15.5" \
  ../freecad-source

Get the source

În instrucțiunile de mai jos, sunt create soursă și folderele compilate unele sub altele

In the following instructions, the source and build folders are created side-by-side under

/Users/username/FreeCAD

but you can use whatever folders you want.

mkdir ~/FreeCAD
cd ~/FreeCAD

The following command will clone the FreeCAD git repository into a directory called FreeCAD-git.

git clone https://github.com/FreeCAD/FreeCAD FreeCAD-git

Create the build folder.

mkdir ~/FreeCAD/build

Run CMake

Next, we will run CMake to generate the build configuration. Several options must be passed to CMake. The following table describes the options and gives some background.

CMake Options

Name Value Notes
CMAKE_BUILD_TYPE Release (STRING) Release or Debug. Debug is generally used for developer-level testing but may also be required for user-level testing and troubleshooting.
BUILD_QT5 1 (BOOL) Required to build with Qt5.
CMAKE_PREFIX_PATH "/usr/local/Cellar/qt@5.6/5.6.2/lib/cmake" (PATH) Required to build with Qt5. See note below.
FREECAD_CREATE_MAC_APP 1 (BOOL) Create a FreeCAD.app bundle at the location specified in CMAKE_INSTALL_PREFIX, when the 'make install' command issued.
CMAKE_INSTALL_PREFIX "./.." (PATH) Path where you want to generate the FreeCAD.app bundle.
FREECAD_USE_EXTERNAL_KDL 1 (BOOL) Required.
BUILD_FEM_NETGEN 1 (BOOL) Required.

Note: Command line to generate CMAKE_PREFIX_PATH:

ls -d $(brew list -1 | grep qt | tail -1 | xargs brew --cellar)/*/lib/cmake

CMake GUI

Deschideți aplicația CMake și completați câmpurile sursă și construiți dosarul. În acest exemplu, ar fi /Users/username/FreeCAD/FreeCAD-gitpentru sursă, și /Users/username/FreeCAD/build pentru construirea folderului .

Open the CMake app, and fill in the source and build folder fields. In this example, it would be /Users/username/FreeCAD/FreeCAD-git for the source, and /Users/username/FreeCAD/build for the build folder.

Next, click the Configure button to populate the list of configuration options. This will display a dialog asking you to specify what generator to use. Leave it at the default Unix Makefiles. Configuring will fail the first time because there are some options that need to be changed. Note: You will need to check the Advanced checkbox to get all of the options.

Set options from the table above, then click Configure again and then Generate.

Set options from the table above, then click Configure again and then Generate.

CMake command line

Enter the following in the terminal.

Enter the following in the terminal.

export PREFIX_PATH="/usr/local/opt/qt5152;\
/usr/local/Cellar/nglib/v6.2.2007/Contents/Resources;\
/usr/local/Cellar/vtk@8.2/8.2.0_1/lib/cmake;"
$cd ~/FreeCAD/build
$cmake \
  -DCMAKE_BUILD_TYPE="Release"   \
  -DBUILD_QT5=1                  \
  -DWITH_PYTHON3=1               \
  -DCMAKE_PREFIX_PATH="$PREFIX_PATH" \
  -DPYTHON_EXECUTABLE="/usr/local/bin/python3" \
  -DFREECAD_USE_EXTERNAL_KDL=1   \
  -DCMAKE_CXX_FLAGS='-std=c++14' \
  -DBUILD_FEM_NETGEN=1           \
  -DFREECAD_CREATE_MAC_APP=1     \
  -DCMAKE_INSTALL_PREFIX="./.."  \
  ../FreeCAD-git/

Run make

În cele din urmă, de la un terminal rulați make pentru a compila și a lega FreeCAD și a genera pachetul de aplicații.

Finally, from a terminal run make to compile and link FreeCAD, and generate the app bundle.

cd ~/FreeCAD/build
make -j5 install

Opțiunea -j specifică câte procese de procesare se execută simultan. Unul plus numărul de nuclee CPU este, de obicei, un număr bun de utilizat. Cu toate acestea, dacă compilarea eșuează dintr-un motiv oarecare, este utilă reluarea efectuării fără opțiunea -j, astfel încât să puteți vedea exact unde a apărut eroarea.

A se vedea și Compiling - Speeding up.

Dacă ați finalizat fără erori, puteți lansa FreeCAD făcând dublu clic pe executabilul din Finder

Updating după Github

Dezvoltarea FreeCAD are loc rapid; aproape în fiecare zi sunt bug fixe sau noi funcionalități. Pentru a obține cele mai recente modificări, utilizați git pentru a actualiza directorul sursă (consultați Source code management), apoi re-executați CMake și parcurgeți pașii de mai sus. De obicei, nu este necesar să începeți cu un director de compliare curat în acest caz, iar compilatele ulterioare vor merge, în general, mult mai repede decât prima.

FreeCAD development happens fast; every day or so there are bug fixes or new features. To get the latest changes, use git to update the source directory (see Source code management), then re-run the CMake and make steps above. It is not usually necessary to start with a clean build directory in this case, and subsequent compiles will generally go much faster than the first one.

Compilarea cu Qt4

FreeCAD a trecut de la Qt 4 la Qt 5. Dacă trebuie să complilați cu Qt4, sunt necesari următorii pași suplimentari.

FreeCAD has transitioned from Qt 4 to Qt 5 as well as homebrew. Qt 4 is no longer available as an option for new build on macOS following Qt 5 transition. Python 2.7 has been deprecated within homebrew and upcoming macOS and we do not support it anymore for macOS build either.

Depanare

Segfault on Qt5 launch

În cazul în care Qt4 a fost instalat anterior via brew, și apoi ați construit cu Qt5, puteți obține o excepție EXC_BAD_ACCESS (SEGSEGV) atunci când lansați compilarea nouli Qt5 . Remedierea pentru aceasta este de a dezinstala manual Qt4.

If Qt4 was previously installed via brew, and you then build with Qt5, you may get a EXC_BAD_ACCESS (SEGSEGV) exception when launching the new Qt5 build. The fix for this is to manually uninstall Qt4.

brew uninstall --ignore-dependencies --force cartr/qt4/shiboken@1.2 cartr/qt4/pyside@1.2 cartr/qt4/pyside-tools@1.2 cartr/qt4/qt-legacy-formula

Fortran

"No CMAKE_Fortran_COMPILER could be found." în timpul configurației - versiunile mai vechi ale FreeCAD vor trebui să compileze instalate. Cu Homebrew, procedați la "brew install gcc" și încerdați configurarea din nou, dând lui cmake cale spre Fortran ie -DCMAKE_Fortran_COMPILER=/opt/local/bin/gfortran-mp-4.9 . Sau, de preferat, utilizați o versiune mai nouă a sursei FreeCAD!

"No CMAKE_Fortran_COMPILER could be found." during configuration - Older versions of FreeCAD will need a fortran compiler installed. With Homebrew, do "brew install gcc" and try configuring again, giving cmake the path to Fortran ie -DCMAKE_Fortran_COMPILER=/opt/local/bin/gfortran-mp-4.9 . Or, preferably use a more current version of FreeCAD source!

FreeType

Atunci când se utilizează versiuni CMake mai vechi de 3.1.0, este necesar să setați variabila CMake FREETYPE_INCLUDE_DIR_freetype2 manually, eg /usr/local/include/freetype2

When using CMake versions older than 3.1.0, it's necessary to set CMake variable FREETYPE_INCLUDE_DIR_freetype2 manually, eg /usr/local/include/freetype2

Additional Build Instructions

FreeCAD can be built against the latest git master hosted on github, and launched from a CLI using libraries provided by the homebrew-freecad tap. For a complete list of build instructions see here.


Overview

Prezentare generală

Acestea sunt biblioteci care nu sunt modificate în proiectul FreeCAD. Ele sunt practic utilizate ca o bibliotecă dinamică de legătură (* .so sau * .dll). Dacă este nevoie de schimbare, sau a wrapper class este necesar , atunci codul wrapper sau biblioteca modificată trebuie mutat în pachetul de bază FreeCAD. Bibliotecile folosite sunt:

The dependencies need to be installed in the system before proceeding with compilation; see compile on Linux, compile on Windows, and compile on MacOS for more information.

Dacă utilizați Windows, luați în considerare folosireaLibPack în loc de a descărca și a instala tot felul de chestii pe cont propriu.

Legături

Link table
Lib name Version needed Link to get it
Python >= 2.5.x http://www.python.org/
OpenCasCade >= 5.2 http://www.opencascade.org
Qt >= 4.1.x https://www.qt.io/
Coin3D >= 2.x http://www.coin3d.org
SoQt >= 1.2 http://www.coin3d.org
Xerces-C++ >= 2.7.x < 3.0 http://xml.apache.org/xerces-c/
Zlib >= 1.x.x http://www.zlib.net/
Boost >= 1.33.x http://www.boost.org/
Eigen3 >= 3.0.1 http://eigen.tuxfamily.org/index.php?title=Main_Page
Shiboken >= 1.1.2 http://shiboken.readthedocs.org/en/latest/
libarea N/A https://github.com/danielfalck/libarea

Detalii

Python

Python

Version: 2.5 or higher

License: Python 2.5 license

Python 2 became obsolete in 2019. Further development of FreeCAD will use exclusively Python 3; compatibility with Python 2 won't be tested, so old workbenches and macros that use this version will have to be updated or they may stop working. Please post on the FreeCAD forum if you encounter problems with Python 3.

Python is a popular all-purpose scripting language that is widely used in Linux and open source software. In FreeCAD, Python is used during compilation and also at runtime in different ways. It is used

  • to write test scripts to test for different conditions, such as memory leaks, to ensure functionality of the software after changes, for post build checks, and test coverage tests,
  • to write macros and macro recording,
  • to implement application logic for standard packages,
  • to implement auxiliary tools such as the Addon Manager,
  • to implement entire workbenches like Draft and Arch,
  • to dynamically load packages,
  • to implement rules for design (knowledge engineering),
  • to do fancy Internet interactions like work groups and PDM

Puteți folosi programul sursă sau binarul de la http://www.python.org/ ori să utlizați alternativ ActiveState Python from http://www.activestate.com/ deși este puțin greu să obțineți depanarea bibliotecilor/libs din ActiveState.

Python was chosen as the scripting language for FreeCAD for different reasons:

  • It is more object oriented than Perl and Tcl.
  • The code is more readable than Perl and Visual Basic.
  • It is easier to embed in another application, unlike, say, Java.

In summary, Python is well documented, and it's easy to embed and extend in a C++ application. It is also well tested and has strong support from the open source community. Read more about Python and browse the official documentation at Python.org.

Boost

Version: 1.33.x

License: Boost Software License - Version 1.0

Bibliotecile Boost C ++ sunt o colecție de biblioteci evaluate de colegi, care extind funcționalitatea C ++. Bibliotecile sunt licențiate sub licența Boost Software License, concepute pentru a permite ca Boost să fie utilizat atât cu proiecte deschise, cât și cu surse închise. Mulți dintre fondatorii lui Boost se află în comitetul standard C ++ și mai multe biblioteci Boost au fost acceptate pentru a fi încorporate în raportul tehnic 1 al C ++ 0x.

Due to their popularity and stability, many Boost libraries have been accepted for incorporation into the C++11 standard, and more are planned for inclusion in subsequent C++ standards.

Pentru a asigura eficiența și flexibilitatea, Boost folosește pe scară largă șabloanele. Boost a fost o sursă de muncă și cercetări ample privind programarea generică și meta-programarea în C ++.

OpenCasCade

Version: 5.2 or higher

License: v6.7.0 and later are governed by GNU Lesser General Public License (LGPL) version 2.1 with additional exception. https://www.opencascade.com/content/licensing Earlier versions use a slightly different license: https://www.opencascade.com/content/occt-public-license

OCC este un kernel CAD complet echipat. Inițial, este dezvoltat de Matra Datavision în Franța pentru aplicațiile Strim (Styler) și Euclid Quantum și mai târziu l-au făcut Open Source. Este o bibliotecă cu adevărat imensă și face posibilă o aplicație CAO gratuită, oferind câteva pachete care ar fi greu sau imposibil de implementat într-un proiect Open Source:

  • Un nucleu geometric complet compatibil cu STEP
  • Un model topologic de date și toate funcțiile necesare pentru a lucra pe (tăiere, fuziune, extrudere, și așa mai departe ...)
  • Procese standard de import / export precum STEP, IGES, VRML
  • Viewer 3D și 2D cu selectare suport
  • O structura de document și a datelor unui proiect cu suport pentru salvare și restaurare, legătura externă a documentelor, recalcularea istoricului de desenului/proiectului (modelarea parametrică) și a unui centru de încărcare a datelor de tip nou, ca un modul de extensie dinamic.

OCCT is a big and complex set of C++ libraries that provide functionality required by a CAD application:

  • A complete STEP compliant geometry kernel.
  • A topological data model and needed functions to work with shapes (cut, fuse, extrude, and many others).
  • Standard import and export processors for files like STEP, IGES, VRML.
  • A 2D and 3D viewer with selection support.
  • A document and project data structure with support for save and restore, external linking of documents, recalculation of design history (parametric modeling) and a facility to load new data types as an extension package dynamically.

There are two main versions of OpenCASCADE in existence in different Linux distributions. One is distributed by the original developers; it is known as OCCT, and is packaged under the names occ or occt. The other version is the "community edition", abbreviated OCE, and is normally found with the oce name. FreeCAD can compile against either version, however, since 2016 FreeCAD recommends compiling against the official OCCT libraries rather than the OCE ones. The reason is that the community edition lacks important bug fixes and functions that make using FreeCAD better.

To learn more about OpenCasCade take a look at the OpenCasCade page or http://www.opencascade.org.

Qt

Version: 4.1.x or higher

License: GPL v2.0/v3.0 or Commercial (from version 4.5 on also LPGL v2.1)

Nu cred că trebuie să spun foarte multe despre QT. Este unul dintre cele mai utilizate instrumente de GUI în proiectele Open Source. Pentru mine cel mai important punct de utilizare a Qt este designerul Qt și posibilitatea de a încărca toate casetele dialog ca resursă (XML) și care încorporează widget-uri specializate. Într-o aplicație CAX interacțiunea cu utilizatorul și casetele de dialog sunt de departe cea mai mare parte a codului și o bună proiectarea a dialogului ester foarte importantă pentru extinderea freeCAD cu noi funcționalități. Informații suplimentare și foarte bună documentație on line o veți găsi pe http://www.qtsoftware.com.

Further information about Qt libraries and their programming documentation are available at Qt Documentation.

Shiboken2 and Pyside2

Shiboken and Pyside

Shiboken (Shi bō ken, 死某剣)este generatorul de legare Python pe care îl utilizează Qt pentru Python pentru a crea modulul PySide, cu alte cuvinte, este sistemul pe care îl folosim pentru a expune API-ul Qt C ++ către Python.

Numele de Shiboken2 și PySide2 face referire la compatibilitatea Qt 5, deoarece versiunile anterioare (fără 2) se referă la Qt 4. Citiți mai multe despre Shiboken și Pyside pe Qt for Python wiki page

Read more about Shiboken and Pyside on Qt for Python.

Coin3D

Version: 2.0 or higher

License: GPL v2.0 or Commercial

Coin este o bibliotecă grafică 3D de nivel înalt cu o interfață de programare a aplicațiilor C ++Application Programming Interface. Coin utilizează structuri de date grafice de scenă pentru a oferi grafică în timp real potrivită pentru majoritatea aplicațiilor de vizualizare științifică și inginerie.

Coin este construit pe standardul industrial OpenGL cu biblioteca de randare imediată și adaugă abstracții pentru primitive de nivel superior, oferă interactivitate 3D, îmbunătățește foarte mult confortul și productivitatea programatorului și conține multe funcții de optimizare complexe pentru randarea rapidă și în plus care este transparentă pentru programatorul de aplicații.

Coin se bazează pe SGI Open Inventor API . Open Inventor, pentru cei care nu sunt familiarizați cu acesta, a devenit de mult timp biblioteca grafică standard de facto pentru vizualizarea 3D și software-ul de simulare vizuală în comunitatea științifică și de inginerie. Și-a demonstrat valoarea timp de peste 10 ani, maturitatea sa contribuind la succesul său ca o fundație majoră în mii de aplicații de inginerie la scară largă din întreaga lume.

Vom folosi OpenInventor ca vizualizator 3D în FreeCAD, deoarece vizualizatorul OpenCasCade (AIS și Graphics3D) au limitele lor din cauza fluxului ridicat de date, mai ales atunci când intră în randarea inginerească la scară largă. Alte lucruri, cum ar fi texturile sau randarea volumetrică, nu sunt cu adevărat susținute și așa mai departe....

Software Coin este portabil pe o gamă largă de platforme: orice platformă UNIX / Linux / * BSD, tot sistemul de operare Microsoft Windows și Mac OS X.

SoQt

Version: 1.2.0 or higher

License: GPL v2.0 or Commercial

SoQt este Inventorul fr lrgături pentru Qt Gui Toolkit. Din păcate, nu mai este LGPL, deci trebuie să îl eliminăm din codul de bază a FreeCAD și să îl conectăm ca o bibliotecă. Are același model de licență ca și Coin. Și trebuie să îl compilați cu versiunea Qt.

SoQt is no longer used in FreeCAD, it was replaced by Quarter which is a more recent Qt binding.

Quarter

Version: 1.0 or higher

License: BSD 3-clause license

Quarter is a newer Coin3D binding to the Qt toolkit. A version of it is included in the source code of FreeCAD so it is compiled together with it.

Pivy

Version: 0.6.3 or higher

License: BSD 3-clause license

Pivy is a library that wraps the Coin3d library for use in Python. It is not needed to build FreeCAD or to start it, but it is needed as a runtime dependency by the Draft Workbench, and by other workbenches that use it internally, like Arch and BIM.

If you are not going to use these workbenches, you won't need Pivy.

Ply

Version: 3.11 or higher

License: BSD 3-clause license

Ply is the Python-Lex-Yacc parser. It is used as a runtime dependency by the OpenSCAD Workbench. If you don't use this workbench, you may not need this package.

For more information see Ply homepage

Xerces-C++

Version: 2.7.0 or higher

License: Apache Software License Version 2.0

Xerces-C ++ este un analizor de validare (parser) XML scris într-un subset portabil de C ++. Cu Xerces-C ++ se ușurează oferirea aplicației dvs. abilității de a citi și scrie date în format XML. O bibliotecă partajată este prevăzută analizarea, generarea, manipularea și validarea documentelor XML.

The parser is used for saving and restoring parameters in FreeCAD.

Eigen3

Version: 3.0 or higher

License: Starting from the 3.1.1 version, it is licensed under the Mozilla Public License 2.0. Earlier versions were licensed under the GNU Lesser General Public License 3.

Eigen is a C++ template library for linear algebra: matrices, vectors, numerical solvers, and related algorithms.

If you just want to use Eigen, you can use the header files right away. There is no binary library to link to, and no configured header file. Eigen is a pure template library defined in the headers.

Eigen is used in FreeCAD for many vector operations in 3D space. To learn more, visit Eigen homepage.

Zipios++

Version: 0.1.5 or higher

License: GNU Lesser General Public License 2.1

Zipios++ is a C++ library for reading and writing .zip files. Access to individual entries is provided through standard C++ iostreams. A simple read-only virtual file system that mounts regular directories and .zip files is also provided. The structure and public interface of Zipios++ are loosely based on the java.util.zip package of Java.

FreeCAD's native file format .FCstd is in reality a .zip file that stores and compresses other types of data within it, such as BREP and XML files. Therefore, Zipios++ is used to save and open compressed archives, including FreeCAD files.

A copy of Zipios++ is included in the source code of FreeCAD so it is compiled together with it. If you want to use an external Zipios++ library, provided by your operating system, you may set -DFREECAD_USE_EXTERNAL_ZIPIOS=ON with cmake.

Zipios++ uses the Zlib library to perform the actual decompression of files.

Zlib

Version: 1.x.x

License: zlib License

zlib este conceput pentru a fi gratuit, cu scop general, fără a fi limitat din punct de vedere juridic - adică nu este acoperit de nici un brevet- Biblioteca de compresie a datelor fără pierderi pentru utilizare pe orice hardware și sistem de operare. Formatul de date zlib este auto-portabil pe orice platformă. Spre deosebire de metoda de compresie LZW folosită în compresia Unix compress(1) și în formatul de imagine GIF, metoda de comprimare utilizată în mod curent în zlib nu extinde niciodată datele. (LZW poate dubla sau tripla mărimea fișierului în cazuri extreme). Amprenta de memorie a bibliotecii zlib este, de asemenea, independentă de datele de intrare și poate fi redusă, dacă este necesar, la un anumit raport de compresie.

A copy of this library is included in the source code of FreeCAD so it is compiled together with it.

libarea

Version: N/A

License: New BSD (BSD 3-Clause)

Area is a piece of software created by Dan Heeks for HeeksCNC. It is employed as a library for generation of CAM related operations in the Path Workbench.

A copy of the library is included with the source code of the CAM Workbench, so it is compiled together with it.

LibPack

LibPack

LibPack este un pachet convenabil cu toate bibliotecile de mai sus ambalate împreună. Este necesar doar dacă construiți pe Platforma Windows și îl puteți găsi la https://github.com/FreeCAD/FreeCAD-ports-cache/releases. Dacă lucrați sub Linux, trebuie să utilizați depozitele de pachete ale distribuției dvs. Linux, adică nu este nevoie de libPack și oferit pentru Linux.

If you're working under Linux, you don't need the LibPack, as you can get the dependencies from your distribution's repositories as mentioned in the compile on Linux page.

FreeCAD 12.1.2

See the announcement in the forum: New libpacks for Windows with Qt5.12, OCC7.3 and Python 3.6 by apeltauer

It includes among other things: Boost 1.67, Coin3D 4.0.0a, Eigen3, Open CASCADE Technology 7.3.0, Python 3.6.8, PySide2, Qt 5.12.1, Salome SMESH, Shiboken2, vtk7, Xerces-C, Zipios++, zlib 1.2.11


Compiling (Speeding up)
Third Party Tools


Tool Page

Pagina Instrumentelor

Pentru fiecare dezvoltare serioasă de software aveți nevoie de unelte. Iată o listă de instrumente pe care le folosim pentru a dezvolta FreeCAD:

Platform independent tools

Qt-Toolkit

Platform independend tools

Qt-Toolkit

Qt-toolkit este un instrument de proiectare a interfeței utilizator independent de platformă. Acesta este conținut în LibPack a lui FreeCAD, dar poate fi descărcat de asemenea de la Qt project.

Inkscape

InkScape

Excelent program de desen vectorial. Aderă la standardul SVG și este folosit pentru a desena Iconițe și Imagini. Luați-l de la www.inkscape.org.

Doxygen

Doxygen

Un instrument foarte bun și stabil pentru a genera documentație plecând de la fișierele sursă .h și .cpp.

Gimp

The Gimp

Nu prea sunt multe de spus despre celebrul Programul de Manipulare a Imaginii Gnu(Gimp). În afară de aceasta, poate administra și fișierele .xpm, care reprezintă o modalitate foarte convenabilă de a crea pictogramele în programele QT Toolkit. formatul XPM este în esență C-Code care poate fi compilat într-un program ca Qt -Toolkit.

Get the GIMP here: www.gimp.org

Gitkraken

Gitkraken

Acesta este un GUI propriu-zis, care este foarte util pentru a afla cum să lucrați dacă sunteți interesat să doriți să contribuiți la FreeCAD. Pagini relevante pentru cercetare:te to FreeCAD.

OBS Studio

Free and open source software for video recording and live streaming. More details on official website: obsproject.com

OpenCamLib

OpenCamLib (OCL) is an open source library aiming to provide computer aided manufacturing (CAM) algorithms. FreeCAD uses OCL in the experimental 3D surface path operations and other experimental features.

StarUML

StarUML

Un program UML de tip Open Source cu funcții complete. El are o mulțime de caracteristici ale celor mari, inclusiv inginerie inversă a codului sursă C++ ...

Download here: staruml.sourceforge.net

Instrumente în Windows

Visual Studio Community

Visual Studio 8 Express

Deși VC8 este pentru dezvoltarea în C ++ nu este cu adevărat un pas înainte, deoarece VisualStudio 6 (mai degrabă un mare pas înapoi), este un sistem de dezvoltare gratuit pe Windows. Pentru aplicațiile native Win32 trebuie să descărcați PlatformSDK din M $, ediția Express este dificil de găsit.

Deși, ediția Express este greu de găsit. Dar, ai putea încerca la this link

CamStudio

CamStudio

CamStudio este instrumentul open source pentru a crea înregistrări video ale ecranului de tip Screencast (Webcasts). Este un instrument foarte bun pentru a crea tutoriale prin înregistrarea tuturor operațiunilor și mișcărilor mouse-lui care se petrec pe ecranul dvs .Un video nu este atât de plictisitor ca și scrierea documentației.

See camstudio.org for details.

Tools on Linux

TODO


Third Party Libraries
Start up and Configuration


In FreeCAD version 0.20 the default location of the program's configuration, data and cache files was changed for Linux.
See Release notes 0.20 for more information. This page has not yet been updated accordingly.

Overview

Această pagină prezintă modalitățile diferite de a lansa FreeCAD și cele mai importante funcții de configurare.

Pornirea FreeCAD din Linia de Comandă

FreeCAD poate fi pornit în mod normal prin dublul clic pe pictograma desktop sau selectând-o din meniul de pornire, dar poate fi pornit și direct din linia de comandă. Aceasta vă permite să modificați unele dintre opțiunile de pornire implicite.

Using command line options without a command line shell

Utilizarea opțiunilor din linia de comandă fără coajă de linie de comandă

  • Pe Ubuntu puteți crea o pictogramă desktop și puteți edita proprietățile. Adăugați opțiunile din linia de comandă separate prin spații în spatele numelui programului în câmpul "Comandă".
  • Pe Windows creați o scurtătură și editați proprietățile. Adăugați opțiunile din linia de comandă separate prin spații în câmpul "Țintă".

Opțiuni linia de Commandă

Opțiunile din linia de comandă sunt supuse unor modificări frecvente.Astfel, este o idee bună să verificați opțiunile curente introducând:

FreeCAD --help

Din răspuns puteți citi parametrii posibili:

 Usage: FreeCAD [options] File1 File2 ...
 
 Allowed options:
 
 Generic options:
   -v [ --version ]          Prints version string
   -h [ --help ]             Prints help message
   -c [ --console ]          Starts in console mode
   --response-file arg       Can be specified with '@name', too
   --dump-config             Dumps configuration
   --get-config arg          Prints the value of the requested configuration key
 
 Configuration:
   -l [ --write-log ]        Writes a log file to:
                             /home/username/.FreeCAD/FreeCAD.log
   --log-file arg            Unlike --write-log this allows logging to an 
                             arbitrary file
   -u [ --user-cfg ] arg     User config file to load/save user settings
   -s [ --system-cfg ] arg   System config file to load/save system settings
   -t [ --run-test ] arg     Test case - or 0 for all
   -M [ --module-path ] arg  Additional module paths
   -P [ --python-path ] arg  Additional python paths
   --single-instance         Allow to run a single instance of the application

In the following table, selected options are described in more detail:

Long option Corresponding config var name Synopsis
--user-cfg <filename> UserParameter Filename or relative path that ends with a filename. Defaults to user.cfg.
--module-path <dir> Prepends to AdditionalModulePaths Directory that contains modules. This option can be given repeatedly to specify multiple directories.
--get-config <config-var-name> most Outputs the requested value in a popup dialog. Exits upon confirmation with OK. Cannot be used repeatedly. If an unknown/illegal variable name is used, the response is empty. The --console flag is not honored.

Options can written in two forms: --long-option arg and --long-option=arg.

Response and config files

FreeCAD poate citi unele dintre aceste opțiuni dintr-un fișier de configurare. Acest fișier trebuie să fie în calea bin și trebuie să fie numit FreeCAD.cfg. Rețineți că opțiunile specificate în linia de comandă suprascriu fișierul de configurare!

Unele sisteme de operare au o limită foarte mică de caractere pe linia de comandă. Modul comun de a evita aceste limitări este utilizarea fișierelor de răspuns. Un fișier de răspuns este doar un fișier de configurare care utilizează aceeași sintaxă ca și linia de comandă. Dacă linia de comandă specifică un nume de fișier de răspuns, acesta este încărcat, analizat și se adaugă în plus la de linia de comandă:

FreeCAD @ResponseFile.txt 

or:

FreeCAD --response-file=ResponseFile.txt

or:

FreeCAD --response-file ResponseFile.txt

Opțiuni ascunse

Există câteva opțiuni care nu sunt vizibile pentru utilizator. Aceste opțiuni sunt de ex. parametrii X-Window analizați de sistemul Windows:

  • -display - Setează afișarea X (implicit este$DISPLAY).
  • -geometry - Setează geometria clientului din prima fereastră care este afișată.
  • -fn or -font - Definește fontul aplicației. Fontul trebuie specificat utilizând o descriere a fontului logic X.
  • -bg or -background - Setează culoarea de fundal implicită și o paletă de aplicații (se calculează nuanțe luminoase și întunecate).
  • -fg or -foreground - Definește culoarea implicită a prim-planului.
  • -btn or -button - Definește culoare implicită a butonului.
  • -name - Definește numele aplicației.
  • -title - Definește titlul aplicației.
  • -visual - Forțează aplicația să utilizeze o imagine TrueColor vizuală pe un afișaj pe 8 biți.
  • -ncols - Limitează numărul de culori alocate în cubul de culoare pe un afișaj pe 8 biți, dacă aplicația folosește QApplication::ManyColor color specification. Dacă numărul este 216, atunci este utilizat un cub colorat de 6x6x6 (adică 6 nivele de roșu, 6 de verde și 6 de albastru); pentru alte valori, este utilizat un cub aproximativ proporțional cu un cub 2x3x1.
  • -cmap - Determină aplicația de a instala o hartă color privată pe un afișaj pe 8 biți.

Rularea FreeCAD fără GUI

FreeCAD este de obicei construit cu două executabile: o funcție GUI apelat FreeCAD și o linie de comandă apelat doar FreeCADCmd. FreeCAD poate fi folosit în modul consolă folosind comutatorul "-c", acesta este comportamentul implicit al FreeCADCmd:

FreeCAD --console

din linia de comandă. În modul consolă, nu va fi afișată nici o interfață de utilizator și veți primi un prompt de interpretor python. Din acel prompt python, aveți aceeași funcționalitate ca interpretorul python care rulează în interiorul FreeCAD GUI și accesul normal la toate modulele și pluginurile FreeCAD, cu excepția modulului FreeCADGui. Rețineți că modulele care depind de FreeCADGui pot fi, de asemenea, indisponibile.

To read more about console or headless mode, refer to Headless FreeCAD.

Running modules, macros and scripts

File type System Command line example
Module Windows "C:\Program Files\FreeCAD\bin\FreeCAD.exe" -M "C:\FreeCAD\Mod\Draft"
Linux FreeCAD_0.19 -M ~/.FreeCAD/Mod/Draft
Linux (AppImage) path/to/FreeCADXXX.AppImage -M ~/.FreeCAD/Mod/Draft
.FCMacro or .py Windows "C:\Program Files\FreeCAD\bin\FreeCAD.exe" "C:\Users\userName\AppData\Roaming\FreeCAD\Mod\WorkFeature\start_WF.FCMacro"
Linux FreeCAD_0.19 ~/.FreeCAD/Mod/WorkFeature/start_WF.FCMacro
Linux (AppImage) path/to/FreeCADXXX.AppImage ~/.FreeCAD/Mod/WorkFeature/start_WF.FCMacro

See Macro at Startup on how to set up a macro to automatically run at FreeCAD startup.

Environment variables

FreeCAD supports the following environment variables, which can be used to configure directories: introduced in version 0.19

Environment variable Corresponding config var name Synopsis
FREECAD_USER_HOME UserHomePath FreeCAD's "base" directory for keeping local user data.
FREECAD_USER_DATA UserAppData If not set, defaults to FREECAD_USER_HOME/.FreeCAD, but only if FREECAD_USER_HOME is set.
FREECAD_USER_TEMP AppTempPath If not set, defaults to FREECAD_USER_HOME/temp, but only if FREECAD_USER_HOME is set.

If the specified path does not exist, the setting is ignored!

The above environment variables are meant to be used to realize a portable FreeCAD environment. For an example how environment variables can be used from the command line on Linux refer to the notes for Linux users on the downloads page.

HOME

FreeCAD uses Qt, which does honor the HOME environmental variable. Thus, setting HOME can be used to specify the base directory of Qt-related configuration files (.config/FreeCAD/FreeCAD.conf).

FreeCad itself does not honor the HOME environmental variable (because it determines the user's home directory from a lower-level system API). Use FREECAD_USER_HOME for this pupose.

TMPDIR

The default temporary directory is /tmp/. The TMPDIR environmental variable can be used to override the default. (Editor: precedence?).

Libraries

Unele biblioteci trebuie să apeleze variabilele mediului sistemului. Uneori, atunci când există o problemă cu o instalare FreeCAD, aceasta se datorează faptului că unele variabile de mediu lipsesc sau sunt setate incorect. Prin urmare, unele variabile importante sunt duplicate în Config și salvate în fișierul jurnal(log file).

Variabile de mediu Python:

  • PYTHONPATH
  • PYTHONHOME
  • TCL_LIBRARY
  • TCLLIBPATH

Variabile de mediu relativ la OpenCascade:

  • CSF_MDTVFontDirectory
  • CSF_MDTVTexturesDirectory
  • CSF_UnitsDefinition
  • CSF_UnitsLexicon
  • CSF_StandardDefaults
  • CSF_PluginDefaults
  • CSF_LANGUAGE
  • CSF_SHMessage
  • CSF_XCAFDefaults
  • CSF_GraphicShr
  • CSF_IGESDefaults
  • CSF_STEPDefaults

The Config set

La fiecare pornire, FreeCAD examinează parametrii din jur și cei ai liniei de comandă. Se construiește un configuration set care conține esența informațiilor de execuție( runtime). Aceste informații se folosesc mai târziu pentru a determina unde să se salveze datele utilizatorului sau fișierele de jurnal. De asemenea, este foarte important pentru analizele post-mortem. Prin urmare, acesta este salvat în fișierul jurnal.

Informații legate de utilizator

User config entries
Config var name Synopsis Example M$ Example Posix (Linux)
UserAppData Path where FreeCAD stores User Related application data. C:\Documents and Settings\username\Application Data\FreeCAD /home/username/.FreeCAD
UserParameter File where FreeCAD stores User Related application data. C:\Documents and Settings\username\Application Data\FreeCAD\user.cfg /home/username/.FreeCAD/user.cfg
SystemParameter File where FreeCAD stores Application Related data. C:\Documents and Settings\username\Application Data\FreeCAD\system.cfg /home/username/.FreeCAD/system.cfg
UserHomePath Home path of the current user C:\Documents and Settings\username\My Documents /home/username

Note: For Linux distributions, an additional configuration file that relates to Qt may exist at path /home/username/.config/FreeCAD/FreeCAD.conf.

Argumentele liniei de Command

User config entries
Config var name Synopsis Example
LoggingFile 1 if the logging is switched on 1
LoggingFileName File name where the log is placed C:\Documents and Settings\username\Application Data\FreeCAD\FreeCAD.log
RunMode This indicates how the main loop will work. "Script" means that the given script is called and then exit. "Cmd" runs the command line interpreter. "Internal" runs an internal script. "Gui" enters the Gui event loop. "Module" loads a given python module. "Cmd"
FileName Meaning depends on the RunMode
ScriptFileName Meaning depends on the RunMode
Verbose Verbosity level of FreeCAD "" or "strict"
OpenFileCount Holds the number of files opened through command line arguments "12"
AdditionalModulePaths Holds the additional Module paths given in the cmd line "extraModules/"

Sisteme conexe

User config entries
Config var name Synopsis Example M$ Example Posix (Linux)
AppHomePath Path where FreeCAD is installed c:/Progam Files/FreeCAD_0.7 /user/local/FreeCAD_0.7
PythonSearchPath Holds a list of paths which python search modules. This is at startup can change during execution

Construirea de informații conexe

Tabelul de mai jos prezintă informațiile disponibile despre versiunea disponibilă Build. Cea mai mare parte a lor provine din depozitul Subversion. Acest truc este necesar pentru a reconstrui exact o versiune!

User config entries
Config var name Synopsis Example
BuildVersionMajor Major Version number of the Build. Defined in src/Build/Version.h.in 0
BuildVersionMinor Minor Version number of the Build. Defined in src/Build/Version.h.in 7
BuildRevision SVN Repository Revision number of the src in the Build. Generated by SVN 356
BuildRevisionRange Range of different changes 123-356
BuildRepositoryURL Repository URL https://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk/src
BuildRevisionDate Date of the above Revision 2007/02/03 22:21:18
BuildScrClean Indicates if the source was changed after checkout Src modified
BuildScrMixed Src not mixed

Branding related

Aceste intrări de configurare sunt legate de mecanismul de branding al FreeCAD. Consultați Branding pentru mai multe informații.

User config entries
Config var name Synopsis Example
ExeName Name of the build Executable file. Can differ from FreeCAD if a different main.cpp is used. FreeCAD.exe
ExeVersion Over all Version shows up at start time V0.7
AppIcon Icon which is used for the Executable, shows in Application MainWindow. "FCIcon"
ConsoleBanner Banner which is prompted in console mode
SplashPicture Name of the Icon used for the Splash Screen "FreeCADSplasher"
SplashAlignment Alignment of the Text in the Splash dialog "Bottom" or "Left"
SplashTextColor Color of the splasher Text "#000000"
StartWorkbench Name of the Workbench which get started automatically after Startup "Part design"
HiddenDockWindow List of dockwindows (separated by a semicolon) which will be disabled "Property editor"

Querying the configuration

From FreeCAD's Python console

Entries of the configuration set can be queried with the config var name (see tables above) from the Python console. For example:

 >>> FreeCAD.ConfigGet("ExeVersion")
 '0.19'

If the name is not found, an empty string is returned.

From command line

Use the --get-config <config-var-name> option to query a single name. Not all names are supported. For example:

 FreeCAD --get-config ExeVersion

Use the --dump-config option to get a list of names and their values. Not all names are supported.

From FreeCAD console

Start FreeCAD in console mode with --console and query with Python code. For example:

 $ FreeCAD --console
 [FreeCAD Console mode <Use Ctrl-D (i.e. EOF) to exit.>]
 >>> FreeCAD.ConfigGet("ExeVersion")
 '0.19'
 >>> exit()

For Linux (bash shell) you can modify the following command line to suit your needs:

 $ FreeCAD --console <<EOF
 print( "FREECAD_USER_HOME: " + ( "not set" if ( os.environ.get('FREECAD_USER_HOME') is None ) else os.environ.get('FREECAD_USER_HOME') ) )
 print( "UserHomePath: " + FreeCAD.ConfigGet("UserHomePath") )
 exit()
 EOF

Starting FreeCAD from the desktop

Linux: Creating an additional start option

The following assumes that your desktop is configured such that you can launch FreeCAD from it. Depending on your Linux distribution and desktop environment, you may have to adapt the following steps:

  1. Copy the freedesktop entry file for FreeCAD from /usr/share/applications/freecad.desktop to ~/.local/share/applications.
  2. Change the name from freecad.desktop to something else (e.g. MyFreeCADConfig.desktop).
  3. Open the file with a text editor and change how FreeCAD is invoked by modifying the line starting with Exec.
  4. As a result, an additional entry in your start menu/application launcher is available. This way, you can have multiple FreeCAD entries with various launch options.

Starting FreeCAD from a portable USB medium

Windows

Put the FreeCAD executable, FreeCAD.exe, on the USB medium. Create a batch file, FreeCAD.bat, and put it into the same directory as FreeCAD.exe. Inside the batch file write:

set CURRENTDIR=%cd%
set FREECAD_USER_HOME=%CURRENTDIR%
start FreeCAD.exe -u FreeCAD/user.cfg -s FreeCAD/system.cfg --write-log

Or with FREECAD_USER_DATA (see):

set CURRENTDIR="%cd%"
set FREECAD_USER_DATA=%CURRENTDIR%/..
start FreeCAD.exe -u %FREECAD_USER_DATA%/user.cfg -s %FREECAD_USER_DATA%/system.cfg

With the batch in the root of the USB medium:

set CURRENTDIR=%cd%
set FREECAD_USER_DATA=%CURRENTDIR%FreeCAD\
start %cd%FreeCAD\bin\FreeCAD.exe -u %FREECAD_USER_DATA%user.cfg -s %FREECAD_USER_DATA%system.cfg

Now double-click the batch file to start FreeCAD. (see)


Third Party Tools
FreeCAD Build Tool


Instrumentul de construcție FreeCAD build tool sau fcbt este un script python localizat la:

trunc/src/Tools/fcbt.py

Acesta poate fi folosit pentru a simplifica unele sarcini frecvente în construirea, distribuirea și extinderea FreeCAD.

Utilizare

Cu Python corect instalat, fcbt can poate fi invocat prin comanda

python fbct.py

Afișează un meniu, unde puteți selecta următoarele:

FreeCAD Build Tool
 Usage:
    fcbt <command name> [command parameter]
 possible commands are:
  - DistSrc         (DS)   Build a source Distr. of the current source tree
  - DistBin         (DB)   Build a binary Distr. of the current source tree
  - DistSetup       (DI)   Build a Setup Distr. of the current source tree
  - DistSetup       (DUI)  Build a User Setup Distr. of the current source tree
  - DistAll         (DA)   Run all three above modules
  - NextBuildNumber (NBN)  Increase the Build Number of this Version
  - CreateModule    (CM)   Insert a new FreeCAD Module (Workbench) in the module directory
 
 For help on the modules type:
   fcbt <command name> ?

La promptul de introducere introduceți comanda abreviată pe care doriți să o apelați. De exemplu, tastați "CM" pentru crearea unui modul creating a workbench.

DistSrc

Comanda "DS" creează sursa de distribuire a arborelui sursă curent

DistBin

Comanda "DB" creează o distribuție binară a arborelui sursă curent.

DistSetup

Comanda "DI" creează o distribuție de instalare a arborelui sursă curent.

DistSetup

Comanda "DUI" creează o distribuție de configurare utilizator a arborelui sursă curent.

DistAll

Comanda "DA" execută secvența "DS", "DB" and "DI" .

NextBuildNumber

Comanda "NBN" incrementează numărul de compilări pentru a crea noua veresiiune FreeCAD.



Introduction

This page will show you how to add a new workbench to the FreeCAD interface. Workbenches are containers for FreeCAD commands. They can be coded in Python, in C++, or in a mix of both, which has the advantage to ally the speed of C++ to the flexibility of Python. In all cases, though, your workbench will be launched by a set of two Python files. They can be "internal" workbenches, included with FreeCAD's distribution, or "external" workbenches, distributed via the Addon Manager or installed manually by downloading from some online repository. Internal workbenches may be coded in either C++, Python, or a combination of the two, whereas external workbenches must be Python-only.

The workbench structure

You need a folder, with any name you like, placed in the user Mod directory, with an Init.py file, and, optionally an InitGui.py file. The Init.py file is executed when FreeCAD starts, and the InitGui.py file is executed immediately after, but only when FreeCAD starts in GUI mode. That's all it needs for FreeCAD to find your workbench at startup and add it to its interface.

The user Mod directory is a sub-directory of the user application data directory (you can find the latter by typing App.getUserAppDataDir() in the Python console):

  • On Linux it is usually /home/<username>/.local/share/FreeCAD/Mod/ (version 0.20 and above) or /home/<username>/.FreeCAD/Mod/ (version 0.19 and below).
  • On Windows it is %APPDATA%\FreeCAD\Mod\, which is usually C:\Users\<username>\Appdata\Roaming\FreeCAD\Mod\.
  • On macOS it is usually /Users/<username>/Library/Application Support/FreeCAD/Mod/.

The Mod directory should look like this:

/Mod/
 +-- MyWorkbench/
     +-- Init.py
     +-- InitGui.py

Inside those files you can do whatever you want. Usually they are used like this:

  • In the Init.py file you just add a couple of things used even when FreeCAD works in console mode, for example the file importers and exporters
  • In the InitGui.py file you usually define a workbench, which contains a name, an icon, and a series of FreeCAD commands (see below). That python file also defines functions that are executed when FreeCAD loads (you try to do as little as possible there, so you don't slow down the startup), another that gets executed when the workbench is activated (that's where you'll do most of the work), and a third one when the workbench is deactivated (so you can remove things if needed).

The structure and file content for a workbench described here is the classic way of creating a new workbench. One can use a slight variation in the structure of files when making a new Python workbench, that alternative way is best described as a "namespaced workbench", opening up the possibility to use pip to install the workbench. Both structures work, so it is more a question of preference when creating a new workbench. The style and structure for workbenches presented here are available in the global namespace of FreeCAD, whereas for the alternative style and structure the workbench resides in a dedicated namespace. For further readings on the topic see Related.

C++ workbench structure

If you are going to code your workbench in python, you don't need to take special care, and can simply place your other python files together with your Init.py and InitGui.py files. When working with C++, however, you should take greater care, and start with respecting one fundamental rule of FreeCAD: The separation of your workbench between an App part (that can run in console mode, without any GUI element), and a Gui part, which will only be loaded when FreeCAD runs with its full GUI environment. So when developing a C++ workbench, you will actually most likely create two modules, an App and a Gui. These two modules must of course be callable from python. Any FreeCAD module (App or Gui) consists, at the very least, of a module init file. This is a typical AppMyModuleGui.cpp file:

extern "C" {
    void MyModuleGuiExport initMyModuleGui()  
    {
         if (!Gui::Application::Instance) {
            PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
            return;
        }
        try {
            // import other modules this one depends on
            Base::Interpreter().runString("import PartGui");
            // run some python code in the console
            Base::Interpreter().runString("print('welcome to my module!')");
        }
        catch(const Base::Exception& e) {
            PyErr_SetString(PyExc_ImportError, e.what());
            return;
        }
        (void) Py_InitModule("MyModuleGui", MyModuleGui_Import_methods);   /* mod name, table ptr */
        Base::Console().Log("Loading GUI of MyModule... done\n");
    
        // initializes the FreeCAD commands (in another cpp file)
        CreateMyModuleCommands();
    
        // initializes workbench and object definitions
        MyModuleGui::Workbench::init();
        MyModuleGui::ViewProviderSomeCustomObject::init();
    
         // add resources and reloads the translators
        loadMyModuleResource();
    }
}

The Init.py file

"""FreeCAD init script of XXX module"""

# ***************************************************************************
# *   Copyright (c) 2015 John Doe john@doe.com                              *   
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENSE text file.                                 *
# *                                                                         *
# *   FreeCAD is distributed in the hope that it will be useful,            *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Lesser General Public License for more details.                   *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with FreeCAD; if not, write to the Free Software        *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************/

FreeCAD.addImportType("My own format (*.own)", "importOwn")
FreeCAD.addExportType("My own format (*.own)", "exportOwn")
print("I am executing some stuff here when FreeCAD starts!")

You can choose any license you like for your workbench, but be aware that if you wish to see your workbench integrated into and distributed with the FreeCAD source code at some point, it needs to be LGPL2+ like the example above. See License.

The FreeCAD.addImportType() and addEXportType() functions allow you to give the name and extension of a file type, and a Python module responsible for its import. In the example above, an importOwn.py module will handle .own files. See Code snippets for more examples.

Python workbenches

This is the InitGui.py file:

class MyWorkbench (Workbench):

    MenuText = "My Workbench"
    ToolTip = "A description of my workbench"
    Icon = """paste here the contents of a 16x16 xpm icon"""

    def Initialize(self):
        """This function is executed when the workbench is first activated.
        It is executed once in a FreeCAD session followed by the Activated function.
        """
        import MyModuleA, MyModuleB # import here all the needed files that create your FreeCAD commands
        self.list = ["MyCommand1", "MyCommand2"] # a list of command names created in the line above
        self.appendToolbar("My Commands", self.list) # creates a new toolbar with your commands
        self.appendMenu("My New Menu", self.list) # creates a new menu
        self.appendMenu(["An existing Menu", "My submenu"], self.list) # appends a submenu to an existing menu

    def Activated(self):
        """This function is executed whenever the workbench is activated"""
        return

    def Deactivated(self):
        """This function is executed whenever the workbench is deactivated"""
        return

    def ContextMenu(self, recipient):
        """This function is executed whenever the user right-clicks on screen"""
        # "recipient" will be either "view" or "tree"
        self.appendContextMenu("My commands", self.list) # add commands to the context menu

    def GetClassName(self): 
        # This function is mandatory if this is a full Python workbench
        # This is not a template, the returned string should be exactly "Gui::PythonWorkbench"
        return "Gui::PythonWorkbench"
       
Gui.addWorkbench(MyWorkbench())

Other than that, you can do anything you want: you could put your whole workbench code inside the InitGui.py if you want, but it is usually more convenient to place the different functions of your workbench in separate files. So those files are smaller and easier to read. Then you import those files into your InitGui.py file. You can organize those files the way you want, a good example is one for each FreeCAD command you add.

Preferences

You can add a Preferences page for your Python workbench. The Preferences pages look for a preference icon with a specific name in the Qt Resource system. If your icon isn't in the resource system or doesn't have the correct name, your icon won't appear on the Preferences page.

Adding your workbench icon:

  • the preferences icon needs to be named "preferences-" + "modulename" + ".svg" (all lowercase)
  • make a qrc file containing all icon names
  • in the main *.py directory, run pyside-rcc -o myResources.py myqrc.qrc
  • in InitGui.py, add import myResource(.py)
  • update your repository(git) with myResources.py and myqrc.qrc

You'll need to redo the steps if you add/change icons.

@kbwbe has created a nice script to compile resources for the A2Plus workbench. See below.

Adding your preference page(s):

  • You need to compile the Qt designer plugin that allows you to add preference settings with Qt Designer
  • Create a blank widget in Qt Designer (no buttons or anything)
  • Design your preference page, any setting that must be saved (preferences) must be one of the Gui::Pref* widgets that were added by the plugin)
  • In any of those, make sure you fill the PrefName (the name of your preference value) and PrefPath (ex: Mod/MyWorkbenchName), which will save your value under BaseApp/Preferences/Mod/MyWorkbenchName
  • Save the ui file in your workbench, make sure it's handled by cmake
  • In your workbench, for ex. inside the InitGui file, inside the Initialize method (but any other place works too), add: FreeCADGui.addPreferencePage("/path/to/myUiFile.ui","MyGroup"), "MyGroup" being one of the preferences groups on the left. FreeCAD will automatically look for a "preferences-mygroup.svg" file in its known locations (which you can extend with FreeCADGui.addIconPath())
  • Make sure the addPreferencePage() method is called only once, otherwise your pref page will be added several times

Distribution

To distribute your Python workbench, you may either simply host the files in some location and instruct your users to download them and place them in their Mod directory manually, or you may host them in an online git repository (GitHub, GitLab, Framagit, and Debian Salsa are currently supported locations) and configure them for the Addon Manager to install. Instructions for inclusion on FreeCAD's official Addons list can be found on the FreeCAD Addons GitHub repository. To use the Addon Manager, a package.xml metadata file should be included, which instructs the Addon Manager how to find your workbench's icon, and allows display of a description, version number, etc. It can also be used to specify other workbenches or Python packages that your Workbench either depends on, is blocked by, or is intended to replace.

For a quick guide on how to create a basic package.xml file and add a workbench to the Addon Manager see: Add Workbench to Addon Manager.

Optionally, you can include a separate metadata file describing your Python dependencies. This may be either a file called metadata.txt describing your workbench's external dependencies (on either other Addons, Workbenches, or Python modules), or a requirements.txt describing your Python dependencies. Note that if using a requirements.txt file, only the names of the specified packages are used for dependency resolution: pip command options, include options and version information are not supported by the Addon Manager. Users may manually run the requirements file using pip if those features are required.

The format of the metadata.txt file is plain text, with three optional lines:

workbenches=
pylibs=
optionalpylibs=

Each line should consist of a comma-separated list of items your Workbench depends on. Workbenches may be either an internal FreeCAD Workbench, e.g. "FEM", or an external Addon, for example "Curves". The required and optional Python libraries should be specified with their canonical Python names, such as you would use with pip install. For example:

workbenches=FEM,Curves
pylibs=ezdxf
optionalpylibs=metadata,git

You may also include a script that is run when your package is uninstalled. This is a file called "uninstall.py" located at the top level of your Addon. It is executed when a user uninstalls your Addon using the Addon Manager. Use it to clean up anything your Addon may have done to the users system that should not persist when the Addon is gone (e.g. removing cache files, etc.).

To ensure that your addon is being read correctly by the Addon Manager, you can enable a "developer mode" in which the Addon Manager examines all available addons and ensures their metadata contains the required elements. To enable this mode select: Edit → Preferences... → Addon Manager → Addon manager options → Addon developer mode, see Preferences Editor.

C++ workbenches

If you are going to code your workbench in C++, you will probably want to code the workbench definition itself in C++ too (although it is not necessary: you could also code only the tools in C++, and leave the workbench definition in Python). In that case, the InitGui.py file becomes very simple: It might contain just one line:

import MyModuleGui

where MyModule is your complete C++ workbench, including the commands and workbench definition.

Coding C++ workbenches works in a pretty similar way. This is a typical Workbench.cpp file to include in the Gui part of your module:

namespace MyModuleGui {
    class MyModuleGuiExport Workbench : public Gui::StdWorkbench
    {
        TYPESYSTEM_HEADER();

    public:
        Workbench();
        virtual ~Workbench();

        virtual void activated();
        virtual void deactivated();

    protected:
        Gui::ToolBarItem* setupToolBars() const;
        Gui::MenuItem*    setupMenuBar() const;
    };
}

Preferences

You can add a Preferences page for C++ workbenches too. The steps are similar to those for Python.

Distribution

There are two options to distribute a C++ workbench, you can either host precompiled versions for the different operating systems yourself, or you can request for your code to be merged into the FreeCAD source code. As mentioned above this requires a LGPL2+ license, and you must first present your workbench to the community in the FreeCAD forum for review.

FreeCAD commands

FreeCAD commands are the basic building block of the FreeCAD interface. They can appear as a button on toolbars, and as a menu entry in menus. But it is the same command. A command is a simple Python class, that must contain a couple of predefined attributes and functions, that define the name of the command, its icon, and what to do when the command is activated.

Python command definition

class My_Command_Class():
    """My new command"""

    def GetResources(self):
        return {"Pixmap"  : "My_Command_Icon", # the name of a svg file available in the resources
                "Accel"   : "Shift+S", # a default shortcut (optional)
                "MenuText": "My New Command",
                "ToolTip" : "What my new command does"}

    def Activated(self):
        """Do something here"""
        return

    def IsActive(self):
        """Here you can define if the command must be active or not (greyed) if certain conditions
        are met or not. This function is optional."""
        return True

FreeCADGui.addCommand("My_Command", My_Command_Class())

C++ command definition

Similarly, you can code your commands in C++, typically in a Commands.cpp file in your Gui module. This is a typical Commands.cpp file:

DEF_STD_CMD_A(CmdMyCommand);

CmdMyCommand::CmdMyCommand()
  :Command("My_Command")
{
  sAppModule    = "MyModule";
  sGroup        = QT_TR_NOOP("MyModule");
  sMenuText     = QT_TR_NOOP("Runs my command...");
  sToolTipText  = QT_TR_NOOP("Describes what my command does");
  sWhatsThis    = QT_TR_NOOP("Describes what my command does");
  sStatusTip    = QT_TR_NOOP("Describes what my command does");
  sPixmap       = "some_svg_icon_from_my_resource";
}

void CmdMyCommand::activated(int iMsg)
{
    openCommand("My Command");
    doCommand(Doc,"print('Hello, world!')");
    commitCommand();
    updateActive();
}

bool CmdMyCommand::isActive(void)
{
  if( getActiveGuiDocument() )
    return true;
  else
    return false;
}

void CreateMyModuleCommands(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
    rcCmdMgr.addCommand(new CmdMyCommand());
}

"Compiling" your resource file

compileA2pResources.py from the A2Plus workbench:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2019 kbwbe                                              *
#*                                                                         *
#*   Portions of code based on hamish's assembly 2                         *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENSE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

# This script compiles the A2plus icons for py2 and py3
# For Linux only
# Start this file in A2plus main directory
# Make sure pyside-rcc is installed

import os, glob

qrc_filename = 'temp.qrc'
if os.path.exists(qrc_filename):
    os.remove(qrc_filename)

qrc = '''<RCC>
\t<qresource prefix="/">'''
for fn in glob.glob('./icons/*.svg'):
    qrc = qrc + '\n\t\t<file>%s</file>' % fn
qrc = qrc + '''\n\t</qresource>
</RCC>'''

print(qrc)

f = open(qrc_filename,'w')
f.write(qrc)
f.close()

os.system(
    'pyside-rcc -o a2p_Resources2.py {}'.format(qrc_filename))
os.system(
    'pyside-rcc -py3 -o a2p_Resources3.py {}'.format(qrc_filename))

os.remove(qrc_filename)

Related



Testează mai întâi

Înainte de a trece prin durerea de a depana utilizați Test framework pentru a verifica dacă testele standard funcționează corect. Dacă acestea nu se execută complet, este posibil să fie o instalare defectuoasă.

Before you go through the pain of debugging use the Test framework to check if the standard tests work properly. If they do not run complete there is possibly a broken installation.

Linie de Commandă

Depanarea debugging în FreeCAD este susținută de câteva mecanisme interne. Versiunea liniei de comandă a FreeCAD oferă câteva opțiuni pentru suportul de depanare.

The debugging of FreeCAD is supported by a few internal mechanisms. The command line version of FreeCAD provides some options for debugging support.

Acestea sunt opțiunile recunoscute curent în FreeCAD 0.15:

Generic options:

 -v [ --version ]      Prints version string
 -h [ --help ]         Prints help message
 -c [ --console ]      Starts in console mode
 --response-file arg   Can be specified with '@name', too

Configuration:

 -l [ --write-log ]       Writes a log file to:
                          $HOME/.FreeCAD/FreeCAD.log
 --log-file arg           Unlike to --write-log this allows to log to an 
                          arbitrary file
 -u [ --user-cfg ] arg    User config file to load/save user settings
 -s [ --system-cfg ] arg  System config file to load/save system settings
 -t [ --run-test ] arg    Test level
 -M [ --module-path ] arg Additional module paths
 -P [ --python-path ] arg Additional python paths

Generarea unei Backtrace

Dacă rulați o versiune experimentală de FreeCAD care este încă în curs de dezvoltare, aceasta poate "îngheța". Vă puteți ajuta să rezolvați astfel de probleme furnizând dezvoltatorilor o "backtrace". Pentru a face acest lucru, trebuie să executați o "Debug build" a software-ului. "Debug build" este un parametru care este setat în timpul compilării, deci va trebui fie să compilați FreeCAD dvs înșivă, fie să obțineți o versiune "debug" precompilată.

If you are running a version of FreeCAD from the bleeding edge of the development curve, it may "crash". You can help solve such problems by providing the developers with a "backtrace". To do this, you need to be running a "debug build" of the software. "Debug build" is a parameter that is set at compile time, so you'll either need to compile FreeCAD yourself, or obtain a pre-compiled "debug" version.

For Linux

Linux Debugging →

Prerequisites:

  • varianta software de package gdb instalat
  • o depanare a variantei compilate a FreeCAD (în acest moment disponibilă prin building from source)
  • un model FreeCAD care a cauzat crash-ul

Pași: Introduceți următoarelor în fereastra terminalului dvs:

Find FreeCAD binary on your system:

$ whereis freecad
freecad: /usr/local/freecad <--- for example

$ cd /usr/local/freecad/bin
$ gdb FreeCAD

GNUdebugger will output some initializing information. The (gdb) shows GNUDebugger is running in the terminal, now input:

(gdb) handle SIG33 noprint nostop
(gdb) run

FreeCAD va porni. Efectuați pașii care determină ca FreeCAD să se prăbușească sau să înghețe, apoi introduceți în fereastra terminalului:

(gdb) bt

Aceasta va genera o listă lungă a exact ceea ce a făcut programul atunci când sa prăbușit sau a înghețat. Includeți acest lucru cu raportul problemei dvs.

(gdb) bt full

Print the values of the local variables also. This can be combined with a number to limit the number of frames shown.

For MacOSX

MacOSX Debugging →

Prerequisites:

  • software package lldb installed
  • a debug build of FreeCAD
  • a FreeCAD model that causes a crash

Steps: Enter the following in your terminal window:

$ cd FreeCAD/bin
$ lldb FreeCAD

LLDB will output some initializing information. The (lldb) shows the debugger is running in the terminal, now input:

(lldb) run

FreeCAD va porni. Efectuați pașii care determină ca FreeCAD să se prăbușească sau să înghețe, apoi introduceți în fereastra terminalului:

(lldb) bt

Aceasta va genera o listă lungă a exact ceea ce a făcut programul atunci când sa prăbușit sau a înghețat. Includeți acest lucru cu raportul problemei dvs.

List Libraries Loaded by FreeCAD

(Applicable to Linux and macOS)

Sometimes it's helpful to understand what libraries FreeCAD is loading, specifically if there are multiple libraries being loaded of the same name but different versions (version collision). In order to see which libraries are loaded by FreeCAD when it crashes you should open a terminal and run it in the debugger. In a second terminal window, find out the process id of FreeCAD:

ps -A | grep FreeCAD

Use the returned id and pass it to lsof:

lsof -p process_id

This prints a long list of loaded resources. So for example, if trying to ascertain if more than one Coin3d library versions is loaded, scroll through the list or search directly for Coin in the output:

lsof -p process_id | grep Coin

Python Debugging

Pentru o abordare mai modernă a depanării Python, cel puțin în Windows, a se vedea asta

For a more modern approach to debugging Python, see these posts:

winpdb

winpdb Debugging →

Here is an example of using Winpdb inside FreeCAD:

Avem nevoie de depanatorul Python: Winpdb . Dacă nu aveți instalat, instalați-l sub Ubuntu / Debian cu:

sudo apt-get install winpdb

Acum permiteți configurarea programului de depanare.

  1. Start Winpdb.
  2. Set the debugger password to "test": Go to menu File->Password" and set the password.

Acum vom rula pas cu pas un script de testare Python în FreeCAD.

  1. Rulați winpdb și definiți password (e.g. test)
  2. Creați un fișier Python cu acest conținut
import rpdb2
rpdb2.start_embedded_debugger("test")
import FreeCAD
import Part
import Draft
print "hello"
print "hello"
import Draft
points=[FreeCAD.Vector(-3.0,-1.0,0.0),FreeCAD.Vector(-2.0,0.0,0.0)]
Draft.makeWire(points,closed=False,face=False,support=None)
  1. Dați Start la FreeCAD și încărcați fișierul de mai sus în FreeCAD
  2. Apăsați F6 ptru al-l executa
  3. Acum FreeCAD se va bloca (nu va răspunde) deoarece debuggerul Python este în așteptare
  4. Comutați pe Windpdb GUI și click on "Attach". După câteva secunde un articol "<Input>" apare acolo unde ați făcut dublu clic
  5. Acum Scriptul aflat în execuție curentă apare în Winpdb.
  6. Definiți o pauză la ultima linie și apăsați F5
  7. Acum apăsați F7 pentru a intra în codul Python al Draft.makeWire

Visual Studio Code (VS Code)

VS Code Debugging →

Prerequisites:

  • The ptvsd package needs to be installed in a Python 3 outside of FreeCAD, then the module must be copied to FreeCAD's Python library folder.
# In a cmd window that has a path to you local Python 3:
pip install ptvsd
# Then if your Python is installed in C:\Users\<userid>\AppData\Local\Programs\Python\Python37
# and your FreeCAD is installed in C:\freecad\bin
xcopy "C:\Users\<userid>\AppData\Local\Programs\Python\Python37\Lib\site-packages\ptvsd" "C:\freecad\bin\Lib\site-packages\ptvsd"

pypi page

Visual Studio Code documentation for remote debugging

Steps:

  • Add following code at the beginning of your script
import ptvsd
print("Waiting for debugger attach")
# 5678 is the default attach port in the VS Code debug configurations
ptvsd.enable_attach(address=('localhost', 5678), redirect_output=True)
ptvsd.wait_for_attach()
  • Add a debug configuration in Visual Studio Code Debug → Add Configurations….
  • The config should look like this:
    "configurations": [
        {
            "name": "Python: Attacher",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost",
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "."
                }
            ]
        },
  • In VS Code add a breakpoint anywhere you want.
  • Launch the script in FreeCAD. FreeCAD freeze waiting for attachment.
  • In VS Code start debugging using created configuration. You should see variables in debugger area.
  • When setting breakpoints, VS Code will complain about not finding the .py file opened in the VS Code editor.
    • Change "remoteRoot": "." to "remoteRoot": "<directory of file>"
      • For example, if the Python file resides in /home/FC_myscripts/myscript.py
      • Change to: "remoteRoot": "/home/FC_myscripts"
    • If you're just debugging FreeCAD macros from the FreeCAD macro folder, and that folder is "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro", then use:
      • "localRoot": "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro",
      • "remoteRoot": "C:/Users/<userid>/AppData/Roaming/FreeCAD/Macro"
  • If your macro can't find ptvsd despite having installed it somewhere precede 'import ptvsd' with
from sys import path
sys.path.append('/path/to/site-packages')

Where the path is to the directory where ptvsd was installed.

  • On the left bottom edge of VSCode you can choose the Python executable - it's best to make this the version packaged with FreeCAD.

In the Mac package it is /Applications/FreeCAD.App/Contents/Resources/bin/python.

You can locate it on your system by typing

import sys
print(sys.executable)

into FreeCAD's Python console.

With LiClipse and AppImage

LiClipse Debugging →

  • Extract AppImage.
> ./your location/FreeCAD_xxx.AppImage --appimage-extract
> cd squashfs-root/
  • The sqashfs-root location is where the debugger later on is hooked up to.
  • Make sure you can start a FreeCAD session from within the squashfs-root location.
squashfs-root> ./usr/bin/freecadcmd
  • Should start up a FreeCAD commandline session.
  • Install LiClipse.
    • Comes ready with pydev and has installers for all platforms.
    • For linux it is just to extract (to any location) and run.
  • Configure liclipse for debugging.
    • Right-click pydev icon (upper right corner) and choose customize.
      • Activate "PyDev Debug" (through checkbox, or it might be needed to go to tab "Action Set Availability" and activate there first).
      • In the pydev menu you can now choose "start debug server".
    • Use menu window/open perspective/other > debug.
      • Right-click debug icon (upper right corner) and choose customize.
      • Checking "Debug" brings the debugging navigation tools to the toolbar.
    • Open preferences through menu window/preferences.
      • In PyDev/Interpreters add "new Interpreter by browsing".
      • The added interpreter should be: your loc/squashfs-root/usr/bin/python.
      • If you are only using this for fc, you can add AddOn workbench folders as well, or do that in a pydev-project later on.
  • Find path to pydevd.py in your liclipse installation.
    • Something along the lines of: your location/liclipse/plugins/org.python.pydev.xx/pysrc.
  • Create a regular pydev-project in liclipse.
    • Import external sources, for example a macro that you want to debug, or an external workbench.
    • In that macro (or workbench .py file) add the code lines:
import sys; sys.path.append("path ending with /pysrc")
import pydevd; pydevd.settrace()
  • This is where the execution will halt when the macro is run.
  • Start the liclipse debug server (menu pydev).
  • Start FreeCAD.
squashfs-root> ./usr/bin/freecad
  • Run the macro (or any other file with a pydevd.settrace() trigger) from within freecad, as you would normally do.
  • Happy debugging.
  • The use of LiClipse for remote debugging, and the steps described here related to liclipse, should work on any platform. The parts related to AppImage is for linux only.

Pyzo

See the main article about Pyzo.

Debugging OpenCasCade

For developers needing to dig deeper in to the OpenCasCade kernel, user @abdullah has created a thread orientation discussing how to do so.



Test workbench icon

Introducere

Aceasta este lista de aplicații de testare de la 0,15 Git 4207:

FreeCAD vine cu un cadru vast de testare. Bazele de testare se bazează pe un set de scripturi. Îngrijirea Python se află în modulul de testare.

You can run the tests from the command line, by using the -t or --run-test options.

Run all tests:

freecad --run-test 0

Run only some the specified unit test, for example:

freecad -t TestDraft

If a test does not need the GUI, it can also be executed in console mode by setting the -c or --console option in addition. This usually results in much faster startup time as the GUI is not loaded. For example:

freecad -c -t TestPartDesignApp

Test menu

Each top level directory in FreeCAD should have a file with the tests that can be run for that particular workbench or module. The file usually starts with the word Test.

To run a test from within FreeCAD, switch to the Test Workbench, then Test commands → TestToolsGui → Self test → Select test name, then enter the name of the Python file with the tests; for example, for the Draft Workbench, this would be TestDraft, then press Start.

Test functions

This is the list of test apps as of 0.15 git 4207:

TestAPP.All

Adăugați funcția de testare

Add test function

BaseTests

Adăugați funcția de testare

Add test function

UnitTests

Adăugați funcția de testare

Add test function

Document

Adăugați funcția de testare

Add test function

UnicodeTests

Adăugați funcția de testare

Add test function

MeshTestsApp

Adăugați funcția de testare

Add test function

TestDraft

Add test function

TestSketcherApp

Adăugați funcția de testare

Add test function

TestPartApp

Adăugați funcția de testare

Add test function

TestPartDesignApp

Adăugați funcția de testare

Add test function

TestCAMApp

Path workbench test cases:

  • depthTestCases:
  • PathTestUtils:
  • TestDressupDogbone: Test functionality of Dogbone dressup.
  • TestHoldingTags: Test functionality of Holding Tags dressup.
  • TestPathAdaptive: Test selection capability of Adaptive operation.
  • TestPathCore: Test core functionality of Path workbench.
  • TestPathDeburr: Test general functionality of Deburr operation.
  • TestPathGeom: Test various functions available in the PathGeom module.
  • TestPathHelix: Test general functionality of Helix operation.
  • TestPathLog: Test various functions available in the PathLog debugging and feedback module.
  • TestPathOpTools:
  • TestPathPreferences: Test various functions available in the PathPreferences module.
  • TestPathPropertyBag:
  • TestPathSetupSheet:
  • TestPathStock:
  • TestPathThreadMilling:
  • TestPathTool:
  • TestPathToolBit:
  • TestPathToolController:
  • TestPathTooltable:
  • TestPathUtil: Test various functions available in the PathUtil module.
  • TestPathVcarve: Test general functionality of Vcarve operation.
  • TestPathVoronoi:

Workbench

Adăugați funcția de testare

Add test function

Meniu

Adăugați funcția de testare

Add test function

Menu.MenuDeleteCases

Adăugați funcția de testare

Add test function

Menu.MenuCreateCases

Adăugați funcția de testare

Add test function

Scripting

See also: FreeCAD Scripting Basics.

Get a list of all top-level test modules

FreeCAD.__unit_test__

Note that the test modules returned here depend on whether a GUI available or not. I.e. when executed in console mode, various tests ending in "Gui" are missing.

Run specific tests

There are various ways of running tests using Python's unittest library. FreeCAD's test framework removes some of the boiler plate for the most common cases.

Run all tests defined in a Python module:

import Test, TestFemApp
Test.runTestsFromModule(TestFemApp)

Run all tests defined in a Python class:

import Test, femtest.app.test_solver_calculix
Test.runTestsFromClass(femtest.app.test_solver_calculix.TestSolverCalculix)

Example 1

Within the Python Console of FreeCAD, the following code format may be used to run built-in tests. Replace the red "TestFem" text in the code below with the desired module test name.

  • For example, use "TestPathApp" to run all unit tests for the Path workbench unit test framework.
  • Submodules are available using dot notation, like "TestPathApp.TestPathAdaptive" to only run the Adaptive unit tests within the greater Path workbench test framework.
  • Multiple test modules or submodules may be combined by adding another `suite.addTest(...)` method call just like the one in the code below, but with a different module or submodule reference.
  • Output for the code below will be in the Report View panel within the FreeCAD GUI.
  • Code source is copied from post by FreeCAD forum user, sgrogan, in the unit tests per python topic, with credit there given to forum user, wmayer.
import unittest
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName("TestFem"))
r = unittest.TextTestRunner()
r.run(suite)

Additional Resources

Forum Topics


Debugging
Continuous Integration


Overview

Acest articol descrie Branding al FreeCAD. Branding înseamnă să începeți propria aplicație pe baza FreeCAD. Acesta poate fi doar propriul dvs. executabil sau splash screen până la un program complet reconfigurat. Pe baza arhitecturii flexibile a FreeCAD, este ușor de utilizat ca bază pentru propriul program special.

Warning

Although FreeCAD is offered to you free of charge, and the FreeCAD community is happy to see other applications emerging, that are based on FreeCAD, we have on the other hand seen a lot of unfair use of the information contained on this page by people who simply rebranded FreeCAD into a closed-source application to make profit from it.

Although the LGPL license allows to use the FreeCAD source code in closed-source applications, it also gives strict rules to do so, and does not allow simply taking FreeCAD, renaming it and stripping it of its license.

Would you be interested in using FreeCAD in a closed-source application, be sure to check thoroughly the implications of the LGPL license, and, even better, contact any FreeCAD developer, administrator or moderator before doing so.

General

General

Majoritatea branding-ului se face în MainCmd.cpp sau MainGui.cpp . Aceste proiecte generează fișierele executabile ale FreeCAD. Pentru a crea propriul dvs. brand doar copiați proiectele Main sau MainGui și dați executabilului un nume propriu, de ex. FooApp.exe. Cele mai importante setări pentru un aspect nou pot fi făcute într-un singur loc în funcția principal (). Iată secțiunea de cod care controlează branding-ul:

int main( int argc, char ** argv )
{
    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FooApp";
    App::Application::Config()["ExeVersion"] = "0.7";

    // set the banner (for loging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "FooAppIcon";
    App::Application::Config()["SplashScreen"] = "FooAppSplasher";
    App::Application::Config()["StartWorkbench"] = "Part design";
    App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#000000"; // black

    // Inits the Application 
    App::Application::Config()["RunMode"] = "Gui";
    App::Application::init(argc,argv);

    Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);

    Gui::Application::initApplication();
    Gui::Application::runApplication();
    App::Application::destruct();

    return 0;
}

Prima intrare Config defineste numele programului. Acesta nu este numele executabilului, care poate fi modificat prin redenumire sau prin setările compilatorului, dar numele care este afișat în bara de activități din ferestrele sau în lista de programe din sistemele Unix.

Următoarele linii definesc intrările Config ale aplicației dvs. FooApp. O descriere a Config și a intrărilor pe care le găsiți în Start up and Configuration.

Images

Imagini

Resursele de imagine sunt compilate în FreeCAD folosind Qt's resource system. Prin urmare, trebuie să scrieți un fișier .qrc, un format de fișier bazat pe XML care afișează fișierele imagine pe disc, dar și orice alt tip de fișiere de resurse. Pentru a încărca resursele compilate din cadrul aplicației, trebuie să adăugați o linie

Q_INIT_RESOURCE(FooApp);

în funcția principal (). Alternativ, dacă aveți o imagine în format XPM, puteți să o includeți direct în main.cpp și să adăugați următoarea linie pentru a o înregistra:

Gui::BitmapFactory().addXPM("FooAppSplasher", ( const char** ) splash_screen);

Branding XML

Branding XML

În FreeCAD există și o metodă acceptată fără scrierea unei funcții principale personalizate (). Pentru această metodă trebuie să scrieți un nume de fișier numit branding.xml și să-l puneți în directorul de instalare al FreeCAD. Iată un exemplu cu toate etichetele acceptate:

<?xml version="1.0" encoding="utf-8"?>
<Branding>
    <Application>FooApp</Application>
    <WindowTitle>Foo App in title bar</WindowTitle>
    <BuildVersionMajor>1</BuildVersionMajor>
    <BuildVersionMinor>0</BuildVersionMinor>
    <BuildRevision>1234</BuildRevision>
    <BuildRevisionDate>2014/1/1</BuildRevisionDate>
    <CopyrightInfo>(c) My copyright</CopyrightInfo>
    <MaintainerUrl>Foo App URL</MaintainerUrl>
    <ProgramLogo>Path to logo (appears in bottom right corner)</ProgramLogo>
    <WindowIcon>Path to icon file</WindowIcon>
    <ProgramIcons>Path to program icons</ProgramIcons>
    <SplashScreen>splashscreen.png</SplashScreen>
    <SplashAlignment>Bottom|Left</SplashAlignment>
    <SplashTextColor>#ffffff</SplashTextColor>
    <SplashInfoColor>#c8c8c8</SplashInfoColor>
    <StartWorkbench>PartDesignWorkbench</StartWorkbench>
</Branding>

Toate etichetele enumerate sunt opționale.


Continuous Integration
Localisation


Branding
Extra python modules

Localizarea este, în general, procesul de furnizare a unui Software cu o interfață de utilizare în mai multe limbi. În FreeCAD puteți seta limba interfeței de utilizator sub Editare → Preferințe → Aplicație . FreeCAD utilizează Qt pentru a activa suportul pentru mai multe limbi. Pe sistemele Unix / Linux, FreeCAD utilizează implicit setările locale locale ale sistemului.

Localisation is in general the process of providing a Software with a multiple language user interface. In FreeCAD you can set the language of the user interface under Edit → Preferences → General. FreeCAD uses Qt to enable multiple language support. On Unix/Linux systems, FreeCAD uses the current locale settings of your system by default.

Ajutor în traducere FreeCAD

Unul dintre lucrurile foarte importante pe care utilizatorii le poate contribui la FreeCAD (dacă, de exemplu, nu au abilități de programare) este de a ajuta la traducerea diferitelor sale aspecte (cod sursă, wiki, site web, documentație etc.) într-o altă limbă. Iată modalitățile de a face acest lucru

Traduceți codul sursă al FreeCAD

 FreeCAD folosește un sistem de traducere on-line, bazat pe colaborare, numit Crowdin. Este software proprietate, dar gratuit pentru proiectele FOSS. Mai jos sunt instrucțiuni despre modul de utilizare:

FreeCAD utilizes a third party collaborative on-line translation system called Crowdin.

It is proprietary software but free to FOSS projects. Below are instructions on how to use it:

  • Du-te la FreeCAD translation project page on Crowdin
  • Conectați-vă prin crearea unui nou profil sau utilizând un cont terță parte ca adresa dvs. (GitHub, GitLab, GMail etc...)
  • Faceți clic pe limba pe care doriți să o traduceți;
  • Începeți traducerea făcând clic pe butonul Traducere de lângă unul dintre fișiere. De exemplu, FreeCAD.ts conține șiruri de text pentru GUI-ul principal al FreeCAD.
  • Puteți să votați pentru traducerile existente sau puteți crea propriile dvs. traduceri ..
Dacă participați în mod activ la traducerea FreeCAD și doriți să fiți informat înainte de lansarea următoarei versiuni, atunci când este gata să fie lansată, deci este timpul să vă revizuiți traducerea, vă rugăm să vă abonați la una dintre echipele de traducere Crowdin FreeCAD.

Note: Details on how to use crowdin can be found on the Crowdin Administration page.

Translating external workbenches

Visit Translating an external workbench.

FreeCAD Preferences for Translators

Starting with FreeCAD 0.20, the following variables can be manually added to the BaseApp/Preferences/General section of the user.cfg file to assist with the development of new translations:

AdditionalLanguageDomainEntries - to add entirely new languages to FreeCAD that are not currently supported by the source code, you can use this user preference to add to the list of available languages. The format of the languages is "Language Name"="code"; for example:

<FCText Name="AdditionalLanguageDomainEntries">"Esperanto"="eo";"French"="fr";</FCText>

AdditionalTranslationsDirectory - add an additional directory for FreeCAD to search for *.qm files. This location will take precedence over $userAppDataDir/translations and $resourceDir/translations. For example:

<FCText Name="AdditionalTranslationsDirectory">C:/Users/FreeCADUser/TestTranslations</FCText>

Tranducere FreeCAD wiki

Acest wiki găzduiește o multitudine de conținuturi, majoritatea cărora construiesc manualul. Puteți căuta documentația pornind de la Main Page, or have a look at the User's manual Online Help Toc.

Pentru a traduce în wiki, trebuie să aveți permisiunea Cum pot obține permisiunea de a edita pe wiki?.

Ar trebui să aveți, de asemenea, suficiente cunoștințe despre marcajul wiki și să urmați liniile generale de orientare descrise în WikiPages.

Mediawiki Translation Extension

Când wiki-ul s-a mutat de la SourceForge, Yorik a instalat extensia de traducere a MediaWiki's Translation extension care facilitează traducerea paginilor. Avantajele extensiei de traducere sunt că titlul paginii poate fi acum tradus, se ține evidența traducerilor, se notifică dacă pagina inițială a fost actualizată și se mențin traducerile sincronizate cu pagina originală în limba engleză.

Instrumentul este documentat în Help:Extension:Translate, și este partea a MediaWiki Language Extension Bundle.

Pentru a începe rapid să pregătiți o pagină pentru traducere, citiți textulPage translation example. Essentially, a pair of

<translate> ... </translate>

etichetele trebuie să înconjoară întreaga pagină pentru a activa sistemul de traducere, iar pagina trebuie marcată pentru traducere.

Pentru a vedea un exemplu de funcționare a instrumentului de traducere odată ce plugin-ul de traducere este activat pe o pagină, accdesați Main Page.Veți vedea o bară de limbă generată automat în partea de sus. Faceți clic pe Deutsch (germană), vă va duce la Main Page/de. În dreptul titlului, puteți citi "Această pagină este o versiune tradusă a Paginii Principale a paginii și traducerea este XX% completă", XX fiind procentul efectiv al traducerii. Faceți clic pe "Traduceți" în partea de sus a paginii pentru a porni utilitarul de traducere pentru a actualiza, corecta și revizui traducerea existentă.

Dacă mergeți la Main Page/de, veți observa că nu mai puteți edita direct pagina făcând clic pe etichetele [Editare], iar linkul de sus "Editare" a fost înlocuit cu linkul "Traduceți" care deschide utilitarul de traducere.

Când se adaugă conținut nou, pagina de engleză trebuie creată mai întâi, apoi tradusă în altă limbă. Dacă cineva dorește să schimbe sau să adauge conținut într-o pagină, pagina în limba Engleză ar trebui să fie prima modificată.

Dacă nu sunteți siguri cum să continuați cu traducerile, nu ezitați să cereți ajutor în subforumul Develpment/Wiki sau în subforumuol specific al limbii în FreeCAD forum.

Note Importante

Fiecare utilizator wiki care are permisiuni "Editor" este capabil să lanseze utilitatea de traducere și să scrie, să salveze și să revizuiască traducerile.

Cu toate acestea, numai utilizatorii cu permisiuni "Administrator" pot marca paginile pentru traducere. O pagină care nu este marcată pentru traducere nu va utiliza extensia de traducere și nu va fi sincronizată corect cu informațiile din limba engleză.

Bara laterală din stânga este, de asemenea, translatabilă, dar numai administratorii pot modifica acest element al site-ului. Urmați instrucțiunile dedicate din paginaLocalisation Sidebar .

Prima dată când comutați o pagină în noul sistem de traducere, aceasta își pierde toate vechile traduceri "manuale". Pentru a recupera o traducere, ar trebui să salvați o copie offline a vechiului text înainte de comutatore. Apoi puteți utiliza acest vechi text tradus pentru a completa unitățile de traducere în noul sistem. De asemenea, puteți deschide o versiune anterioară din istoric și puteți obține vechiul text în acest fel. Acest lucru trebuie făcut pentru fiecare limbă care a avut o pagină tradusă.

Traducerea documentației FreeCAD

As per general consensus, the reference page in the wiki is the English page, which should be created first. If you want to change or add content to a page, you should do it to the English page first, and only once the update is completed, port the modification to the translated page.

Instrucțiuni pentru Vechile traduceri

Aceste instrucțiuni sunt doar pentru istoricul istoric. Traducerile ar trebui să utilizeze noul sistem cu extensia #Translation extension descrisă mai sus.

Deci, primul pas este să verificați dacă traducerea manuală a fost deja pornită pentru limba dvs. (vedeți în bara laterală stângă, sub "manual").
Dacă nu, mergeți la forum și spuneți că doriți să începeți o nouă traducere, vom crea setările de bază pentru limba în care doriți să lucrați.
Trebuie apoi să obțineți gain wiki permission edit.
Dacă limba dvs. este deja listată, vedeți în ce pagini încă lipsește o traducere (acestea vor fi listate în roșu). Tehnica este simplă: intrați într-o pagină roșie și copiați / inserați conținutul paginii engleză corespunzătoare și începeți să traduceți.
Nu uitați să includeți toate etichetele și șabloanele din pagina engleză originală. Unele dintre aceste șabloane vor avea un echivalent în limba dvs. (de exemplu, există un șablon French Docnav numit Docnav/fr). Ar trebui să utilizați un slash și codul limbii dvs în toate link-urile. Uitați-vă la alte pagini deja traduse pentru a vedea cum au făcut-o.
Adăugați un slash și codul de limbă în categorii, cum ar fi [[Category: Documentation Developer / fr]]
Și dacă nu sunteți sigur, mergeți la forumuri și cereți-le oamenilor să verifice ceea ce ați făcut și să vă spun dacă este corect sau nu.
Patru șabloane sunt utilizate frecvent în paginile manuale. Aceste 4 șabloane au versiuni localizate (Template: Docnav/fr, Template:fr, etc ...)

  • Template:GuiCommand: este blocul de informații Gui Command în partea dreaptă sus a documentației de comandă.
  • Template: Docnav: este bara de navigare din partea de jos a paginilor, care afișează paginile anterioare și următoare.

Pagina de numire a Convenției
Vă rugăm să rețineți că, datorită limitărilor din implementarea Sourceforge a motorului MediaWiki, solicităm ca toate paginile dvs. să păstreze numele original al omologului său, adăugând un slash și codul dvs. de limbă. De exemplu, pagina tradusă pentru About FreeCAD ar trebui să fie Despre Freecad/es pentru spaniolă, Despre FreeCAD/pl pentru poloneză, etc. Motivul este simplu: pentru ca dacă traducătorii să dispară, administratorii wiki, care nu vorbesc toate limbile, vor ști ce sunt aceste pagini. Acest lucru va facilita întreținerea și va evita paginile pierdute.
Dacă doriți ca șablonul Docnav să afișeze pagini legate în limba dvs., puteți utiliza paginile de redirecționare . Ele sunt linkuri rapide la pagina actuală. Iată un exemplu cu pagina franceză Despre FreeCAD.

  • Pagina About FreeCAD/fr este pagina cu conținut
  • Pagina À propos de FreeCAD conține acest cod:
#REDIRECT  [[About FreeCAD/fr]] 
  • În pagina About FreeCAD/fr, codul Docnav va arăta astfel:
 {{docnav/fr|Bienvenue sur l'aide en ligne|Fonctionnalités}}

Pagina "Bienvenue sur l'aide en ligne" se redirecționează către pagina Online Help Startpage/fr, iar pagina "Fonctionalités" redirecționează către Feature list/fr.

Traduceți site-ul FreeCAD

Traducerea site-ului FreeCAD se face acum prin intermediul Crowdin. Fișierul este denumit homepage.po.

Translation of the FreeCAD website is now done through Crowdin. The file is named homepage.po.

Dezvoltare - Cum se adaugă Localizarea

Această secțiune este destinată dezvoltatorilor care doresc să adauge localizare codului lor.

This section is for developers who want to add localisation to their code.

Pregătirea modulelor FreeCAD / master pentru traducere

Acestea sunt părțile la procesul de traducere a FreeCAD:

  • extrageți șiruri de text din codul sursă în fișiere *.ts
  • încărcați fișierele .ts în FreeCAD Crowdin.
  • traducerea șirurilor în Crowdin
  • extrage fișiere modificate/noi *.ts de la Crowdin
  • convertește fișierele *.ts în fișiere *.qm și actualizează fișierul *.qrc al fiecărui modul
  • Actualizați masterul FreeCAD

These are the parts to the FreeCAD translation process:

  • extract text strings from source code into *.ts files
  • load *.ts files into FreeCAD Crowdin.
  • translation of strings within Crowdin
  • extract modified/new *.ts files from Crowdin
  • convert *.ts files into *.qm files and update each module's *.qrc file
  • update FreeCAD master

Toți pașii de mai sus sunt realizați prin "scripturile de traducere", care sunt gestionate periodic de un administrator.

Pregătirea modulului dvs. pentru traducere este destul de ușoară. În primul rând, trebuie să vă asigurați că aveți un director de "traduceri" în MyModule / Gui / Resources. Apoi deschideți o fereastră terminală (sau echivalent Windows / OSX) în directorul "traduceri" și introduceți următoarea comandă:

lupdate -ts myModule.ts

Aceasta creează un fișier de traducere gol. Odată ce acest lucru este făcut, trebuie să vă asigurați că scripturile de traducere sunt actualizate ca în acesta pull request.

Totul după acest lucru este automat în ceea ce privește un dezvoltator. Administratorul va extrage șirurile de text, traducătorii îi vor traduce, apoi administratorul va extrage traducerile și va actualiza FreeCAD / master.

Pregătirea modulului de la o terță parte sau a unei macro pentru traducere

Modulele sau macro-urile de la terțe părți sunt traduse în aceeași manieră, cu excepția faptului că trebuie să faceți o parte din munca dumneavoastră. Această adresă forum discussion descrie detaliile.

3rd party modules or macros are translated in much the same fashion, except that you must do some of the work yourself. This forum discussion describes the details.

Update: see Translating an external workbench

Tehnici mai vechi de traducere a modulelor

Metode de localizare mai vechi descrie utilizarea în detaliu a instrumentelor de traducere, cum ar fi Qt Lingvistist, lupdate, lrelease, pylupdate4, etc. Cele mai multe dintre acestea nu mai sunt necesare pentru modulele FreeCAD / master, dar poate fi utilă pregătirea și actualizarea modulelor terțelor părți.

Localization Older Methods describes the use of translation tools such as Qt Linguist, lupdate, lrelease, pylupdate4, etc in detail. Most of this is no longer required for FreeCAD/master modules, but may be helpful preparing and updating 3rd party modules.

Automatizarea actualizărilor traducerii Crowdin

În prezent, administratorii FreeCAD utilizează API-ul Crowdin prin Crowdin Scripts pentru a trage și împinge traducerile în Crowdin și înapoi la repo Github. API-ul Crowdin oferă administratorilor FreeCAD capacitatea de a automatiza aspectele fluxului de lucru al proiectului, pentru mai multe informații, consultați documentația Crowdin API.

Currently FreeCAD maintainers use the Crowdin API via Crowdin Scripts to pull and push translations in to Crowdin and back in to the Github repo. The Crowdin API gives FreeCAD maintainers the ability to automate aspects of the project's translation workflow, for more info refer to the Crowdin API documentation.

Scripting

See also: FreeCAD Scripting Basics.

To get a dictionary with the languages the FreeCAD interface supports, use the supportedLocales method of the FreeCADGui module.

locales = FreeCADGui.supportedLocales()

After execution locales will contain:

{'English': 'en', 'Afrikaans': 'af', 'Arabic': 'ar', 'Basque': 'eu', 'Catalan': 'ca', 'Chinese Simplified': 'zh-CN', 'Chinese Traditional': 'zh-TW', 'Croatian': 'hr', 'Czech': 'cs', 'Dutch': 'nl', 'Filipino': 'fil', 'Finnish': 'fi', 'French': 'fr', 'Galician': 'gl', 'German': 'de', 'Hungarian': 'hu', 'Indonesian': 'id', 'Italian': 'it', 'Japanese': 'ja', 'Kabyle': 'kab', 'Korean': 'ko', 'Lithuanian': 'lt', 'Norwegian': 'no', 'Polish': 'pl', 'Portuguese': 'pt-PT', 'Portuguese, Brazilian': 'pt-BR', 'Romanian': 'ro', 'Russian': 'ru', 'Slovak': 'sk', 'Slovenian': 'sl', 'Spanish': 'es-ES', 'Swedish': 'sv-SE', 'Turkish': 'tr', 'Ukrainian': 'uk', 'Valencian': 'val-ES', 'Vietnamese': 'vi'}

To get the current interface language use the getLocale method of the same module:

locale = FreeCADGui.getLocale()

If the current language is English locale will contain:

'English'

To get the corresponding language code you can use use:

locale = FreeCADGui.supportedLocales()[Gui.getLocale()]

If the current language is English the result will be:

'en'

To set the current interface language use the setLocale method of the same module. You can specify the language or the language code:

FreeCADGui.setLocale('Russian')
FreeCADGui.setLocale('ru')


Branding
Extra python modules


Overview

Această pagină afișează câteva module suplimentare de tip python sau alte piese de software care pot fi descărcate gratuit de pe internet și pot adăuga funcționalitate pentru FreeCAD instalat.

PySide (previously PyQt)

PySide (previously PyQt4)

PySide (anterior numit PyQt) este solicitat de mai multe module ale FreeCAD pentru a accesa interfața Qt a FreeCAD. Acesta este deja inclus în versiunea Windows a FreeCAD și, de obicei, este instalat automat de FreeCAD pe Linux, când se instalează din depozitele oficiale. Dacă aceste module (Draft, Arch etc.) sunt activate după ce FreeCAD este instalat, înseamnă că PySide (anterior PyQt) este deja acolo și nu mai trebuie să mai faceți nimic.

Notă: FreeCAD sa mutat progresiv de la PyQt după versiunea 0.13, în favoareaPySide, care face exact același lucru, dar are o licență (LGPL) mai compatibilă cu FreeCAD.

Instalarea

Linux

Linux

Cea mai simplă modalitate de a instala PySide este prin managerul de pachete al distribuției. Pe sistemele Debian / Ubuntu, numele pachetului este în general "python-PySide", în timp ce în sistemele bazate pe RPM se numește "pyside". Dependentele necesare (Qt și SIP) vor fi luate în considerare automat.

Windows

Windows

Programul poate fi descărcat de la http://qt-project.org/wiki/Category:LanguageBindings::PySide::Downloads. Va trebui să instalați bibliotecile Qt și SIP înainte de a instala PySide (pentru a fi documentate).

MacOS

MacOSX

PyQt on Mac can be installed via homebrew or port. See Compile on MacOS/ro#Install_Dependencies for more information.

Usage

Utilizare

Odată ce este instalat, puteți verifica dacă totul funcționează prin tastarea în consolă Python FreeCAD:

import PySide

To access the FreeCAD interface, type :

from PySide import QtCore,QtGui
FreeCADWindow = FreeCADGui.getMainWindow()

Acum puteți începe să explorați interfața cu comanda dir (). Puteți adăuga elemente noi, cum ar fi un widget personalizat, cu comenzi cum ar fi:

FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget)

Working with Unicode :

text = text.encode('utf-8')

Working with QFileDialog and OpenFileName :

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt")

Working with QFileDialog and SaveFileName :

path = FreeCAD.ConfigGet("AppHomePath")
#path = FreeCAD.ConfigGet("UserAppData")
SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")

Example of transition from PyQt4 and PySide

PS: Aceste exemple de erori au fost găsite în tranziția de la PyQt4 la PySide și aceste corecții au fost făcute, alte soluții sunt cu siguranță disponibile cu exemplele de mai sus

try:
    import PyQt4                                        # PyQt4
    from PyQt4 import QtGui ,QtCore                     # PyQt4
    from PyQt4.QtGui import QComboBox                   # PyQt4
    from PyQt4.QtGui import QMessageBox                 # PyQt4
    from PyQt4.QtGui import QTableWidget, QApplication  # PyQt4
    from PyQt4.QtGui import *                           # PyQt4
    from PyQt4.QtCore import *                          # PyQt4
except Exception:
    import PySide                                       # PySide
    from PySide import QtGui ,QtCore                    # PySide
    from PySide.QtGui import QComboBox                  # PySide
    from PySide.QtGui import QMessageBox                # PySide
    from PySide.QtGui import QTableWidget, QApplication # PySide
    from PySide.QtGui import *                          # PySide
    from PySide.QtCore import *                         # PySide

Pentru a accesa interfața FreeCAD, tastați: Puteți adăuga elemente noi, cum ar fi un widget personalizat, cu comenzi cum ar fi:

myNewFreeCADWidget = QtGui.QDockWidget()          # create a new dockwidget
myNewFreeCADWidget.ui = Ui_MainWindow()           # myWidget_Ui()             # load the Ui script
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
try:
    app = QtGui.qApp                              # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw = app.activeWindow()                     # PyQt4 # the active qt window, = the freecad window since we are inside it
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
except Exception:
    FCmw = FreeCADGui.getMainWindow()             # PySide # the active qt window, = the freecad window since we are inside it
    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Working with Unicode :

try:
    text = unicode(text, 'ISO-8859-1').encode('UTF-8')  # PyQt4
except Exception:
    text = text.encode('utf-8')                         # PySide

Working with QFileDialog and OpenFileName :

OpenName = ""
try:
    OpenName = QFileDialog.getOpenFileName(None,QString.fromLocal8Bit("Lire un fichier FCInfo ou txt"),path,"*.FCInfo *.txt") # PyQt4
except Exception:
    OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide

Working with QFileDialog and SaveFileName :

SaveName = ""
try:
    SaveName = QFileDialog.getSaveFileName(None,QString.fromLocal8Bit("Sauver un fichier FCInfo"),path,"*.FCInfo") # PyQt4
except Exception:
    SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide

The MessageBox:

def errorDialog(msg):
    diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical,u"Error Message",msg )
    try:
        diag.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint) # PyQt4 # this function sets the window before
    except Exception:
        diag.setWindowFlags(PySide.QtCore.Qt.WindowStaysOnTopHint)# PySide # this function sets the window before
#    diag.setWindowModality(QtCore.Qt.ApplicationModal)       # function has been disabled to promote "WindowStaysOnTopHint"
    diag.exec_()

Working with setProperty (PyQt4) and setValue (PySide)

self.doubleSpinBox.setProperty("value", 10.0) # PyQt4

înlocuiți cu :

self.doubleSpinBox.setValue(10.0) # PySide

Working with setToolTip

self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None)) # PyQt4

înlocuiți la :

self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y")) # PySide

ori :

self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide

Additional documentation

Pivy

Pivy

Pivy is a needed by several modules to access the 3D view of FreeCAD. On windows, Pivy is already bundled inside the FreeCAD installer, and on Linux it is usually automatically installed when you install FreeCAD from an official repository. On MacOSX, unfortunately, you will need to compile pivy yourself.

Instalare

Prerequisites

Cerințe preliminare

Cred că înainte de a compila Pivy, veți dori să instalați Coin și SoQt.

Am găsit că pentru construirea pe Mac a fost suficient pentru a instala Coin3 binary package. Încercarea de a instala coin de la MacPorts a fost problematică: a încercat să adauge o mulțime de pachete X Windows și în cele din urmă s-a prăbușit cu o eroare de script.

For Fedora I found an RPM with Coin3.

SoQt compiled from source fine on Mac and Linux.

Debian & Ubuntu

Debian & Ubuntu

Începând cu Debian Squeeze și Ubuntu Lucid, pivy va fi disponibil direct din depozitele oficiale, economisind astfel o mulțime de bătăi de cap. Între timp, puteți să descărcați unul dintre pachetele pe care le-am făcut (pentru debian și karmic ubuntu) disponibile în paginile Download sau să le compilați singur.

Cea mai bună modalitate de a compila pivy cu ușurință este să luați pachetul sursă debian pentru pivy și să faceți un pachet cu debuild. Este același cod sursă de pe site-ul oficial pivy, dar oamenii de la debian au făcut mai multe adăugări de fixare a bug-urilor. De asemenea, compilează bine karmicul ubuntu: http://packages.debian.org/squeeze/python-pivy descărcați fișierul .orig.gz și .diff.gz, apoi dezarhivați ambele, apoi aplicați .diff la sursă: mergeți la directorul sursă de pivy dezarhivate și aplicați patch-ul .diff:

patch -p1 < ../pivy_0.5.0~svn765-2.diff

then

debuild

to have pivy properly built into an official installable package. Then, just install the package with gdebi.

Other linux distributions

Alte distribuții linux

First get the latest sources from the project's repository:

hg clone http://hg.sim.no/Pivy/default Pivy

As of March 2012, the latest version is Pivy-0.5.

Apoi aveți nevoie de un instrument numit SWIG pentru a genera codul C++ pentru legăturile Python. Pivy-0.5 raportează că a fost testată numai cu SWIG 1.3.31, 1.3.33, 1.3.35 și 1.3.40. Deci, puteți descărca o sursă tarball pentru una dintre aceste versiuni vechi de la http://www.swig.org. Then unpack it and from a command line do (as root):

./configure
make
make install (or checkinstall if you use it)

Ia doar câteva secunde compilarea.

Alternativ, puteți încerca construirea cu un SWIG mai recent. Începând cu luna martie 2012, o versiune tipică pentru depozit este 2.0.4. Pivy are o problemă minoră de compilare cu SWIG 2.0.4 pe Mac OS (vezi mai jos), dar pare să construiască bine pe Fedora Core 15.

După aceea, mergeți la sursele de pivy și sunați

python setup.py build

which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.

Acest lucru este probabil depășit, însă este posibil să întâmpinați o eroare de compilator în care un "const char *" nu poate fi convertit într-un 'char *'. Pentru a repara că trebuie doar să scrieți un "const" înainte în liniile corespunzătoare. Există șase linii de rezolvat.

După asta, instalați by issuing (ca root):

python setup.py install (or checkinstall python setup.py install)

Et voila, pivy este instalat.

MacOS

Mac OS

Este posibil ca aceste instrucțiuni să nu fie complete. Ceva aproape de acest lucru a funcționat pentru OS 10.7 în martie 2012. Eu folosesc MacPorts pentru depozite, dar ar trebui să funcționeze și alte opțiuni.

În ceea ce privește linux, obțineți cea mai recentă sursă:

hg clone http://hg.sim.no/Pivy/default Pivy

Dacă nu aveți hg, îl puteți obține de la MacPorts:

port install mercurial

Then, as above you need SWIG. It should be a matter of:

port install swig

I found I needed also:

port install swig-python

Începând cu luna martie 2012, MacPorts SWIG este la versiunea 2.0.4. După cum s-a menționat mai sus pentru linux, este posibil să fie mai bine să descărcați o versiune mai veche. SWIG 2.0.4 pare să aibă un bug care oprește clădirea Pivy. Vedeți primul mesaj din acest rezumat:https://sourceforge.net/mailarchive/message.php?msg_id=28114815

Acest lucru poate fi corectat prin editarea celor două locații sursă pentru a adăuga dereferențe: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:

python setup.py build
sudo python setup.py install

Windows

Windows

Presupunând că utilizați Visual Studio 2005 sau o versiune ulterioară, ar trebui să deschideți un prompt de comandă cu "Visual Studio 2005 Command prompt" din meniul Instrumente. Dacă interpretul Python nu este încă în calea sistemului, faceți acest lucru

set PATH=path_to_python_2.5;%PATH%

Pentru a obține o pivă de lucru, ar trebui să obțineți cele mai recente surse din depozitul proiectului:

svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy

Apoi aveți nevoie de un instrument numit SWIG pentru a genera codul C++ pentru legăturile Python. Se recomandă utilizarea versiunii 1.3.25 a SWIG, nu cea mai recentă versiune, deoarece în acest moment pivy va funcționa corect numai cu 1.3.25. Descărcați binarele pentru 1.3.25 de la http://www.swig.org. Apoi despachetați-l și din linia de comandă adăugați-l pe calea sistemului

set PATH=path_to_swig_1.3.25;%PATH%

și setați COINDIR pe calea potrivită

set COINDIR=path_to_coin

Pe Windows, fișierul config pivy se așteaptă ca SoWin în loc de SoQt ca implicit. Nu am găsit o modalitate evidentă de a construi cu SoQt, așa că am modificat fișierul setup.py direct. În linia 200, scoateți doar partea "sowin": ('gui._sowin', 'sowin-config', 'pivy.gui.') (Nu scoateți paranteza de închidere).

After that go to the pivy sources and call

python setup.py build

care creează fișierele sursă. S-ar putea să întâlniți o eroare de compilator că nu au putut fi găsite mai multe fișiere antet. În acest caz, ajustați variabila INCLUDE

set INCLUDE=%INCLUDE%;path_to_coin_include_dir

și dacă antetele SoQt nu se află în același loc ca și antetele de Coin

set INCLUDE=%INCLUDE%;path_to_soqt_include_dir

și în final anteturile Qt

set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

Dacă utilizați Express Edition din Visual Studio, puteți obține o excepție python keyerror. În acest caz, trebuie să modificați câteva lucruri în msvccompiler.py localizate în instalarea dvs. python.

Mergeți la linia 122 și înlocuiți linia de cod

vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version

cu

vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version

Apoi încercați din nou. Dacă primiți o a doua eroare cum ar fi

error: Python was built with Visual Studio 2003;...

trebui să înlocuiți și linia 128

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")

cu

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")

Reîncercați încă o dată. Dacă apare din nou o eroare cum ar fi

error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed.

then you should check the environment variables DISTUTILS_USE_SDK and MSSDK with

echo %DISTUTILS_USE_SDK%
echo %MSSDK%

If not yet set then just set it e.g. to 1

set DISTUTILS_USE_SDK=1
set MSSDK=1

Acum, puteți întâlni o eroare de compilator în care un 'const char *' nu poate fi convertit într-un 'char *'. Pentru a repara că trebuie doar să scrieți un "const" înainte în liniile corespunzătoare. Există șase linii de rezolvat. Dupa ce copiați directorul generat pivy într-un loc in care interpretul python din FreeCAD îl poate gasi.

Usage

Utilizare

Pentru a verifica dacă Pivy este instalat corect:

import pivy

To have Pivy access the FreeCAD scenegraph do the following:

from pivy import coin
App.newDocument() # Open a document and a view
view = Gui.ActiveDocument.ActiveView
FCSceneGraph = view.getSceneGraph() # returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraph
FCSceneGraph.addChild(coin.SoCube()) # add a box to scene

You can now explore the FCSceneGraph with the dir() command.

Additonal Documentation

Documentație suplimentară

Din păcate, documentația despre pivu este încă aproape inexistentă pe net. Dar s-ar putea să găsiți documentația Coin utilă, deoarece pivy pur și simplu traduce funcții de coin, noduri și metode în Python, totul păstrează același nume și proprietăți, ținând cont de diferența de sintaxă dintre C și python:

You can also look at the Draft.py file in the FreeCAD Mod/Draft folder, since it makes big use of pivy.

pyCollada

pyCollada

pyCollada is a python library that allow programs to read and write Collada (*.DAE) files. When pyCollada is installed on your system, FreeCAD will be able to handle importing and exporting in the Collada file format.

Installation

Linux

sudo apt-get install python3-collada

You can check if pycollada was correctly installed by issuing in a python console:

import collada

If it returns nothing (no error message), then all is OK

Windows

Pe Windows, de la 0.15 pycollada este inclus atât în versiunea FreeCAD, cât și în versiunea dezvoltatorului, deci nu sunt necesare pași suplimentari.

Mac OS

Dacă utilizați buildul Homebrew al FreeCAD, puteți instala pycollada în sistemul dvs. Python folosind pip.

If you need to install pip:

$ sudo easy_install pip

Install pycollada:

$ sudo pip install pycollada

Dacă utilizați o versiune binară a FreeCAD, puteți spune pip-ului să instaleze pycollada în pachetele de site-uri din cadrul FreeCAD.app:

$ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada

sau după descărcarea codului pycollada

$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
$ python setup.py install --prefix=/Applications/FreeCAD\ 0.16.6706.app/Contents

IfcOpenShell

IFCOpenShell este o bibliotecă în curs de dezvoltare, care permite importul fișierelor Classes Fundation Classes (* .IFC) pentru import (și, în curând, export). IFC este o extensie a formatului STEP și devine standard în fluxurile de lucru BIM. Când sistemul ifcopenshell este instalat corect pe sistem, FreeCAD Arch Workbench/ro îl va detecta și îl va folosi pentru a importa fișiere IFC în locul importatorului său rudimentar integrat. Deoarece ifcopenshell se bazează pe OpenCasCade, precum FreeCAD, calitatea importului este foarte mare, producând o geometrie solidă de înaltă calitate.

Installation

Instalare

Din moment ce ifcopenshell este destul de nou, probabil că va trebui să-l compilați singur.

Linux

Linux

Veți avea nevoie de câteva pachete de dezvoltare instalate pe sistemul dvs. pentru a compila ifcopenshell:

liboce-*-dev
python-dev
swig

dar din moment ce FreeCAD le cere tuturor, dacă puteți compila FreeCAD, nu veți avea nevoie de nici o dependență suplimentară pentru a compila IfcOpenShell.

Grab the latest source code from here:

git clone https://github.com/IfcOpenShell/IfcOpenShell.git

The build process is very easy:

mkdir ifcopenshell-build
cd ifcopenshell-build
cmake ../IfcOpenShell/cmake

or, if you are using oce instead of opencascade:

cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake

Deoarece ifcopenshell este făcut în primul rând pentru Blender, el folosește în mod implicit python3. Pentru a o folosi în interiorul FreeCAD, trebuie să o compilați împotriva aceleiași versiuni de Python care este folosită de FreeCAD. Deci este posibil să trebuiască să forțați versiunea python cu parametri suplimentari de tip cmake (ajustați versiunea python la a ta):

cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake

Then:

make
sudo make install

You can check that ifcopenshell was correctly installed by issuing in a python console:

import ifcopenshell

If it returns nothing (no error message), then all is OK

Windows

Notă: Instalatorii oficiali FreeCAD obținuți de pe pagina web/github a FreeCAD conțin acum ifcopenshell.

Copied from the IfcOpenShell README file

Users are advised to use the Visual Studio .sln file in the win/ folder. For Windows users a prebuilt Open CASCADE version is available from the http://opencascade.org website. Download and install this version and provide the paths to the Open CASCADE header and library files to MS Visual Studio C++.

Pentru a construi învelișul IfcPython, trebuie instalat SWIG. Descărcați cea mai recentă versiune swigwin de la http://www.swig.org/download.html. După extragerea fișierului .zip, adăugați dosarul extras la variabila de mediu PATH. Python trebuie să fie instalat, vă rugăm să furnizați căile de includere și bibliotecă la Visual Studio.

Links

LazyLoader

LazyLoader is a Python module that allows deferred loading, while still importing at the top of the script. This is useful if you are importing another module that is slow, and it is used several times throughout the script. Using LazyLoader can improve workbench startup times, but the module will still need to be loaded on first use.

Installation

LazyLoader is included with FreeCAD v0.19

Usage

You will need to import LazyLoader, then change the import of whatever module you want to be deferred.

from lazy_loader.lazy_loader import LazyLoader
Part = LazyLoader('Part', globals(), 'Part')

The variable Part is how the module is named in your script. You can replicate "import Part as P" by changing the variable.

P = LazyLoader('Part', globals(), 'Part')

You can also import a module from a package.

utils = LazyLoader('PathScripts', globals(), 'PathScripts.PathUtils')

You can't import individual functions, just entire modules.

Links


Link-uri utile

FreeCAD este un soft de modelare parametrică 3D și face parte din marea familie a software CAD . Dezvoltarea este în întregime Open Source Open Source (LGPL License)(licences GPL et LGPL). FreeCAD and este orientat spre inginerie mecanică mechanical engineering și proiectarea de produse product design, dar vizează de asemenea și alte domenii de activitate inginerească (ca arhitectura, construcțiile în general, navele, robotica, etc).

Caracteristicile instrumentelor FreeCAD sunt similare cu Catia, SolidWorks sau Solid Edge, și de aceea intră în categoria MCAD, PLM, CAx și CAE. Este un feature based parametric modeler cu o arhitectură software modulară care facilitează furnizarea de funcționalități suplimentare fără a modifica sistemul central.

Ca și multe alte modelatoare moderne 3D CAD modelers are multe componente 2D pentru a schița forme 2D sau pentru a extrage detaliile de proiectare de la modelul 3D pentru a crea desene de producție 2D, desen 2D direct.(like AutoCAD LT) nu este focalizat nici pe animație sau forma organice (ca de exemplu Maya, 3ds Max, Blender or Cinema 4D), în ciuda adaptabilității sale largi, FreeCAD poate fi mult mai util într-o paletă largă dea domenii decât în prezent.

FreeCAD utilizează din greu toate bibliotecile mari open source care există în domeniul Scientific Computing. Printre ele sunt OpenCascade, a powerful CAD kernel, Coin3D, o încarnare a Open Inventor, Qt, the world-famous UI framework, and Python, una dintre cele mai bune limbaje de scripting disponibile. FreeCAD în sine poate fi folosit ca o bibliotecă de alte programe.

FreeCAD este de asmenea plin de multi-platform, și rulează în mod curent fără probleme pe sistemele Windows și Linux / Mac OSX, având exact același aspect și funcționalitate pe toate platformele.

Pentru mai multe informații despre capabilitățile FreeCAD, aruncați o privire laFeature list, the latest release notes or the Getting started articles, or see more screenshots.

Despre proiectul FreeCAD

Proiectul FreeCAD a început tocmai din anul 2001, după cum se descrie pagina sa de istorie history .

FreeCAD este menținută și dezvoltată de o comunitate de dezvoltatori și utilizatori entuziaști (vezi pagina contributors). Ei lucrează pe FreeCAD în mod voluntar, în timpul lor liber. Ei nu pot garanta că FreeCAD va conține toți v-ați dori, dar de obicei ei vor face tot ce pot! Comunitatea se adună pe forumul FreeCAD, unde se discută majoritatea ideilor și deciziilor. Simțiți-vă liber să vă alăturați!

About the FPA

The FreeCAD project is also supported by a non-profit organization, the FreeCAD project association (FPA). The FPA is an independent body created by some FreeCAD veterans in 2021 to collect donations and other resources to support the project and its community, to help protect that community and allow it to continue developing in the best conditions, and to represent the project against other bodies such as companies and institutions.


Online Help Startpage/ro
Installing/ro

A gentle introduction/ro



Feature list
Install on Linux

Standard Installation

The easiest way to install the latest stable version of FreeCAD is to use the installer, see the Download page.

Daca doriți sa descărcați versiunea pe 64 de biți sau versiunea aflată acum în dezvoltare (care ar putea fi instabilă) vizitați pagina de descărcări.

Dupa ce fișierul .msi (Microsoft Installer) a fost descarcat, doar faceți dublu-click pe el pentru a începe instalarea.

Mai jos sunt descrise opțiunile de instalare. Daca pare complicat nu va ingrijorați! Cei mai mulți utilizatori nu vor avea nevoie de nimic mai mult decat fișierul de mai sus .msi și articolul Primii pasi!

Installation for all users of the Windows system

By default FreeCAD will be installed for the user that executes the installer. If this user only has user permissions, the default installation path is:

C:\Users\<username>\AppData\Local\Programs\FreeCAD X.YY

If the installer is executed by an admin user, or you execute it as admin, you can choose if FreeCAD should be installed for all users of the system or just for you. The default is for all users.

If installed for all users, the default installation path is:

C:\Program Files\FreeCAD X.YY

Silent Installation

To install FreeCAD silently, you can execute the installer from the command line:

FreeCAD-~.exe /S

Default settings will be used for all options. A custom installation path can be specified in this manner:

FreeCAD-~.exe /S /D=A path to FreeCAD with spaces

By default, even with silent installations, there will be a short popup when the installer is checked for corruption. This so-called cyclic redundancy check only takes a few seconds at most. To disable this corruption check:

FreeCAD-~.exe /S /NCRC

Note that this /NCRC flag is not recommended since the corruption check assures that the installer was e.g. completely downloaded.

Chocolatey

Using the Chocolatey package manager is currently not recommended as that repository is no longer kept up-to-date.

Dezinstalarea

Folosind

To uninstall FreeCAD it is preferable to use the Windows tools for uninstalling software. Alternatively you can execute the uninstaller directly. This is the file:

Uninstall-FreeCAD.exe

You can find it in the folder where FreeCAD is installed.

The uninstaller can also be executed silently using the command line:

Uninstall-FreeCAD.exe /S

Note that (silent) uninstallation will fail if there is a running instance of FreeCAD, even if that instance is not the version being uninstalled.


Feature list
Install on Linux


Template:Tutorials/ro

All workbenches at a glance/ro
_________________________________________________

























Contribuții



Listă ne exhaustivă, alte manuale vor urma, funcție de evoluția atelierelor.