Added options handling to build_object function.

This commit is contained in:
Jeremy Mack Wright 2017-09-03 18:01:39 -04:00
parent 9689664aa1
commit 2cdd504888
13 changed files with 239 additions and 74 deletions

View File

@ -168,9 +168,13 @@ class CadQueryExecuteScript:
if build_result.success:
# Display all the results that the user requested
for result in build_result.results:
show(result)
# Apply options to the show function if any were provided
if result.options and result.options["rgba"]:
show(result.shape, result.options["rgba"])
else:
show(result.shape)
else:
FreeCAD.Console.PrintError("Error executing CQGI-compliant script.\r\n")
FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n")
else:
# Save our code to a tempfile and render it
tempFile = tempfile.NamedTemporaryFile(delete=False)

File diff suppressed because one or more lines are too long

View File

@ -1,7 +0,0 @@
build/
*.pyc
doc/_build/*
dist/*
.idea/*
cadquery.egg-info
target/*

View File

@ -1,32 +0,0 @@
language: python
before_install:
- sudo add-apt-repository -y ppa:freecad-maintainers/freecad-stable
- sudo apt-get update -qq
install:
- sudo apt-get install -y freecad freecad-doc
- gcc --version
- g++ --version
- python ./setup.py install
- pip install -r requirements-dev.txt
- pip install travis-sphinx
script:
- coverage run --source=cadquery ./runtests.py
- travis-sphinx --nowarn --source=doc build
after_success:
- coveralls
- travis-sphinx deploy
branches:
except:
- pythonocc
- 2_0_branch
deploy:
provider: pypi
user: dcowden
password:
secure: aP02wBbry1j3hYG/w++siF1lk26teuRQlPAx1c+ec8fxUw+bECa2HbPQHcIvSXB5N6nc6P3L9LjHt9ktm+Dn6FLJu3qWYNGAZx9PTn24ug0iAmB+JyNrsET3nK6WUKR1XpBqvjKgdpukd1Hknh2FSzYoyUvFWH9/CovITCFN3jo=
on:
tags: true

View File

@ -223,7 +223,11 @@ Use these steps if you would like to write CadQuery scripts as a python API. In
```bash
pip install cadquery
```
3. test your installation::
4. installing cadquery should install pyparsing as well, but if not::
```bash
pip install pyparsing
```
5. test your installation::
```python
from cadquery import *
box = Workplane("XY").box(1,2,3)
@ -234,7 +238,7 @@ You're up and running!
Installing -- Using CadQuery from Inside FreeCAD
=================================================
Use the Excellent CadQuery-FreeCAD plugin here:
Use the CadQuery module for FreeCAD here:
https://github.com/jmwright/cadquery-freecad-module
It includes a distribution of the latest version of cadquery.

View File

@ -0,0 +1,154 @@
Metadata-Version: 1.1
Name: cadquery
Version: 1.0.0
Summary: CadQuery is a parametric scripting language for creating and traversing CAD models
Home-page: https://github.com/dcowden/cadquery
Author: David Cowden
Author-email: dave.cowden@gmail.com
License: Apache Public License 2.0
Description: What is a CadQuery?
========================================
[![Travis Build Status](https://travis-ci.org/dcowden/cadquery.svg)](https://travis-ci.org/dcowden/cadquery)
[![Coverage Status](https://coveralls.io/repos/dcowden/cadquery/badge.svg)](https://coveralls.io/r/dcowden/cadquery)
[![GitHub version](https://badge.fury.io/gh/dcowden%2Fcadquery.svg)](https://github.com/dcowden/cadquery/releases/tag/v0.3.0)
[![License](https://img.shields.io/badge/license-LGPL-lightgrey.svg)](https://github.com/dcowden/cadquery/blob/master/LICENSE)
CadQuery is an intuitive, easy-to-use python based language for building parametric 3D CAD models. CadQuery is for 3D CAD what jQuery is for javascript. Imagine selecting Faces of a 3d object the same way you select DOM objects with JQuery!
CadQuery has several goals:
* Build models with scripts that are as close as possible to how you'd describe the object to a human.
* Create parametric models that can be very easily customized by end users
* Output high quality CAD formats like STEP and AMF in addition to traditional STL
* Provide a non-proprietary, plain text model format that can be edited and executed with only a web browser
Using CadQuery, you can write short, simple scripts that produce high quality CAD models. It is easy to make many different objects using a single script that can be customized.
Full Documentation
============================
You can find the full cadquery documentation at http://dcowden.github.io/cadquery
Getting Started With CadQuery
========================================
The easiest way to get started with CadQuery is to Install FreeCAD (version 14+) (http://www.freecadweb.org/), and then to use our great CadQuery-FreeCAD plugin here: https://github.com/jmwright/cadquery-freecad-module
It includes the latest version of cadquery alreadby bundled, and has super-easy installation on Mac, Windows, and Unix.
It has tons of awesome features like integration with FreeCAD so you can see your objects, code-autocompletion, an examples bundle, and script saving/loading. Its definitely the best way to kick the tires!
We also have a Google Group to make it easy to get help from other CadQuery users. Please join the group and introduce yourself, and we would also love to hear what you are doing with CadQuery. https://groups.google.com/forum/#!forum/cadquery
Why CadQuery instead of OpenSCAD?
========================================
CadQuery is based on OpenCasCade. CadQuery shares many features with OpenSCAD, another open source, script based, parametric model generator.
The primary advantage of OpenSCAD is the large number of already existing model libaries that exist already. So why not simply use OpenSCAD?
CadQuery scripts have several key advantages over OpenSCAD:
1. **The scripts use a standard programming language**, python, and thus can benefit from the associated infrastructure.
This includes many standard libraries and IDEs
2. **More powerful CAD kernel** OpenCascade is much more powerful than CGAL. Features supported natively
by OCC include NURBS, splines, surface sewing, STL repair, STEP import/export, and other complex operations,
in addition to the standard CSG operations supported by CGAL
3. **Ability to import/export STEP** We think the ability to begin with a STEP model, created in a CAD package,
and then add parametric features is key. This is possible in OpenSCAD using STL, but STL is a lossy format
4. **Less Code and easier scripting** CadQuery scripts require less code to create most objects, because it is possible to locate
features based on the position of other features, workplanes, vertices, etc.
5. **Better Performance** CadQuery scripts can build STL, STEP, and AMF faster than OpenSCAD.
License
========
CadQuery is licensed under the terms of the Apache Public License, version 2.0.
A copy of the license can be found at http://www.apache.org/licenses/LICENSE-2.0
Where is the GUI?
==================
If you would like IDE support, you can use CadQuery inside of FreeCAD. There's an excellent plugin module here https://github.com/jmwright/cadquery-freecad-module
CadQuery also provides the backbone of http://parametricparts.com, so the easiest way to see it in action is to review the samples and objects there.
Installing -- FreeStanding Installation
========================================
Use these steps if you would like to write CadQuery scripts as a python API. In this case, FreeCAD is used only as a CAD kernel.
1. install FreeCAD, version 0.12 or greater for your platform. http://sourceforge.net/projects/free-cad/.
2. adjust your path if necessary. FreeCAD bundles a python interpreter, but you'll probably want to use your own,
preferably one that has virtualenv available. To use FreeCAD from any python interpreter, just append the FreeCAD
lib directory to your path. On (*Nix)::
import sys
sys.path.append('/usr/lib/freecad/lib')
or on Windows::
import sys
sys.path.append('/c/apps/FreeCAD/bin')
*NOTE* FreeCAD on Windows will not work with python 2.7-- you must use pthon 2.6.X!!!!
3. install cadquery::
pip install cadquery
3. test your installation::
from cadquery import *
box = Workplane("XY").box(1,2,3)
exporters.toString(box,'STL')
You're up and running!
Installing -- Using CadQuery from Inside FreeCAD
=================================================
Use the Excellent CadQuery-FreeCAD plugin here:
https://github.com/jmwright/cadquery-freecad-module
It includes a distribution of the latest version of cadquery.
Where does the name CadQuery come from?
========================================
CadQuery is inspired by ( `jQuery <http://www.jquery.com>`_ ), a popular framework that
revolutionized web development involving javascript.
If you are familiar with how jQuery, you will probably recognize several jQuery features that CadQuery uses:
* A fluent api to create clean, easy to read code
* Language features that make selection and iteration incredibly easy
*
* Ability to use the library along side other python libraries
* Clear and complete documentation, with plenty of samples.
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: End Users/Desktop
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX
Classifier: Operating System :: MacOS
Classifier: Operating System :: Unix
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet
Classifier: Topic :: Scientific/Engineering

View File

@ -0,0 +1,29 @@
MANIFEST.in
README.txt
setup.cfg
setup.py
cadquery/__init__.py
cadquery/cq.py
cadquery/cq_directive.py
cadquery/cqgi.py
cadquery/selectors.py
cadquery.egg-info/PKG-INFO
cadquery.egg-info/SOURCES.txt
cadquery.egg-info/dependency_links.txt
cadquery.egg-info/not-zip-safe
cadquery.egg-info/top_level.txt
cadquery/contrib/__init__.py
cadquery/freecad_impl/__init__.py
cadquery/freecad_impl/exporters.py
cadquery/freecad_impl/geom.py
cadquery/freecad_impl/importers.py
cadquery/freecad_impl/shapes.py
cadquery/plugins/__init__.py
tests/TestCQGI.py
tests/TestCQSelectors.py
tests/TestCadObjects.py
tests/TestCadQuery.py
tests/TestExporters.py
tests/TestImporters.py
tests/TestWorkplanes.py
tests/__init__.py

View File

@ -0,0 +1 @@

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,2 @@
cadquery
tests

View File

@ -34,7 +34,6 @@ class CQModel(object):
the build method can be used to generate a 3d model
"""
def __init__(self, script_source):
"""
Create an object by parsing the supplied python script.
@ -48,7 +47,7 @@ class CQModel(object):
# TODO: pick up other scirpt metadata:
# describe
# pick up validation methods
self._find_descriptions()
self._find_descriptions()
def _find_vars(self):
"""
@ -136,6 +135,14 @@ class CQModel(object):
p.set_value(v)
class ShapeResult(object):
"""
An object created by a build, including the user parameters provided
"""
def __init__(self):
self.shape = None
self.options = None
class BuildResult(object):
"""
The result of executing a CadQuery script.
@ -149,8 +156,8 @@ class BuildResult(object):
"""
def __init__(self):
self.buildTime = None
self.results = []
self.debugObjects = []
self.results = [] #list of ShapeResult
self.debugObjects = [] #list of ShapeResult
self.first_result = None
self.success = False
self.exception = None
@ -287,18 +294,25 @@ class ScriptCallback(object):
self.outputObjects = []
self.debugObjects = []
def build_object(self, shape):
def build_object(self, shape,options={}):
"""
return an object to the executing environment
return an object to the executing environment, with options
:param shape: a cadquery object
:param options: a dictionary of options that will be made available to the executing envrionment
"""
self.outputObjects.append(shape)
o = ShapeResult()
o.options=options
o.shape = shape
self.outputObjects.append(o)
def debug(self,obj,args={}):
"""
Debug print/output an object, with optional arguments.
"""
self.debugObjects.append(DebugObject(obj,args))
s = ShapeResult()
s.shape = obj
s.options = args
self.debugObjects.append(s)
def describe_parameter(self,var_data ):
"""
@ -315,15 +329,7 @@ class ScriptCallback(object):
def has_results(self):
return len(self.outputObjects) > 0
class DebugObject(object):
"""
Represents a request to debug an object
Object is the type of object we want to debug
args are parameters for use during debuging ( for example, color, tranparency )
"""
def __init__(self,object,args):
self.args = args
self.object = object
class InvalidParameterError(Exception):
"""

View File

@ -37,6 +37,9 @@ CQGI compliant containers provide an execution environment for scripts. The envi
Scripts must call build_output at least once. Invoking build_object more than once will send multiple objects to
the container. An error will occur if the script does not return an object using the build_object() method.
An optional options dictionary can be provided to the build_object method. If provided, it is passed onto the executing environment, and is used to render the object. Typically, this will be colors, transparency, and other visual affects.
This CQGI compliant script produces a cube with a circle on top, and displays a workplane as well as an intermediate circle as debug output::
base_cube = cq.Workplane('XY').rect(1.0,1.0).extrude(1.0)
@ -47,7 +50,7 @@ This CQGI compliant script produces a cube with a circle on top, and displays a
circle=top_of_cube_plane.circle(0.5)
debug(circle, { 'color': 'red' } )
build_object( circle.extrude(1.0) )
build_object( circle.extrude(1.0),{"color": "#aaaaaa" )
Note that importing cadquery is not required.
At the end of this script, one object will be displayed, in addition to a workplane, a point, and a circle

View File

@ -48,10 +48,11 @@ class TestCQGI(BaseTest):
result = model.build()
debugItems = result.debugObjects
self.assertTrue(len(debugItems) == 2)
self.assertTrue( debugItems[0].object == "bar" )
self.assertTrue( debugItems[0].args == { "color":'yellow' } )
self.assertTrue( debugItems[1].object == 2.0 )
self.assertTrue( debugItems[1].args == {} )
self.assertTrue( debugItems[0].shape == "bar" )
self.assertTrue( debugItems[0].options == { "color":'yellow' } )
self.assertTrue( debugItems[1].shape == 2.0 )
self.assertTrue( debugItems[1].options == {} )
def test_build_with_empty_params(self):
model = cqgi.CQModel(TESTSCRIPT)
@ -59,12 +60,12 @@ class TestCQGI(BaseTest):
self.assertTrue(result.success)
self.assertTrue(len(result.results) == 1)
self.assertTrue(result.results[0] == "2.0|3.0|bar|1.0")
self.assertTrue(result.results[0].shape == "2.0|3.0|bar|1.0")
def test_build_with_different_params(self):
model = cqgi.CQModel(TESTSCRIPT)
result = model.build({'height': 3.0})
self.assertTrue(result.results[0] == "3.0|3.0|bar|1.0")
self.assertTrue(result.results[0].shape == "3.0|3.0|bar|1.0")
def test_describe_parameters(self):
script = textwrap.dedent(
@ -128,8 +129,8 @@ class TestCQGI(BaseTest):
model = cqgi.CQModel(script)
result = model.build({})
self.assertEquals(2, len(result.results))
self.assertEquals(1, result.results[0])
self.assertEquals(2, result.results[1])
self.assertEquals(1, result.results[0].shape)
self.assertEquals(2, result.results[1].shape)
def test_that_assinging_number_to_string_works(self):
script = textwrap.dedent(
@ -139,7 +140,7 @@ class TestCQGI(BaseTest):
"""
)
result = cqgi.parse(script).build( {'h': 33.33})
self.assertEquals(result.results[0], "33.33")
self.assertEquals(result.results[0].shape, "33.33")
def test_that_assigning_string_to_number_fails(self):
script = textwrap.dedent(
@ -181,7 +182,7 @@ class TestCQGI(BaseTest):
result = cqgi.parse(script).build()
self.assertTrue(result.success)
self.assertIsNotNone(result.first_result)
self.assertIsNotNone(result.first_result.shape)
def test_setting_boolean_variable(self):
script = textwrap.dedent(
@ -195,7 +196,7 @@ class TestCQGI(BaseTest):
result = cqgi.parse(script).build({'h': False})
self.assertTrue(result.success)
self.assertEquals(result.first_result,'*False*')
self.assertEquals(result.first_result.shape,'*False*')
def test_that_only_top_level_vars_are_detected(self):
script = textwrap.dedent(
@ -213,4 +214,4 @@ class TestCQGI(BaseTest):
model = cqgi.parse(script)
self.assertEquals(2, len(model.metadata.parameters))
self.assertEquals(2, len(model.metadata.parameters))