index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
44,331 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/harvesters/jsonharvester.py | #!/usr/bin/python
# -*- coding: utf8 -*-
from ckanext.harvest.model import HarvestObject
from ckanext.govdatade.harvesters.translator import translate_groups
from ckanext.govdatade.harvesters.ckanharvester import GovDataHarvester
import json
import logging
import uuid
import zipfile
import StringIO
import httplib
from urlparse import urlparse
log = logging.getLogger(__name__)
class JSONDumpBaseCKANHarvester(GovDataHarvester):
def info(self):
return {'name': 'base',
'title': 'Base Harvester',
'description': 'A Base CKAN Harvester for CKANs which return a JSON dump file.'}
def get_remote_dataset_names(self, content):
log.info('Calling JSONDumpBaseCKANHarvester get_remote_dataset_names..')
remote_datasets = json.loads(content)
remote_dataset_names = map(lambda d: d.get('name'), remote_datasets)
log.info('REMOTE_DATASET_NAMES: ' + str(remote_dataset_names))
return remote_dataset_names
def gather_stage(self, harvest_job):
self._set_config(harvest_job.source.config)
# Request all remote packages
try:
content = self._get_content(harvest_job.source.url)
except Exception, e:
self._save_gather_error('Unable to get content for URL: %s: %s' % (harvest_job.source.url, str(e)),
harvest_job)
return None
object_ids = []
packages = json.loads(content)
for package in packages:
obj = HarvestObject(guid=package['name'], job=harvest_job)
obj.content = json.dumps(package)
obj.save()
object_ids.append(obj.id)
context = self.build_context()
remote_dataset_names = self.get_remote_dataset_names(content)
self.delete_deprecated_datasets(context, remote_dataset_names)
if object_ids:
return object_ids
else:
self._save_gather_error('No packages received for URL: %s' % harvest_job.source.url,
harvest_job)
return None
def fetch_stage(self, harvest_object):
self._set_config(harvest_object.job.source.config)
if harvest_object.content:
return True
else:
return False
class BremenCKANHarvester(JSONDumpBaseCKANHarvester):
"""
A CKAN Harvester for Bremen. The Harvester retrieves a JSON dump,
which will be loaded to CKAN.
"""
PORTAL = 'http://daten.bremen.de/sixcms/detail.php?template=export_daten_json_d'
def info(self):
return {'name': 'bremen',
'title': 'Bremen CKAN Harvester',
'description': 'A CKAN Harvester for Bremen.'}
def amend_package(self, package):
"""
This function fixes some differences in the datasets retrieved from Bremen and our schema such as:
- fix groups
- set metadata_original_portal
- fix terms_of_use
- copy veroeffentlichende_stelle to maintainer
- set spatial text
"""
# set metadata original portal
package['extras'][
'metadata_original_portal'] = self.PORTAL
# set correct groups
if not package['groups']:
package['groups'] = []
package['groups'] = translate_groups(package['groups'], 'bremen')
# copy veroeffentlichende_stelle to maintainer
if 'contacts' in package['extras']:
quelle = filter(lambda x: x['role'] == 'veroeffentlichende_stelle', package['extras']['contacts'])[0]
package['maintainer'] = quelle['name']
package['maintainer_email'] = quelle['email']
# fix typos in terms of use
if 'terms_of_use' in package['extras']:
self.fix_terms_of_use(package['extras']['terms_of_use'])
# copy license id
package['license_id'] = package['extras']['terms_of_use']['license_id']
else:
package['license_id'] = u'notspecified'
if "spatial-text" not in package["extras"]:
package["extras"]["spatial-text"] = 'Bremen 04 0 11 000'
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
for resource in package['resources']:
resource['format'] = resource['format'].lower()
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(BremenCKANHarvester, self).import_stage(harvest_object)
def fix_terms_of_use(self, terms_of_use):
terms_of_use['license_id'] = terms_of_use['licence_id']
del (terms_of_use['licence_id'])
terms_of_use['license_url'] = terms_of_use['licence_url']
del (terms_of_use['licence_url'])
class BayernCKANHarvester(JSONDumpBaseCKANHarvester):
"""
A CKAN Harvester for Bavaria. The Harvester retrieves a JSON dump,
which will be loaded to CKAN.
"""
def info(self):
return {'name': 'bayern',
'title': 'Bavarian CKAN Harvester',
'description': 'A CKAN Harvester for Bavaria.'}
def amend_package(self, package):
if len(package['name']) > 100:
package['name'] = package['name'][:100]
if not package['groups']:
package['groups'] = []
# copy autor to author
quelle = {}
if 'contacts' in package['extras']:
quelle = filter(lambda x: x['role'] == 'autor', package['extras']['contacts'])[0]
if not package['author'] and quelle:
package['author'] = quelle['name']
if not package['author_email']:
if 'email' in quelle:
package['author_email'] = quelle['email']
if not "spatial-text" in package["extras"].keys():
package["extras"]["spatial-text"] = 'Bayern 09'
for r in package['resources']:
r['format'] = r['format'].upper()
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(BayernCKANHarvester, self).import_stage(harvest_object)
class MoersCKANHarvester(JSONDumpBaseCKANHarvester):
"""A CKAN Harvester for Moers solving data compatibility problems."""
PORTAL = 'http://www.offenedaten.moers.de/'
def info(self):
return {'name': 'moers',
'title': 'Moers Harvester',
'description': 'A CKAN Harvester for Moers solving data compatibility problems.'}
def amend_dataset_name(self, dataset):
dataset['name'] = dataset['name'].replace(u'ä', 'ae')
dataset['name'] = dataset['name'].replace(u'ü', 'ue')
dataset['name'] = dataset['name'].replace(u'ö', 'oe')
dataset['name'] = dataset['name'].replace('(', '')
dataset['name'] = dataset['name'].replace(')', '')
dataset['name'] = dataset['name'].replace('.', '')
dataset['name'] = dataset['name'].replace('/', '')
dataset['name'] = dataset['name'].replace('http://www.moers.de', '')
def amend_package(self, package):
publishers = filter(lambda x: x['role'] == 'veroeffentlichende_stelle', package['extras']['contacts'])
maintainers = filter(lambda x: x['role'] == 'ansprechpartner', package['extras']['contacts'])
if not publishers:
raise ValueError('There is no author email for package %s' % package['id'])
self.amend_dataset_name(package)
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['name'] = package['name'].lower()
if 'moers' not in package['title'].lower():
package['title'] += ' Moers'
package['author'] = 'Stadt Moers'
package['author_email'] = publishers[0]['email']
if maintainers:
package['maintainer'] = maintainers[0]['name']
package['maintainer_email'] = maintainers[0]['email']
package['license_id'] = package['extras']['terms_of_use']['license_id']
package['extras']['metadata_original_portal'] = self.PORTAL
if not "spatial-text" in package["extras"].keys():
package["extras"]["spatial-text"] = '05 1 70 024 Moers'
if isinstance(package['tags'], basestring):
if not package['tags']: # if tags was set to "" or null
package['tags'] = []
else:
package['tags'] = [package['tags']]
package['tags'].append('moers')
for resource in package['resources']:
resource['format'] = resource['format'].replace('text/comma-separated-values', 'xls')
resource['format'] = resource['format'].replace('application/json', 'json')
resource['format'] = resource['format'].replace('application/xml', 'xml')
for resource in package['resources']:
resource['format'] = resource['format'].lower()
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package_dict = json.loads(harvest_object.content)
try:
self.amend_package(package_dict)
except ValueError, e:
self._save_object_error(str(e), harvest_object)
log.error('Moers: ' + str(e))
return
harvest_object.content = json.dumps(package_dict)
super(MoersCKANHarvester, self).import_stage(harvest_object)
class GovAppsHarvester(JSONDumpBaseCKANHarvester):
"""
A CKAN Harvester for GovApps. The Harvester retrieves a JSON dump,
which will be loaded to CKAN.
"""
def info(self):
return {'name': 'govapps',
'title': 'GovApps Harvester',
'description': 'A CKAN Harvester for GovApps.'}
def amend_package(self, package):
if not package['groups']:
package['groups'] = []
# fix groups
if not package['groups']:
package['groups'] = []
package['groups'] = [x for x in translate_groups(package['groups'], 'govapps') if len(x) > 0]
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(GovAppsHarvester, self).import_stage(harvest_object)
class JSONZipBaseHarvester(JSONDumpBaseCKANHarvester):
def info(self):
return {'name': 'zipbase',
'title': 'Base Zip Harvester',
'description': 'A Harvester for Portals, which return JSON files in a zip file.'}
def gather_stage(self, harvest_job):
self._set_config(harvest_job.source.config)
# Request all remote packages
try:
content = self._get_content(harvest_job.source.url)
except Exception, e:
self._save_gather_error('Unable to get content for URL: %s: %s' % (harvest_job.source.url, str(e)),
harvest_job)
return None
object_ids = []
packages = []
file_content = StringIO.StringIO(content)
archive = zipfile.ZipFile(file_content, "r")
remote_dataset_names = []
for name in archive.namelist():
if name.endswith(".json"):
package = json.loads(archive.read(name))
packages.append(package)
remote_dataset_names.append(package['name'])
obj = HarvestObject(guid=package['name'], job=harvest_job)
obj.content = json.dumps(package)
obj.save()
object_ids.append(obj.id)
log.info('REMOTE_DATASET_NAMES: ' + str(remote_dataset_names))
context = self.build_context()
self.delete_deprecated_datasets(context, remote_dataset_names)
if object_ids:
return object_ids
else:
self._save_gather_error('No packages received for URL: %s' % harvest_job.source.url,
harvest_job)
return None
class BKGHarvester(JSONZipBaseHarvester):
PORTAL = 'http://ims.geoportal.de/'
def info(self):
return {'name': 'bkg',
'title': 'BKG CKAN Harvester',
'description': 'A CKAN Harvester for BKG.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
class DestatisZipHarvester(JSONZipBaseHarvester):
PORTAL = 'http://www-genesis.destatis.de/'
def info(self):
return {'name': 'destatis',
'title': 'Destatis CKAN Harvester',
'description': 'A CKAN Harvester for destatis.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
class RegionalStatistikZipHarvester(JSONZipBaseHarvester):
PORTAL = 'https://www.regionalstatistik.de/'
def info(self):
return {'name': 'regionalStatistik',
'title': 'RegionalStatistik CKAN Harvester',
'description': 'A CKAN Harvester for Regional Statistik.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
class SecondDestatisZipHarvester(JSONZipBaseHarvester):
PORTAL = 'http://destatis.de/'
def info(self):
return {'name': 'destatis2',
'title': 'Destatis CKAN Harvester',
'description': 'A CKAN Harvester for destatis.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
def gather_stage(self, harvest_job):
self._set_config(harvest_job.source.config)
# Request all remote packages
try:
content = self._get_content(harvest_job.source.url)
except Exception, e:
self._save_gather_error('Unable to get content for URL: %s: %s' % (harvest_job.source.url, str(e)),
harvest_job)
return None
object_ids = []
packages = []
file_content = StringIO.StringIO(content)
archive = zipfile.ZipFile(file_content, "r")
for name in archive.namelist():
if name.endswith(".json"):
_input = archive.read(name)
_input = _input.decode("utf-8-sig")
package = json.loads(_input)
packages.append(package)
obj = HarvestObject(guid=package['name'], job=harvest_job)
obj.content = json.dumps(package)
obj.save()
object_ids.append(obj.id)
context = self.build_context()
if object_ids:
return object_ids
else:
self._save_gather_error('No packages received for URL: %s' % harvest_job.source.url,
harvest_job)
return None
class SachsenZipHarvester(SecondDestatisZipHarvester):
PORTAL = 'http://www.statistik.sachsen.de/'
def info(self):
return {'name': 'sachsen',
'title': 'Sachsen Harvester',
'description': 'A CKAN Harvester for Sachsen.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
class BMBF_ZipHarvester(JSONDumpBaseCKANHarvester):
PORTAL = 'http://www.datenportal.bmbf.de/'
def info(self):
return {'name': 'bmbf',
'title': 'BMBF JSON zip Harvester',
'description': 'A JSON zip Harvester for BMBF.'}
def _set_config(self, config_str):
if config_str:
self.config = json.loads(config_str)
else:
self.config = {}
self.api_version = 1
self.config['api_version'] = 1
self.config['force_all'] = True
self.config['remote_groups'] = 'only_local'
self.config['user'] = 'bmbf-datenportal'
def amend_package(self, package):
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(BMBF_ZipHarvester, self).import_stage(harvest_object)
class BfJHarvester(JSONZipBaseHarvester):
PORTAL = 'https://www.bundesjustizamt.de'
def info(self):
return {'name': 'bfj',
'title': 'BfJ CKAN Harvester',
'description': 'A CKAN Harvester for BfJ.'}
def amend_package(self, package):
# generate id based on OID namespace and package name, this makes sure,
# that packages with the same name get the same id
package['id'] = str(uuid.uuid5(uuid.NAMESPACE_OID, str(package['name'])))
package['extras']['metadata_original_portal'] = self.PORTAL
for resource in package['resources']:
resource['format'] = resource['format'].lower()
def gather_stage(self, harvest_job):
self._set_config(harvest_job.source.config)
# Request all remote packages
try:
#split the url into base, path and query to set up a https connectino before downloading the *.zip
#url has to start with 'https://..'
parsed_uri = urlparse(harvest_job.source.url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
url = '{uri.path}?{uri.query}'.format(uri=parsed_uri)
conn = httplib.HTTPSConnection(domain)
conn.request("GET", url)
response = conn.getresponse()
content = response.read()
except Exception, e:
self._save_gather_error('Unable to get content for URL: %s: %s' % (harvest_job.source.url, str(e)),
harvest_job)
return None
object_ids = []
packages = []
file_content = StringIO.StringIO(content)
archive = zipfile.ZipFile(file_content, "r")
remote_dataset_names = []
for name in archive.namelist():
if name.endswith(".json"):
_input = archive.read(name)
_input = _input.decode("latin9")
package = json.loads(_input)
packages.append(package)
remote_dataset_names.append(package['name'])
obj = HarvestObject(guid=package['name'], job=harvest_job)
obj.content = json.dumps(package)
obj.save()
object_ids.append(obj.id)
context = self.build_context()
self.delete_deprecated_datasets(context, remote_dataset_names)
if object_ids:
return object_ids
else:
self._save_gather_error('No packages received for URL: %s' % harvest_job.source.url,
harvest_job)
return None
def import_stage(self, harvest_object):
package = json.loads(harvest_object.content)
self.amend_package(package)
harvest_object.content = json.dumps(package)
super(JSONZipBaseHarvester, self).import_stage(harvest_object)
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,332 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/commands/schema_checker.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ckan import model
from ckan.model import Session
from ckan.lib.cli import CkanCommand
from ckan.logic import get_action, NotFound
from ckan.logic.schema import default_package_schema
from ckanext.govdatade.config import CONFIG
from ckanext.govdatade.util import normalize_action_dataset
from ckanext.govdatade.util import iterate_local_datasets
from ckanext.govdatade.validators import schema_checker
from collections import defaultdict
from jinja2 import Environment, FileSystemLoader
from jsonschema.validators import Draft3Validator
from math import ceil
import ckanclient
class SchemaChecker(CkanCommand):
'''Validates datasets against the GovData.de JSON schema'''
summary = __doc__.split('\n')[0]
SCHEMA_URL = 'https://raw.github.com/fraunhoferfokus/ogd-metadata/master/OGPD_JSON_Schema.json' # NOQA
def __init__(self, name):
super(SchemaChecker, self).__init__(name)
def get_dataset_count(self, ckan):
print 'Retrieve total number of datasets'
return ckan.action('package_search', rows=1)['count']
def get_datasets(self, ckan, rows, i):
datasets = (i * 1000) + 1
print 'Retrieve datasets %s - %s' % (datasets, datasets + rows - 1)
records = ckan.action('package_search', rows=rows, start=rows * i)
return records['results']
def render_template(self, template_file, data):
template_dir = os.path.dirname(__file__)
template_dir = os.path.join(template_dir, '../../..', 'lib/templates')
template_dir = os.path.abspath(template_dir)
environment = Environment(loader=FileSystemLoader(template_dir))
template = environment.get_template(template_file)
return template.render(data)
def write_validation_result(self, rendered_template, template_file):
target_file = template_file.rstrip(".jinja2")
target_dir = CONFIG.get('validators', 'report_dir')
target_dir = os.path.join(target_dir, target_file)
target_dir = os.path.abspath(target_dir)
fd = open(target_dir, 'w')
fd.write(rendered_template.encode('UTF-8'))
fd.close()
def validate_datasets(self, dataset, data):
normalize_action_dataset(dataset)
identifier = dataset['id']
portal = dataset['extras'].get('metadata_original_portal', 'null')
data['broken_rules'][portal][identifier] = []
broken_rules = data['broken_rules'][portal][identifier]
data['datasets_per_portal'][portal].add(identifier)
errors = Draft3Validator(self.schema).iter_errors(dataset)
if Draft3Validator(self.schema).is_valid(dataset):
data['valid_datasets'] += 1
else:
data['invalid_datasets'] += 1
errors = Draft3Validator(self.schema).iter_errors(dataset)
for error in errors:
path = [e for e in error.path if isinstance(e, basestring)]
path = str(' -> '.join(map((lambda e: str(e)), path)))
data['field_paths'][path] += 1
field_path_message = [path, error.message]
broken_rules.append(field_path_message)
def create_context(self):
return {'model': model,
'session': Session,
'user': u'harvest',
'schema': default_package_schema,
'validate': False}
def command(self):
super(SchemaChecker, self)._load_config()
context = self.create_context()
data = {'field_paths': defaultdict(int),
'broken_rules': defaultdict(dict),
'datasets_per_portal': defaultdict(set),
'invalid_datasets': 0,
'valid_datasets': 0}
if len(self.args) == 0:
active_datasets = []
context = {'model': model,
'session': model.Session,
'ignore_auth': True}
validator = schema_checker.SchemaChecker()
num_datasets = 0
for i, dataset in enumerate(iterate_local_datasets(context)):
print 'Processing dataset %s' % i
normalize_action_dataset(dataset)
validator.process_record(dataset)
num_datasets += 1
active_datasets.append(dataset['id'])
delete_deprecated_violations(active_datasets)
general = {'num_datasets': num_datasets}
validator.redis_client.set('general', general)
elif len(self.args) == 2 and self.args[0] == 'specific':
context = {'model': model,
'session': model.Session,
'ignore_auth': True}
package_show = get_action('package_show')
dataset_name = self.args[1]
dataset = package_show(context, {'id': dataset_name})
print 'Processing dataset %s' % dataset
normalize_action_dataset(dataset)
validator = schema_checker.SchemaChecker()
validator.process_record(dataset)
elif len(self.args) == 2 and self.args[0] == 'remote':
endpoint = self.args[1]
ckan = ckanclient.CkanClient(base_location=endpoint)
rows = 1000
total = self.get_dataset_count(ckan)
steps = int(ceil(total / float(rows)))
for i in range(0, steps):
if i == steps - 1:
rows = total - (i * rows)
datasets = self.get_datasets(ckan, rows, i)
self.validate_datasets(datasets, data)
self.write_validation_result(self.render_template(data))
def delete_deprecated_violations(self, active_datasets):
redis_client = validator.redis.client
redis_dataset_ids = redis_client.keys()
for redis_id in redis_dataset_ids:
if redis_id not in active_datasets:
redis_client.delete(redis_id)
print 'deleted deprecated package %s from redis' % redis_id
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,333 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/harvesters/translator.py | #!/bin/env python
from ckanext.govdatade.config import CONFIG
import json
import urllib2
def translate_groups(groups, source_name):
url = 'https://raw.github.com/fraunhoferfokus/ogd-metadata/master/kategorien/' + source_name + '2deutschland.json'
json_string = urllib2.urlopen(url).read()
group_dict = json.loads(json_string)
result = []
for group in groups:
if group in group_dict:
result = result + group_dict[group]
return result
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,334 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/config.py | import ConfigParser
import os
# Make configuration file globally accessible
CONFIG = ConfigParser.ConfigParser()
config_file = os.path.dirname(__file__)
config_file = os.path.join(config_file, '../..', 'config.ini')
config_file = os.path.abspath(config_file)
CONFIG.read(config_file)
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,335 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/tests/test_validation.py | #!/usr/bin/python
# -*- coding: utf8 -*-
from jsonschema import validate, ValidationError
from nose.tools import raises
import json
import urllib2
class TestValidation:
SCHEMA_URL = 'https://raw.github.com/fraunhoferfokus/ogd-metadata/master/OGPD_JSON_Schema.json' # NOQA
def setup(self):
self.schema = json.loads(urllib2.urlopen(self.SCHEMA_URL).read())
@raises(ValidationError)
def test_empty_package(self):
validate({}, self.schema)
def test_minimal_package(self):
package = {'name': 'statistiken-2013',
'author': 'Eric Walter',
'notes': 'Statistiken von 2013.',
'title': 'Statistiken 2013',
'resources': [],
'groups': ['verwaltung'],
'license_id': 'cc-zero',
'type': 'app',
'extras': {'dates': []}}
validate(package, self.schema)
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,336 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/commands/report.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
from collections import defaultdict
from ckan.lib.cli import CkanCommand
from ckanext.govdatade.config import CONFIG
from ckanext.govdatade.util import copy_report_vendor_files
from ckanext.govdatade.util import copy_report_asset_files
from ckanext.govdatade.util import generate_link_checker_data
from ckanext.govdatade.util import generate_schema_checker_data
from ckanext.govdatade.util import generate_general_data
from ckanext.govdatade.util import amend_portal
from jinja2 import Environment, FileSystemLoader
import os
class Report(CkanCommand):
'''Generates metadata quality report based on Redis data.'''
summary = __doc__.split('\n')[0]
def __init__(self, name):
super(Report, self).__init__(name)
def generate_report(self):
data = defaultdict(defaultdict)
generate_general_data(data)
generate_link_checker_data(data)
generate_schema_checker_data(data)
copy_report_asset_files()
copy_report_vendor_files()
templates = ['index.html', 'linkchecker.html', 'schemachecker.html']
templates = map(lambda name: name + '.jinja2', templates)
for template_file in templates:
rendered_template = self.render_template(template_file, data)
self.write_validation_result(rendered_template, template_file)
def render_template(self, template_file, data):
template_dir = os.path.dirname(__file__)
template_dir = os.path.join(template_dir, '../../..', 'lib/templates')
template_dir = os.path.abspath(template_dir)
environment = Environment(loader=FileSystemLoader(template_dir))
environment.globals.update(amend_portal=amend_portal)
template = environment.get_template(template_file)
return template.render(data)
def write_validation_result(self, rendered_template, template_file):
target_file = template_file.rstrip(".jinja2")
target_dir = CONFIG.get('validators', 'report_dir')
target_dir = os.path.join(target_dir, target_file)
target_dir = os.path.abspath(target_dir)
fd = open(target_dir, 'w')
fd.write(rendered_template.encode('UTF-8'))
fd.close()
def command(self):
self.generate_report()
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,337 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/validators/schema_checker.py | import json
import urllib2
from jsonschema.validators import Draft3Validator
from jsonschema import FormatChecker
import redis
class SchemaChecker:
SCHEMA_URL = 'https://raw.github.com/fraunhoferfokus/ogd-metadata/master/OGPD_JSON_Schema.json' # NOQA
def __init__(self, db='production'):
redis_db_dict = {'production': 0, 'test': 1}
database = redis_db_dict[db]
self.schema = json.loads(urllib2.urlopen(self.SCHEMA_URL).read())
self.redis_client = redis.StrictRedis(host='localhost',
port=6379,
db=database)
def process_record(self, dataset):
dataset_id = dataset['id']
record = self.redis_client.get(dataset_id)
try:
record = eval(record)
print "RECORD_ID_____: ", record['id']
except:
print "EVAL_ERROR"
portal = dataset['extras'].get('metadata_original_portal', 'null')
if record is None:
record = {'id': dataset_id, 'metadata_original_portal': portal}
#fca print "if RECORD is NONE_________: ", record
record['schema'] = []
broken_rules = []
#fca else:
# try:
# record = eval(record)
# except:
# print "SECONDE_EVAL_ERROR_____: ", record
#errors = Draft3Validator(self.schema).iter_errors(dataset)
if not Draft3Validator(self.schema, format_checker=FormatChecker(('date-time',))).is_valid(dataset):
errors = Draft3Validator(self.schema, format_checker=FormatChecker(('date-time',))).iter_errors(dataset)
for error in errors:
path = [e for e in error.path if isinstance(e, basestring)]
path = str('.'.join(map((lambda e: str(e)), path)))
field_path_message = [path, error.message]
broken_rules.append(field_path_message)
dataset_groups = dataset['groups']
if (len(dataset_groups) >= 4):
path = "groups"
field_path_message = [path, "WARNING: too many groups set"]
broken_rules.append(field_path_message)
print "BROKEN_RULES_____: ", broken_rules
try:
record['schema'] = broken_rules
except:
print "SCHEMA_BROKEN_RULES_ERROR_____"
self.redis_client.set(dataset_id, record)
return not broken_rules
def get_records(self):
result = []
for dataset_id in self.redis_client.keys('*'):
if dataset_id == 'general':
continue
try:
result.append(eval(self.redis_client.get(dataset_id)))
except:
print "DS_errer_schema: ", dataset_id
return result
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,338 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/validators/link_checker.py | from datetime import datetime
import socket
import logging
import urllib2
import time
import redis
import requests
import codecs
log = logging.getLogger(__name__)
my_path="/tmp/measurement_linkchecker.log"
def logme(logText, path="/opt/linkChecker.log"):
with codecs.open(path, "a", "utf-8") as f:
f.write(logText + '\n')
class LinkChecker:
HEADERS = {'User-Agent': 'curl/7.29.0'}
TIMEOUT = 30.0
def __init__(self, db='production'):
redis_db_dict = {'production': 0, 'test': 1}
database = redis_db_dict[db]
self.redis_client = redis.StrictRedis(host='localhost',
port=6379,
db=database)
def process_record(self, dataset):
dataset_id = dataset['id']
delete = False
portal = None
if 'extras' in dataset and \
'metadata_original_portal' in dataset['extras']:
portal = dataset['extras']['metadata_original_portal']
logme("Beging link checking", my_path)
for resource in dataset['resources']:
logme("RESOURCE_URL: " + resource['url'], my_path)
start_time = time.time()
logme("Start time: "+ str(start_time), my_path)
url = resource['url']
url = url.replace('sequenz=tabelleErgebnis', 'sequenz=tabellen')
url = url.replace('sequenz=tabelleDownload', 'sequenz=tabellen')
try:
code = self.validate(url)
if self.is_available(code):
self.record_success(dataset_id, url)
else:
delete = delete or self.record_failure(dataset, url,
code, portal)
except requests.exceptions.Timeout:
delete = delete or self.record_failure(dataset, url,
'Timeout', portal)
except requests.exceptions.TooManyRedirects:
delete = delete or self.record_failure(dataset, url,
'Redirect Loop', portal)
except requests.exceptions.SSLError:
delete = delete or self.record_failure(dataset, url,'SSL Error', portal)
except requests.exceptions.RequestException as e:
if e is None:
delete = delete or self.record_failure(dataset, url,
'Unknown', portal)
else:
delete = delete or self.record_failure(dataset, url, str(e), portal)
except socket.timeout:
delete = delete or self.record_failure(dataset, url,
'Timeout', portal)
except ValueError as e:
self.record_success(dataset_id,url)
except Exception as e:
#In case of an unknown exception, change nothing
delete = delete or self.record_failure(dataset, url, 'Unknown', portal)
end_time = time.time()
logme("End time: "+ str(end_time),my_path)
logme("Total time: " + str(end_time-start_time),my_path)
logme("--------------------------", my_path)
logme("Rueckgabewert von process_record:"+str(delete), my_path)
return delete
def check_dataset(self, dataset):
results = []
for resource in dataset['resources']:
# logme("check_dataset: RESOURCE: " + resource['url'])
# fca results.append(self.validate(resource['url']))
url = resource['url']
url = url.replace('sequenz=tabelleErgebnis', 'sequenz=tabellen')
url = url.replace('sequenz=tabelleDownload', 'sequenz=tabellen')
results.append(self.validate(url))
# logme("check_dataset: RESOURCE: " + resource['url'])
# logme("check_dataset: RESULTS: " + results)
return results
def validate(self, url):
# logme(url)
# do not check datasets from saxony until fix
if "statistik.sachsen" in url:
return 200
elif "www.bundesjustizamt.de" in url:
headers = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, None, headers)
try:
respo = urllib2.urlopen(req)
return respo.code
except urllib2.URLError, e:
return e.code
else:
try:
response = requests.get(url, allow_redirects=True, stream=True, timeout=self.TIMEOUT,verify=False)
except requests.exceptions.SSLError:
logme("SSL_Error",my_path)
response = requests.head(url, allow_redirects=True, timeout=self.TIMEOUT)
response.raise_for_status()
size = 0
start = time.time()
maximum_response_size = 10485760
recieve_timeout = 35.0
for chunk in response.iter_content(1024):
if time.time() - start > recieve_timeout:
raise ValueError('timeout reached at'+ str(recieve_timeout))
size += len(chunk)
if size > maximum_response_size:
raise ValueError('response too large (bigger than '+ str(size)+')' )
return response.status_code
def is_available(self, response_code):
return response_code >= 200 and response_code < 300
def record_failure(self, dataset, url, status, portal,
date=datetime.now().date()):
dataset_id = dataset['id']
dataset_name = dataset['name']
delete = False
record = unicode(self.redis_client.get(dataset_id))
try:
record = eval(record)
except:
print "Record_error: ", record
initial_url_record = {'status': status,
'date': date.strftime("%Y-%m-%d"),
'strikes': 1}
if record is not None:
record['name'] = dataset_name
record['metadata_original_portal'] = portal
self.redis_client.set(dataset_id, record)
# Record is not known yet
if record is None:
record = {'id': dataset_id, 'name': dataset_name, 'urls': {}}
record['urls'][url] = initial_url_record
record['metadata_original_portal'] = portal
self.redis_client.set(dataset_id, record)
# Record is known, but only with schema errors
elif 'urls' not in record:
record['urls'] = {}
record['urls'][url] = initial_url_record
self.redis_client.set(dataset_id, record)
# Record is known, but not that particular URL (Resource)
elif url not in record['urls']:
record['urls'][url] = initial_url_record
self.redis_client.set(dataset_id, record)
# Record and URL are known, increment Strike counter if 1+ day(s) have
# passed since the last check
else:
url_entry = record['urls'][url]
last_updated = datetime.strptime(url_entry['date'], "%Y-%m-%d")
last_updated = last_updated.date()
if last_updated < date:
url_entry['status'] = status
url_entry['strikes'] += 1
url_entry['date'] = date.strftime("%Y-%m-%d")
self.redis_client.set(dataset_id, record)
delete = record['urls'][url]['strikes'] >= 100
return delete
def record_success(self, dataset_id, url):
record = self.redis_client.get(dataset_id)
if record is not None:
try:
record = eval(unicode(record))
except:
print "ConnError"
_type = type(record) is dict
# Remove URL entry due to working URL
if record.get('urls'):
record['urls'].pop(url, None)
# Remove record entry altogether if there are no failures
# anymore
if not record.get('urls'):
self.redis_client.delete(dataset_id)
else:
self.redis_client.set(dataset_id, record)
def get_records(self):
result = []
for dataset_id in self.redis_client.keys('*'):
# print "DS_id: ",dataset_id
if dataset_id == 'general':
continue
try:
result.append(eval(self.redis_client.get(dataset_id)))
except:
print "DS_error: ", dataset_id
return result
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,339 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/tests/test_normalize_extras.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ckanext.govdatade.util import normalize_extras
import json
def test_simple_json_object():
source = json.dumps({'a': '1', 'b': '2', 'c': '3'})
assert normalize_extras(source) == {'a': '1', 'b': '2', 'c': '3'}
def test_nested_json_object():
source = json.dumps({'a': {'b': {'c': {}}}})
assert normalize_extras(source) == {'a': {'b': {'c': {}}}}
def test_simple_json_array():
source = json.dumps(['1', '2', '3'])
assert normalize_extras(source) == ['1', '2', '3']
def test_nested_json_array():
array = ['1', '2', '3']
source = json.dumps([array] * 3)
assert normalize_extras(source) == [['1', '2', '3']] * 3
def test_invalid_json():
source = 'test'
assert normalize_extras(source) == 'test'
def test_string_encoded_integer():
source = json.dumps({'a': '1'})
assert normalize_extras(source) == {'a': '1'}
def test_string_encoded_float():
source = json.dumps({'a': '3.5'})
assert normalize_extras(source) == {'a': '3.5'}
def test_string_encoded_boolean():
source = json.dumps({'a': 'true'})
assert normalize_extras(source) == {'a': 'true'}
def test_string_encoded_string():
source = json.dumps({'a': '"string"'})
assert normalize_extras(source) == {'a': 'string'}
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,340 | fraunhoferfokus/ckanext-govdatade | refs/heads/master | /ckanext/govdatade/commands/link_checker.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import os
from jinja2 import Environment, FileSystemLoader
from ckan import model
from ckan.model import Session
from ckan.lib.cli import CkanCommand
from ckan.logic import get_action
from ckan.logic.schema import default_package_schema
from ckanext.govdatade.util import normalize_action_dataset
from ckan.lib.cli import CkanCommand
from ckanext.govdatade.config import CONFIG
from ckanext.govdatade.util import iterate_remote_datasets
from ckanext.govdatade.util import iterate_local_datasets
from ckanext.govdatade.util import generate_link_checker_data
from ckanext.govdatade.validators import link_checker
def logme(logText):
f = open('/tmp/linkCheckerCommand.log','a')
f.write(logText + '\n')
f.close
class LinkChecker(CkanCommand):
'''Checks the availability of the dataset's URLs'''
summary = __doc__.split('\n')[0]
def __init__(self, name):
super(LinkChecker, self).__init__(name)
def check_remote_host(self, endpoint):
checker = link_checker.LinkChecker()
num_urls = 0
num_success = 0
for i, dataset in enumerate(iterate_remote_datasets(endpoint)):
print 'Process %s' % i
for resource in dataset['resources']:
num_urls += 1
url = resource['url'].encode('utf-8')
response_code = checker.validate(url)
if checker.is_available(response_code):
num_success += 1
def generate_report(self):
data = {}
generate_link_checker_data(data)
self.write_report(self.render_template(data))
def render_template(self, data):
template_file = 'linkchecker-report.html.jinja2'
template_dir = os.path.dirname(__file__)
template_dir = os.path.join(template_dir, '../../..', 'lib/templates')
template_dir = os.path.abspath(template_dir)
environment = Environment(loader=FileSystemLoader(template_dir))
template = environment.get_template(template_file)
return template.render(data)
def write_report(self, rendered_template):
target_dir = CONFIG.get('validators', 'report_dir')
target_dir = os.path.abspath(target_dir)
output = os.path.join(target_dir, 'linkchecker.html')
fd = open(output, 'w')
fd.write(rendered_template.encode('UTF-8'))
fd.close()
def create_context(self):
return {'model': model,
'session': Session,
'user': u'harvest',
'schema': default_package_schema,
'validate': False}
def command(self):
super(LinkChecker,self)._load_config()
active_datasets = set()
if len(self.args) == 0:
context = {'model': model,
'session': model.Session,
'ignore_auth': True}
validator = link_checker.LinkChecker()
num_datasets = 0
for i, dataset in enumerate(iterate_local_datasets(context)):
print 'Processing dataset %s with name: %s' % (i,dataset['name'])
normalize_action_dataset(dataset)
validator.process_record(dataset)
num_datasets += 1
active_datasets.add(dataset['id'])
self.delete_deprecated_datasets(active_dataset_ids)
general = {'num_datasets': num_datasets}
validator.redis_client.set('general', general)
if len(self.args) > 0:
subcommand = self.args[0]
if subcommand == 'remote':
self.check_remote_host(self.args[1])
elif subcommand == 'report':
self.generate_report()
elif len(self.args) == 2 and self.args[0] == 'specific':
dataset_name = self.args[1]
context = {'model': model,
'session': model.Session,
'ignore_auth': True}
package_show = get_action('package_show')
validator = link_checker.LinkChecker()
dataset = package_show(context, {'id': dataset_name})
print 'Processing dataset %s' % dataset
normalize_action_dataset(dataset)
validator.process_record(dataset)
def delete_deprecated_datasets(self, dataset_ids):
validator = link_checker.LinkChecker()
redis_ids = validator.redis_client.keys()
for redis_id in redis_ids:
if not redis_id in dataset_ids:
validator.redis_client.delete(redis_id)
logme('***Removing deprecated dataset '+str(redis_id)+' from Redis***')
| {"/ckanext/govdatade/tests/test_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py", "/ckanext/govdatade/harvesters/jsonharvester.py"], "/ckanext/govdatade/tests/test_datahub_harvester.py": ["/ckanext/govdatade/harvesters/ckanharvester.py"], "/ckanext/govdatade/harvesters/translator.py": ["/ckanext/govdatade/config.py"], "/ckanext/govdatade/commands/report.py": ["/ckanext/govdatade/config.py", "/ckanext/govdatade/util.py"], "/ckanext/govdatade/tests/test_normalize_extras.py": ["/ckanext/govdatade/util.py"]} |
44,419 | abeillebuzz/learning_to_test_code | refs/heads/master | /employee.py | class Employee():
"""Collect employee data and give info about salary."""
def __init__(self, first_name, last_name, salary):
"""Store employee info."""
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, increase=5000):
"""Add raise to annual salary."""
salary += increase
return salary
| {"/test_employee.py": ["/employee.py"]} |
44,420 | abeillebuzz/learning_to_test_code | refs/heads/master | /test_employee.py | import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Tests for the class Employee."""
def setUp(self):
"""
Create an employee and salary for use in all test methods.
"""
first_name = 'tiffany'
last_name = 'gay'
salary = 51000
self.sample_employee = Employee(first_name, last_name, salary)
def test_give_default_raise(self):
"""Test that give_raise method works with default raise value."""
self.sample_employee.give_raise()
self.assertEqual(56000, self.sample_employee.salary)
def test_give_custom_raise(self):
"""Test that give_raise method works with custom raise value."""
self.sample_employee.give_raise(7000)
self.assertEqual(58000, self.sample_employee.salary)
unittest.main()
| {"/test_employee.py": ["/employee.py"]} |
44,431 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/admin.py | from django.contrib import admin
from metrics.models import Metric, Data
admin.site.register(Metric)
admin.site.register(Data)
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,432 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/management/commands/fetch.py | # -*- coding: utf-8 -*-
from django.core.management.base import NoArgsCommand
from metrics.models import Metric
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
for metric in Metric.objects.all():
metric.fetch()
return u"ok!"
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,433 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/tests/test_index_view.py | from django.test import TestCase
class IndexViewTestCase(TestCase):
def test_should_have_metrics_on_context(self):
response = self.client.get("/")
self.assertIn("object_list", response.context)
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,434 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/views.py | from django.views.generic import ListView
from metrics.models import Metric
class Index(ListView):
model = Metric
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,435 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/tests/test_metric_model.py | from django.test import TestCase
from metrics.models import Metric
import mock
class MetricModelTestCase(TestCase):
def test_should_have_name_field(self):
fields = Metric._meta.get_all_field_names()
self.assertIn("name", fields)
def test_should_have_url_field(self):
fields = Metric._meta.get_all_field_names()
self.assertIn("url", fields)
def test_fetch_should_add_data(self):
metric = Metric.objects.create(
name="issues",
url="https://api.github.com/repos/globocom/tsuru"
)
with mock.patch("requests.get") as get:
get.return_value = mock.Mock(json={"open_issues": 105})
metric.fetch()
data = metric.data_set.all()[0]
self.assertEqual(105, data.count)
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,436 | hfeeki/tsuru-dev-dashboard | refs/heads/master | /metrics/models.py | from django.db import models
from datetime import datetime
import requests
class Metric(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
def fetch(self):
result = requests.get(self.url)
Data.objects.create(
metric=self,
count=result.json["open_issues"]
)
class Data(models.Model):
metric = models.ForeignKey(Metric)
count = models.IntegerField()
date = models.DateTimeField(default=datetime.now)
| {"/metrics/admin.py": ["/metrics/models.py"], "/metrics/management/commands/fetch.py": ["/metrics/models.py"], "/metrics/views.py": ["/metrics/models.py"], "/metrics/tests/test_metric_model.py": ["/metrics/models.py"]} |
44,437 | Timfts/opencv-exercises | refs/heads/master | /cv_proj/main.py | from .chapters.one import display_img, use_webcam
# chapter one
# display_img()
use_webcam() | {"/cv_proj/main.py": ["/cv_proj/chapters/one/__init__.py"]} |
44,438 | Timfts/opencv-exercises | refs/heads/master | /cv_proj/chapters/one/__init__.py | import cv2
def display_img():
img = cv2.imread("resources/paint.jpg")
cv2.imshow("output", img)
cv2.waitKey(0)
def use_webcam():
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
cap.set(10, 100)
while True:
success, img = cap.read()
cv2.imshow("Video", img)
if cv2.waitKey(1) & 0xDD ==ord('q'):
break | {"/cv_proj/main.py": ["/cv_proj/chapters/one/__init__.py"]} |
44,465 | CadQuery/cadquery | refs/heads/master | /cadquery/hull.py | from typing import List, Tuple, Union, Iterable, Set
from math import pi, sin, cos, atan2, sqrt, inf, degrees
from numpy import lexsort, argmin, argmax
from .occ_impl.shapes import Edge, Wire
from .occ_impl.geom import Vector
"""
Convex hull for line segments and circular arcs based on
Yue, Y., Murray, J. L., Corney, J. R., & Clark, D. E. R. (1999).
Convex hull of a planar set of straight and circular line segments. Engineering Computations.
"""
Arcs = List["Arc"]
Points = List["Point"]
Entity = Union["Arc", "Point"]
Hull = List[Union["Arc", "Point", "Segment"]]
class Point:
x: float
y: float
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return f"( {self.x},{self.y} )"
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
class Segment:
a: Point
b: Point
def __init__(self, a: Point, b: Point):
self.a = a
self.b = b
class Arc:
c: Point
s: Point
e: Point
r: float
a1: float
a2: float
ac: float
def __init__(self, c: Point, r: float, a1: float, a2: float):
self.c = c
self.r = r
self.a1 = a1
self.a2 = a2
self.s = Point(r * cos(a1), r * sin(a1))
self.e = Point(r * cos(a2), r * sin(a2))
self.ac = 2 * pi - (a1 - a2)
def atan2p(x, y):
rv = atan2(y, x)
if rv < 0:
rv = (2 * pi + rv) % (2 * pi)
return rv
def convert_and_validate(edges: Iterable[Edge]) -> Tuple[List[Arc], List[Point]]:
arcs: Set[Arc] = set()
points: Set[Point] = set()
for e in edges:
gt = e.geomType()
if gt == "LINE":
p1 = e.startPoint()
p2 = e.endPoint()
points.update((Point(p1.x, p1.y), Point(p2.x, p2.y)))
elif gt == "CIRCLE":
c = e.arcCenter()
r = e.radius()
a1, a2 = e._bounds()
arcs.add(Arc(Point(c.x, c.y), r, a1, a2))
else:
raise ValueError("Unsupported geometry {gt}")
return list(arcs), list(points)
def select_lowest_point(points: Points) -> Tuple[Point, int]:
x = []
y = []
for p in points:
x.append(p.x)
y.append(p.y)
# select the lowest point
ixs = lexsort((x, y))
return points[ixs[0]], ixs[0]
def select_lowest_arc(arcs: Arcs) -> Tuple[Point, Arc]:
x = []
y = []
for a in arcs:
if a.a1 < 1.5 * pi and a.a2 > 1.5 * pi:
x.append(a.c.x)
y.append(a.c.y - a.r)
else:
p, _ = select_lowest_point([a.s, a.e])
x.append(p.x)
y.append(p.y)
ixs = lexsort((x, y))
return Point(x[ixs[0]], y[ixs[0]]), arcs[ixs[0]]
def select_lowest(arcs: Arcs, points: Points) -> Entity:
rv: Entity
p_lowest = select_lowest_point(points) if points else None
a_lowest = select_lowest_arc(arcs) if arcs else None
if p_lowest is None and a_lowest:
rv = a_lowest[1]
elif p_lowest is not None and a_lowest is None:
rv = p_lowest[0]
elif p_lowest and a_lowest:
_, ix = select_lowest_point([p_lowest[0], a_lowest[0]])
rv = p_lowest[0] if ix == 0 else a_lowest[1]
else:
raise ValueError("No entities specified")
return rv
def pt_pt(p1: Point, p2: Point) -> Tuple[float, Segment]:
angle = 0
dx, dy = p2.x - p1.x, p2.y - p1.y
if (dx, dy) != (0, 0):
angle = atan2p(dx, dy)
return angle, Segment(p1, p2)
def _pt_arc(p: Point, a: Arc) -> Tuple[float, float, float, float]:
x, y = p.x, p.y
r = a.r
xc, yc = a.c.x, a.c.y
dx, dy = x - xc, y - yc
l = sqrt(dx ** 2 + dy ** 2)
x1 = r ** 2 / l ** 2 * dx - r / l ** 2 * sqrt(l ** 2 - r ** 2) * dy + xc
y1 = r ** 2 / l ** 2 * dy + r / l ** 2 * sqrt(l ** 2 - r ** 2) * dx + yc
x2 = r ** 2 / l ** 2 * dx + r / l ** 2 * sqrt(l ** 2 - r ** 2) * dy + xc
y2 = r ** 2 / l ** 2 * dy - r / l ** 2 * sqrt(l ** 2 - r ** 2) * dx + yc
return x1, y1, x2, y2
def pt_arc(p: Point, a: Arc) -> Tuple[float, Segment]:
x, y = p.x, p.y
x1, y1, x2, y2 = _pt_arc(p, a)
angles = atan2p(x1 - x, y1 - y), atan2p(x2 - x, y2 - y)
points = Point(x1, y1), Point(x2, y2)
ix = int(argmin(angles))
return angles[ix], Segment(p, points[ix])
def arc_pt(a: Arc, p: Point) -> Tuple[float, Segment]:
x, y = p.x, p.y
x1, y1, x2, y2 = _pt_arc(p, a)
angles = atan2p(x - x1, y - y1), atan2p(x - x2, y - y2)
points = Point(x1, y1), Point(x2, y2)
ix = int(argmax(angles))
return angles[ix], Segment(points[ix], p)
def arc_arc(a1: Arc, a2: Arc) -> Tuple[float, Segment]:
r1 = a1.r
xc1, yc1 = a1.c.x, a1.c.y
r2 = a2.r
xc2, yc2 = a2.c.x, a2.c.y
# construct tangency points for a related point-circle problem
if r1 > r2:
arc_tmp = Arc(a1.c, r1 - r2, a1.a1, a1.a2)
xtmp1, ytmp1, xtmp2, ytmp2 = _pt_arc(a2.c, arc_tmp)
delta_r = r1 - r2
dx1 = (xtmp1 - xc1) / delta_r
dy1 = (ytmp1 - yc1) / delta_r
dx2 = (xtmp2 - xc1) / delta_r
dy2 = (ytmp2 - yc1) / delta_r
elif r1 < r2:
arc_tmp = Arc(a2.c, r2 - r1, a2.a1, a2.a2)
xtmp1, ytmp1, xtmp2, ytmp2 = _pt_arc(a1.c, arc_tmp)
delta_r = r2 - r1
dx1 = (xtmp1 - xc2) / delta_r
dy1 = (ytmp1 - yc2) / delta_r
dx2 = (xtmp2 - xc2) / delta_r
dy2 = (ytmp2 - yc2) / delta_r
else:
dx = xc2 - xc1
dy = yc2 - yc1
l = sqrt(dx ** 2 + dy ** 2)
dx /= l
dy /= l
dx1 = -dy
dy1 = dx
dx2 = dy
dy2 = -dx
# construct the tangency points and angles
x11 = xc1 + dx1 * r1
y11 = yc1 + dy1 * r1
x12 = xc1 + dx2 * r1
y12 = yc1 + dy2 * r1
x21 = xc2 + dx1 * r2
y21 = yc2 + dy1 * r2
x22 = xc2 + dx2 * r2
y22 = yc2 + dy2 * r2
a1_out = atan2p(x21 - x11, y21 - y11)
a2_out = atan2p(x22 - x12, y22 - y12)
# select the feasible angle
a11 = (atan2p(x11 - xc1, y11 - yc1) + pi / 2) % (2 * pi)
a21 = (atan2p(x12 - xc1, y12 - yc1) + pi / 2) % (2 * pi)
ix = int(argmin((abs(a11 - a1_out), abs(a21 - a2_out))))
angles = (a1_out, a2_out)
segments = (
Segment(Point(x11, y11), Point(x21, y21)),
Segment(Point(x12, y12), Point(x22, y22)),
)
return angles[ix], segments[ix]
def get_angle(current: Entity, e: Entity) -> Tuple[float, Segment]:
if current is e:
return inf, Segment(Point(inf, inf), Point(inf, inf))
if isinstance(current, Point):
if isinstance(e, Point):
return pt_pt(current, e)
else:
return pt_arc(current, e)
else:
if isinstance(e, Point):
return arc_pt(current, e)
else:
return arc_arc(current, e)
def update_hull(
current_e: Entity,
ix: int,
entities: List[Entity],
angles: List[float],
segments: List[Segment],
hull: Hull,
) -> Tuple[Entity, float, bool]:
next_e = entities[ix]
connecting_seg = segments[ix]
if isinstance(next_e, Point):
entities.pop(ix)
hull.extend((connecting_seg, next_e))
return next_e, angles[ix], next_e is hull[0]
def finalize_hull(hull: Hull) -> Wire:
rv = []
for el_p, el, el_n in zip(hull, hull[1:], hull[2:]):
if isinstance(el, Segment):
rv.append(Edge.makeLine(Vector(el.a.x, el.a.y), Vector(el.b.x, el.b.y)))
elif (
isinstance(el, Arc)
and isinstance(el_p, Segment)
and isinstance(el_n, Segment)
):
a1 = degrees(atan2p(el_p.b.x - el.c.x, el_p.b.y - el.c.y))
a2 = degrees(atan2p(el_n.a.x - el.c.x, el_n.a.y - el.c.y))
rv.append(
Edge.makeCircle(el.r, Vector(el.c.x, el.c.y), angle1=a1, angle2=a2)
)
el1 = hull[1]
if isinstance(el, Segment) and isinstance(el_n, Arc) and isinstance(el1, Segment):
a1 = degrees(atan2p(el.b.x - el_n.c.x, el.b.y - el_n.c.y))
a2 = degrees(atan2p(el1.a.x - el_n.c.x, el1.a.y - el_n.c.y))
rv.append(
Edge.makeCircle(el_n.r, Vector(el_n.c.x, el_n.c.y), angle1=a1, angle2=a2)
)
return Wire.assembleEdges(rv)
def find_hull(edges: Iterable[Edge]) -> Wire:
# initialize the hull
rv: Hull = []
# split into arcs and points
arcs, points = convert_and_validate(edges)
# select the starting element
start = select_lowest(arcs, points)
rv.append(start)
# initialize
entities: List[Entity] = []
entities.extend(arcs)
entities.extend(points)
current_e = start
current_angle = 0.0
finished = False
# march around
while not finished:
angles = []
segments = []
for e in entities:
angle, segment = get_angle(current_e, e)
angles.append(angle if angle >= current_angle else inf)
segments.append(segment)
next_ix = int(argmin(angles))
current_e, current_angle, finished = update_hull(
current_e, next_ix, entities, angles, segments, rv
)
# convert back to Edges and return
return finalize_hull(rv)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,466 | CadQuery/cadquery | refs/heads/master | /examples/Ex017_Shelling_to_Create_Thin_Features.py | import cadquery as cq
# Create a hollow box that's open on both ends with a thin wall.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects faces with normal in +z direction.
# 4. Create a shell by cutting out the top-most Z face.
result = cq.Workplane("front").box(2, 2, 2).faces("+Z").shell(0.05)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,467 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/threemf.py | from datetime import datetime
from os import PathLike
import xml.etree.cElementTree as ET
from typing import IO, List, Literal, Tuple, Union
from zipfile import ZipFile, ZIP_DEFLATED, ZIP_STORED
from ...cq import Compound, Shape, Vector
class CONTENT_TYPES(object):
MODEL = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"
RELATION = "application/vnd.openxmlformats-package.relationships+xml"
class SCHEMAS(object):
CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types"
RELATION = "http://schemas.openxmlformats.org/package/2006/relationships"
CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
Unit = Literal["micron", "millimeter", "centimeter", "meter", "inch", "foot"]
class ThreeMFWriter(object):
def __init__(
self,
shape: Shape,
tolerance: float,
angularTolerance: float,
unit: Unit = "millimeter",
):
"""
Initialize the writer.
Used to write the given Shape to a 3MF file.
"""
self.unit = unit
if isinstance(shape, Compound):
shapes = list(shape)
else:
shapes = [shape]
tessellations = [s.tessellate(tolerance, angularTolerance) for s in shapes]
# Remove shapes that did not tesselate
self.tessellations = [t for t in tessellations if all(t)]
def write3mf(
self, outfile: Union[PathLike, str, IO[bytes]],
):
"""
Write to the given file.
"""
try:
import zlib
compression = ZIP_DEFLATED
except ImportError:
compression = ZIP_STORED
with ZipFile(outfile, "w", compression) as zf:
zf.writestr("_rels/.rels", self._write_relationships())
zf.writestr("[Content_Types].xml", self._write_content_types())
zf.writestr("3D/3dmodel.model", self._write_3d())
def _write_3d(self) -> str:
no_meshes = len(self.tessellations)
model = ET.Element(
"model", {"xml:lang": "en-US", "xmlns": SCHEMAS.CORE,}, unit=self.unit,
)
# Add meta data
ET.SubElement(
model, "metadata", name="Application"
).text = "CadQuery 3MF Exporter"
ET.SubElement(
model, "metadata", name="CreationDate"
).text = datetime.now().isoformat()
resources = ET.SubElement(model, "resources")
# Add all meshes to resources
for i, tessellation in enumerate(self.tessellations):
self._add_mesh(resources, str(i), tessellation)
# Create a component of all meshes
comp_object = ET.SubElement(
resources,
"object",
id=str(no_meshes),
name=f"CadQuery Component",
type="model",
)
components = ET.SubElement(comp_object, "components")
# Add all meshes to the component
for i in range(no_meshes):
ET.SubElement(
components, "component", objectid=str(i),
)
# Add the component to the build
build = ET.SubElement(model, "build")
ET.SubElement(build, "item", objectid=str(no_meshes))
return ET.tostring(model, xml_declaration=True, encoding="utf-8")
def _add_mesh(
self,
to: ET.Element,
id: str,
tessellation: Tuple[List[Vector], List[Tuple[int, int, int]]],
):
object = ET.SubElement(
to, "object", id=id, name=f"CadQuery Shape {id}", type="model"
)
mesh = ET.SubElement(object, "mesh")
# add vertices
vertices = ET.SubElement(mesh, "vertices")
for v in tessellation[0]:
ET.SubElement(vertices, "vertex", x=str(v.x), y=str(v.y), z=str(v.z))
# add triangles
volume = ET.SubElement(mesh, "triangles")
for t in tessellation[1]:
ET.SubElement(volume, "triangle", v1=str(t[0]), v2=str(t[1]), v3=str(t[2]))
def _write_content_types(self) -> str:
root = ET.Element("Types")
root.set("xmlns", SCHEMAS.CONTENT_TYPES)
ET.SubElement(
root,
"Override",
PartName="/3D/3dmodel.model",
ContentType=CONTENT_TYPES.MODEL,
)
ET.SubElement(
root,
"Override",
PartName="/_rels/.rels",
ContentType=CONTENT_TYPES.RELATION,
)
return ET.tostring(root, xml_declaration=True, encoding="utf-8")
def _write_relationships(self) -> str:
root = ET.Element("Relationships")
root.set("xmlns", SCHEMAS.RELATION)
ET.SubElement(
root,
"Relationship",
Target="/3D/3dmodel.model",
Id="rel-1",
Type=SCHEMAS.MODEL,
TargetMode="Internal",
)
return ET.tostring(root, xml_declaration=True, encoding="utf-8")
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,468 | CadQuery/cadquery | refs/heads/master | /tests/test_sketch.py | import os
from cadquery.sketch import Sketch, Vector, Location
from cadquery.selectors import LengthNthSelector
from pytest import approx, raises
from math import pi, sqrt
testdataDir = os.path.join(os.path.dirname(__file__), "testdata")
def test_face_interface():
s1 = Sketch().rect(1, 2, 45)
assert s1._faces.Area() == approx(2)
assert s1.vertices(">X")._selection[0].toTuple()[0] == approx(1.5 / sqrt(2))
s2 = Sketch().circle(1)
assert s2._faces.Area() == approx(pi)
s3 = Sketch().ellipse(2, 0.5)
assert s3._faces.Area() == approx(pi)
s4 = Sketch().trapezoid(2, 0.5, 45)
assert s4._faces.Area() == approx(0.75)
s4 = Sketch().trapezoid(2, 0.5, 45)
assert s4._faces.Area() == approx(0.75)
s5 = Sketch().slot(3, 2)
assert s5._faces.Area() == approx(6 + pi)
assert s5.edges(">Y")._selection[0].Length() == approx(3)
s6 = Sketch().regularPolygon(1, 5)
assert len(s6.vertices()._selection) == 5
assert s6.vertices(">Y")._selection[0].toTuple()[1] == approx(1)
s7 = Sketch().polygon([(0, 0), (0, 1), (1, 0)])
assert len(s7.vertices()._selection) == 3
assert s7._faces.Area() == approx(0.5)
with raises(ValueError):
Sketch().face(Sketch().rect(1, 1)._faces)
def test_modes():
s1 = Sketch().rect(2, 2).rect(1, 1, mode="a")
assert s1._faces.Area() == approx(4)
assert len(s1._faces.Faces()) == 2
s2 = Sketch().rect(2, 2).rect(1, 1, mode="s")
assert s2._faces.Area() == approx(4 - 1)
assert len(s2._faces.Faces()) == 1
s3 = Sketch().rect(2, 2).rect(1, 1, mode="i")
assert s3._faces.Area() == approx(1)
assert len(s3._faces.Faces()) == 1
s4 = Sketch().rect(2, 2).rect(1, 1, mode="c", tag="t")
assert s4._faces.Area() == approx(4)
assert len(s4._faces.Faces()) == 1
assert s4._tags["t"][0].Area() == approx(1)
with raises(ValueError):
Sketch().rect(2, 2).rect(1, 1, mode="c")
with raises(ValueError):
Sketch().rect(2, 2).rect(1, 1, mode="dummy")
def test_distribute():
with raises(ValueError):
Sketch().rect(2, 2).faces().distribute(5)
with raises(ValueError):
Sketch().rect(2, 2).distribute(5)
with raises(ValueError):
Sketch().circle(1).wires().distribute(0, 0, 1)
s1 = Sketch().circle(4, mode="c", tag="c").edges(tag="c").distribute(3)
assert len(s1._selection) == approx(3)
s1.rect(1, 1)
assert s1._faces.Area() == approx(3)
assert len(s1._faces.Faces()) == 3
assert len(s1.reset().vertices("<X")._selection) == 2
for f in s1._faces.Faces():
assert f.Center().Length == approx(4)
s2 = (
Sketch()
.circle(4, mode="c", tag="c")
.edges(tag="c")
.distribute(3, rotate=False)
.rect(1, 1)
)
assert s2._faces.Area() == approx(3)
assert len(s2._faces.Faces()) == 3
assert len(s2.reset().vertices("<X")._selection) == 4
for f in s2._faces.Faces():
assert f.Center().Length == approx(4)
s3 = (
Sketch().circle(4, mode="c", tag="c").edges(tag="c").distribute(3, 0.625, 0.875)
)
assert len(s3._selection) == approx(3)
s3.rect(1, 0.5).reset().vertices("<X")
assert s3._selection[0].toTuple() == approx(
(-3.358757210636101, -3.005203820042827, 0.0)
)
s3.reset().vertices(">X")
assert s3._selection[0].toTuple() == approx(
(3.358757210636101, -3.005203820042827, 0.0)
)
s4 = Sketch().arc((0, 0), 4, 180, 180).edges().distribute(3, 0.25, 0.75)
assert len(s4._selection) == approx(3)
s4.rect(1, 0.5).reset().faces("<X").vertices("<X")
assert s4._selection[0].toTuple() == approx(
(-3.358757210636101, -3.005203820042827, 0.0)
)
s4.reset().faces(">X").vertices(">X")
assert s4._selection[0].toTuple() == approx(
(3.358757210636101, -3.005203820042827, 0.0)
)
s5 = (
Sketch()
.arc((0, 2), 4, 0, 90)
.arc((0, -2), 4, 0, -90)
.edges()
.distribute(4, 0, 1)
.circle(0.5)
)
assert len(s5._selection) == approx(8)
s5.reset().faces(">X").faces(">Y")
assert s5._selection[0].Center().toTuple() == approx((4.0, 2.0, 0.0))
s5.reset().faces(">X").faces("<Y")
assert s5._selection[0].Center().toTuple() == approx((4.0, -2.0, 0.0))
s5.reset().faces(">Y")
assert s5._selection[0].Center().toTuple() == approx((0.0, 6.0, 0.0))
def test_rarray():
with raises(ValueError):
Sketch().rarray(2, 2, 3, 0).rect(1, 1)
s1 = Sketch().rarray(2, 2, 3, 3).rect(1, 1)
assert s1._faces.Area() == approx(9)
assert len(s1._faces.Faces()) == 9
s2 = Sketch().push([(0, 0), (1, 1)]).rarray(2, 2, 3, 3).rect(0.5, 0.5)
assert s2._faces.Area() == approx(18 * 0.25)
assert len(s2._faces.Faces()) == 18
assert s2.reset().vertices(">(1,1,0)")._selection[0].toTuple() == approx(
(3.25, 3.25, 0)
)
def test_parray():
with raises(ValueError):
Sketch().parray(2, 0, 90, 0).rect(1, 1)
s1 = Sketch().parray(2, 0, 90, 3).rect(1, 1)
assert s1._faces.Area() == approx(3)
assert len(s1._faces.Faces()) == 3
s2 = Sketch().push([(0, 0), (1, 1)]).parray(2, 0, 90, 3).rect(0.5, 0.5)
assert s2._faces.Area() == approx(6 * 0.25)
assert len(s2._faces.Faces()) == 6
s3 = Sketch().parray(2, 0, 90, 3, False).rect(0.5, 0.5).reset().vertices(">(1,1,0)")
assert len(s3._selection) == 1
assert s3._selection[0].toTuple() == approx(
(1.6642135623730951, 1.664213562373095, 0.0)
)
s4 = Sketch().push([(0, 0), (0, 1)]).parray(2, 0, 90, 3).rect(0.5, 0.5)
s4.reset().faces(">(0,1,0)")
assert s4._selection[0].Center().Length == approx(3)
s5 = Sketch().push([(0, 1)], tag="loc")
assert len(s5._tags["loc"]) == 1
s6 = Sketch().push([(-4, 1), (0, 0), (4, -1)]).parray(2, 10, 50, 3).rect(1.0, 0.5)
s6.reset().vertices(">(-1,0,0)")
assert s6._selection[0].toTuple() == approx(
(-3.46650635094611, 2.424038105676658, 0.0)
)
s6.reset().vertices(">(1,0,0)")
assert s6._selection[0].toTuple() == approx(
(6.505431426947252, -0.8120814940857262, 0.0)
)
s7 = Sketch().parray(1, 135, 0, 1).circle(0.1)
s7.reset().faces()
assert len(s7._selection) == 1
assert s7._selection[0].Center().toTuple() == approx(
(-0.7071067811865475, 0.7071067811865476, 0.0)
)
s8 = Sketch().parray(4, 20, 360, 6).rect(1.0, 0.5)
assert len(s8._faces.Faces()) == 6
s8.reset().vertices(">(0,-1,0)")
assert s8._selection[0].toTuple() == approx(
(-0.5352148612481344, -4.475046932971669, 0.0)
)
s9 = (
Sketch()
.push([(-4, 1)])
.circle(0.1)
.reset()
.faces()
.parray(2, 10, 50, 3)
.rect(1.0, 0.5, 40, "a", "rects")
)
assert len(s9._faces.Faces()) == 4
s9.reset().vertices(">(-1,0,0)", tag="rects")
assert s9._selection[0].toTuple() == approx(
(-3.3330260270865173, 3.1810426396582487, 0.0)
)
def test_each():
s1 = Sketch().each(lambda l: Sketch().push([l]).rect(1, 1))
assert len(s1._faces.Faces()) == 1
s2 = (
Sketch()
.push([(0, 0), (2, 2)])
.each(lambda l: Sketch().push([l]).rect(1, 1), ignore_selection=True)
)
assert len(s2._faces.Faces()) == 1
def test_modifiers():
s1 = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).reset().vertices("<X").fillet(0.1)
assert len(s1._faces.Faces()) == 2
assert len(s1._faces.Edges()) == 10
s2 = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).reset().vertices(">X").chamfer(0.1)
assert len(s2._faces.Faces()) == 2
assert len(s2._faces.Edges()) == 10
s3 = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).reset().hull()
assert len(s3._faces.Faces()) == 3
assert s3._faces.Area() == approx(5)
s4 = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).reset().hull()
assert len(s4._faces.Faces()) == 3
assert s4._faces.Area() == approx(5)
s5 = (
Sketch()
.push([(-2, 0), (0, 0), (2, 0)])
.rect(1, 1)
.reset()
.faces("not >X")
.edges()
.hull()
)
assert len(s5._faces.Faces()) == 4
assert s5._faces.Area() == approx(4)
s6 = Sketch().segment((0, 0), (0, 1)).segment((1, 0), (2, 0)).hull()
assert len(s6._faces.Faces()) == 1
assert s6._faces.Area() == approx(1)
with raises(ValueError):
Sketch().rect(1, 1).vertices().hull()
with raises(ValueError):
Sketch().hull()
s7 = Sketch().rect(2, 2).wires().offset(1)
assert len(s7._faces.Faces()) == 2
assert len(s7._faces.Edges()) == 4 + 4 + 4
s7.clean()
assert len(s7._faces.Faces()) == 1
assert len(s7._faces.Edges()) == 4 + 4
s8 = Sketch().rect(2, 2).wires().offset(-0.5, mode="s")
assert len(s8._faces.Faces()) == 1
assert len(s8._faces.Edges()) == 4 + 4
def test_delete():
s1 = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).reset()
assert len(s1._faces.Faces()) == 2
s1.faces("<X").delete()
assert len(s1._faces.Faces()) == 1
s2 = Sketch().segment((0, 0), (1, 0)).segment((0, 1), tag="e").close()
assert len(s2._edges) == 3
s2.edges("<X").delete()
assert len(s2._edges) == 2
def test_selectors():
s = Sketch().push([(-2, 0), (2, 0)]).rect(1, 1).rect(0.5, 0.5, mode="s").reset()
assert len(s._selection) == 0
s.vertices()
assert len(s._selection) == 16
s.reset()
assert len(s._selection) == 0
s.edges()
assert len(s._selection) == 16
s.reset().wires()
assert len(s._selection) == 4
s.reset().faces()
assert len(s._selection) == 2
s.reset().vertices("<Y")
assert len(s._selection) == 4
s.reset().edges("<X or >X")
assert len(s._selection) == 2
s.tag("test").reset()
assert len(s._selection) == 0
s.select("test")
assert len(s._selection) == 2
s.reset().wires()
assert len(s._selection) == 4
s.reset().wires(LengthNthSelector(1))
assert len(s._selection) == 2
assert len(s.vals()) == 2
s.reset().vertices("<X and <Y").val()
assert s.val().toTuple() == approx((-2.5, -0.5, 0.0))
s.reset().vertices(">>X[1] and <Y").val()
assert s.val().toTuple()[0] == approx((0, 0, 0))
def test_edge_interface():
s1 = (
Sketch()
.segment((0, 0), (1, 0))
.segment((1, 1))
.segment(1, 180)
.close()
.assemble()
)
assert len(s1._faces.Faces()) == 1
assert s1._faces.Area() == approx(1)
s2 = Sketch().arc((0, 0), (1, 1), (0, 2)).close().assemble()
assert len(s2._faces.Faces()) == 1
assert s2._faces.Area() == approx(pi / 2)
s3 = Sketch().arc((0, 0), (1, 1), (0, 2)).arc((-1, 1), (0, 0)).assemble()
assert len(s3._faces.Faces()) == 1
assert s3._faces.Area() == approx(pi)
s4 = Sketch().arc((0, 0), 1, 0, 90)
assert len(s4.vertices()._selection) == 2
assert s4.vertices(">Y")._selection[0].Center().y == approx(1)
s5 = Sketch().arc((0, 0), 1, 0, -90)
assert len(s5.vertices()._selection) == 2
assert s5.vertices(">Y")._selection[0].Center().y == approx(0)
s6 = Sketch().arc((0, 0), 1, 90, 360)
assert len(s6.vertices()._selection) == 1
def test_assemble():
s1 = Sketch()
s1.segment((0.0, 0), (0.0, 2.0))
s1.segment(Vector(4.0, -1)).close().arc((0.7, 0.6), 0.4, 0.0, 360.0).assemble()
s2 = Sketch()
s2.segment((0, 0), (1, 0))
s2.segment((2, 0), (3, 0))
with raises(ValueError):
s2.assemble()
def test_finalize():
parent = object()
s = Sketch(parent).rect(2, 2).circle(0.5, mode="s")
assert s.finalize() is parent
def test_misc():
with raises(ValueError):
Sketch()._startPoint()
with raises(ValueError):
Sketch()._endPoint()
def test_located():
s1 = Sketch().segment((0, 0), (1, 0)).segment((1, 1)).close().assemble()
assert len(s1._edges) == 3
assert len(s1._faces.Faces()) == 1
s2 = s1.located(loc=Location())
assert len(s2._edges) == 0
assert len(s2._faces.Faces()) == 1
def test_constraint_validation():
with raises(ValueError):
Sketch().segment(1.0, 1.0, "s").constrain("s", "Dummy", None)
with raises(ValueError):
Sketch().segment(1.0, 1.0, "s").constrain("s", "s", "Fixed", None)
with raises(ValueError):
Sketch().spline([(1.0, 1.0), (2.0, 1.0), (0.0, 0.0)], "s").constrain(
"s", "Fixed", None
)
with raises(ValueError):
Sketch().segment(1.0, 1.0, "s").constrain("s", "Fixed", 1)
def test_constraint_solver():
s1 = (
Sketch()
.segment((0.0, 0), (0.0, 2.0), "s1")
.segment((0.5, 2.5), (1.0, 1), "s2")
.close("s3")
)
s1.constrain("s1", "Fixed", None)
s1.constrain("s1", "s2", "Coincident", None)
s1.constrain("s2", "s3", "Coincident", None)
s1.constrain("s3", "s1", "Coincident", None)
s1.constrain("s3", "s1", "Angle", 90)
s1.constrain("s2", "s3", "Angle", 180 - 45)
s1.solve()
assert s1._solve_status["status"] == 4
s1.assemble()
assert s1._faces.isValid()
s2 = (
Sketch()
.arc((0.0, 0.0), (-0.5, 0.5), (0.0, 1.0), "a1")
.arc((0.0, 1.0), (0.5, 1.5), (1.0, 1.0), "a2")
.segment((1.0, 0.0), "s1")
.close("s2")
)
s2.constrain("s2", "Fixed", None)
s2.constrain("s1", "s2", "Coincident", None)
s2.constrain("a2", "s1", "Coincident", None)
s2.constrain("s2", "a1", "Coincident", None)
s2.constrain("a1", "a2", "Coincident", None)
s2.constrain("s1", "s2", "Angle", 90)
s2.constrain("s2", "a1", "Angle", 90)
s2.constrain("a1", "a2", "Angle", -90)
s2.constrain("a2", "s1", "Angle", 90)
s2.constrain("s1", "Length", 0.5)
s2.constrain("a1", "Length", 1.0)
s2.solve()
assert s2._solve_status["status"] == 4
s2.assemble()
assert s2._faces.isValid()
assert s2._tags["s1"][0].Length() == approx(0.5)
assert s2._tags["a1"][0].Length() == approx(1.0)
s3 = (
Sketch()
.arc((0.0, 0.0), (-0.5, 0.5), (0.0, 1.0), "a1")
.segment((1.0, 0.0), "s1")
.close("s2")
)
s3.constrain("s2", "Fixed", None)
s3.constrain("a1", "ArcAngle", 60)
s3.constrain("a1", "Radius", 1.0)
s3.constrain("s2", "a1", "Coincident", None)
s3.constrain("a1", "s1", "Coincident", None)
s3.constrain("s1", "s2", "Coincident", None)
s3.solve()
assert s3._solve_status["status"] == 4
s3.assemble()
assert s3._faces.isValid()
assert s3._tags["a1"][0].radius() == approx(1)
assert s3._tags["a1"][0].Length() == approx(pi / 3)
s4 = (
Sketch()
.arc((0.0, 0.0), (-0.5, 0.5), (0.0, 1.0), "a1")
.segment((1.0, 0.0), "s1")
.close("s2")
)
s4.constrain("s2", "Fixed", None)
s4.constrain("s1", "Orientation", (-1.0, -1))
s4.constrain("s1", "s2", "Distance", (0.0, 0.5, 2.0))
s4.constrain("s2", "a1", "Coincident", None)
s4.constrain("a1", "s1", "Coincident", None)
s4.constrain("s1", "s2", "Coincident", None)
s4.solve()
assert s4._solve_status["status"] == 4
s4.assemble()
assert s4._faces.isValid()
seg1 = s4._tags["s1"][0]
seg2 = s4._tags["s2"][0]
assert (seg1.endPoint() - seg1.startPoint()).getAngle(Vector(-1, -1)) == approx(
0, abs=1e-9
)
midpoint = (seg2.startPoint() + seg2.endPoint()) / 2
assert (midpoint - seg1.startPoint()).Length == approx(2)
s5 = (
Sketch()
.segment((0, 0), (0, 3.0), "s1")
.arc((0.0, 0), (1.5, 1.5), (0.0, 3), "a1")
.arc((0.0, 0), (-1.0, 1.5), (0.0, 3), "a2")
)
s5.constrain("s1", "Fixed", None)
s5.constrain("s1", "a1", "Distance", (0.5, 0.5, 3))
s5.constrain("s1", "a1", "Distance", (0.0, 1.0, 0.0))
s5.constrain("a1", "s1", "Distance", (0.0, 1.0, 0.0))
s5.constrain("s1", "a2", "Coincident", None)
s5.constrain("a2", "s1", "Coincident", None)
s5.constrain("a1", "a2", "Distance", (0.5, 0.5, 10.5))
s5.solve()
assert s5._solve_status["status"] == 4
mid0 = s5._edges[0].positionAt(0.5)
mid1 = s5._edges[1].positionAt(0.5)
mid2 = s5._edges[2].positionAt(0.5)
assert (mid1 - mid0).Length == approx(3)
assert (mid1 - mid2).Length == approx(10.5)
s6 = (
Sketch()
.segment((0, 0), (0, 3.0), "s1")
.arc((0.0, 0), (5.5, 5.5), (0.0, 3), "a1")
)
s6.constrain("s1", "Fixed", None)
s6.constrain("s1", "a1", "Coincident", None)
s6.constrain("a1", "s1", "Coincident", None)
s6.constrain("a1", "s1", "Distance", (None, 0.5, 0))
s6.solve()
assert s6._solve_status["status"] == 4
mid0 = s6._edges[0].positionAt(0.5)
mid1 = s6._edges[1].positionAt(0.5)
assert (mid1 - mid0).Length == approx(1.5)
s7 = (
Sketch()
.segment((0, 0), (0, 3.0), "s1")
.arc((0.0, 0), (5.5, 5.5), (0.0, 4), "a1")
)
s7.constrain("s1", "FixedPoint", 0)
s7.constrain("a1", "FixedPoint", None)
s7.constrain("a1", "FixedPoint", 1)
s7.constrain("a1", "s1", "Distance", (0, 0, 0))
s7.constrain("a1", "s1", "Distance", (1, 1, 0))
s7.solve()
assert s7._solve_status["status"] == 4
s7.assemble()
assert s7._faces.isValid()
def test_dxf_import():
filename = os.path.join(testdataDir, "gear.dxf")
s1 = Sketch().importDXF(filename, tol=1e-3)
assert s1._faces.isValid()
s2 = Sketch().importDXF(filename, tol=1e-3).circle(5, mode="s")
assert s2._faces.isValid()
s3 = Sketch().circle(20).importDXF(filename, tol=1e-3, mode="s")
assert s3._faces.isValid()
s4 = Sketch().importDXF(filename, tol=1e-3, include=["0"])
assert s4._faces.isValid()
s5 = Sketch().importDXF(filename, tol=1e-3, exclude=["1"])
assert s5._faces.isValid()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,469 | CadQuery/cadquery | refs/heads/master | /cadquery/__init__.py | from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version("cadquery")
except PackageNotFoundError:
# package is not installed
__version__ = "2.4-dev"
# these items point to the OCC implementation
from .occ_impl.geom import Plane, BoundBox, Vector, Matrix, Location
from .occ_impl.shapes import (
Shape,
Vertex,
Edge,
Face,
Wire,
Solid,
Shell,
Compound,
sortWiresByBuildOrder,
)
from .occ_impl import exporters
from .occ_impl import importers
# these items are the common implementation
# the order of these matter
from .selectors import (
NearestToPointSelector,
ParallelDirSelector,
DirectionSelector,
PerpendicularDirSelector,
TypeSelector,
DirectionMinMaxSelector,
StringSyntaxSelector,
Selector,
)
from .sketch import Sketch
from .cq import CQ, Workplane
from .assembly import Assembly, Color, Constraint
from . import selectors
from . import plugins
__all__ = [
"CQ",
"Workplane",
"Assembly",
"Color",
"Constraint",
"plugins",
"selectors",
"Plane",
"BoundBox",
"Matrix",
"Vector",
"Location",
"sortWiresByBuildOrder",
"Shape",
"Vertex",
"Edge",
"Wire",
"Face",
"Solid",
"Shell",
"Compound",
"exporters",
"importers",
"NearestToPointSelector",
"ParallelDirSelector",
"DirectionSelector",
"PerpendicularDirSelector",
"TypeSelector",
"DirectionMinMaxSelector",
"StringSyntaxSelector",
"Selector",
"plugins",
"Sketch",
]
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,470 | CadQuery/cadquery | refs/heads/master | /cadquery/sketch.py | from typing import (
Union,
Optional,
List,
Dict,
Callable,
Tuple,
Iterable,
Iterator,
Any,
Sequence,
TypeVar,
cast as tcast,
)
from typing_extensions import Literal
from math import tan, sin, cos, pi, radians, remainder
from itertools import product, chain
from multimethod import multimethod
from typish import instance_of, get_type
from .hull import find_hull
from .selectors import StringSyntaxSelector, Selector
from .types import Real
from .occ_impl.shapes import Shape, Face, Edge, Wire, Compound, Vertex, edgesToWires
from .occ_impl.geom import Location, Vector
from .occ_impl.importers.dxf import _importDXF
from .occ_impl.sketch_solver import (
SketchConstraintSolver,
ConstraintKind,
ConstraintInvariants,
DOF,
arc_first,
arc_last,
arc_point,
)
Modes = Literal["a", "s", "i", "c"] # add, subtract, intersect, construct
Point = Union[Vector, Tuple[Real, Real]]
TOL = 1e-6
T = TypeVar("T", bound="Sketch")
SketchVal = Union[Shape, Location]
class Constraint(object):
tags: Tuple[str, ...]
args: Tuple[Edge, ...]
kind: ConstraintKind
param: Any
def __init__(
self,
tags: Tuple[str, ...],
args: Tuple[Edge, ...],
kind: ConstraintKind,
param: Any = None,
):
# validate based on the solver provided spec
if kind not in ConstraintInvariants:
raise ValueError(f"Unknown constraint {kind}.")
arity, types, param_type, converter = ConstraintInvariants[kind]
if arity != len(tags):
raise ValueError(
f"Invalid number of entities for constraint {kind}. Provided {len(tags)}, required {arity}."
)
if any(e.geomType() not in types for e in args):
raise ValueError(
f"Unsupported geometry types {[e.geomType() for e in args]} for constraint {kind}."
)
if not instance_of(param, param_type):
raise ValueError(
f"Unsupported argument types {get_type(param)}, required {param_type}."
)
# if all is fine store everything and possibly convert the params
self.tags = tags
self.args = args
self.kind = kind
self.param = tcast(Any, converter)(param) if converter else param
class Sketch(object):
"""
2D sketch. Supports faces, edges and edges with constraints based construction.
"""
parent: Any
locs: List[Location]
_faces: Compound
_wires: List[Wire]
_edges: List[Edge]
_selection: List[SketchVal]
_constraints: List[Constraint]
_tags: Dict[str, Sequence[SketchVal]]
_solve_status: Optional[Dict[str, Any]]
def __init__(self: T, parent: Any = None, locs: Iterable[Location] = (Location(),)):
"""
Construct an empty sketch.
"""
self.parent = parent
self.locs = list(locs)
self._faces = Compound.makeCompound(())
self._wires = []
self._edges = []
self._selection = []
self._constraints = []
self._tags = {}
self._solve_status = None
def __iter__(self) -> Iterator[Face]:
"""
Iterate over faces-locations combinations.
"""
return iter(f for l in self.locs for f in self._faces.moved(l).Faces())
def _tag(self: T, val: Sequence[Union[Shape, Location]], tag: str):
self._tags[tag] = val
# face construction
def face(
self: T,
b: Union[Wire, Iterable[Edge], Compound, T],
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
ignore_selection: bool = False,
) -> T:
"""
Construct a face from a wire or edges.
"""
res: Union[Face, Sketch, Compound]
if isinstance(b, Wire):
res = Face.makeFromWires(b)
elif isinstance(b, (Sketch, Compound)):
res = b
elif isinstance(b, Iterable):
wires = edgesToWires(tcast(Iterable[Edge], b))
res = Face.makeFromWires(*(wires[0], wires[1:]))
else:
raise ValueError(f"Unsupported argument {b}")
if angle != 0:
res = res.moved(Location(Vector(), Vector(0, 0, 1), angle))
return self.each(lambda l: res.moved(l), mode, tag, ignore_selection)
def importDXF(
self: T,
filename: str,
tol: float = 1e-6,
exclude: List[str] = [],
include: List[str] = [],
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Import a DXF file and construct face(s)
"""
res = Compound.makeCompound(_importDXF(filename, tol, exclude, include))
return self.face(res, angle, mode, tag)
def rect(
self: T,
w: Real,
h: Real,
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct a rectangular face.
"""
res = Face.makePlane(h, w).rotate(Vector(), Vector(0, 0, 1), angle)
return self.each(lambda l: res.located(l), mode, tag)
def circle(self: T, r: Real, mode: Modes = "a", tag: Optional[str] = None) -> T:
"""
Construct a circular face.
"""
res = Face.makeFromWires(Wire.makeCircle(r, Vector(), Vector(0, 0, 1)))
return self.each(lambda l: res.located(l), mode, tag)
def ellipse(
self: T,
a1: Real,
a2: Real,
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct an elliptical face.
"""
res = Face.makeFromWires(
Wire.makeEllipse(
a1, a2, Vector(), Vector(0, 0, 1), Vector(1, 0, 0), rotation_angle=angle
)
)
return self.each(lambda l: res.located(l), mode, tag)
def trapezoid(
self: T,
w: Real,
h: Real,
a1: Real,
a2: Optional[float] = None,
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct a trapezoidal face.
"""
v1 = Vector(-w / 2, -h / 2)
v2 = Vector(w / 2, -h / 2)
v3 = Vector(-w / 2 + h / tan(radians(a1)), h / 2)
v4 = Vector(w / 2 - h / tan(radians(a2) if a2 else radians(a1)), h / 2)
return self.polygon((v1, v2, v4, v3, v1), angle, mode, tag)
def slot(
self: T,
w: Real,
h: Real,
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct a slot-shaped face.
"""
p1 = Vector(-w / 2, h / 2)
p2 = Vector(w / 2, h / 2)
p3 = Vector(-w / 2, -h / 2)
p4 = Vector(w / 2, -h / 2)
p5 = Vector(-w / 2 - h / 2, 0)
p6 = Vector(w / 2 + h / 2, 0)
e1 = Edge.makeLine(p1, p2)
e2 = Edge.makeThreePointArc(p2, p6, p4)
e3 = Edge.makeLine(p4, p3)
e4 = Edge.makeThreePointArc(p3, p5, p1)
wire = Wire.assembleEdges((e1, e2, e3, e4))
return self.face(wire, angle, mode, tag)
def regularPolygon(
self: T,
r: Real,
n: int,
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct a regular polygonal face.
"""
pts = [
Vector(r * sin(i * 2 * pi / n), r * cos(i * 2 * pi / n))
for i in range(n + 1)
]
return self.polygon(pts, angle, mode, tag)
def polygon(
self: T,
pts: Iterable[Point],
angle: Real = 0,
mode: Modes = "a",
tag: Optional[str] = None,
) -> T:
"""
Construct a polygonal face.
"""
w = Wire.makePolygon(
(p if isinstance(p, Vector) else Vector(*p) for p in pts), False, True
)
return self.face(w, angle, mode, tag)
# distribute locations
def rarray(self: T, xs: Real, ys: Real, nx: int, ny: int) -> T:
"""
Generate a rectangular array of locations.
"""
if nx < 1 or ny < 1:
raise ValueError(f"At least 1 elements required, requested {nx}, {ny}")
locs = []
offset = Vector((nx - 1) * xs, (ny - 1) * ys) * 0.5
for i, j in product(range(nx), range(ny)):
locs.append(Location(Vector(i * xs, j * ys) - offset))
if self._selection:
selection: Sequence[Union[Shape, Location, Vector]] = self._selection
else:
selection = [Vector()]
return self.push(
(l * el if isinstance(el, Location) else l * Location(el.Center()))
for l in locs
for el in selection
)
def parray(self: T, r: Real, a1: Real, da: Real, n: int, rotate: bool = True) -> T:
"""
Generate a polar array of locations.
"""
if n < 1:
raise ValueError(f"At least 1 element required, requested {n}")
locs = []
if abs(remainder(da, 360)) < TOL:
angle = da / n
else:
angle = da / (n - 1) if n > 1 else a1
for i in range(0, n):
phi = a1 + (angle * i)
x = r * cos(radians(phi))
y = r * sin(radians(phi))
loc = Location(Vector(x, y))
locs.append(loc)
if self._selection:
selection: Sequence[Union[Shape, Location, Vector]] = self._selection
else:
selection = [Vector()]
return self.push(
(
l
* el
* Location(
Vector(0, 0), Vector(0, 0, 1), (a1 + (angle * i)) if rotate else 0
)
)
for i, l in enumerate(locs)
for el in [
el if isinstance(el, Location) else Location(el.Center())
for el in selection
]
)
def distribute(
self: T, n: int, start: Real = 0, stop: Real = 1, rotate: bool = True
) -> T:
"""
Distribute locations along selected edges or wires.
"""
if n < 1:
raise ValueError(f"At least 1 element required, requested {n}")
if not self._selection:
raise ValueError("Nothing selected to distribute over")
if 1 - abs(stop - start) < TOL:
trimmed = False
else:
trimmed = True
# closed edge or wire parameters
params_closed = [start + i * (stop - start) / n for i in range(n)]
# open or trimmed edge or wire parameters
params_open = [
start + i * (stop - start) / (n - 1) if n - 1 > 0 else start
for i in range(n)
]
locs = []
for el in self._selection:
if isinstance(el, (Wire, Edge)):
if el.IsClosed() and not trimmed:
params = params_closed
else:
params = params_open
if rotate:
locs.extend(el.locations(params, planar=True,))
else:
locs.extend(Location(v) for v in el.positions(params))
else:
raise ValueError(f"Unsupported selection: {el}")
return self.push(locs)
def push(
self: T, locs: Iterable[Union[Location, Point]], tag: Optional[str] = None,
) -> T:
"""
Set current selection to given locations or points.
"""
self._selection = [
l if isinstance(l, Location) else Location(Vector(l)) for l in locs
]
if tag:
self._tag(self._selection[:], tag)
return self
def each(
self: T,
callback: Callable[[Location], Union[Face, "Sketch", Compound]],
mode: Modes = "a",
tag: Optional[str] = None,
ignore_selection: bool = False,
) -> T:
"""
Apply a callback on all applicable entities.
"""
res: List[Face] = []
locs: List[Location] = []
if self._selection and not ignore_selection:
for el in self._selection:
if isinstance(el, Location):
loc = el
else:
loc = Location(el.Center())
locs.append(loc)
else:
locs.append(Location())
for loc in locs:
tmp = callback(loc)
if isinstance(tmp, Sketch):
res.extend(tmp._faces.Faces())
elif isinstance(tmp, Compound):
res.extend(tmp.Faces())
else:
res.append(tmp)
if tag:
self._tag(res, tag)
if mode == "a":
self._faces = self._faces.fuse(*res)
elif mode == "s":
self._faces = self._faces.cut(*res)
elif mode == "i":
self._faces = self._faces.intersect(*res)
elif mode == "c":
if not tag:
raise ValueError("No tag specified - the geometry will be unreachable")
else:
raise ValueError(f"Invalid mode: {mode}")
return self
# modifiers
def hull(self: T, mode: Modes = "a", tag: Optional[str] = None) -> T:
"""
Generate a convex hull from current selection or all objects.
"""
if self._selection:
rv = find_hull(el for el in self._selection if isinstance(el, Edge))
elif self._faces:
rv = find_hull(el for el in self._faces.Edges())
elif self._edges or self._wires:
rv = find_hull(
chain(self._edges, chain.from_iterable(w.Edges() for w in self._wires))
)
else:
raise ValueError("No objects available for hull construction")
self.face(rv, mode=mode, tag=tag, ignore_selection=bool(self._selection))
return self
def offset(self: T, d: Real, mode: Modes = "a", tag: Optional[str] = None) -> T:
"""
Offset selected wires or edges.
"""
rv = (el.offset2D(d) for el in self._selection if isinstance(el, Wire))
for el in chain.from_iterable(rv):
self.face(el, mode=mode, tag=tag, ignore_selection=bool(self._selection))
return self
def _matchFacesToVertices(self) -> Dict[Face, List[Vertex]]:
rv = {}
for f in self._faces.Faces():
f_vertices = f.Vertices()
rv[f] = [
v for v in self._selection if isinstance(v, Vertex) and v in f_vertices
]
return rv
def fillet(self: T, d: Real) -> T:
"""
Add a fillet based on current selection.
"""
f2v = self._matchFacesToVertices()
self._faces = Compound.makeCompound(
k.fillet2D(d, v) if v else k for k, v in f2v.items()
)
return self
def chamfer(self: T, d: Real) -> T:
"""
Add a chamfer based on current selection.
"""
f2v = self._matchFacesToVertices()
self._faces = Compound.makeCompound(
k.chamfer2D(d, v) if v else k for k, v in f2v.items()
)
return self
def clean(self: T) -> T:
"""
Remove internal wires.
"""
self._faces = self._faces.clean()
return self
# selection
def _unique(self: T, vals: List[SketchVal]) -> List[SketchVal]:
tmp = {hash(v): v for v in vals}
return list(tmp.values())
def _select(
self: T,
s: Optional[Union[str, Selector]],
kind: Literal["Faces", "Wires", "Edges", "Vertices"],
tag: Optional[str] = None,
) -> T:
rv = []
if tag:
for el in self._tags[tag]:
rv.extend(getattr(el, kind)())
elif self._selection:
for el in self._selection:
if not isinstance(el, Location):
rv.extend(getattr(el, kind)())
else:
rv.extend(getattr(self._faces, kind)())
for el in self._edges:
rv.extend(getattr(el, kind)())
if s and isinstance(s, Selector):
filtered = s.filter(rv)
elif s and isinstance(s, str):
filtered = StringSyntaxSelector(s).filter(rv)
else:
filtered = rv
self._selection = self._unique(filtered)
return self
def tag(self: T, tag: str) -> T:
"""
Tag current selection.
"""
self._tags[tag] = list(self._selection)
return self
def select(self: T, *tags: str) -> T:
"""
Select based on tags.
"""
self._selection = []
for tag in tags:
self._selection.extend(self._tags[tag])
return self
def faces(
self: T, s: Optional[Union[str, Selector]] = None, tag: Optional[str] = None
) -> T:
"""
Select faces.
"""
return self._select(s, "Faces", tag)
def wires(
self: T, s: Optional[Union[str, Selector]] = None, tag: Optional[str] = None
) -> T:
"""
Select wires.
"""
return self._select(s, "Wires", tag)
def edges(
self: T, s: Optional[Union[str, Selector]] = None, tag: Optional[str] = None
) -> T:
"""
Select edges.
"""
return self._select(s, "Edges", tag)
def vertices(
self: T, s: Optional[Union[str, Selector]] = None, tag: Optional[str] = None
) -> T:
"""
Select vertices.
"""
return self._select(s, "Vertices", tag)
def reset(self: T) -> T:
"""
Reset current selection.
"""
self._selection = []
return self
def delete(self: T) -> T:
"""
Delete selected object.
"""
for obj in self._selection:
if isinstance(obj, Face):
self._faces.remove(obj)
elif isinstance(obj, Wire):
self._wires.remove(obj)
elif isinstance(obj, Edge):
self._edges.remove(obj)
self._selection = []
return self
# edge based interface
def _startPoint(self) -> Vector:
if not self._edges:
raise ValueError("No free edges available")
e = self._edges[0]
return e.startPoint()
def _endPoint(self) -> Vector:
if not self._edges:
raise ValueError("No free edges available")
e = self._edges[-1]
return e.endPoint()
def edge(
self: T, val: Edge, tag: Optional[str] = None, forConstruction: bool = False
) -> T:
"""
Add an edge to the sketch.
"""
val.forConstruction = forConstruction
self._edges.append(val)
if tag:
self._tag([val], tag)
return self
@multimethod
def segment(
self: T,
p1: Point,
p2: Point,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
"""
Construct a segment.
"""
val = Edge.makeLine(Vector(p1), Vector(p2))
return self.edge(val, tag, forConstruction)
@segment.register
def segment(
self: T, p2: Point, tag: Optional[str] = None, forConstruction: bool = False
) -> T:
p1 = self._endPoint()
val = Edge.makeLine(p1, Vector(p2))
return self.edge(val, tag, forConstruction)
@segment.register
def segment(
self: T,
l: Real,
a: Real,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
p1 = self._endPoint()
d = Vector(l * cos(radians(a)), l * sin(radians(a)))
val = Edge.makeLine(p1, p1 + d)
return self.edge(val, tag, forConstruction)
@multimethod
def arc(
self: T,
p1: Point,
p2: Point,
p3: Point,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
"""
Construct an arc.
"""
val = Edge.makeThreePointArc(Vector(p1), Vector(p2), Vector(p3))
return self.edge(val, tag, forConstruction)
@arc.register
def arc(
self: T,
p2: Point,
p3: Point,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
p1 = self._endPoint()
val = Edge.makeThreePointArc(Vector(p1), Vector(p2), Vector(p3))
return self.edge(val, tag, forConstruction)
@arc.register
def arc(
self: T,
c: Point,
r: Real,
a: Real,
da: Real,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
if abs(da) >= 360:
val = Edge.makeCircle(r, Vector(c), angle1=a, angle2=a, orientation=da > 0)
else:
p0 = Vector(c)
p1 = p0 + r * Vector(cos(radians(a)), sin(radians(a)))
p2 = p0 + r * Vector(cos(radians(a + da / 2)), sin(radians(a + da / 2)))
p3 = p0 + r * Vector(cos(radians(a + da)), sin(radians(a + da)))
val = Edge.makeThreePointArc(p1, p2, p3)
return self.edge(val, tag, forConstruction)
@multimethod
def spline(
self: T,
pts: Iterable[Point],
tangents: Optional[Iterable[Point]],
periodic: bool,
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
"""
Construct a spline edge.
"""
val = Edge.makeSpline(
[Vector(*p) for p in pts],
[Vector(*t) for t in tangents] if tangents else None,
periodic,
)
return self.edge(val, tag, forConstruction)
@spline.register
def spline(
self: T,
pts: Iterable[Point],
tag: Optional[str] = None,
forConstruction: bool = False,
) -> T:
return self.spline(pts, None, False, tag, forConstruction)
def close(self: T, tag: Optional[str] = None) -> T:
"""
Connect last edge to the first one.
"""
self.segment(self._endPoint(), self._startPoint(), tag)
return self
def assemble(self: T, mode: Modes = "a", tag: Optional[str] = None) -> T:
"""
Assemble edges into faces.
"""
return self.face(
(e for e in self._edges if not e.forConstruction), 0, mode, tag
)
# constraints
@multimethod
def constrain(self: T, tag: str, constraint: ConstraintKind, arg: Any) -> T:
"""
Add a constraint.
"""
self._constraints.append(
Constraint((tag,), (self._tags[tag][0],), constraint, arg)
)
return self
@constrain.register
def constrain(
self: T, tag1: str, tag2: str, constraint: ConstraintKind, arg: Any
) -> T:
self._constraints.append(
Constraint(
(tag1, tag2),
(self._tags[tag1][0], self._tags[tag2][0]),
constraint,
arg,
)
)
return self
def solve(self: T) -> T:
"""
Solve current constraints and update edge positions.
"""
entities = [] # list with all degrees of freedom
e2i = {} # mapping from tags to indices of entities
geoms = [] # geometry types
# fill entities, e2i and geoms
for i, (k, v) in enumerate(
filter(lambda kv: isinstance(kv[1][0], Edge), self._tags.items())
):
v0 = tcast(Edge, v[0])
# dispatch on geom type
if v0.geomType() == "LINE":
p1 = v0.startPoint()
p2 = v0.endPoint()
ent: DOF = (p1.x, p1.y, p2.x, p2.y)
elif v0.geomType() == "CIRCLE":
p = v0.arcCenter()
p1 = v0.startPoint() - p
p2 = v0.endPoint() - p
pm = v0.positionAt(0.5) - p
a1 = Vector(0, 1).getSignedAngle(p1)
a2 = p1.getSignedAngle(p2)
a3 = p1.getSignedAngle(pm)
if a3 > 0 and a2 < 0:
a2 += 2 * pi
elif a3 < 0 and a2 > 0:
a2 -= 2 * pi
radius = v0.radius()
ent = (p.x, p.y, radius, a1, a2)
else:
continue
entities.append(ent)
e2i[k] = i
geoms.append(v0.geomType())
# build the POD constraint list
constraints = []
for c in self._constraints:
ix = (e2i[c.tags[0]], e2i[c.tags[1]] if len(c.tags) == 2 else None)
constraints.append((ix, c.kind, c.param))
# optimize
solver = SketchConstraintSolver(entities, constraints, geoms)
res, self._solve_status = solver.solve()
self._solve_status["x"] = res
# translate back the solution - update edges
for g, (k, i) in zip(geoms, e2i.items()):
el = res[i]
# dispatch on geom type
if g == "LINE":
p1 = Vector(el[0], el[1])
p2 = Vector(el[2], el[3])
e = Edge.makeLine(p1, p2)
elif g == "CIRCLE":
p1 = Vector(*arc_first(el))
p2 = Vector(*arc_point(el, 0.5))
p3 = Vector(*arc_last(el))
e = Edge.makeThreePointArc(p1, p2, p3)
# overwrite the low level object
self._tags[k][0].wrapped = e.wrapped
return self
# misc
def copy(self: T) -> T:
"""
Create a partial copy of the sketch.
"""
rv = self.__class__()
rv._faces = self._faces.copy()
return rv
def moved(self: T, loc: Location) -> T:
"""
Create a partial copy of the sketch with moved _faces.
"""
rv = self.__class__()
rv._faces = self._faces.moved(loc)
return rv
def located(self: T, loc: Location) -> T:
"""
Create a partial copy of the sketch with a new location.
"""
rv = self.__class__(locs=(loc,))
rv._faces = self._faces.copy()
return rv
def finalize(self) -> Any:
"""
Finish sketch construction and return the parent.
"""
return self.parent
def val(self: T) -> SketchVal:
"""
Return the first selected item or Location().
"""
return self._selection[0] if self._selection else Location()
def vals(self: T) -> List[SketchVal]:
"""
Return the list of selected items.
"""
return self._selection
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,471 | CadQuery/cadquery | refs/heads/master | /examples/Ex004_Extruded_Cylindrical_Plate.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
circle_radius = 50.0 # Radius of the plate
thickness = 13.0 # Thickness of the plate
rectangle_width = 13.0 # Width of rectangular hole in cylindrical plate
rectangle_length = 19.0 # Length of rectangular hole in cylindrical plate
# Extrude a cylindrical plate with a rectangular hole in the middle of it.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. The 2D geometry for the outer circle is created at the same time as the
# rectangle that will create the hole in the center.
# 2a. The circle and the rectangle will be automatically centered on the
# workplane.
# 2b. Unlike some other functions like the hole(), circle() takes
# a radius and not a diameter.
# 3. The circle and rectangle are extruded together, creating a cylindrical
# plate with a rectangular hole in the center.
# 3a. circle() and rect() could be changed to any other shape to completely
# change the resulting plate and/or the hole in it.
result = (
cq.Workplane("front")
.circle(circle_radius)
.rect(rectangle_width, rectangle_length)
.extrude(thickness)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,472 | CadQuery/cadquery | refs/heads/master | /cadquery/cq_directive.py | """
A special directive for including a cq object.
"""
import traceback
from json import dumps
from cadquery import exporters, Assembly, Compound, Color, Sketch
from cadquery import cqgi
from cadquery.occ_impl.assembly import toJSON
from cadquery.occ_impl.jupyter_tools import DEFAULT_COLOR
from docutils.parsers.rst import directives, Directive
template = """
.. raw:: html
<div class="cq" style="text-align:%(txt_align)s;float:left;">
%(out_svg)s
</div>
<div style="clear:both;">
</div>
"""
rendering_code = """
const RENDERERS = {};
var ID = 0;
const renderWindow = vtk.Rendering.Core.vtkRenderWindow.newInstance();
const openglRenderWindow = vtk.Rendering.OpenGL.vtkRenderWindow.newInstance();
renderWindow.addView(openglRenderWindow);
const rootContainer = document.createElement('div');
rootContainer.style.position = 'fixed';
//rootContainer.style.zIndex = -1;
rootContainer.style.left = 0;
rootContainer.style.top = 0;
rootContainer.style.pointerEvents = 'none';
rootContainer.style.width = '100%';
rootContainer.style.height = '100%';
openglRenderWindow.setContainer(rootContainer);
const interact_style = vtk.Interaction.Style.vtkInteractorStyleManipulator.newInstance();
const manips = {
rot: vtk.Interaction.Manipulators.vtkMouseCameraTrackballRotateManipulator.newInstance(),
pan: vtk.Interaction.Manipulators.vtkMouseCameraTrackballPanManipulator.newInstance(),
zoom1: vtk.Interaction.Manipulators.vtkMouseCameraTrackballZoomManipulator.newInstance(),
zoom2: vtk.Interaction.Manipulators.vtkMouseCameraTrackballZoomManipulator.newInstance(),
roll: vtk.Interaction.Manipulators.vtkMouseCameraTrackballRollManipulator.newInstance(),
};
manips.zoom1.setControl(true);
manips.zoom2.setButton(3);
manips.roll.setShift(true);
manips.pan.setButton(2);
for (var k in manips){{
interact_style.addMouseManipulator(manips[k]);
}};
const interactor = vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance();
interactor.setView(openglRenderWindow);
interactor.initialize();
interactor.setInteractorStyle(interact_style);
document.addEventListener('DOMContentLoaded', function () {
document.body.appendChild(rootContainer);
});
function updateViewPort(element, renderer) {
const { innerHeight, innerWidth } = window;
const { x, y, width, height } = element.getBoundingClientRect();
const viewport = [
x / innerWidth,
1 - (y + height) / innerHeight,
(x + width) / innerWidth,
1 - y / innerHeight,
];
renderer.setViewport(...viewport);
}
function recomputeViewports() {
const rendererElems = document.querySelectorAll('.renderer');
for (let i = 0; i < rendererElems.length; i++) {
const elem = rendererElems[i];
const { id } = elem;
const renderer = RENDERERS[id];
updateViewPort(elem, renderer);
}
renderWindow.render();
}
function resize() {
rootContainer.style.width = `${window.innerWidth}px`;
openglRenderWindow.setSize(window.innerWidth, window.innerHeight);
recomputeViewports();
}
window.addEventListener('resize', resize);
document.addEventListener('scroll', recomputeViewports);
function enterCurrentRenderer(e) {
interactor.bindEvents(document.body);
interact_style.setEnabled(true);
interactor.setCurrentRenderer(RENDERERS[e.target.id]);
}
function exitCurrentRenderer(e) {
interactor.setCurrentRenderer(null);
interact_style.setEnabled(false);
interactor.unbindEvents();
}
function applyStyle(element) {
element.classList.add('renderer');
element.style.width = '100%';
element.style.height = '100%';
element.style.display = 'inline-block';
element.style.boxSizing = 'border';
return element;
}
window.addEventListener('load', resize);
function render(data, parent_element, ratio){
// Initial setup
const renderer = vtk.Rendering.Core.vtkRenderer.newInstance({ background: [1, 1, 1 ] });
// iterate over all children children
for (var el of data){
var trans = el.position;
var rot = el.orientation;
var rgba = el.color;
var shape = el.shape;
// load the inline data
var reader = vtk.IO.XML.vtkXMLPolyDataReader.newInstance();
const textEncoder = new TextEncoder();
reader.parseAsArrayBuffer(textEncoder.encode(shape));
// setup actor,mapper and add
const mapper = vtk.Rendering.Core.vtkMapper.newInstance();
mapper.setInputConnection(reader.getOutputPort());
mapper.setResolveCoincidentTopologyToPolygonOffset();
mapper.setResolveCoincidentTopologyPolygonOffsetParameters(0.5,100);
const actor = vtk.Rendering.Core.vtkActor.newInstance();
actor.setMapper(mapper);
// set color and position
actor.getProperty().setColor(rgba.slice(0,3));
actor.getProperty().setOpacity(rgba[3]);
actor.rotateZ(rot[2]*180/Math.PI);
actor.rotateY(rot[1]*180/Math.PI);
actor.rotateX(rot[0]*180/Math.PI);
actor.setPosition(trans);
renderer.addActor(actor);
};
//add the container
const container = applyStyle(document.createElement("div"));
parent_element.appendChild(container);
container.addEventListener('mouseenter', enterCurrentRenderer);
container.addEventListener('mouseleave', exitCurrentRenderer);
container.id = ID;
renderWindow.addRenderer(renderer);
updateViewPort(container, renderer);
renderer.getActiveCamera().set({ position: [1, -1, 1], viewUp: [0, 0, 1] });
renderer.resetCamera();
RENDERERS[ID] = renderer;
ID++;
};
"""
template_vtk = """
.. raw:: html
<div class="cq-vtk"
style="text-align:{txt_align};float:left;border: 1px solid #ddd; width:{width}; height:{height}">
<script>
var parent_element = {element};
var data = {data};
render(data, parent_element);
</script>
</div>
<div style="clear:both;">
</div>
"""
class cq_directive(Directive):
has_content = True
required_arguments = 0
optional_arguments = 0
option_spec = {
"align": directives.unchanged,
}
def run(self):
options = self.options
content = self.content
state_machine = self.state_machine
# only consider inline snippets
plot_code = "\n".join(content)
# Since we don't have a filename, use a hash based on the content
# the script must define a variable called 'out', which is expected to
# be a CQ object
out_svg = "Your Script Did not assign call build_output() function!"
try:
result = cqgi.parse(plot_code).build()
if result.success:
out_svg = exporters.getSVG(
exporters.toCompound(result.first_result.shape)
)
else:
raise result.exception
except Exception:
traceback.print_exc()
out_svg = traceback.format_exc()
# now out
# Now start generating the lines of output
lines = []
# get rid of new lines
out_svg = out_svg.replace("\n", "")
txt_align = "left"
if "align" in options:
txt_align = options["align"]
lines.extend((template % locals()).split("\n"))
lines.extend(["::", ""])
lines.extend([" %s" % row.rstrip() for row in plot_code.split("\n")])
lines.append("")
if len(lines):
state_machine.insert_input(lines, state_machine.input_lines.source(0))
return []
class cq_directive_vtk(Directive):
has_content = True
required_arguments = 0
optional_arguments = 0
option_spec = {
"height": directives.length_or_unitless,
"width": directives.length_or_percentage_or_unitless,
"align": directives.unchanged,
"select": directives.unchanged,
}
def run(self):
options = self.options
content = self.content
state_machine = self.state_machine
# only consider inline snippets
plot_code = "\n".join(content)
# collect the result
try:
result = cqgi.parse(plot_code).build()
if result.success:
if result.first_result:
shape = result.first_result.shape
else:
shape = result.env[options.get("select", "result")]
if isinstance(shape, Assembly):
assy = shape
elif isinstance(shape, Sketch):
assy = Assembly(shape._faces, color=Color(*DEFAULT_COLOR))
else:
assy = Assembly(shape, color=Color(*DEFAULT_COLOR))
else:
raise result.exception
except Exception:
traceback.print_exc()
assy = Assembly(Compound.makeText("CQGI error", 10, 5))
# add the output
lines = []
data = dumps(toJSON(assy))
lines.extend(
template_vtk.format(
data=data,
element="document.currentScript.parentNode",
txt_align=options.get("align", "left"),
width=options.get("width", "100%"),
height=options.get("height", "500px"),
).splitlines()
)
lines.extend(["::", ""])
lines.extend([" %s" % row.rstrip() for row in plot_code.split("\n")])
lines.append("")
if len(lines):
state_machine.insert_input(lines, state_machine.input_lines.source(0))
return []
def setup(app):
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
app.add_directive("cq_plot", cq_directive)
app.add_directive("cadquery", cq_directive_vtk)
# add vtk.js
app.add_js_file("vtk.js")
app.add_js_file(None, body=rendering_code)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,473 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/solver.py | from typing import (
List,
Tuple,
Union,
Any,
Callable,
Optional,
Dict,
Literal,
cast as tcast,
Type,
)
from math import radians, pi
from typish import instance_of, get_type
import casadi as ca
from OCP.gp import (
gp_Vec,
gp_Pln,
gp_Dir,
gp_Pnt,
gp_Trsf,
gp_Quaternion,
gp_Lin,
gp_Extrinsic_XYZ,
)
from OCP.BRepTools import BRepTools
from OCP.Precision import Precision
from .geom import Location, Vector, Plane
from .shapes import Shape, Face, Edge, Wire
from ..types import Real
# type definitions
NoneType = type(None)
DOF6 = Tuple[Tuple[float, float, float], Tuple[float, float, float]]
ConstraintMarker = Union[gp_Pln, gp_Dir, gp_Pnt, gp_Lin, None]
UnaryConstraintKind = Literal["Fixed", "FixedPoint", "FixedAxis", "FixedRotation"]
BinaryConstraintKind = Literal["Plane", "Point", "Axis", "PointInPlane", "PointOnLine"]
ConstraintKind = Literal[
"Plane",
"Point",
"Axis",
"PointInPlane",
"Fixed",
"FixedPoint",
"FixedAxis",
"PointOnLine",
"FixedRotation",
]
# (arity, marker types, param type, conversion func)
ConstraintInvariants = {
"Point": (2, (gp_Pnt, gp_Pnt), Real, None),
"Axis": (
2,
(gp_Dir, gp_Dir),
Real,
lambda x: radians(x) if x is not None else None,
),
"PointInPlane": (2, (gp_Pnt, gp_Pln), Real, None),
"PointOnLine": (2, (gp_Pnt, gp_Lin), Real, None),
"Fixed": (1, (None,), Type[None], None),
"FixedPoint": (1, (gp_Pnt,), Tuple[Real, Real, Real], None),
"FixedAxis": (1, (gp_Dir,), Tuple[Real, Real, Real], None),
"FixedRotation": (
1,
(None,),
Tuple[Real, Real, Real],
lambda x: tuple(map(radians, x)),
),
}
# translation table for compound constraints {name : (name, ...), converter}
CompoundConstraints: Dict[
ConstraintKind, Tuple[Tuple[ConstraintKind, ...], Callable[[Any], Tuple[Any, ...]]]
] = {
"Plane": (("Axis", "Point"), lambda x: (radians(x) if x is not None else None, 0)),
}
# constraint POD type
Constraint = Tuple[
Tuple[ConstraintMarker, ...], ConstraintKind, Optional[Any],
]
NDOF_V = 3
NDOF_Q = 3
NDOF = 6
DIR_SCALING = 1e2
DIFF_EPS = 1e-10
TOL = 1e-12
MAXITER = 2000
# high-level constraint class - to be used by clients
class ConstraintSpec(object):
"""
Geometrical constraint specification between two shapes of an assembly.
"""
objects: Tuple[str, ...]
args: Tuple[Shape, ...]
sublocs: Tuple[Location, ...]
kind: ConstraintKind
param: Any
def __init__(
self,
objects: Tuple[str, ...],
args: Tuple[Shape, ...],
sublocs: Tuple[Location, ...],
kind: ConstraintKind,
param: Any = None,
):
"""
Construct a constraint.
:param objects: object names referenced in the constraint
:param args: subshapes (e.g. faces or edges) of the objects
:param sublocs: locations of the objects (only relevant if the objects are nested in a sub-assembly)
:param kind: constraint kind
:param param: optional arbitrary parameter passed to the solver
"""
# validate
if not instance_of(kind, ConstraintKind):
raise ValueError(f"Unknown constraint {kind}.")
if kind in CompoundConstraints:
kinds, convert_compound = CompoundConstraints[kind]
for k, p in zip(kinds, convert_compound(param)):
self._validate(args, k, p)
else:
self._validate(args, kind, param)
# convert here for simple constraints
convert = ConstraintInvariants[kind][-1]
param = convert(param) if convert else param
# store
self.objects = objects
self.args = args
self.sublocs = sublocs
self.kind = kind
self.param = param
def _validate(self, args: Tuple[Shape, ...], kind: ConstraintKind, param: Any):
arity, marker_types, param_type, converter = ConstraintInvariants[kind]
# check arity
if arity != len(args):
raise ValueError(
f"Invalid number of entities for constraint {kind}. Provided {len(args)}, required {arity}."
)
# check arguments
arg_check: Dict[Any, Callable[[Shape], Any]] = {
gp_Pnt: self._getPnt,
gp_Dir: self._getAxis,
gp_Pln: self._getPln,
gp_Lin: self._getLin,
None: lambda x: True, # dummy check for None marker
}
for a, t in zip(args, tcast(Tuple[Type[ConstraintMarker], ...], marker_types)):
try:
arg_check[t](a)
except ValueError:
raise ValueError(f"Unsupported entity {a} for constraint {kind}.")
# check parameter
if not instance_of(param, param_type) and param is not None:
raise ValueError(
f"Unsupported argument types {get_type(param)}, required {param_type}."
)
# check parameter conversion
try:
if param is not None and converter:
converter(param)
except Exception as e:
raise ValueError(f"Exception {e} occured in the parameter conversion")
def _getAxis(self, arg: Shape) -> gp_Dir:
if isinstance(arg, Face):
rv = arg.normalAt()
elif isinstance(arg, Edge) and arg.geomType() != "CIRCLE":
rv = arg.tangentAt()
elif isinstance(arg, Edge) and arg.geomType() == "CIRCLE":
rv = arg.normal()
else:
raise ValueError(f"Cannot construct Axis for {arg}")
return rv.toDir()
def _getPln(self, arg: Shape) -> gp_Pln:
if isinstance(arg, Face):
rv = gp_Pln(self._getPnt(arg), arg.normalAt().toDir())
elif isinstance(arg, (Edge, Wire)):
normal = arg.normal()
origin = arg.Center()
plane = Plane(origin, normal=normal)
rv = plane.toPln()
else:
raise ValueError(f"Cannot construct a plane for {arg}.")
return rv
def _getPnt(self, arg: Shape) -> gp_Pnt:
# check for infinite face
if isinstance(arg, Face) and any(
Precision.IsInfinite_s(x) for x in BRepTools.UVBounds_s(arg.wrapped)
):
# fall back to gp_Pln center
pln = arg.toPln()
center = Vector(pln.Location())
else:
center = arg.Center()
return center.toPnt()
def _getLin(self, arg: Shape) -> gp_Lin:
if isinstance(arg, (Edge, Wire)):
center = arg.Center()
tangent = arg.tangentAt()
else:
raise ValueError(f"Cannot construct a plane for {arg}.")
return gp_Lin(center.toPnt(), tangent.toDir())
def toPODs(self) -> Tuple[Constraint, ...]:
"""
Convert the constraint to a representation used by the solver.
NB: Compound constraints are decomposed into simple ones.
"""
# apply sublocation
args = tuple(
arg.located(loc * arg.location())
for arg, loc in zip(self.args, self.sublocs)
)
markers: List[Tuple[ConstraintMarker, ...]]
# convert to marker objects
if self.kind == "Axis":
markers = [(self._getAxis(args[0]), self._getAxis(args[1]),)]
elif self.kind == "Point":
markers = [(self._getPnt(args[0]), self._getPnt(args[1]))]
elif self.kind == "Plane":
markers = [
(self._getAxis(args[0]), self._getAxis(args[1]),),
(self._getPnt(args[0]), self._getPnt(args[1])),
]
elif self.kind == "PointInPlane":
markers = [(self._getPnt(args[0]), self._getPln(args[1]))]
elif self.kind == "PointOnLine":
markers = [(self._getPnt(args[0]), self._getLin(args[1]))]
elif self.kind == "Fixed":
markers = [(None,)]
elif self.kind == "FixedPoint":
markers = [(self._getPnt(args[0]),)]
elif self.kind == "FixedAxis":
markers = [(self._getAxis(args[0]),)]
elif self.kind == "FixedRotation":
markers = [(None,), (None,), (None,)]
elif self.kind == "FixedRotationAxis":
markers = [(None,)]
else:
raise ValueError(f"Unknown constraint kind {self.kind}")
# specify kinds of the simple constraint
if self.kind in CompoundConstraints:
kinds, converter = CompoundConstraints[self.kind]
params = converter(self.param,)
else:
kinds = (self.kind,)
params = (self.param,)
# builds the tuple and return
return tuple(zip(markers, kinds, params))
# Cost functions of simple constraints
def Quaternion(R):
m = ca.sumsqr(R)
u = 2 * R / (1 + m)
s = (1 - m) / (1 + m)
return s, u
def Rotate(v, R):
s, u = Quaternion(R)
return 2 * ca.dot(u, v) * u + (s ** 2 - ca.dot(u, u)) * v + 2 * s * ca.cross(u, v)
def Transform(v, T, R):
return Rotate(v, R) + T
def point_cost(
problem,
m1: gp_Pnt,
m2: gp_Pnt,
T1_0,
R1_0,
T2_0,
R2_0,
T1,
R1,
T2,
R2,
val: Optional[float] = None,
scale: float = 1,
) -> float:
val = 0 if val is None else val
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
m2_dm = ca.DM((m2.X(), m2.Y(), m2.Z()))
dummy = (
Transform(m1_dm, T1_0 + T1, R1_0 + R1) - Transform(m2_dm, T2_0 + T2, R2_0 + R2)
) / scale
if val == 0:
return ca.sumsqr(dummy)
return (ca.sumsqr(dummy) - (val / scale) ** 2) ** 2
def axis_cost(
problem,
m1: gp_Dir,
m2: gp_Dir,
T1_0,
R1_0,
T2_0,
R2_0,
T1,
R1,
T2,
R2,
val: Optional[float] = None,
scale: float = 1,
) -> float:
val = pi if val is None else val
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
m2_dm = ca.DM((m2.X(), m2.Y(), m2.Z()))
d1, d2 = (Rotate(m1_dm, R1_0 + R1), Rotate(m2_dm, R2_0 + R2))
if val == 0:
dummy = d1 - d2
return ca.sumsqr(dummy)
elif val == pi:
dummy = d1 + d2
return ca.sumsqr(dummy)
dummy = ca.dot(d1, d2) - ca.cos(val)
return dummy ** 2
def point_in_plane_cost(
problem,
m1: gp_Pnt,
m2: gp_Pln,
T1_0,
R1_0,
T2_0,
R2_0,
T1,
R1,
T2,
R2,
val: Optional[float] = None,
scale: float = 1,
) -> float:
val = 0 if val is None else val
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
m2_dir = m2.Axis().Direction()
m2_pnt = m2.Axis().Location().Translated(val * gp_Vec(m2_dir))
m2_dir_dm = ca.DM((m2_dir.X(), m2_dir.Y(), m2_dir.Z()))
m2_pnt_dm = ca.DM((m2_pnt.X(), m2_pnt.Y(), m2_pnt.Z()))
dummy = (
ca.dot(
Rotate(m2_dir_dm, R2_0 + R2),
Transform(m2_pnt_dm, T2_0 + T2, R2_0 + R2)
- Transform(m1_dm, T1_0 + T1, R1_0 + R1),
)
/ scale
)
return dummy ** 2
def point_on_line_cost(
problem,
m1: gp_Pnt,
m2: gp_Lin,
T1_0,
R1_0,
T2_0,
R2_0,
T1,
R1,
T2,
R2,
val: Optional[float] = None,
scale: float = 1,
) -> float:
val = 0 if val is None else val
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
m2_dir = m2.Direction()
m2_pnt = m2.Location()
m2_dir_dm = ca.DM((m2_dir.X(), m2_dir.Y(), m2_dir.Z()))
m2_pnt_dm = ca.DM((m2_pnt.X(), m2_pnt.Y(), m2_pnt.Z()))
d = Transform(m1_dm, T1_0 + T1, R1_0 + R1) - Transform(
m2_pnt_dm, T2_0 + T2, R2_0 + R2
)
n = Rotate(m2_dir_dm, R2_0 + R2)
dummy = (d - n * ca.dot(d, n)) / scale
if val == 0:
return ca.sumsqr(dummy)
return (ca.sumsqr(dummy) - val) ** 2
# dummy cost, fixed constraint is handled on variable level
def fixed_cost(
problem,
m1: Type[None],
T1_0,
R1_0,
T1,
R1,
val: Optional[Type[None]] = None,
scale: float = 1,
):
return None
def fixed_point_cost(
problem,
m1: gp_Pnt,
T1_0,
R1_0,
T1,
R1,
val: Tuple[float, float, float],
scale: float = 1,
):
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
dummy = (Transform(m1_dm, T1_0 + T1, R1_0 + R1) - ca.DM(val)) / scale
return ca.sumsqr(dummy)
def fixed_axis_cost(
problem,
m1: gp_Dir,
T1_0,
R1_0,
T1,
R1,
val: Tuple[float, float, float],
scale: float = 1,
):
m1_dm = ca.DM((m1.X(), m1.Y(), m1.Z()))
m_val = ca.DM(val) / ca.norm_2(ca.DM(val))
dummy = Rotate(m1_dm, R1_0 + R1) - m_val
return ca.sumsqr(dummy)
def fixed_rotation_cost(
problem,
m1: Type[None],
T1_0,
R1_0,
T1,
R1,
val: Tuple[float, float, float],
scale: float = 1,
):
q = gp_Quaternion()
q.SetEulerAngles(gp_Extrinsic_XYZ, *val)
q_dm = ca.DM((q.W(), q.X(), q.Y(), q.Z()))
dummy = 1 - ca.dot(ca.vertcat(*Quaternion(R1_0 + R1)), q_dm) ** 2
return dummy
# dictionary of individual constraint cost functions
costs: Dict[str, Callable[..., float]] = dict(
Point=point_cost,
Axis=axis_cost,
PointInPlane=point_in_plane_cost,
PointOnLine=point_on_line_cost,
Fixed=fixed_cost,
FixedPoint=fixed_point_cost,
FixedAxis=fixed_axis_cost,
FixedRotation=fixed_rotation_cost,
)
scaling: Dict[str, bool] = dict(
Point=True,
Axis=False,
PointInPlane=True,
PointOnLine=True,
Fixed=False,
FixedPoint=True,
FixedAxis=False,
FixedRotation=False,
)
# Actual solver class
class ConstraintSolver(object):
opti: ca.Opti
variables: List[Tuple[ca.MX, ca.MX]]
starting_points: List[Tuple[ca.MX, ca.MX]]
constraints: List[Tuple[Tuple[int, ...], Constraint]]
locked: List[int]
ne: int
nc: int
scale: float
def __init__(
self,
entities: List[Location],
constraints: List[Tuple[Tuple[int, ...], Constraint]],
locked: List[int] = [],
scale: float = 1,
):
self.scale = scale
self.opti = opti = ca.Opti()
self.variables = [
(scale * opti.variable(NDOF_V), opti.variable(NDOF_Q))
if i not in locked
else (opti.parameter(NDOF_V), opti.parameter(NDOF_Q))
for i, _ in enumerate(entities)
]
self.start_points = [
(opti.parameter(NDOF_V), opti.parameter(NDOF_Q)) for _ in entities
]
# initialize, add the unit quaternion constraints and handle locked
for i, ((T, R), (T0, R0), loc) in enumerate(
zip(self.variables, self.start_points, entities)
):
T0val, R0val = self._locToDOF6(loc)
opti.set_value(T0, T0val)
opti.set_value(R0, R0val)
if i in locked:
opti.set_value(T, (0, 0, 0))
opti.set_value(R, (0, 0, 0))
else:
opti.set_initial(T, (0.0, 0.0, 0.0))
opti.set_initial(R, (1e-2, 1e-2, 1e-2))
self.constraints = constraints
# additional book-keeping
self.ne = len(entities)
self.locked = locked
self.nc = len(self.constraints)
@staticmethod
def _locToDOF6(loc: Location) -> DOF6:
Tr = loc.wrapped.Transformation()
v = Tr.TranslationPart()
q = Tr.GetRotation()
alpha_2 = (1 - q.W()) / (1 + q.W())
a = (alpha_2 + 1) * q.X() / 2
b = (alpha_2 + 1) * q.Y() / 2
c = (alpha_2 + 1) * q.Z() / 2
return (v.X(), v.Y(), v.Z()), (a, b, c)
def _build_transform(self, T: ca.MX, R: ca.MX) -> gp_Trsf:
opti = self.opti
rv = gp_Trsf()
a, b, c = opti.value(R)
m = a ** 2 + b ** 2 + c ** 2
rv.SetRotation(
gp_Quaternion(
2 * a / (m + 1), 2 * b / (m + 1), 2 * c / (m + 1), (1 - m) / (m + 1),
)
)
rv.SetTranslationPart(gp_Vec(*opti.value(T)))
return rv
def solve(self, verbosity: int = 0) -> Tuple[List[Location], Dict[str, Any]]:
suppress_banner = "yes" if verbosity == 0 else "no"
opti = self.opti
constraints = self.constraints
variables = self.variables
start_points = self.start_points
# construct a penalty term
penalty = 0.0
for T, R in variables:
penalty += ca.sumsqr(ca.vertcat(T / self.scale, R))
# construct the objective
objective = 0.0
for ks, (ms, kind, params) in constraints:
# select the relevant variables and starting points
s_ks: List[ca.DM] = []
v_ks: List[ca.MX] = []
for k in ks:
s_ks.extend(start_points[k])
v_ks.extend(variables[k])
c = costs[kind](
opti,
*ms,
*s_ks,
*v_ks,
params,
scale=self.scale if scaling[kind] else 1,
)
if c is not None:
objective += c
opti.minimize(objective + 1e-16 * penalty)
# solve
opti.solver(
"ipopt",
{"print_time": False},
{
"acceptable_obj_change_tol": 1e-12,
"acceptable_iter": 1,
"tol": 1e-14,
"hessian_approximation": "exact",
"nlp_scaling_method": "none",
"honor_original_bounds": "yes",
"bound_relax_factor": 0,
"print_level": verbosity,
"sb": suppress_banner,
"print_timing_statistics": "no",
"linear_solver": "mumps",
},
)
sol = opti.solve_limited()
result = sol.stats()
result["opti"] = opti # this might be removed in the future
locs = [
Location(self._build_transform(T + T0, R + R0))
for (T, R), (T0, R0) in zip(variables, start_points)
]
return locs, result
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,474 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/utils.py | from ...cq import Workplane
from ..shapes import Compound, Shape
def toCompound(shape: Workplane) -> Compound:
return Compound.makeCompound(val for val in shape.vals() if isinstance(val, Shape))
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,475 | CadQuery/cadquery | refs/heads/master | /examples/Ex025_Swept_Helix.py | import cadquery as cq
r = 0.5 # Radius of the helix
p = 0.4 # Pitch of the helix - vertical distance between loops
h = 2.4 # Height of the helix - total height
# Helix
wire = cq.Wire.makeHelix(pitch=p, height=h, radius=r)
helix = cq.Workplane(obj=wire)
# Final result: A 2D shape swept along a helix.
result = (
cq.Workplane("XZ") # helix is moving up the Z axis
.center(r, 0) # offset isosceles trapezoid
.polyline(((-0.15, 0.1), (0.0, 0.05), (0, 0.35), (-0.15, 0.3)))
.close() # make edges a wire
.sweep(helix, isFrenet=True) # Frenet keeps orientation as expected
)
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,476 | CadQuery/cadquery | refs/heads/master | /cadquery/assembly.py | from functools import reduce
from typing import (
Union,
Optional,
List,
Dict,
Any,
overload,
Tuple,
Iterator,
cast,
get_args,
)
from typing_extensions import Literal
from typish import instance_of
from uuid import uuid1 as uuid
from .cq import Workplane
from .occ_impl.shapes import Shape, Compound
from .occ_impl.geom import Location
from .occ_impl.assembly import Color
from .occ_impl.solver import (
ConstraintKind,
ConstraintSolver,
ConstraintSpec as Constraint,
UnaryConstraintKind,
BinaryConstraintKind,
)
from .occ_impl.exporters.assembly import (
exportAssembly,
exportCAF,
exportVTKJS,
exportVRML,
exportGLTF,
STEPExportModeLiterals,
ExportModes,
)
from .selectors import _expression_grammar as _selector_grammar
# type definitions
AssemblyObjects = Union[Shape, Workplane, None]
ExportLiterals = Literal["STEP", "XML", "GLTF", "VTKJS", "VRML", "STL"]
PATH_DELIM = "/"
# entity selector grammar definition
def _define_grammar():
from pyparsing import (
Literal as Literal,
Word,
Optional,
alphas,
alphanums,
delimitedList,
)
Separator = Literal("@").suppress()
TagSeparator = Literal("?").suppress()
Name = delimitedList(
Word(alphas, alphanums + "_"), PATH_DELIM, combine=True
).setResultsName("name")
Tag = Word(alphas, alphanums + "_").setResultsName("tag")
Selector = _selector_grammar.setResultsName("selector")
SelectorType = (
Literal("solids") | Literal("faces") | Literal("edges") | Literal("vertices")
).setResultsName("selector_kind")
return (
Name
+ Optional(TagSeparator + Tag)
+ Optional(Separator + SelectorType + Separator + Selector)
)
_grammar = _define_grammar()
class Assembly(object):
"""Nested assembly of Workplane and Shape objects defining their relative positions."""
loc: Location
name: str
color: Optional[Color]
metadata: Dict[str, Any]
obj: AssemblyObjects
parent: Optional["Assembly"]
children: List["Assembly"]
objects: Dict[str, "Assembly"]
constraints: List[Constraint]
_solve_result: Optional[Dict[str, Any]]
def __init__(
self,
obj: AssemblyObjects = None,
loc: Optional[Location] = None,
name: Optional[str] = None,
color: Optional[Color] = None,
metadata: Optional[Dict[str, Any]] = None,
):
"""
construct an assembly
:param obj: root object of the assembly (default: None)
:param loc: location of the root object (default: None, interpreted as identity transformation)
:param name: unique name of the root object (default: None, resulting in an UUID being generated)
:param color: color of the added object (default: None)
:param metadata: a store for user-defined metadata (default: None)
:return: An Assembly object.
To create an empty assembly use::
assy = Assembly(None)
To create one constraint a root object::
b = Workplane().box(1, 1, 1)
assy = Assembly(b, Location(Vector(0, 0, 1)), name="root")
"""
self.obj = obj
self.loc = loc if loc else Location()
self.name = name if name else str(uuid())
self.color = color if color else None
self.metadata = metadata if metadata else {}
self.parent = None
self.children = []
self.constraints = []
self.objects = {self.name: self}
self._solve_result = None
def _copy(self) -> "Assembly":
"""
Make a deep copy of an assembly
"""
rv = self.__class__(self.obj, self.loc, self.name, self.color, self.metadata)
for ch in self.children:
ch_copy = ch._copy()
ch_copy.parent = rv
rv.children.append(ch_copy)
rv.objects[ch_copy.name] = ch_copy
rv.objects.update(ch_copy.objects)
return rv
@overload
def add(
self,
obj: "Assembly",
loc: Optional[Location] = None,
name: Optional[str] = None,
color: Optional[Color] = None,
) -> "Assembly":
"""
Add a subassembly to the current assembly.
:param obj: subassembly to be added
:param loc: location of the root object (default: None, resulting in the location stored in
the subassembly being used)
:param name: unique name of the root object (default: None, resulting in the name stored in
the subassembly being used)
:param color: color of the added object (default: None, resulting in the color stored in the
subassembly being used)
"""
...
@overload
def add(
self,
obj: AssemblyObjects,
loc: Optional[Location] = None,
name: Optional[str] = None,
color: Optional[Color] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> "Assembly":
"""
Add a subassembly to the current assembly with explicit location and name.
:param obj: object to be added as a subassembly
:param loc: location of the root object (default: None, interpreted as identity
transformation)
:param name: unique name of the root object (default: None, resulting in an UUID being
generated)
:param color: color of the added object (default: None)
:param metadata: a store for user-defined metadata (default: None)
"""
...
def add(self, arg, **kwargs):
"""
Add a subassembly to the current assembly.
"""
if isinstance(arg, Assembly):
# enforce unique names
name = kwargs["name"] if kwargs.get("name") else arg.name
if name in self.objects:
raise ValueError("Unique name is required")
subassy = arg._copy()
subassy.loc = kwargs["loc"] if kwargs.get("loc") else arg.loc
subassy.name = kwargs["name"] if kwargs.get("name") else arg.name
subassy.color = kwargs["color"] if kwargs.get("color") else arg.color
subassy.metadata = (
kwargs["metadata"] if kwargs.get("metadata") else arg.metadata
)
subassy.parent = self
self.children.append(subassy)
self.objects.update(subassy._flatten())
else:
assy = self.__class__(arg, **kwargs)
assy.parent = self
self.add(assy)
return self
def _query(self, q: str) -> Tuple[str, Optional[Shape]]:
"""
Execute a selector query on the assembly.
The query is expected to be in the following format:
name[?tag][@kind@args]
valid example include:
obj_name @ faces @ >Z
obj_name?tag1@faces@>Z
obj_name ? tag
obj_name
"""
tmp: Workplane
res: Workplane
query = _grammar.parseString(q, True)
name: str = query.name
obj = self.objects[name].obj
if isinstance(obj, Workplane) and query.tag:
tmp = obj._getTagged(query.tag)
elif isinstance(obj, (Workplane, Shape)):
tmp = Workplane().add(obj)
else:
raise ValueError("Workplane or Shape required to define a constraint")
if query.selector:
res = getattr(tmp, query.selector_kind)(query.selector)
else:
res = tmp
val = res.val()
return name, val if isinstance(val, Shape) else None
def _subloc(self, name: str) -> Tuple[Location, str]:
"""
Calculate relative location of an object in a subassembly.
Returns the relative positions as well as the name of the top assembly.
"""
rv = Location()
obj = self.objects[name]
name_out = name
if obj not in self.children and obj is not self:
locs = []
while not obj.parent is self:
locs.append(obj.loc)
obj = cast(Assembly, obj.parent)
name_out = obj.name
rv = reduce(lambda l1, l2: l1 * l2, locs)
return (rv, name_out)
@overload
def constrain(
self, q1: str, q2: str, kind: ConstraintKind, param: Any = None
) -> "Assembly":
...
@overload
def constrain(self, q1: str, kind: ConstraintKind, param: Any = None) -> "Assembly":
...
@overload
def constrain(
self,
id1: str,
s1: Shape,
id2: str,
s2: Shape,
kind: ConstraintKind,
param: Any = None,
) -> "Assembly":
...
@overload
def constrain(
self, id1: str, s1: Shape, kind: ConstraintKind, param: Any = None,
) -> "Assembly":
...
def constrain(self, *args, param=None):
"""
Define a new constraint.
"""
# dispatch on arguments
if len(args) == 2:
q1, kind = args
id1, s1 = self._query(q1)
elif len(args) == 3 and instance_of(args[1], UnaryConstraintKind):
q1, kind, param = args
id1, s1 = self._query(q1)
elif len(args) == 3:
q1, q2, kind = args
id1, s1 = self._query(q1)
id2, s2 = self._query(q2)
elif len(args) == 4:
q1, q2, kind, param = args
id1, s1 = self._query(q1)
id2, s2 = self._query(q2)
elif len(args) == 5:
id1, s1, id2, s2, kind = args
elif len(args) == 6:
id1, s1, id2, s2, kind, param = args
else:
raise ValueError(f"Incompatible arguments: {args}")
# handle unary and binary constraints
if instance_of(kind, UnaryConstraintKind):
loc1, id1_top = self._subloc(id1)
c = Constraint((id1_top,), (s1,), (loc1,), kind, param)
elif instance_of(kind, BinaryConstraintKind):
loc1, id1_top = self._subloc(id1)
loc2, id2_top = self._subloc(id2)
c = Constraint((id1_top, id2_top), (s1, s2), (loc1, loc2), kind, param)
else:
raise ValueError(f"Unknown constraint: {kind}")
self.constraints.append(c)
return self
def solve(self, verbosity: int = 0) -> "Assembly":
"""
Solve the constraints.
"""
# Get all entities and number them. First entity is marked as locked
ents = {}
i = 0
locked: List[int] = []
for c in self.constraints:
for name in c.objects:
if name not in ents:
ents[name] = i
i += 1
if (c.kind == "Fixed" or name == self.name) and ents[
name
] not in locked:
locked.append(ents[name])
# Lock the first occurring entity if needed.
if not locked:
unary_objects = [
c.objects[0]
for c in self.constraints
if instance_of(c.kind, UnaryConstraintKind)
]
binary_objects = [
c.objects[0]
for c in self.constraints
if instance_of(c.kind, BinaryConstraintKind)
]
for b in binary_objects:
if b not in unary_objects:
locked.append(ents[b])
break
# Lock the first occurring entity if needed.
if not locked:
locked.append(0)
locs = [self.objects[n].loc for n in ents]
# construct the constraint mapping
constraints = []
for c in self.constraints:
ixs = tuple(ents[obj] for obj in c.objects)
pods = c.toPODs()
for pod in pods:
constraints.append((ixs, pod))
# check if any constraints were specified
if not constraints:
raise ValueError("At least one constraint required")
# check if at least two entities are present
if len(ents) < 2:
raise ValueError("At least two entities need to be constrained")
# instantiate the solver
scale = self.toCompound().BoundingBox().DiagonalLength
solver = ConstraintSolver(locs, constraints, locked=locked, scale=scale)
# solve
locs_new, self._solve_result = solver.solve(verbosity)
# update positions
# find the inverse root loc
loc_root_inv = Location()
if self.obj:
for loc_new, n in zip(locs_new, ents):
if n == self.name:
loc_root_inv = loc_new.inverse
break
# update the positions
for loc_new, n in zip(locs_new, ents):
if n != self.name:
self.objects[n].loc = loc_root_inv * loc_new
return self
def save(
self,
path: str,
exportType: Optional[ExportLiterals] = None,
mode: STEPExportModeLiterals = "default",
tolerance: float = 0.1,
angularTolerance: float = 0.1,
**kwargs,
) -> "Assembly":
"""
Save assembly to a file.
:param path: Path and filename for writing.
:param exportType: export format (default: None, results in format being inferred form the path)
:param tolerance: the deflection tolerance, in model units. Only used for GLTF, VRML. Default 0.1.
:param angularTolerance: the angular tolerance, in radians. Only used for GLTF, VRML. Default 0.1.
:param \**kwargs: Additional keyword arguments. Only used for STEP.
See :meth:`~cadquery.occ_impl.exporters.assembly.exportAssembly`.
"""
# Make sure the export mode setting is correct
if mode not in get_args(STEPExportModeLiterals):
raise ValueError(f"Unknown assembly export mode {mode} for STEP")
if exportType is None:
t = path.split(".")[-1].upper()
if t in ("STEP", "XML", "VRML", "VTKJS", "GLTF", "STL"):
exportType = cast(ExportLiterals, t)
else:
raise ValueError("Unknown extension, specify export type explicitly")
if exportType == "STEP":
exportAssembly(self, path, mode, **kwargs)
elif exportType == "XML":
exportCAF(self, path)
elif exportType == "VRML":
exportVRML(self, path, tolerance, angularTolerance)
elif exportType == "GLTF":
exportGLTF(self, path, True, tolerance, angularTolerance)
elif exportType == "VTKJS":
exportVTKJS(self, path)
elif exportType == "STL":
self.toCompound().exportStl(path, tolerance, angularTolerance)
else:
raise ValueError(f"Unknown format: {exportType}")
return self
@classmethod
def load(cls, path: str) -> "Assembly":
raise NotImplementedError
@property
def shapes(self) -> List[Shape]:
"""
List of Shape objects in the .obj field
"""
rv: List[Shape] = []
if isinstance(self.obj, Shape):
rv = [self.obj]
elif isinstance(self.obj, Workplane):
rv = [el for el in self.obj.vals() if isinstance(el, Shape)]
return rv
def traverse(self) -> Iterator[Tuple[str, "Assembly"]]:
"""
Yield (name, child) pairs in a bottom-up manner
"""
for ch in self.children:
for el in ch.traverse():
yield el
yield (self.name, self)
def _flatten(self, parents=[]):
"""
Generate a dict with all ancestors with keys indicating parent-child relations.
"""
rv = {}
for ch in self.children:
rv.update(ch._flatten(parents=parents + [self.name]))
rv[PATH_DELIM.join(parents + [self.name])] = self
return rv
def __iter__(
self,
loc: Optional[Location] = None,
name: Optional[str] = None,
color: Optional[Color] = None,
) -> Iterator[Tuple[Shape, str, Location, Optional[Color]]]:
"""
Assembly iterator yielding shapes, names, locations and colors.
"""
name = f"{name}/{self.name}" if name else self.name
loc = loc * self.loc if loc else self.loc
color = self.color if self.color else color
if self.obj:
yield self.obj if isinstance(self.obj, Shape) else Compound.makeCompound(
s for s in self.obj.vals() if isinstance(s, Shape)
), name, loc, color
for ch in self.children:
yield from ch.__iter__(loc, name, color)
def toCompound(self) -> Compound:
"""
Returns a Compound made from this Assembly (including all children) with the
current Locations applied. Usually this method would only be used after solving.
"""
shapes = self.shapes
shapes.extend((child.toCompound() for child in self.children))
return Compound.makeCompound(shapes).locate(self.loc)
def _repr_javascript_(self):
"""
Jupyter 3D representation support
"""
from .occ_impl.jupyter_tools import display
return display(self)._repr_javascript_()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,477 | CadQuery/cadquery | refs/heads/master | /tests/test_workplanes.py | """
Tests basic workplane functionality
"""
# core modules
# my modules
from cadquery import *
from tests import BaseTest, toTuple
xAxis_ = Vector(1, 0, 0)
yAxis_ = Vector(0, 1, 0)
zAxis_ = Vector(0, 0, 1)
xInvAxis_ = Vector(-1, 0, 0)
yInvAxis_ = Vector(0, -1, 0)
zInvAxis_ = Vector(0, 0, -1)
class TestWorkplanes(BaseTest):
def testYZPlaneOrigins(self):
# xy plane-- with origin at x=0.25
base = Vector(0.25, 0, 0)
p = Plane(base, Vector(0, 1, 0), Vector(1, 0, 0))
# origin is always (0,0,0) in local coordinates
self.assertTupleAlmostEquals((0, 0, 0), p.toLocalCoords(p.origin).toTuple(), 2)
# (0,0,0) is always the original base in global coordinates
self.assertTupleAlmostEquals(
base.toTuple(), p.toWorldCoords((0, 0)).toTuple(), 2
)
def testXYPlaneOrigins(self):
base = Vector(0, 0, 0.25)
p = Plane(base, Vector(1, 0, 0), Vector(0, 0, 1))
# origin is always (0,0,0) in local coordinates
self.assertTupleAlmostEquals((0, 0, 0), p.toLocalCoords(p.origin).toTuple(), 2)
# (0,0,0) is always the original base in global coordinates
self.assertTupleAlmostEquals(
toTuple(base), p.toWorldCoords((0, 0)).toTuple(), 2
)
def testXZPlaneOrigins(self):
base = Vector(0, 0.25, 0)
p = Plane(base, Vector(0, 0, 1), Vector(0, 1, 0))
# (0,0,0) is always the original base in global coordinates
self.assertTupleAlmostEquals(
toTuple(base), p.toWorldCoords((0, 0)).toTuple(), 2
)
# origin is always (0,0,0) in local coordinates
self.assertTupleAlmostEquals((0, 0, 0), p.toLocalCoords(p.origin).toTuple(), 2)
def testPlaneBasics(self):
p = Plane.XY()
# local to world
self.assertTupleAlmostEquals(
(1.0, 1.0, 0), p.toWorldCoords((1, 1)).toTuple(), 2
)
self.assertTupleAlmostEquals(
(-1.0, -1.0, 0), p.toWorldCoords((-1, -1)).toTuple(), 2
)
# world to local
self.assertTupleAlmostEquals(
(-1.0, -1.0), p.toLocalCoords(Vector(-1, -1, 0)).toTuple(), 2
)
self.assertTupleAlmostEquals(
(1.0, 1.0), p.toLocalCoords(Vector(1, 1, 0)).toTuple(), 2
)
p = Plane.YZ()
self.assertTupleAlmostEquals(
(0, 1.0, 1.0), p.toWorldCoords((1, 1)).toTuple(), 2
)
# world to local
self.assertTupleAlmostEquals(
(1.0, 1.0), p.toLocalCoords(Vector(0, 1, 1)).toTuple(), 2
)
p = Plane.XZ()
r = p.toWorldCoords((1, 1)).toTuple()
self.assertTupleAlmostEquals((1.0, 0.0, 1.0), r, 2)
# world to local
self.assertTupleAlmostEquals(
(1.0, 1.0), p.toLocalCoords(Vector(1, 0, 1)).toTuple(), 2
)
def testOffsetPlanes(self):
"Tests that a plane offset from the origin works ok too"
p = Plane.XY(origin=(10.0, 10.0, 0))
self.assertTupleAlmostEquals(
(11.0, 11.0, 0.0), p.toWorldCoords((1.0, 1.0)).toTuple(), 2
)
self.assertTupleAlmostEquals(
(2.0, 2.0), p.toLocalCoords(Vector(12.0, 12.0, 0)).toTuple(), 2
)
# TODO test these offsets in the other dimensions too
p = Plane.YZ(origin=(0, 2, 2))
self.assertTupleAlmostEquals(
(0.0, 5.0, 5.0), p.toWorldCoords((3.0, 3.0)).toTuple(), 2
)
self.assertTupleAlmostEquals(
(10, 10.0, 0.0), p.toLocalCoords(Vector(0.0, 12.0, 12.0)).toTuple(), 2
)
p = Plane.XZ(origin=(2, 0, 2))
r = p.toWorldCoords((1.0, 1.0)).toTuple()
self.assertTupleAlmostEquals((3.0, 0.0, 3.0), r, 2)
self.assertTupleAlmostEquals(
(10.0, 10.0), p.toLocalCoords(Vector(12.0, 0.0, 12.0)).toTuple(), 2
)
def testXYPlaneBasics(self):
p = Plane.named("XY")
self.assertTupleAlmostEquals(p.zDir.toTuple(), zAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), xAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), yAxis_.toTuple(), 4)
def testYZPlaneBasics(self):
p = Plane.named("YZ")
self.assertTupleAlmostEquals(p.zDir.toTuple(), xAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), yAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), zAxis_.toTuple(), 4)
def testZXPlaneBasics(self):
p = Plane.named("ZX")
self.assertTupleAlmostEquals(p.zDir.toTuple(), yAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), zAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), xAxis_.toTuple(), 4)
def testXZPlaneBasics(self):
p = Plane.named("XZ")
self.assertTupleAlmostEquals(p.zDir.toTuple(), yInvAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), xAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), zAxis_.toTuple(), 4)
def testYXPlaneBasics(self):
p = Plane.named("YX")
self.assertTupleAlmostEquals(p.zDir.toTuple(), zInvAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), yAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), xAxis_.toTuple(), 4)
def testZYPlaneBasics(self):
p = Plane.named("ZY")
self.assertTupleAlmostEquals(p.zDir.toTuple(), xInvAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.xDir.toTuple(), zAxis_.toTuple(), 4)
self.assertTupleAlmostEquals(p.yDir.toTuple(), yAxis_.toTuple(), 4)
def test_mirror(self):
"""Create a unit box and mirror it so that it doubles in size"""
b2 = Workplane().box(1, 1, 1)
b2 = b2.mirror("XY", (0, 0, 0.5), union=True)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [1.0, 1.0, 2]
self.assertAlmostEqual(b2.findSolid().Volume(), 2, 5)
def test_all_planes(self):
b2 = Workplane().box(1, 1, 1)
for p in ["XY", "YX", "XZ", "ZX", "YZ", "ZY"]:
b2 = b2.mirror(p)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [1.0, 1.0, 1.0]
self.assertAlmostEqual(b2.findSolid().Volume(), 1, 5)
def test_bad_plane_input(self):
b2 = Workplane().box(1, 1, 1)
with self.assertRaises(ValueError) as context:
b2.mirror(b2.edges())
self.assertTrue("Face required, got" in str(context.exception))
def test_mirror_axis(self):
"""Create a unit box and mirror it so that it doubles in size"""
b2 = Workplane().box(1, 1, 1)
b2 = b2.mirror((0, 0, 1), (0, 0, 0.5), union=True)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [1.0, 1.0, 2]
self.assertAlmostEqual(b2.findSolid().Volume(), 2, 5)
def test_mirror_workplane(self):
"""Create a unit box and mirror it so that it doubles in size"""
b2 = Workplane().box(1, 1, 1)
# double in Z plane
b2 = b2.mirror(b2.faces(">Z"), union=True)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [1.0, 1.0, 2]
self.assertAlmostEqual(b2.findSolid().Volume(), 2, 5)
# double in Y plane
b2 = b2.mirror(b2.faces(">Y"), union=True)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [1.0, 2.0, 2]
self.assertAlmostEqual(b2.findSolid().Volume(), 4, 5)
# double in X plane
b2 = b2.mirror(b2.faces(">X"), union=True)
bbBox = b2.findSolid().BoundingBox()
assert [bbBox.xlen, bbBox.ylen, bbBox.zlen] == [2.0, 2.0, 2]
self.assertAlmostEqual(b2.findSolid().Volume(), 8, 5)
def test_mirror_equivalence(self):
"""test that the plane string, plane normal and face object perform a mirror operation in the same way"""
boxes = []
boxDims = 1
for i in range(3): # create 3 sets of identical boxes
boxTmp = Workplane("XY").box(boxDims, boxDims, boxDims)
boxTmp = boxTmp.translate([i * 2, 0, boxDims / 2])
boxes.append(boxTmp)
# 3 different types of plane definition
planeArg = ["XY", (0, 0, 1), boxes[0].faces("<Z")]
planeOffset = (0, 0, 0.5) # use the safe offset for each
boxResults = [] # store the resulting mirrored objects
for b, p in zip(boxes, planeArg):
boxResults.append(b.mirror(p, planeOffset, union=True))
# all resulting boxes should be equal to each other
for i in range(len(boxResults) - 1):
curBoxDims = boxResults[i].findSolid().BoundingBox() # get bbox dims
nextBoxDims = boxResults[i + 1].findSolid().BoundingBox() # get bbox dims
cbd = (curBoxDims.xlen, curBoxDims.ylen, curBoxDims.zlen)
nbd = (nextBoxDims.xlen, nextBoxDims.ylen, nextBoxDims.zlen)
self.assertTupleAlmostEquals(cbd, nbd, 4)
self.assertAlmostEqual(
boxResults[i].findSolid().Volume(),
boxResults[i + 1].findSolid().Volume(),
5,
)
def test_mirror_face(self):
"""Create a triangle and mirror into a unit box"""
r = Workplane("XY").line(0, 1).line(1, -1).close().extrude(1)
bbBox = r.findSolid().BoundingBox()
self.assertTupleAlmostEquals(
(bbBox.xlen, bbBox.ylen, bbBox.zlen), (1.0, 1.0, 1.0), 4
)
self.assertAlmostEqual(r.findSolid().Volume(), 0.5, 5)
r = r.mirror(r.faces().objects[1], union=True)
bbBox = r.findSolid().BoundingBox()
self.assertTupleAlmostEquals(
(bbBox.xlen, bbBox.ylen, bbBox.zlen), (1.0, 1.0, 1.0), 4
)
self.assertAlmostEqual(r.findSolid().Volume(), 1.0, 5)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,478 | CadQuery/cadquery | refs/heads/master | /examples/Ex100_Lego_Brick.py | # This script can create any regular rectangular Lego(TM) Brick
import cadquery as cq
#####
# Inputs
######
lbumps = 1 # number of bumps long
wbumps = 1 # number of bumps wide
thin = True # True for thin, False for thick
#
# Lego Brick Constants-- these make a lego brick a lego :)
#
pitch = 8.0
clearance = 0.1
bumpDiam = 4.8
bumpHeight = 1.8
if thin:
height = 3.2
else:
height = 9.6
t = (pitch - (2 * clearance) - bumpDiam) / 2.0
postDiam = pitch - t # works out to 6.5
total_length = lbumps * pitch - 2.0 * clearance
total_width = wbumps * pitch - 2.0 * clearance
# make the base
s = cq.Workplane("XY").box(total_length, total_width, height)
# shell inwards not outwards
s = s.faces("<Z").shell(-1.0 * t)
# make the bumps on the top
s = (
s.faces(">Z")
.workplane()
.rarray(pitch, pitch, lbumps, wbumps, True)
.circle(bumpDiam / 2.0)
.extrude(bumpHeight)
)
# add posts on the bottom. posts are different diameter depending on geometry
# solid studs for 1 bump, tubes for multiple, none for 1x1
tmp = s.faces("<Z").workplane(invert=True)
if lbumps > 1 and wbumps > 1:
tmp = (
tmp.rarray(pitch, pitch, lbumps - 1, wbumps - 1, center=True)
.circle(postDiam / 2.0)
.circle(bumpDiam / 2.0)
.extrude(height - t)
)
elif lbumps > 1:
tmp = (
tmp.rarray(pitch, pitch, lbumps - 1, 1, center=True)
.circle(t)
.extrude(height - t)
)
elif wbumps > 1:
tmp = (
tmp.rarray(pitch, pitch, 1, wbumps - 1, center=True)
.circle(t)
.extrude(height - t)
)
else:
tmp = s
# Render the solid
show_object(tmp)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,479 | CadQuery/cadquery | refs/heads/master | /examples/Ex012_Creating_Workplanes_on_Faces.py | import cadquery as cq
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a 3D box that will have a hole placed in it later.
result = cq.Workplane("front").box(2, 3, 0.5)
# 3. Find the top-most face with the >Z max selector.
# 3a. Establish a new workplane to build geometry on.
# 3b. Create a hole down into the box.
result = result.faces(">Z").workplane().hole(0.5)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,480 | CadQuery/cadquery | refs/heads/master | /examples/Ex002_Block_With_Bored_Center_Hole.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
length = 80.0 # Length of the block
height = 60.0 # Height of the block
thickness = 10.0 # Thickness of the block
center_hole_dia = 22.0 # Diameter of center hole in block
# Create a block based on the dimensions above and add a 22mm center hole.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
# 2. The highest (max) Z face is selected and a new workplane is created on it.
# 3. The new workplane is used to drill a hole through the block.
# 3a. The hole is automatically centered in the workplane.
result = (
cq.Workplane("XY")
.box(length, height, thickness)
.faces(">Z")
.workplane()
.hole(center_hole_dia)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,481 | CadQuery/cadquery | refs/heads/master | /doc/ext/sphinx_autodoc_multimethod.py | from types import ModuleType
from typing import Any, List, Tuple, ValuesView
from multimethod import multimethod
import re
from sphinx.ext.autosummary import Autosummary
from sphinx.ext.autosummary import (
get_import_prefixes_from_env,
ImportExceptionGroup,
mangle_signature,
extract_summary,
)
from docutils.statemachine import StringList
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.ext.autodoc import MethodDocumenter as SphinxMethodDocumenter
from sphinx.util import inspect, logging
from sphinx.util.inspect import evaluate_signature, safe_getattr, stringify_signature
from sphinx.util.typing import get_type_hints
logger = logging.getLogger(__name__)
def get_first(obj):
"""Use to return first element (first param type annotation or first registered multimethod)."""
return next(iter(obj))
patindent = re.compile(r"(\W*)")
def process_docstring_multimethod(app, what, name, obj, options, lines):
"""multimethod docstring customization
Remove extraneous signatures and combine docstrings if docstring also defined
in registered methods. Requires sphinx-build -E if rebuilding docs.
"""
methods = []
if what == "method" and isinstance(obj, multimethod):
# instance or static method
# handle functools.singledispatch style register (multiple names)
if obj.pending:
methods = set(m.__name__ for m in obj.pending)
else:
methods = set(m.__name__ for m in obj.values())
elif what == "method" and inspect.isclassmethod(obj) and hasattr(obj, "pending"):
if obj.pending:
methods = set(m.__name__ for m in obj.pending)
else:
methods = set(m.__name__ for m in obj.__func__.values())
if methods:
lines_replace = []
patsig = re.compile(rf"\W*[{'|'.join(methods)}]+\(.*\).*")
indent = -1
for line in lines:
if indent < 0:
# fix indent when multiple docstrings defined
if m := patindent.match(line):
indent = len(m.group(1))
else:
indent = 0
if patsig.match(line):
lines_replace.append("")
else:
lines_replace.append(line[indent:])
del lines[:]
lines.extend(lines_replace)
class MultimethodAutosummary(Autosummary):
"""Customize autosummary multimethod signature."""
def get_items(self, names: List[str]) -> List[Tuple[str, str, str, str]]:
"""Try to import the given names, and return a list of
``[(name, signature, summary_string, real_name), ...]``.
"""
prefixes = get_import_prefixes_from_env(self.env)
items: List[Tuple[str, str, str, str]] = []
max_item_chars = 50
for name in names:
display_name = name
if name.startswith("~"):
name = name[1:]
display_name = name.split(".")[-1]
try:
real_name, obj, parent, modname = self.import_by_name(
name, prefixes=prefixes
)
except ImportExceptionGroup as exc:
errors = list(
set("* %s: %s" % (type(e).__name__, e) for e in exc.exceptions)
)
logger.warning(
__("autosummary: failed to import %s.\nPossible hints:\n%s"),
name,
"\n".join(errors),
location=self.get_location(),
)
continue
self.bridge.result = StringList() # initialize for each documenter
full_name = real_name
if not isinstance(obj, ModuleType):
# give explicitly separated module name, so that members
# of inner classes can be documented
full_name = modname + "::" + full_name[len(modname) + 1 :]
# NB. using full_name here is important, since Documenters
# handle module prefixes slightly differently
documenter = self.create_documenter(self.env.app, obj, parent, full_name)
if not documenter.parse_name():
logger.warning(
__("failed to parse name %s"),
real_name,
location=self.get_location(),
)
items.append((display_name, "", "", real_name))
continue
if not documenter.import_object():
logger.warning(
__("failed to import object %s"),
real_name,
location=self.get_location(),
)
items.append((display_name, "", "", real_name))
continue
# try to also get a source code analyzer for attribute docs
try:
documenter.analyzer = ModuleAnalyzer.for_module(
documenter.get_real_modname()
)
# parse right now, to get PycodeErrors on parsing (results will
# be cached anyway)
documenter.analyzer.find_attr_docs()
except PycodeError as err:
logger.debug("[autodoc] module analyzer failed: %s", err)
# no source file -- e.g. for builtin and C modules
documenter.analyzer = None
# -- Grab the signature
try:
sig = documenter.format_signature(show_annotation=False)
# -- multimethod customization
if isinstance(obj, multimethod):
sig = "(...)"
# -- end customization
except TypeError:
# the documenter does not support ``show_annotation`` option
sig = documenter.format_signature()
if not sig:
sig = ""
else:
max_chars = max(10, max_item_chars - len(display_name))
sig = mangle_signature(sig, max_chars=max_chars)
# -- Grab the summary
documenter.add_content(None)
summary = extract_summary(self.bridge.result.data[:], self.state.document)
items.append((display_name, sig, summary, real_name))
return items
class MethodDocumenter(SphinxMethodDocumenter):
"""Customize to append multimethod signatures."""
def append_signature_multiple_dispatch(self, methods: ValuesView[Any]):
sigs = []
for dispatchmeth in methods:
documenter = MethodDocumenter(self.directive, "")
documenter.parent = self.parent
documenter.object = dispatchmeth
documenter.objpath = [None]
sigs.append(documenter.format_signature())
return sigs
def format_signature(self, **kwargs: Any) -> str:
if self.config.autodoc_typehints_format == "short":
kwargs.setdefault("unqualified_typehints", True)
sigs = []
if (
self.analyzer
and ".".join(self.objpath) in self.analyzer.overloads
and self.config.autodoc_typehints != "none"
):
# Use signatures for overloaded methods instead of the implementation method.
overloaded = True
else:
overloaded = False
sig = super(SphinxMethodDocumenter, self).format_signature(**kwargs)
sigs.append(sig)
meth = self.parent.__dict__.get(self.objpath[-1])
if inspect.is_singledispatch_method(meth):
# append signature of singledispatch'ed functions
for typ, func in meth.dispatcher.registry.items():
if typ is object:
pass # default implementation. skipped.
else:
dispatchmeth = self.annotate_to_first_argument(func, typ)
if dispatchmeth:
documenter = MethodDocumenter(self.directive, "")
documenter.parent = self.parent
documenter.object = dispatchmeth
documenter.objpath = [None]
sigs.append(documenter.format_signature())
# -- multimethod customization
elif isinstance(meth, multimethod):
if meth.pending:
methods = meth.pending
else:
methods = set(meth.values())
sigs = self.append_signature_multiple_dispatch(methods)
elif inspect.isclassmethod(self.object) and hasattr(self.object, "pending"):
if self.object.pending:
methods = self.object.pending
else:
methods = set(self.object.__func__.values())
sigs = self.append_signature_multiple_dispatch(methods)
elif inspect.isstaticmethod(meth) and isinstance(self.object, multimethod):
sigs = []
methods = self.object.values()
for dispatchmeth in methods:
actual = inspect.signature(
dispatchmeth,
bound_method=False,
type_aliases=self.config.autodoc_type_aliases,
)
sig = stringify_signature(actual, **kwargs)
sigs.append(sig)
# -- end customization
if overloaded:
if inspect.isstaticmethod(
self.object, cls=self.parent, name=self.object_name
):
actual = inspect.signature(
self.object,
bound_method=False,
type_aliases=self.config.autodoc_type_aliases,
)
else:
actual = inspect.signature(
self.object,
bound_method=True,
type_aliases=self.config.autodoc_type_aliases,
)
__globals__ = safe_getattr(self.object, "__globals__", {})
for overload in self.analyzer.overloads.get(".".join(self.objpath)):
overload = self.merge_default_value(actual, overload)
overload = evaluate_signature(
overload, __globals__, self.config.autodoc_type_aliases
)
if not inspect.isstaticmethod(
self.object, cls=self.parent, name=self.object_name
):
parameters = list(overload.parameters.values())
overload = overload.replace(parameters=parameters[1:])
sig = stringify_signature(overload, **kwargs)
sigs.append(sig)
return "\n".join(sigs)
def setup(app):
app.connect("autodoc-process-docstring", process_docstring_multimethod)
app.add_directive("autosummary", MultimethodAutosummary, override=True)
app.add_autodocumenter(MethodDocumenter, override=True)
return {"parallel_read_safe": True, "parallel_write_safe": True}
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,482 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/vtk.py | from vtkmodules.vtkIOXML import vtkXMLPolyDataWriter
from ..shapes import Shape
def exportVTP(
shape: Shape, fname: str, tolerance: float = 0.1, angularTolerance: float = 0.1
):
writer = vtkXMLPolyDataWriter()
writer.SetFileName(fname)
writer.SetInputData(shape.toVtkPolyData(tolerance, angularTolerance))
writer.Write()
def toString(
shape: Shape, tolerance: float = 1e-3, angularTolerance: float = 0.1
) -> str:
writer = vtkXMLPolyDataWriter()
writer.SetWriteToOutputString(True)
writer.SetInputData(shape.toVtkPolyData(tolerance, angularTolerance, True))
writer.Write()
return writer.GetOutputString()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,483 | CadQuery/cadquery | refs/heads/master | /examples/Ex005_Extruded_Lines_and_Arcs.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
width = 2.0 # Overall width of the plate
thickness = 0.25 # Thickness of the plate
# Extrude a plate outline made of lines and an arc
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Draws a line from the origin to an X position of the plate's width.
# 2a. The starting point of a 2D drawing like this will be at the center of the
# workplane (0, 0) unless the moveTo() function moves the starting point.
# 3. A line is drawn from the last position straight up in the Y direction
# 1.0 millimeters.
# 4. An arc is drawn from the last point, through point (1.0, 1.5) which is
# half-way back to the origin in the X direction and 0.5 mm above where
# the last line ended at. The arc then ends at (0.0, 1.0), which is 1.0 mm
# above (in the Y direction) where our first line started from.
# 5. An arc is drawn from the last point that ends on (-0.5, 1.0), the sag of
# the curve 0.2 determines that the curve is concave with the midpoint 0.1 mm
# from the arc baseline. If the sag was -0.2 the arc would be convex.
# This convention is valid when the profile is drawn counterclockwise.
# The reverse is true if the profile is drawn clockwise.
# Clockwise: +sag => convex, -sag => concave
# Counterclockwise: +sag => concave, -sag => convex
# 6. An arc is drawn from the last point that ends on (-0.7, -0.2), the arc is
# determined by the radius of -1.5 mm.
# Clockwise: +radius => convex, -radius => concave
# Counterclockwise: +radius => concave, -radius => convex
# 7. close() is called to automatically draw the last line for us and close
# the sketch so that it can be extruded.
# 7a. Without the close(), the 2D sketch will be left open and the extrude
# operation will provide unpredictable results.
# 8. The 2D sketch is extruded into a solid object of the specified thickness.
result = (
cq.Workplane("front")
.lineTo(width, 0)
.lineTo(width, 1.0)
.threePointArc((1.0, 1.5), (0.0, 1.0))
.sagittaArc((-0.5, 1.0), 0.2)
.radiusArc((-0.7, -0.2), -1.5)
.close()
.extrude(thickness)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,484 | CadQuery/cadquery | refs/heads/master | /tests/test_cadquery.py | """
This module tests cadquery creation and manipulation functions
"""
# system modules
import math, os.path, time, tempfile
from random import random
from random import randrange
from itertools import product
from pytest import approx, raises
# my modules
from cadquery import *
from cadquery import occ_impl
from tests import (
BaseTest,
writeStringToFile,
makeUnitCube,
readFileAsString,
makeUnitSquareWire,
makeCube,
)
# test data directory
testdataDir = os.path.join(os.path.dirname(__file__), "testdata")
# where unit test output will be saved
OUTDIR = tempfile.gettempdir()
SUMMARY_FILE = os.path.join(OUTDIR, "testSummary.html")
SUMMARY_TEMPLATE = """<html>
<head>
<style type="text/css">
.testResult{
background: #eeeeee;
margin: 50px;
border: 1px solid black;
}
</style>
</head>
<body>
<!--TEST_CONTENT-->
</body>
</html>"""
TEST_RESULT_TEMPLATE = """
<div class="testResult"><h3>%(name)s</h3>
%(svg)s
</div>
<!--TEST_CONTENT-->
"""
# clean up any summary file that is in the output directory.
# i know, this sux, but there is no other way to do this in 2.6, as we cannot do class fixtures till 2.7
writeStringToFile(SUMMARY_TEMPLATE, SUMMARY_FILE)
class TestCadQuery(BaseTest):
def tearDown(self):
"""
Update summary with data from this test.
This is a really hacky way of doing it-- we get a startup event from module load,
but there is no way in unittest to get a single shutdown event-- except for stuff in 2.7 and above
So what we do here is to read the existing file, stick in more content, and leave it
"""
svgFile = os.path.join(OUTDIR, self._testMethodName + ".svg")
# all tests do not produce output
if os.path.exists(svgFile):
existingSummary = readFileAsString(SUMMARY_FILE)
svgText = readFileAsString(svgFile)
svgText = svgText.replace(
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>', ""
)
# now write data into the file
# the content we are replacing it with also includes the marker, so it can be replaced again
existingSummary = existingSummary.replace(
"<!--TEST_CONTENT-->",
TEST_RESULT_TEMPLATE % (dict(svg=svgText, name=self._testMethodName)),
)
writeStringToFile(existingSummary, SUMMARY_FILE)
def saveModel(self, shape):
"""
shape must be a CQ object
Save models in SVG and STEP format
"""
shape.exportSvg(os.path.join(OUTDIR, self._testMethodName + ".svg"))
shape.val().exportStep(os.path.join(OUTDIR, self._testMethodName + ".step"))
def testToOCC(self):
"""
Tests to make sure that a CadQuery object is converted correctly to a OCC object.
"""
r = Workplane("XY").rect(5, 5).extrude(5)
r = r.toOCC()
import OCP
self.assertEqual(type(r), OCP.TopoDS.TopoDS_Solid)
def testToSVG(self):
"""
Tests to make sure that a CadQuery object is converted correctly to SVG
"""
r = Workplane("XY").rect(5, 5).extrude(5)
r_str = r.toSvg()
# Make sure that a couple of sections from the SVG output make sense
self.assertTrue(r_str.index('path d="M') > 0)
self.assertTrue(
r_str.index('line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3"') > 0
)
def testCubePlugin(self):
"""
Tests a plugin that combines cubes together with a base
:return:
"""
# make the plugin method
def makeCubes(self, length):
# self refers to the CQ or Workplane object
# create the solid
s = Solid.makeBox(length, length, length, Vector(0, 0, 0))
# use CQ utility method to iterate over the stack an position the cubes
return self.eachpoint(lambda loc: s.located(loc), True)
# link the plugin in
Workplane.makeCubes = makeCubes
# call it
result = (
Workplane("XY")
.box(6.0, 8.0, 0.5)
.faces(">Z")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
)
result = result.makeCubes(1.0)
result = result.combineSolids()
self.saveModel(result)
self.assertEqual(1, result.solids().size())
def testCylinderPlugin(self):
"""
Tests a cylinder plugin.
The plugin creates cylinders of the specified radius and height for each item on the stack
This is a very short plugin that illustrates just about the simplest possible
plugin
"""
def cylinders(self, radius, height):
# construct a cylinder at (0,0,0)
c = Solid.makeCylinder(radius, height, Vector(0, 0, 0))
# combine all the cylinders into a single compound
r = self.eachpoint(lambda loc: c.located(loc), True).combineSolids()
return r
Workplane.cyl = cylinders
# now test. here we want weird workplane to see if the objects are transformed right
s = (
Workplane(Plane(Vector((0, 0, 0)), Vector((1, -1, 0)), Vector((1, 1, 0))))
.rect(2.0, 3.0, forConstruction=True)
.vertices()
.cyl(0.25, 0.5)
)
self.assertEqual(4, s.solids().size())
self.saveModel(s)
def testPolygonPlugin(self):
"""
Tests a plugin to make regular polygons around points on the stack
Demonstrations using eachpoint to allow working in local coordinates
to create geometry
"""
def rPoly(self, nSides, diameter):
def _makePolygon(loc):
# pnt is a vector in local coordinates
angle = 2.0 * math.pi / nSides
pnts = []
for i in range(nSides + 1):
pnts.append(
Vector(
(diameter / 2.0 * math.cos(angle * i)),
(diameter / 2.0 * math.sin(angle * i)),
0,
)
)
return Wire.makePolygon(pnts).located(loc)
return self.eachpoint(_makePolygon, True)
Workplane.rPoly = rPoly
s = (
Workplane("XY")
.box(4.0, 4.0, 0.25)
.faces(">Z")
.workplane()
.rect(2.0, 2.0, forConstruction=True)
.vertices()
.rPoly(5, 0.5)
.cutThruAll()
)
# 6 base sides, 4 pentagons, 5 sides each = 26
self.assertEqual(26, s.faces().size())
self.saveModel(s)
def testFluentMethodInheritance(self):
"""
Tests that a derived class inherits fluent methods which return
instances of derived class when inherited.
"""
class ExtendedWorkplane(Workplane):
def nonExistentInWorkplane(self):
pass
# Call an inherited fluent method:
wp = ExtendedWorkplane("XY").moveTo(1, 2)
# Verify that the inherited method returned an instance of the derived
# class:
self.assertEqual(type(wp), ExtendedWorkplane)
# The following is redundant, but can make the use case clearer.
# This must not raise an AttributeError:
wp.nonExistentInWorkplane()
def testPointList(self):
"""
Tests adding points and using them
"""
c = CQ(makeUnitCube())
s = c.faces(">Z").workplane().pushPoints([(-0.3, 0.3), (0.3, 0.3), (0, 0)])
self.assertEqual(3, s.size())
# TODO: is the ability to iterate over points with circle really worth it?
# maybe we should just require using all() and a loop for this. the semantics and
# possible combinations got too hard ( ie, .circle().circle() ) was really odd
body = s.circle(0.05).cutThruAll()
self.saveModel(body)
self.assertEqual(9, body.faces().size())
# Test the case when using eachpoint with only a blank workplane
def callback_fn(loc):
self.assertEqual(
Vector(0, 0, 0), Vector(loc.wrapped.Transformation().TranslationPart())
)
r = Workplane("XY")
r.objects = []
r.eachpoint(callback_fn)
def testWorkplaneFromFace(self):
# make a workplane on the top face
s = CQ(makeUnitCube()).faces(">Z").workplane()
r = s.circle(0.125).cutBlind(-2.0)
self.saveModel(r)
# the result should have 7 faces
self.assertEqual(7, r.faces().size())
self.assertEqual(type(r.val()), Compound)
self.assertEqual(type(r.first().val()), Compound)
def testFrontReference(self):
# make a workplane on the top face
s = CQ(makeUnitCube()).faces("front").workplane()
r = s.circle(0.125).cutBlind(-2.0)
self.saveModel(r)
# the result should have 7 faces
self.assertEqual(7, r.faces().size())
self.assertEqual(type(r.val()), Compound)
self.assertEqual(type(r.first().val()), Compound)
def testRotate(self):
"""Test solid rotation at the CQ object level."""
box = Workplane("XY").box(1, 1, 5)
box.rotate((0, 0, 0), (1, 0, 0), 90)
startPoint = box.faces("<Y").edges("<X").first().val().startPoint().toTuple()
endPoint = box.faces("<Y").edges("<X").first().val().endPoint().toTuple()
self.assertEqual(-0.5, startPoint[0])
self.assertEqual(-0.5, startPoint[1])
self.assertEqual(-2.5, startPoint[2])
self.assertEqual(-0.5, endPoint[0])
self.assertEqual(-0.5, endPoint[1])
self.assertEqual(2.5, endPoint[2])
def testRotateAboutCenter(self):
r = Workplane().box(1, 1, 1).rotateAboutCenter((1, 0, 0), 20)
assert len(r.edges("|X").vals()) == 4
assert r.faces(">X").vertices("<Y").val().Center().toTuple() == approx(
(0.5, -0.6408563820557885, 0.2988362387301199)
)
def testPlaneRotateZNormal(self):
"""
Rotation of a plane in the Z direction should never alter its normal.
This test creates random planes. The plane is rotated a random angle in
the Z-direction to verify that the resulting plane maintains the same
normal.
The test also checks that the random origin is unaltered after
rotation.
"""
for _ in range(100):
angle = (random() - 0.5) * 720
xdir = Vector(random(), random(), random()).normalized()
rdir = Vector(random(), random(), random()).normalized()
zdir = xdir.cross(rdir).normalized()
origin = (random(), random(), random())
plane = Plane(origin=origin, xDir=xdir, normal=zdir)
rotated = plane.rotated((0, 0, angle))
assert rotated.zDir.toTuple() == approx(zdir.toTuple())
assert rotated.origin.toTuple() == approx(origin)
def testPlaneRotateConcat(self):
"""
Test the result of a well-known concatenated rotation example.
"""
xdir = (1, 0, 0)
normal = (0, 0, 1)
k = 2.0 ** 0.5 / 2.0
origin = (2, -1, 1)
plane = Plane(origin=origin, xDir=xdir, normal=normal)
plane = plane.rotated((0, 0, 45))
assert plane.xDir.toTuple() == approx((k, k, 0))
assert plane.yDir.toTuple() == approx((-k, k, 0))
assert plane.zDir.toTuple() == approx((0, 0, 1))
plane = plane.rotated((0, 45, 0))
assert plane.xDir.toTuple() == approx((0.5, 0.5, -k))
assert plane.yDir.toTuple() == approx((-k, k, 0))
assert plane.zDir.toTuple() == approx((0.5, 0.5, k))
assert plane.origin.toTuple() == origin
def testPlaneRotateConcatRandom(self):
"""
Rotation of a plane in a given direction should never alter that
direction.
This test creates a plane and rotates it a random angle in a given
direction. After the rotation, the direction of the resulting plane
in the rotation-direction should be constant.
The test also checks that the origin is unaltered after all rotations.
"""
origin = (2, -1, 1)
plane = Plane(origin=origin, xDir=(1, 0, 0), normal=(0, 0, 1))
for _ in range(100):
before = {
0: plane.xDir.toTuple(),
1: plane.yDir.toTuple(),
2: plane.zDir.toTuple(),
}
angle = (random() - 0.5) * 720
direction = randrange(3)
rotation = [0, 0, 0]
rotation[direction] = angle
plane = plane.rotated(rotation)
after = {
0: plane.xDir.toTuple(),
1: plane.yDir.toTuple(),
2: plane.zDir.toTuple(),
}
assert before[direction] == approx(after[direction])
assert plane.origin.toTuple() == origin
def testPlaneNoXDir(self):
"""
Plane should pick an arbitrary x direction if None is passed in.
"""
for z_dir in [(0, 0, 1), (1, 0, 0), (-1, 0, 0), Vector(-1, 0, 0)]:
result = Plane(origin=(1, 2, 3), xDir=None, normal=z_dir)
assert result.zDir == Vector(z_dir)
assert result.xDir.Length == approx(1)
assert result.origin == Vector(1, 2, 3)
# unspecified xDir should be the same as xDir=None
result2 = Plane(origin=(1, 2, 3), normal=z_dir)
assert result2 == result
def testPlaneToPln(self):
plane = Plane(origin=(1, 2, 3), xDir=(-1, 0, 0), normal=(0, 1, 0))
gppln = plane.toPln()
assert Vector(gppln.XAxis().Direction()) == Vector(-1, 0, 0)
assert Vector(gppln.YAxis().Direction()) == plane.yDir
assert Vector(gppln.Axis().Direction()) == plane.zDir
def testRect(self):
x = 10
y = 11
s = Workplane().rect(x, y)
# a rectangle has 4 sides
self.assertEqual(s.edges().size(), 4)
# assert that the lower left corner is in the correct spot for all
# possible values of centered
for centered_x, xval in zip([True, False], [-x / 2, 0]):
for centered_y, yval in zip([True, False], [-y / 2, 0]):
s = (
Workplane()
.rect(x, y, centered=(centered_x, centered_y))
.vertices("<X and <Y")
)
self.assertEqual(s.size(), 1)
self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, 0), 3)
# check that centered=True is the same as centered=(True, True)
for option0 in [True, False]:
v0 = (
Workplane()
.rect(x, y, centered=option0)
.vertices(">X and >Y")
.val()
.toTuple()
)
v1 = (
Workplane()
.rect(x, y, centered=(option0, option0))
.vertices(">X and >Y")
.val()
.toTuple()
)
self.assertTupleAlmostEquals(v0, v1, 3)
# test negative lengths
r0 = Workplane().rect(-x, -y, centered=False)
self.assertTupleAlmostEquals(
(0, 0, 0), r0.vertices(">X and >Y").val().toTuple(), 3
)
self.assertTupleAlmostEquals(
(-x, -y, 0), r0.vertices("<X and <Y").val().toTuple(), 3
)
# test move plus negative length
r1 = Workplane().move(x, y).rect(-x, -y, centered=False)
self.assertTupleAlmostEquals(
(x, y, 0), r1.vertices(">X and >Y").val().toTuple(), 3
)
self.assertTupleAlmostEquals(
(0, 0, 0), r1.vertices("<X and <Y").val().toTuple(), 3
)
# negative length should have no effect with centered=True
v2 = Workplane().rect(x, y).vertices(">X and >Y").val().toTuple()
v3 = Workplane().rect(-x, -y).vertices(">X and >Y").val().toTuple()
self.assertTupleAlmostEquals(v2, v3, 3)
def testLoft(self):
"""
Test making a lofted solid
"""
s = Workplane("XY").circle(4.0).workplane(5.0).rect(2.0, 2.0).loft()
self.saveModel(s)
# the result should have 7 faces
self.assertEqual(1, s.solids().size())
# the resulting loft had a split on the side, not sure why really, i expected only 3 faces
self.assertEqual(7, s.faces().size())
# test loft with combine="cut"
box = Workplane().box(10, 10, 10)
cut = (
box.faces(">Z")
.workplane()
.circle(2)
.workplane(invert=True, offset=12)
.rect(3, 2)
.loft(combine="cut")
)
self.assertGreater(box.val().Volume(), cut.val().Volume())
# test loft with combine=True
box = Workplane().box(10, 10, 10)
add = (
box.faces(">Z")
.workplane()
.circle(2)
.workplane(offset=12)
.rect(3, 2)
.loft(combine=True)
)
self.assertGreater(add.val().Volume(), box.val().Volume())
def testLoftRaisesValueError(self):
s0 = Workplane().hLine(1) # no wires
with raises(ValueError):
s0.loft()
s1 = Workplane("XY").circle(5) # one wire
with self.assertRaises(ValueError) as cm:
s1.loft()
err = cm.exception
self.assertEqual(str(err), "More than one wire is required")
def testLoftCombine(self):
"""
test combining a lof with another feature
:return:
"""
s = (
Workplane("front")
.box(4.0, 4.0, 0.25)
.faces(">Z")
.circle(1.5)
.workplane(offset=3.0)
.rect(0.75, 0.5)
.loft(combine=True)
)
self.saveModel(s)
# self.assertEqual(1,s.solids().size() )
# self.assertEqual(8,s.faces().size() )
def testRevolveCylinder(self):
"""
Test creating a solid using the revolve operation.
:return:
"""
# The dimensions of the model. These can be modified rather than changing the
# shape's code directly.
rectangle_width = 10.0
rectangle_length = 10.0
angle_degrees = 360.0
# Test revolve without any options for making a cylinder
result = (
Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve()
)
self.assertEqual(3, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(3, result.edges().size())
# Test revolve when only setting the angle to revolve through
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length, False)
.revolve(angle_degrees)
)
self.assertEqual(3, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(3, result.edges().size())
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length, False)
.revolve(270.0)
)
self.assertEqual(5, result.faces().size())
self.assertEqual(6, result.vertices().size())
self.assertEqual(9, result.edges().size())
# Test when passing revolve the angle and the axis of revolution's start point
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(angle_degrees, (-5, -5))
)
self.assertEqual(3, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(3, result.edges().size())
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(270.0, (-5, -5))
)
self.assertEqual(5, result.faces().size())
self.assertEqual(6, result.vertices().size())
self.assertEqual(9, result.edges().size())
# Test when passing revolve the angle and both the start and ends of the axis of revolution
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(angle_degrees, (-5, -5), (-5, 5))
)
self.assertEqual(3, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(3, result.edges().size())
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(270.0, (-5, -5), (-5, 5))
)
self.assertEqual(5, result.faces().size())
self.assertEqual(6, result.vertices().size())
self.assertEqual(9, result.edges().size())
# Testing all of the above without combine
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(angle_degrees, (-5, -5), (-5, 5), False)
)
self.assertEqual(3, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(3, result.edges().size())
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length)
.revolve(270.0, (-5, -5), (-5, 5), False)
)
self.assertEqual(5, result.faces().size())
self.assertEqual(6, result.vertices().size())
self.assertEqual(9, result.edges().size())
def testRevolveDonut(self):
"""
Test creating a solid donut shape with square walls
:return:
"""
# The dimensions of the model. These can be modified rather than changing the
# shape's code directly.
rectangle_width = 10.0
rectangle_length = 10.0
angle_degrees = 360.0
result = (
Workplane("XY")
.rect(rectangle_width, rectangle_length, True)
.revolve(angle_degrees, (20, 0), (20, 10))
)
self.assertEqual(4, result.faces().size())
self.assertEqual(4, result.vertices().size())
self.assertEqual(6, result.edges().size())
def testRevolveCone(self):
"""
Test creating a solid from a revolved triangle
:return:
"""
result = Workplane("XY").lineTo(0, 10).lineTo(5, 0).close().revolve()
self.assertEqual(2, result.faces().size())
self.assertEqual(2, result.vertices().size())
self.assertEqual(2, result.edges().size())
def testRevolveCut(self):
box = Workplane().box(10, 10, 10)
cut = (
box.transformed((90, 0, 0))
.move(5, 0)
.rect(3, 4, centered=False)
.revolve(360, (0, 0, 0), (0, 1, 0), combine="cut")
)
self.assertGreater(box.val().Volume(), cut.val().Volume())
def testRevolveErrors(self):
"""
Test that revolve raises errors when used incorrectly.
"""
result = Workplane("XY").lineTo(0, 10).lineTo(5, 0)
with raises(ValueError):
result.revolve()
def testSpline(self):
"""
Tests construction of splines
"""
pts = [(0, 0), (0, 1), (1, 2), (2, 4)]
# Spline path - just a smoke test
path = Workplane("XZ").spline(pts).val()
# Closed spline
path_closed = Workplane("XZ").spline(pts, periodic=True).val()
self.assertTrue(path_closed.IsClosed())
# attempt to build a valid face
w = Wire.assembleEdges([path_closed,])
f = Face.makeFromWires(w)
self.assertTrue(f.isValid())
# attempt to build an invalid face
w = Wire.assembleEdges([path,])
f = Face.makeFromWires(w)
self.assertFalse(f.isValid())
# Spline with explicit tangents
path_const = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val()
self.assertFalse(path.tangentAt(0) == path_const.tangentAt(0))
self.assertFalse(path.tangentAt(1) == path_const.tangentAt(1))
# test include current
path1 = Workplane("XZ").spline(pts[1:], includeCurrent=True).val()
self.assertAlmostEqual(path.Length(), path1.Length())
# test tangents and offset plane
pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)]
tangents = [(0, 1), (1, 0)]
path2 = Workplane("XY", (0, 0, 10)).spline(pts, tangents=tangents)
self.assertAlmostEqual(path2.val().tangentAt(0).z, 0)
def testSplineWithMultipleTangents(self):
"""
Tests specifying B-spline tangents, besides the start point and end
point tangents.
"""
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)]
parameters = range(len(points))
spline = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=parameters)
.consolidateWires()
)
test_point = spline.edges().val().positionAt(2.5, mode="parameter")
expected_test_point = Vector(1.875, -0.625, 0.0)
self.assertAlmostEqual((test_point - expected_test_point).Length, 0)
def testSplineWithSpecifiedAndUnspecifiedTangents(self):
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
tangents = [(0, 1), None, (0, -1), (-1, 0)]
parameters = range(len(points))
spline = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=parameters)
.consolidateWires()
)
test_point = spline.edges().val().positionAt(1.5, mode="parameter")
expected_test_point = Vector(1.6875, 0.875, 0.0)
self.assertAlmostEqual((test_point - expected_test_point).Length, 0)
def testSplineSpecifyingParameters(self):
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)]
spline1 = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=[0, 1, 2, 3])
.consolidateWires()
)
# Multiply all parameter values by 10:
spline2 = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=[0, 10, 20, 30])
.consolidateWires()
)
# Test point equivalence for parameter, and parameter multiplied by 10:
test_point1 = spline1.edges().val().positionAt(1.5, mode="parameter")
test_point2 = spline2.edges().val().positionAt(15, mode="parameter")
expected_test_point = Vector(1.625, 0.625, 0.0)
self.assertAlmostEqual((test_point1 - test_point2).Length, 0)
self.assertAlmostEqual((test_point1 - expected_test_point).Length, 0)
# test periodic with parameters
spline3 = Workplane().spline(
points, periodic=True, parameters=[x for x in range(len(points) + 1)]
)
self.assertTrue(spline3.val().IsClosed())
def testSplineWithScaleTrue(self):
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)]
parameters = range(len(points))
spline = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=parameters, scale=True)
.consolidateWires()
)
test_point = spline.edges().val().positionAt(0.5, mode="parameter")
expected_test_point = Vector(0.375, 0.875, 0.0)
self.assertAlmostEqual((test_point - expected_test_point).Length, 0)
def testSplineWithScaleFalse(self):
"""
Like testSplineWithScaleTrue, but verifies the tangent vector is
different when scale=False.
The interpolation points and tangent vectors are the same in
`testSplineWithScaleTrue`, and `testSplineWithScaleFalse`. A test
point is rendered at the same parameter value in both cases, but its
coordinates are different in each case.
"""
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)]
parameters = range(len(points))
spline = (
Workplane("XY")
.spline(points, tangents=tangents, parameters=parameters, scale=False)
.consolidateWires()
)
test_point = spline.edges().val().positionAt(0.5, mode="parameter")
expected_test_point = Vector(0.375, 0.625, 0.0)
self.assertAlmostEqual((test_point - expected_test_point).Length, 0)
def testSplineTangentMagnitudeBelowToleranceThrows(self):
import OCP
points = [(0, 0), (1, 1), (2, 0), (1, -1)]
# Use a tangent vector with magnitude 0.5:
tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)]
parameters = range(len(points))
# Set tolerance above the 0.5 length of the tangent vector. This
# should throw an exception:
with raises(
(OCP.Standard.Standard_ConstructionError, OCP.Standard.Standard_Failure)
):
spline = (
Workplane("XY")
.spline(points, tangents=tangents, tol=1)
.consolidateWires()
)
def testSplineInputValidation(self):
points = [(0, 0), (1, 1), (2, 0)]
tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)]
with raises(ValueError):
spline = Workplane().spline(points, tangents=tangents)
with raises(ValueError):
Workplane().spline(
points, periodic=False, parameters=[x for x in range(len(points) + 1)],
)
with raises(ValueError):
Workplane().spline(
points, periodic=True, parameters=[x for x in range(len(points))],
)
def testRotatedEllipse(self):
def rotatePoint(x, y, alpha):
# rotation matrix
a = alpha * DEG2RAD
r = ((math.cos(a), math.sin(a)), (-math.sin(a), math.cos(a)))
return ((x * r[0][0] + y * r[1][0]), (x * r[0][1] + y * r[1][1]))
def ellipsePoints(r1, r2, a):
return (r1 * math.cos(a * DEG2RAD), r2 * math.sin(a * DEG2RAD))
DEG2RAD = math.pi / 180.0
p0 = (10, 20)
a1, a2 = 30, -60
r1, r2 = 20, 10
ra = 25
sx_rot, sy_rot = rotatePoint(*ellipsePoints(r1, r2, a1), ra)
ex_rot, ey_rot = rotatePoint(*ellipsePoints(r1, r2, a2), ra)
# startAtCurrent=False, sense = 1
ellipseArc1 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra
)
)
start = ellipseArc1.vertices().objects[0]
end = ellipseArc1.vertices().objects[1]
self.assertTupleAlmostEquals(
(start.X, start.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3
)
self.assertTupleAlmostEquals(
(end.X, end.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3
)
# startAtCurrent=True, sense = 1
ellipseArc2 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1, r2, startAtCurrent=True, angle1=a1, angle2=a2, rotation_angle=ra
)
)
start = ellipseArc2.vertices().objects[0]
end = ellipseArc2.vertices().objects[1]
self.assertTupleAlmostEquals(
(start.X, start.Y), (p0[0] + sx_rot - sx_rot, p0[1] + sy_rot - sy_rot), 3
)
self.assertTupleAlmostEquals(
(end.X, end.Y), (p0[0] + ex_rot - sx_rot, p0[1] + ey_rot - sy_rot), 3
)
# startAtCurrent=False, sense = -1
ellipseArc3 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1,
r2,
startAtCurrent=False,
angle1=a1,
angle2=a2,
rotation_angle=ra,
sense=-1,
)
)
start = ellipseArc3.vertices().objects[0]
end = ellipseArc3.vertices().objects[1]
# swap start and end points for comparison due to different sense
self.assertTupleAlmostEquals(
(start.X, start.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3
)
self.assertTupleAlmostEquals(
(end.X, end.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3
)
# startAtCurrent=True, sense = -1
ellipseArc4 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1,
r2,
startAtCurrent=True,
angle1=a1,
angle2=a2,
rotation_angle=ra,
sense=-1,
makeWire=True,
)
)
self.assertEqual(len(ellipseArc4.ctx.pendingWires), 1)
start = ellipseArc4.vertices().objects[0]
end = ellipseArc4.vertices().objects[1]
# swap start and end points for comparison due to different sense
self.assertTupleAlmostEquals(
(start.X, start.Y), (p0[0] + ex_rot - ex_rot, p0[1] + ey_rot - ey_rot), 3
)
self.assertTupleAlmostEquals(
(end.X, end.Y), (p0[0] + sx_rot - ex_rot, p0[1] + sy_rot - ey_rot), 3
)
def testEllipseArcsClockwise(self):
ellipseArc = (
Workplane("XY")
.moveTo(10, 15)
.ellipseArc(5, 4, -10, 190, 45, sense=-1, startAtCurrent=False)
)
sp = ellipseArc.val().startPoint()
ep = ellipseArc.val().endPoint()
self.assertTupleAlmostEquals(
(sp.x, sp.y), (7.009330014275797, 11.027027582524015), 3
)
self.assertTupleAlmostEquals(
(ep.x, ep.y), (13.972972417475985, 17.990669985724203), 3
)
ellipseArc = (
ellipseArc.ellipseArc(5, 4, -10, 190, 315, sense=-1)
.ellipseArc(5, 4, -10, 190, 225, sense=-1)
.ellipseArc(5, 4, -10, 190, 135, sense=-1)
)
ep = ellipseArc.val().endPoint()
self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3)
def testEllipseArcsCounterClockwise(self):
ellipseArc = (
Workplane("XY")
.moveTo(10, 15)
.ellipseArc(5, 4, -10, 190, 45, startAtCurrent=False)
)
sp = ellipseArc.val().startPoint()
ep = ellipseArc.val().endPoint()
self.assertTupleAlmostEquals(
(sp.x, sp.y), (13.972972417475985, 17.990669985724203), 3
)
self.assertTupleAlmostEquals(
(ep.x, ep.y), (7.009330014275797, 11.027027582524015), 3
)
ellipseArc = (
ellipseArc.ellipseArc(5, 4, -10, 190, 135)
.ellipseArc(5, 4, -10, 190, 225)
.ellipseArc(5, 4, -10, 190, 315)
)
ep = ellipseArc.val().endPoint()
self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3)
def testEllipseCenterAndMoveTo(self):
# Whether we start from a center() call or a moveTo call, it should be the same ellipse Arc
p0 = (10, 20)
a1, a2 = 30, -60
r1, r2 = 20, 10
ra = 25
ellipseArc1 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra
)
)
sp1 = ellipseArc1.val().startPoint()
ep1 = ellipseArc1.val().endPoint()
ellipseArc2 = (
Workplane("XY")
.moveTo(*p0)
.ellipseArc(
r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra
)
)
sp2 = ellipseArc2.val().startPoint()
ep2 = ellipseArc2.val().endPoint()
self.assertTupleAlmostEquals(sp1.toTuple(), sp2.toTuple(), 3)
self.assertTupleAlmostEquals(ep1.toTuple(), ep2.toTuple(), 3)
def testMakeEllipse(self):
el = Wire.makeEllipse(
1, 2, Vector(0, 0, 0), Vector(0, 0, 1), Vector(1, 0, 0), 0, 90, 45, True,
)
self.assertTrue(el.IsClosed())
self.assertTrue(el.isValid())
def testSweep(self):
"""
Tests the operation of sweeping a wire(s) along a path
"""
pts = [(0, 0), (0, 1), (1, 2), (2, 4)]
# Spline path
path = Workplane("XZ").spline(pts)
# Test defaults
result = Workplane("XY").circle(1.0).sweep(path)
self.assertEqual(3, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test Wire path
result = Workplane("XY").circle(1.0).sweep(path.val())
self.assertEqual(3, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test with makeSolid False
result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False)
self.assertEqual(1, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test with isFrenet True
result = Workplane("XY").circle(1.0).sweep(path, isFrenet=True)
self.assertEqual(3, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test with makeSolid False and isFrenet True
result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False, isFrenet=True)
self.assertEqual(1, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test rectangle with defaults
result = Workplane("XY").rect(1.0, 1.0).sweep(path)
self.assertEqual(6, result.faces().size())
self.assertEqual(12, result.edges().size())
# Test fixed normal
result = Workplane().circle(0.5).sweep(path, normal=Vector(0, 0, 1))
self.assertTupleAlmostEquals(
result.faces(">Z").val().normalAt().toTuple(), (0, 0, 1), 6
)
# Polyline path
path = Workplane("XZ").polyline(pts)
# Test defaults
result = Workplane("XY").circle(0.1).sweep(path, transition="transformed")
self.assertEqual(5, result.faces().size())
self.assertEqual(7, result.edges().size())
# Polyline path and one inner profiles
path = Workplane("XZ").polyline(pts)
# Test defaults
result = (
Workplane("XY")
.circle(0.2)
.circle(0.1)
.sweep(path, transition="transformed")
)
self.assertEqual(8, result.faces().size())
self.assertEqual(14, result.edges().size())
# Polyline path and different transition settings
for t in ("transformed", "right", "round"):
path = Workplane("XZ").polyline(pts)
result = (
Workplane("XY")
.circle(0.2)
.rect(0.2, 0.1)
.rect(0.1, 0.2)
.sweep(path, transition=t)
)
self.assertTrue(result.solids().val().isValid())
# Polyline path and multiple inner profiles
path = Workplane("XZ").polyline(pts)
# Test defaults
result = (
Workplane("XY")
.circle(0.2)
.rect(0.2, 0.1)
.rect(0.1, 0.2)
.circle(0.1)
.sweep(path)
)
self.assertTrue(result.solids().val().isValid())
# Arc path
path = Workplane("XZ").threePointArc((1.0, 1.5), (0.0, 1.0))
# Test defaults
result = Workplane("XY").circle(0.1).sweep(path)
self.assertEqual(3, result.faces().size())
self.assertEqual(3, result.edges().size())
# Test aux spine
pts1 = [(0, 0), (20, 100)]
pts2 = [(0, 20, 0), (20, 0, 100)]
path = Workplane("YZ").spline(pts1, tangents=[(0, 1, 0), (0, 1, 0)])
aux_path = Workplane("XY").spline(pts2, tangents=[(0, 0, 1), (0, 0, 1)])
result = Workplane("XY").rect(10, 20).sweep(path, auxSpine=aux_path)
bottom = result.faces("<Z")
top = result.faces(">Z")
v1 = bottom.wires().val().tangentAt(0.0)
v2 = top.wires().val().tangentAt(0.0)
self.assertAlmostEqual(v1.getAngle(v2), math.pi / 4, 6)
# test for ValueError if pending wires is empty
w0 = Workplane().hLine(1).vLine(1)
with raises(ValueError):
w0.sweep(path)
# Test aux spine invalid input handling
with raises(ValueError):
result = (
Workplane("XY")
.rect(10, 20)
.sweep(path, auxSpine=Workplane().box(1, 1, 1))
)
# test sweep with combine="cut"
box = Workplane().box(10, 10, 10, centered=False)
path = Workplane("YZ").lineTo(10, 10)
cut = (
box.vertices(">Z and >X and >Y")
.workplane(centerOption="CenterOfMass")
.circle(1.5)
.sweep(path, combine="cut")
)
self.assertGreater(box.val().Volume(), cut.val().Volume())
# test sweep with combine = True
box = Workplane().box(10, 10, 10, centered=False)
path = Workplane("YZ").lineTo(10, 10)
add = (
box.vertices(">Z and >X and >Y")
.workplane(centerOption="CenterOfMass")
.circle(1.5)
.sweep(path, combine=True)
)
self.assertGreater(add.val().Volume(), box.val().Volume())
def testMultisectionSweep(self):
"""
Tests the operation of sweeping along a list of wire(s) along a path
"""
# X axis line length 20.0
path = Workplane("XZ").moveTo(-10, 0).lineTo(10, 0)
# Sweep a circle from diameter 2.0 to diameter 1.0 to diameter 2.0 along X axis length 10.0 + 10.0
defaultSweep = (
Workplane("YZ")
.workplane(offset=-10.0)
.circle(2.0)
.workplane(offset=10.0)
.circle(1.0)
.workplane(offset=10.0)
.circle(2.0)
.sweep(path, multisection=True)
)
# We can sweep through different shapes
recttocircleSweep = (
Workplane("YZ")
.workplane(offset=-10.0)
.rect(2.0, 2.0)
.workplane(offset=8.0)
.circle(1.0)
.workplane(offset=4.0)
.circle(1.0)
.workplane(offset=8.0)
.rect(2.0, 2.0)
.sweep(path, multisection=True)
)
circletorectSweep = (
Workplane("YZ")
.workplane(offset=-10.0)
.circle(1.0)
.workplane(offset=7.0)
.rect(2.0, 2.0)
.workplane(offset=6.0)
.rect(2.0, 2.0)
.workplane(offset=7.0)
.circle(1.0)
.sweep(path, multisection=True)
)
# Placement of the Shape is important otherwise could produce unexpected shape
specialSweep = (
Workplane("YZ")
.circle(1.0)
.workplane(offset=10.0)
.rect(2.0, 2.0)
.sweep(path, multisection=True)
)
# Switch to an arc for the path : line l=5.0 then half circle r=4.0 then line l=5.0
path = (
Workplane("XZ")
.moveTo(-5, 4)
.lineTo(0, 4)
.threePointArc((4, 0), (0, -4))
.lineTo(-5, -4)
)
# Placement of different shapes should follow the path
# cylinder r=1.5 along first line
# then sweep along arc from r=1.5 to r=1.0
# then cylinder r=1.0 along last line
arcSweep = (
Workplane("YZ")
.workplane(offset=-5)
.moveTo(0, 4)
.circle(1.5)
.workplane(offset=5, centerOption="CenterOfMass")
.circle(1.5)
.moveTo(0, -8)
.circle(1.0)
.workplane(offset=-5, centerOption="CenterOfMass")
.circle(1.0)
.sweep(path, multisection=True)
)
# Test multisection with normal
pts = [(0, 0), (20, 100)]
path = Workplane("YZ").spline(pts, tangents=[(0, 1, 0), (0, 1, 0)])
normalSweep = (
Workplane()
.rect(10, 10)
.workplane(offset=100)
.rect(10, 20)
.sweep(path, multisection=True, normal=(0, 1, 1))
)
self.assertTupleAlmostEquals(
normalSweep.faces("<Z").val().normalAt().toTuple(),
Vector(0, -1, -1).normalized().toTuple(),
6,
)
self.assertTupleAlmostEquals(
normalSweep.faces(">Z").val().normalAt().toTuple(),
Vector(0, 1, 1).normalized().toTuple(),
6,
)
# Test and saveModel
self.assertEqual(1, defaultSweep.solids().size())
self.assertEqual(1, circletorectSweep.solids().size())
self.assertEqual(1, recttocircleSweep.solids().size())
self.assertEqual(1, specialSweep.solids().size())
self.assertEqual(1, arcSweep.solids().size())
self.saveModel(defaultSweep)
def testTwistExtrude(self):
"""
Tests extrusion while twisting through an angle.
"""
profile = Workplane("XY").rect(10, 10)
r = profile.twistExtrude(10, 45, False)
self.assertEqual(6, r.faces().size())
def testTwistExtrudeCombineCut(self):
"""
Tests extrusion while twisting through an angle, removing the solid from the base solid
"""
box = Workplane().box(10, 10, 10)
cut = (
box.faces(">Z")
.workplane(invert=True)
.rect(1.5, 5)
.twistExtrude(10, 90, combine="cut")
)
self.assertGreater(box.val().Volume(), cut.val().Volume())
def testTwistExtrudeCombine(self):
"""
Tests extrusion while twisting through an angle, combining with other solids.
"""
profile = Workplane("XY").rect(10, 10)
r = profile.twistExtrude(10, 45)
self.assertEqual(6, r.faces().size())
def testRectArray(self):
x_num = 3
y_num = 3
x_spacing = 8.0
y_spacing = 8.0
s = (
Workplane("XY")
.box(40, 40, 5, centered=(True, True, True))
.faces(">Z")
.workplane()
.rarray(x_spacing, y_spacing, x_num, y_num, True)
.circle(2.0)
.extrude(2.0)
)
self.saveModel(s)
# 6 faces for the box, 2 faces for each cylinder
self.assertEqual(6 + x_num * y_num * 2, s.faces().size())
with raises(ValueError):
Workplane().rarray(0, 0, x_num, y_num, True)
# check lower and upper corner points are correct for all combinations of centering
for x_opt, x_min, x_max in zip(
[True, False], [-x_spacing, 0.0], [x_spacing, x_spacing * 2]
):
for y_opt, y_min, y_max in zip(
[True, False], [-y_spacing, 0.0], [y_spacing, y_spacing * 2]
):
s = Workplane().rarray(
x_spacing, y_spacing, x_num, y_num, center=(x_opt, y_opt)
)
lower = Vector(x_min, y_min, 0)
upper = Vector(x_max, y_max, 0)
self.assertTrue(lower in s.objects)
self.assertTrue(upper in s.objects)
# check centered=True is equivalent to centered=(True, True)
for val in [True, False]:
s0 = Workplane().rarray(x_spacing, y_spacing, x_num, y_num, center=val)
s1 = Workplane().rarray(
x_spacing, y_spacing, x_num, y_num, center=(val, val)
)
# check all the points in s0 are present in s1
self.assertTrue(all(pnt in s1.objects for pnt in s0.objects))
self.assertEqual(s0.size(), s1.size())
def testPolarArray(self):
radius = 10
to_x = lambda l: l.wrapped.Transformation().TranslationPart().X()
to_y = lambda l: l.wrapped.Transformation().TranslationPart().Y()
to_angle = (
lambda l: l.wrapped.Transformation().GetRotation().GetRotationAngle()
* 180.0
/ math.pi
)
# Test for proper placement when fill == True
s = Workplane("XY").polarArray(radius, 0, 180, 3)
self.assertEqual(3, s.size())
self.assertAlmostEqual(radius, to_x(s.objects[0]))
self.assertAlmostEqual(0, to_y(s.objects[0]))
# Test for proper placement when angle to fill is multiple of 360 deg
s = Workplane("XY").polarArray(radius, 0, 360, 4)
self.assertEqual(4, s.size())
self.assertAlmostEqual(radius, to_x(s.objects[0]))
self.assertAlmostEqual(0, to_y(s.objects[0]))
# Test for proper placement when fill == False
s = Workplane("XY").polarArray(radius, 0, 90, 3, fill=False)
self.assertEqual(3, s.size())
self.assertAlmostEqual(-radius, to_x(s.objects[2]))
self.assertAlmostEqual(0, to_y(s.objects[2]))
# Test for proper operation of startAngle
s = Workplane("XY").polarArray(radius, 90, 180, 3)
self.assertEqual(3, s.size())
self.assertAlmostEqual(0, to_x(s.objects[0]))
self.assertAlmostEqual(radius, to_y(s.objects[0]))
# Test for local rotation
s = Workplane().polarArray(radius, 0, 180, 3)
self.assertAlmostEqual(0, to_angle(s.objects[0]))
self.assertAlmostEqual(90, to_angle(s.objects[1]))
s = Workplane().polarArray(radius, 0, 180, 3, rotate=False)
self.assertAlmostEqual(0, to_angle(s.objects[0]))
self.assertAlmostEqual(0, to_angle(s.objects[1]))
with raises(ValueError):
Workplane().polarArray(radius, 20, 180, 0)
s = Workplane().polarArray(radius, 20, 0, 1)
assert s.size() == 1
assert Workplane().polarLine(radius, 20).val().positionAt(
1
).toTuple() == approx(s.val().toTuple()[0])
s = Workplane().center(2, -4).polarArray(2, 10, 50, 3).rect(1.0, 0.5).extrude(1)
assert s.solids().size() == 3
assert s.vertices(">Y and >Z").val().toTuple() == approx(
(3.0334936490538906, -1.7099364905389036, 1.0)
)
def testNestedCircle(self):
s = (
Workplane("XY")
.box(40, 40, 5)
.pushPoints([(10, 0), (0, 10)])
.circle(4)
.circle(2)
.extrude(4)
)
self.saveModel(s)
self.assertEqual(14, s.faces().size())
def testConcentricEllipses(self):
concentricEllipses = (
Workplane("XY").center(10, 20).ellipse(100, 10).center(0, 0).ellipse(50, 5)
)
v = concentricEllipses.vertices().objects[0]
self.assertTupleAlmostEquals((v.X, v.Y), (10 + 50, 20), 3)
def testLegoBrick(self):
# test making a simple lego brick
# which of the below
# inputs
lbumps = 8
wbumps = 2
# lego brick constants
P = 8.0 # nominal pitch
c = 0.1 # clearance on each brick side
H = 1.2 * P # nominal height of a brick
bumpDiam = 4.8 # the standard bump diameter
# the nominal thickness of the walls, normally 1.5
t = (P - (2 * c) - bumpDiam) / 2.0
postDiam = P - t # works out to 6.5
total_length = lbumps * P - 2.0 * c
total_width = wbumps * P - 2.0 * c
# build the brick
s = Workplane("XY").box(total_length, total_width, H) # make the base
s = s.faces("<Z").shell(-1.0 * t) # shell inwards not outwards
s = (
s.faces(">Z")
.workplane()
.rarray(P, P, lbumps, wbumps, True)
.circle(bumpDiam / 2.0)
.extrude(1.8)
) # make the bumps on the top
# add posts on the bottom. posts are different diameter depending on geometry
# solid studs for 1 bump, tubes for multiple, none for 1x1
# this is cheating a little-- how to select the inner face from the shell?
tmp = s.faces("<Z").workplane(invert=True)
if lbumps > 1 and wbumps > 1:
tmp = (
tmp.rarray(P, P, lbumps - 1, wbumps - 1, center=True)
.circle(postDiam / 2.0)
.circle(bumpDiam / 2.0)
.extrude(H - t)
)
elif lbumps > 1:
tmp = tmp.rarray(P, P, lbumps - 1, 1, center=True).circle(t).extrude(H - t)
elif wbumps > 1:
tmp = tmp.rarray(P, P, 1, wbumps - 1, center=True).circle(t).extrude(H - t)
self.saveModel(s)
def testAngledHoles(self):
s = (
Workplane("front")
.box(4.0, 4.0, 0.25)
.faces(">Z")
.workplane()
.transformed(offset=Vector(0, -1.5, 1.0), rotate=Vector(60, 0, 0))
.rect(1.5, 1.5, forConstruction=True)
.vertices()
.hole(0.25)
)
self.saveModel(s)
self.assertEqual(10, s.faces().size())
def testTranslateSolid(self):
c = CQ(makeUnitCube())
self.assertAlmostEqual(0.0, c.faces("<Z").vertices().item(0).val().Z, 3)
# TODO: it might be nice to provide a version of translate that modifies the existing geometry too
d = c.translate(Vector(0, 0, 1.5))
self.assertAlmostEqual(1.5, d.faces("<Z").vertices().item(0).val().Z, 3)
def testTranslateWire(self):
c = CQ(makeUnitSquareWire())
self.assertAlmostEqual(0.0, c.edges().vertices().item(0).val().Z, 3)
d = c.translate(Vector(0, 0, 1.5))
self.assertAlmostEqual(1.5, d.edges().vertices().item(0).val().Z, 3)
def testSolidReferencesCombine(self):
"test that solid references are preserved correctly"
c = CQ(makeUnitCube()) # the cube is the context solid
self.assertEqual(6, c.faces().size()) # cube has six faces
r = (
c.faces(">Z").workplane().circle(0.125).extrude(0.5, True)
) # make a boss, not updating the original
self.assertEqual(8, r.faces().size()) # just the boss faces
self.assertEqual(6, c.faces().size()) # original is not modified
def testSolidReferencesCombineTrue(self):
s = Workplane(Plane.XY())
r = s.rect(2.0, 2.0).extrude(0.5)
# the result of course has 6 faces
self.assertEqual(6, r.faces().size())
# the original workplane does not, because it did not have a solid initially
self.assertEqual(0, s.faces().size())
t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, True)
# of course the result has 11 faces
self.assertEqual(11, t.faces().size())
# r (being the parent) remains unmodified
self.assertEqual(6, r.faces().size())
self.saveModel(r)
def testSolidReferenceCombineFalse(self):
s = Workplane(Plane.XY())
r = s.rect(2.0, 2.0).extrude(0.5)
# the result of course has 6 faces
self.assertEqual(6, r.faces().size())
# the original workplane does not, because it did not have a solid initially
self.assertEqual(0, s.faces().size())
t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, False)
# result has 6 faces, because it was not combined with the original
self.assertEqual(6, t.faces().size())
self.assertEqual(6, r.faces().size()) # original is unmodified as well
# subsequent operations use that context solid afterwards
def testSimpleWorkplane(self):
"""
A simple square part with a hole in it
"""
s = Workplane(Plane.XY())
r = (
s.rect(2.0, 2.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.circle(0.25)
.cutBlind(-1.0)
)
self.saveModel(r)
self.assertEqual(7, r.faces().size())
def testMultiFaceWorkplane(self):
"""
Test Creation of workplane from multiple co-planar face
selection.
"""
s = Workplane("XY").box(1, 1, 1).faces(">Z").rect(1, 0.5).cutBlind(-0.2)
w = s.faces(">Z").workplane()
o = w.val() # origin of the workplane
self.assertAlmostEqual(o.x, 0.0, 3)
self.assertAlmostEqual(o.y, 0.0, 3)
self.assertAlmostEqual(o.z, 0.5, 3)
def testTriangularPrism(self):
s = Workplane("XY").lineTo(1, 0).lineTo(1, 1).close().extrude(0.2)
self.saveModel(s)
def testMultiWireWorkplane(self):
"""
A simple square part with a hole in it-- but this time done as a single extrusion
with two wires, as opposed to s cut
"""
s = Workplane(Plane.XY())
r = s.rect(2.0, 2.0).circle(0.25).extrude(0.5)
self.saveModel(r)
self.assertEqual(7, r.faces().size())
def testConstructionWire(self):
"""
Tests a wire with several holes, that are based on the vertices of a square
also tests using a workplane plane other than XY
"""
s = Workplane(Plane.YZ())
r = (
s.rect(2.0, 2.0)
.rect(1.3, 1.3, forConstruction=True)
.vertices()
.circle(0.125)
.extrude(0.5)
)
self.saveModel(r)
# 10 faces-- 6 plus 4 holes, the vertices of the second rect.
self.assertEqual(10, r.faces().size())
def testTwoWorkplanes(self):
"""
Tests a model that uses more than one workplane
"""
# base block
s = Workplane(Plane.XY())
# TODO: this syntax is nice, but the iteration might not be worth
# the complexity.
# the simpler and slightly longer version would be:
# r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices()
# for c in r.all():
# c.circle(0.125).extrude(0.5,True)
r = (
s.rect(2.0, 2.0)
.rect(1.3, 1.3, forConstruction=True)
.vertices()
.circle(0.125)
.extrude(0.5)
)
# side hole, blind deep 1.9
t = r.faces(">Y").workplane().circle(0.125).cutBlind(-1.9)
self.saveModel(t)
self.assertEqual(12, t.faces().size())
def testCut(self):
"""
Tests the cut function by itself to catch the case where a Solid object is passed.
"""
s = Workplane(Plane.XY())
currentS = s.rect(2.0, 2.0).extrude(0.5)
toCut = s.rect(1.0, 1.0).extrude(0.5)
resS = currentS.cut(toCut.val())
self.assertEqual(10, resS.faces().size())
with self.assertRaises(ValueError):
currentS.cut(toCut.faces().val())
# Test syntactic sugar [__sub__ method]
sugar = currentS - toCut.val()
self.assertEqual(resS.faces().size(), sugar.faces().size())
# test ValueError on no solid found
s0 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
s0.cut(toCut.val())
def testIntersect(self):
"""
Tests the intersect function.
"""
s = Workplane(Plane.XY())
currentS = s.rect(2.0, 2.0).extrude(0.5)
toIntersect = s.rect(1.0, 1.0).extrude(1)
resS = currentS.intersect(toIntersect.val())
self.assertEqual(6, resS.faces().size())
self.assertAlmostEqual(resS.val().Volume(), 0.5)
resS = currentS.intersect(toIntersect)
self.assertEqual(6, resS.faces().size())
self.assertAlmostEqual(resS.val().Volume(), 0.5)
b1 = Workplane("XY").box(1, 1, 1)
b2 = Workplane("XY", origin=(0, 0, 0.5)).box(1, 1, 1)
resS = b1.intersect(b2)
self.assertAlmostEqual(resS.val().Volume(), 0.5)
with self.assertRaises(ValueError):
b1.intersect(b2.faces().val())
# Test syntactic sugar [__mul__ method]
sugar = b1 & b2
self.assertEqual(resS.val().Volume(), sugar.val().Volume())
# raise ValueError when no solid found
with raises(ValueError):
Workplane().intersect(toIntersect)
def testBoundingBox(self):
"""
Tests the boudingbox center of a model
"""
result0 = (
Workplane("XY")
.moveTo(10, 0)
.lineTo(5, 0)
.threePointArc((3.9393, 0.4393), (3.5, 1.5))
.threePointArc((3.0607, 2.5607), (2, 3))
.lineTo(1.5, 3)
.threePointArc((0.4393, 3.4393), (0, 4.5))
.lineTo(0, 13.5)
.threePointArc((0.4393, 14.5607), (1.5, 15))
.lineTo(28, 15)
.lineTo(28, 13.5)
.lineTo(24, 13.5)
.lineTo(24, 11.5)
.lineTo(27, 11.5)
.lineTo(27, 10)
.lineTo(22, 10)
.lineTo(22, 13.2)
.lineTo(14.5, 13.2)
.lineTo(14.5, 10)
.lineTo(12.5, 10)
.lineTo(12.5, 13.2)
.lineTo(5.5, 13.2)
.lineTo(5.5, 2)
.threePointArc((5.793, 1.293), (6.5, 1))
.lineTo(10, 1)
.close()
)
result = result0.extrude(100)
bb_center = result.val().BoundingBox().center
self.saveModel(result)
self.assertAlmostEqual(14.0, bb_center.x, 3)
self.assertAlmostEqual(7.5, bb_center.y, 3)
self.assertAlmostEqual(50.0, bb_center.z, 3)
# The following will raise with the default tolerance of TOL 1e-2
bb = result.val().BoundingBox(tolerance=1e-3)
self.assertAlmostEqual(0.0, bb.xmin, 2)
self.assertAlmostEqual(28, bb.xmax, 2)
self.assertAlmostEqual(0.0, bb.ymin, 2)
self.assertAlmostEqual(15.0, bb.ymax, 2)
self.assertAlmostEqual(0.0, bb.zmin, 2)
self.assertAlmostEqual(100.0, bb.zmax, 2)
def testCutThroughAll(self):
"""
Tests a model that uses more than one workplane
"""
# base block
s = Workplane(Plane.XY())
r = (
s.rect(2.0, 2.0)
.rect(1.3, 1.3, forConstruction=True)
.vertices()
.circle(0.125)
.extrude(0.5)
)
# thru all without explicit face selection
t = r.circle(0.5).cutThruAll()
self.assertEqual(11, t.faces().size())
# side hole, thru all
t = (
t.faces(">Y")
.workplane(centerOption="CenterOfMass")
.circle(0.125)
.cutThruAll()
)
self.saveModel(t)
self.assertEqual(13, t.faces().size())
# no planar faces
sphere_r = 10.0
r = (
Workplane()
.sphere(sphere_r)
.workplane()
.circle(sphere_r / 2.0)
.cutThruAll()
.workplane()
.transformed(rotate=(90, 0, 0))
.circle(sphere_r / 2.0)
.cutThruAll()
.workplane()
.transformed(rotate=(0, 90, 0))
.circle(sphere_r / 2.0)
.cutThruAll()
)
self.assertTrue(r.val().isValid())
self.assertEqual(r.faces().size(), 7)
# test errors
box0 = Workplane().box(1, 1, 1).faces(">Z").workplane().hLine(1)
with raises(ValueError):
box0.cutThruAll()
no_box = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
no_box.cutThruAll()
def testCutToFaceOffsetNOTIMPLEMENTEDYET(self):
"""
Tests cutting up to a given face, or an offset from a face
"""
# base block
s = Workplane(Plane.XY())
r = (
s.rect(2.0, 2.0)
.rect(1.3, 1.3, forConstruction=True)
.vertices()
.circle(0.125)
.extrude(0.5)
)
# side hole, up to 0.1 from the last face
try:
t = (
r.faces(">Y")
.workplane()
.circle(0.125)
.cutToOffsetFromFace(r.faces().mminDist(Dir.Y), 0.1)
)
# should end up being a blind hole
self.assertEqual(10, t.faces().size())
t.first().val().exportStep("c:/temp/testCutToFace.STEP")
except:
pass
# Not Implemented Yet
def testWorkplaneOnExistingSolid(self):
"Tests extruding on an existing solid"
c = (
CQ(makeUnitCube())
.faces(">Z")
.workplane()
.circle(0.25)
.circle(0.125)
.extrude(0.25)
)
self.saveModel(c)
self.assertEqual(10, c.faces().size())
def testWorkplaneCenterMove(self):
# this workplane is centered at x=0.5,y=0.5, the center of the upper face
s = (
Workplane("XY").box(1, 1, 1).faces(">Z").workplane().center(-0.5, -0.5)
) # move the center to the corner
t = s.circle(0.25).extrude(0.2) # make a boss
self.assertEqual(9, t.faces().size())
self.saveModel(t)
def testBasicLines(self):
"Make a triangular boss"
global OUTDIR
s = Workplane(Plane.XY())
# TODO: extrude() should imply wire() if not done already
# most users dont understand what a wire is, they are just drawing
r = s.lineTo(1.0, 0).lineTo(0, 1.0).close().wire().extrude(0.25)
r.val().exportStep(os.path.join(OUTDIR, "testBasicLinesStep1.STEP"))
# no faces on the original workplane
self.assertEqual(0, s.faces().size())
# 5 faces on newly created object
self.assertEqual(5, r.faces().size())
# now add a circle through a side face
r1 = (
r.faces("+XY")
.workplane(centerOption="CenterOfMass")
.circle(0.08)
.cutThruAll()
)
self.assertEqual(6, r1.faces().size())
r1.val().exportStep(os.path.join(OUTDIR, "testBasicLinesXY.STEP"))
# now add a circle through a top
r2 = (
r1.faces("+Z")
.workplane(centerOption="CenterOfMass")
.circle(0.08)
.cutThruAll()
)
self.assertEqual(9, r2.faces().size())
r2.val().exportStep(os.path.join(OUTDIR, "testBasicLinesZ.STEP"))
self.saveModel(r2)
def test2DDrawing(self):
"""
Draw things like 2D lines and arcs, should be expanded later to include all 2D constructs
"""
s = Workplane(Plane.XY())
r = (
s.lineTo(1.0, 0.0)
.lineTo(1.0, 1.0)
.threePointArc((1.0, 1.5), (0.0, 1.0))
.lineTo(0.0, 0.0)
.moveTo(1.0, 0.0)
.lineTo(2.0, 0.0)
.lineTo(2.0, 2.0)
.threePointArc((2.0, 2.5), (0.0, 2.0))
.lineTo(-2.0, 2.0)
.lineTo(-2.0, 0.0)
.close()
)
self.assertEqual(1, r.wires().size())
# Test the *LineTo functions
s = Workplane(Plane.XY())
r = s.hLineTo(1.0).vLineTo(1.0).hLineTo(0.0).close()
self.assertEqual(1, r.wire().size())
self.assertEqual(4, r.edges().size())
# Test the *Line functions
s = Workplane(Plane.XY())
r = s.hLine(1.0).vLine(1.0).hLine(-1.0).close()
self.assertEqual(1, r.wire().size())
self.assertEqual(4, r.edges().size())
# Test the move function
s = Workplane(Plane.XY())
r = s.move(1.0, 1.0).hLine(1.0).vLine(1.0).hLine(-1.0).close()
self.assertEqual(1, r.wire().size())
self.assertEqual(4, r.edges().size())
self.assertEqual(
(1.0, 1.0),
(
r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0)))
.first()
.val()
.X,
r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0)))
.first()
.val()
.Y,
),
)
# Test the sagittaArc and radiusArc functions
a1 = Workplane(Plane.YZ()).threePointArc((5, 1), (10, 0))
a2 = Workplane(Plane.YZ()).sagittaArc((10, 0), -1)
a3 = Workplane(Plane.YZ()).threePointArc((6, 2), (12, 0))
a4 = Workplane(Plane.YZ()).radiusArc((12, 0), -10)
assert a1.edges().first().val().geomType() == "CIRCLE"
assert a2.edges().first().val().geomType() == "CIRCLE"
assert a3.edges().first().val().geomType() == "CIRCLE"
assert a4.edges().first().val().geomType() == "CIRCLE"
assert a1.edges().first().val().Length() == a2.edges().first().val().Length()
assert a3.edges().first().val().Length() == a4.edges().first().val().Length()
def testPolarLines(self):
"""
Draw some polar lines and check expected results
"""
# Test the PolarLine* functions
s = Workplane(Plane.XY())
r = (
s.polarLine(10, 45)
.polarLineTo(10, -45)
.polarLine(10, -180)
.polarLine(-10, -90)
.close()
)
# a single wire, 5 edges
self.assertEqual(1, r.wires().size())
self.assertEqual(5, r.wires().edges().size())
r = Workplane().polarLineTo(1, 20)
assert r.val().positionAt(1).toTuple() == approx(
(0.9396926207859084, 0.3420201433256687, 0.0)
)
r = Workplane().move(1, 1).polarLine(1, 20)
assert r.val().positionAt(1).toTuple() == approx(
(1.9396926207859084, 1.3420201433256687, 0.0)
)
def testLargestDimension(self):
"""
Tests the largestDimension function when no solids are on the stack and when there are
"""
r = Workplane("XY").box(1, 1, 1)
dim = r.largestDimension()
self.assertAlmostEqual(1.76, dim, 1)
r = Workplane("XY").rect(1, 1).extrude(1)
dim = r.largestDimension()
self.assertAlmostEqual(1.76, dim, 1)
r = Workplane("XY")
with raises(ValueError):
r.largestDimension()
def testOccBottle(self):
"""
Make the OCC bottle example.
"""
L = 20.0
w = 6.0
t = 3.0
s = Workplane(Plane.XY())
# draw half the profile of the bottle
p = (
s.center(-L / 2.0, 0)
.vLine(w / 2.0)
.threePointArc((L / 2.0, w / 2.0 + t), (L, w / 2.0))
.vLine(-w / 2.0)
.mirrorX()
.extrude(30.0, True)
)
# make the neck
p.faces(">Z").workplane().circle(3.0).extrude(
2.0, True
) # .edges().fillet(0.05)
# make a shell
p.faces(">Z").shell(0.3)
self.saveModel(p)
def testSplineShape(self):
"""
Tests making a shape with an edge that is a spline
"""
s = Workplane(Plane.XY())
sPnts = [
(2.75, 1.5),
(2.5, 1.75),
(2.0, 1.5),
(1.5, 1.0),
(1.0, 1.25),
(0.5, 1.0),
(0, 1.0),
]
r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close()
r = r.extrude(0.5)
self.saveModel(r)
def testSimpleMirror(self):
"""
Tests a simple mirroring operation
"""
s = (
Workplane("XY")
.lineTo(2, 2)
.threePointArc((3, 1), (2, 0))
.mirrorX()
.extrude(0.25)
)
self.assertEqual(6, s.faces().size())
self.saveModel(s)
def testUnorderedMirror(self):
"""
Tests whether or not a wire can be mirrored if its mirror won't connect to it
"""
r = 20
s = 7
t = 1.5
points = [
(0, 0),
(0, t / 2),
(r / 2 - 1.5 * t, r / 2 - t),
(s / 2, r / 2 - t),
(s / 2, r / 2),
(r / 2, r / 2),
(r / 2, s / 2),
(r / 2 - t, s / 2),
(r / 2 - t, r / 2 - 1.5 * t),
(t / 2, 0),
]
r = Workplane("XY").polyline(points).mirrorX()
self.assertEqual(1, r.wires().size())
self.assertEqual(18, r.edges().size())
# try the same with includeCurrent=True
r = Workplane("XY").polyline(points[1:], includeCurrent=True).mirrorX()
self.assertEqual(1, r.wires().size())
self.assertEqual(18, r.edges().size())
def testChainedMirror(self):
"""
Tests whether or not calling mirrorX().mirrorY() works correctly
"""
r = 20
s = 7
t = 1.5
points = [
(0, t / 2),
(r / 2 - 1.5 * t, r / 2 - t),
(s / 2, r / 2 - t),
(s / 2, r / 2),
(r / 2, r / 2),
(r / 2, s / 2),
(r / 2 - t, s / 2),
(r / 2 - t, r / 2 - 1.5 * t),
(t / 2, 0),
]
r = Workplane("XY").polyline(points).mirrorX().mirrorY().extrude(1).faces(">Z")
self.assertEqual(1, r.wires().size())
self.assertEqual(32, r.edges().size())
# TODO: Re-work testIbeam test below now that chaining works
# TODO: Add toLocalCoords and toWorldCoords tests
def testIbeam(self):
"""
Make an ibeam. demonstrates fancy mirroring
"""
s = Workplane(Plane.XY())
L = 100.0
H = 20.0
W = 20.0
t = 1.0
# TODO: for some reason doing 1/4 of the profile and mirroring twice ( .mirrorX().mirrorY() )
# did not work, due to a bug in freecad-- it was losing edges when creating a composite wire.
# i just side-stepped it for now
pts = [
(0, 0),
(0, H / 2.0),
(W / 2.0, H / 2.0),
(W / 2.0, (H / 2.0 - t)),
(t / 2.0, (H / 2.0 - t)),
(t / 2.0, (t - H / 2.0)),
(W / 2.0, (t - H / 2.0)),
(W / 2.0, H / -2.0),
(0, H / -2.0),
]
r = s.polyline(pts).mirrorY() # these other forms also work
res = r.extrude(L)
self.saveModel(res)
def testCone(self):
"""
Tests that a simple cone works
"""
s = Solid.makeCone(0, 1.0, 2.0)
t = CQ(s)
self.saveModel(t)
self.assertEqual(2, t.faces().size())
def testFillet(self):
"""
Tests filleting edges on a solid
"""
c = (
CQ(makeUnitCube())
.faces(">Z")
.workplane()
.circle(0.25)
.extrude(0.25, True)
.edges("|Z")
.fillet(0.2)
)
self.saveModel(c)
self.assertEqual(12, c.faces().size())
# should raise an error if no solid
c1 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
c1.fillet(0.1)
def testChamfer(self):
"""
Test chamfer API with a box shape
"""
cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1)
self.saveModel(cube)
self.assertEqual(10, cube.faces().size())
# should raise an error if no solid
c1 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
c1.chamfer(0.1)
def testChamferAsymmetrical(self):
"""
Test chamfer API with a box shape for asymmetrical lengths
"""
cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1, 0.2)
self.saveModel(cube)
self.assertEqual(10, cube.faces().size())
# test if edge lengths are different
edge = cube.edges(">Z").vals()[0]
self.assertAlmostEqual(0.6, edge.Length(), 3)
edge = cube.edges("|Z").vals()[0]
self.assertAlmostEqual(0.9, edge.Length(), 3)
def testChamferCylinder(self):
"""
Test chamfer API with a cylinder shape
"""
cylinder = Workplane("XY").circle(1).extrude(1).faces(">Z").chamfer(0.1)
self.saveModel(cylinder)
self.assertEqual(4, cylinder.faces().size())
def testCounterBores(self):
"""
Tests making a set of counterbored holes in a face
"""
c = CQ(makeCube(3.0))
pnts = [(-1.0, -1.0), (0.0, 0.0), (1.0, 1.0)]
c = c.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25, 0.75)
self.assertEqual(18, c.faces().size())
self.saveModel(c)
# Tests the case where the depth of the cboreHole is not specified
c2 = CQ(makeCube(3.0))
c2 = c2.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25)
self.assertEqual(15, c2.faces().size())
def testCounterSinks(self):
"""
Tests countersinks
"""
s = Workplane(Plane.XY())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
def testSplitKeepingHalf(self):
"""
Tests splitting a solid
"""
# drill a hole in the side
c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll()
self.assertEqual(7, c.faces().size())
# now cut it in half sideways
result = c.faces(">Y").workplane(-0.5).split(keepTop=True)
self.saveModel(result)
self.assertEqual(8, result.faces().size())
def testSplitKeepingBoth(self):
"""
Tests splitting a solid
"""
# drill a hole in the side
c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll()
self.assertEqual(7, c.faces().size())
# now cut it in half sideways
result = c.faces(">Y").workplane(-0.5).split(keepTop=True, keepBottom=True)
# stack will have both halves, original will be unchanged
# two solids are on the stack, eac
self.assertEqual(2, result.solids().size())
self.assertEqual(8, result.solids().item(0).faces().size())
self.assertEqual(8, result.solids().item(1).faces().size())
def testSplitKeepingBottom(self):
"""
Tests splitting a solid improperly
"""
# Drill a hole in the side
c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll()
self.assertEqual(7, c.faces().size())
# Now cut it in half sideways
result = c.faces(">Y").workplane(-0.5).split(keepTop=False, keepBottom=True)
# stack will have both halves, original will be unchanged
# one solid is on the stack
self.assertEqual(1, result.solids().size())
self.assertEqual(8, result.solids().item(0).faces().size())
def testSplitError(self):
# Test split produces the correct error when called with no solid to split.
w = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
w.split(keepTop=True)
# Split should raise ValueError when called with no side kept
with raises(ValueError):
w.split(keepTop=False, keepBottom=False)
def testBoxDefaults(self):
"""
Tests creating a single box
"""
s = Workplane("XY").box(2, 3, 4)
self.assertEqual(1, s.solids().size())
self.saveModel(s)
def testSimpleShell(self):
"""
Create s simple box
"""
s1 = Workplane("XY").box(2, 2, 2).faces("+Z").shell(0.05)
self.saveModel(s1)
self.assertEqual(23, s1.faces().size())
s2 = (
Workplane()
.ellipse(4, 2)
.extrude(4)
.faces(">Z")
.shell(+2, kind="intersection")
)
self.assertEqual(5, s2.faces().size())
s3 = Workplane().ellipse(4, 2).extrude(4).faces(">Z").shell(+2, kind="arc")
self.assertEqual(6, s3.faces().size())
# test error on no solid found
s4 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
s4.shell(1)
def testClosedShell(self):
"""
Create a hollow box
"""
s1 = Workplane("XY").box(2, 2, 2).shell(-0.1)
self.assertEqual(12, s1.faces().size())
self.assertTrue(s1.val().isValid())
s2 = Workplane("XY").box(2, 2, 2).shell(0.1)
self.assertEqual(32, s2.faces().size())
self.assertTrue(s2.val().isValid())
pts = [(1.0, 0.0), (0.3, 0.2), (0.0, 0.0), (0.3, -0.1), (1.0, -0.03)]
s3 = Workplane().polyline(pts).close().extrude(1).shell(-0.05)
self.assertTrue(s3.val().isValid())
s4_shape = Workplane("XY").box(2, 2, 2).val()
# test that None and empty list both work and are equivalent
s4_shell_1 = s4_shape.shell(faceList=None, thickness=-0.1)
s4_shell_2 = s4_shape.shell(faceList=[], thickness=-0.1)
# this should be the same as the first shape
self.assertEqual(len(s4_shell_1.Faces()), s1.faces().size())
self.assertEqual(len(s4_shell_2.Faces()), s1.faces().size())
def testOpenCornerShell(self):
s = Workplane("XY").box(1, 1, 1)
s1 = s.faces("+Z")
s1.add(s.faces("+Y")).add(s.faces("+X"))
self.saveModel(s1.shell(0.2))
# Tests the list option variation of add
s1 = s.faces("+Z")
s1.add(s.faces("+Y")).add([s.faces("+X")])
# Tests the raw object option variation of add
s1 = s.faces("+Z")
s1.add(s.faces("+Y")).add(s.faces("+X").val().wrapped)
def testTopFaceFillet(self):
s = Workplane("XY").box(1, 1, 1).faces("+Z").edges().fillet(0.1)
self.assertEqual(s.faces().size(), 10)
self.saveModel(s)
def testBoxPointList(self):
"""
Tests creating an array of boxes
"""
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.box(0.25, 0.25, 0.25, combine=True)
)
# 1 object, 4 solids because the object is a compound
self.assertEqual(4, s.solids().size())
self.assertEqual(1, s.size())
self.saveModel(s)
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.box(0.25, 0.25, 0.25, combine=False)
)
# 4 objects, 4 solids, because each is a separate solid
self.assertEqual(4, s.size())
self.assertEqual(4, s.solids().size())
def testBoxCombine(self):
s = (
Workplane("XY")
.box(4, 4, 0.5)
.faces(">Z")
.workplane()
.rect(3, 3, forConstruction=True)
.vertices()
.box(0.25, 0.25, 0.25, combine=True)
)
self.saveModel(s)
self.assertEqual(1, s.solids().size()) # we should have one big solid
# should have 26 faces. 6 for the box, and 4x5 for the smaller cubes
self.assertEqual(26, s.faces().size())
def testBoxCentered(self):
x, y, z = 10, 11, 12
# check that the bottom corner is where we expect it for all possible combinations of centered
b = [True, False]
expected_x = [-x / 2, 0]
expected_y = [-y / 2, 0]
expected_z = [-z / 2, 0]
for (xopt, xval), (yopt, yval), (zopt, zval) in product(
zip(b, expected_x), zip(b, expected_y), zip(b, expected_z)
):
s = (
Workplane()
.box(x, y, z, centered=(xopt, yopt, zopt))
.vertices("<X and <Y and <Z")
)
self.assertEqual(s.size(), 1)
self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3)
# check centered=True produces the same result as centered=(True, True, True)
for val in b:
s0 = Workplane().box(x, y, z, centered=val).vertices(">X and >Y and >Z")
self.assertEqual(s0.size(), 1)
s1 = (
Workplane()
.box(x, y, z, centered=(val, val, val))
.vertices(">X and >Y and >Z")
)
self.assertEqual(s0.size(), 1)
self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3)
def testSphereDefaults(self):
s = Workplane("XY").sphere(10)
self.saveModel(s) # Until FreeCAD fixes their sphere operation
self.assertEqual(1, s.solids().size())
self.assertEqual(1, s.faces().size())
def testSphereCustom(self):
s = Workplane("XY").sphere(
10, angle1=0, angle2=90, angle3=360, centered=(False, False, False)
)
self.saveModel(s)
self.assertEqual(1, s.solids().size())
self.assertEqual(2, s.faces().size())
# check that the bottom corner is where we expect it for all possible combinations of centered
radius = 10
for (xopt, xval), (yopt, yval), (zopt, zval) in product(
zip((True, False), (0, radius)), repeat=3
):
s = Workplane().sphere(radius, centered=(xopt, yopt, zopt))
self.assertEqual(s.size(), 1)
self.assertTupleAlmostEquals(
s.val().Center().toTuple(), (xval, yval, zval), 3
)
# check centered=True produces the same result as centered=(True, True, True)
for val in (True, False):
s0 = Workplane().sphere(radius, centered=val)
self.assertEqual(s0.size(), 1)
s1 = Workplane().sphere(radius, centered=(val, val, val))
self.assertEqual(s0.size(), 1)
self.assertTupleAlmostEquals(
s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3
)
def testSpherePointList(self):
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.sphere(0.25, combine=False)
)
# self.saveModel(s) # Until FreeCAD fixes their sphere operation
self.assertEqual(4, s.solids().size())
self.assertEqual(4, s.faces().size())
def testSphereCombine(self):
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.sphere(2.25, combine=True)
)
# self.saveModel(s) # Until FreeCAD fixes their sphere operation
self.assertEqual(1, s.solids().size())
self.assertEqual(4, s.faces().size())
def testCylinderDefaults(self):
s = Workplane("XY").cylinder(20, 10)
self.assertEqual(1, s.size())
self.assertEqual(1, s.solids().size())
self.assertEqual(3, s.faces().size())
self.assertEqual(2, s.vertices().size())
self.assertTupleAlmostEquals(s.val().Center().toTuple(), (0, 0, 0), 3)
def testCylinderCentering(self):
radius = 10
height = 40
b = (True, False)
expected_x = (0, radius)
expected_y = (0, radius)
expected_z = (0, height / 2)
for (xopt, xval), (yopt, yval), (zopt, zval) in product(
zip(b, expected_x), zip(b, expected_y), zip(b, expected_z)
):
s = Workplane("XY").cylinder(height, radius, centered=(xopt, yopt, zopt))
self.assertEqual(1, s.size())
self.assertTupleAlmostEquals(
s.val().Center().toTuple(), (xval, yval, zval), 3
)
# check centered=True produces the same result as centered=(True, True, True)
for val in b:
s0 = Workplane("XY").cylinder(height, radius, centered=val)
self.assertEqual(s0.size(), 1)
s1 = Workplane("XY").cylinder(height, radius, centered=(val, val, val))
self.assertEqual(s1.size(), 1)
self.assertTupleAlmostEquals(
s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3
)
def testWedgeDefaults(self):
s = Workplane("XY").wedge(10, 10, 10, 5, 5, 5, 5)
self.saveModel(s)
self.assertEqual(1, s.solids().size())
self.assertEqual(5, s.faces().size())
self.assertEqual(5, s.vertices().size())
def testWedgeCentering(self):
s = Workplane("XY").wedge(
10, 10, 10, 5, 5, 5, 5, centered=(False, False, False)
)
# self.saveModel(s)
self.assertEqual(1, s.solids().size())
self.assertEqual(5, s.faces().size())
self.assertEqual(5, s.vertices().size())
# check that the bottom corner is where we expect it for all possible combinations of centered
x, y, z = 10, 11, 12
b = [True, False]
expected_x = [-x / 2, 0]
expected_y = [-y / 2, 0]
expected_z = [-z / 2, 0]
for (xopt, xval), (yopt, yval), (zopt, zval) in product(
zip(b, expected_x), zip(b, expected_y), zip(b, expected_z)
):
s = (
Workplane()
.wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(xopt, yopt, zopt))
.vertices("<X and <Y and <Z")
)
self.assertEqual(s.size(), 1)
self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3)
# check centered=True produces the same result as centered=(True, True, True)
for val in b:
s0 = (
Workplane()
.wedge(x, y, z, 2, 2, x - 2, z - 2, centered=val)
.vertices(">X and >Z")
)
self.assertEqual(s0.size(), 1)
s1 = (
Workplane()
.wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(val, val, val))
.vertices(">X and >Z")
)
self.assertEqual(s0.size(), 1)
self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3)
def testWedgePointList(self):
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.wedge(10, 10, 10, 5, 5, 5, 5, combine=False)
)
# self.saveModel(s)
self.assertEqual(4, s.solids().size())
self.assertEqual(20, s.faces().size())
self.assertEqual(20, s.vertices().size())
def testWedgeCombined(self):
s = (
Workplane("XY")
.rect(4.0, 4.0, forConstruction=True)
.vertices()
.wedge(10, 10, 10, 5, 5, 5, 5, combine=True)
)
# self.saveModel(s)
self.assertEqual(1, s.solids().size())
self.assertEqual(12, s.faces().size())
self.assertEqual(16, s.vertices().size())
def testQuickStartXY(self):
s = (
Workplane(Plane.XY())
.box(2, 4, 0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.assertEqual(1, s.solids().size())
self.assertEqual(14, s.faces().size())
self.saveModel(s)
def testQuickStartYZ(self):
s = (
Workplane(Plane.YZ())
.box(2, 4, 0.5)
.faces(">X")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.assertEqual(1, s.solids().size())
self.assertEqual(14, s.faces().size())
self.saveModel(s)
def testQuickStartXZ(self):
s = (
Workplane(Plane.XZ())
.box(2, 4, 0.5)
.faces(">Y")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.assertEqual(1, s.solids().size())
self.assertEqual(14, s.faces().size())
self.saveModel(s)
def testDoubleTwistedLoft(self):
s = (
Workplane("XY")
.polygon(8, 20.0)
.workplane(offset=4.0)
.transformed(rotate=Vector(0, 0, 15.0))
.polygon(8, 20)
.loft()
)
s2 = (
Workplane("XY")
.polygon(8, 20.0)
.workplane(offset=-4.0)
.transformed(rotate=Vector(0, 0, 15.0))
.polygon(8, 20)
.loft()
)
# self.assertEquals(10,s.faces().size())
# self.assertEquals(1,s.solids().size())
s3 = s.combineSolids(s2)
self.saveModel(s3)
def testTwistedLoft(self):
s = (
Workplane("XY")
.polygon(8, 20.0)
.workplane(offset=4.0)
.transformed(rotate=Vector(0, 0, 15.0))
.polygon(8, 20)
.loft()
)
self.assertEqual(10, s.faces().size())
self.assertEqual(1, s.solids().size())
self.saveModel(s)
def testUnions(self):
# duplicates a memory problem of some kind reported when combining lots of objects
s = Workplane("XY").rect(0.5, 0.5).extrude(5.0)
o = []
beginTime = time.time()
for i in range(15):
t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0)
o.append(t)
# union stuff
for oo in o:
s = s.union(oo)
print("Total time %0.3f" % (time.time() - beginTime))
# Test unioning a Solid object
s = Workplane(Plane.XY())
currentS = s.rect(2.0, 2.0).extrude(0.5)
toUnion = s.rect(1.0, 1.0).extrude(1.0)
resS = currentS.union(toUnion)
self.assertEqual(11, resS.faces().size())
with self.assertRaises(ValueError):
resS.union(toUnion.faces().val())
# Test syntactic sugar [__add__ method]
sugar1 = currentS | toUnion
sugar2 = currentS + toUnion
self.assertEqual(resS.faces().size(), sugar1.faces().size())
self.assertEqual(resS.faces().size(), sugar2.faces().size())
def testCombine(self):
s = Workplane(Plane.XY())
objects1 = s.rect(2.0, 2.0).extrude(0.5).faces(">Z").rect(1.0, 1.0).extrude(0.5)
objects1.combine()
self.assertEqual(11, objects1.faces().size())
objects1 = s.rect(2.0, 2.0).extrude(0.5)
objects2 = s.rect(1.0, 1.0).extrude(0.5).translate((0, 0, 0.5))
objects2 = objects1.add(objects2).combine(glue=True, tol=None)
self.assertEqual(11, objects2.faces().size())
def testCombineSolidsInLoop(self):
# duplicates a memory problem of some kind reported when combining lots of objects
s = Workplane("XY").rect(0.5, 0.5).extrude(5.0)
o = []
beginTime = time.time()
for i in range(15):
t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0)
o.append(t)
# append the 'good way'
for oo in o:
s.add(oo)
s = s.combineSolids()
print("Total time %0.3f" % (time.time() - beginTime))
self.saveModel(s)
def testClean(self):
"""
Tests the `clean()` method which is called automatically.
"""
# make a cube with a splitter edge on one of the faces
# autosimplify should remove the splitter
s = (
Workplane("XY")
.moveTo(0, 0)
.line(5, 0)
.line(5, 0)
.line(0, 10)
.line(-10, 0)
.close()
.extrude(10)
)
self.assertEqual(6, s.faces().size())
# test removal of splitter caused by union operation
s = Workplane("XY").box(10, 10, 10).union(Workplane("XY").box(20, 10, 10))
self.assertEqual(6, s.faces().size())
# test removal of splitter caused by extrude+combine operation
s = (
Workplane("XY")
.box(10, 10, 10)
.faces(">Y")
.workplane()
.rect(5, 10, True)
.extrude(20)
)
self.assertEqual(10, s.faces().size())
# test removal of splitter caused by double hole operation
s = (
Workplane("XY")
.box(10, 10, 10)
.faces(">Z")
.workplane()
.hole(3, 5)
.faces(">Z")
.workplane()
.hole(3, 10)
)
self.assertEqual(7, s.faces().size())
# test removal of splitter caused by cutThruAll
s = (
Workplane("XY")
.box(10, 10, 10)
.faces(">Y")
.workplane()
.rect(10, 5)
.cutBlind(-5)
.faces(">Z")
.workplane(centerOption="CenterOfMass")
.center(0, 2.5)
.rect(5, 5)
.cutThruAll()
)
self.assertEqual(18, s.faces().size())
# test removal of splitter with box
s = Workplane("XY").box(5, 5, 5).box(10, 5, 2)
self.assertEqual(14, s.faces().size())
s = Workplane().sphere(1).box(0.5, 4, 4, clean=True)
assert len(s.edges().vals()) == 14
s = (
Workplane()
.box(1, 1, 1)
.faces("<Z")
.workplane()
.cylinder(
2, 0.2, centered=(True, True, False), direct=(0, 0, -1), clean=True
)
)
assert len(s.edges().vals()) == 15
s = (
Workplane()
.pushPoints([(-0.5, -0.2), (0.5, 0.2)])
.rect(2, 2)
.extrude(0.2, clean=False)
.pushPoints([(0, 0, -1)])
.interpPlate(
[Edge.makeCircle(2)], [(0, 0, 1)], 0.2, combine=True, clean=True
)
)
assert len(s.edges().vals()) < 40
s = Workplane().box(0.5, 4, 4).sphere(1, clean=True)
assert len(s.edges().vals()) == 14
s = Workplane().sphere(1).wedge(0.5, 4, 4, 0, 0, 0.5, 4, clean=True)
assert len(s.edges().vals()) == 14
def testNoClean(self):
"""
Test the case when clean is disabled.
"""
# test disabling autoSimplify
s = (
Workplane("XY")
.moveTo(0, 0)
.line(5, 0)
.line(5, 0)
.line(0, 10)
.line(-10, 0)
.close()
.extrude(10, clean=False)
)
self.assertEqual(7, s.faces().size())
s = (
Workplane("XY")
.box(10, 10, 10)
.union(Workplane("XY").box(20, 10, 10), clean=False)
)
self.assertEqual(14, s.faces().size())
s = (
Workplane("XY")
.box(10, 10, 10)
.faces(">Y")
.workplane()
.rect(5, 10, True)
.extrude(20, clean=False)
)
self.assertEqual(12, s.faces().size())
s = Workplane().sphere(1).box(0.5, 4, 4, clean=False)
assert len(s.edges().vals()) == 16
s = (
Workplane()
.box(1, 1, 1)
.faces("<Z")
.workplane()
.cylinder(
2, 0.2, centered=(True, True, False), direct=(0, 0, -1), clean=False
)
)
assert len(s.edges().vals()) == 16
s = (
Workplane()
.pushPoints([(-0.5, -0.2), (0.5, 0.2)])
.rect(2, 2)
.extrude(0.2, clean=False)
.pushPoints([(0, 0, -1)])
.interpPlate(
[Edge.makeCircle(2)], [(0, 0, 1)], 0.2, combine=True, clean=False
)
)
assert len(s.edges().vals()) > 45
s = Workplane().box(0.5, 4, 4).sphere(1, clean=False)
assert len(s.edges().vals()) == 16
s = Workplane().sphere(1).wedge(0.5, 4, 4, 0, 0, 0.5, 4, clean=False)
assert len(s.edges().vals()) == 16
def testExplicitClean(self):
"""
Test running of `clean()` method explicitly.
"""
s = (
Workplane("XY")
.moveTo(0, 0)
.line(5, 0)
.line(5, 0)
.line(0, 10)
.line(-10, 0)
.close()
.extrude(10, clean=False)
.clean()
)
self.assertEqual(6, s.faces().size())
def testPlanes(self):
"""
Test other planes other than the normal ones (XY, YZ)
"""
# ZX plane
s = Workplane(Plane.ZX())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# YX plane
s = Workplane(Plane.YX())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# YX plane
s = Workplane(Plane.YX())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# ZY plane
s = Workplane(Plane.ZY())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# front plane
s = Workplane(Plane.front())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# back plane
s = Workplane(Plane.back())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# left plane
s = Workplane(Plane.left())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# right plane
s = Workplane(Plane.right())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# top plane
s = Workplane(Plane.top())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
# bottom plane
s = Workplane(Plane.bottom())
result = (
s.rect(2.0, 4.0)
.extrude(0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
self.saveModel(result)
def testIsInside(self):
"""
Testing if one box is inside of another.
"""
box1 = Workplane(Plane.XY()).box(10, 10, 10)
box2 = Workplane(Plane.XY()).box(5, 5, 5)
self.assertFalse(box2.val().BoundingBox().isInside(box1.val().BoundingBox()))
self.assertTrue(box1.val().BoundingBox().isInside(box2.val().BoundingBox()))
def testCup(self):
"""
UOM = "mm"
#
# PARAMETERS and PRESETS
# These parameters can be manipulated by end users
#
bottomDiameter = FloatParam(min=10.0,presets={'default':50.0,'tumbler':50.0,'shot':35.0,'tea':50.0,'saucer':100.0},group="Basics", desc="Bottom diameter")
topDiameter = FloatParam(min=10.0,presets={'default':85.0,'tumbler':85.0,'shot':50.0,'tea':51.0,'saucer':400.0 },group="Basics", desc="Top diameter")
thickness = FloatParam(min=0.1,presets={'default':2.0,'tumbler':2.0,'shot':2.66,'tea':2.0,'saucer':2.0},group="Basics", desc="Thickness")
height = FloatParam(min=1.0,presets={'default':80.0,'tumbler':80.0,'shot':59.0,'tea':125.0,'saucer':40.0},group="Basics", desc="Overall height")
lipradius = FloatParam(min=1.0,presets={'default':1.0,'tumbler':1.0,'shot':0.8,'tea':1.0,'saucer':1.0},group="Basics", desc="Lip Radius")
bottomThickness = FloatParam(min=1.0,presets={'default':5.0,'tumbler':5.0,'shot':10.0,'tea':10.0,'saucer':5.0},group="Basics", desc="BottomThickness")
#
# Your build method. It must return a solid object
#
def build():
br = bottomDiameter.value / 2.0
tr = topDiameter.value / 2.0
t = thickness.value
s1 = Workplane("XY").circle(br).workplane(offset=height.value).circle(tr).loft()
s2 = Workplane("XY").workplane(offset=bottomThickness.value).circle(br - t ).workplane(offset=height.value - t ).circle(tr - t).loft()
cup = s1.cut(s2)
cup.faces(">Z").edges().fillet(lipradius.value)
return cup
"""
# for some reason shell doesn't work on this simple shape. how disappointing!
td = 50.0
bd = 20.0
h = 10.0
t = 1.0
s1 = Workplane("XY").circle(bd).workplane(offset=h).circle(td).loft()
s2 = (
Workplane("XY")
.workplane(offset=t)
.circle(bd - (2.0 * t))
.workplane(offset=(h - t))
.circle(td - (2.0 * t))
.loft()
)
s3 = s1.cut(s2)
self.saveModel(s3)
def testEnclosure(self):
"""
Builds an electronics enclosure
Original FreeCAD script: 81 source statements ,not including variables
This script: 34
"""
# parameter definitions
p_outerWidth = 100.0 # Outer width of box enclosure
p_outerLength = 150.0 # Outer length of box enclosure
p_outerHeight = 50.0 # Outer height of box enclosure
p_thickness = 3.0 # Thickness of the box walls
p_sideRadius = 10.0 # Radius for the curves around the sides of the bo
# Radius for the curves on the top and bottom edges of the box
p_topAndBottomRadius = 2.0
# How far in from the edges the screwposts should be place.
p_screwpostInset = 12.0
# Inner Diameter of the screwpost holes, should be roughly screw diameter not including threads
p_screwpostID = 4.0
# Outer Diameter of the screwposts.\nDetermines overall thickness of the posts
p_screwpostOD = 10.0
p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any
p_boreDepth = 1.0 # Depth of the counterbore hole, if
# Outer diameter of countersink. Should roughly match the outer diameter of the screw head
p_countersinkDiameter = 0.0
# Countersink angle (complete angle between opposite sides, not from center to one side)
p_countersinkAngle = 90.0
# Whether to place the lid with the top facing down or not.
p_flipLid = True
# Height of lip on the underside of the lid.\nSits inside the box body for a snug fit.
p_lipHeight = 1.0
# outer shell
oshell = (
Workplane("XY")
.rect(p_outerWidth, p_outerLength)
.extrude(p_outerHeight + p_lipHeight)
)
# weird geometry happens if we make the fillets in the wrong order
if p_sideRadius > p_topAndBottomRadius:
oshell = (
oshell.edges("|Z")
.fillet(p_sideRadius)
.edges("#Z")
.fillet(p_topAndBottomRadius)
)
else:
oshell = (
oshell.edges("#Z")
.fillet(p_topAndBottomRadius)
.edges("|Z")
.fillet(p_sideRadius)
)
# inner shell
ishell = (
oshell.faces("<Z")
.workplane(p_thickness, True)
.rect(
(p_outerWidth - 2.0 * p_thickness), (p_outerLength - 2.0 * p_thickness)
)
.extrude((p_outerHeight - 2.0 * p_thickness), False)
) # set combine false to produce just the new boss
ishell = ishell.edges("|Z").fillet(p_sideRadius - p_thickness)
# make the box outer box
box = oshell.cut(ishell)
# make the screwposts
POSTWIDTH = p_outerWidth - 2.0 * p_screwpostInset
POSTLENGTH = p_outerLength - 2.0 * p_screwpostInset
box = (
box.faces(">Z")
.workplane(-p_thickness)
.rect(POSTWIDTH, POSTLENGTH, forConstruction=True)
.vertices()
.circle(p_screwpostOD / 2.0)
.circle(p_screwpostID / 2.0)
.extrude((-1.0) * (p_outerHeight + p_lipHeight - p_thickness), True)
)
# split lid into top and bottom parts
(lid, bottom) = (
box.faces(">Z")
.workplane(-p_thickness - p_lipHeight)
.split(keepTop=True, keepBottom=True)
.all()
) # splits into two solids
# translate the lid, and subtract the bottom from it to produce the lid inset
lowerLid = lid.translate((0, 0, -p_lipHeight))
cutlip = lowerLid.cut(bottom).translate(
(p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight)
)
# compute centers for counterbore/countersink or counterbore
topOfLidCenters = (
cutlip.faces(">Z")
.workplane()
.rect(POSTWIDTH, POSTLENGTH, forConstruction=True)
.vertices()
)
# add holes of the desired type
if p_boreDiameter > 0 and p_boreDepth > 0:
topOfLid = topOfLidCenters.cboreHole(
p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness
)
elif p_countersinkDiameter > 0 and p_countersinkAngle > 0:
topOfLid = topOfLidCenters.cskHole(
p_screwpostID,
p_countersinkDiameter,
p_countersinkAngle,
(2.0) * p_thickness,
)
else:
topOfLid = topOfLidCenters.hole(p_screwpostID, (2.0) * p_thickness)
# flip lid upside down if desired
if p_flipLid:
topOfLid.rotateAboutCenter((1, 0, 0), 180)
# return the combined result
result = topOfLid.union(bottom)
self.saveModel(result)
def testExtrudeUntilFace(self):
"""
Test untilNextFace and untilLastFace options of Workplane.extrude()
"""
# Basic test to see if it yields same results as regular extrude for similar use case
# Also test if the extrusion worked well by counting the number of faces before and after extrusion
wp_ref = Workplane("XY").box(10, 10, 10).center(20, 0).box(10, 10, 10)
wp_ref_extrude = wp_ref.faces(">X[1]").workplane().rect(1, 1).extrude(10)
wp = Workplane("XY").box(10, 10, 10).center(20, 0).box(10, 10, 10)
nb_faces = wp.faces().size()
wp = wp_ref.faces(">X[1]").workplane().rect(1, 1).extrude("next")
self.assertAlmostEqual(wp_ref_extrude.val().Volume(), wp.val().Volume())
self.assertTrue(wp.faces().size() - nb_faces == 4)
# Test tapered option and both option
wp = (
wp_ref.faces(">X[1]")
.workplane(centerOption="CenterOfMass", offset=5)
.polygon(5, 3)
.extrude("next", both=True)
)
wp_both_volume = wp.val().Volume()
self.assertTrue(wp.val().isValid())
# taper
wp = (
wp_ref.faces(">X[1]")
.workplane(centerOption="CenterOfMass")
.polygon(5, 3)
.extrude("next", taper=5)
)
self.assertTrue(wp.val().Volume() < wp_both_volume)
self.assertTrue(wp.val().isValid())
# Test extrude until with more that one wire in context
wp = (
wp_ref.faces(">X[1]")
.workplane(centerOption="CenterOfMass")
.pushPoints([(0, 0), (3, 3)])
.rect(2, 3)
.extrude("next")
)
self.assertTrue(wp.solids().size() == 1)
self.assertTrue(wp.val().isValid())
# Test until last surf
wp_ref = wp_ref.workplane().move(10, 0).box(5, 5, 5)
wp = (
wp_ref.faces(">X[1]")
.workplane(centerOption="CenterOfMass")
.circle(2)
.extrude("last")
)
self.assertTrue(wp.solids().size() == 1)
with self.assertRaises(ValueError):
Workplane("XY").box(10, 10, 10).center(20, 0).box(10, 10, 10).faces(
">X[1]"
).workplane().rect(1, 1).extrude("test")
# Test extrude until arbitrary face
arbitrary_face = (
Workplane("XZ", origin=(0, 30, 0))
.transformed((20, 0, 0))
.box(10, 10, 10)
.faces("<Y")
.val()
)
wp = (
Workplane()
.box(5, 5, 5)
.faces(">Y")
.workplane()
.circle(2)
.extrude(until=arbitrary_face)
)
extremity_face_area = wp.faces(">Y").val().Area()
self.assertAlmostEqual(extremity_face_area, 13.372852288495501, 5)
# Test that a ValueError is raised if no face can be found to extrude until
with self.assertRaises(ValueError):
wp = (
Workplane()
.box(5, 5, 5)
.faces(">X")
.workplane(offset=10)
.transformed((90, 0, 0))
.circle(2)
.extrude(until="next")
)
# Test that a ValueError for:
# Extrusion in both direction while having a face to extrude only in one
with self.assertRaises(ValueError):
wp = (
Workplane()
.box(5, 5, 5)
.faces(">X")
.workplane(offset=10)
.transformed((90, 0, 0))
.circle(2)
.extrude(until="next", both=True)
)
# Test that a ValueError for:
# Extrusion in both direction while having no faces to extrude
with self.assertRaises(ValueError):
wp = Workplane().circle(2).extrude(until="next", both=True)
# Check that a ValueError is raised if the user want to use `until` with a face and `combine` = False
# This isn't possible as the result of the extrude operation automatically combine the result with the base solid
with self.assertRaises(ValueError):
wp = (
Workplane()
.box(5, 5, 5)
.faces(">X")
.workplane(offset=10)
.transformed((90, 0, 0))
.circle(2)
.extrude(until="next", combine=False)
)
# Same as previous test, but use an object of type Face
with self.assertRaises(ValueError):
wp = Workplane().box(5, 5, 5).faces(">X")
face0 = wp.val()
wp = (
wp.workplane(offset=10)
.transformed((90, 0, 0))
.circle(2)
.extrude(until=face0, combine=False)
)
# Test extrude up to next face when workplane is inside a solid (which should still extrude
# past solid surface and up to next face)
# make an I-beam shape
part = (
Workplane()
.tag("base")
.box(10, 1, 1, centered=True)
.faces(">Z")
.workplane()
.box(1, 1, 10, centered=(True, True, False))
.faces(">Z")
.workplane()
.box(10, 1, 1, centered=(True, True, False))
# make an extrusion that starts inside the existing solid
.workplaneFromTagged("base")
.center(3, 0)
.circle(0.4)
# "next" should extrude to the top of the I-beam, not the bottom (0.5 units away)
.extrude("next")
)
part_section = part.faces("<Z").workplane().section(-5)
self.assertEqual(part_section.faces().size(), 2)
def testCutBlindUntilFace(self):
"""
Test untilNextFace and untilLastFace options of Workplane.cutBlind()
"""
# Basic test to see if it yields same results as regular cutBlind for similar use case
wp_ref = (
Workplane("XY")
.box(40, 10, 2)
.pushPoints([(-20, 0, 5), (0, 0, 5), (20, 0, 5)])
.box(10, 10, 10)
)
wp_ref_regular_cut = (
wp_ref.faces(">X[2]")
.workplane(centerOption="CenterOfMass")
.rect(2, 2)
.cutBlind(-10)
)
wp = (
wp_ref.faces(">X[2]")
.workplane(centerOption="CenterOfMass")
.rect(2, 2)
.cutBlind("last")
)
self.assertAlmostEqual(wp_ref_regular_cut.val().Volume(), wp.val().Volume())
wp_last = (
wp_ref.faces(">X[4]")
.workplane(centerOption="CenterOfMass")
.rect(2, 2)
.cutBlind("last")
)
wp_next = (
wp_ref.faces(">X[4]")
.workplane(centerOption="CenterOfMass")
.rect(2, 2)
.cutBlind("next")
)
self.assertTrue(wp_last.val().Volume() < wp_next.val().Volume())
# multiple wire cuts
wp = (
wp_ref.faces(">X[4]")
.workplane(centerOption="CenterOfMass", offset=0)
.rect(2.5, 2.5, forConstruction=True)
.vertices()
.rect(1, 1)
.cutBlind("last")
)
self.assertTrue(wp.faces().size() == 50)
with self.assertRaises(ValueError):
Workplane("XY").box(10, 10, 10).center(20, 0).box(10, 10, 10).faces(
">X[1]"
).workplane().rect(1, 1).cutBlind("test")
# Test extrusion to an arbitrary face
arbitrary_face = (
Workplane("XZ", origin=(0, 5, 0))
.transformed((20, 0, 0))
.box(10, 10, 10)
.faces("<Y")
.val()
)
wp = (
Workplane()
.box(5, 5, 5)
.faces(">Y")
.workplane()
.circle(2)
.cutBlind(until=arbitrary_face)
)
inner_face_area = wp.faces("<<Y[3]").val().Area()
self.assertAlmostEqual(inner_face_area, 13.372852288495503, 5)
def testFaceIntersectedByLine(self):
with self.assertRaises(ValueError):
Workplane().box(5, 5, 5).val().facesIntersectedByLine(
(0, 0, 0), (0, 0, 1), direction="Z"
)
pts = [(-10, 0), (-5, 0), (0, 0), (5, 0), (10, 0)]
shape = (
Workplane()
.box(20, 10, 5)
.faces(">Z")
.workplane()
.pushPoints(pts)
.box(1, 10, 10)
)
faces = shape.val().facesIntersectedByLine((0, 0, 7.5), (1, 0, 0))
mx_face = shape.faces("<X").val()
px_face = shape.faces(">X").val()
self.assertTrue(len(faces) == 10)
# extremum faces are last or before last face
self.assertTrue(mx_face in faces[-2:])
self.assertTrue(px_face in faces[-2:])
def testExtrude(self):
"""
Test extrude
"""
r = 1.0
h = 1.0
decimal_places = 9.0
# extrude in one direction
s = Workplane("XY").circle(r).extrude(h, both=False)
top_face = s.faces(">Z")
bottom_face = s.faces("<Z")
# calculate the distance between the top and the bottom face
delta = top_face.val().Center().sub(bottom_face.val().Center())
self.assertTupleAlmostEquals(delta.toTuple(), (0.0, 0.0, h), decimal_places)
# extrude symmetrically
s = Workplane("XY").circle(r).extrude(h, both=True)
self.assertTrue(len(s.val().Solids()) == 1)
top_face = s.faces(">Z")
bottom_face = s.faces("<Z")
# calculate the distance between the top and the bottom face
delta = top_face.val().Center().sub(bottom_face.val().Center())
self.assertTupleAlmostEquals(
delta.toTuple(), (0.0, 0.0, 2.0 * h), decimal_places
)
# check that non-conplanar extrusion raises
with self.assertRaises(ValueError):
Workplane().box(1, 1, 1).faces().circle(0.1).extrude(0.1)
# check that extruding nested geometry raises
with self.assertRaises(ValueError):
Workplane().rect(2, 2).rect(1, 1).extrude(2, taper=4)
# Test extrude with combine="cut"
box = Workplane().box(5, 5, 5)
r = box.faces(">Z").workplane(invert=True).circle(0.5).extrude(4, combine="cut")
self.assertGreater(box.val().Volume(), r.val().Volume())
# Test extrude with both=True and combine="cut"
wp_ref = Workplane("XY").rect(40, 40).extrude(20, both=True)
wp_ref_regular_cut = (
wp_ref.workplane(offset=-20).rect(20, 20).extrude(40, combine="s")
)
wp = wp_ref.workplane().rect(20, 20).extrude(20, both=True, combine="s")
assert wp.faces().size() == 6 + 4
self.assertAlmostEqual(wp_ref_regular_cut.val().Volume(), wp.val().Volume())
def testTaperedExtrudeCutBlind(self):
h = 1.0
r = 1.0
t = 5
# extrude with a positive taper
s = Workplane("XY").circle(r).extrude(h, taper=t)
top_face = s.faces(">Z")
bottom_face = s.faces("<Z")
# top and bottom face area
delta = top_face.val().Area() - bottom_face.val().Area()
self.assertTrue(delta < 0)
# extrude with a negative taper
s = Workplane("XY").circle(r).extrude(h, taper=-t)
top_face = s.faces(">Z")
bottom_face = s.faces("<Z")
# top and bottom face area
delta = top_face.val().Area() - bottom_face.val().Area()
self.assertTrue(delta > 0)
# cut a tapered hole
s = (
Workplane("XY")
.rect(2 * r, 2 * r)
.extrude(2 * h)
.faces(">Z")
.workplane()
.rect(r, r)
.cutBlind(-h, taper=t)
)
middle_face = s.faces(">Z[-2]")
self.assertTrue(middle_face.val().Area() < 1)
with self.assertWarns(DeprecationWarning):
s = (
Workplane("XY")
.rect(2 * r, 2 * r)
.extrude(2 * h)
.faces(">Z")
.workplane()
.rect(r, r)
.cutBlind(-h, True, float(t))
)
def testTaperedExtrudeHeight(self):
"""
Ensures that the tapered prism has the correct height.
"""
# Tapered extrusion to check the height of, with positive taper
s = Workplane("XY").rect(100.0, 100.0).extrude(100.0, taper=20.0)
# Get the bounding box and make sure the height matches the requested height
bb = s.val().BoundingBox()
self.assertAlmostEqual(bb.zlen, 100.0)
# Tapered extrusion to check the height of, with negative taper
s2 = Workplane("XY").rect(100.0, 100.0).extrude(100.0, taper=-20.0)
# Get the bounding box and make sure the height matches the requested height
bb2 = s2.val().BoundingBox()
self.assertAlmostEqual(bb2.zlen, 100.0)
def testClose(self):
# Close without endPoint and startPoint coincide.
# Create a half-circle
a = Workplane(Plane.XY()).sagittaArc((10, 0), 2).close().extrude(2)
# Close when endPoint and startPoint coincide.
# Create a double half-circle
b = (
Workplane(Plane.XY())
.sagittaArc((10, 0), 2)
.sagittaArc((0, 0), 2)
.close()
.extrude(2)
)
# The b shape shall have twice the volume of the a shape.
self.assertAlmostEqual(a.val().Volume() * 2.0, b.val().Volume())
# Testcase 3 from issue #238
thickness = 3.0
length = 10.0
width = 5.0
obj1 = (
Workplane("XY", origin=(0, 0, -thickness / 2))
.moveTo(length / 2, 0)
.threePointArc((0, width / 2), (-length / 2, 0))
.threePointArc((0, -width / 2), (length / 2, 0))
.close()
.extrude(thickness)
)
os_x = 8.0 # Offset in X
os_y = -19.5 # Offset in Y
obj2 = (
Workplane("YZ", origin=(os_x, os_y, -thickness / 2))
.moveTo(os_x + length / 2, os_y)
.sagittaArc((os_x - length / 2, os_y), width / 2)
.sagittaArc((os_x + length / 2, os_y), width / 2)
.close()
.extrude(thickness)
)
# The obj1 shape shall have the same volume as the obj2 shape.
self.assertAlmostEqual(obj1.val().Volume(), obj2.val().Volume())
def testText(self):
global testdataDir
box = Workplane("XY").box(4, 4, 0.5)
obj1 = (
box.faces(">Z")
.workplane()
.text(
"CQ 2.0",
0.5,
-0.05,
cut=True,
halign="left",
valign="bottom",
font="Sans",
)
)
# combined object should have smaller volume
self.assertGreater(box.val().Volume(), obj1.val().Volume())
obj2 = (
box.faces(">Z")
.workplane()
.text("CQ 2.0", 0.5, 0.05, cut=False, combine=True, font="Sans")
)
# combined object should have bigger volume
self.assertLess(box.val().Volume(), obj2.val().Volume())
# verify that the number of top faces is correct (NB: this is font specific)
self.assertEqual(len(obj2.faces(">Z").vals()), 5)
obj3 = (
box.faces(">Z")
.workplane()
.text(
"CQ 2.0",
0.5,
0.05,
cut=False,
combine=False,
halign="right",
valign="top",
font="Sans",
)
)
# verify that the number of solids is correct
self.assertEqual(len(obj3.solids().vals()), 5)
obj4 = (
box.faces(">Z")
.workplane()
.text(
"CQ 2.0",
0.5,
0.05,
fontPath=os.path.join(testdataDir, "OpenSans-Regular.ttf"),
cut=False,
combine=False,
halign="right",
valign="top",
font="Sans",
)
)
# verify that the number of solids is correct
self.assertEqual(len(obj4.solids().vals()), 5)
# test to see if non-existent file causes segfault
obj5 = (
box.faces(">Z")
.workplane()
.text(
"CQ 2.0",
0.5,
0.05,
fontPath=os.path.join(testdataDir, "OpenSans-Irregular.ttf"),
cut=False,
combine=False,
halign="right",
valign="top",
font="Sans",
)
)
# verify that the number of solids is correct
self.assertEqual(len(obj5.solids().vals()), 5)
# check it doesn't fall over with int sizes
obj1 = (
box.faces(">Z")
.workplane()
.text(
"CQ 2.0", 10, -1, cut=True, halign="left", valign="bottom", font="Sans",
)
)
def testParametricCurve(self):
from math import sin, cos, pi
k = 4
r = 1
func = lambda t: (
r * (k + 1) * cos(t) - r * cos((k + 1) * t),
r * (k + 1) * sin(t) - r * sin((k + 1) * t),
)
res_open = Workplane("XY").parametricCurve(func).extrude(3)
# open profile generates an invalid solid
self.assertFalse(res_open.solids().val().isValid())
res_closed = (
Workplane("XY").parametricCurve(func, start=0, stop=2 * pi).extrude(3)
)
# closed profile will generate a valid solid with 3 faces
self.assertTrue(res_closed.solids().val().isValid())
self.assertEqual(len(res_closed.faces().vals()), 3)
res_edge = Workplane("XY").parametricCurve(func, makeWire=False)
self.assertEqual(len(res_edge.ctx.pendingEdges), 1)
self.assertEqual(len(res_edge.ctx.pendingWires), 0)
def testMakeShellSolid(self):
c0 = math.sqrt(2) / 4
vertices = [[c0, -c0, c0], [c0, c0, -c0], [-c0, c0, c0], [-c0, -c0, -c0]]
faces_ixs = [[0, 1, 2, 0], [1, 0, 3, 1], [2, 3, 0, 2], [3, 2, 1, 3]]
faces = []
for ixs in faces_ixs:
lines = []
for v1, v2 in zip(ixs, ixs[1:]):
lines.append(
Edge.makeLine(Vector(*vertices[v1]), Vector(*vertices[v2]))
)
wire = Wire.combine(lines)[0]
faces.append(Face.makeFromWires(wire))
shell = Shell.makeShell(faces)
solid = Solid.makeSolid(shell)
self.assertTrue(shell.isValid())
self.assertTrue(solid.isValid())
self.assertEqual(len(solid.Vertices()), 4)
self.assertEqual(len(solid.Faces()), 4)
def testIsInsideSolid(self):
# test solid
model = Workplane("XY").box(10, 10, 10)
solid = model.val() # get first object on stack
self.assertTrue(solid.isInside((0, 0, 0)))
self.assertFalse(solid.isInside((10, 10, 10)))
self.assertTrue(solid.isInside((Vector(3, 3, 3))))
self.assertFalse(solid.isInside((Vector(30.0, 30.0, 30.0))))
self.assertTrue(solid.isInside((0, 0, 4.99), tolerance=0.1))
self.assertTrue(solid.isInside((0, 0, 5))) # check point on surface
self.assertTrue(solid.isInside((0, 0, 5.01), tolerance=0.1))
self.assertFalse(solid.isInside((0, 0, 5.1), tolerance=0.1))
# test compound solid
model = Workplane("XY").box(10, 10, 10)
model = model.moveTo(50, 50).box(10, 10, 10)
solid = model.val()
self.assertTrue(solid.isInside((0, 0, 0)))
self.assertTrue(solid.isInside((50, 50, 0)))
self.assertFalse(solid.isInside((50, 56, 0)))
# make sure raises on non solid
model = Workplane("XY").rect(10, 10)
solid = model.val()
with self.assertRaises(AttributeError):
solid.isInside((0, 0, 0))
# test solid with an internal void
void = Workplane("XY").box(10, 10, 10)
model = Workplane("XY").box(100, 100, 100).cut(void)
solid = model.val()
self.assertFalse(solid.isInside((0, 0, 0)))
self.assertTrue(solid.isInside((40, 40, 40)))
self.assertFalse(solid.isInside((55, 55, 55)))
def testWorkplaneCenterOptions(self):
"""
Test options for specifying origin of workplane
"""
decimal_places = 9
pts = [(0, 0), (90, 0), (90, 30), (30, 30), (30, 60), (0.0, 60)]
r = Workplane("XY").polyline(pts).close().extrude(10.0)
origin = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places)
origin = (
r.faces(">Z").workplane(centerOption="CenterOfMass").plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (37.5, 22.5, 10.0), decimal_places)
origin = (
r.faces(">Z")
.workplane(centerOption="CenterOfBoundBox")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (45.0, 30.0, 10.0), decimal_places)
origin = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin", origin=(30, 10, 20))
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places)
origin = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin", origin=Vector(30, 10, 20))
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places)
with self.assertRaises(ValueError):
origin = r.faces(">Z").workplane(centerOption="undefined")
# test case where plane origin is shifted with center call
r = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin")
.center(30, 0)
.hole(90)
)
origin = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (30.0, 0.0, 10.0), decimal_places)
origin = (
r.faces(">Z")
.workplane(centerOption="ProjectedOrigin", origin=(0, 0, 0))
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places)
# make sure projection works in all directions
r = Workplane("YZ").polyline(pts).close().extrude(10.0)
origin = (
r.faces(">X")
.workplane(centerOption="ProjectedOrigin")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (10.0, 0.0, 0.0), decimal_places)
origin = (
r.faces(">X").workplane(centerOption="CenterOfMass").plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (10.0, 37.5, 22.5), decimal_places)
origin = (
r.faces(">X")
.workplane(centerOption="CenterOfBoundBox")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (10.0, 45.0, 30.0), decimal_places)
r = Workplane("XZ").polyline(pts).close().extrude(10.0)
origin = (
r.faces("<Y")
.workplane(centerOption="ProjectedOrigin")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (0.0, -10.0, 0.0), decimal_places)
origin = (
r.faces("<Y").workplane(centerOption="CenterOfMass").plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (37.5, -10.0, 22.5), decimal_places)
origin = (
r.faces("<Y")
.workplane(centerOption="CenterOfBoundBox")
.plane.origin.toTuple()
)
self.assertTupleAlmostEquals(origin, (45.0, -10.0, 30.0), decimal_places)
def testFindSolid(self):
r = Workplane("XY").pushPoints([(-2, 0), (2, 0)]).box(1, 1, 1, combine=False)
# there should be two solids on the stack
self.assertEqual(len(r.objects), 2)
self.assertTrue(isinstance(r.val(), Solid))
# find solid should return a compound of two solids
s = r.findSolid()
self.assertEqual(len(s.Solids()), 2)
self.assertTrue(isinstance(s, Compound))
# if no solids are found, should raise ValueError
w = Workplane().hLine(1).close()
with raises(ValueError):
w.findSolid()
def testSlot2D(self):
decimal_places = 9
# Ensure it produces a solid with the correct volume
result = Workplane("XY").slot2D(4, 1, 0).extrude(1)
self.assertAlmostEqual(result.val().Volume(), 3.785398163, decimal_places)
# Test for proper expected behaviour when cutting
box = Workplane("XY").box(5, 5, 1)
result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutThruAll()
self.assertAlmostEqual(result.val().Volume(), 21.214601837, decimal_places)
result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutBlind(-0.5)
self.assertAlmostEqual(result.val().Volume(), 23.107300918, decimal_places)
# Test to see if slot is rotated correctly
result = Workplane("XY").slot2D(4, 1, 45).extrude(1)
point = result.faces(">Z").edges(">X").first().val().startPoint().toTuple()
self.assertTupleAlmostEquals(
point, (0.707106781, 1.414213562, 1.0), decimal_places
)
def test_assembleEdges(self):
# Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides
# Passes an open wire to assembleEdges so that IsDone is true but Error returns 2 to test the warning functionality.
edge_points = [
[-7.0, -7.0, 0.0],
[-3.0, -10.0, 3.0],
[7.0, -7.0, 0.0],
[7.0, 7.0, 0.0],
[-7.0, 7.0, 0.0],
]
edge_wire = Workplane("XY").polyline(
[(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)]
)
edge_wire = edge_wire.add(
Workplane("YZ")
.workplane()
.transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0))
.spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)])
)
edge_wire = [o.vals()[0] for o in edge_wire.all()]
edge_wire = Wire.assembleEdges(edge_wire)
# Embossed star, need to change optional parameters to obtain nice looking result.
r1 = 3.0
r2 = 10.0
fn = 6
edge_points = [
[r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn)]
if i % 2 == 0
else [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn)]
for i in range(2 * fn + 1)
]
edge_wire = Workplane("XY").polyline(edge_points)
edge_wire = [o.vals()[0] for o in edge_wire.all()]
edge_wire = Wire.assembleEdges(edge_wire)
# Points on hexagonal pattern coordinates, use of pushpoints.
r1 = 1.0
fn = 6
edge_points = [
[r1 * math.cos(i * 2 * math.pi / fn), r1 * math.sin(i * 2 * math.pi / fn)]
for i in range(fn + 1)
]
surface_points = [
[0.25, 0, 0.75],
[-0.25, 0, 0.75],
[0, 0.25, 0.75],
[0, -0.25, 0.75],
[0, 0, 2],
]
edge_wire = Workplane("XY").polyline(edge_points)
edge_wire = [o.vals()[0] for o in edge_wire.all()]
edge_wire = Wire.assembleEdges(edge_wire)
# Gyroïd, all edges are splines on different workplanes.
edge_points = [
[[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
]
plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"]
offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54]
edge_wire = (
Workplane(plane_list[0])
.workplane(offset=-offset_list[0])
.spline(edge_points[0])
)
for i in range(len(edge_points) - 1):
edge_wire = edge_wire.add(
Workplane(plane_list[i + 1])
.workplane(offset=-offset_list[i + 1])
.spline(edge_points[i + 1])
)
edge_wire = [o.vals()[0] for o in edge_wire.all()]
edge_wire = Wire.assembleEdges(edge_wire)
def testTag(self):
# test tagging
result = (
Workplane("XY")
.pushPoints([(-2, 0), (2, 0)])
.box(1, 1, 1, combine=False)
.tag("2 solids")
.union(Workplane("XY").box(6, 1, 1))
)
self.assertEqual(len(result.objects), 1)
result = result._getTagged("2 solids")
self.assertEqual(len(result.objects), 2)
with self.assertRaises(ValueError):
result = result._getTagged("3 solids")
def testCopyWorkplane(self):
obj0 = Workplane("XY").box(1, 1, 10).faces(">Z").workplane()
obj1 = Workplane("XY").copyWorkplane(obj0).box(1, 1, 1)
self.assertTupleAlmostEquals((0, 0, 5), obj1.val().Center().toTuple(), 9)
def testWorkplaneFromTagged(self):
# create a flat, wide base. Extrude one object 4 units high, another
# object on top of it 6 units high. Go back to base plane. Extrude an
# object 11 units high. Assert that top face is 11 units high.
result = (
Workplane("XY")
.box(10, 10, 1, centered=(True, True, False))
.faces(">Z")
.workplane()
.tag("base")
.center(3, 0)
.rect(2, 2)
.extrude(4)
.faces(">Z")
.workplane()
.circle(1)
.extrude(6)
.workplaneFromTagged("base")
.center(-3, 0)
.circle(1)
.extrude(11)
)
self.assertTupleAlmostEquals(
result.faces(">Z").val().Center().toTuple(), (-3, 0, 12), 9
)
def testWorkplaneOrientationOnVertex(self):
# create a 10 unit sized cube on the XY plane
parent = Workplane("XY").rect(10.0, 10.0).extrude(10)
# assert that the direction tuples reflect accordingly
assert parent.plane.xDir.toTuple() == approx((1.0, 0.0, 0.0))
assert parent.plane.zDir.toTuple() == approx((0.0, 0.0, 1.0))
# select the <XZ vertex on the <Y face and create a new workplane.
child = parent.faces("<Y").vertices("<XZ").workplane()
# assert that the direction tuples reflect the new workplane on the <Y face
assert child.plane.xDir.toTuple() == approx((1.0, 0.0, -0.0))
assert child.plane.zDir.toTuple() == approx((0.0, -1.0, -0.0))
def testTagSelectors(self):
result0 = Workplane("XY").box(1, 1, 1).tag("box").sphere(1)
# result is currently a sphere
self.assertEqual(1, result0.faces().size())
# a box has 8 vertices
self.assertEqual(8, result0.vertices(tag="box").size())
# 6 faces
self.assertEqual(6, result0.faces(tag="box").size())
# 12 edges
self.assertEqual(12, result0.edges(tag="box").size())
# 6 wires
self.assertEqual(6, result0.wires(tag="box").size())
# create two solids, tag them, join to one solid
result1 = (
Workplane("XY")
.pushPoints([(1, 0), (-1, 0)])
.box(1, 1, 1)
.tag("boxes")
.sphere(1)
)
self.assertEqual(1, result1.solids().size())
self.assertEqual(2, result1.solids(tag="boxes").size())
self.assertEqual(1, result1.shells().size())
self.assertEqual(2, result1.shells(tag="boxes").size())
# create 4 individual objects, tag it, then combine to one compound
result2 = (
Workplane("XY")
.rect(4, 4)
.vertices()
.box(1, 1, 1, combine=False)
.tag("4 objs")
)
result2 = result2.newObject([Compound.makeCompound(result2.objects)])
self.assertEqual(1, result2.compounds().size())
self.assertEqual(0, result2.compounds(tag="4 objs").size())
def test_interpPlate(self):
"""
Tests the interpPlate() functionalities
Numerical values of Areas and Volumes were obtained with the Area() and Volume() functions on a Linux machine under Debian 10 with python 3.7.
"""
# example from PythonOCC core_geometry_geomplate.py, use of thickness = 0 returns 2D surface.
thickness = 0
edge_points = [
(0.0, 0.0, 0.0),
(0.0, 10.0, 0.0),
(0.0, 10.0, 10.0),
(0.0, 0.0, 10.0),
]
surface_points = [(5.0, 5.0, 5.0)]
plate_0 = Workplane("XY").interpPlate(edge_points, surface_points, thickness)
self.assertTrue(plate_0.val().isValid())
self.assertAlmostEqual(plate_0.val().Area(), 141.218823892, 1)
# Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides
thickness = 0.1
edge_points = [
(-7.0, -7.0, 0.0),
(-3.0, -10.0, 3.0),
(7.0, -7.0, 0.0),
(7.0, 7.0, 0.0),
(-7.0, 7.0, 0.0),
]
edge_wire = Workplane("XY").polyline(
[(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)]
)
# edge_wire = edge_wire.add(Workplane('YZ').workplane().transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)).polyline([(-7.,0.), (3,-3), (7.,0.)]))
# In CadQuery Sept-2019 it worked with rotate=Vector(0, 45, 0). In CadQuery Dec-2019 rotate=Vector(45, 0, 0) only closes the wire.
edge_wire = edge_wire.add(
Workplane("YZ")
.workplane()
.transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0))
.spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)])
)
surface_points = [(-3.0, -3.0, -3.0), (3.0, 3.0, 3.0)]
plate_1 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness)
self.assertTrue(plate_1.val().isValid())
self.assertAlmostEqual(plate_1.val().Volume(), 26.124970206, 2)
# Embossed star, need to change optional parameters to obtain nice looking result.
r1 = 3.0
r2 = 10.0
fn = 6
thickness = 0.1
edge_points = [
(r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn))
if i % 2 == 0
else (r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn))
for i in range(2 * fn + 1)
]
edge_wire = Workplane("XY").polyline(edge_points)
r2 = 4.5
surface_points = [
(r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn), 1.0)
for i in range(2 * fn)
] + [(0.0, 0.0, -2.0)]
plate_2 = Workplane("XY").interpPlate(
edge_wire,
surface_points,
thickness,
combine=True,
clean=True,
degree=3,
nbPtsOnCur=15,
nbIter=2,
anisotropy=False,
tol2d=0.00001,
tol3d=0.0001,
tolAng=0.01,
tolCurv=0.1,
maxDeg=8,
maxSegments=49,
)
self.assertTrue(plate_2.val().isValid())
self.assertAlmostEqual(plate_2.val().Volume(), 10.956054314, 0)
# Points on hexagonal pattern coordinates, use of pushpoints.
r1 = 1.0
N = 3
ca = math.cos(30.0 * math.pi / 180.0)
sa = math.sin(30.0 * math.pi / 180.0)
# EVEN ROWS
pts = [
(-3.0, -3.0),
(-1.267949, -3.0),
(0.464102, -3.0),
(2.196152, -3.0),
(-3.0, 0.0),
(-1.267949, 0.0),
(0.464102, 0.0),
(2.196152, 0.0),
(-2.133974, -1.5),
(-0.401923, -1.5),
(1.330127, -1.5),
(3.062178, -1.5),
(-2.133975, 1.5),
(-0.401924, 1.5),
(1.330127, 1.5),
(3.062178, 1.5),
]
# Spike surface
thickness = 0.1
fn = 6
edge_points = [
(
r1 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180),
r1 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180),
)
for i in range(fn + 1)
]
surface_points = [
(
r1 / 4 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180),
r1 / 4 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180),
0.75,
)
for i in range(fn + 1)
] + [(0, 0, 2)]
edge_wire = Workplane("XY").polyline(edge_points)
plate_3 = (
Workplane("XY")
.pushPoints(pts)
.interpPlate(
edge_wire,
surface_points,
thickness,
combine=False,
clean=False,
degree=2,
nbPtsOnCur=20,
nbIter=2,
anisotropy=False,
tol2d=0.00001,
tol3d=0.0001,
tolAng=0.01,
tolCurv=0.1,
maxDeg=8,
maxSegments=9,
)
)
self.assertTrue(plate_3.val().isValid())
self.assertAlmostEqual(plate_3.val().Volume(), 0.45893954685189414, 1)
# Gyroïd, all edges are splines on different workplanes.
thickness = 0.1
edge_points = [
[[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
]
plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"]
offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54]
edge_wire = (
Workplane(plane_list[0])
.workplane(offset=-offset_list[0])
.spline(edge_points[0])
)
for i in range(len(edge_points) - 1):
edge_wire = edge_wire.add(
Workplane(plane_list[i + 1])
.workplane(offset=-offset_list[i + 1])
.spline(edge_points[i + 1])
)
surface_points = [(0, 0, 0)]
plate_4 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness)
self.assertTrue(plate_4.val().isValid())
self.assertAlmostEqual(plate_4.val().Volume(), 7.760559490, 2)
plate_5 = Workplane().interpPlate(Workplane().slot2D(2, 1).vals())
assert plate_5.val().isValid()
plate_6 = Solid.interpPlate(
[(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [], thickness=1
)
assert plate_6.isValid()
self.assertAlmostEqual(plate_6.Volume(), 1, 2)
def testTangentArcToPoint(self):
# create a simple shape with tangents of straight edges and see if it has the correct area
s0 = (
Workplane("XY")
.hLine(1)
.tangentArcPoint((1, 1), relative=False)
.hLineTo(0)
.tangentArcPoint((0, 0), relative=False)
.close()
.extrude(1)
)
area0 = s0.faces(">Z").val().Area()
self.assertAlmostEqual(area0, (1 + math.pi * 0.5 ** 2), 4)
# test relative coords
s1 = (
Workplane("XY")
.hLine(1)
.tangentArcPoint((0, 1), relative=True)
.hLineTo(0)
.tangentArcPoint((0, -1), relative=True)
.close()
.extrude(1)
)
self.assertTupleAlmostEquals(
s1.val().Center().toTuple(), s0.val().Center().toTuple(), 4
)
self.assertAlmostEqual(s1.val().Volume(), s0.val().Volume(), 4)
# consecutive tangent arcs
s1 = (
Workplane("XY")
.vLine(2)
.tangentArcPoint((1, 0))
.tangentArcPoint((1, 0))
.tangentArcPoint((1, 0))
.vLine(-2)
.close()
.extrude(1)
)
self.assertAlmostEqual(
s1.faces(">Z").val().Area(), 2 * 3 + 0.5 * math.pi * 0.5 ** 2, 4
)
# tangentArc on the end of a spline
# spline will be a simple arc of a circle, then finished off with a
# tangentArcPoint
angles = [idx * 1.5 * math.pi / 10 for idx in range(10)]
pts = [(math.sin(a), math.cos(a)) for a in angles]
s2 = (
Workplane("XY")
.spline(pts)
.tangentArcPoint((0, 1), relative=False)
.close()
.extrude(1)
)
# volume should almost be pi, but not accurately because we need to
# start with a spline
self.assertAlmostEqual(s2.val().Volume(), math.pi, 1)
# assert local coords are mapped to global correctly
arc0 = Workplane("XZ", origin=(1, 1, 1)).hLine(1).tangentArcPoint((1, 1)).val()
self.assertTupleAlmostEquals(arc0.endPoint().toTuple(), (3, 1, 2), 4)
# tangentArcPoint with 3-tuple argument
w0 = Workplane("XY").lineTo(1, 1).tangentArcPoint((1, 1, 1)).wire()
zmax = w0.val().BoundingBox().zmax
self.assertAlmostEqual(zmax, 1, 1)
def test_findFromEdge(self):
part = Workplane("XY", origin=(1, 1, 1)).hLine(1)
found_edge = part._findFromEdge(useLocalCoords=False)
self.assertTupleAlmostEquals(found_edge.startPoint().toTuple(), (1, 1, 1), 3)
self.assertTupleAlmostEquals(found_edge.Center().toTuple(), (1.5, 1, 1), 3)
self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (2, 1, 1), 3)
found_edge = part._findFromEdge(useLocalCoords=True)
self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (1, 0, 0), 3)
# check _findFromEdge can find a spline
pts = [(0, 0), (0, 1), (1, 2), (2, 4)]
spline0 = Workplane("XZ").spline(pts)._findFromEdge()
self.assertTupleAlmostEquals((2, 0, 4), spline0.endPoint().toTuple(), 3)
# check method fails if no edge is present
part2 = Workplane("XY").box(1, 1, 1)
with self.assertRaises(RuntimeError):
part2._findFromEdge()
with self.assertRaises(RuntimeError):
part2._findFromEdge(useLocalCoords=True)
def testMakeHelix(self):
h = 10
pitch = 1.5
r = 1.2
obj = Wire.makeHelix(pitch, h, r)
bb = obj.BoundingBox()
self.assertAlmostEqual(bb.zlen, h, 1)
def testUnionCompound(self):
box1 = Workplane("XY").box(10, 20, 30)
box2 = Workplane("YZ").box(10, 20, 30)
shape_to_cut = Workplane("XY").box(15, 15, 15).translate((8, 8, 8))
list_of_shapes = []
for o in box1.all():
list_of_shapes.extend(o.vals())
for o in box2.all():
list_of_shapes.extend(o.vals())
obj = Workplane("XY").newObject(list_of_shapes).cut(shape_to_cut)
assert obj.val().isValid()
def testSection(self):
box = Workplane("XY", origin=(1, 2, 3)).box(1, 1, 1)
s1 = box.section()
s2 = box.section(0.5)
self.assertAlmostEqual(s1.faces().val().Area(), 1)
self.assertAlmostEqual(s2.faces().val().Area(), 1)
line = Workplane("XY").hLine(1)
with self.assertRaises(ValueError):
line.section()
def testGlue(self):
box1 = Workplane("XY").rect(1, 1).extrude(2)
box2 = Workplane("XY", origin=(0, 1, 0)).rect(1, 1).extrude(1)
res = box1.union(box2, glue=True)
self.assertEqual(res.faces().size(), 8)
obj = obj = (
Workplane("XY").rect(1, 1).extrude(2).moveTo(0, 2).rect(1, 1).extrude(2)
)
res = obj.union(box2, glue=True)
self.assertEqual(res.faces().size(), 10)
def testFuzzyBoolOp(self):
eps = 1e-3
# test fuse
box1 = Workplane("XY").box(1, 1, 1)
box2 = Workplane("XY", origin=(1 + eps, 0.0)).box(1, 1, 1)
box3 = Workplane("XY", origin=(2, 0, 0)).box(1, 1, 1)
res = box1.union(box2)
res_fuzzy = box1.union(box2, tol=eps)
res_fuzzy2 = box1.union(box3).union(box2, tol=eps)
self.assertEqual(res.solids().size(), 2)
self.assertEqual(res_fuzzy.solids().size(), 1)
self.assertEqual(res_fuzzy2.solids().size(), 1)
# test cut and intersect
box4 = Workplane("XY", origin=(eps, 0.0)).box(1, 1, 1)
res_fuzzy_cut = box1.cut(box4, tol=eps)
res_fuzzy_intersect = box1.intersect(box4, tol=eps)
self.assertAlmostEqual(res_fuzzy_cut.val().Volume(), 0)
self.assertAlmostEqual(res_fuzzy_intersect.val().Volume(), 1)
# test with compounds
box1_cmp = Compound.makeCompound(box1.vals())
box4_cmp = Compound.makeCompound(box4.vals())
res_fuzzy_cut_cmp = box1_cmp.cut(box4_cmp, tol=eps)
res_fuzzy_intersect_cmp = box1_cmp.intersect(box4_cmp, tol=eps)
self.assertAlmostEqual(res_fuzzy_cut_cmp.Volume(), 0)
self.assertAlmostEqual(res_fuzzy_intersect_cmp.Volume(), 1)
# test with solids
res_fuzzy_cut_val = box1.val().cut(box4.val(), tol=eps)
res_fuzzy_intersect_val = box1.val().intersect(box4.val(), tol=eps)
self.assertAlmostEqual(res_fuzzy_cut_val.Volume(), 0)
self.assertAlmostEqual(res_fuzzy_intersect_val.Volume(), 1)
def testLocatedMoved(self):
box = Solid.makeBox(1, 1, 1, Vector(-0.5, -0.5, -0.5))
loc = Location(Vector(1, 1, 1))
box1 = box.located(loc)
self.assertTupleAlmostEquals(box1.Center().toTuple(), (1, 1, 1), 6)
self.assertTupleAlmostEquals(box.Center().toTuple(), (0, 0, 0), 6)
box.locate(loc)
self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6)
box2 = box.moved(loc)
self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6)
self.assertTupleAlmostEquals(box2.Center().toTuple(), (2, 2, 2), 6)
box.move(loc)
self.assertTupleAlmostEquals(box.Center().toTuple(), (2, 2, 2), 6)
def testNullShape(self):
from OCP.TopoDS import TopoDS_Shape
s = TopoDS_Shape()
# make sure raises on non solid
with self.assertRaises(ValueError):
r = occ_impl.shapes.downcast(s)
def testCenterOfBoundBox(self):
obj = Workplane().pushPoints([(0, 0), (2, 2)]).box(1, 1, 1)
c = obj.workplane(centerOption="CenterOfBoundBox").plane.origin
self.assertTupleAlmostEquals(c.toTuple(), (1, 1, 0), 6)
def testOffset2D(self):
w1 = Workplane().rect(1, 1).offset2D(0.5, "arc")
self.assertEqual(w1.edges().size(), 8)
w2 = Workplane().rect(1, 1).offset2D(0.5, "tangent")
self.assertEqual(w2.edges().size(), 4)
w3 = Workplane().rect(1, 1).offset2D(0.5, "intersection")
self.assertEqual(w3.edges().size(), 4)
w4 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.5)
self.assertEqual(w4.wires().size(), 0)
w5 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.25)
self.assertEqual(w5.wires().size(), 2)
r = 20
s = 7
t = 1.5
points = [
(0, t / 2),
(r / 2 - 1.5 * t, r / 2 - t),
(s / 2, r / 2 - t),
(s / 2, r / 2),
(r / 2, r / 2),
(r / 2, s / 2),
(r / 2 - t, s / 2),
(r / 2 - t, r / 2 - 1.5 * t),
(t / 2, 0),
]
s = (
Workplane("XY")
.polyline(points)
.mirrorX()
.mirrorY()
.offset2D(-0.9)
.extrude(1)
)
self.assertEqual(s.solids().size(), 4)
# test forConstruction
# forConstruction=True should place results in objects, not ctx.pendingWires
w6 = Workplane().hLine(1).vLine(1).close().offset2D(0.5, forConstruction=True)
self.assertEqual(len(w6.ctx.pendingWires), 0)
self.assertEqual(w6.size(), 1)
self.assertEqual(type(w6.val()), Wire)
# make sure the resulting wire has forConstruction set
self.assertEqual(w6.val().forConstruction, True)
def testConsolidateWires(self):
w1 = Workplane().lineTo(0, 1).lineTo(1, 1).consolidateWires()
self.assertEqual(w1.size(), 1)
w1 = Workplane().consolidateWires()
self.assertEqual(w1.size(), 0)
def testLocationAt(self):
r = 1
e = Wire.makeHelix(r, r, r).Edges()[0]
locs_frenet = e.locations([0, 1], frame="frenet")
T1 = locs_frenet[0].wrapped.Transformation()
T2 = locs_frenet[1].wrapped.Transformation()
self.assertAlmostEqual(T1.TranslationPart().X(), r, 6)
self.assertAlmostEqual(T2.TranslationPart().X(), r, 6)
self.assertAlmostEqual(
T1.GetRotation().GetRotationAngle(), -T2.GetRotation().GetRotationAngle(), 6
)
ga = e._geomAdaptor()
locs_corrected = e.locations(
[ga.FirstParameter(), ga.LastParameter()],
mode="parameter",
frame="corrected",
)
T3 = locs_corrected[0].wrapped.Transformation()
T4 = locs_corrected[1].wrapped.Transformation()
self.assertAlmostEqual(T3.TranslationPart().X(), r, 6)
self.assertAlmostEqual(T4.TranslationPart().X(), r, 6)
w = Wire.assembleEdges(
[
Edge.makeLine(Vector(), Vector(0, 1)),
Edge.makeLine(Vector(0, 1), Vector(1, 1)),
]
)
locs_wire = e.locations([0, 1])
T5 = locs_wire[0].wrapped.Transformation()
T6 = locs_wire[1].wrapped.Transformation()
self.assertAlmostEqual(T5.TranslationPart().X(), r, 0)
self.assertAlmostEqual(T6.TranslationPart().X(), r, 1)
def testNormal(self):
circ = Workplane().circle(1).edges().val()
n = circ.normal()
self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6)
ell = Workplane().ellipse(1, 2).edges().val()
n = ell.normal()
self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6)
r = Workplane().rect(1, 2).wires().val()
n = r.normal()
self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6)
with self.assertRaises(ValueError):
edge = Workplane().rect(1, 2).edges().val()
n = edge.normal()
def testPositionAt(self):
# test with an open wire
w = Workplane().lineTo(0, 1).lineTo(1, 1).wire().val()
p0 = w.positionAt(0.0)
p1 = w.positionAt(0.5)
p2 = w.positionAt(1.0)
self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6)
self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6)
self.assertTupleAlmostEquals(p2.toTuple(), (1, 1, 0), 6)
p0 = w.positionAt(0.0, mode="param")
self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6)
p0, p1, p2 = w.positions([0.0, 0.25, 0.5])
self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6)
self.assertTupleAlmostEquals(p1.toTuple(), (0, 0.5, 0), 6)
self.assertTupleAlmostEquals(p2.toTuple(), (0, 1, 0), 6)
# test with a closed wire
w = Workplane().lineTo(0, 1).close().wire().val()
p0 = w.positionAt(0.0)
p1 = w.positionAt(0.5)
p2 = w.positionAt(1.0)
self.assertTupleAlmostEquals(p0.toTuple(), p2.toTuple(), 6)
self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6)
# test with arc of circle
e = Edge.makeCircle(1, (0, 0, 0), (0, 0, 1), 90, 180)
p0 = e.positionAt(0.0)
p1 = e.positionAt(1.0)
assert p0.toTuple() == approx((0.0, 1.0, 0.0))
assert p1.toTuple() == approx((-1.0, 0.0, 0.0))
w = Wire.assembleEdges([e])
p0 = w.positionAt(0.0)
p1 = w.positionAt(1.0)
assert p0.toTuple() == approx((0.0, 1.0, 0.0))
assert p1.toTuple() == approx((-1.0, 0.0, 0.0))
def testTangengAt(self):
pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)]
path = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val()
self.assertTrue(
path.tangentAt(0.0, mode="parameter") == path.tangentAt(0.0, mode="length")
)
self.assertFalse(
path.tangentAt(0.5, mode="parameter") == path.tangentAt(0.5, mode="length")
)
arc = Workplane().radiusArc((2, 0), 1).val()
self.assertTupleAlmostEquals(
arc.tangentAt(math.pi / 2, "parameter").toTuple(), (1, 0, 0), 6
)
self.assertTupleAlmostEquals(
arc.tangentAt(0.5, "length").toTuple(), (1, 0, 0), 6
)
def testEnd(self):
with self.assertRaises(ValueError):
Workplane().end()
self.assertTrue(Workplane().objects == [])
self.assertTrue(Workplane().box(1, 1, 1).end().objects == [])
self.assertTrue(Workplane().box(1, 1, 1).box(2, 2, 1).end(2).objects == [])
def testCutEach(self):
# base shape:
w = Workplane().box(3, 2, 2)
# cutter:
c = Workplane().box(2, 2, 2).val()
# cut all the corners off
w0 = w.vertices().cutEach(lambda loc: c.located(loc))
# we are left with a 1x2x2 box:
self.assertAlmostEqual(w0.val().Volume(), 4, 3)
# test error on no solid found
w1 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
w1.cutEach(lambda loc: c.located(loc))
def testCutBlind(self):
# cutBlind is already tested in several of the complicated tests, so this method is short.
# test ValueError on no solid found
w0 = Workplane().hLine(1).vLine(1).close()
with raises(ValueError):
w0.cutBlind(1)
def testFindFace(self):
# if there are no faces to find, should raise ValueError
w0 = Workplane()
with raises(ValueError):
w0.findFace()
w1 = Workplane().box(1, 1, 1).faces(">Z")
self.assertTrue(isinstance(w1.findFace(), Face))
with raises(ValueError):
w1.findFace(searchStack=False)
w2 = w1.workplane().circle(0.1).extrude(0.1)
self.assertTrue(isinstance(w2.findFace(searchParents=True), Face))
with raises(ValueError):
w2.findFace(searchParents=False)
def testPopPending(self):
# test pending edges
w0 = Workplane().hLine(1)
self.assertEqual(len(w0.ctx.pendingEdges), 1)
edges = w0.ctx.popPendingEdges()
self.assertEqual(len(edges), 1)
self.assertEqual(edges[0], w0.val())
# pending edges should now be cleared
self.assertEqual(len(w0.ctx.pendingEdges), 0)
# test pending wires
w1 = Workplane().hLine(1).vLine(1).close()
wire = w1.val()
self.assertEqual(w1.ctx.pendingWires[0], wire)
pop_pending_output = w1.ctx.popPendingWires()
self.assertEqual(pop_pending_output[0], wire)
# pending wires should now be cleared
self.assertEqual(len(w1.ctx.pendingWires), 0)
# test error when empty pending edges
w2 = Workplane()
# the following 2 should not raise an exception
w2.ctx.popPendingEdges(errorOnEmpty=False)
w2.ctx.popPendingWires(errorOnEmpty=False)
# empty edges
w3 = Workplane().hLine(1).vLine(1).close()
with self.assertRaises(ValueError):
w3.ctx.popPendingEdges()
# empty wires
w4 = Workplane().circle(1).extrude(1)
with self.assertRaises(ValueError):
w4.ctx.popPendingWires()
# test via cutBlind
w5 = Workplane().circle(1).extrude(1)
with self.assertRaises(ValueError):
w5.cutBlind(-1)
def testCompSolid(self):
from OCP.BRepPrimAPI import BRepPrimAPI_MakePrism
tool = Solid.makeSphere(1, angleDegrees3=120)
shell = tool.Shells()[0]
v = Vector(0, 0, 1)
builder = BRepPrimAPI_MakePrism(shell.wrapped, v.wrapped)
result = Shape.cast(builder.Shape())
self.assertEqual(len(result.CompSolids()), 1)
self.assertEqual(len(result.Solids()), 4)
def test2Dfillet(self):
r = Workplane().rect(1, 2).wires().val()
f = Face.makeFromWires(r)
verts = r.Vertices()
self.assertEqual(len(f.fillet2D(0.5, verts).Vertices()), 6)
self.assertEqual(len(r.fillet2D(0.5, verts).Vertices()), 6)
self.assertEqual(len(r.fillet2D(0.25, verts).Vertices()), 8)
# Test fillet2D with open wire and single vertex
w0 = Workplane().hLine(1).vLine(1).wire()
w0_verts = w0.vertices(">X and <Y").vals()
unfilleted_wire0 = w0.val()
filleted_wire0 = unfilleted_wire0.fillet2D(0.5, w0_verts)
self.assertEqual(len(filleted_wire0.Vertices()), 4)
# the filleted wire is shorter than the original
self.assertGreater(unfilleted_wire0.Length() - filleted_wire0.Length(), 0.1)
def test2Dchamfer(self):
r = Workplane().rect(1, 2).wires().val()
f = Face.makeFromWires(r)
verts = r.Vertices()
self.assertEqual(len(f.chamfer2D(0.5, verts).Vertices()), 6)
self.assertEqual(len(r.chamfer2D(0.5, verts).Vertices()), 6)
self.assertEqual(len(r.chamfer2D(0.25, verts).Vertices()), 8)
r = Workplane().hLine(1).vLine(1).wire().val()
vs = r.Vertices()
self.assertEqual(len(r.chamfer2D(0.25, [vs[1]]).Vertices()), 4)
with raises(ValueError):
r.chamfer2D(0.25, [vs[0]])
def test_Face_makeFromWires(self):
w0 = Wire.assembleEdges(
[
Edge.makeLine(Vector(), Vector(0, 1)),
Edge.makeLine(Vector(0, 1), Vector(1, 1)),
Edge.makeLine(Vector(1, 1), Vector(1, 0)),
Edge.makeLine(Vector(1, 0), Vector(0, 0)),
]
)
w1 = Wire.assembleEdges(
[
Edge.makeLine(Vector(0.25, 0.25), Vector(0.25, 0.75)),
Edge.makeLine(Vector(0.25, 0.75), Vector(0.75, 0.75)),
Edge.makeLine(Vector(0.75, 0.75), Vector(0.75, 0.25)),
Edge.makeLine(Vector(0.75, 0.25), Vector(0.25, 0.25)),
]
)
f = Face.makeFromWires(w0, [w1])
assert f.isValid()
with raises(ValueError):
w0 = Wire.assembleEdges([Edge.makeLine(Vector(), Vector(0, 1)),])
w1 = Wire.assembleEdges([Edge.makeLine(Vector(0, 1), Vector(1, 1)),])
f = Face.makeFromWires(w0, [w1])
with raises(ValueError):
w0 = Wire.assembleEdges([Edge.makeLine(Vector(), Vector(0, 1)),])
w1 = Wire.assembleEdges(
[
Edge.makeLine(Vector(), Vector(1, 1)),
Edge.makeLine(Vector(1, 1), Vector(2, 0)),
Edge.makeLine(Vector(2, 0), Vector(0, 0)),
]
)
f = Face.makeFromWires(w0, [w1])
with raises(ValueError):
w0 = Wire.assembleEdges(
[
Edge.makeLine(Vector(), Vector(1, 1)),
Edge.makeLine(Vector(1, 1), Vector(2, 0)),
Edge.makeLine(Vector(2, 0), Vector(0, 0)),
]
)
w1 = Wire.assembleEdges(
[Edge.makeLine(Vector(0.1, 0.1), Vector(0.2, 0.2)),]
)
f = Face.makeFromWires(w0, [w1])
def testSplineApprox(self):
from .naca import naca5305
from math import pi, cos
pts = [Vector(e[0], e[1], 0) for e in naca5305]
# spline
e1 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=6, smoothing=(1, 1, 1))
e2 = Edge.makeSplineApprox(pts, 1e-6, minDeg=2, maxDeg=6)
self.assertTrue(e1.isValid())
self.assertTrue(e2.isValid())
self.assertTrue(e1.Length() > e2.Length())
with raises(ValueError):
e4 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=3, smoothing=(1, 1, 1.0))
pts_closed = pts + [pts[0]]
e3 = Edge.makeSplineApprox(pts_closed)
w = Edge.makeSplineApprox(pts).close()
self.assertTrue(e3.IsClosed())
self.assertTrue(w.IsClosed())
# Workplane method
w1 = Workplane().splineApprox(pts)
w2 = Workplane().splineApprox(pts, forConstruction=True)
w3 = Workplane().splineApprox(pts, makeWire=True)
w4 = Workplane().splineApprox(pts, makeWire=True, forConstruction=True)
self.assertEqual(w1.edges().size(), 1)
self.assertEqual(len(w1.ctx.pendingEdges), 1)
self.assertEqual(w2.edges().size(), 1)
self.assertEqual(len(w2.ctx.pendingEdges), 0)
self.assertEqual(w3.wires().size(), 1)
self.assertEqual(len(w3.ctx.pendingWires), 1)
self.assertEqual(w4.wires().size(), 1)
self.assertEqual(len(w4.ctx.pendingWires), 0)
# spline surface
N = 40
T = 20
A = 5
pts = [
[
Vector(i, j, A * cos(2 * pi * i / T) * cos(2 * pi * j / T))
for i in range(N + 1)
]
for j in range(N + 1)
]
f1 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=6)
f2 = Face.makeSplineApprox(pts)
self.assertTrue(f1.isValid())
self.assertTrue(f2.isValid())
with raises(ValueError):
f3 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=3)
def testParametricSurface(self):
from math import pi, cos
r1 = Workplane().parametricSurface(
lambda u, v: (u, v, cos(pi * u) * cos(pi * v)), start=-1, stop=1
)
self.assertTrue(r1.faces().val().isValid())
r2 = Workplane().box(1, 1, 3).split(r1)
self.assertTrue(r2.solids().val().isValid())
self.assertEqual(r2.solids().size(), 2)
def testEdgeWireClose(self):
# test with edge
e0 = Edge.makeThreePointArc(Vector(0, 0, 0), Vector(1, 1, 0), Vector(0, 2, 0))
self.assertFalse(e0.IsClosed())
w0 = e0.close()
self.assertTrue(w0.IsClosed())
# test with already closed edge
e1 = Edge.makeCircle(1)
self.assertTrue(e1.IsClosed())
e2 = e1.close()
self.assertTrue(e2.IsClosed())
self.assertEqual(type(e1), type(e2))
# test with already closed WIRE
w1 = Wire.makeCircle(1, Vector(), Vector(0, 0, 1))
self.assertTrue(w1.IsClosed())
w2 = w1.close()
self.assertTrue(w1 is w2)
def test_close_3D_points(self):
r = Workplane().polyline([(0, 0, 10), (5, 0, 12), (0, 5, 10),]).close()
assert r.wire().val().Closed()
def testSplitShape(self):
"""
Testing the Shape.split method.
"""
# split an edge with a vertex
e0 = Edge.makeCircle(1, (0, 0, 0), (0, 0, 1))
v0 = Vertex.makeVertex(0, 1, 0)
list_of_edges = e0.split(v0).Edges()
self.assertEqual(len(list_of_edges), 2)
self.assertTrue(Vector(0, 1, 0) in [e.endPoint() for e in list_of_edges])
# split a circle with multiple vertices
angles = [2 * math.pi * idx / 10 for idx in range(10)]
vecs = [Vector(math.sin(a), math.cos(a), 0) for a in angles]
vertices = [Vertex.makeVertex(*v.toTuple()) for v in vecs]
edges = e0.split(*vertices).Edges()
self.assertEqual(len(edges), len(vertices) + 1)
endpoints = [e.endPoint() for e in edges]
self.assertTrue(all([v in endpoints for v in vecs]))
def testBrepImportExport(self):
# import/export to file
s = Workplane().box(1, 1, 1).val()
s.exportBrep("test.brep")
si = Shape.importBrep("test.brep")
self.assertTrue(si.isValid())
self.assertAlmostEqual(si.Volume(), 1)
# import/export to BytesIO
from io import BytesIO
bio = BytesIO()
s.exportBrep(bio)
bio.seek(0)
si = Shape.importBrep("test.brep")
self.assertTrue(si.isValid())
self.assertAlmostEqual(si.Volume(), 1)
def testFaceToPln(self):
origin = (1, 2, 3)
normal = (1, 1, 1)
f0 = Face.makePlane(length=None, width=None, basePnt=origin, dir=normal)
p0 = f0.toPln()
self.assertTrue(Vector(p0.Location()) == Vector(origin))
self.assertTrue(Vector(p0.Axis().Direction()) == Vector(normal).normalized())
origin1 = (0, 0, -3)
normal1 = (-1, 1, -1)
f1 = Face.makePlane(length=0.1, width=100, basePnt=origin1, dir=normal1)
p1 = f1.toPln()
self.assertTrue(Vector(p1.Location()) == Vector(origin1))
self.assertTrue(Vector(p1.Axis().Direction()) == Vector(normal1).normalized())
f2 = Workplane().box(1, 1, 10, centered=False).faces(">Z").val()
p2 = f2.toPln()
self.assertTrue(p2.Contains(f2.Center().toPnt(), 0.1))
self.assertTrue(Vector(p2.Axis().Direction()) == f2.normalAt())
def testEachpoint(self):
r1 = (
Workplane(origin=(0, 0, 1))
.add(
[
Vector(),
Location(Vector(0, 0, -1,)),
Sketch().rect(1, 1),
Face.makePlane(1, 1),
]
)
.eachpoint(lambda l: Face.makePlane(1, 1).locate(l))
)
self.assertTrue(len(r1.objects) == 4)
for v in r1.vals():
self.assertTupleAlmostEquals(v.Center().toTuple(), (0, 0, 0), 6)
# test eachpoint with combine = True
box = Workplane().box(2, 1, 1).val()
ref = Workplane().box(5, 5, 5)
r = ref.vertices().eachpoint(lambda loc: box.moved(loc), combine=True)
self.assertGreater(r.val().Volume(), ref.val().Volume())
# test eachpoint with combine = "cut"
r = ref.vertices().eachpoint(lambda loc: box.moved(loc), combine="cut")
self.assertGreater(ref.val().Volume(), r.val().Volume())
def testSketch(self):
r1 = (
Workplane()
.box(10, 10, 1)
.faces(">Z")
.sketch()
.slot(2, 1)
.slot(2, 1, angle=90)
.clean()
.finalize()
.extrude(1)
)
self.assertTrue(r1.val().isValid())
self.assertEqual(len(r1.faces().vals()), 19)
r2 = (
Workplane()
.sketch()
.circle(2)
.wires()
.offset(0.1, mode="s")
.finalize()
.sketch()
.rect(1, 1)
.finalize()
.extrude(1, taper=5)
)
self.assertTrue(r2.val().isValid())
self.assertEqual(len(r2.faces().vals()), 6)
r3 = (
Workplane()
.pushPoints((Location(Vector(1, 1, 0)),))
.sketch()
.circle(2)
.wires()
.offset(-0.1, mode="s")
.finalize()
.extrude(1)
)
self.assertTrue(r3.val().isValid())
self.assertEqual(len(r3.faces().vals()), 4)
self.assertTupleAlmostEquals(r3.val().Center().toTuple(), (1, 1, 0.5), 6)
s = Sketch().trapezoid(3, 1, 120)
r4 = Workplane().placeSketch(s, s.moved(Location(Vector(0, 0, 3)))).loft()
self.assertEqual(len(r4.solids().vals()), 1)
r5 = (
Workplane().sketch().polygon([(0, 0), (0, 1), (1, 0)]).finalize().extrude(1)
)
assert r5.val().Volume() == approx(0.5)
def testCircumscribedPolygon(self):
"""
Test that circumscribed polygons result in the correct shapes
"""
def circumradius(n, a):
return a / math.cos(math.pi / n)
a = 1
# Test triangle
vs = Workplane("XY").polygon(3, 2 * a, circumscribed=True).vertices().vals()
self.assertEqual(3, len(vs))
R = circumradius(3, a)
self.assertEqual(
vs[0].toTuple(), approx((a, a * math.tan(math.radians(60)), 0))
)
self.assertEqual(vs[1].toTuple(), approx((-R, 0, 0)))
self.assertEqual(
vs[2].toTuple(), approx((a, -a * math.tan(math.radians(60)), 0))
)
# Test square
vs = Workplane("XY").polygon(4, 2 * a, circumscribed=True).vertices().vals()
self.assertEqual(4, len(vs))
R = circumradius(4, a)
self.assertEqual(
vs[0].toTuple(), approx((a, a * math.tan(math.radians(45)), 0))
)
self.assertEqual(
vs[1].toTuple(), approx((-a, a * math.tan(math.radians(45)), 0))
)
self.assertEqual(
vs[2].toTuple(), approx((-a, -a * math.tan(math.radians(45)), 0))
)
self.assertEqual(
vs[3].toTuple(), approx((a, -a * math.tan(math.radians(45)), 0))
)
def test_combineWithBase(self):
# Test the helper mehod _combinewith
box = Workplane().box(10, 10, 10)
sphere = box.faces(">Z").sphere(2)
new_box = box._combineWithBase(sphere.val())
self.assertGreater(new_box.val().Volume(), box.val().Volume())
def test_cutFromBase(self):
# Test the helper method _cutFromBase
box = Workplane().box(10, 10, 10)
sphere = Workplane().sphere(2)
hoolow_box = box._cutFromBase(sphere.val())
self.assertGreater(box.val().Volume(), hoolow_box.val().Volume())
def test_MergeTags(self):
a = Workplane().box(1, 1, 1)
b = (
Workplane(origin=(1, 0, 0))
.box(1, 1, 1)
.vertices(">X and >Y and >Z")
.tag("box_vertex")
.end(2)
)
a = a.add(b)
assert a.vertices(tag="box_vertex").val().Center().toTuple() == approx(
(1.5, 0.5, 0.5)
)
a = Workplane().box(4, 4, 4)
b = Workplane(origin=(0, 0, 1)).box(2, 2, 2).faces("<Z").tag("box2_face").end()
a = a.cut(b)
assert a.val().Volume() == approx(4 ** 3 - 2 ** 3)
a = a.faces(tag="box2_face").wires().toPending().extrude(4)
assert a.val().Volume() == approx(4 ** 3 + 2 ** 3)
a = Workplane().sphere(2)
b = Workplane().cylinder(4, 1).tag("cyl")
a = a.intersect(b)
assert len(a.solids(tag="cyl").val().Solids()) == 1
a = Workplane().box(4, 4, 4)
b = (
Workplane()
.box(2, 5, 5, centered=(False, True, True))
.faces(">X")
.workplane()
.tag("splitter")
.end(2)
)
a = a.split(b)
a = a.solids("<X")
assert a.val().Volume() == approx((4 ** 3) / 2.0)
a = a.workplaneFromTagged("splitter").rect(4, 4).extrude(until="next")
assert a.val().Volume() == approx((4 ** 3))
a = Workplane().box(4, 4, 4)
b = Workplane(origin=(0, 0, 3)).box(2, 2, 2).faces(">Z").tag("box2_face").end()
a = a.union(b)
a = a.faces(tag="box2_face").workplane(offset=0.5).box(1, 1, 1)
assert a.val().Volume() == approx(4 ** 3 + 2 ** 3 + 1)
# tag name conflict; keep tag from left side of boolean
a = Workplane().box(1, 1, 1).faces(">Z").workplane().tag("zface").end(2)
b = (
Workplane(origin=(1, 0, 0))
.box(1, 1, 2)
.faces(">Z")
.workplane()
.tag("zface")
.end(2)
)
a = a.union(b)
a = a.workplaneFromTagged("zface").circle(0.2)
assert a.edges("%CIRCLE").val().Center().toTuple() == approx((0, 0, 0.5))
def test_plane_repr(self):
wp = Workplane("XY")
assert (
repr(wp.plane)
== "Plane(origin=(0.0, 0.0, 0.0), xDir=(1.0, 0.0, 0.0), normal=(0.0, 0.0, 1.0))"
)
def test_distance(self):
w1 = Face.makePlane(2, 2).Wires()[0]
w2 = Face.makePlane(1, 1).Wires()[0]
w3 = Face.makePlane(3, 3).Wires()[0]
d12 = w1.distance(w2)
assert d12 == approx(0.5)
d12, d13 = w1.distances(w2, w3)
assert d12 == approx(0.5)
assert d13 == approx(0.5)
def test_project(self):
# project a single letter
t = Compound.makeText("T", 5, 0).Faces()[0]
f = Workplane("XZ", origin=(0, 0, -7)).sphere(6).faces("not %PLANE").val()
res = t.project(f, (0, 0, 1))
assert res.isValid()
assert len(res.Edges()) == len(t.Edges())
assert t.distance(res) == approx(1)
# extrude it
res_ex = Solid.extrudeLinear(t.project(f, (0, 0, -1)), (0.0, 0.0, 0.5))
assert res_ex.isValid()
assert len(res_ex.Faces()) == 10
# project a wire
w = t.outerWire()
res_w = w.project(f, (0, 0, 1))
assert len(res_w.Edges()) == 8
assert res_w.isValid()
res_w1, res_w2 = w.project(f, (0, 0, 1), False)
assert len(res_w1.Edges()) == 8
assert len(res_w2.Edges()) == 8
# project a single letter with openings
o = Compound.makeText("O", 5, 0).Faces()[0]
f = Workplane("XZ", origin=(0, 0, -7)).sphere(6).faces("not %PLANE").val()
res_o = o.project(f, (0, 0, 1))
assert res_o.isValid()
# extrude it
res_o_ex = Solid.extrudeLinear(o.project(f, (0, 0, -1)), (0.0, 0.0, 0.5))
assert res_o_ex.isValid()
def test_makeNSidedSurface(self):
# inner edge/wire constraint
outer_w = Workplane().slot2D(2, 1).wires().vals()
inner_e1 = (
Workplane(origin=(0, 0, 1)).moveTo(-0.5, 0).lineTo(0.5, 0.0).edges().vals()
)
inner_e2 = (
Workplane(origin=(0, 0, 1)).moveTo(0, -0.2).lineTo(0, 0.2).edges().vals()
)
inner_w = Workplane(origin=(0, 0, 1)).ellipse(0.5, 0.2).vals()
f1 = Face.makeNSidedSurface(outer_w, inner_e1 + inner_e2 + inner_w)
assert f1.isValid()
assert len(f1.Edges()) == 4
# inner points
f2 = Face.makeNSidedSurface(
outer_w, [Vector(-0.4, 0, 1).toPnt(), Vector(0.4, 0, 1)]
)
assert f2.isValid()
assert len(f2.Edges()) == 4
# exception on invalid constraint
with raises(ValueError):
Face.makeNSidedSurface(outer_w, [[0, 0, 1]])
def test_toVtk(self):
from vtkmodules.vtkCommonDataModel import vtkPolyData
f = Face.makePlane(2, 2)
vtk = f.toVtkPolyData(normals=False)
assert isinstance(vtk, vtkPolyData)
assert vtk.GetNumberOfPolys() == 2
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,485 | CadQuery/cadquery | refs/heads/master | /tests/test_cqgi.py | """
Tests CQGI functionality
Currently, this includes:
Parsing a script, and detecting its available variables
Altering the values at runtime
defining a build_object function to return results
"""
from cadquery import cqgi
from tests import BaseTest
import textwrap
TESTSCRIPT = textwrap.dedent(
"""
height=2.0
width=3.0
(a,b) = (1.0,1.0)
foo="bar"
result = "%s|%s|%s|%s" % ( str(height) , str(width) , foo , str(a) )
show_object(result)
"""
)
TEST_DEBUG_SCRIPT = textwrap.dedent(
"""
height=2.0
width=3.0
(a,b) = (1.0,1.0)
foo="bar"
debug(foo, { "color": 'yellow' } )
result = "%s|%s|%s|%s" % ( str(height) , str(width) , foo , str(a) )
show_object(result)
debug(height )
"""
)
class TestCQGI(BaseTest):
def test_parser(self):
model = cqgi.CQModel(TESTSCRIPT)
metadata = model.metadata
self.assertEqual(
set(metadata.parameters.keys()), {"height", "width", "a", "b", "foo"}
)
def test_build_with_debug(self):
model = cqgi.CQModel(TEST_DEBUG_SCRIPT)
result = model.build()
debugItems = result.debugObjects
self.assertTrue(len(debugItems) == 2)
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)
result = model.build()
self.assertTrue(result.success)
self.assertTrue(len(result.results) == 1)
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].shape == "3.0|3.0|bar|1.0")
def test_describe_parameters(self):
script = textwrap.dedent(
"""
a = 2.0
describe_parameter(a,'FirstLetter')
"""
)
model = cqgi.CQModel(script)
a_param = model.metadata.parameters["a"]
self.assertTrue(a_param.default_value == 2.0)
self.assertTrue(a_param.desc == "FirstLetter")
self.assertTrue(a_param.varType == cqgi.NumberParameterType)
def test_describe_parameter_invalid_doesnt_fail_script(self):
script = textwrap.dedent(
"""
a = 2.0
describe_parameter(a, 2 - 1 )
"""
)
model = cqgi.CQModel(script)
a_param = model.metadata.parameters["a"]
self.assertTrue(a_param.name == "a")
def test_build_with_exception(self):
badscript = textwrap.dedent(
"""
raise ValueError("ERROR")
"""
)
model = cqgi.CQModel(badscript)
result = model.build({})
self.assertFalse(result.success)
self.assertIsNotNone(result.exception)
self.assertTrue(result.exception.args[0] == "ERROR")
def test_that_invalid_syntax_in_script_fails_immediately(self):
badscript = textwrap.dedent(
"""
this doesn't even compile
"""
)
exception = None
try:
cqgi.CQModel(badscript)
except Exception as e:
exception = e
self.assertIsInstance(exception, SyntaxError)
def test_that_two_results_are_returned(self):
script = textwrap.dedent(
"""
h = 1
show_object(h)
h = 2
show_object(h)
"""
)
model = cqgi.CQModel(script)
result = model.build({})
self.assertEqual(2, len(result.results))
self.assertEqual(1, result.results[0].shape)
self.assertEqual(2, result.results[1].shape)
def test_that_assinging_number_to_string_works(self):
script = textwrap.dedent(
"""
h = "this is a string"
show_object(h)
"""
)
result = cqgi.parse(script).build({"h": 33.33})
self.assertEqual(result.results[0].shape, "33.33")
def test_that_assigning_string_to_number_fails(self):
script = textwrap.dedent(
"""
h = 20.0
show_object(h)
"""
)
result = cqgi.parse(script).build({"h": "a string"})
self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError))
def test_that_assigning_unknown_var_fails(self):
script = textwrap.dedent(
"""
h = 20.0
show_object(h)
"""
)
result = cqgi.parse(script).build({"w": "var is not there"})
self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError))
def test_that_cq_objects_are_visible(self):
script = textwrap.dedent(
"""
r = cadquery.Workplane('XY').box(1,2,3)
show_object(r)
"""
)
result = cqgi.parse(script).build()
self.assertTrue(result.success)
self.assertIsNotNone(result.first_result)
def test_that_options_can_be_passed(self):
script = textwrap.dedent(
"""
r = cadquery.Workplane('XY').box(1,2,3)
show_object(r, options={"rgba":(128, 255, 128, 0.0)})
"""
)
result = cqgi.parse(script).build()
self.assertTrue(result.success)
self.assertIsNotNone(result.first_result.options)
def test_setting_boolean_variable(self):
script = textwrap.dedent(
"""
h = True
show_object( "*%s*" % str(h) )
"""
)
result = cqgi.parse(script).build({"h": False})
self.assertTrue(result.success)
self.assertEqual(result.first_result.shape, "*False*")
def test_that_only_top_level_vars_are_detected(self):
script = textwrap.dedent(
"""
h = 1.0
w = 2.0
def do_stuff():
x = 1
y = 2
show_object( "result" )
"""
)
model = cqgi.parse(script)
self.assertEqual(2, len(model.metadata.parameters))
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,486 | CadQuery/cadquery | refs/heads/master | /tests/test_utils.py | from cadquery.utils import cqmultimethod as multimethod
from pytest import raises
def test_multimethod():
class A:
@multimethod
def f(self, a: int, c: str = "s"):
return 1
@f.register
def f(self, a: int, b: int, c: str = "b"):
return 2
assert A().f(0, "s") == 1
assert A().f(0, c="s") == 1
assert A().f(0) == 1
assert A().f(0, 1, c="s") == 2
assert A().f(0, 1, "s") == 2
assert A().f(0, 1) == 2
assert A().f(a=0, c="s") == 1
with raises(TypeError):
A().f(a=0, b=1, c="s")
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,487 | CadQuery/cadquery | refs/heads/master | /examples/Ex001_Simple_Block.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
length = 80.0 # Length of the block
height = 60.0 # Height of the block
thickness = 10.0 # Thickness of the block
# Create a 3D block based on the dimension variables above.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
result = cq.Workplane("XY").box(length, height, thickness)
# The following method is now outdated, but can still be used to display the
# results of the script if you want
# from Helpers import show
# show(result) # Render the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,488 | CadQuery/cadquery | refs/heads/master | /doc/gen_colors.py | """
A script to generate RST (HTML only) for displaying all the colours supported
by OCP. Used in the file assy.rst.
"""
from OCP import Quantity
import cadquery as cq
from typing import Dict
from itertools import chain
OCP_COLOR_LEADER, SEP = "Quantity_NOC", "_"
TEMPLATE = """\
<div style="background-color:rgba({background_color});padding:10px;border-radius:5px;color:rgba({text_color});">{color_name}</div>\
"""
def color_to_rgba_str(c: cq.Color) -> str:
""" Convert a Color object to a string for the HTML/CSS template.
"""
t = c.toTuple()
vals = [int(v * 255) for v in t[:3]]
return ",".join([str(v) for v in chain(vals, [t[3]])])
def calc_text_color(c: cq.Color) -> str:
""" Calculate required overlay text color from background color.
"""
val = sum(c.toTuple()[:3]) / 3
if val < 0.5:
rv = "255,255,255"
else:
rv = "0,0,0"
return rv
def get_colors() -> Dict[str, cq.Color]:
""" Scan OCP for colors and output to a dict.
"""
colors = {}
for name in dir(Quantity):
splitted = name.rsplit(SEP, 1)
if splitted[0] == OCP_COLOR_LEADER:
colors.update({splitted[1].lower(): cq.Color(splitted[1])})
return colors
def rst():
""" Produce the text for a Sphinx directive.
"""
lines = [
".. raw:: html",
"",
' <div class="color-grid" style="display:grid;grid-gap:10px;grid-template-columns:repeat(auto-fill, minmax(200px,1fr));">',
]
colors = get_colors()
for name, c in colors.items():
lines += [
TEMPLATE.format(
background_color=color_to_rgba_str(c),
text_color=calc_text_color(c),
color_name=name,
)
]
lines.append(" </div>")
return "\n".join(lines)
if __name__ == "__main__":
print(rst())
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,489 | CadQuery/cadquery | refs/heads/master | /tests/test_hull.py | import pytest
import cadquery as cq
from cadquery import hull
def test_hull():
c1 = cq.Edge.makeCircle(0.5, (-1.5, 0.5, 0))
c2 = cq.Edge.makeCircle(0.5, (1.9, 0.0, 0))
c3 = cq.Edge.makeCircle(0.2, (0.3, 1.5, 0))
c4 = cq.Edge.makeCircle(0.2, (1.0, 1.5, 0))
c5 = cq.Edge.makeCircle(0.1, (0.0, 0.0, 0.0))
e1 = cq.Edge.makeLine(cq.Vector(0, -0.5), cq.Vector(-0.5, 1.5))
e2 = cq.Edge.makeLine(cq.Vector(2.1, 1.5), cq.Vector(2.6, 1.5))
edges = [c1, c2, c3, c4, c5, e1, e2]
h = hull.find_hull(edges)
assert len(h.Vertices()) == 11
assert h.IsClosed()
assert h.isValid()
def test_validation():
with pytest.raises(ValueError):
e1 = cq.Edge.makeEllipse(2, 1)
c1 = cq.Edge.makeCircle(0.5, (-1.5, 0.5, 0))
hull.find_hull([c1, e1])
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,490 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/__init__.py | import tempfile
import os
import io as StringIO
from typing import IO, Optional, Union, cast, Dict, Any
from typing_extensions import Literal
from OCP.VrmlAPI import VrmlAPI
from ...cq import Workplane
from ...utils import deprecate
from ..shapes import Shape
from .svg import getSVG
from .json import JsonMesh
from .amf import AmfWriter
from .threemf import ThreeMFWriter
from .dxf import exportDXF, DxfDocument
from .vtk import exportVTP
from .utils import toCompound
class ExportTypes:
STL = "STL"
STEP = "STEP"
AMF = "AMF"
SVG = "SVG"
TJS = "TJS"
DXF = "DXF"
VRML = "VRML"
VTP = "VTP"
THREEMF = "3MF"
ExportLiterals = Literal[
"STL", "STEP", "AMF", "SVG", "TJS", "DXF", "VRML", "VTP", "3MF"
]
def export(
w: Union[Shape, Workplane],
fname: str,
exportType: Optional[ExportLiterals] = None,
tolerance: float = 0.1,
angularTolerance: float = 0.1,
opt: Optional[Dict[str, Any]] = None,
):
"""
Export Workplane or Shape to file. Multiple entities are converted to compound.
:param w: Shape or Workplane to be exported.
:param fname: output filename.
:param exportType: the exportFormat to use. If None will be inferred from the extension. Default: None.
:param tolerance: the deflection tolerance, in model units. Default 0.1.
:param angularTolerance: the angular tolerance, in radians. Default 0.1.
:param opt: additional options passed to the specific exporter. Default None.
"""
shape: Shape
f: IO
if not opt:
opt = {}
if isinstance(w, Workplane):
shape = toCompound(w)
else:
shape = w
if exportType is None:
t = fname.split(".")[-1].upper()
if t in ExportTypes.__dict__.values():
exportType = cast(ExportLiterals, t)
else:
raise ValueError("Unknown extensions, specify export type explicitly")
if exportType == ExportTypes.TJS:
tess = shape.tessellate(tolerance, angularTolerance)
mesher = JsonMesh()
# add vertices
for v in tess[0]:
mesher.addVertex(v.x, v.y, v.z)
# add triangles
for ixs in tess[1]:
mesher.addTriangleFace(*ixs)
with open(fname, "w") as f:
f.write(mesher.toJson())
elif exportType == ExportTypes.SVG:
with open(fname, "w") as f:
f.write(getSVG(shape, opt))
elif exportType == ExportTypes.AMF:
tess = shape.tessellate(tolerance, angularTolerance)
aw = AmfWriter(tess)
with open(fname, "wb") as f:
aw.writeAmf(f)
elif exportType == ExportTypes.THREEMF:
tmfw = ThreeMFWriter(shape, tolerance, angularTolerance, **opt)
with open(fname, "wb") as f:
tmfw.write3mf(f)
elif exportType == ExportTypes.DXF:
if isinstance(w, Workplane):
exportDXF(w, fname, **opt)
else:
raise ValueError("Only Workplanes can be exported as DXF")
elif exportType == ExportTypes.STEP:
shape.exportStep(fname, **opt)
elif exportType == ExportTypes.STL:
if opt:
useascii = opt.get("ascii", False) or opt.get("ASCII", False)
else:
useascii = False
shape.exportStl(fname, tolerance, angularTolerance, useascii)
elif exportType == ExportTypes.VRML:
shape.mesh(tolerance, angularTolerance)
VrmlAPI.Write_s(shape.wrapped, fname)
elif exportType == ExportTypes.VTP:
exportVTP(shape, fname, tolerance, angularTolerance)
else:
raise ValueError("Unknown export type")
@deprecate()
def toString(shape, exportType, tolerance=0.1, angularTolerance=0.05):
s = StringIO.StringIO()
exportShape(shape, exportType, s, tolerance, angularTolerance)
return s.getvalue()
@deprecate()
def exportShape(
w: Union[Shape, Workplane],
exportType: ExportLiterals,
fileLike: IO,
tolerance: float = 0.1,
angularTolerance: float = 0.1,
):
"""
:param shape: the shape to export. it can be a shape object, or a cadquery object. If a cadquery
object, the first value is exported
:param exportType: the exportFormat to use
:param fileLike: a file like object to which the content will be written.
The object should be already open and ready to write. The caller is responsible
for closing the object
:param tolerance: the linear tolerance, in model units. Default 0.1.
:param angularTolerance: the angular tolerance, in radians. Default 0.1.
"""
def tessellate(shape, angularTolerance):
return shape.tessellate(tolerance, angularTolerance)
shape: Shape
if isinstance(w, Workplane):
shape = toCompound(w)
else:
shape = w
if exportType == ExportTypes.TJS:
tess = tessellate(shape, angularTolerance)
mesher = JsonMesh()
# add vertices
for v in tess[0]:
mesher.addVertex(v.x, v.y, v.z)
# add triangles
for t in tess[1]:
mesher.addTriangleFace(*t)
fileLike.write(mesher.toJson())
elif exportType == ExportTypes.SVG:
fileLike.write(getSVG(shape))
elif exportType == ExportTypes.AMF:
tess = tessellate(shape, angularTolerance)
aw = AmfWriter(tess)
aw.writeAmf(fileLike)
elif exportType == ExportTypes.THREEMF:
tmfw = ThreeMFWriter(shape, tolerance, angularTolerance)
tmfw.write3mf(fileLike)
else:
# all these types required writing to a file and then
# re-reading. this is due to the fact that FreeCAD writes these
(h, outFileName) = tempfile.mkstemp()
# weird, but we need to close this file. the next step is going to write to
# it from c code, so it needs to be closed.
os.close(h)
if exportType == ExportTypes.STEP:
shape.exportStep(outFileName)
elif exportType == ExportTypes.STL:
shape.exportStl(outFileName, tolerance, angularTolerance, True)
else:
raise ValueError("No idea how i got here")
res = readAndDeleteFile(outFileName)
fileLike.write(res)
@deprecate()
def readAndDeleteFile(fileName):
"""
Read data from file provided, and delete it when done
return the contents as a string
"""
res = ""
with open(fileName, "r") as f:
res = "{}".format(f.read())
os.remove(fileName)
return res
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,491 | CadQuery/cadquery | refs/heads/master | /examples/Ex026_Case_Seam_Lip.py | import cadquery as cq
from cadquery.selectors import AreaNthSelector
case_bottom = (
cq.Workplane("XY")
.rect(20, 20)
.extrude(10) # solid 20x20x10 box
.edges("|Z or <Z")
.fillet(2) # rounding all edges except 4 edges of the top face
.faces(">Z")
.shell(2) # shell of thickness 2 with top face open
.faces(">Z")
.wires(AreaNthSelector(-1)) # selecting top outer wire
.toPending()
.workplane()
.offset2D(-1) # creating centerline wire of case seam face
.extrude(1) # covering the sell with temporary "lid"
.faces(">Z[-2]")
.wires(AreaNthSelector(0)) # selecting case crossection wire
.toPending()
.workplane()
.cutBlind(2) # cutting through the "lid" leaving a lip on case seam surface
)
# similar process repeated for the top part
# but instead of "growing" an inner lip
# material is removed inside case seam centerline
# to create an outer lip
case_top = (
cq.Workplane("XY")
.move(25)
.rect(20, 20)
.extrude(5)
.edges("|Z or >Z")
.fillet(2)
.faces("<Z")
.shell(2)
.faces("<Z")
.wires(AreaNthSelector(-1))
.toPending()
.workplane()
.offset2D(-1)
.cutBlind(-1)
)
show_object(case_bottom)
show_object(case_top, options={"alpha": 0.5})
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,492 | CadQuery/cadquery | refs/heads/master | /tests/__init__.py | from cadquery import *
from OCP.gp import gp_Vec
import unittest
import sys
import os
def readFileAsString(fileName):
f = open(fileName, "r")
s = f.read()
f.close()
return s
def writeStringToFile(strToWrite, fileName):
f = open(fileName, "w")
f.write(strToWrite)
f.close()
def makeUnitSquareWire():
V = Vector
return Wire.makePolygon(
[V(0, 0, 0), V(1, 0, 0), V(1, 1, 0), V(0, 1, 0), V(0, 0, 0)]
)
def makeUnitCube(centered=True):
return makeCube(1.0, centered)
def makeCube(size, xycentered=True):
if xycentered:
return Workplane().rect(size, size).extrude(size).val()
else:
return Solid.makeBox(size, size, size)
def toTuple(v):
"""convert a vector or a vertex to a 3-tuple: x,y,z"""
if type(v) == gp_Vec:
return (v.X(), v.Y(), v.Z())
elif type(v) == Vector:
return v.toTuple()
else:
raise RuntimeError("dont know how to convert type %s to tuple" % str(type(v)))
class BaseTest(unittest.TestCase):
def assertTupleAlmostEquals(self, expected, actual, places, msg=None):
for i, j in zip(actual, expected):
self.assertAlmostEqual(i, j, places, msg=msg)
__all__ = [
"TestCadObjects",
"TestCadQuery",
"TestCQGI",
"TestCQSelectors",
"TestCQSelectors",
"TestExporters",
"TestImporters",
"TestJupyter",
"TestWorkplanes",
]
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,493 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/jupyter_tools.py | from typing import Dict, Any, List
from json import dumps
from IPython.display import Javascript
from .exporters.vtk import toString
from .shapes import Shape
from ..assembly import Assembly
from .assembly import toJSON
DEFAULT_COLOR = [1, 0.8, 0, 1]
TEMPLATE_RENDER = """
function render(data, parent_element, ratio){{
// Initial setup
const renderWindow = vtk.Rendering.Core.vtkRenderWindow.newInstance();
const renderer = vtk.Rendering.Core.vtkRenderer.newInstance({{ background: [1, 1, 1 ] }});
renderWindow.addRenderer(renderer);
// iterate over all children children
for (var el of data){{
var trans = el.position;
var rot = el.orientation;
var rgba = el.color;
var shape = el.shape;
// load the inline data
var reader = vtk.IO.XML.vtkXMLPolyDataReader.newInstance();
const textEncoder = new TextEncoder();
reader.parseAsArrayBuffer(textEncoder.encode(shape));
// setup actor,mapper and add
const mapper = vtk.Rendering.Core.vtkMapper.newInstance();
mapper.setInputConnection(reader.getOutputPort());
mapper.setResolveCoincidentTopologyToPolygonOffset();
mapper.setResolveCoincidentTopologyPolygonOffsetParameters(0.9,20);
const actor = vtk.Rendering.Core.vtkActor.newInstance();
actor.setMapper(mapper);
// set color and position
actor.getProperty().setColor(rgba.slice(0,3));
actor.getProperty().setOpacity(rgba[3]);
actor.rotateZ(rot[2]*180/Math.PI);
actor.rotateY(rot[1]*180/Math.PI);
actor.rotateX(rot[0]*180/Math.PI);
actor.setPosition(trans);
renderer.addActor(actor);
}};
renderer.resetCamera();
const openglRenderWindow = vtk.Rendering.OpenGL.vtkRenderWindow.newInstance();
renderWindow.addView(openglRenderWindow);
// Add output to the "parent element"
var container;
var dims;
if(typeof(parent_element.appendChild) !== "undefined"){{
container = document.createElement("div");
parent_element.appendChild(container);
dims = parent_element.getBoundingClientRect();
}}else{{
container = parent_element.append("<div/>").children("div:last-child").get(0);
dims = parent_element.get(0).getBoundingClientRect();
}};
openglRenderWindow.setContainer(container);
// handle size
if (ratio){{
openglRenderWindow.setSize(dims.width, dims.width*ratio);
}}else{{
openglRenderWindow.setSize(dims.width, dims.height);
}};
// Interaction setup
const interact_style = vtk.Interaction.Style.vtkInteractorStyleManipulator.newInstance();
const manips = {{
rot: vtk.Interaction.Manipulators.vtkMouseCameraTrackballRotateManipulator.newInstance(),
pan: vtk.Interaction.Manipulators.vtkMouseCameraTrackballPanManipulator.newInstance(),
zoom1: vtk.Interaction.Manipulators.vtkMouseCameraTrackballZoomManipulator.newInstance(),
zoom2: vtk.Interaction.Manipulators.vtkMouseCameraTrackballZoomManipulator.newInstance(),
roll: vtk.Interaction.Manipulators.vtkMouseCameraTrackballRollManipulator.newInstance(),
}};
manips.zoom1.setControl(true);
manips.zoom2.setScrollEnabled(true);
manips.roll.setShift(true);
manips.pan.setButton(2);
for (var k in manips){{
interact_style.addMouseManipulator(manips[k]);
}};
const interactor = vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance();
interactor.setView(openglRenderWindow);
interactor.initialize();
interactor.bindEvents(container);
interactor.setInteractorStyle(interact_style);
// Orientation marker
const axes = vtk.Rendering.Core.vtkAnnotatedCubeActor.newInstance();
axes.setXPlusFaceProperty({{text: '+X'}});
axes.setXMinusFaceProperty({{text: '-X'}});
axes.setYPlusFaceProperty({{text: '+Y'}});
axes.setYMinusFaceProperty({{text: '-Y'}});
axes.setZPlusFaceProperty({{text: '+Z'}});
axes.setZMinusFaceProperty({{text: '-Z'}});
const orientationWidget = vtk.Interaction.Widgets.vtkOrientationMarkerWidget.newInstance({{
actor: axes,
interactor: interactor }});
orientationWidget.setEnabled(true);
orientationWidget.setViewportCorner(vtk.Interaction.Widgets.vtkOrientationMarkerWidget.Corners.BOTTOM_LEFT);
orientationWidget.setViewportSize(0.2);
}};
"""
TEMPLATE = (
TEMPLATE_RENDER
+ """
new Promise(
function(resolve, reject)
{{
if (typeof(require) !== "undefined" ){{
require.config({{
"paths": {{"vtk": "https://unpkg.com/vtk"}},
}});
require(["vtk"], resolve, reject);
}} else if ( typeof(vtk) === "undefined" ){{
var script = document.createElement("script");
script.onload = resolve;
script.onerror = reject;
script.src = "https://unpkg.com/vtk.js";
document.head.appendChild(script);
}} else {{ resolve() }};
}}
).then(() => {{
var parent_element = {element};
var data = {data};
render(data, parent_element, {ratio});
}});
"""
)
def display(shape):
payload: List[Dict[str, Any]] = []
if isinstance(shape, Shape):
payload.append(
dict(
shape=toString(shape),
color=DEFAULT_COLOR,
position=[0, 0, 0],
orientation=[0, 0, 0],
)
)
elif isinstance(shape, Assembly):
payload = toJSON(shape)
else:
raise ValueError(f"Type {type(shape)} is not supported")
code = TEMPLATE.format(data=dumps(payload), element="element", ratio=0.5)
return Javascript(code)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,494 | CadQuery/cadquery | refs/heads/master | /examples/Ex015_Rotated_Workplanes.py | import cadquery as cq
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects the top-most Z face of the box.
# 4. Creates a new workplane and then moves and rotates it with the
# transformed function.
# 5. Creates a for-construction rectangle that only exists to use for placing
# other geometry.
# 6. Selects the vertices of the for-construction rectangle.
# 7. Places holes at the center of each selected vertex.
# 7a. Since the workplane is rotated, this results in angled holes in the face.
result = (
cq.Workplane("front")
.box(4.0, 4.0, 0.25)
.faces(">Z")
.workplane()
.transformed(offset=(0, -1.5, 1.0), rotate=(60, 0, 0))
.rect(1.5, 1.5, forConstruction=True)
.vertices()
.hole(0.25)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,495 | CadQuery/cadquery | refs/heads/master | /examples/Ex003_Pillow_Block_With_Counterbored_Holes.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
length = 80.0 # Length of the block
width = 100.0 # Width of the block
thickness = 10.0 # Thickness of the block
center_hole_dia = 22.0 # Diameter of center hole in block
cbore_hole_diameter = 2.4 # Bolt shank/threads clearance hole diameter
cbore_inset = 12.0 # How far from the edge the cbored holes are set
cbore_diameter = 4.4 # Bolt head pocket hole diameter
cbore_depth = 2.1 # Bolt head pocket hole depth
# Create a 3D block based on the dimensions above and add a 22mm center hold
# and 4 counterbored holes for bolts
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
# 2. The highest(max) Z face is selected and a new workplane is created on it.
# 3. The new workplane is used to drill a hole through the block.
# 3a. The hole is automatically centered in the workplane.
# 4. The highest(max) Z face is selected and a new workplane is created on it.
# 5. A for-construction rectangle is created on the workplane based on the
# block's overall dimensions.
# 5a. For-construction objects are used only to place other geometry, they
# do not show up in the final displayed geometry.
# 6. The vertices of the rectangle (corners) are selected, and a counter-bored
# hole is placed at each of the vertices (all 4 of them at once).
result = (
cq.Workplane("XY")
.box(length, width, thickness)
.faces(">Z")
.workplane()
.hole(center_hole_dia)
.faces(">Z")
.workplane()
.rect(length - cbore_inset, width - cbore_inset, forConstruction=True)
.vertices()
.cboreHole(cbore_hole_diameter, cbore_diameter, cbore_depth)
.edges("|Z")
.fillet(2.0)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,496 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/importers/dxf.py | from collections import OrderedDict
from math import pi
from typing import List
from ... import cq
from ..geom import Vector
from ..shapes import Shape, Edge, Face, sortWiresByBuildOrder
import ezdxf
from OCP.ShapeAnalysis import ShapeAnalysis_FreeBounds
from OCP.TopTools import TopTools_HSequenceOfShape
from OCP.gp import gp_Pnt
from OCP.Geom import Geom_BSplineCurve
from OCP.TColgp import TColgp_Array1OfPnt
from OCP.TColStd import TColStd_Array1OfReal, TColStd_Array1OfInteger
from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeEdge
RAD2DEG = 360.0 / (2 * pi)
def _dxf_line(el):
try:
return (Edge.makeLine(Vector(el.dxf.start.xyz), Vector(el.dxf.end.xyz)),)
except Exception:
return ()
def _dxf_circle(el):
try:
return (Edge.makeCircle(el.dxf.radius, Vector(el.dxf.center.xyz)),)
except Exception:
return ()
def _dxf_arc(el):
try:
return (
Edge.makeCircle(
el.dxf.radius,
Vector(el.dxf.center.xyz),
angle1=el.dxf.start_angle,
angle2=el.dxf.end_angle,
),
)
except Exception:
return ()
def _dxf_polyline(el):
rv = (DXF_CONVERTERS[e.dxf.dxftype](e) for e in el.virtual_entities())
return (e[0] for e in rv if e)
def _dxf_spline(el):
try:
degree = el.dxf.degree
periodic = el.closed
rational = False
knots_unique = OrderedDict()
for k in el.knots:
if k in knots_unique:
knots_unique[k] += 1
else:
knots_unique[k] = 1
# assmble knots
knots = TColStd_Array1OfReal(1, len(knots_unique))
multiplicities = TColStd_Array1OfInteger(1, len(knots_unique))
for i, (k, m) in enumerate(knots_unique.items()):
knots.SetValue(i + 1, k)
multiplicities.SetValue(i + 1, m)
# assemble weights if present:
if el.weights:
rational = True
weights = TColStd_Array1OfReal(1, len(el.weights))
for i, w in enumerate(el.weights):
weights.SetValue(i + 1, w)
# assemble control points
pts = TColgp_Array1OfPnt(1, len(el.control_points))
for i, p in enumerate(el.control_points):
pts.SetValue(i + 1, gp_Pnt(*p))
if rational:
spline = Geom_BSplineCurve(
pts, weights, knots, multiplicities, degree, periodic
)
else:
spline = Geom_BSplineCurve(pts, knots, multiplicities, degree, periodic)
return (Edge(BRepBuilderAPI_MakeEdge(spline).Edge()),)
except Exception:
return ()
def _dxf_ellipse(el):
try:
return (
Edge.makeEllipse(
el.dxf.major_axis.magnitude,
el.minor_axis.magnitude,
pnt=Vector(el.dxf.center.xyz),
dir=el.dxf.extrusion.xyz,
xdir=Vector(el.dxf.major_axis.xyz),
angle1=el.dxf.start_param * RAD2DEG,
angle2=el.dxf.end_param * RAD2DEG,
),
)
except Exception:
return ()
DXF_CONVERTERS = {
"LINE": _dxf_line,
"CIRCLE": _dxf_circle,
"ARC": _dxf_arc,
"POLYLINE": _dxf_polyline,
"LWPOLYLINE": _dxf_polyline,
"SPLINE": _dxf_spline,
"ELLIPSE": _dxf_ellipse,
}
def _dxf_convert(elements, tol):
rv = []
edges = []
for el in elements:
conv = DXF_CONVERTERS.get(el.dxf.dxftype)
if conv:
edges.extend(conv(el))
if edges:
edges_in = TopTools_HSequenceOfShape()
wires_out = TopTools_HSequenceOfShape()
for e in edges:
edges_in.Append(e.wrapped)
ShapeAnalysis_FreeBounds.ConnectEdgesToWires_s(edges_in, tol, False, wires_out)
rv = [Shape.cast(el) for el in wires_out]
return rv
def _importDXF(
filename: str, tol: float = 1e-6, exclude: List[str] = [], include: List[str] = [],
) -> List[Face]:
"""
Loads a DXF file into a list of faces.
:param fileName: The path and name of the DXF file to be imported
:param tol: The tolerance used for merging edges into wires
:param exclude: a list of layer names not to import
:param include: a list of layer names to import
"""
if exclude and include:
raise ValueError("you may specify either 'include' or 'exclude' but not both")
dxf = ezdxf.readfile(filename)
faces = []
layers = dxf.modelspace().groupby(dxfattrib="layer")
# normalize layer names to conform the DXF spec
names = set([name.lower() for name in layers.keys()])
if include:
selected = names & set([name.lower() for name in include])
elif exclude:
selected = names - set([name.lower() for name in exclude])
else:
selected = names
if not selected:
raise ValueError("no DXF layers selected")
for name, layer in layers.items():
if name.lower() in selected:
res = _dxf_convert(layers[name], tol)
wire_sets = sortWiresByBuildOrder(res)
for wire_set in wire_sets:
faces.append(Face.makeFromWires(wire_set[0], wire_set[1:]))
return faces
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,497 | CadQuery/cadquery | refs/heads/master | /cadquery/units.py | from math import pi
RAD2DEG = 180 / pi
DEG2RAD = pi / 180
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,498 | CadQuery/cadquery | refs/heads/master | /examples/Ex009_Polylines.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
# Define up our Length, Height, Width, and thickness of the beam
(L, H, W, t) = (100.0, 20.0, 20.0, 1.0)
# Define the points that the polyline will be drawn to/thru
pts = [
(0, H / 2.0),
(W / 2.0, H / 2.0),
(W / 2.0, (H / 2.0 - t)),
(t / 2.0, (H / 2.0 - t)),
(t / 2.0, (t - H / 2.0)),
(W / 2.0, (t - H / 2.0)),
(W / 2.0, H / -2.0),
(0, H / -2.0),
]
# We generate half of the I-beam outline and then mirror it to create the full
# I-beam.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. moveTo() is used to move the first point from the origin (0, 0) to
# (0, 10.0), with 10.0 being half the height (H/2.0). If this is not done
# the first line will start from the origin, creating an extra segment that
# will cause the extrude to have an invalid shape.
# 3. The polyline function takes a list of points and generates the lines
# through all the points at once.
# 3. Only half of the I-beam profile has been drawn so far. That half is
# mirrored around the Y-axis to create the complete I-beam profile.
# 4. The I-beam profile is extruded to the final length of the beam.
result = cq.Workplane("front").polyline(pts).mirrorY().extrude(L)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,499 | CadQuery/cadquery | refs/heads/master | /setup.py | # Copyright 2015 Parametric Products Intellectual Holdings, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from setuptools import setup, find_packages
reqs = []
setup_reqs = []
# ReadTheDocs, AppVeyor and Azure builds will break when trying to instal pip deps in a conda env
is_rtd = "READTHEDOCS" in os.environ
is_appveyor = "APPVEYOR" in os.environ
is_azure = "CONDA_PY" in os.environ
is_conda = "CONDA_PREFIX_1" in os.environ
# Only include the installation dependencies if we are not running on RTD or AppVeyor or in a conda env
if not is_rtd and not is_appveyor and not is_azure and not is_conda:
reqs = [
"cadquery-ocp>=7.7.0a0,<7.8",
"ezdxf",
"multimethod>=1.7,<2.0",
"nlopt",
"nptyping==2.0.1",
"typish",
"casadi",
"path",
]
setup(
name="cadquery",
version="2.4.0dev", # Update this for the next release
url="https://github.com/CadQuery/cadquery",
license="Apache Public License 2.0",
author="David Cowden",
author_email="dave.cowden@gmail.com",
description="CadQuery is a parametric scripting language for creating and traversing CAD models",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
packages=find_packages(exclude=("tests",)),
python_requires=">=3.8",
setup_requires=setup_reqs,
install_requires=reqs,
extras_require={
"dev": ["docutils", "ipython", "pytest", "black==19.10b0", "click==8.0.4",],
"ipython": ["ipython",],
},
include_package_data=True,
zip_safe=False,
platforms="any",
test_suite="tests",
classifiers=[
"Development Status :: 5 - Production/Stable",
#'Development Status :: 6 - Mature',
#'Development Status :: 7 - Inactive',
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Information Technology",
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Operating System :: POSIX",
"Operating System :: MacOS",
"Operating System :: Unix",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Internet",
"Topic :: Scientific/Engineering",
],
)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,500 | CadQuery/cadquery | refs/heads/master | /cadquery/types.py | from typing import Union
Real = Union[int, float]
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,501 | CadQuery/cadquery | refs/heads/master | /examples/Ex007_Using_Point_Lists.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
plate_radius = 2.0 # The radius of the plate that will be extruded
hole_pattern_radius = 0.25 # Radius of circle where the holes will be placed
thickness = 0.125 # The thickness of the plate that will be extruded
# Make a plate with 4 holes in it at various points in a polar arrangement from
# the center of the workplane.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. A 2D circle is drawn that will become though outer profile of the plate.
r = cq.Workplane("front").circle(plate_radius)
# 3. Push 4 points on the stack that will be used as the center points of the
# holes.
r = r.pushPoints([(1.5, 0), (0, 1.5), (-1.5, 0), (0, -1.5)])
# 4. This circle() call will operate on all four points, putting a circle at
# each one.
r = r.circle(hole_pattern_radius)
# 5. All 2D geometry is extruded to the specified thickness of the plate.
# 5a. The small hole circles are enclosed in the outer circle of the plate and
# so it is assumed that we want them to be cut out of the plate. A
# separate cut operation is not needed.
result = r.extrude(thickness)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,502 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/dxf.py | """DXF export utilities."""
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
import ezdxf
from ezdxf import units, zoom
from ezdxf.entities import factory
from OCP.GeomConvert import GeomConvert
from OCP.gp import gp_Dir
from OCP.GC import GC_MakeArcOfEllipse
from typing_extensions import Self
from ...cq import Face, Plane, Workplane
from ...units import RAD2DEG
from ..shapes import Edge
from .utils import toCompound
ApproxOptions = Literal["spline", "arc"]
DxfEntityAttributes = Tuple[
Literal["ARC", "CIRCLE", "ELLIPSE", "LINE", "SPLINE",], Dict[str, Any]
]
class DxfDocument:
"""Create DXF document from CadQuery objects.
A wrapper for `ezdxf <https://ezdxf.readthedocs.io/>`_ providing methods for
converting :class:`cadquery.Workplane` objects to DXF entities.
The ezdxf document is available as the property ``document``, allowing most
features of ezdxf to be utilised directly.
.. rubric:: Example usage
.. code-block:: python
:caption: Single layer DXF document
rectangle = cq.Workplane().rect(10, 20)
dxf = DxfDocument()
dxf.add_shape(rectangle)
dxf.document.saveas("rectangle.dxf")
.. code-block:: python
:caption: Multilayer DXF document
rectangle = cq.Workplane().rect(10, 20)
circle = cq.Workplane().circle(3)
dxf = DxfDocument()
dxf = (
dxf.add_layer("layer_1", color=2)
.add_layer("layer_2", color=3)
.add_shape(rectangle, "layer_1")
.add_shape(circle, "layer_2")
)
dxf.document.saveas("rectangle-with-hole.dxf")
"""
CURVE_TOLERANCE = 1e-9
def __init__(
self,
dxfversion: str = "AC1027",
setup: Union[bool, List[str]] = False,
doc_units: int = units.MM,
*,
metadata: Union[Dict[str, str], None] = None,
approx: Optional[ApproxOptions] = None,
tolerance: float = 1e-3,
):
"""Initialize DXF document.
:param dxfversion: :attr:`DXF version specifier <ezdxf-stable:ezdxf.document.Drawing.dxfversion>`
as string, default is "AC1027" respectively "R2013"
:param setup: setup default styles, ``False`` for no setup, ``True`` to set up
everything or a list of topics as strings, e.g. ``["linetypes", "styles"]``
refer to :func:`ezdxf-stable:ezdxf.new`.
:param doc_units: ezdxf document/modelspace :doc:`units <ezdxf-stable:concepts/units>`
:param metadata: document :ref:`metadata <ezdxf-stable:ezdxf_metadata>` a dictionary of name value pairs
:param approx: Approximation strategy for converting :class:`cadquery.Workplane` objects to DXF entities:
``None``
no approximation applied
``"spline"``
all splines approximated as cubic splines
``"arc"``
all curves approximated as arcs and straight segments
:param tolerance: Approximation tolerance for converting :class:`cadquery.Workplane` objects to DXF entities.
"""
if metadata is None:
metadata = {}
self._DISPATCH_MAP = {
"LINE": self._dxf_line,
"CIRCLE": self._dxf_circle,
"ELLIPSE": self._dxf_ellipse,
}
self.approx = approx
self.tolerance = tolerance
self.document = ezdxf.new(dxfversion=dxfversion, setup=setup, units=doc_units) # type: ignore[attr-defined]
self.msp = self.document.modelspace()
doc_metadata = self.document.ezdxf_metadata()
for key, value in metadata.items():
doc_metadata[key] = value
def add_layer(
self, name: str, *, color: int = 7, linetype: str = "CONTINUOUS"
) -> Self:
"""Create a layer definition
Refer to :ref:`ezdxf layers <ezdxf-stable:layer_concept>` and
:doc:`ezdxf layer tutorial <ezdxf-stable:tutorials/layers>`.
:param name: layer definition name
:param color: color index. Standard colors include:
1 red, 2 yellow, 3 green, 4 cyan, 5 blue, 6 magenta, 7 white/black
:param linetype: ezdxf :doc:`line type <ezdxf-stable:concepts/linetypes>`
"""
self.document.layers.add(name, color=color, linetype=linetype)
return self
def add_shape(self, workplane: Workplane, layer: str = "") -> Self:
"""Add CadQuery shape to a DXF layer.
:param workplane: CadQuery Workplane
:param layer: layer definition name
"""
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
general_attributes = {}
if layer:
general_attributes["layer"] = layer
if self.approx == "spline":
edges = [
e.toSplines() if e.geomType() == "BSPLINE" else e for e in shape.Edges()
]
elif self.approx == "arc":
edges = []
# this is needed to handle free wires
for el in shape.Wires():
edges.extend(Face.makeFromWires(el).toArcs(self.tolerance).Edges())
else:
edges = shape.Edges()
for edge in edges:
converter = self._DISPATCH_MAP.get(edge.geomType(), None)
if converter:
entity_type, entity_attributes = converter(edge)
entity = factory.new(
entity_type, dxfattribs={**entity_attributes, **general_attributes}
)
self.msp.add_entity(entity) # type: ignore[arg-type]
else:
_, entity_attributes = self._dxf_spline(edge, plane)
entity = ezdxf.math.BSpline(**entity_attributes) # type: ignore[assignment]
self.msp.add_spline(
dxfattribs=general_attributes
).apply_construction_tool(entity)
zoom.extents(self.msp)
return self
@staticmethod
def _dxf_line(edge: Edge) -> DxfEntityAttributes:
"""Convert a Line to DXF entity attributes.
:param edge: CadQuery Edge to be converted to a DXF line
:return: dictionary of DXF entity attributes for creating a line
"""
return (
"LINE",
{"start": edge.startPoint().toTuple(), "end": edge.endPoint().toTuple(),},
)
@staticmethod
def _dxf_circle(edge: Edge) -> DxfEntityAttributes:
"""Convert a Circle to DXF entity attributes.
:param edge: CadQuery Edge to be converted to a DXF circle
:return: dictionary of DXF entity attributes for creating either a circle or arc
"""
geom = edge._geomAdaptor()
circ = geom.Circle()
radius = circ.Radius()
location = circ.Location()
direction_y = circ.YAxis().Direction()
direction_z = circ.Axis().Direction()
dy = gp_Dir(0, 1, 0)
phi = direction_y.AngleWithRef(dy, direction_z)
if direction_z.XYZ().Z() > 0:
a1 = RAD2DEG * (geom.FirstParameter() - phi)
a2 = RAD2DEG * (geom.LastParameter() - phi)
else:
a1 = -RAD2DEG * (geom.LastParameter() - phi) + 180
a2 = -RAD2DEG * (geom.FirstParameter() - phi) + 180
if edge.IsClosed():
return (
"CIRCLE",
{
"center": (location.X(), location.Y(), location.Z()),
"radius": radius,
},
)
else:
return (
"ARC",
{
"center": (location.X(), location.Y(), location.Z()),
"radius": radius,
"start_angle": a1,
"end_angle": a2,
},
)
@staticmethod
def _dxf_ellipse(edge: Edge) -> DxfEntityAttributes:
"""Convert an Ellipse to DXF entity attributes.
:param edge: CadQuery Edge to be converted to a DXF ellipse
:return: dictionary of DXF entity attributes for creating an ellipse
"""
geom = edge._geomAdaptor()
ellipse = geom.Ellipse()
r1 = ellipse.MinorRadius()
r2 = ellipse.MajorRadius()
c = ellipse.Location()
xdir = ellipse.XAxis().Direction()
xax = r2 * xdir.XYZ()
zdir = ellipse.Axis().Direction()
if zdir.Z() > 0:
start_param = geom.FirstParameter()
end_param = geom.LastParameter()
else:
gc = GC_MakeArcOfEllipse(
ellipse,
geom.FirstParameter(),
geom.LastParameter(),
False, # reverse Sense
).Value()
start_param = gc.FirstParameter()
end_param = gc.LastParameter()
return (
"ELLIPSE",
{
"center": (c.X(), c.Y(), c.Z()),
"major_axis": (xax.X(), xax.Y(), xax.Z()),
"ratio": r1 / r2,
"start_param": start_param,
"end_param": end_param,
},
)
@classmethod
def _dxf_spline(cls, edge: Edge, plane: Plane) -> DxfEntityAttributes:
"""Convert a Spline to ezdxf.math.BSpline parameters.
:param edge: CadQuery Edge to be converted to a DXF spline
:param plane: CadQuery Plane
:return: dictionary of ezdxf.math.BSpline parameters
"""
adaptor = edge._geomAdaptor()
curve = GeomConvert.CurveToBSplineCurve_s(adaptor.Curve().Curve())
spline = GeomConvert.SplitBSplineCurve_s(
curve,
adaptor.FirstParameter(),
adaptor.LastParameter(),
cls.CURVE_TOLERANCE,
)
# need to apply the transform on the geometry level
spline.Transform(adaptor.Trsf())
order = spline.Degree() + 1
knots = list(spline.KnotSequence())
poles = [(p.X(), p.Y(), p.Z()) for p in spline.Poles()]
weights = (
[spline.Weight(i) for i in range(1, spline.NbPoles() + 1)]
if spline.IsRational()
else None
)
if spline.IsPeriodic():
pad = spline.NbKnots() - spline.LastUKnotIndex()
poles += poles[:pad]
return (
"SPLINE",
{
"control_points": poles,
"order": order,
"knots": knots,
"weights": weights,
},
)
def exportDXF(
w: Workplane,
fname: str,
approx: Optional[ApproxOptions] = None,
tolerance: float = 1e-3,
*,
doc_units: int = units.MM,
) -> None:
"""
Export Workplane content to DXF. Works with 2D sections.
:param w: Workplane to be exported.
:param fname: Output filename.
:param approx: Approximation strategy. None means no approximation is applied.
"spline" results in all splines being approximated as cubic splines. "arc" results
in all curves being approximated as arcs and straight segments.
:param tolerance: Approximation tolerance.
:param doc_units: ezdxf document/modelspace :doc:`units <ezdxf-stable:concepts/units>` (in. = ``1``, mm = ``4``).
"""
dxf = DxfDocument(approx=approx, tolerance=tolerance, doc_units=doc_units)
dxf.add_shape(w)
dxf.document.saveas(fname)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,503 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/sketch_solver.py | from typing import Tuple, Union, Any, Callable, List, Optional, Iterable, Dict, Sequence
from typing_extensions import Literal
from nptyping import NDArray as Array
from nptyping import Float
from itertools import accumulate, chain
from math import sin, cos, radians
from numpy import array, full, inf, sign
from numpy.linalg import norm
import nlopt
from OCP.gp import gp_Vec2d
from .shapes import Geoms
from ..types import Real
NoneType = type(None)
SegmentDOF = Tuple[float, float, float, float] # p1 p2
ArcDOF = Tuple[float, float, float, float, float] # p r a da
DOF = Union[SegmentDOF, ArcDOF]
ConstraintKind = Literal[
"Fixed",
"FixedPoint",
"Coincident",
"Angle",
"Length",
"Distance",
"Radius",
"Orientation",
"ArcAngle",
]
ConstraintInvariants = { # (arity, geometry types, param type, conversion func)
"Fixed": (1, ("CIRCLE", "LINE"), NoneType, None),
"FixedPoint": (1, ("CIRCLE", "LINE"), Optional[Real], None),
"Coincident": (2, ("CIRCLE", "LINE"), NoneType, None),
"Angle": (2, ("CIRCLE", "LINE"), Real, radians),
"Length": (1, ("CIRCLE", "LINE"), Real, None),
"Distance": (
2,
("CIRCLE", "LINE"),
Tuple[Optional[Real], Optional[Real], Real],
None,
),
"Radius": (1, ("CIRCLE",), Real, None),
"Orientation": (1, ("LINE",), Tuple[Real, Real], None),
"ArcAngle": (1, ("CIRCLE",), Real, radians),
}
Constraint = Tuple[Tuple[int, Optional[int]], ConstraintKind, Optional[Any]]
DIFF_EPS = 1e-10
TOL = 1e-9
MAXITER = 0
def invalid_args(*t):
return ValueError("Invalid argument types {t}")
def arc_first(x):
return array((x[0] + x[2] * sin(x[3]), x[1] + x[2] * cos(x[3])))
def arc_last(x):
return array((x[0] + x[2] * sin(x[3] + x[4]), x[1] + x[2] * cos(x[3] + x[4])))
def arc_point(x, val):
if val is None:
rv = x[:2]
else:
a = x[3] + val * x[4]
rv = array((x[0] + x[2] * sin(a), x[1] + x[2] * cos(a)))
return rv
def line_point(x, val):
return x[:2] + val * (x[2:] - x[:2])
def arc_first_tangent(x):
return gp_Vec2d(sign(x[4]) * cos(x[3]), -sign(x[4]) * sin(x[3]))
def arc_last_tangent(x):
return gp_Vec2d(sign(x[4]) * cos(x[3] + x[4]), -sign(x[4]) * sin(x[3] + x[4]))
def fixed_cost(x, t, x0, val):
return norm(x - x0)
def fixed_point_cost(x, t, x0, val):
if t == "LINE":
rv = norm(line_point(x, val) - line_point(x0, val))
elif t == "CIRCLE":
rv = norm(arc_point(x, val) - arc_point(x0, val))
else:
raise invalid_args(t)
return rv
def coincident_cost(x1, t1, x10, x2, t2, x20, val):
if t1 == "LINE" and t2 == "LINE":
v1 = x1[2:]
v2 = x2[:2]
elif t1 == "LINE" and t2 == "CIRCLE":
v1 = x1[2:]
v2 = arc_first(x2)
elif t1 == "CIRCLE" and t2 == "LINE":
v1 = arc_last(x1)
v2 = x2[:2]
elif t1 == "CIRCLE" and t2 == "CIRCLE":
v1 = arc_last(x1)
v2 = arc_first(x2)
else:
raise invalid_args(t1, t2)
return norm(v1 - v2)
def angle_cost(x1, t1, x10, x2, t2, x20, val):
if t1 == "LINE" and t2 == "LINE":
v1 = gp_Vec2d(*(x1[2:] - x1[:2]))
v2 = gp_Vec2d(*(x2[2:] - x2[:2]))
elif t1 == "LINE" and t2 == "CIRCLE":
v1 = gp_Vec2d(*(x1[2:] - x1[:2]))
v2 = arc_first_tangent(x2)
elif t1 == "CIRCLE" and t2 == "LINE":
v1 = arc_last_tangent(x1)
v2 = gp_Vec2d(*(x2[2:] - x2[:2]))
elif t1 == "CIRCLE" and t2 == "CIRCLE":
v1 = arc_last_tangent(x1)
v2 = arc_first_tangent(x2)
else:
raise invalid_args(t1, t2)
return v2.Angle(v1) - val
def length_cost(x, t, x0, val):
rv = 0
if t == "LINE":
rv = norm(x[2:] - x[:2]) - val
elif t == "CIRCLE":
rv = norm(x[2] * x[4]) - val
else:
raise invalid_args(t)
return rv
def distance_cost(x1, t1, x10, x2, t2, x20, val):
val1, val2, d = val
if t1 == "LINE" and t2 == "LINE":
v1 = line_point(x1, val1)
v2 = line_point(x2, val2)
elif t1 == "LINE" and t2 == "CIRCLE":
v1 = line_point(x1, val1)
v2 = arc_point(x2, val2)
elif t1 == "CIRCLE" and t2 == "LINE":
v1 = arc_point(x1, val1)
v2 = line_point(x2, val2)
elif t1 == "CIRCLE" and t2 == "CIRCLE":
v1 = arc_point(x1, val1)
v2 = arc_point(x2, val2)
else:
raise invalid_args(t1, t2)
return norm(v1 - v2) - d
def radius_cost(x, t, x0, val):
if t == "CIRCLE":
rv = x[2] - val
else:
raise invalid_args(t)
return rv
def orientation_cost(x, t, x0, val):
if t == "LINE":
rv = gp_Vec2d(*(x[2:] - x[:2])).Angle(gp_Vec2d(*val))
else:
raise invalid_args(t)
return rv
def arc_angle_cost(x, t, x0, val):
if t == "CIRCLE":
rv = x[4] - val
else:
raise invalid_args(t)
return rv
# dictionary of individual constraint cost functions
costs: Dict[str, Callable[..., float]] = dict(
Fixed=fixed_cost,
FixedPoint=fixed_point_cost,
Coincident=coincident_cost,
Angle=angle_cost,
Length=length_cost,
Distance=distance_cost,
Radius=radius_cost,
Orientation=orientation_cost,
ArcAngle=arc_angle_cost,
)
class SketchConstraintSolver(object):
entities: List[DOF]
constraints: List[Constraint]
geoms: List[Geoms]
ne: int
nc: int
ixs: List[int]
def __init__(
self,
entities: Iterable[DOF],
constraints: Iterable[Constraint],
geoms: Iterable[Geoms],
):
self.entities = list(entities)
self.constraints = list(constraints)
self.geoms = list(geoms)
self.ne = len(self.entities)
self.nc = len(self.constraints)
# validate and transform constraints
# indices of x corresponding to the entities
self.ixs = [0] + list(accumulate(len(e) for e in self.entities))
def _cost(
self, x0: Array[Any, Float]
) -> Tuple[
Callable[[Array[Any, Float]], float],
Callable[[Array[Any, Float], Array[Any, Float]], None],
Array[Any, Float],
Array[Any, Float],
]:
ixs = self.ixs
constraints = self.constraints
geoms = self.geoms
# split initial values per entity
x0s = [x0[ixs[e] : ixs[e + 1]] for e in range(self.ne)]
def f(x) -> float:
"""
Cost function to be minimized
"""
rv = 0.0
for i, ((e1, e2), kind, val) in enumerate(constraints):
cost = costs[kind]
# build arguments for the specific constraint
args = [x[ixs[e1] : ixs[e1 + 1]], geoms[e1], x0s[e1]]
if e2 is not None:
args += [x[ixs[e2] : ixs[e2 + 1]], geoms[e2], x0s[e2]]
# evaluate
rv += cost(*args, val) ** 2
return rv
def grad(x, rv) -> None:
"""
Gradient of the cost function
"""
rv[:] = 0
for i, ((e1, e2), kind, val) in enumerate(constraints):
cost = costs[kind]
# build arguments for the specific constraint
x1 = x[ixs[e1] : ixs[e1 + 1]]
args = [x1.copy(), geoms[e1], x0s[e1]]
if e2 is not None:
x2 = x[ixs[e2] : ixs[e2 + 1]]
args += [x2.copy(), geoms[e2], x0s[e2]]
# evaluate
tmp = cost(*args, val)
for j, k in enumerate(range(ixs[e1], ixs[e1 + 1])):
args[0][j] += DIFF_EPS
tmp1 = cost(*args, val)
rv[k] += 2 * tmp * (tmp1 - tmp) / DIFF_EPS
args[0][j] = x1[j]
if e2 is not None:
for j, k in enumerate(range(ixs[e2], ixs[e2 + 1])):
args[3][j] += DIFF_EPS
tmp2 = cost(*args, val)
rv[k] += 2 * tmp * (tmp2 - tmp) / DIFF_EPS
args[3][j] = x2[j]
# generate lower and upper bounds for optimization
lb = full(ixs[-1], -inf)
ub = full(ixs[-1], +inf)
for i, g in enumerate(geoms):
if g == "CIRCLE":
lb[ixs[i] + 2] = 0 # lower bound for radius
return f, grad, lb, ub
def solve(self) -> Tuple[Sequence[Sequence[float]], Dict[str, Any]]:
x0 = array(list(chain.from_iterable(self.entities))).ravel()
f, grad, lb, ub = self._cost(x0)
def func(x, g):
if g.size > 0:
grad(x, g)
return f(x)
opt = nlopt.opt(nlopt.LD_SLSQP, len(x0))
opt.set_min_objective(func)
opt.set_lower_bounds(lb)
opt.set_upper_bounds(ub)
opt.set_ftol_abs(0)
opt.set_ftol_rel(0)
opt.set_xtol_rel(TOL)
opt.set_xtol_abs(TOL * 1e-3)
opt.set_maxeval(MAXITER)
x = opt.optimize(x0)
status = {
"entities": self.entities,
"cost": opt.last_optimum_value(),
"iters": opt.get_numevals(),
"status": opt.last_optimize_result(),
}
ixs = self.ixs
return [x[i1:i2] for i1, i2 in zip(ixs, ixs[1:])], status
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,504 | CadQuery/cadquery | refs/heads/master | /tests/test_jupyter.py | from tests import BaseTest
import cadquery as cq
from cadquery.occ_impl.jupyter_tools import display
class TestJupyter(BaseTest):
def test_repr_javascript(self):
cube = cq.Workplane("XY").box(1, 1, 1)
assy = cq.Assembly().add(cube)
shape = cube.val()
self.assertIsInstance(shape, cq.occ_impl.shapes.Solid)
# Test no exception on rendering to js
js1 = shape._repr_javascript_()
js2 = cube._repr_javascript_()
js3 = assy._repr_javascript_()
assert "function render" in js1
assert "function render" in js2
assert "function render" in js3
def test_display_error(self):
with self.assertRaises(ValueError):
display(cq.Vector())
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,505 | CadQuery/cadquery | refs/heads/master | /tests/test_examples.py | import pytest
from glob import glob
from itertools import chain, count
from path import Path
from docutils.parsers.rst import directives
from docutils.core import publish_doctree
from docutils.utils import Reporter
import cadquery as cq
from cadquery import cqgi
from cadquery.cq_directive import cq_directive
def find_examples(pattern="examples/*.py", path=Path("examples")):
for p in glob(pattern):
with open(p, encoding="UTF-8") as f:
code = f.read()
yield code, path
def find_examples_in_docs(pattern="doc/*.rst", path=Path("doc")):
# dummy CQ directive for code
class dummy_cq_directive(cq_directive):
codes = []
def run(self):
self.codes.append("\n".join(self.content))
return []
directives.register_directive("cadquery", dummy_cq_directive)
# read and parse all rst files
for p in glob(pattern):
with open(p, encoding="UTF-8") as f:
doc = f.read()
publish_doctree(
doc, settings_overrides={"report_level": Reporter.SEVERE_LEVEL + 1}
)
# yield all code snippets
for c in dummy_cq_directive.codes:
yield c, path
@pytest.mark.parametrize(
"code, path", chain(find_examples(), find_examples_in_docs()), ids=count(0)
)
def test_example(code, path):
# build
with path:
res = cqgi.parse(code).build()
assert res.exception is None
# check if the resulting objects are valid
for r in res.results:
r = r.shape
if isinstance(r, cq.Workplane):
for v in r.vals():
if isinstance(v, cq.Shape):
assert v.isValid()
elif isinstance(r, cq.Shape):
assert r.isValid()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,506 | CadQuery/cadquery | refs/heads/master | /examples/Ex014_Offset_Workplanes.py | import cadquery as cq
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a 3D box that will have geometry based off it later.
result = cq.Workplane("front").box(3, 2, 0.5)
# 3. The lowest face in the X direction is selected with the <X selector.
# 4. A new workplane is created
# 4a.The workplane is offset from the object surface so that it is not touching
# the original box.
result = result.faces("<X").workplane(offset=0.75)
# 5. Creates a thin disc on the offset workplane that is floating near the box.
result = result.circle(1.0).extrude(0.5)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,507 | CadQuery/cadquery | refs/heads/master | /tests/test_importers.py | """
Tests file importers such as STEP
"""
# core modules
import tempfile
import os
from cadquery import importers, Workplane
from tests import BaseTest
from pytest import approx, raises
# where unit test output will be saved
OUTDIR = tempfile.gettempdir()
# test data directory
testdataDir = os.path.join(os.path.dirname(__file__), "testdata")
class TestImporters(BaseTest):
def importBox(self, importType, fileName):
"""
Exports a simple box to a STEP file and then imports it again
:param importType: The type of file we're importing (STEP, STL, etc)
:param fileName: The path and name of the file to write to
"""
# We're importing a STEP file
if importType == importers.ImportTypes.STEP:
# We first need to build a simple shape to export
shape = Workplane("XY").box(1, 2, 3).val()
# Export the shape to a temporary file
shape.exportStep(fileName)
# Reimport the shape from the new STEP file
importedShape = importers.importShape(importType, fileName)
# Check to make sure we got a solid back
self.assertTrue(importedShape.val().ShapeType() == "Solid")
# Check the number of faces and vertices per face to make sure we have a box shape
self.assertTrue(
importedShape.faces("+X").size() == 1
and importedShape.faces("+X").vertices().size() == 4
)
self.assertTrue(
importedShape.faces("+Y").size() == 1
and importedShape.faces("+Y").vertices().size() == 4
)
self.assertTrue(
importedShape.faces("+Z").size() == 1
and importedShape.faces("+Z").vertices().size() == 4
)
def testSTEP(self):
"""
Tests STEP file import
"""
self.importBox(importers.ImportTypes.STEP, OUTDIR + "/tempSTEP.step")
def testInvalidSTEP(self):
"""
Attempting to load an invalid STEP file should throw an exception, but
not segfault.
"""
tmpfile = OUTDIR + "/badSTEP.step"
with open(tmpfile, "w") as f:
f.write("invalid STEP file")
with self.assertRaises(ValueError):
importers.importShape(importers.ImportTypes.STEP, tmpfile)
def testImportMultipartSTEP(self):
"""
Import a STEP file that contains two objects and ensure that both are
loaded.
"""
filename = os.path.join(testdataDir, "red_cube_blue_cylinder.step")
objs = importers.importShape(importers.ImportTypes.STEP, filename)
self.assertEqual(2, len(objs.all()))
def testImportDXF(self):
"""
Test DXF import with various tolerances.
"""
filename = os.path.join(testdataDir, "gear.dxf")
with self.assertRaises(ValueError):
# tol >~ 2e-4 required for closed wires
obj = importers.importDXF(filename)
obj = importers.importDXF(filename, tol=1e-3)
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.faces().size(), 1)
self.assertEqual(obj.wires().size(), 2)
obj = obj.wires().toPending().extrude(1)
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.solids().size(), 1)
obj = importers.importShape(importers.ImportTypes.DXF, filename, tol=1e-3)
self.assertTrue(obj.val().isValid())
# additional files to test more DXF entities
filename = os.path.join(testdataDir, "MC 12x31.dxf")
obj = importers.importDXF(filename)
self.assertTrue(obj.val().isValid())
filename = os.path.join(testdataDir, "1001.dxf")
obj = importers.importDXF(filename)
self.assertTrue(obj.val().isValid())
# test spline import
filename = os.path.join(testdataDir, "spline.dxf")
obj = importers.importDXF(filename, tol=1)
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.faces().size(), 1)
self.assertEqual(obj.wires().size(), 2)
# test rational spline import
filename = os.path.join(testdataDir, "rational_spline.dxf")
obj = importers.importDXF(filename)
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.faces().size(), 1)
self.assertEqual(obj.edges().size(), 1)
# importing of a complex shape exported from Inkscape
filename = os.path.join(testdataDir, "genshi.dxf")
obj = importers.importDXF(filename)
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.faces().size(), 1)
# test layer filtering
filename = os.path.join(testdataDir, "three_layers.dxf")
obj = importers.importDXF(filename, exclude=["Layer2"])
self.assertTrue(obj.val().isValid())
self.assertEqual(obj.faces().size(), 2)
self.assertEqual(obj.wires().size(), 2)
obj = importers.importDXF(filename, include=["Layer2"])
assert obj.vertices("<XY").val().toTuple() == approx(
(104.2871791623584, 0.0038725018551133, 0.0)
)
obj = importers.importDXF(filename, include=["Layer2", "Layer3"])
assert obj.vertices("<XY").val().toTuple() == approx(
(104.2871791623584, 0.0038725018551133, 0.0)
)
assert obj.vertices(">XY").val().toTuple() == approx(
(257.6544359816229, 93.62447646419444, 0.0)
)
with raises(ValueError):
importers.importDXF(filename, include=["Layer1"], exclude=["Layer3"])
with raises(ValueError):
# Layer4 does not exist
importers.importDXF(filename, include=["Layer4"])
# test dxf extrusion into the third dimension
extrusion_value = 15.0
tmp = obj.wires()
tmp.ctx.pendingWires = tmp.vals()
threed = tmp.extrude(extrusion_value)
self.assertEqual(threed.findSolid().BoundingBox().zlen, extrusion_value)
if __name__ == "__main__":
import unittest
unittest.main()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,508 | CadQuery/cadquery | refs/heads/master | /examples/Ex101_InterpPlate.py | from math import sin, cos, pi, sqrt
import cadquery as cq
# TEST_1
# example from PythonOCC core_geometry_geomplate.py, use of thickness = 0 returns 2D surface.
thickness = 0
edge_points = [(0.0, 0.0, 0.0), (0.0, 10.0, 0.0), (0.0, 10.0, 10.0), (0.0, 0.0, 10.0)]
surface_points = [(5.0, 5.0, 5.0)]
plate_0 = cq.Workplane("XY").interpPlate(edge_points, surface_points, thickness)
print("plate_0.val().Volume() = ", plate_0.val().Volume())
plate_0 = plate_0.translate((0, 6 * 12, 0))
show_object(plate_0)
# EXAMPLE 1
# Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides
thickness = 0.1
edge_points = [
(-7.0, -7.0, 0.0),
(-3.0, -10.0, 3.0),
(7.0, -7.0, 0.0),
(7.0, 7.0, 0.0),
(-7.0, 7.0, 0.0),
]
edge_wire = cq.Workplane("XY").polyline(
[(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)]
)
# edge_wire = edge_wire.add(cq.Workplane("YZ").workplane().transformed(offset=cq.Vector(0, 0, -7), rotate=cq.Vector(45, 0, 0)).polyline([(-7.,0.), (3,-3), (7.,0.)]))
# In CadQuery Sept-2019 it worked with rotate=cq.Vector(0, 45, 0). In CadQuery Dec-2019 rotate=cq.Vector(45, 0, 0) only closes the wire.
edge_wire = edge_wire.add(
cq.Workplane("YZ")
.workplane()
.transformed(offset=cq.Vector(0, 0, -7), rotate=cq.Vector(45, 0, 0))
.spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)])
)
surface_points = [(-3.0, -3.0, -3.0), (3.0, 3.0, 3.0)]
plate_1 = cq.Workplane("XY").interpPlate(edge_wire, surface_points, thickness)
# plate_1 = cq.Workplane("XY").interpPlate(edge_points, surface_points, thickness) # list of (x,y,z) points instead of wires for edges
print("plate_1.val().Volume() = ", plate_1.val().Volume())
show_object(plate_1)
# EXAMPLE 2
# Embossed star, need to change optional parameters to obtain nice looking result.
r1 = 3.0
r2 = 10.0
fn = 6
thickness = 0.1
edge_points = [
(r1 * cos(i * pi / fn), r1 * sin(i * pi / fn))
if i % 2 == 0
else (r2 * cos(i * pi / fn), r2 * sin(i * pi / fn))
for i in range(2 * fn + 1)
]
edge_wire = cq.Workplane("XY").polyline(edge_points)
r2 = 4.5
surface_points = [
(r2 * cos(i * pi / fn), r2 * sin(i * pi / fn), 1.0) for i in range(2 * fn)
] + [(0.0, 0.0, -2.0)]
plate_2 = cq.Workplane("XY").interpPlate(
edge_wire,
surface_points,
thickness,
combine=True,
clean=True,
degree=3,
nbPtsOnCur=15,
nbIter=2,
anisotropy=False,
tol2d=0.00001,
tol3d=0.0001,
tolAng=0.01,
tolCurv=0.1,
maxDeg=8,
maxSegments=49,
)
# plate_2 = cq.Workplane("XY").interpPlate(edge_points, surface_points, thickness, combine=True, clean=True, Degree=3, NbPtsOnCur=15, NbIter=2, Anisotropie=False, Tol2d=0.00001, Tol3d=0.0001, TolAng=0.01, TolCurv=0.1, MaxDeg=8, MaxSegments=49) # list of (x,y,z) points instead of wires for edges
print("plate_2.val().Volume() = ", plate_2.val().Volume())
plate_2 = plate_2.translate((0, 2 * 12, 0))
show_object(plate_2)
# EXAMPLE 3
# Points on hexagonal pattern coordinates, use of pushpoints.
r1 = 1.0
N = 3
ca = cos(30.0 * pi / 180.0)
sa = sin(30.0 * pi / 180.0)
# EVEN ROWS
pts = [
(-3.0, -3.0),
(-1.267949, -3.0),
(0.464102, -3.0),
(2.196152, -3.0),
(-3.0, 0.0),
(-1.267949, 0.0),
(0.464102, 0.0),
(2.196152, 0.0),
(-2.133974, -1.5),
(-0.401923, -1.5),
(1.330127, -1.5),
(3.062178, -1.5),
(-2.133975, 1.5),
(-0.401924, 1.5),
(1.330127, 1.5),
(3.062178, 1.5),
]
# Spike surface
thickness = 0.1
fn = 6
edge_points = [
(
r1 * cos(i * 2 * pi / fn + 30 * pi / 180),
r1 * sin(i * 2 * pi / fn + 30 * pi / 180),
)
for i in range(fn + 1)
]
surface_points = [
(
r1 / 4 * cos(i * 2 * pi / fn + 30 * pi / 180),
r1 / 4 * sin(i * 2 * pi / fn + 30 * pi / 180),
0.75,
)
for i in range(fn + 1)
] + [(0, 0, 2)]
edge_wire = cq.Workplane("XY").polyline(edge_points)
plate_3 = (
cq.Workplane("XY")
.pushPoints(pts)
.interpPlate(
edge_wire,
surface_points,
thickness,
combine=False,
clean=False,
degree=2,
nbPtsOnCur=20,
nbIter=2,
anisotropy=False,
tol2d=0.00001,
tol3d=0.0001,
tolAng=0.01,
tolCurv=0.1,
maxDeg=8,
maxSegments=9,
)
)
print("plate_3.val().Volume() = ", plate_3.val().Volume())
plate_3 = plate_3.translate((0, 4 * 11, 0))
show_object(plate_3)
# EXAMPLE 4
# Gyroïd, all edges are splines on different workplanes.
thickness = 0.1
edge_points = [
[[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]],
[[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
[[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]],
]
plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"]
offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54]
edge_wire = (
cq.Workplane(plane_list[0]).workplane(offset=-offset_list[0]).spline(edge_points[0])
)
for i in range(len(edge_points) - 1):
edge_wire = edge_wire.add(
cq.Workplane(plane_list[i + 1])
.workplane(offset=-offset_list[i + 1])
.spline(edge_points[i + 1])
)
surface_points = [(0, 0, 0)]
plate_4 = cq.Workplane("XY").interpPlate(edge_wire, surface_points, thickness)
print("plate_4.val().Volume() = ", plate_4.val().Volume())
plate_4 = plate_4.translate((0, 5 * 12, 0))
show_object(plate_4)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,509 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/assembly.py | import os.path
import uuid
from tempfile import TemporaryDirectory
from shutil import make_archive
from itertools import chain
from typing_extensions import Literal
from vtkmodules.vtkIOExport import vtkJSONSceneExporter, vtkVRMLExporter
from vtkmodules.vtkRenderingCore import vtkRenderer, vtkRenderWindow
from OCP.XSControl import XSControl_WorkSession
from OCP.STEPCAFControl import STEPCAFControl_Writer
from OCP.STEPControl import STEPControl_StepModelType
from OCP.IFSelect import IFSelect_ReturnStatus
from OCP.XCAFApp import XCAFApp_Application
from OCP.XmlDrivers import (
XmlDrivers_DocumentStorageDriver,
XmlDrivers_DocumentRetrievalDriver,
)
from OCP.TCollection import TCollection_ExtendedString, TCollection_AsciiString
from OCP.PCDM import PCDM_StoreStatus
from OCP.RWGltf import RWGltf_CafWriter
from OCP.TColStd import TColStd_IndexedDataMapOfStringString
from OCP.Message import Message_ProgressRange
from OCP.Interface import Interface_Static
from ..assembly import AssemblyProtocol, toCAF, toVTK, toFusedCAF
from ..geom import Location
class ExportModes:
DEFAULT = "default"
FUSED = "fused"
STEPExportModeLiterals = Literal["default", "fused"]
def exportAssembly(
assy: AssemblyProtocol,
path: str,
mode: STEPExportModeLiterals = "default",
**kwargs
) -> bool:
"""
Export an assembly to a STEP file.
kwargs is used to provide optional keyword arguments to configure the exporter.
:param assy: assembly
:param path: Path and filename for writing
:param mode: STEP export mode. The options are "default", and "fused" (a single fused compound).
It is possible that fused mode may exhibit low performance.
:param fuzzy_tol: OCCT fuse operation tolerance setting used only for fused assembly export.
:type fuzzy_tol: float
:param glue: Enable gluing mode for improved performance during fused assembly export.
This option should only be used for non-intersecting shapes or those that are only touching or partially overlapping.
Note that when glue is enabled, the resulting fused shape may be invalid if shapes are intersecting in an incompatible way.
Defaults to False.
:type glue: bool
:param write_pcurves: Enable or disable writing parametric curves to the STEP file. Default True.
If False, writes STEP file without pcurves. This decreases the size of the resulting STEP file.
:type write_pcurves: bool
:param precision_mode: Controls the uncertainty value for STEP entities. Specify -1, 0, or 1. Default 0.
See OCCT documentation.
:type precision_mode: int
"""
# Handle the extra settings for the STEP export
pcurves = 1
if "write_pcurves" in kwargs and not kwargs["write_pcurves"]:
pcurves = 0
precision_mode = kwargs["precision_mode"] if "precision_mode" in kwargs else 0
fuzzy_tol = kwargs["fuzzy_tol"] if "fuzzy_tol" in kwargs else None
glue = kwargs["glue"] if "glue" in kwargs else False
# Use the assembly name if the user set it
assembly_name = assy.name if assy.name else str(uuid.uuid1())
# Handle the doc differently based on which mode we are using
if mode == "fused":
_, doc = toFusedCAF(assy, glue, fuzzy_tol)
else: # Includes "default"
_, doc = toCAF(assy, True)
session = XSControl_WorkSession()
writer = STEPCAFControl_Writer(session, False)
writer.SetColorMode(True)
writer.SetLayerMode(True)
writer.SetNameMode(True)
Interface_Static.SetIVal_s("write.surfacecurve.mode", pcurves)
Interface_Static.SetIVal_s("write.precision.mode", precision_mode)
writer.Transfer(doc, STEPControl_StepModelType.STEPControl_AsIs)
status = writer.Write(path)
return status == IFSelect_ReturnStatus.IFSelect_RetDone
def exportCAF(assy: AssemblyProtocol, path: str) -> bool:
"""
Export an assembly to a OCAF xml file (internal OCCT format).
"""
folder, fname = os.path.split(path)
name, ext = os.path.splitext(fname)
ext = ext[1:] if ext[0] == "." else ext
_, doc = toCAF(assy)
app = XCAFApp_Application.GetApplication_s()
store = XmlDrivers_DocumentStorageDriver(
TCollection_ExtendedString("Copyright: Open Cascade, 2001-2002")
)
ret = XmlDrivers_DocumentRetrievalDriver()
app.DefineFormat(
TCollection_AsciiString("XmlOcaf"),
TCollection_AsciiString("Xml XCAF Document"),
TCollection_AsciiString(ext),
ret,
store,
)
doc.SetRequestedFolder(TCollection_ExtendedString(folder))
doc.SetRequestedName(TCollection_ExtendedString(name))
status = app.SaveAs(doc, TCollection_ExtendedString(path))
app.Close(doc)
return status == PCDM_StoreStatus.PCDM_SS_OK
def _vtkRenderWindow(
assy: AssemblyProtocol, tolerance: float = 1e-3, angularTolerance: float = 0.1
) -> vtkRenderWindow:
"""
Convert an assembly to a vtkRenderWindow. Used by vtk based exporters.
"""
renderer = toVTK(assy, tolerance=tolerance, angularTolerance=angularTolerance)
renderWindow = vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderer.ResetCamera()
renderer.SetBackground(1, 1, 1)
return renderWindow
def exportVTKJS(assy: AssemblyProtocol, path: str):
"""
Export an assembly to a zipped vtkjs. NB: .zip extensions is added to path.
"""
renderWindow = _vtkRenderWindow(assy)
with TemporaryDirectory() as tmpdir:
exporter = vtkJSONSceneExporter()
exporter.SetFileName(tmpdir)
exporter.SetRenderWindow(renderWindow)
exporter.Write()
make_archive(path, "zip", tmpdir)
def exportVRML(
assy: AssemblyProtocol,
path: str,
tolerance: float = 1e-3,
angularTolerance: float = 0.1,
):
"""
Export an assembly to a vrml file using vtk.
"""
exporter = vtkVRMLExporter()
exporter.SetFileName(path)
exporter.SetRenderWindow(_vtkRenderWindow(assy, tolerance, angularTolerance))
exporter.Write()
def exportGLTF(
assy: AssemblyProtocol,
path: str,
binary: bool = True,
tolerance: float = 1e-3,
angularTolerance: float = 0.1,
):
"""
Export an assembly to a gltf file.
"""
# map from CadQuery's right-handed +Z up coordinate system to glTF's right-handed +Y up coordinate system
# https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#coordinate-system-and-units
orig_loc = assy.loc
assy.loc *= Location((0, 0, 0), (1, 0, 0), -90)
_, doc = toCAF(assy, True, True, tolerance, angularTolerance)
writer = RWGltf_CafWriter(TCollection_AsciiString(path), binary)
result = writer.Perform(
doc, TColStd_IndexedDataMapOfStringString(), Message_ProgressRange()
)
# restore coordinate system after exporting
assy.loc = orig_loc
return result
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,510 | CadQuery/cadquery | refs/heads/master | /examples/Ex020_Rounding_Corners_with_Fillets.py | import cadquery as cq
# Create a plate with 4 rounded corners in the Z-axis.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects all edges that are parallel to the Z axis.
# 4. Creates fillets on each of the selected edges with the specified radius.
result = cq.Workplane("XY").box(3, 3, 0.5).edges("|Z").fillet(0.125)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,511 | CadQuery/cadquery | refs/heads/master | /conda/web-installer/build.py | import sys
import os
import subprocess
from jinja2 import Environment, select_autoescape, FileSystemLoader
def usage():
print("Web installer build script")
print("build.py <installer version> <tag version>")
print(
"The installer verison is the version number used within the conda constructor script"
)
print("The tag verison is the version of cadquery that will be pulled from github")
def write_file(destpath, contents):
with open(destpath, "w") as destfile:
destfile.write(contents)
def run_cmd(cmdarray, workingdir, captureout=False):
stdout = stderr = None
if captureout:
stdout = stderr = subprocess.PIPE
proc = subprocess.Popen(
cmdarray, cwd=workingdir, stdout=stdout, stderr=stderr, universal_newlines=True
)
proc_out, proc_err = proc.communicate()
if proc.returncode != 0:
raise RuntimeError("Failure to run command")
return stdout, stderr
def generate_templates(installer_version, tag_version):
print("Generating Scripts")
env = Environment(loader=FileSystemLoader("."), autoescape=select_autoescape())
template = env.get_template("construct.yaml.jinja2")
output = template.render(installer_version=installer_version)
write_file("construct.yaml", output)
template = env.get_template("post-install.bat.jinja2")
output = template.render(tag_version=tag_version)
write_file("post-install.bat", output)
template = env.get_template("post-install.sh.jinja2")
output = template.render(tag_version=tag_version)
write_file("post-install.sh", output)
def run_constructor():
print("Running constructor")
scriptdir = os.path.dirname(os.path.realpath(__file__))
builddir = os.path.join(scriptdir, "build")
if not os.path.exists(builddir):
os.makedirs(builddir)
run_cmd(["constructor", scriptdir], builddir)
def main():
if len(sys.argv) < 2:
usage()
return
installer_version = sys.argv[1]
tag_version = sys.argv[2]
generate_templates(installer_version, tag_version)
run_constructor()
main()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,512 | CadQuery/cadquery | refs/heads/master | /examples/Ex008_Polygon_Creation.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
width = 3.0 # The width of the plate
height = 4.0 # The height of the plate
thickness = 0.25 # The thickness of the plate
polygon_sides = 6 # The number of sides that the polygonal holes should have
polygon_dia = 1.0 # The diameter of the circle enclosing the polygon points
# Create a plate with two polygons cut through it
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. A 3D box is created in one box() operation to represent the plate.
# 2a. The box is centered around the origin, which creates a result that may
# be unituitive when the polygon cuts are made.
# 3. 2 points are pushed onto the stack and will be used as centers for the
# polygonal holes.
# 4. The two polygons are created, on for each point, with one call to
# polygon() using the number of sides and the circle that bounds the
# polygon.
# 5. The polygons are cut thru all objects that are in the line of extrusion.
# 5a. A face was not selected, and so the polygons are created on the
# workplane. Since the box was centered around the origin, the polygons end
# up being in the center of the box. This makes them cut from the center to
# the outside along the normal (positive direction).
# 6. The polygons are cut through all objects, starting at the center of the
# box/plate and going "downward" (opposite of normal) direction. Functions
# like cutBlind() assume a positive cut direction, but cutThruAll() assumes
# instead that the cut is made from a max direction and cuts downward from
# that max through all objects.
result = (
cq.Workplane("front")
.box(width, height, thickness)
.pushPoints([(0, 0.75), (0, -0.75)])
.polygon(polygon_sides, polygon_dia)
.cutThruAll()
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,513 | CadQuery/cadquery | refs/heads/master | /tests/test_vis.py | from cadquery import Workplane, Assembly, Sketch
from cadquery.vis import show, show_object
import cadquery.occ_impl.exporters.assembly as assembly
import cadquery.vis as vis
from vtkmodules.vtkRenderingCore import vtkRenderWindow, vtkRenderWindowInteractor
from pytest import fixture, raises
@fixture
def wp():
return Workplane().box(1, 1, 1)
@fixture
def assy(wp):
return Assembly().add(wp)
@fixture
def sk():
return Sketch().circle(1.0)
class FakeInteractor(vtkRenderWindowInteractor):
def Start(self):
pass
def Initialize(self):
pass
class FakeWindow(vtkRenderWindow):
def Render(*args):
pass
def SetSize(*args):
pass
def GetScreenSize(*args):
return 1, 1
def SetPosition(*args):
pass
def test_show(wp, assy, sk, monkeypatch):
# use some dummy vtk objects
monkeypatch.setattr(vis, "vtkRenderWindowInteractor", FakeInteractor)
monkeypatch.setattr(assembly, "vtkRenderWindow", FakeWindow)
# simple smoke test
show(wp)
show(wp.val())
show(assy)
show(sk)
show(wp, sk, assy, wp.val())
show()
with raises(ValueError):
show(1)
show_object(wp)
show_object(wp.val())
show_object(assy)
show_object(sk)
show_object(wp, sk, assy, wp.val())
show_object()
with raises(ValueError):
show_object("a")
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,514 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/json.py | """
Objects that represent
three.js JSON object notation
https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3.0
"""
JSON_TEMPLATE = """\
{
"metadata" :
{
"formatVersion" : 3,
"generatedBy" : "ParametricParts",
"vertices" : %(nVertices)d,
"faces" : %(nFaces)d,
"normals" : 0,
"colors" : 0,
"uvs" : 0,
"materials" : 1,
"morphTargets" : 0
},
"scale" : 1.0,
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "Material",
"colorAmbient" : [0.0, 0.0, 0.0],
"colorDiffuse" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746],
"colorSpecular" : [0.5, 0.5, 0.5],
"shading" : "Lambert",
"specularCoef" : 50,
"transparency" : 1.0,
"vertexColors" : false
}],
"vertices": %(vertices)s,
"morphTargets": [],
"normals": [],
"colors": [],
"uvs": [[]],
"faces": %(faces)s
}
"""
class JsonMesh(object):
def __init__(self):
self.vertices = []
self.faces = []
self.nVertices = 0
self.nFaces = 0
def addVertex(self, x, y, z):
self.nVertices += 1
self.vertices.extend([x, y, z])
# add triangle composed of the three provided vertex indices
def addTriangleFace(self, i, j, k):
# first position means justa simple triangle
self.nFaces += 1
self.faces.extend([0, int(i), int(j), int(k)])
"""
Get a json model from this model.
For now we'll forget about colors, vertex normals, and all that stuff
"""
def toJson(self):
return JSON_TEMPLATE % {
"vertices": str(self.vertices),
"faces": str(self.faces),
"nVertices": self.nVertices,
"nFaces": self.nFaces,
}
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,515 | CadQuery/cadquery | refs/heads/master | /examples/Ex023_Sweep.py | import cadquery as cq
# Points we will use to create spline and polyline paths to sweep over
pts = [(0, 1), (1, 2), (2, 4)]
# Spline path generated from our list of points (tuples)
path = cq.Workplane("XZ").spline(pts)
# Sweep a circle with a diameter of 1.0 units along the spline path we just created
defaultSweep = cq.Workplane("XY").circle(1.0).sweep(path)
# Sweep defaults to making a solid and not generating a Frenet solid. Setting Frenet to True helps prevent creep in
# the orientation of the profile as it is being swept
frenetShell = cq.Workplane("XY").circle(1.0).sweep(path, makeSolid=True, isFrenet=True)
# We can sweep shapes other than circles
defaultRect = cq.Workplane("XY").rect(1.0, 1.0).sweep(path)
# Switch to a polyline path, but have it use the same points as the spline
path = cq.Workplane("XZ").polyline(pts, includeCurrent=True)
# Using a polyline path leads to the resulting solid having segments rather than a single swept outer face
plineSweep = cq.Workplane("XY").circle(1.0).sweep(path)
# Switch to an arc for the path
path = cq.Workplane("XZ").threePointArc((1.0, 1.5), (0.0, 1.0))
# Use a smaller circle section so that the resulting solid looks a little nicer
arcSweep = cq.Workplane("XY").circle(0.5).sweep(path)
# Translate the resulting solids so that they do not overlap and display them left to right
show_object(defaultSweep)
show_object(frenetShell.translate((5, 0, 0)))
show_object(defaultRect.translate((10, 0, 0)))
show_object(plineSweep)
show_object(arcSweep.translate((20, 0, 0)))
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,516 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/amf.py | import xml.etree.cElementTree as ET
class AmfWriter(object):
def __init__(self, tessellation):
self.units = "mm"
self.tessellation = tessellation
def writeAmf(self, outFile):
amf = ET.Element("amf", units=self.units)
# TODO: if result is a compound, we need to loop through them
object = ET.SubElement(amf, "object", id="0")
mesh = ET.SubElement(object, "mesh")
vertices = ET.SubElement(mesh, "vertices")
volume = ET.SubElement(mesh, "volume")
# add vertices
for v in self.tessellation[0]:
vtx = ET.SubElement(vertices, "vertex")
coord = ET.SubElement(vtx, "coordinates")
x = ET.SubElement(coord, "x")
x.text = str(v.x)
y = ET.SubElement(coord, "y")
y.text = str(v.y)
z = ET.SubElement(coord, "z")
z.text = str(v.z)
# add triangles
for t in self.tessellation[1]:
triangle = ET.SubElement(volume, "triangle")
v1 = ET.SubElement(triangle, "v1")
v1.text = str(t[0])
v2 = ET.SubElement(triangle, "v2")
v2.text = str(t[1])
v3 = ET.SubElement(triangle, "v3")
v3.text = str(t[2])
amf = ET.ElementTree(amf).write(outFile, xml_declaration=True)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,517 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/geom.py | import math
from typing import overload, Sequence, Union, Tuple, Type, Optional
from OCP.gp import (
gp_Vec,
gp_Ax1,
gp_Ax3,
gp_Pnt,
gp_Dir,
gp_Pln,
gp_Trsf,
gp_GTrsf,
gp_XYZ,
gp_EulerSequence,
gp,
)
from OCP.Bnd import Bnd_Box
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.TopoDS import TopoDS_Shape
from OCP.TopLoc import TopLoc_Location
from ..types import Real
TOL = 1e-2
VectorLike = Union["Vector", Tuple[Real, Real], Tuple[Real, Real, Real]]
class Vector(object):
"""Create a 3-dimensional vector
:param args: a 3D vector, with x-y-z parts.
you can either provide:
* nothing (in which case the null vector is return)
* a gp_Vec
* a vector ( in which case it is copied )
* a 3-tuple
* a 2-tuple (z assumed to be 0)
* three float values: x, y, and z
* two float values: x,y
"""
_wrapped: gp_Vec
@overload
def __init__(self, x: float, y: float, z: float) -> None:
...
@overload
def __init__(self, x: float, y: float) -> None:
...
@overload
def __init__(self, v: "Vector") -> None:
...
@overload
def __init__(self, v: Sequence[float]) -> None:
...
@overload
def __init__(self, v: Union[gp_Vec, gp_Pnt, gp_Dir, gp_XYZ]) -> None:
...
@overload
def __init__(self) -> None:
...
def __init__(self, *args):
if len(args) == 3:
fV = gp_Vec(*args)
elif len(args) == 2:
fV = gp_Vec(*args, 0)
elif len(args) == 1:
if isinstance(args[0], Vector):
fV = gp_Vec(args[0].wrapped.XYZ())
elif isinstance(args[0], (tuple, list)):
arg = args[0]
if len(arg) == 3:
fV = gp_Vec(*arg)
elif len(arg) == 2:
fV = gp_Vec(*arg, 0)
elif isinstance(args[0], (gp_Vec, gp_Pnt, gp_Dir)):
fV = gp_Vec(args[0].XYZ())
elif isinstance(args[0], gp_XYZ):
fV = gp_Vec(args[0])
else:
raise TypeError("Expected three floats, OCC gp_, or 3-tuple")
elif len(args) == 0:
fV = gp_Vec(0, 0, 0)
else:
raise TypeError("Expected three floats, OCC gp_, or 3-tuple")
self._wrapped = fV
@property
def x(self) -> float:
return self.wrapped.X()
@x.setter
def x(self, value: float) -> None:
self.wrapped.SetX(value)
@property
def y(self) -> float:
return self.wrapped.Y()
@y.setter
def y(self, value: float) -> None:
self.wrapped.SetY(value)
@property
def z(self) -> float:
return self.wrapped.Z()
@z.setter
def z(self, value: float) -> None:
self.wrapped.SetZ(value)
@property
def Length(self) -> float:
return self.wrapped.Magnitude()
@property
def wrapped(self) -> gp_Vec:
return self._wrapped
def toTuple(self) -> Tuple[float, float, float]:
return (self.x, self.y, self.z)
def cross(self, v: "Vector") -> "Vector":
return Vector(self.wrapped.Crossed(v.wrapped))
def dot(self, v: "Vector") -> float:
return self.wrapped.Dot(v.wrapped)
def sub(self, v: "Vector") -> "Vector":
return Vector(self.wrapped.Subtracted(v.wrapped))
def __sub__(self, v: "Vector") -> "Vector":
return self.sub(v)
def add(self, v: "Vector") -> "Vector":
return Vector(self.wrapped.Added(v.wrapped))
def __add__(self, v: "Vector") -> "Vector":
return self.add(v)
def multiply(self, scale: float) -> "Vector":
"""Return a copy multiplied by the provided scalar"""
return Vector(self.wrapped.Multiplied(scale))
def __mul__(self, scale: float) -> "Vector":
return self.multiply(scale)
def __truediv__(self, denom: float) -> "Vector":
return self.multiply(1.0 / denom)
def __rmul__(self, scale: float) -> "Vector":
return self.multiply(scale)
def normalized(self) -> "Vector":
"""Return a normalized version of this vector"""
return Vector(self.wrapped.Normalized())
def Center(self) -> "Vector":
"""Return the vector itself
The center of myself is myself.
Provided so that vectors, vertices, and other shapes all support a
common interface, when Center() is requested for all objects on the
stack.
"""
return self
def getAngle(self, v: "Vector") -> float:
return self.wrapped.Angle(v.wrapped)
def getSignedAngle(self, v: "Vector") -> float:
return self.wrapped.AngleWithRef(v.wrapped, gp_Vec(0, 0, -1))
def distanceToLine(self):
raise NotImplementedError("Have not needed this yet, but OCCT supports it!")
def projectToLine(self, line: "Vector") -> "Vector":
"""
Returns a new vector equal to the projection of this Vector onto the line
represented by Vector <line>
:param args: Vector
Returns the projected vector.
"""
lineLength = line.Length
return line * (self.dot(line) / (lineLength * lineLength))
def distanceToPlane(self):
raise NotImplementedError("Have not needed this yet, but OCCT supports it!")
def projectToPlane(self, plane: "Plane") -> "Vector":
"""
Vector is projected onto the plane provided as input.
:param args: Plane object
Returns the projected vector.
"""
base = plane.origin
normal = plane.zDir
return self - normal * (((self - base).dot(normal)) / normal.Length ** 2)
def __neg__(self) -> "Vector":
return self * -1
def __abs__(self) -> float:
return self.Length
def __repr__(self) -> str:
return "Vector: " + str((self.x, self.y, self.z))
def __str__(self) -> str:
return "Vector: " + str((self.x, self.y, self.z))
def __eq__(self, other: "Vector") -> bool: # type: ignore[override]
return self.wrapped.IsEqual(other.wrapped, 0.00001, 0.00001)
def toPnt(self) -> gp_Pnt:
return gp_Pnt(self.wrapped.XYZ())
def toDir(self) -> gp_Dir:
return gp_Dir(self.wrapped.XYZ())
def transform(self, T: "Matrix") -> "Vector":
# to gp_Pnt to obey cq transformation convention (in OCP.vectors do not translate)
pnt = self.toPnt()
pnt_t = pnt.Transformed(T.wrapped.Trsf())
return Vector(gp_Vec(pnt_t.XYZ()))
class Matrix:
"""A 3d , 4x4 transformation matrix.
Used to move geometry in space.
The provided "matrix" parameter may be None, a gp_GTrsf, or a nested list of
values.
If given a nested list, it is expected to be of the form:
[[m11, m12, m13, m14],
[m21, m22, m23, m24],
[m31, m32, m33, m34]]
A fourth row may be given, but it is expected to be: [0.0, 0.0, 0.0, 1.0]
since this is a transform matrix.
"""
wrapped: gp_GTrsf
@overload
def __init__(self) -> None:
...
@overload
def __init__(self, matrix: Union[gp_GTrsf, gp_Trsf]) -> None:
...
@overload
def __init__(self, matrix: Sequence[Sequence[float]]) -> None:
...
def __init__(self, matrix=None):
if matrix is None:
self.wrapped = gp_GTrsf()
elif isinstance(matrix, gp_GTrsf):
self.wrapped = matrix
elif isinstance(matrix, gp_Trsf):
self.wrapped = gp_GTrsf(matrix)
elif isinstance(matrix, (list, tuple)):
# Validate matrix size & 4x4 last row value
valid_sizes = all(
(isinstance(row, (list, tuple)) and (len(row) == 4)) for row in matrix
) and len(matrix) in (3, 4)
if not valid_sizes:
raise TypeError(
"Matrix constructor requires 2d list of 4x3 or 4x4, but got: {!r}".format(
matrix
)
)
elif (len(matrix) == 4) and (tuple(matrix[3]) != (0, 0, 0, 1)):
raise ValueError(
"Expected the last row to be [0,0,0,1], but got: {!r}".format(
matrix[3]
)
)
# Assign values to matrix
self.wrapped = gp_GTrsf()
[
self.wrapped.SetValue(i + 1, j + 1, e)
for i, row in enumerate(matrix[:3])
for j, e in enumerate(row)
]
else:
raise TypeError("Invalid param to matrix constructor: {}".format(matrix))
def rotateX(self, angle: float):
self._rotate(gp.OX_s(), angle)
def rotateY(self, angle: float):
self._rotate(gp.OY_s(), angle)
def rotateZ(self, angle: float):
self._rotate(gp.OZ_s(), angle)
def _rotate(self, direction: gp_Ax1, angle: float):
new = gp_Trsf()
new.SetRotation(direction, angle)
self.wrapped = self.wrapped * gp_GTrsf(new)
def inverse(self) -> "Matrix":
return Matrix(self.wrapped.Inverted())
@overload
def multiply(self, other: Vector) -> Vector:
...
@overload
def multiply(self, other: "Matrix") -> "Matrix":
...
def multiply(self, other):
if isinstance(other, Vector):
return other.transform(self)
return Matrix(self.wrapped.Multiplied(other.wrapped))
def transposed_list(self) -> Sequence[float]:
"""Needed by the cqparts gltf exporter"""
trsf = self.wrapped
data = [[trsf.Value(i, j) for j in range(1, 5)] for i in range(1, 4)] + [
[0.0, 0.0, 0.0, 1.0]
]
return [data[j][i] for i in range(4) for j in range(4)]
def __getitem__(self, rc: Tuple[int, int]) -> float:
"""Provide Matrix[r, c] syntax for accessing individual values. The row
and column parameters start at zero, which is consistent with most
python libraries, but is counter to gp_GTrsf(), which is 1-indexed.
"""
if not isinstance(rc, tuple) or (len(rc) != 2):
raise IndexError("Matrix subscript must provide (row, column)")
(r, c) = rc
if (0 <= r <= 3) and (0 <= c <= 3):
if r < 3:
return self.wrapped.Value(r + 1, c + 1)
else:
# gp_GTrsf doesn't provide access to the 4th row because it has
# an implied value as below:
return [0.0, 0.0, 0.0, 1.0][c]
else:
raise IndexError("Out of bounds access into 4x4 matrix: {!r}".format(rc))
def __repr__(self) -> str:
"""
Generate a valid python expression representing this Matrix
"""
matrix_transposed = self.transposed_list()
matrix_str = ",\n ".join(str(matrix_transposed[i::4]) for i in range(4))
return f"Matrix([{matrix_str}])"
class Plane(object):
"""A 2D coordinate system in space
A 2D coordinate system in space, with the x-y axes on the plane, and a
particular point as the origin.
A plane allows the use of 2D coordinates, which are later converted to
global, 3d coordinates when the operations are complete.
Frequently, it is not necessary to create work planes, as they can be
created automatically from faces.
"""
xDir: Vector
yDir: Vector
zDir: Vector
_origin: Vector
lcs: gp_Ax3
rG: Matrix
fG: Matrix
# equality tolerances
_eq_tolerance_origin = 1e-6
_eq_tolerance_dot = 1e-6
@classmethod
def named(cls: Type["Plane"], stdName: str, origin=(0, 0, 0)) -> "Plane":
"""Create a predefined Plane based on the conventional names.
:param stdName: one of (XY|YZ|ZX|XZ|YX|ZY|front|back|left|right|top|bottom)
:type stdName: string
:param origin: the desired origin, specified in global coordinates
:type origin: 3-tuple of the origin of the new plane, in global coordinates.
Available named planes are as follows. Direction references refer to
the global directions.
=========== ======= ======= ======
Name xDir yDir zDir
=========== ======= ======= ======
XY +x +y +z
YZ +y +z +x
ZX +z +x +y
XZ +x +z -y
YX +y +x -z
ZY +z +y -x
front +x +y +z
back -x +y -z
left +z +y -x
right -z +y +x
top +x -z +y
bottom +x +z -y
=========== ======= ======= ======
"""
namedPlanes = {
# origin, xDir, normal
"XY": Plane(origin, (1, 0, 0), (0, 0, 1)),
"YZ": Plane(origin, (0, 1, 0), (1, 0, 0)),
"ZX": Plane(origin, (0, 0, 1), (0, 1, 0)),
"XZ": Plane(origin, (1, 0, 0), (0, -1, 0)),
"YX": Plane(origin, (0, 1, 0), (0, 0, -1)),
"ZY": Plane(origin, (0, 0, 1), (-1, 0, 0)),
"front": Plane(origin, (1, 0, 0), (0, 0, 1)),
"back": Plane(origin, (-1, 0, 0), (0, 0, -1)),
"left": Plane(origin, (0, 0, 1), (-1, 0, 0)),
"right": Plane(origin, (0, 0, -1), (1, 0, 0)),
"top": Plane(origin, (1, 0, 0), (0, 1, 0)),
"bottom": Plane(origin, (1, 0, 0), (0, -1, 0)),
}
try:
return namedPlanes[stdName]
except KeyError:
raise ValueError("Supported names are {}".format(list(namedPlanes.keys())))
@classmethod
def XY(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)):
plane = Plane.named("XY", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def YZ(cls, origin=(0, 0, 0), xDir=Vector(0, 1, 0)):
plane = Plane.named("YZ", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def ZX(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)):
plane = Plane.named("ZX", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def XZ(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)):
plane = Plane.named("XZ", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def YX(cls, origin=(0, 0, 0), xDir=Vector(0, 1, 0)):
plane = Plane.named("YX", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def ZY(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)):
plane = Plane.named("ZY", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def front(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)):
plane = Plane.named("front", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def back(cls, origin=(0, 0, 0), xDir=Vector(-1, 0, 0)):
plane = Plane.named("back", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def left(cls, origin=(0, 0, 0), xDir=Vector(0, 0, 1)):
plane = Plane.named("left", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def right(cls, origin=(0, 0, 0), xDir=Vector(0, 0, -1)):
plane = Plane.named("right", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def top(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)):
plane = Plane.named("top", origin)
plane._setPlaneDir(xDir)
return plane
@classmethod
def bottom(cls, origin=(0, 0, 0), xDir=Vector(1, 0, 0)):
plane = Plane.named("bottom", origin)
plane._setPlaneDir(xDir)
return plane
def __init__(
self,
origin: Union[Tuple[float, float, float], Vector],
xDir: Optional[Union[Tuple[float, float, float], Vector]] = None,
normal: Union[Tuple[float, float, float], Vector] = (0, 0, 1),
):
"""
Create a Plane with an arbitrary orientation
:param origin: the origin in global coordinates
:param xDir: an optional vector representing the xDirection.
:param normal: the normal direction for the plane
:raises ValueError: if the specified xDir is not orthogonal to the provided normal
"""
zDir = Vector(normal)
if zDir.Length == 0.0:
raise ValueError("normal should be non null")
self.zDir = zDir.normalized()
if xDir is None:
ax3 = gp_Ax3(Vector(origin).toPnt(), Vector(normal).toDir())
xDir = Vector(ax3.XDirection())
else:
xDir = Vector(xDir)
if xDir.Length == 0.0:
raise ValueError("xDir should be non null")
self._setPlaneDir(xDir)
self.origin = Vector(origin)
def _eq_iter(self, other):
"""Iterator to successively test equality"""
cls = type(self)
yield isinstance(other, Plane) # comparison is with another Plane
# origins are the same
yield abs(self.origin - other.origin) < cls._eq_tolerance_origin
# z-axis vectors are parallel (assumption: both are unit vectors)
yield abs(self.zDir.dot(other.zDir) - 1) < cls._eq_tolerance_dot
# x-axis vectors are parallel (assumption: both are unit vectors)
yield abs(self.xDir.dot(other.xDir) - 1) < cls._eq_tolerance_dot
def __eq__(self, other):
return all(self._eq_iter(other))
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return f"Plane(origin={str(self.origin.toTuple())}, xDir={str(self.xDir.toTuple())}, normal={str(self.zDir.toTuple())})"
@property
def origin(self) -> Vector:
return self._origin
@origin.setter
def origin(self, value):
self._origin = Vector(value)
self._calcTransforms()
def setOrigin2d(self, x, y):
"""
Set a new origin in the plane itself
Set a new origin in the plane itself. The plane's orientation and
xDrection are unaffected.
:param float x: offset in the x direction
:param float y: offset in the y direction
:return: void
The new coordinates are specified in terms of the current 2D system.
As an example:
p = Plane.XY()
p.setOrigin2d(2, 2)
p.setOrigin2d(2, 2)
results in a plane with its origin at (x, y) = (4, 4) in global
coordinates. Both operations were relative to local coordinates of the
plane.
"""
self.origin = self.toWorldCoords((x, y))
def toLocalCoords(self, obj):
"""Project the provided coordinates onto this plane
:param obj: an object or vector to convert
:type vector: a vector or shape
:return: an object of the same type, but converted to local coordinates
Most of the time, the z-coordinate returned will be zero, because most
operations based on a plane are all 2D. Occasionally, though, 3D
points outside of the current plane are transformed. One such example is
:py:meth:`Workplane.box`, where 3D corners of a box are transformed to
orient the box in space correctly.
"""
from .shapes import Shape
if isinstance(obj, Vector):
return obj.transform(self.fG)
elif isinstance(obj, Shape):
return obj.transformShape(self.fG)
else:
raise ValueError(
"Don't know how to convert type {} to local coordinates".format(
type(obj)
)
)
def toWorldCoords(self, tuplePoint) -> Vector:
"""Convert a point in local coordinates to global coordinates
:param tuplePoint: point in local coordinates to convert.
:type tuplePoint: a 2 or three tuple of float. The third value is taken to be zero if not supplied.
:return: a Vector in global coordinates
"""
if isinstance(tuplePoint, Vector):
v = tuplePoint
elif len(tuplePoint) == 2:
v = Vector(tuplePoint[0], tuplePoint[1], 0)
else:
v = Vector(tuplePoint)
return v.transform(self.rG)
def rotated(self, rotate=(0, 0, 0)):
"""Returns a copy of this plane, rotated about the specified axes
Since the z axis is always normal the plane, rotating around Z will
always produce a plane that is parallel to this one.
The origin of the workplane is unaffected by the rotation.
Rotations are done in order x, y, z. If you need a different order,
manually chain together multiple rotate() commands.
:param rotate: Vector [xDegrees, yDegrees, zDegrees]
:return: a copy of this plane rotated as requested.
"""
# NB: this is not a geometric Vector
rotate = Vector(rotate)
# Convert to radians.
rotate = rotate.multiply(math.pi / 180.0)
# Compute rotation matrix.
T1 = gp_Trsf()
T1.SetRotation(
gp_Ax1(gp_Pnt(*(0, 0, 0)), gp_Dir(*self.xDir.toTuple())), rotate.x
)
T2 = gp_Trsf()
T2.SetRotation(
gp_Ax1(gp_Pnt(*(0, 0, 0)), gp_Dir(*self.yDir.toTuple())), rotate.y
)
T3 = gp_Trsf()
T3.SetRotation(
gp_Ax1(gp_Pnt(*(0, 0, 0)), gp_Dir(*self.zDir.toTuple())), rotate.z
)
T = Matrix(gp_GTrsf(T1 * T2 * T3))
# Compute the new plane.
newXdir = self.xDir.transform(T)
newZdir = self.zDir.transform(T)
return Plane(self.origin, newXdir, newZdir)
def mirrorInPlane(self, listOfShapes, axis="X"):
local_coord_system = gp_Ax3(
self.origin.toPnt(), self.zDir.toDir(), self.xDir.toDir()
)
T = gp_Trsf()
if axis == "X":
T.SetMirror(gp_Ax1(self.origin.toPnt(), local_coord_system.XDirection()))
elif axis == "Y":
T.SetMirror(gp_Ax1(self.origin.toPnt(), local_coord_system.YDirection()))
else:
raise NotImplementedError
resultWires = []
for w in listOfShapes:
mirrored = w.transformShape(Matrix(T))
# attempt stitching of the wires
resultWires.append(mirrored)
return resultWires
def _setPlaneDir(self, xDir):
"""Set the vectors parallel to the plane, i.e. xDir and yDir"""
xDir = Vector(xDir)
self.xDir = xDir.normalized()
self.yDir = self.zDir.cross(self.xDir).normalized()
def _calcTransforms(self):
"""Computes transformation matrices to convert between coordinates
Computes transformation matrices to convert between local and global
coordinates.
"""
# r is the forward transformation matrix from world to local coordinates
# ok i will be really honest, i cannot understand exactly why this works
# something bout the order of the translation and the rotation.
# the double-inverting is strange, and I don't understand it.
forward = Matrix()
inverse = Matrix()
forwardT = gp_Trsf()
inverseT = gp_Trsf()
global_coord_system = gp_Ax3()
local_coord_system = gp_Ax3(
gp_Pnt(*self.origin.toTuple()),
gp_Dir(*self.zDir.toTuple()),
gp_Dir(*self.xDir.toTuple()),
)
forwardT.SetTransformation(global_coord_system, local_coord_system)
forward.wrapped = gp_GTrsf(forwardT)
inverseT.SetTransformation(local_coord_system, global_coord_system)
inverse.wrapped = gp_GTrsf(inverseT)
self.lcs = local_coord_system
self.rG = inverse
self.fG = forward
@property
def location(self) -> "Location":
return Location(self)
def toPln(self) -> gp_Pln:
return gp_Pln(gp_Ax3(self.origin.toPnt(), self.zDir.toDir(), self.xDir.toDir()))
class BoundBox(object):
"""A BoundingBox for an object or set of objects. Wraps the OCP one"""
wrapped: Bnd_Box
xmin: float
xmax: float
xlen: float
ymin: float
ymax: float
ylen: float
zmin: float
zmax: float
zlen: float
center: Vector
DiagonalLength: float
def __init__(self, bb: Bnd_Box) -> None:
self.wrapped = bb
XMin, YMin, ZMin, XMax, YMax, ZMax = bb.Get()
self.xmin = XMin
self.xmax = XMax
self.xlen = XMax - XMin
self.ymin = YMin
self.ymax = YMax
self.ylen = YMax - YMin
self.zmin = ZMin
self.zmax = ZMax
self.zlen = ZMax - ZMin
self.center = Vector((XMax + XMin) / 2, (YMax + YMin) / 2, (ZMax + ZMin) / 2)
self.DiagonalLength = self.wrapped.SquareExtent() ** 0.5
def add(
self,
obj: Union[Tuple[float, float, float], Vector, "BoundBox"],
tol: Optional[float] = None,
) -> "BoundBox":
"""Returns a modified (expanded) bounding box
obj can be one of several things:
1. a 3-tuple corresponding to x,y, and z amounts to add
2. a vector, containing the x,y,z values to add
3. another bounding box, where a new box will be created that
encloses both.
This bounding box is not changed.
"""
tol = TOL if tol is None else tol # tol = TOL (by default)
tmp = Bnd_Box()
tmp.SetGap(tol)
tmp.Add(self.wrapped)
if isinstance(obj, tuple):
tmp.Update(*obj)
elif isinstance(obj, Vector):
tmp.Update(*obj.toTuple())
elif isinstance(obj, BoundBox):
tmp.Add(obj.wrapped)
return BoundBox(tmp)
@staticmethod
def findOutsideBox2D(bb1: "BoundBox", bb2: "BoundBox") -> Optional["BoundBox"]:
"""Compares bounding boxes
Compares bounding boxes. Returns none if neither is inside the other.
Returns the outer one if either is outside the other.
BoundBox.isInside works in 3d, but this is a 2d bounding box, so it
doesn't work correctly plus, there was all kinds of rounding error in
the built-in implementation i do not understand.
"""
if (
bb1.xmin < bb2.xmin
and bb1.xmax > bb2.xmax
and bb1.ymin < bb2.ymin
and bb1.ymax > bb2.ymax
):
return bb1
if (
bb2.xmin < bb1.xmin
and bb2.xmax > bb1.xmax
and bb2.ymin < bb1.ymin
and bb2.ymax > bb1.ymax
):
return bb2
return None
@classmethod
def _fromTopoDS(
cls: Type["BoundBox"],
shape: TopoDS_Shape,
tol: Optional[float] = None,
optimal: bool = True,
):
"""
Constructs a bounding box from a TopoDS_Shape
"""
tol = TOL if tol is None else tol # tol = TOL (by default)
bbox = Bnd_Box()
if optimal:
BRepBndLib.AddOptimal_s(
shape, bbox
) # this is 'exact' but expensive - not yet wrapped by PythonOCC
else:
mesh = BRepMesh_IncrementalMesh(shape, tol, True)
mesh.Perform()
# this is adds +margin but is faster
BRepBndLib.Add_s(shape, bbox, True)
return cls(bbox)
def isInside(self, b2: "BoundBox") -> bool:
"""Is the provided bounding box inside this one?"""
if (
b2.xmin > self.xmin
and b2.ymin > self.ymin
and b2.zmin > self.zmin
and b2.xmax < self.xmax
and b2.ymax < self.ymax
and b2.zmax < self.zmax
):
return True
else:
return False
class Location(object):
"""Location in 3D space. Depending on usage can be absolute or relative.
This class wraps the TopLoc_Location class from OCCT. It can be used to move Shape
objects in both relative and absolute manner. It is the preferred type to locate objects
in CQ.
"""
wrapped: TopLoc_Location
@overload
def __init__(self) -> None:
"""Empty location with not rotation or translation with respect to the original location."""
...
@overload
def __init__(self, t: VectorLike) -> None:
"""Location with translation t with respect to the original location."""
...
@overload
def __init__(self, t: Plane) -> None:
"""Location corresponding to the location of the Plane t."""
...
@overload
def __init__(self, t: Plane, v: VectorLike) -> None:
"""Location corresponding to the angular location of the Plane t with translation v."""
...
@overload
def __init__(self, t: TopLoc_Location) -> None:
"""Location wrapping the low-level TopLoc_Location object t"""
...
@overload
def __init__(self, t: gp_Trsf) -> None:
"""Location wrapping the low-level gp_Trsf object t"""
...
@overload
def __init__(self, t: VectorLike, ax: VectorLike, angle: float) -> None:
"""Location with translation t and rotation around ax by angle
with respect to the original location."""
...
def __init__(self, *args):
T = gp_Trsf()
if len(args) == 0:
pass
elif len(args) == 1:
t = args[0]
if isinstance(t, (Vector, tuple)):
T.SetTranslationPart(Vector(t).wrapped)
elif isinstance(t, Plane):
cs = gp_Ax3(t.origin.toPnt(), t.zDir.toDir(), t.xDir.toDir())
T.SetTransformation(cs)
T.Invert()
elif isinstance(t, TopLoc_Location):
self.wrapped = t
return
elif isinstance(t, gp_Trsf):
T = t
else:
raise TypeError("Unexpected parameters")
elif len(args) == 2:
t, v = args
cs = gp_Ax3(Vector(v).toPnt(), t.zDir.toDir(), t.xDir.toDir())
T.SetTransformation(cs)
T.Invert()
else:
t, ax, angle = args
T.SetRotation(
gp_Ax1(Vector().toPnt(), Vector(ax).toDir()), angle * math.pi / 180.0
)
T.SetTranslationPart(Vector(t).wrapped)
self.wrapped = TopLoc_Location(T)
@property
def inverse(self) -> "Location":
return Location(self.wrapped.Inverted())
def __mul__(self, other: "Location") -> "Location":
return Location(self.wrapped * other.wrapped)
def __pow__(self, exponent: int) -> "Location":
return Location(self.wrapped.Powered(exponent))
def toTuple(self) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
"""Convert the location to a translation, rotation tuple."""
T = self.wrapped.Transformation()
trans = T.TranslationPart()
rot = T.GetRotation()
rv_trans = (trans.X(), trans.Y(), trans.Z())
rv_rot = rot.GetEulerAngles(gp_EulerSequence.gp_Extrinsic_XYZ)
return rv_trans, rv_rot
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,518 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/shapes.py | from typing import (
Optional,
Tuple,
Union,
Iterable,
List,
Sequence,
Iterator,
Dict,
Any,
overload,
TypeVar,
cast as tcast,
)
from typing_extensions import Literal, Protocol
from io import BytesIO
from vtkmodules.vtkCommonDataModel import vtkPolyData
from vtkmodules.vtkFiltersCore import vtkTriangleFilter, vtkPolyDataNormals
from .geom import Vector, VectorLike, BoundBox, Plane, Location, Matrix
from ..utils import cqmultimethod as multimethod
import OCP.TopAbs as ta # Topology type enum
import OCP.GeomAbs as ga # Geometry type enum
from OCP.Precision import Precision
from OCP.gp import (
gp_Vec,
gp_Pnt,
gp_Ax1,
gp_Ax2,
gp_Ax3,
gp_Dir,
gp_Circ,
gp_Trsf,
gp_Pln,
gp_Pnt2d,
gp_Dir2d,
gp_Elips,
)
# Array of points (used for B-spline construction):
from OCP.TColgp import TColgp_HArray1OfPnt, TColgp_HArray2OfPnt
# Array of vectors (used for B-spline interpolation):
from OCP.TColgp import TColgp_Array1OfVec
# Array of booleans (used for B-spline interpolation):
from OCP.TColStd import TColStd_HArray1OfBoolean
# Array of floats (used for B-spline interpolation):
from OCP.TColStd import TColStd_HArray1OfReal
from OCP.BRepAdaptor import (
BRepAdaptor_Curve,
BRepAdaptor_CompCurve,
BRepAdaptor_Surface,
)
from OCP.BRepBuilderAPI import (
BRepBuilderAPI_MakeVertex,
BRepBuilderAPI_MakeEdge,
BRepBuilderAPI_MakeFace,
BRepBuilderAPI_MakePolygon,
BRepBuilderAPI_MakeWire,
BRepBuilderAPI_Sewing,
BRepBuilderAPI_Copy,
BRepBuilderAPI_GTransform,
BRepBuilderAPI_Transform,
BRepBuilderAPI_Transformed,
BRepBuilderAPI_RightCorner,
BRepBuilderAPI_RoundCorner,
BRepBuilderAPI_MakeSolid,
)
# properties used to store mass calculation result
from OCP.GProp import GProp_GProps
from OCP.BRepGProp import BRepGProp_Face, BRepGProp # used for mass calculation
from OCP.BRepPrimAPI import (
BRepPrimAPI_MakeBox,
BRepPrimAPI_MakeCone,
BRepPrimAPI_MakeCylinder,
BRepPrimAPI_MakeTorus,
BRepPrimAPI_MakeWedge,
BRepPrimAPI_MakePrism,
BRepPrimAPI_MakeRevol,
BRepPrimAPI_MakeSphere,
)
from OCP.BRepIntCurveSurface import BRepIntCurveSurface_Inter
from OCP.TopExp import TopExp_Explorer # Topology explorer
# used for getting underlying geometry -- is this equivalent to brep adaptor?
from OCP.BRep import BRep_Tool, BRep_Builder
from OCP.TopoDS import (
TopoDS,
TopoDS_Shape,
TopoDS_Builder,
TopoDS_Compound,
TopoDS_Iterator,
TopoDS_Wire,
TopoDS_Face,
TopoDS_Edge,
TopoDS_Vertex,
TopoDS_Solid,
TopoDS_Shell,
TopoDS_CompSolid,
)
from OCP.GC import GC_MakeArcOfCircle, GC_MakeArcOfEllipse # geometry construction
from OCP.GCE2d import GCE2d_MakeSegment
from OCP.gce import gce_MakeLin, gce_MakeDir
from OCP.GeomAPI import (
GeomAPI_Interpolate,
GeomAPI_ProjectPointOnSurf,
GeomAPI_PointsToBSpline,
GeomAPI_PointsToBSplineSurface,
)
from OCP.BRepFill import BRepFill
from OCP.BRepAlgoAPI import (
BRepAlgoAPI_Common,
BRepAlgoAPI_Fuse,
BRepAlgoAPI_Cut,
BRepAlgoAPI_BooleanOperation,
BRepAlgoAPI_Splitter,
)
from OCP.Geom import (
Geom_ConicalSurface,
Geom_CylindricalSurface,
Geom_Surface,
Geom_Plane,
)
from OCP.Geom2d import Geom2d_Line
from OCP.BRepLib import BRepLib, BRepLib_FindSurface
from OCP.BRepOffsetAPI import (
BRepOffsetAPI_ThruSections,
BRepOffsetAPI_MakePipeShell,
BRepOffsetAPI_MakeThickSolid,
BRepOffsetAPI_MakeOffset,
)
from OCP.BRepFilletAPI import (
BRepFilletAPI_MakeChamfer,
BRepFilletAPI_MakeFillet,
BRepFilletAPI_MakeFillet2d,
)
from OCP.TopTools import (
TopTools_IndexedDataMapOfShapeListOfShape,
TopTools_ListOfShape,
TopTools_MapOfShape,
)
from OCP.TopExp import TopExp
from OCP.ShapeFix import ShapeFix_Shape, ShapeFix_Solid, ShapeFix_Face
from OCP.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.StlAPI import StlAPI_Writer
from OCP.ShapeUpgrade import ShapeUpgrade_UnifySameDomain
from OCP.BRepTools import BRepTools
from OCP.LocOpe import LocOpe_DPrism
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.Font import (
Font_FontMgr,
Font_FA_Regular,
Font_FA_Italic,
Font_FA_Bold,
Font_SystemFont,
)
from OCP.StdPrs import StdPrs_BRepFont, StdPrs_BRepTextBuilder as Font_BRepTextBuilder
from OCP.NCollection import NCollection_Utf8String
from OCP.BRepFeat import BRepFeat_MakeDPrism
from OCP.BRepClass3d import BRepClass3d_SolidClassifier
from OCP.TCollection import TCollection_AsciiString
from OCP.TopLoc import TopLoc_Location
from OCP.GeomAbs import (
GeomAbs_Shape,
GeomAbs_C0,
GeomAbs_Intersection,
GeomAbs_JoinType,
)
from OCP.BRepOffsetAPI import BRepOffsetAPI_MakeFilling
from OCP.BRepOffset import BRepOffset_MakeOffset, BRepOffset_Mode
from OCP.BOPAlgo import BOPAlgo_GlueEnum
from OCP.IFSelect import IFSelect_ReturnStatus
from OCP.TopAbs import TopAbs_ShapeEnum, TopAbs_Orientation
from OCP.ShapeAnalysis import ShapeAnalysis_FreeBounds
from OCP.TopTools import TopTools_HSequenceOfShape
from OCP.GCPnts import GCPnts_AbscissaPoint
from OCP.GeomFill import (
GeomFill_Frenet,
GeomFill_CorrectedFrenet,
GeomFill_TrihedronLaw,
)
from OCP.BRepProj import BRepProj_Projection
from OCP.BRepExtrema import BRepExtrema_DistShapeShape
from OCP.IVtkOCC import IVtkOCC_Shape, IVtkOCC_ShapeMesher
from OCP.IVtkVTK import IVtkVTK_ShapeData
# for catching exceptions
from OCP.Standard import Standard_NoSuchObject, Standard_Failure
from OCP.Prs3d import Prs3d_IsoAspect
from OCP.Quantity import Quantity_Color
from OCP.Aspect import Aspect_TOL_SOLID
from OCP.Interface import Interface_Static
from OCP.ShapeCustom import ShapeCustom, ShapeCustom_RestrictionParameters
from OCP.BRepAlgo import BRepAlgo
from math import pi, sqrt, inf, radians, cos
import warnings
from ..utils import deprecate
Real = Union[float, int]
TOLERANCE = 1e-6
HASH_CODE_MAX = 2147483647 # max 32bit signed int, required by OCC.Core.HashCode
shape_LUT = {
ta.TopAbs_VERTEX: "Vertex",
ta.TopAbs_EDGE: "Edge",
ta.TopAbs_WIRE: "Wire",
ta.TopAbs_FACE: "Face",
ta.TopAbs_SHELL: "Shell",
ta.TopAbs_SOLID: "Solid",
ta.TopAbs_COMPSOLID: "CompSolid",
ta.TopAbs_COMPOUND: "Compound",
}
shape_properties_LUT = {
ta.TopAbs_VERTEX: None,
ta.TopAbs_EDGE: BRepGProp.LinearProperties_s,
ta.TopAbs_WIRE: BRepGProp.LinearProperties_s,
ta.TopAbs_FACE: BRepGProp.SurfaceProperties_s,
ta.TopAbs_SHELL: BRepGProp.SurfaceProperties_s,
ta.TopAbs_SOLID: BRepGProp.VolumeProperties_s,
ta.TopAbs_COMPOUND: BRepGProp.VolumeProperties_s,
}
inverse_shape_LUT = {v: k for k, v in shape_LUT.items()}
downcast_LUT = {
ta.TopAbs_VERTEX: TopoDS.Vertex_s,
ta.TopAbs_EDGE: TopoDS.Edge_s,
ta.TopAbs_WIRE: TopoDS.Wire_s,
ta.TopAbs_FACE: TopoDS.Face_s,
ta.TopAbs_SHELL: TopoDS.Shell_s,
ta.TopAbs_SOLID: TopoDS.Solid_s,
ta.TopAbs_COMPSOLID: TopoDS.CompSolid_s,
ta.TopAbs_COMPOUND: TopoDS.Compound_s,
}
geom_LUT = {
ta.TopAbs_VERTEX: "Vertex",
ta.TopAbs_EDGE: BRepAdaptor_Curve,
ta.TopAbs_WIRE: "Wire",
ta.TopAbs_FACE: BRepAdaptor_Surface,
ta.TopAbs_SHELL: "Shell",
ta.TopAbs_SOLID: "Solid",
ta.TopAbs_SOLID: "CompSolid",
ta.TopAbs_COMPOUND: "Compound",
}
geom_LUT_FACE = {
ga.GeomAbs_Plane: "PLANE",
ga.GeomAbs_Cylinder: "CYLINDER",
ga.GeomAbs_Cone: "CONE",
ga.GeomAbs_Sphere: "SPHERE",
ga.GeomAbs_Torus: "TORUS",
ga.GeomAbs_BezierSurface: "BEZIER",
ga.GeomAbs_BSplineSurface: "BSPLINE",
ga.GeomAbs_SurfaceOfRevolution: "REVOLUTION",
ga.GeomAbs_SurfaceOfExtrusion: "EXTRUSION",
ga.GeomAbs_OffsetSurface: "OFFSET",
ga.GeomAbs_OtherSurface: "OTHER",
}
geom_LUT_EDGE = {
ga.GeomAbs_Line: "LINE",
ga.GeomAbs_Circle: "CIRCLE",
ga.GeomAbs_Ellipse: "ELLIPSE",
ga.GeomAbs_Hyperbola: "HYPERBOLA",
ga.GeomAbs_Parabola: "PARABOLA",
ga.GeomAbs_BezierCurve: "BEZIER",
ga.GeomAbs_BSplineCurve: "BSPLINE",
ga.GeomAbs_OffsetCurve: "OFFSET",
ga.GeomAbs_OtherCurve: "OTHER",
}
Shapes = Literal[
"Vertex", "Edge", "Wire", "Face", "Shell", "Solid", "CompSolid", "Compound"
]
Geoms = Literal[
"Vertex",
"Wire",
"Shell",
"Solid",
"Compound",
"PLANE",
"CYLINDER",
"CONE",
"SPHERE",
"TORUS",
"BEZIER",
"BSPLINE",
"REVOLUTION",
"EXTRUSION",
"OFFSET",
"OTHER",
"LINE",
"CIRCLE",
"ELLIPSE",
"HYPERBOLA",
"PARABOLA",
]
T = TypeVar("T", bound="Shape")
def shapetype(obj: TopoDS_Shape) -> TopAbs_ShapeEnum:
if obj.IsNull():
raise ValueError("Null TopoDS_Shape object")
return obj.ShapeType()
def downcast(obj: TopoDS_Shape) -> TopoDS_Shape:
"""
Downcasts a TopoDS object to suitable specialized type
"""
f_downcast: Any = downcast_LUT[shapetype(obj)]
rv = f_downcast(obj)
return rv
def fix(obj: TopoDS_Shape) -> TopoDS_Shape:
"""
Fix a TopoDS object to suitable specialized type
"""
sf = ShapeFix_Shape(obj)
sf.Perform()
return downcast(sf.Shape())
class Shape(object):
"""
Represents a shape in the system. Wraps TopoDS_Shape.
"""
wrapped: TopoDS_Shape
forConstruction: bool
def __init__(self, obj: TopoDS_Shape):
self.wrapped = downcast(obj)
self.forConstruction = False
# Helps identify this solid through the use of an ID
self.label = ""
def clean(self: T) -> T:
"""Experimental clean using ShapeUpgrade"""
upgrader = ShapeUpgrade_UnifySameDomain(self.wrapped, True, True, True)
upgrader.AllowInternalEdges(False)
upgrader.Build()
return self.__class__(upgrader.Shape())
def fix(self: T) -> T:
"""Try to fix shape if not valid"""
if not self.isValid():
fixed = fix(self.wrapped)
return self.__class__(fixed)
return self
@classmethod
def cast(cls, obj: TopoDS_Shape, forConstruction: bool = False) -> "Shape":
"Returns the right type of wrapper, given a OCCT object"
tr = None
# define the shape lookup table for casting
constructor_LUT = {
ta.TopAbs_VERTEX: Vertex,
ta.TopAbs_EDGE: Edge,
ta.TopAbs_WIRE: Wire,
ta.TopAbs_FACE: Face,
ta.TopAbs_SHELL: Shell,
ta.TopAbs_SOLID: Solid,
ta.TopAbs_COMPSOLID: CompSolid,
ta.TopAbs_COMPOUND: Compound,
}
t = shapetype(obj)
# NB downcast is needed to handle TopoDS_Shape types
tr = constructor_LUT[t](downcast(obj))
tr.forConstruction = forConstruction
return tr
def exportStl(
self,
fileName: str,
tolerance: float = 1e-3,
angularTolerance: float = 0.1,
ascii: bool = False,
) -> bool:
"""
Exports a shape to a specified STL file.
:param fileName: The path and file name to write the STL output to.
:param tolerance: A linear deflection setting which limits the distance between a curve and its tessellation.
Setting this value too low will result in large meshes that can consume computing resources.
Setting the value too high can result in meshes with a level of detail that is too low.
Default is 1e-3, which is a good starting point for a range of cases.
:param angularTolerance: Angular deflection setting which limits the angle between subsequent segments in a polyline. Default is 0.1.
:param ascii: Export the file as ASCII (True) or binary (False) STL format. Default is binary.
"""
mesh = BRepMesh_IncrementalMesh(self.wrapped, tolerance, True, angularTolerance)
mesh.Perform()
writer = StlAPI_Writer()
if ascii:
writer.ASCIIMode = True
else:
writer.ASCIIMode = False
return writer.Write(self.wrapped, fileName)
def exportStep(self, fileName: str, **kwargs) -> IFSelect_ReturnStatus:
"""
Export this shape to a STEP file.
kwargs is used to provide optional keyword arguments to configure the exporter.
:param fileName: Path and filename for writing.
:param write_pcurves: Enable or disable writing parametric curves to the STEP file. Default True.
If False, writes STEP file without pcurves. This decreases the size of the resulting STEP file.
:type write_pcurves: bool
:param precision_mode: Controls the uncertainty value for STEP entities. Specify -1, 0, or 1. Default 0.
See OCCT documentation.
:type precision_mode: int
"""
# Handle the extra settings for the STEP export
pcurves = 1
if "write_pcurves" in kwargs and not kwargs["write_pcurves"]:
pcurves = 0
precision_mode = kwargs["precision_mode"] if "precision_mode" in kwargs else 0
writer = STEPControl_Writer()
Interface_Static.SetIVal_s("write.surfacecurve.mode", pcurves)
Interface_Static.SetIVal_s("write.precision.mode", precision_mode)
writer.Transfer(self.wrapped, STEPControl_AsIs)
return writer.Write(fileName)
def exportBrep(self, f: Union[str, BytesIO]) -> bool:
"""
Export this shape to a BREP file
"""
rv = BRepTools.Write_s(self.wrapped, f)
return True if rv is None else rv
@classmethod
def importBrep(cls, f: Union[str, BytesIO]) -> "Shape":
"""
Import shape from a BREP file
"""
s = TopoDS_Shape()
builder = BRep_Builder()
BRepTools.Read_s(s, f, builder)
if s.IsNull():
raise ValueError(f"Could not import {f}")
return cls.cast(s)
def geomType(self) -> Geoms:
"""
Gets the underlying geometry type.
Implementations can return any values desired, but the values the user
uses in type filters should correspond to these.
As an example, if a user does::
CQ(object).faces("%mytype")
The expectation is that the geomType attribute will return 'mytype'
The return values depend on the type of the shape:
| Vertex: always 'Vertex'
| Edge: LINE, CIRCLE, ELLIPSE, HYPERBOLA, PARABOLA, BEZIER,
| BSPLINE, OFFSET, OTHER
| Face: PLANE, CYLINDER, CONE, SPHERE, TORUS, BEZIER, BSPLINE,
| REVOLUTION, EXTRUSION, OFFSET, OTHER
| Solid: 'Solid'
| Shell: 'Shell'
| Compound: 'Compound'
| Wire: 'Wire'
:returns: A string according to the geometry type
"""
tr: Any = geom_LUT[shapetype(self.wrapped)]
if isinstance(tr, str):
rv = tr
elif tr is BRepAdaptor_Curve:
rv = geom_LUT_EDGE[tr(self.wrapped).GetType()]
else:
rv = geom_LUT_FACE[tr(self.wrapped).GetType()]
return tcast(Geoms, rv)
def hashCode(self) -> int:
"""
Returns a hashed value denoting this shape. It is computed from the
TShape and the Location. The Orientation is not used.
"""
return self.wrapped.HashCode(HASH_CODE_MAX)
def isNull(self) -> bool:
"""
Returns true if this shape is null. In other words, it references no
underlying shape with the potential to be given a location and an
orientation.
"""
return self.wrapped.IsNull()
def isSame(self, other: "Shape") -> bool:
"""
Returns True if other and this shape are same, i.e. if they share the
same TShape with the same Locations. Orientations may differ. Also see
:py:meth:`isEqual`
"""
return self.wrapped.IsSame(other.wrapped)
def isEqual(self, other: "Shape") -> bool:
"""
Returns True if two shapes are equal, i.e. if they share the same
TShape with the same Locations and Orientations. Also see
:py:meth:`isSame`.
"""
return self.wrapped.IsEqual(other.wrapped)
def isValid(self) -> bool:
"""
Returns True if no defect is detected on the shape S or any of its
subshapes. See the OCCT docs on BRepCheck_Analyzer::IsValid for a full
description of what is checked.
"""
return BRepCheck_Analyzer(self.wrapped).IsValid()
def BoundingBox(
self, tolerance: Optional[float] = None
) -> BoundBox: # need to implement that in GEOM
"""
Create a bounding box for this Shape.
:param tolerance: Tolerance value passed to :class:`BoundBox`
:returns: A :class:`BoundBox` object for this Shape
"""
return BoundBox._fromTopoDS(self.wrapped, tol=tolerance)
def mirror(
self,
mirrorPlane: Union[
Literal["XY", "YX", "XZ", "ZX", "YZ", "ZY"], VectorLike
] = "XY",
basePointVector: VectorLike = (0, 0, 0),
) -> "Shape":
"""
Applies a mirror transform to this Shape. Does not duplicate objects
about the plane.
:param mirrorPlane: The direction of the plane to mirror about - one of
'XY', 'XZ' or 'YZ'
:param basePointVector: The origin of the plane to mirror about
:returns: The mirrored shape
"""
if isinstance(mirrorPlane, str):
if mirrorPlane == "XY" or mirrorPlane == "YX":
mirrorPlaneNormalVector = gp_Dir(0, 0, 1)
elif mirrorPlane == "XZ" or mirrorPlane == "ZX":
mirrorPlaneNormalVector = gp_Dir(0, 1, 0)
elif mirrorPlane == "YZ" or mirrorPlane == "ZY":
mirrorPlaneNormalVector = gp_Dir(1, 0, 0)
else:
if isinstance(mirrorPlane, tuple):
mirrorPlaneNormalVector = gp_Dir(*mirrorPlane)
elif isinstance(mirrorPlane, Vector):
mirrorPlaneNormalVector = mirrorPlane.toDir()
if isinstance(basePointVector, tuple):
basePointVector = Vector(basePointVector)
T = gp_Trsf()
T.SetMirror(gp_Ax2(gp_Pnt(*basePointVector.toTuple()), mirrorPlaneNormalVector))
return self._apply_transform(T)
@staticmethod
def _center_of_mass(shape: "Shape") -> Vector:
Properties = GProp_GProps()
BRepGProp.VolumeProperties_s(shape.wrapped, Properties)
return Vector(Properties.CentreOfMass())
def Center(self) -> Vector:
"""
:returns: The point of the center of mass of this Shape
"""
return Shape.centerOfMass(self)
def CenterOfBoundBox(self, tolerance: Optional[float] = None) -> Vector:
"""
:param tolerance: Tolerance passed to the :py:meth:`BoundingBox` method
:returns: Center of the bounding box of this shape
"""
return self.BoundingBox(tolerance=tolerance).center
@staticmethod
def CombinedCenter(objects: Iterable["Shape"]) -> Vector:
"""
Calculates the center of mass of multiple objects.
:param objects: A list of objects with mass
"""
total_mass = sum(Shape.computeMass(o) for o in objects)
weighted_centers = [
Shape.centerOfMass(o).multiply(Shape.computeMass(o)) for o in objects
]
sum_wc = weighted_centers[0]
for wc in weighted_centers[1:]:
sum_wc = sum_wc.add(wc)
return Vector(sum_wc.multiply(1.0 / total_mass))
@staticmethod
def computeMass(obj: "Shape") -> float:
"""
Calculates the 'mass' of an object.
:param obj: Compute the mass of this object
"""
Properties = GProp_GProps()
calc_function = shape_properties_LUT[shapetype(obj.wrapped)]
if calc_function:
calc_function(obj.wrapped, Properties)
return Properties.Mass()
else:
raise NotImplementedError
@staticmethod
def centerOfMass(obj: "Shape") -> Vector:
"""
Calculates the center of 'mass' of an object.
:param obj: Compute the center of mass of this object
"""
Properties = GProp_GProps()
calc_function = shape_properties_LUT[shapetype(obj.wrapped)]
if calc_function:
calc_function(obj.wrapped, Properties)
return Vector(Properties.CentreOfMass())
else:
raise NotImplementedError
@staticmethod
def CombinedCenterOfBoundBox(objects: List["Shape"]) -> Vector:
"""
Calculates the center of a bounding box of multiple objects.
:param objects: A list of objects
"""
total_mass = len(objects)
weighted_centers = []
for o in objects:
weighted_centers.append(BoundBox._fromTopoDS(o.wrapped).center)
sum_wc = weighted_centers[0]
for wc in weighted_centers[1:]:
sum_wc = sum_wc.add(wc)
return Vector(sum_wc.multiply(1.0 / total_mass))
def Closed(self) -> bool:
"""
:returns: The closedness flag
"""
return self.wrapped.Closed()
def ShapeType(self) -> Shapes:
return tcast(Shapes, shape_LUT[shapetype(self.wrapped)])
def _entities(self, topo_type: Shapes) -> List[TopoDS_Shape]:
rv = []
shape_set = TopTools_MapOfShape()
explorer = TopExp_Explorer(self.wrapped, inverse_shape_LUT[topo_type])
while explorer.More():
item = explorer.Current()
# needed to avoid pseudo-duplicate entities
if shape_set.Add(item):
rv.append(item)
explorer.Next()
return rv
def _entitiesFrom(
self, child_type: Shapes, parent_type: Shapes
) -> Dict["Shape", List["Shape"]]:
res = TopTools_IndexedDataMapOfShapeListOfShape()
TopTools_IndexedDataMapOfShapeListOfShape()
TopExp.MapShapesAndAncestors_s(
self.wrapped,
inverse_shape_LUT[child_type],
inverse_shape_LUT[parent_type],
res,
)
out: Dict[Shape, List[Shape]] = {}
for i in range(1, res.Extent() + 1):
out[Shape.cast(res.FindKey(i))] = [
Shape.cast(el) for el in res.FindFromIndex(i)
]
return out
def Vertices(self) -> List["Vertex"]:
"""
:returns: All the vertices in this Shape
"""
return [Vertex(i) for i in self._entities("Vertex")]
def Edges(self) -> List["Edge"]:
"""
:returns: All the edges in this Shape
"""
return [
Edge(i)
for i in self._entities("Edge")
if not BRep_Tool.Degenerated_s(TopoDS.Edge_s(i))
]
def Compounds(self) -> List["Compound"]:
"""
:returns: All the compounds in this Shape
"""
return [Compound(i) for i in self._entities("Compound")]
def Wires(self) -> List["Wire"]:
"""
:returns: All the wires in this Shape
"""
return [Wire(i) for i in self._entities("Wire")]
def Faces(self) -> List["Face"]:
"""
:returns: All the faces in this Shape
"""
return [Face(i) for i in self._entities("Face")]
def Shells(self) -> List["Shell"]:
"""
:returns: All the shells in this Shape
"""
return [Shell(i) for i in self._entities("Shell")]
def Solids(self) -> List["Solid"]:
"""
:returns: All the solids in this Shape
"""
return [Solid(i) for i in self._entities("Solid")]
def CompSolids(self) -> List["CompSolid"]:
"""
:returns: All the compsolids in this Shape
"""
return [CompSolid(i) for i in self._entities("CompSolid")]
def Area(self) -> float:
"""
:returns: The surface area of all faces in this Shape
"""
Properties = GProp_GProps()
BRepGProp.SurfaceProperties_s(self.wrapped, Properties)
return Properties.Mass()
def Volume(self) -> float:
"""
:returns: The volume of this Shape
"""
# when density == 1, mass == volume
return Shape.computeMass(self)
def _apply_transform(self: T, Tr: gp_Trsf) -> T:
return self.__class__(BRepBuilderAPI_Transform(self.wrapped, Tr, True).Shape())
def rotate(
self: T, startVector: VectorLike, endVector: VectorLike, angleDegrees: float
) -> T:
"""
Rotates a shape around an axis.
:param startVector: start point of rotation axis
:type startVector: either a 3-tuple or a Vector
:param endVector: end point of rotation axis
:type endVector: either a 3-tuple or a Vector
:param angleDegrees: angle to rotate, in degrees
:returns: a copy of the shape, rotated
"""
if type(startVector) == tuple:
startVector = Vector(startVector)
if type(endVector) == tuple:
endVector = Vector(endVector)
Tr = gp_Trsf()
Tr.SetRotation(
gp_Ax1(
Vector(startVector).toPnt(),
(Vector(endVector) - Vector(startVector)).toDir(),
),
radians(angleDegrees),
)
return self._apply_transform(Tr)
def translate(self: T, vector: VectorLike) -> T:
"""
Translates this shape through a transformation.
"""
T = gp_Trsf()
T.SetTranslation(Vector(vector).wrapped)
return self._apply_transform(T)
def scale(self, factor: float) -> "Shape":
"""
Scales this shape through a transformation.
"""
T = gp_Trsf()
T.SetScale(gp_Pnt(), factor)
return self._apply_transform(T)
def copy(self: T, mesh: bool = False) -> T:
"""
Creates a new object that is a copy of this object.
:param mesh: should I copy the triangulation too (default: False)
:returns: a copy of the object
"""
return self.__class__(BRepBuilderAPI_Copy(self.wrapped, True, mesh).Shape())
def transformShape(self, tMatrix: Matrix) -> "Shape":
"""
Transforms this Shape by tMatrix. Also see :py:meth:`transformGeometry`.
:param tMatrix: The transformation matrix
:returns: a copy of the object, transformed by the provided matrix,
with all objects keeping their type
"""
r = Shape.cast(
BRepBuilderAPI_Transform(self.wrapped, tMatrix.wrapped.Trsf()).Shape()
)
r.forConstruction = self.forConstruction
return r
def transformGeometry(self, tMatrix: Matrix) -> "Shape":
"""
Transforms this shape by tMatrix.
WARNING: transformGeometry will sometimes convert lines and circles to
splines, but it also has the ability to handle skew and stretching
transformations.
If your transformation is only translation and rotation, it is safer to
use :py:meth:`transformShape`, which doesn't change the underlying type
of the geometry, but cannot handle skew transformations.
:param tMatrix: The transformation matrix
:returns: a copy of the object, but with geometry transformed instead
of just rotated.
"""
r = Shape.cast(
BRepBuilderAPI_GTransform(self.wrapped, tMatrix.wrapped, True).Shape()
)
r.forConstruction = self.forConstruction
return r
def location(self) -> Location:
"""
Return the current location
"""
return Location(self.wrapped.Location())
def locate(self: T, loc: Location) -> T:
"""
Apply a location in absolute sense to self
"""
self.wrapped.Location(loc.wrapped)
return self
def located(self: T, loc: Location) -> T:
"""
Apply a location in absolute sense to a copy of self
"""
r = self.__class__(self.wrapped.Located(loc.wrapped))
r.forConstruction = self.forConstruction
return r
def move(self: T, loc: Location) -> T:
"""
Apply a location in relative sense (i.e. update current location) to self
"""
self.wrapped.Move(loc.wrapped)
return self
def moved(self: T, loc: Location) -> T:
"""
Apply a location in relative sense (i.e. update current location) to a copy of self
"""
r = self.__class__(self.wrapped.Moved(loc.wrapped))
r.forConstruction = self.forConstruction
return r
def __hash__(self) -> int:
return self.hashCode()
def __eq__(self, other) -> bool:
return self.isSame(other) if isinstance(other, Shape) else False
def _bool_op(
self,
args: Iterable["Shape"],
tools: Iterable["Shape"],
op: Union[BRepAlgoAPI_BooleanOperation, BRepAlgoAPI_Splitter],
parallel: bool = True,
) -> "Shape":
"""
Generic boolean operation
:param parallel: Sets the SetRunParallel flag, which enables parallel execution of boolean operations in OCC kernel
"""
arg = TopTools_ListOfShape()
for obj in args:
arg.Append(obj.wrapped)
tool = TopTools_ListOfShape()
for obj in tools:
tool.Append(obj.wrapped)
op.SetArguments(arg)
op.SetTools(tool)
op.SetRunParallel(parallel)
op.Build()
return Shape.cast(op.Shape())
def cut(self, *toCut: "Shape", tol: Optional[float] = None) -> "Shape":
"""
Remove the positional arguments from this Shape.
:param tol: Fuzzy mode tolerance
"""
cut_op = BRepAlgoAPI_Cut()
if tol:
cut_op.SetFuzzyValue(tol)
return self._bool_op((self,), toCut, cut_op)
def fuse(
self, *toFuse: "Shape", glue: bool = False, tol: Optional[float] = None
) -> "Shape":
"""
Fuse the positional arguments with this Shape.
:param glue: Sets the glue option for the algorithm, which allows
increasing performance of the intersection of the input shapes
:param tol: Fuzzy mode tolerance
"""
fuse_op = BRepAlgoAPI_Fuse()
if glue:
fuse_op.SetGlue(BOPAlgo_GlueEnum.BOPAlgo_GlueShift)
if tol:
fuse_op.SetFuzzyValue(tol)
rv = self._bool_op((self,), toFuse, fuse_op)
return rv
def intersect(self, *toIntersect: "Shape", tol: Optional[float] = None) -> "Shape":
"""
Intersection of the positional arguments and this Shape.
:param tol: Fuzzy mode tolerance
"""
intersect_op = BRepAlgoAPI_Common()
if tol:
intersect_op.SetFuzzyValue(tol)
return self._bool_op((self,), toIntersect, intersect_op)
def facesIntersectedByLine(
self,
point: VectorLike,
axis: VectorLike,
tol: float = 1e-4,
direction: Optional[Literal["AlongAxis", "Opposite"]] = None,
):
"""
Computes the intersections between the provided line and the faces of this Shape
:param point: Base point for defining a line
:param axis: Axis on which the line rests
:param tol: Intersection tolerance
:param direction: Valid values: "AlongAxis", "Opposite";
If specified, will ignore all faces that are not in the specified direction
including the face where the point lies if it is the case
:returns: A list of intersected faces sorted by distance from point
"""
oc_point = (
gp_Pnt(*point.toTuple()) if isinstance(point, Vector) else gp_Pnt(*point)
)
oc_axis = (
gp_Dir(Vector(axis).wrapped)
if not isinstance(axis, Vector)
else gp_Dir(axis.wrapped)
)
line = gce_MakeLin(oc_point, oc_axis).Value()
shape = self.wrapped
intersectMaker = BRepIntCurveSurface_Inter()
intersectMaker.Init(shape, line, tol)
faces_dist = [] # using a list instead of a dictionary to be able to sort it
while intersectMaker.More():
interPt = intersectMaker.Pnt()
interDirMk = gce_MakeDir(oc_point, interPt)
distance = oc_point.SquareDistance(interPt)
# interDir is not done when `oc_point` and `oc_axis` have the same coord
if interDirMk.IsDone():
interDir: Any = interDirMk.Value()
else:
interDir = None
if direction == "AlongAxis":
if (
interDir is not None
and not interDir.IsOpposite(oc_axis, tol)
and distance > tol
):
faces_dist.append((intersectMaker.Face(), distance))
elif direction == "Opposite":
if (
interDir is not None
and interDir.IsOpposite(oc_axis, tol)
and distance > tol
):
faces_dist.append((intersectMaker.Face(), distance))
elif direction is None:
faces_dist.append(
(intersectMaker.Face(), abs(distance))
) # will sort all intersected faces by distance whatever the direction is
else:
raise ValueError(
"Invalid direction specification.\nValid specification are 'AlongAxis' and 'Opposite'."
)
intersectMaker.Next()
faces_dist.sort(key=lambda x: x[1])
faces = [face[0] for face in faces_dist]
return [Face(face) for face in faces]
def split(self, *splitters: "Shape") -> "Shape":
"""
Split this shape with the positional arguments.
"""
split_op = BRepAlgoAPI_Splitter()
return self._bool_op((self,), splitters, split_op)
def distance(self, other: "Shape") -> float:
"""
Minimal distance between two shapes
"""
return BRepExtrema_DistShapeShape(self.wrapped, other.wrapped).Value()
def distances(self, *others: "Shape") -> Iterator[float]:
"""
Minimal distances to between self and other shapes
"""
dist_calc = BRepExtrema_DistShapeShape()
dist_calc.LoadS1(self.wrapped)
for s in others:
dist_calc.LoadS2(s.wrapped)
dist_calc.Perform()
yield dist_calc.Value()
def mesh(self, tolerance: float, angularTolerance: float = 0.1):
"""
Generate triangulation if none exists.
"""
if not BRepTools.Triangulation_s(self.wrapped, tolerance):
BRepMesh_IncrementalMesh(self.wrapped, tolerance, True, angularTolerance)
def tessellate(
self, tolerance: float, angularTolerance: float = 0.1
) -> Tuple[List[Vector], List[Tuple[int, int, int]]]:
self.mesh(tolerance, angularTolerance)
vertices: List[Vector] = []
triangles: List[Tuple[int, int, int]] = []
offset = 0
for f in self.Faces():
loc = TopLoc_Location()
poly = BRep_Tool.Triangulation_s(f.wrapped, loc)
Trsf = loc.Transformation()
reverse = (
True
if f.wrapped.Orientation() == TopAbs_Orientation.TopAbs_REVERSED
else False
)
# add vertices
vertices += [
Vector(v.X(), v.Y(), v.Z())
for v in (
poly.Node(i).Transformed(Trsf) for i in range(1, poly.NbNodes() + 1)
)
]
# add triangles
triangles += [
(
t.Value(1) + offset - 1,
t.Value(3) + offset - 1,
t.Value(2) + offset - 1,
)
if reverse
else (
t.Value(1) + offset - 1,
t.Value(2) + offset - 1,
t.Value(3) + offset - 1,
)
for t in poly.Triangles()
]
offset += poly.NbNodes()
return vertices, triangles
def toSplines(
self: T, degree: int = 3, tolerance: float = 1e-3, nurbs: bool = False
) -> T:
"""
Approximate shape with b-splines of the specified degree.
:param degree: Maximum degree.
:param tolerance: Approximation tolerance.
:param nurbs: Use rational splines.
"""
params = ShapeCustom_RestrictionParameters()
result = ShapeCustom.BSplineRestriction_s(
self.wrapped,
tolerance, # 3D tolerance
tolerance, # 2D tolerance
degree,
1, # dumy value, degree is leading
ga.GeomAbs_C0,
ga.GeomAbs_C0,
True, # set degree to be leading
not nurbs,
params,
)
return self.__class__(result)
def toVtkPolyData(
self,
tolerance: Optional[float] = None,
angularTolerance: Optional[float] = None,
normals: bool = False,
) -> vtkPolyData:
"""
Convert shape to vtkPolyData
"""
vtk_shape = IVtkOCC_Shape(self.wrapped)
shape_data = IVtkVTK_ShapeData()
shape_mesher = IVtkOCC_ShapeMesher()
drawer = vtk_shape.Attributes()
drawer.SetUIsoAspect(Prs3d_IsoAspect(Quantity_Color(), Aspect_TOL_SOLID, 1, 0))
drawer.SetVIsoAspect(Prs3d_IsoAspect(Quantity_Color(), Aspect_TOL_SOLID, 1, 0))
if tolerance:
drawer.SetDeviationCoefficient(tolerance)
if angularTolerance:
drawer.SetDeviationAngle(angularTolerance)
shape_mesher.Build(vtk_shape, shape_data)
rv = shape_data.getVtkPolyData()
# convert to triangles and split edges
t_filter = vtkTriangleFilter()
t_filter.SetInputData(rv)
t_filter.Update()
rv = t_filter.GetOutput()
# compute normals
if normals:
n_filter = vtkPolyDataNormals()
n_filter.SetComputePointNormals(True)
n_filter.SetComputeCellNormals(True)
n_filter.SetFeatureAngle(360)
n_filter.SetInputData(rv)
n_filter.Update()
rv = n_filter.GetOutput()
return rv
def _repr_javascript_(self):
"""
Jupyter 3D representation support
"""
from .jupyter_tools import display
return display(self)._repr_javascript_()
class ShapeProtocol(Protocol):
@property
def wrapped(self) -> TopoDS_Shape:
...
def __init__(self, wrapped: TopoDS_Shape) -> None:
...
def Faces(self) -> List["Face"]:
...
def geomType(self) -> Geoms:
...
class Vertex(Shape):
"""
A Single Point in Space
"""
wrapped: TopoDS_Vertex
def __init__(self, obj: TopoDS_Shape, forConstruction: bool = False):
"""
Create a vertex
"""
super(Vertex, self).__init__(obj)
self.forConstruction = forConstruction
self.X, self.Y, self.Z = self.toTuple()
def toTuple(self) -> Tuple[float, float, float]:
geom_point = BRep_Tool.Pnt_s(self.wrapped)
return (geom_point.X(), geom_point.Y(), geom_point.Z())
def Center(self) -> Vector:
"""
The center of a vertex is itself!
"""
return Vector(self.toTuple())
@classmethod
def makeVertex(cls, x: float, y: float, z: float) -> "Vertex":
return cls(BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z)).Vertex())
class Mixin1DProtocol(ShapeProtocol, Protocol):
def _geomAdaptor(self) -> Union[BRepAdaptor_Curve, BRepAdaptor_CompCurve]:
...
def paramAt(self, d: float) -> float:
...
def positionAt(
self, d: float, mode: Literal["length", "parameter"] = "length",
) -> Vector:
...
def locationAt(
self,
d: float,
mode: Literal["length", "parameter"] = "length",
frame: Literal["frenet", "corrected"] = "frenet",
planar: bool = False,
) -> Location:
...
T1D = TypeVar("T1D", bound=Mixin1DProtocol)
class Mixin1D(object):
def _bounds(self: Mixin1DProtocol) -> Tuple[float, float]:
curve = self._geomAdaptor()
return curve.FirstParameter(), curve.LastParameter()
def startPoint(self: Mixin1DProtocol) -> Vector:
"""
:return: a vector representing the start point of this edge
Note, circles may have the start and end points the same
"""
curve = self._geomAdaptor()
umin = curve.FirstParameter()
return Vector(curve.Value(umin))
def endPoint(self: Mixin1DProtocol) -> Vector:
"""
:return: a vector representing the end point of this edge.
Note, circles may have the start and end points the same
"""
curve = self._geomAdaptor()
umax = curve.LastParameter()
return Vector(curve.Value(umax))
def paramAt(self: Mixin1DProtocol, d: float) -> float:
"""
Compute parameter value at the specified normalized distance.
:param d: normalized distance [0, 1]
:return: parameter value
"""
curve = self._geomAdaptor()
l = GCPnts_AbscissaPoint.Length_s(curve)
return GCPnts_AbscissaPoint(curve, l * d, curve.FirstParameter()).Parameter()
def tangentAt(
self: Mixin1DProtocol,
locationParam: float = 0.5,
mode: Literal["length", "parameter"] = "length",
) -> Vector:
"""
Compute tangent vector at the specified location.
:param locationParam: distance or parameter value (default: 0.5)
:param mode: position calculation mode (default: parameter)
:return: tangent vector
"""
curve = self._geomAdaptor()
tmp = gp_Pnt()
res = gp_Vec()
if mode == "length":
param = self.paramAt(locationParam)
else:
param = locationParam
curve.D1(param, tmp, res)
return Vector(gp_Dir(res))
def normal(self: Mixin1DProtocol) -> Vector:
"""
Calculate the normal Vector. Only possible for planar curves.
:return: normal vector
"""
curve = self._geomAdaptor()
gtype = self.geomType()
if gtype == "CIRCLE":
circ = curve.Circle()
rv = Vector(circ.Axis().Direction())
elif gtype == "ELLIPSE":
ell = curve.Ellipse()
rv = Vector(ell.Axis().Direction())
else:
fs = BRepLib_FindSurface(self.wrapped, OnlyPlane=True)
surf = fs.Surface()
if isinstance(surf, Geom_Plane):
pln = surf.Pln()
rv = Vector(pln.Axis().Direction())
else:
raise ValueError("Normal not defined")
return rv
def Center(self: Mixin1DProtocol) -> Vector:
Properties = GProp_GProps()
BRepGProp.LinearProperties_s(self.wrapped, Properties)
return Vector(Properties.CentreOfMass())
def Length(self: Mixin1DProtocol) -> float:
return GCPnts_AbscissaPoint.Length_s(self._geomAdaptor())
def radius(self: Mixin1DProtocol) -> float:
"""
Calculate the radius.
Note that when applied to a Wire, the radius is simply the radius of the first edge.
:return: radius
:raises ValueError: if kernel can not reduce the shape to a circular edge
"""
geom = self._geomAdaptor()
try:
circ = geom.Circle()
except (Standard_NoSuchObject, Standard_Failure) as e:
raise ValueError("Shape could not be reduced to a circle") from e
return circ.Radius()
def IsClosed(self: Mixin1DProtocol) -> bool:
return BRep_Tool.IsClosed_s(self.wrapped)
def positionAt(
self: Mixin1DProtocol,
d: float,
mode: Literal["length", "parameter"] = "length",
) -> Vector:
"""Generate a position along the underlying curve.
:param d: distance or parameter value
:param mode: position calculation mode (default: length)
:return: A Vector on the underlying curve located at the specified d value.
"""
curve = self._geomAdaptor()
if mode == "length":
param = self.paramAt(d)
else:
param = d
return Vector(curve.Value(param))
def positions(
self: Mixin1DProtocol,
ds: Iterable[float],
mode: Literal["length", "parameter"] = "length",
) -> List[Vector]:
"""Generate positions along the underlying curve
:param ds: distance or parameter values
:param mode: position calculation mode (default: length)
:return: A list of Vector objects.
"""
return [self.positionAt(d, mode) for d in ds]
def locationAt(
self: Mixin1DProtocol,
d: float,
mode: Literal["length", "parameter"] = "length",
frame: Literal["frenet", "corrected"] = "frenet",
planar: bool = False,
) -> Location:
"""Generate a location along the underlying curve.
:param d: distance or parameter value
:param mode: position calculation mode (default: length)
:param frame: moving frame calculation method (default: frenet)
:param planar: planar mode
:return: A Location object representing local coordinate system at the specified distance.
"""
curve = self._geomAdaptor()
if mode == "length":
param = self.paramAt(d)
else:
param = d
law: GeomFill_TrihedronLaw
if frame == "frenet":
law = GeomFill_Frenet()
else:
law = GeomFill_CorrectedFrenet()
law.SetCurve(curve)
tangent, normal, binormal = gp_Vec(), gp_Vec(), gp_Vec()
law.D0(param, tangent, normal, binormal)
pnt = curve.Value(param)
T = gp_Trsf()
if planar:
T.SetTransformation(
gp_Ax3(pnt, gp_Dir(0, 0, 1), gp_Dir(normal.XYZ())), gp_Ax3()
)
else:
T.SetTransformation(
gp_Ax3(pnt, gp_Dir(tangent.XYZ()), gp_Dir(normal.XYZ())), gp_Ax3()
)
return Location(TopLoc_Location(T))
def locations(
self: Mixin1DProtocol,
ds: Iterable[float],
mode: Literal["length", "parameter"] = "length",
frame: Literal["frenet", "corrected"] = "frenet",
planar: bool = False,
) -> List[Location]:
"""Generate location along the curve
:param ds: distance or parameter values
:param mode: position calculation mode (default: length)
:param frame: moving frame calculation method (default: frenet)
:param planar: planar mode
:return: A list of Location objects representing local coordinate systems at the specified distances.
"""
return [self.locationAt(d, mode, frame, planar) for d in ds]
def project(
self: T1D, face: "Face", d: VectorLike, closest: bool = True
) -> Union[T1D, List[T1D]]:
"""
Project onto a face along the specified direction
"""
bldr = BRepProj_Projection(self.wrapped, face.wrapped, Vector(d).toDir())
shapes = Compound(bldr.Shape())
# select the closest projection if requested
rv: Union[T1D, List[T1D]]
if closest:
dist_calc = BRepExtrema_DistShapeShape()
dist_calc.LoadS1(self.wrapped)
min_dist = inf
for el in shapes:
dist_calc.LoadS2(el.wrapped)
dist_calc.Perform()
dist = dist_calc.Value()
if dist < min_dist:
min_dist = dist
rv = tcast(T1D, el)
else:
rv = [tcast(T1D, el) for el in shapes]
return rv
class Edge(Shape, Mixin1D):
"""
A trimmed curve that represents the border of a face
"""
wrapped: TopoDS_Edge
def _geomAdaptor(self) -> BRepAdaptor_Curve:
"""
Return the underlying geometry
"""
return BRepAdaptor_Curve(self.wrapped)
def close(self) -> Union["Edge", "Wire"]:
"""
Close an Edge
"""
rv: Union[Wire, Edge]
if not self.IsClosed():
rv = Wire.assembleEdges((self,)).close()
else:
rv = self
return rv
def arcCenter(self) -> Vector:
"""
Center of an underlying circle or ellipse geometry.
"""
g = self.geomType()
a = self._geomAdaptor()
if g == "CIRCLE":
rv = Vector(a.Circle().Position().Location())
elif g == "ELLIPSE":
rv = Vector(a.Ellipse().Position().Location())
else:
raise ValueError(f"{g} has no arc center")
return rv
@classmethod
def makeCircle(
cls,
radius: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angle1: float = 360.0,
angle2: float = 360,
orientation=True,
) -> "Edge":
pnt = Vector(pnt)
dir = Vector(dir)
circle_gp = gp_Circ(gp_Ax2(pnt.toPnt(), dir.toDir()), radius)
if angle1 == angle2: # full circle case
return cls(BRepBuilderAPI_MakeEdge(circle_gp).Edge())
else: # arc case
circle_geom = GC_MakeArcOfCircle(
circle_gp, radians(angle1), radians(angle2), orientation
).Value()
return cls(BRepBuilderAPI_MakeEdge(circle_geom).Edge())
@classmethod
def makeEllipse(
cls,
x_radius: float,
y_radius: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
xdir: VectorLike = Vector(1, 0, 0),
angle1: float = 360.0,
angle2: float = 360.0,
sense: Literal[-1, 1] = 1,
) -> "Edge":
"""
Makes an Ellipse centered at the provided point, having normal in the provided direction.
:param cls:
:param x_radius: x radius of the ellipse (along the x-axis of plane the ellipse should lie in)
:param y_radius: y radius of the ellipse (along the y-axis of plane the ellipse should lie in)
:param pnt: vector representing the center of the ellipse
:param dir: vector representing the direction of the plane the ellipse should lie in
:param angle1: start angle of arc
:param angle2: end angle of arc (angle2 == angle1 return closed ellipse = default)
:param sense: clockwise (-1) or counter clockwise (1)
:return: an Edge
"""
pnt_p = Vector(pnt).toPnt()
dir_d = Vector(dir).toDir()
xdir_d = Vector(xdir).toDir()
ax1 = gp_Ax1(pnt_p, dir_d)
ax2 = gp_Ax2(pnt_p, dir_d, xdir_d)
if y_radius > x_radius:
# swap x and y radius and rotate by 90° afterwards to create an ellipse with x_radius < y_radius
correction_angle = radians(90.0)
ellipse_gp = gp_Elips(ax2, y_radius, x_radius).Rotated(
ax1, correction_angle
)
else:
correction_angle = 0.0
ellipse_gp = gp_Elips(ax2, x_radius, y_radius)
if angle1 == angle2: # full ellipse case
ellipse = cls(BRepBuilderAPI_MakeEdge(ellipse_gp).Edge())
else: # arc case
# take correction_angle into account
ellipse_geom = GC_MakeArcOfEllipse(
ellipse_gp,
radians(angle1) - correction_angle,
radians(angle2) - correction_angle,
sense == 1,
).Value()
ellipse = cls(BRepBuilderAPI_MakeEdge(ellipse_geom).Edge())
return ellipse
@classmethod
def makeSpline(
cls,
listOfVector: List[Vector],
tangents: Optional[Sequence[Vector]] = None,
periodic: bool = False,
parameters: Optional[Sequence[float]] = None,
scale: bool = True,
tol: float = 1e-6,
) -> "Edge":
"""
Interpolate a spline through the provided points.
:param listOfVector: a list of Vectors that represent the points
:param tangents: tuple of Vectors specifying start and finish tangent
:param periodic: creation of periodic curves
:param parameters: the value of the parameter at each interpolation point. (The interpolated
curve is represented as a vector-valued function of a scalar parameter.) If periodic ==
True, then len(parameters) must be len(intepolation points) + 1, otherwise len(parameters)
must be equal to len(interpolation points).
:param scale: whether to scale the specified tangent vectors before interpolating. Each
tangent is scaled, so it's length is equal to the derivative of the Lagrange interpolated
curve. I.e., set this to True, if you want to use only the direction of the tangent
vectors specified by ``tangents``, but not their magnitude.
:param tol: tolerance of the algorithm (consult OCC documentation). Used to check that the
specified points are not too close to each other, and that tangent vectors are not too
short. (In either case interpolation may fail.)
:return: an Edge
"""
pnts = TColgp_HArray1OfPnt(1, len(listOfVector))
for ix, v in enumerate(listOfVector):
pnts.SetValue(ix + 1, v.toPnt())
if parameters is None:
spline_builder = GeomAPI_Interpolate(pnts, periodic, tol)
else:
if len(parameters) != (len(listOfVector) + periodic):
raise ValueError(
"There must be one parameter for each interpolation point "
"(plus one if periodic), or none specified. Parameter count: "
f"{len(parameters)}, point count: {len(listOfVector)}"
)
parameters_array = TColStd_HArray1OfReal(1, len(parameters))
for p_index, p_value in enumerate(parameters):
parameters_array.SetValue(p_index + 1, p_value)
spline_builder = GeomAPI_Interpolate(pnts, parameters_array, periodic, tol)
if tangents:
if len(tangents) == 2 and len(listOfVector) != 2:
# Specify only initial and final tangent:
t1, t2 = tangents
spline_builder.Load(t1.wrapped, t2.wrapped, scale)
else:
if len(tangents) != len(listOfVector):
raise ValueError(
f"There must be one tangent for each interpolation point, "
f"or just two end point tangents. Tangent count: "
f"{len(tangents)}, point count: {len(listOfVector)}"
)
# Specify a tangent for each interpolation point:
tangents_array = TColgp_Array1OfVec(1, len(tangents))
tangent_enabled_array = TColStd_HArray1OfBoolean(1, len(tangents))
for t_index, t_value in enumerate(tangents):
tangent_enabled_array.SetValue(t_index + 1, t_value is not None)
tangent_vec = t_value if t_value is not None else Vector()
tangents_array.SetValue(t_index + 1, tangent_vec.wrapped)
spline_builder.Load(tangents_array, tangent_enabled_array, scale)
spline_builder.Perform()
if not spline_builder.IsDone():
raise ValueError("B-spline interpolation failed")
spline_geom = spline_builder.Curve()
return cls(BRepBuilderAPI_MakeEdge(spline_geom).Edge())
@classmethod
def makeSplineApprox(
cls,
listOfVector: List[Vector],
tol: float = 1e-3,
smoothing: Optional[Tuple[float, float, float]] = None,
minDeg: int = 1,
maxDeg: int = 6,
) -> "Edge":
"""
Approximate a spline through the provided points.
:param listOfVector: a list of Vectors that represent the points
:param tol: tolerance of the algorithm (consult OCC documentation).
:param smoothing: optional tuple of 3 weights use for variational smoothing (default: None)
:param minDeg: minimum spline degree. Enforced only when smothing is None (default: 1)
:param maxDeg: maximum spline degree (default: 6)
:return: an Edge
"""
pnts = TColgp_HArray1OfPnt(1, len(listOfVector))
for ix, v in enumerate(listOfVector):
pnts.SetValue(ix + 1, v.toPnt())
if smoothing:
spline_builder = GeomAPI_PointsToBSpline(
pnts, *smoothing, DegMax=maxDeg, Tol3D=tol
)
else:
spline_builder = GeomAPI_PointsToBSpline(
pnts, DegMin=minDeg, DegMax=maxDeg, Tol3D=tol
)
if not spline_builder.IsDone():
raise ValueError("B-spline approximation failed")
spline_geom = spline_builder.Curve()
return cls(BRepBuilderAPI_MakeEdge(spline_geom).Edge())
@classmethod
def makeThreePointArc(
cls, v1: VectorLike, v2: VectorLike, v3: VectorLike
) -> "Edge":
"""
Makes a three point arc through the provided points
:param cls:
:param v1: start vector
:param v2: middle vector
:param v3: end vector
:return: an edge object through the three points
"""
circle_geom = GC_MakeArcOfCircle(
Vector(v1).toPnt(), Vector(v2).toPnt(), Vector(v3).toPnt()
).Value()
return cls(BRepBuilderAPI_MakeEdge(circle_geom).Edge())
@classmethod
def makeTangentArc(cls, v1: VectorLike, v2: VectorLike, v3: VectorLike) -> "Edge":
"""
Makes a tangent arc from point v1, in the direction of v2 and ends at v3.
:param cls:
:param v1: start vector
:param v2: tangent vector
:param v3: end vector
:return: an edge
"""
circle_geom = GC_MakeArcOfCircle(
Vector(v1).toPnt(), Vector(v2).wrapped, Vector(v3).toPnt()
).Value()
return cls(BRepBuilderAPI_MakeEdge(circle_geom).Edge())
@classmethod
def makeLine(cls, v1: VectorLike, v2: VectorLike) -> "Edge":
"""
Create a line between two points
:param v1: Vector that represents the first point
:param v2: Vector that represents the second point
:return: A linear edge between the two provided points
"""
return cls(
BRepBuilderAPI_MakeEdge(Vector(v1).toPnt(), Vector(v2).toPnt()).Edge()
)
class Wire(Shape, Mixin1D):
"""
A series of connected, ordered Edges, that typically bounds a Face
"""
wrapped: TopoDS_Wire
def _geomAdaptor(self) -> BRepAdaptor_CompCurve:
"""
Return the underlying geometry
"""
return BRepAdaptor_CompCurve(self.wrapped)
def close(self) -> "Wire":
"""
Close a Wire
"""
if not self.IsClosed():
e = Edge.makeLine(self.endPoint(), self.startPoint())
rv = Wire.combine((self, e))[0]
else:
rv = self
return rv
@classmethod
def combine(
cls, listOfWires: Iterable[Union["Wire", Edge]], tol: float = 1e-9
) -> List["Wire"]:
"""
Attempt to combine a list of wires and edges into a new wire.
:param cls:
:param listOfWires:
:param tol: default 1e-9
:return: List[Wire]
"""
edges_in = TopTools_HSequenceOfShape()
wires_out = TopTools_HSequenceOfShape()
for e in Compound.makeCompound(listOfWires).Edges():
edges_in.Append(e.wrapped)
ShapeAnalysis_FreeBounds.ConnectEdgesToWires_s(edges_in, tol, False, wires_out)
return [cls(el) for el in wires_out]
@classmethod
def assembleEdges(cls, listOfEdges: Iterable[Edge]) -> "Wire":
"""
Attempts to build a wire that consists of the edges in the provided list
:param cls:
:param listOfEdges: a list of Edge objects. The edges are not to be consecutive.
:return: a wire with the edges assembled
BRepBuilderAPI_MakeWire::Error() values:
* BRepBuilderAPI_WireDone = 0
* BRepBuilderAPI_EmptyWire = 1
* BRepBuilderAPI_DisconnectedWire = 2
* BRepBuilderAPI_NonManifoldWire = 3
"""
wire_builder = BRepBuilderAPI_MakeWire()
occ_edges_list = TopTools_ListOfShape()
for e in listOfEdges:
occ_edges_list.Append(e.wrapped)
wire_builder.Add(occ_edges_list)
wire_builder.Build()
if not wire_builder.IsDone():
w = (
"BRepBuilderAPI_MakeWire::Error(): returns the construction status. BRepBuilderAPI_WireDone if the wire is built, or another value of the BRepBuilderAPI_WireError enumeration indicating why the construction failed = "
+ str(wire_builder.Error())
)
warnings.warn(w)
return cls(wire_builder.Wire())
@classmethod
def makeCircle(
cls, radius: float, center: VectorLike, normal: VectorLike
) -> "Wire":
"""
Makes a Circle centered at the provided point, having normal in the provided direction
:param radius: floating point radius of the circle, must be > 0
:param center: vector representing the center of the circle
:param normal: vector representing the direction of the plane the circle should lie in
"""
circle_edge = Edge.makeCircle(radius, center, normal)
w = cls.assembleEdges([circle_edge])
return w
@classmethod
def makeEllipse(
cls,
x_radius: float,
y_radius: float,
center: VectorLike,
normal: VectorLike,
xDir: VectorLike,
angle1: float = 360.0,
angle2: float = 360.0,
rotation_angle: float = 0.0,
closed: bool = True,
) -> "Wire":
"""
Makes an Ellipse centered at the provided point, having normal in the provided direction
:param x_radius: floating point major radius of the ellipse (x-axis), must be > 0
:param y_radius: floating point minor radius of the ellipse (y-axis), must be > 0
:param center: vector representing the center of the circle
:param normal: vector representing the direction of the plane the circle should lie in
:param angle1: start angle of arc
:param angle2: end angle of arc
:param rotation_angle: angle to rotate the created ellipse / arc
"""
ellipse_edge = Edge.makeEllipse(
x_radius, y_radius, center, normal, xDir, angle1, angle2
)
if angle1 != angle2 and closed:
line = Edge.makeLine(ellipse_edge.endPoint(), ellipse_edge.startPoint())
w = cls.assembleEdges([ellipse_edge, line])
else:
w = cls.assembleEdges([ellipse_edge])
if rotation_angle != 0.0:
w = w.rotate(center, Vector(center) + Vector(normal), rotation_angle)
return w
@classmethod
def makePolygon(
cls,
listOfVertices: Iterable[VectorLike],
forConstruction: bool = False,
close: bool = False,
) -> "Wire":
"""
Construct a polygonal wire from points.
"""
wire_builder = BRepBuilderAPI_MakePolygon()
for v in listOfVertices:
wire_builder.Add(Vector(v).toPnt())
if close:
wire_builder.Close()
w = cls(wire_builder.Wire())
w.forConstruction = forConstruction
return w
@classmethod
def makeHelix(
cls,
pitch: float,
height: float,
radius: float,
center: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angle: float = 360.0,
lefthand: bool = False,
) -> "Wire":
"""
Make a helix with a given pitch, height and radius
By default a cylindrical surface is used to create the helix. If
the fourth parameter is set (the apex given in degree) a conical surface is used instead'
"""
# 1. build underlying cylindrical/conical surface
if angle == 360.0:
geom_surf: Geom_Surface = Geom_CylindricalSurface(
gp_Ax3(Vector(center).toPnt(), Vector(dir).toDir()), radius
)
else:
geom_surf = Geom_ConicalSurface(
gp_Ax3(Vector(center).toPnt(), Vector(dir).toDir()),
radians(angle),
radius,
)
# 2. construct an segment in the u,v domain
if lefthand:
geom_line = Geom2d_Line(gp_Pnt2d(0.0, 0.0), gp_Dir2d(-2 * pi, pitch))
else:
geom_line = Geom2d_Line(gp_Pnt2d(0.0, 0.0), gp_Dir2d(2 * pi, pitch))
# 3. put it together into a wire
n_turns = height / pitch
u_start = geom_line.Value(0.0)
u_stop = geom_line.Value(n_turns * sqrt((2 * pi) ** 2 + pitch ** 2))
geom_seg = GCE2d_MakeSegment(u_start, u_stop).Value()
e = BRepBuilderAPI_MakeEdge(geom_seg, geom_surf).Edge()
# 4. Convert to wire and fix building 3d geom from 2d geom
w = BRepBuilderAPI_MakeWire(e).Wire()
BRepLib.BuildCurves3d_s(w, 1e-6, MaxSegment=2000) # NB: preliminary values
return cls(w)
def stitch(self, other: "Wire") -> "Wire":
"""Attempt to stitch wires"""
wire_builder = BRepBuilderAPI_MakeWire()
wire_builder.Add(TopoDS.Wire_s(self.wrapped))
wire_builder.Add(TopoDS.Wire_s(other.wrapped))
wire_builder.Build()
return self.__class__(wire_builder.Wire())
def offset2D(
self, d: float, kind: Literal["arc", "intersection", "tangent"] = "arc"
) -> List["Wire"]:
"""Offsets a planar wire"""
kind_dict = {
"arc": GeomAbs_JoinType.GeomAbs_Arc,
"intersection": GeomAbs_JoinType.GeomAbs_Intersection,
"tangent": GeomAbs_JoinType.GeomAbs_Tangent,
}
offset = BRepOffsetAPI_MakeOffset()
offset.Init(kind_dict[kind])
offset.AddWire(self.wrapped)
offset.Perform(d)
obj = downcast(offset.Shape())
if isinstance(obj, TopoDS_Compound):
rv = [self.__class__(el.wrapped) for el in Compound(obj)]
else:
rv = [self.__class__(obj)]
return rv
def fillet2D(self, radius: float, vertices: Iterable[Vertex]) -> "Wire":
"""
Apply 2D fillet to a wire
"""
f = Face.makeFromWires(self)
return f.fillet2D(radius, vertices).outerWire()
def chamfer2D(self, d: float, vertices: Iterable[Vertex]) -> "Wire":
"""
Apply 2D chamfer to a wire
"""
f = Face.makeFromWires(self)
return f.chamfer2D(d, vertices).outerWire()
class Face(Shape):
"""
a bounded surface that represents part of the boundary of a solid
"""
wrapped: TopoDS_Face
def _geomAdaptor(self) -> Geom_Surface:
"""
Return the underlying geometry
"""
return BRep_Tool.Surface_s(self.wrapped)
def _uvBounds(self) -> Tuple[float, float, float, float]:
return BRepTools.UVBounds_s(self.wrapped)
def normalAt(self, locationVector: Optional[Vector] = None) -> Vector:
"""
Computes the normal vector at the desired location on the face.
:returns: a vector representing the direction
:param locationVector: the location to compute the normal at. If none, the center of the face is used.
:type locationVector: a vector that lies on the surface.
"""
# get the geometry
surface = self._geomAdaptor()
if locationVector is None:
u0, u1, v0, v1 = self._uvBounds()
u = 0.5 * (u0 + u1)
v = 0.5 * (v0 + v1)
else:
# project point on surface
projector = GeomAPI_ProjectPointOnSurf(locationVector.toPnt(), surface)
u, v = projector.LowerDistanceParameters()
p = gp_Pnt()
vn = gp_Vec()
BRepGProp_Face(self.wrapped).Normal(u, v, p, vn)
return Vector(vn)
def Center(self) -> Vector:
Properties = GProp_GProps()
BRepGProp.SurfaceProperties_s(self.wrapped, Properties)
return Vector(Properties.CentreOfMass())
def outerWire(self) -> Wire:
return Wire(BRepTools.OuterWire_s(self.wrapped))
def innerWires(self) -> List[Wire]:
outer = self.outerWire()
return [w for w in self.Wires() if not w.isSame(outer)]
@classmethod
def makeNSidedSurface(
cls,
edges: Iterable[Union[Edge, Wire]],
constraints: Iterable[Union[Edge, Wire, VectorLike, gp_Pnt]],
continuity: GeomAbs_Shape = GeomAbs_C0,
degree: int = 3,
nbPtsOnCur: int = 15,
nbIter: int = 2,
anisotropy: bool = False,
tol2d: float = 0.00001,
tol3d: float = 0.0001,
tolAng: float = 0.01,
tolCurv: float = 0.1,
maxDeg: int = 8,
maxSegments: int = 9,
) -> "Face":
"""
Returns a surface enclosed by a closed polygon defined by 'edges' and 'constraints'.
:param edges: edges
:type edges: list of edges or wires
:param constraints: constraints
:type constraints: list of points or edges
:param continuity: OCC.Core.GeomAbs continuity condition
:param degree: >=2
:param nbPtsOnCur: number of points on curve >= 15
:param nbIter: number of iterations >= 2
:param anisotropy: bool Anisotropy
:param tol2d: 2D tolerance >0
:param tol3d: 3D tolerance >0
:param tolAng: angular tolerance
:param tolCurv: tolerance for curvature >0
:param maxDeg: highest polynomial degree >= 2
:param maxSegments: greatest number of segments >= 2
"""
n_sided = BRepOffsetAPI_MakeFilling(
degree,
nbPtsOnCur,
nbIter,
anisotropy,
tol2d,
tol3d,
tolAng,
tolCurv,
maxDeg,
maxSegments,
)
# outer edges
for el in edges:
if isinstance(el, Edge):
n_sided.Add(el.wrapped, continuity)
else:
for el_edge in el.Edges():
n_sided.Add(el_edge.wrapped, continuity)
# (inner) constraints
for c in constraints:
if isinstance(c, gp_Pnt):
n_sided.Add(c)
elif isinstance(c, Vector):
n_sided.Add(c.toPnt())
elif isinstance(c, tuple):
n_sided.Add(Vector(c).toPnt())
elif isinstance(c, Edge):
n_sided.Add(c.wrapped, GeomAbs_C0, False)
elif isinstance(c, Wire):
for e in c.Edges():
n_sided.Add(e.wrapped, GeomAbs_C0, False)
else:
raise ValueError(f"Invalid constraint {c}")
# build, fix and return
n_sided.Build()
face = n_sided.Shape()
return Face(face).fix()
@classmethod
def makePlane(
cls,
length: Optional[float] = None,
width: Optional[float] = None,
basePnt: VectorLike = (0, 0, 0),
dir: VectorLike = (0, 0, 1),
) -> "Face":
basePnt = Vector(basePnt)
dir = Vector(dir)
pln_geom = gp_Pln(basePnt.toPnt(), dir.toDir())
if length and width:
pln_shape = BRepBuilderAPI_MakeFace(
pln_geom, -width * 0.5, width * 0.5, -length * 0.5, length * 0.5
).Face()
else:
pln_shape = BRepBuilderAPI_MakeFace(pln_geom).Face()
return cls(pln_shape)
@overload
@classmethod
def makeRuledSurface(cls, edgeOrWire1: Edge, edgeOrWire2: Edge) -> "Face":
...
@overload
@classmethod
def makeRuledSurface(cls, edgeOrWire1: Wire, edgeOrWire2: Wire) -> "Face":
...
@classmethod
def makeRuledSurface(cls, edgeOrWire1, edgeOrWire2):
"""
makeRuledSurface(Edge|Wire,Edge|Wire) -- Make a ruled surface
Create a ruled surface out of two edges or wires. If wires are used then
these must have the same number of edges
"""
if isinstance(edgeOrWire1, Wire):
return cls.cast(BRepFill.Shell_s(edgeOrWire1.wrapped, edgeOrWire2.wrapped))
else:
return cls.cast(BRepFill.Face_s(edgeOrWire1.wrapped, edgeOrWire2.wrapped))
@classmethod
def makeFromWires(cls, outerWire: Wire, innerWires: List[Wire] = []) -> "Face":
"""
Makes a planar face from one or more wires
"""
if innerWires and not outerWire.IsClosed():
raise ValueError("Cannot build face(s): outer wire is not closed")
# check if wires are coplanar
ws = Compound.makeCompound([outerWire] + innerWires)
if not BRepLib_FindSurface(ws.wrapped, OnlyPlane=True).Found():
raise ValueError("Cannot build face(s): wires not planar")
# fix outer wire
sf_s = ShapeFix_Shape(outerWire.wrapped)
sf_s.Perform()
wo = TopoDS.Wire_s(sf_s.Shape())
face_builder = BRepBuilderAPI_MakeFace(wo, True)
for w in innerWires:
if not w.IsClosed():
raise ValueError("Cannot build face(s): inner wire is not closed")
face_builder.Add(w.wrapped)
face_builder.Build()
if not face_builder.IsDone():
raise ValueError(f"Cannot build face(s): {face_builder.Error()}")
face = face_builder.Face()
sf_f = ShapeFix_Face(face)
sf_f.FixOrientation()
sf_f.Perform()
return cls(sf_f.Result())
@classmethod
def makeSplineApprox(
cls,
points: List[List[Vector]],
tol: float = 1e-2,
smoothing: Optional[Tuple[float, float, float]] = None,
minDeg: int = 1,
maxDeg: int = 3,
) -> "Face":
"""
Approximate a spline surface through the provided points.
:param points: a 2D list of Vectors that represent the points
:param tol: tolerance of the algorithm (consult OCC documentation).
:param smoothing: optional tuple of 3 weights use for variational smoothing (default: None)
:param minDeg: minimum spline degree. Enforced only when smothing is None (default: 1)
:param maxDeg: maximum spline degree (default: 6)
"""
points_ = TColgp_HArray2OfPnt(1, len(points), 1, len(points[0]))
for i, vi in enumerate(points):
for j, v in enumerate(vi):
points_.SetValue(i + 1, j + 1, v.toPnt())
if smoothing:
spline_builder = GeomAPI_PointsToBSplineSurface(
points_, *smoothing, DegMax=maxDeg, Tol3D=tol
)
else:
spline_builder = GeomAPI_PointsToBSplineSurface(
points_, DegMin=minDeg, DegMax=maxDeg, Tol3D=tol
)
if not spline_builder.IsDone():
raise ValueError("B-spline approximation failed")
spline_geom = spline_builder.Surface()
return cls(BRepBuilderAPI_MakeFace(spline_geom, Precision.Confusion_s()).Face())
def fillet2D(self, radius: float, vertices: Iterable[Vertex]) -> "Face":
"""
Apply 2D fillet to a face
"""
fillet_builder = BRepFilletAPI_MakeFillet2d(self.wrapped)
for v in vertices:
fillet_builder.AddFillet(v.wrapped, radius)
fillet_builder.Build()
return self.__class__(fillet_builder.Shape())
def chamfer2D(self, d: float, vertices: Iterable[Vertex]) -> "Face":
"""
Apply 2D chamfer to a face
"""
chamfer_builder = BRepFilletAPI_MakeFillet2d(self.wrapped)
edge_map = self._entitiesFrom("Vertex", "Edge")
for v in vertices:
edges = edge_map[v]
if len(edges) < 2:
raise ValueError("Cannot chamfer at this location")
e1, e2 = edges
chamfer_builder.AddChamfer(
TopoDS.Edge_s(e1.wrapped), TopoDS.Edge_s(e2.wrapped), d, d
)
chamfer_builder.Build()
return self.__class__(chamfer_builder.Shape()).fix()
def toPln(self) -> gp_Pln:
"""
Convert this face to a gp_Pln.
Note the Location of the resulting plane may not equal the center of this face,
however the resulting plane will still contain the center of this face.
"""
adaptor = BRepAdaptor_Surface(self.wrapped)
return adaptor.Plane()
def thicken(self, thickness: float) -> "Solid":
"""
Return a thickened face
"""
builder = BRepOffset_MakeOffset()
builder.Initialize(
self.wrapped,
thickness,
1.0e-6,
BRepOffset_Mode.BRepOffset_Skin,
False,
False,
GeomAbs_Intersection,
True,
) # The last True is important to make solid
builder.MakeOffsetShape()
return Solid(builder.Shape())
@classmethod
def constructOn(cls, f: "Face", outer: "Wire", *inner: "Wire") -> "Face":
bldr = BRepBuilderAPI_MakeFace(f._geomAdaptor(), outer.wrapped)
for w in inner:
bldr.Add(TopoDS.Wire_s(w.wrapped))
return cls(bldr.Face()).fix()
def project(self, other: "Face", d: VectorLike) -> "Face":
outer_p = tcast(Wire, self.outerWire().project(other, d))
inner_p = (tcast(Wire, w.project(other, d)) for w in self.innerWires())
return self.constructOn(other, outer_p, *inner_p)
def toArcs(self, tolerance: float = 1e-3) -> "Face":
"""
Approximate planar face with arcs and straight line segments.
:param tolerance: Approximation tolerance.
"""
return self.__class__(BRepAlgo.ConvertFace_s(self.wrapped, tolerance))
class Shell(Shape):
"""
the outer boundary of a surface
"""
wrapped: TopoDS_Shell
@classmethod
def makeShell(cls, listOfFaces: Iterable[Face]) -> "Shell":
shell_builder = BRepBuilderAPI_Sewing()
for face in listOfFaces:
shell_builder.Add(face.wrapped)
shell_builder.Perform()
s = shell_builder.SewedShape()
return cls(s)
TS = TypeVar("TS", bound=ShapeProtocol)
class Mixin3D(object):
def fillet(self: Any, radius: float, edgeList: Iterable[Edge]) -> Any:
"""
Fillets the specified edges of this solid.
:param radius: float > 0, the radius of the fillet
:param edgeList: a list of Edge objects, which must belong to this solid
:return: Filleted solid
"""
nativeEdges = [e.wrapped for e in edgeList]
fillet_builder = BRepFilletAPI_MakeFillet(self.wrapped)
for e in nativeEdges:
fillet_builder.Add(radius, e)
return self.__class__(fillet_builder.Shape())
def chamfer(
self: Any, length: float, length2: Optional[float], edgeList: Iterable[Edge]
) -> Any:
"""
Chamfers the specified edges of this solid.
:param length: length > 0, the length (length) of the chamfer
:param length2: length2 > 0, optional parameter for asymmetrical chamfer. Should be `None` if not required.
:param edgeList: a list of Edge objects, which must belong to this solid
:return: Chamfered solid
"""
nativeEdges = [e.wrapped for e in edgeList]
# make a edge --> faces mapping
edge_face_map = TopTools_IndexedDataMapOfShapeListOfShape()
TopExp.MapShapesAndAncestors_s(
self.wrapped, ta.TopAbs_EDGE, ta.TopAbs_FACE, edge_face_map
)
# note: we prefer 'length' word to 'radius' as opposed to FreeCAD's API
chamfer_builder = BRepFilletAPI_MakeChamfer(self.wrapped)
if length2:
d1 = length
d2 = length2
else:
d1 = length
d2 = length
for e in nativeEdges:
face = edge_face_map.FindFromKey(e).First()
chamfer_builder.Add(
d1, d2, e, TopoDS.Face_s(face)
) # NB: edge_face_map return a generic TopoDS_Shape
return self.__class__(chamfer_builder.Shape())
def shell(
self: Any,
faceList: Optional[Iterable[Face]],
thickness: float,
tolerance: float = 0.0001,
kind: Literal["arc", "intersection"] = "arc",
) -> Any:
"""
Make a shelled solid of self.
:param faceList: List of faces to be removed, which must be part of the solid. Can
be an empty list.
:param thickness: Floating point thickness. Positive shells outwards, negative
shells inwards.
:param tolerance: Modelling tolerance of the method, default=0.0001.
:return: A shelled solid.
"""
kind_dict = {
"arc": GeomAbs_JoinType.GeomAbs_Arc,
"intersection": GeomAbs_JoinType.GeomAbs_Intersection,
}
occ_faces_list = TopTools_ListOfShape()
shell_builder = BRepOffsetAPI_MakeThickSolid()
if faceList:
for f in faceList:
occ_faces_list.Append(f.wrapped)
shell_builder.MakeThickSolidByJoin(
self.wrapped,
occ_faces_list,
thickness,
tolerance,
Intersection=True,
Join=kind_dict[kind],
)
shell_builder.Build()
if faceList:
rv = self.__class__(shell_builder.Shape())
else: # if no faces provided a watertight solid will be constructed
s1 = self.__class__(shell_builder.Shape()).Shells()[0].wrapped
s2 = self.Shells()[0].wrapped
# s1 can be outer or inner shell depending on the thickness sign
if thickness > 0:
sol = BRepBuilderAPI_MakeSolid(s1, s2)
else:
sol = BRepBuilderAPI_MakeSolid(s2, s1)
# fix needed for the orientations
rv = self.__class__(sol.Shape()).fix()
return rv
def isInside(
self: ShapeProtocol, point: VectorLike, tolerance: float = 1.0e-6
) -> bool:
"""
Returns whether or not the point is inside a solid or compound
object within the specified tolerance.
:param point: tuple or Vector representing 3D point to be tested
:param tolerance: tolerance for inside determination, default=1.0e-6
:return: bool indicating whether or not point is within solid
"""
if isinstance(point, Vector):
point = point.toTuple()
solid_classifier = BRepClass3d_SolidClassifier(self.wrapped)
solid_classifier.Perform(gp_Pnt(*point), tolerance)
return solid_classifier.State() == ta.TopAbs_IN or solid_classifier.IsOnAFace()
@multimethod
def dprism(
self: TS,
basis: Optional[Face],
profiles: List[Wire],
depth: Optional[Real] = None,
taper: Real = 0,
upToFace: Optional[Face] = None,
thruAll: bool = True,
additive: bool = True,
) -> "Solid":
"""
Make a prismatic feature (additive or subtractive)
:param basis: face to perform the operation on
:param profiles: list of profiles
:param depth: depth of the cut or extrusion
:param upToFace: a face to extrude until
:param thruAll: cut thruAll
:return: a Solid object
"""
sorted_profiles = sortWiresByBuildOrder(profiles)
faces = [Face.makeFromWires(p[0], p[1:]) for p in sorted_profiles]
return self.dprism(basis, faces, depth, taper, upToFace, thruAll, additive)
@dprism.register
def dprism(
self: TS,
basis: Optional[Face],
faces: List[Face],
depth: Optional[Real] = None,
taper: Real = 0,
upToFace: Optional[Face] = None,
thruAll: bool = True,
additive: bool = True,
) -> "Solid":
shape: Union[TopoDS_Shape, TopoDS_Solid] = self.wrapped
for face in faces:
feat = BRepFeat_MakeDPrism(
shape,
face.wrapped,
basis.wrapped if basis else TopoDS_Face(),
radians(taper),
additive,
False,
)
if upToFace is not None:
feat.Perform(upToFace.wrapped)
elif thruAll or depth is None:
feat.PerformThruAll()
else:
feat.Perform(depth)
shape = feat.Shape()
return self.__class__(shape)
class Solid(Shape, Mixin3D):
"""
a single solid
"""
wrapped: TopoDS_Solid
@classmethod
@deprecate()
def interpPlate(
cls,
surf_edges,
surf_pts,
thickness,
degree=3,
nbPtsOnCur=15,
nbIter=2,
anisotropy=False,
tol2d=0.00001,
tol3d=0.0001,
tolAng=0.01,
tolCurv=0.1,
maxDeg=8,
maxSegments=9,
) -> Union["Solid", Face]:
"""
Returns a plate surface that is 'thickness' thick, enclosed by 'surf_edge_pts' points, and going through 'surf_pts' points.
:param surf_edges:
list of [x,y,z] float ordered coordinates
or list of ordered or unordered wires
:param surf_pts: list of [x,y,z] float coordinates (uses only edges if [])
:param thickness: thickness may be negative or positive depending on direction, (returns 2D surface if 0)
:param degree: >=2
:param nbPtsOnCur: number of points on curve >= 15
:param nbIter: number of iterations >= 2
:param anisotropy: bool Anisotropy
:param tol2d: 2D tolerance >0
:param tol3d: 3D tolerance >0
:param tolAng: angular tolerance
:param tolCurv: tolerance for curvature >0
:param maxDeg: highest polynomial degree >= 2
:param maxSegments: greatest number of segments >= 2
"""
# POINTS CONSTRAINTS: list of (x,y,z) points, optional.
pts_array = [gp_Pnt(*pt) for pt in surf_pts]
# EDGE CONSTRAINTS
# If a list of wires is provided, make a closed wire
if not isinstance(surf_edges, list):
surf_edges = [o.vals()[0] for o in surf_edges.all()]
surf_edges = Wire.assembleEdges(surf_edges)
w = surf_edges.wrapped
# If a list of (x,y,z) points provided, build closed polygon
if isinstance(surf_edges, list):
e_array = [Vector(*e) for e in surf_edges]
wire_builder = BRepBuilderAPI_MakePolygon()
for e in e_array: # Create polygon from edges
wire_builder.Add(e.toPnt())
wire_builder.Close()
w = wire_builder.Wire()
edges = [i for i in Shape(w).Edges()]
# MAKE SURFACE
continuity = GeomAbs_C0 # Fixed, changing to anything else crashes.
face = Face.makeNSidedSurface(
edges,
pts_array,
continuity,
degree,
nbPtsOnCur,
nbIter,
anisotropy,
tol2d,
tol3d,
tolAng,
tolCurv,
maxDeg,
maxSegments,
)
# THICKEN SURFACE
if (
abs(thickness) > 0
): # abs() because negative values are allowed to set direction of thickening
return face.thicken(thickness)
else: # Return 2D surface only
return face
@staticmethod
def isSolid(obj: Shape) -> bool:
"""
Returns true if the object is a solid, false otherwise
"""
if hasattr(obj, "ShapeType"):
if obj.ShapeType == "Solid" or (
obj.ShapeType == "Compound" and len(obj.Solids()) > 0
):
return True
return False
@classmethod
def makeSolid(cls, shell: Shell) -> "Solid":
return cls(ShapeFix_Solid().SolidFromShell(shell.wrapped))
@classmethod
def makeBox(
cls,
length: float,
width: float,
height: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
) -> "Solid":
"""
makeBox(length,width,height,[pnt,dir]) -- Make a box located in pnt with the dimensions (length,width,height)
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)
"""
return cls(
BRepPrimAPI_MakeBox(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()), length, width, height
).Shape()
)
@classmethod
def makeCone(
cls,
radius1: float,
radius2: float,
height: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angleDegrees: float = 360,
) -> "Solid":
"""
Make a cone with given radii and height
By default pnt=Vector(0,0,0),
dir=Vector(0,0,1) and angle=360
"""
return cls(
BRepPrimAPI_MakeCone(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()),
radius1,
radius2,
height,
radians(angleDegrees),
).Shape()
)
@classmethod
def makeCylinder(
cls,
radius: float,
height: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angleDegrees: float = 360,
) -> "Solid":
"""
makeCylinder(radius,height,[pnt,dir,angle]) --
Make a cylinder with a given radius and height
By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360
"""
return cls(
BRepPrimAPI_MakeCylinder(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()),
radius,
height,
radians(angleDegrees),
).Shape()
)
@classmethod
def makeTorus(
cls,
radius1: float,
radius2: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angleDegrees1: float = 0,
angleDegrees2: float = 360,
) -> "Solid":
"""
makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) --
Make a torus with a given radii and angles
By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0
,angle1=360 and angle=360
"""
return cls(
BRepPrimAPI_MakeTorus(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()),
radius1,
radius2,
radians(angleDegrees1),
radians(angleDegrees2),
).Shape()
)
@classmethod
def makeLoft(cls, listOfWire: List[Wire], ruled: bool = False) -> "Solid":
"""
makes a loft from a list of wires
The wires will be converted into faces when possible-- it is presumed that nobody ever actually
wants to make an infinitely thin shell for a real FreeCADPart.
"""
# the True flag requests building a solid instead of a shell.
if len(listOfWire) < 2:
raise ValueError("More than one wire is required")
loft_builder = BRepOffsetAPI_ThruSections(True, ruled)
for w in listOfWire:
loft_builder.AddWire(w.wrapped)
loft_builder.Build()
return cls(loft_builder.Shape())
@classmethod
def makeWedge(
cls,
dx: float,
dy: float,
dz: float,
xmin: float,
zmin: float,
xmax: float,
zmax: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
) -> "Solid":
"""
Make a wedge located in pnt
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)
"""
return cls(
BRepPrimAPI_MakeWedge(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()),
dx,
dy,
dz,
xmin,
zmin,
xmax,
zmax,
).Solid()
)
@classmethod
def makeSphere(
cls,
radius: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
angleDegrees1: float = 0,
angleDegrees2: float = 90,
angleDegrees3: float = 360,
) -> "Shape":
"""
Make a sphere with a given radius
By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360
"""
return cls(
BRepPrimAPI_MakeSphere(
gp_Ax2(Vector(pnt).toPnt(), Vector(dir).toDir()),
radius,
radians(angleDegrees1),
radians(angleDegrees2),
radians(angleDegrees3),
).Shape()
)
@classmethod
def _extrudeAuxSpine(
cls, wire: TopoDS_Wire, spine: TopoDS_Wire, auxSpine: TopoDS_Wire
) -> TopoDS_Shape:
"""
Helper function for extrudeLinearWithRotation
"""
extrude_builder = BRepOffsetAPI_MakePipeShell(spine)
extrude_builder.SetMode(auxSpine, False) # auxiliary spine
extrude_builder.Add(wire)
extrude_builder.Build()
extrude_builder.MakeSolid()
return extrude_builder.Shape()
@multimethod
def extrudeLinearWithRotation(
cls,
outerWire: Wire,
innerWires: List[Wire],
vecCenter: VectorLike,
vecNormal: VectorLike,
angleDegrees: Real,
) -> "Solid":
"""
Creates a 'twisted prism' by extruding, while simultaneously rotating around the extrusion vector.
Though the signature may appear to be similar enough to extrudeLinear to merit combining them, the
construction methods used here are different enough that they should be separate.
At a high level, the steps followed are:
(1) accept a set of wires
(2) create another set of wires like this one, but which are transformed and rotated
(3) create a ruledSurface between the sets of wires
(4) create a shell and compute the resulting object
:param outerWire: the outermost wire
:param innerWires: a list of inner wires
:param vecCenter: the center point about which to rotate. the axis of rotation is defined by
vecNormal, located at vecCenter.
:param vecNormal: a vector along which to extrude the wires
:param angleDegrees: the angle to rotate through while extruding
:return: a Solid object
"""
# make straight spine
straight_spine_e = Edge.makeLine(vecCenter, vecCenter.add(vecNormal))
straight_spine_w = Wire.combine([straight_spine_e,])[0].wrapped
# make an auxiliary spine
pitch = 360.0 / angleDegrees * vecNormal.Length
radius = 1
aux_spine_w = Wire.makeHelix(
pitch, vecNormal.Length, radius, center=vecCenter, dir=vecNormal
).wrapped
# extrude the outer wire
outer_solid = cls._extrudeAuxSpine(
outerWire.wrapped, straight_spine_w, aux_spine_w
)
# extrude inner wires
inner_solids = [
cls._extrudeAuxSpine(w.wrapped, straight_spine_w, aux_spine_w)
for w in innerWires
]
# combine the inner solids into compound
inner_comp = Compound._makeCompound(inner_solids)
# subtract from the outer solid
return cls(BRepAlgoAPI_Cut(outer_solid, inner_comp).Shape())
@classmethod
@extrudeLinearWithRotation.register
def extrudeLinearWithRotation(
cls,
face: Face,
vecCenter: VectorLike,
vecNormal: VectorLike,
angleDegrees: Real,
) -> "Solid":
return cls.extrudeLinearWithRotation(
face.outerWire(), face.innerWires(), vecCenter, vecNormal, angleDegrees
)
@multimethod
def extrudeLinear(
cls,
outerWire: Wire,
innerWires: List[Wire],
vecNormal: VectorLike,
taper: Real = 0,
) -> "Solid":
"""
Attempt to extrude the list of wires into a prismatic solid in the provided direction
:param outerWire: the outermost wire
:param innerWires: a list of inner wires
:param vecNormal: a vector along which to extrude the wires
:param taper: taper angle, default=0
:return: a Solid object
The wires must not intersect
Extruding wires is very non-trivial. Nested wires imply very different geometry, and
there are many geometries that are invalid. In general, the following conditions must be met:
* all wires must be closed
* there cannot be any intersecting or self-intersecting wires
* wires must be listed from outside in
* more than one levels of nesting is not supported reliably
This method will attempt to sort the wires, but there is much work remaining to make this method
reliable.
"""
if taper == 0:
face = Face.makeFromWires(outerWire, innerWires)
else:
face = Face.makeFromWires(outerWire)
return cls.extrudeLinear(face, vecNormal, taper)
@classmethod
@extrudeLinear.register
def extrudeLinear(
cls, face: Face, vecNormal: VectorLike, taper: Real = 0,
) -> "Solid":
if taper == 0:
prism_builder: Any = BRepPrimAPI_MakePrism(
face.wrapped, Vector(vecNormal).wrapped, True
)
else:
faceNormal = face.normalAt()
d = 1 if vecNormal.getAngle(faceNormal) < radians(90.0) else -1
# Divided by cos of taper angle to ensure the height chosen by the user is respected
prism_builder = LocOpe_DPrism(
face.wrapped,
(d * vecNormal.Length) / cos(radians(taper)),
d * radians(taper),
)
return cls(prism_builder.Shape())
@multimethod
def revolve(
cls,
outerWire: Wire,
innerWires: List[Wire],
angleDegrees: Real,
axisStart: VectorLike,
axisEnd: VectorLike,
) -> "Solid":
"""
Attempt to revolve the list of wires into a solid in the provided direction
:param outerWire: the outermost wire
:param innerWires: a list of inner wires
:param angleDegrees: the angle to revolve through.
:type angleDegrees: float, anything less than 360 degrees will leave the shape open
:param axisStart: the start point of the axis of rotation
:param axisEnd: the end point of the axis of rotation
:return: a Solid object
The wires must not intersect
* all wires must be closed
* there cannot be any intersecting or self-intersecting wires
* wires must be listed from outside in
* more than one levels of nesting is not supported reliably
* the wire(s) that you're revolving cannot be centered
This method will attempt to sort the wires, but there is much work remaining to make this method
reliable.
"""
face = Face.makeFromWires(outerWire, innerWires)
return cls.revolve(face, angleDegrees, axisStart, axisEnd)
@classmethod
@revolve.register
def revolve(
cls, face: Face, angleDegrees: Real, axisStart: VectorLike, axisEnd: VectorLike,
) -> "Solid":
v1 = Vector(axisStart)
v2 = Vector(axisEnd)
v2 = v2 - v1
revol_builder = BRepPrimAPI_MakeRevol(
face.wrapped, gp_Ax1(v1.toPnt(), v2.toDir()), radians(angleDegrees), True
)
return cls(revol_builder.Shape())
_transModeDict = {
"transformed": BRepBuilderAPI_Transformed,
"round": BRepBuilderAPI_RoundCorner,
"right": BRepBuilderAPI_RightCorner,
}
@classmethod
def _setSweepMode(
cls,
builder: BRepOffsetAPI_MakePipeShell,
path: Union[Wire, Edge],
mode: Union[Vector, Wire, Edge],
) -> bool:
rotate = False
if isinstance(mode, Vector):
ax = gp_Ax2()
ax.SetLocation(path.startPoint().toPnt())
ax.SetDirection(mode.toDir())
builder.SetMode(ax)
rotate = True
elif isinstance(mode, (Wire, Edge)):
builder.SetMode(cls._toWire(mode).wrapped, True)
return rotate
@staticmethod
def _toWire(p: Union[Edge, Wire]) -> Wire:
if isinstance(p, Edge):
rv = Wire.assembleEdges([p,])
else:
rv = p
return rv
@multimethod
def sweep(
cls,
outerWire: Wire,
innerWires: List[Wire],
path: Union[Wire, Edge],
makeSolid: bool = True,
isFrenet: bool = False,
mode: Union[Vector, Wire, Edge, None] = None,
transitionMode: Literal["transformed", "round", "right"] = "transformed",
) -> "Shape":
"""
Attempt to sweep the list of wires into a prismatic solid along the provided path
:param outerWire: the outermost wire
:param innerWires: a list of inner wires
:param path: The wire to sweep the face resulting from the wires over
:param makeSolid: return Solid or Shell (default True)
:param isFrenet: Frenet mode (default False)
:param mode: additional sweep mode parameters
:param transitionMode:
handling of profile orientation at C1 path discontinuities.
Possible values are {'transformed','round', 'right'} (default: 'right').
:return: a Solid object
"""
p = cls._toWire(path)
shapes = []
for w in [outerWire] + innerWires:
builder = BRepOffsetAPI_MakePipeShell(p.wrapped)
translate = False
rotate = False
# handle sweep mode
if mode:
rotate = cls._setSweepMode(builder, path, mode)
else:
builder.SetMode(isFrenet)
builder.SetTransitionMode(cls._transModeDict[transitionMode])
builder.Add(w.wrapped, translate, rotate)
builder.Build()
if makeSolid:
builder.MakeSolid()
shapes.append(Shape.cast(builder.Shape()))
rv, inner_shapes = shapes[0], shapes[1:]
if inner_shapes:
rv = rv.cut(*inner_shapes)
return rv
@classmethod
@sweep.register
def sweep(
cls,
face: Face,
path: Union[Wire, Edge],
makeSolid: bool = True,
isFrenet: bool = False,
mode: Union[Vector, Wire, Edge, None] = None,
transitionMode: Literal["transformed", "round", "right"] = "transformed",
) -> "Shape":
return cls.sweep(
face.outerWire(),
face.innerWires(),
path,
makeSolid,
isFrenet,
mode,
transitionMode,
)
@classmethod
def sweep_multi(
cls,
profiles: Iterable[Union[Wire, Face]],
path: Union[Wire, Edge],
makeSolid: bool = True,
isFrenet: bool = False,
mode: Union[Vector, Wire, Edge, None] = None,
) -> "Solid":
"""
Multi section sweep. Only single outer profile per section is allowed.
:param profiles: list of profiles
:param path: The wire to sweep the face resulting from the wires over
:param mode: additional sweep mode parameters.
:return: a Solid object
"""
if isinstance(path, Edge):
w = Wire.assembleEdges([path,]).wrapped
else:
w = path.wrapped
builder = BRepOffsetAPI_MakePipeShell(w)
translate = False
rotate = False
if mode:
rotate = cls._setSweepMode(builder, path, mode)
else:
builder.SetMode(isFrenet)
for p in profiles:
w = p.wrapped if isinstance(p, Wire) else p.outerWire().wrapped
builder.Add(w, translate, rotate)
builder.Build()
if makeSolid:
builder.MakeSolid()
return cls(builder.Shape())
class CompSolid(Shape, Mixin3D):
"""
a single compsolid
"""
wrapped: TopoDS_CompSolid
class Compound(Shape, Mixin3D):
"""
a collection of disconnected solids
"""
wrapped: TopoDS_Compound
@staticmethod
def _makeCompound(listOfShapes: Iterable[TopoDS_Shape]) -> TopoDS_Compound:
comp = TopoDS_Compound()
comp_builder = TopoDS_Builder()
comp_builder.MakeCompound(comp)
for s in listOfShapes:
comp_builder.Add(comp, s)
return comp
def remove(self, shape: Shape):
"""
Remove the specified shape.
"""
comp_builder = TopoDS_Builder()
comp_builder.Remove(self.wrapped, shape.wrapped)
@classmethod
def makeCompound(cls, listOfShapes: Iterable[Shape]) -> "Compound":
"""
Create a compound out of a list of shapes
"""
return cls(cls._makeCompound((s.wrapped for s in listOfShapes)))
@classmethod
def makeText(
cls,
text: str,
size: float,
height: float,
font: str = "Arial",
fontPath: Optional[str] = None,
kind: Literal["regular", "bold", "italic"] = "regular",
halign: Literal["center", "left", "right"] = "center",
valign: Literal["center", "top", "bottom"] = "center",
position: Plane = Plane.XY(),
) -> "Shape":
"""
Create a 3D text
"""
font_kind = {
"regular": Font_FA_Regular,
"bold": Font_FA_Bold,
"italic": Font_FA_Italic,
}[kind]
mgr = Font_FontMgr.GetInstance_s()
if fontPath and mgr.CheckFont(TCollection_AsciiString(fontPath).ToCString()):
font_t = Font_SystemFont(TCollection_AsciiString(fontPath))
font_t.SetFontPath(font_kind, TCollection_AsciiString(fontPath))
mgr.RegisterFont(font_t, True)
else:
font_t = mgr.FindFont(TCollection_AsciiString(font), font_kind)
builder = Font_BRepTextBuilder()
font_i = StdPrs_BRepFont(
NCollection_Utf8String(font_t.FontName().ToCString()),
font_kind,
float(size),
)
text_flat = Shape(builder.Perform(font_i, NCollection_Utf8String(text)))
bb = text_flat.BoundingBox()
t = Vector()
if halign == "center":
t.x = -bb.xlen / 2
elif halign == "right":
t.x = -bb.xlen
if valign == "center":
t.y = -bb.ylen / 2
elif valign == "top":
t.y = -bb.ylen
text_flat = text_flat.translate(t)
if height != 0:
vecNormal = text_flat.Faces()[0].normalAt() * height
text_3d = BRepPrimAPI_MakePrism(text_flat.wrapped, vecNormal.wrapped)
rv = cls(text_3d.Shape()).transformShape(position.rG)
else:
rv = text_flat.transformShape(position.rG)
return rv
def __iter__(self) -> Iterator[Shape]:
"""
Iterate over subshapes.
"""
it = TopoDS_Iterator(self.wrapped)
while it.More():
yield Shape.cast(it.Value())
it.Next()
def __bool__(self) -> bool:
"""
Check if empty.
"""
return TopoDS_Iterator(self.wrapped).More()
def cut(self, *toCut: "Shape", tol: Optional[float] = None) -> "Compound":
"""
Remove the positional arguments from this Shape.
:param tol: Fuzzy mode tolerance
"""
cut_op = BRepAlgoAPI_Cut()
if tol:
cut_op.SetFuzzyValue(tol)
return tcast(Compound, self._bool_op(self, toCut, cut_op))
def fuse(
self, *toFuse: Shape, glue: bool = False, tol: Optional[float] = None
) -> "Compound":
"""
Fuse shapes together
"""
fuse_op = BRepAlgoAPI_Fuse()
if glue:
fuse_op.SetGlue(BOPAlgo_GlueEnum.BOPAlgo_GlueShift)
if tol:
fuse_op.SetFuzzyValue(tol)
args = tuple(self) + toFuse
if len(args) <= 1:
rv: Shape = args[0]
else:
rv = self._bool_op(args[:1], args[1:], fuse_op)
# fuse_op.RefineEdges()
# fuse_op.FuseEdges()
return tcast(Compound, rv)
def intersect(
self, *toIntersect: "Shape", tol: Optional[float] = None
) -> "Compound":
"""
Intersection of the positional arguments and this Shape.
:param tol: Fuzzy mode tolerance
"""
intersect_op = BRepAlgoAPI_Common()
if tol:
intersect_op.SetFuzzyValue(tol)
return tcast(Compound, self._bool_op(self, toIntersect, intersect_op))
def sortWiresByBuildOrder(wireList: List[Wire]) -> List[List[Wire]]:
"""Tries to determine how wires should be combined into faces.
Assume:
The wires make up one or more faces, which could have 'holes'
Outer wires are listed ahead of inner wires
there are no wires inside wires inside wires
( IE, islands -- we can deal with that later on )
none of the wires are construction wires
Compute:
one or more sets of wires, with the outer wire listed first, and inner
ones
Returns, list of lists.
"""
# check if we have something to sort at all
if len(wireList) < 2:
return [
wireList,
]
# make a Face, NB: this might return a compound of faces
faces = Face.makeFromWires(wireList[0], wireList[1:])
rv = []
for face in faces.Faces():
rv.append([face.outerWire(),] + face.innerWires())
return rv
def wiresToFaces(wireList: List[Wire]) -> List[Face]:
"""
Convert wires to a list of faces.
"""
return Face.makeFromWires(wireList[0], wireList[1:]).Faces()
def edgesToWires(edges: Iterable[Edge], tol: float = 1e-6) -> List[Wire]:
"""
Convert edges to a list of wires.
"""
edges_in = TopTools_HSequenceOfShape()
wires_out = TopTools_HSequenceOfShape()
for e in edges:
edges_in.Append(e.wrapped)
ShapeAnalysis_FreeBounds.ConnectEdgesToWires_s(edges_in, tol, False, wires_out)
return [Wire(el) for el in wires_out]
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,519 | CadQuery/cadquery | refs/heads/master | /examples/Ex010_Defining_an_Edge_with_a_Spline.py | import cadquery as cq
# 1. Establishes a workplane to create the spline on to extrude.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
s = cq.Workplane("XY")
# The points that the spline will pass through
sPnts = [
(2.75, 1.5),
(2.5, 1.75),
(2.0, 1.5),
(1.5, 1.0),
(1.0, 1.25),
(0.5, 1.0),
(0, 1.0),
]
# 2. Generate our plate with the spline feature and make sure it is a
# closed entity
r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts, includeCurrent=True).close()
# 3. Extrude to turn the wire into a plate
result = r.extrude(0.5)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,520 | CadQuery/cadquery | refs/heads/master | /cadquery/vis.py | from . import Shape, Workplane, Assembly, Sketch, Compound, Color
from .occ_impl.exporters.assembly import _vtkRenderWindow
from .occ_impl.jupyter_tools import DEFAULT_COLOR
from typing import Union
from OCP.TopoDS import TopoDS_Shape
from vtkmodules.vtkInteractionWidgets import vtkOrientationMarkerWidget
from vtkmodules.vtkRenderingAnnotation import vtkAxesActor
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkRenderingCore import vtkMapper, vtkRenderWindowInteractor
def _to_assy(*objs: Union[Shape, Workplane, Assembly, Sketch]) -> Assembly:
assy = Assembly(color=Color(*DEFAULT_COLOR))
for obj in objs:
if isinstance(obj, (Shape, Workplane, Assembly)):
assy.add(obj)
elif isinstance(obj, Sketch):
assy.add(obj._faces)
assy.add(Compound.makeCompound(obj._edges))
assy.add(Compound.makeCompound(obj._wires))
elif isinstance(obj, TopoDS_Shape):
assy.add(Shape(obj))
else:
raise ValueError(f"{obj} has unsupported type {type(obj)}")
return assy
def show(*objs: Union[Shape, Workplane, Assembly, Sketch]):
"""
Show CQ objects using VTK
"""
# construct the assy
assy = _to_assy(*objs)
# create a VTK window
win = _vtkRenderWindow(assy)
win.SetWindowName("CQ viewer")
# rendering related settings
win.SetMultiSamples(16)
vtkMapper.SetResolveCoincidentTopologyToPolygonOffset()
vtkMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 0)
vtkMapper.SetResolveCoincidentTopologyLineOffsetParameters(-1, 0)
# create a VTK interactor
inter = vtkRenderWindowInteractor()
inter.SetInteractorStyle(vtkInteractorStyleTrackballCamera())
inter.SetRenderWindow(win)
# construct an axes indicator
axes = vtkAxesActor()
axes.SetDragable(0)
tp = axes.GetXAxisCaptionActor2D().GetCaptionTextProperty()
tp.SetColor(0, 0, 0)
axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().ShallowCopy(tp)
axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().ShallowCopy(tp)
# add to an orientation widget
orient_widget = vtkOrientationMarkerWidget()
orient_widget.SetOrientationMarker(axes)
orient_widget.SetViewport(0.9, 0.0, 1.0, 0.2)
orient_widget.SetZoom(1.1)
orient_widget.SetInteractor(inter)
orient_widget.EnabledOn()
orient_widget.InteractiveOff()
# use gradient background
renderer = win.GetRenderers().GetFirstRenderer()
renderer.GradientBackgroundOn()
# set size and camera
win.SetSize(*win.GetScreenSize())
win.SetPosition(-10, 0)
camera = renderer.GetActiveCamera()
camera.Roll(-35)
camera.Elevation(-45)
renderer.ResetCamera()
# show and return
inter.Initialize()
win.Render()
inter.Start()
# alias
show_object = show
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,521 | CadQuery/cadquery | refs/heads/master | /cadquery/utils.py | from functools import wraps
from inspect import signature
from typing import TypeVar, Callable, cast
from warnings import warn
from multimethod import multimethod, DispatchError
TCallable = TypeVar("TCallable", bound=Callable)
class deprecate_kwarg:
def __init__(self, name, new_value):
self.name = name
self.new_value = new_value
def __call__(self, f: TCallable) -> TCallable:
@wraps(f)
def wrapped(*args, **kwargs):
f_sig_bound = signature(f).bind(*args, **kwargs)
if self.name not in f_sig_bound.kwargs:
warn(
f"Default value of {self.name} will change in the next release to {self.new_value}",
FutureWarning,
)
return f(*args, **kwargs)
return cast(TCallable, wrapped)
class deprecate:
def __call__(self, f):
@wraps(f)
def wrapped(*args, **kwargs):
warn(f"{f.__name__} will be removed in the next release.", FutureWarning)
return f(*args, **kwargs)
return wrapped
class cqmultimethod(multimethod):
def __call__(self, *args, **kwargs):
try:
return super().__call__(*args, **kwargs)
except DispatchError:
return next(iter(self.values()))(*args, **kwargs)
class deprecate_kwarg_name:
def __init__(self, name, new_name):
self.name = name
self.new_name = new_name
def __call__(self, f):
@wraps(f)
def wrapped(*args, **kwargs):
if self.name in kwargs:
warn(
f"Kwarg <{self.name}> will be removed. Please use <{self.new_name}>",
FutureWarning,
)
return f(*args, **kwargs)
return wrapped
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,522 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/exporters/svg.py | import io as StringIO
from ..shapes import Shape, Compound, TOLERANCE
from ..geom import BoundBox
from OCP.gp import gp_Ax2, gp_Pnt, gp_Dir
from OCP.BRepLib import BRepLib
from OCP.HLRBRep import HLRBRep_Algo, HLRBRep_HLRToShape
from OCP.HLRAlgo import HLRAlgo_Projector
from OCP.GCPnts import GCPnts_QuasiUniformDeflection
DISCRETIZATION_TOLERANCE = 1e-3
SVG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
width="%(width)s"
height="%(height)s"
>
<g transform="scale(%(unitScale)s, -%(unitScale)s) translate(%(xTranslate)s,%(yTranslate)s)" stroke-width="%(strokeWidth)s" fill="none">
<!-- hidden lines -->
<g stroke="rgb(%(hiddenColor)s)" fill="none" stroke-dasharray="%(strokeWidth)s,%(strokeWidth)s" >
%(hiddenContent)s
</g>
<!-- solid lines -->
<g stroke="rgb(%(strokeColor)s)" fill="none">
%(visibleContent)s
</g>
</g>
%(axesIndicator)s
</svg>
"""
# The axes indicator - needs to be replaced with something dynamic eventually
AXES_TEMPLATE = """<g transform="translate(20,%(textboxY)s)" stroke="rgb(0,0,255)">
<line x1="30" y1="-30" x2="75" y2="-33" stroke-width="3" stroke="#000000" />
<text x="80" y="-30" style="stroke:#000000">X </text>
<line x1="30" y1="-30" x2="30" y2="-75" stroke-width="3" stroke="#000000" />
<text x="25" y="-85" style="stroke:#000000">Y </text>
<line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3" stroke="#000000" />
<text x="65" y="-5" style="stroke:#000000">Z </text>
<!--
<line x1="0" y1="0" x2="%(unitScale)s" y2="0" stroke-width="3" />
<text x="0" y="20" style="stroke:#000000">1 %(uom)s </text>
-->
</g>"""
PATHTEMPLATE = '\t\t\t<path d="%s" />\n'
class UNITS:
MM = "mm"
IN = "in"
def guessUnitOfMeasure(shape):
"""
Guess the unit of measure of a shape.
"""
bb = BoundBox._fromTopoDS(shape.wrapped)
dimList = [bb.xlen, bb.ylen, bb.zlen]
# no real part would likely be bigger than 10 inches on any side
if max(dimList) > 10:
return UNITS.MM
# no real part would likely be smaller than 0.1 mm on all dimensions
if min(dimList) < 0.1:
return UNITS.IN
# no real part would have the sum of its dimensions less than about 5mm
if sum(dimList) < 10:
return UNITS.IN
return UNITS.MM
def makeSVGedge(e):
"""
Creates an SVG edge from a OCCT edge.
"""
cs = StringIO.StringIO()
curve = e._geomAdaptor() # adapt the edge into curve
start = curve.FirstParameter()
end = curve.LastParameter()
points = GCPnts_QuasiUniformDeflection(curve, DISCRETIZATION_TOLERANCE, start, end)
if points.IsDone():
point_it = (points.Value(i + 1) for i in range(points.NbPoints()))
p = next(point_it)
cs.write("M{},{} ".format(p.X(), p.Y()))
for p in point_it:
cs.write("L{},{} ".format(p.X(), p.Y()))
return cs.getvalue()
def getPaths(visibleShapes, hiddenShapes):
"""
Collects the visible and hidden edges from the CadQuery object.
"""
hiddenPaths = []
visiblePaths = []
for s in visibleShapes:
for e in s.Edges():
visiblePaths.append(makeSVGedge(e))
for s in hiddenShapes:
for e in s.Edges():
hiddenPaths.append(makeSVGedge(e))
return (hiddenPaths, visiblePaths)
def getSVG(shape, opts=None):
"""
Export a shape to SVG text.
:param shape: A CadQuery shape object to convert to an SVG string.
:type Shape: Vertex, Edge, Wire, Face, Shell, Solid, or Compound.
:param opts: An options dictionary that influences the SVG that is output.
:type opts: Dictionary, keys are as follows:
width: Width of the resulting image (None to fit based on height).
height: Height of the resulting image (None to fit based on width).
marginLeft: Inset margin from the left side of the document.
marginTop: Inset margin from the top side of the document.
projectionDir: Direction the camera will view the shape from.
showAxes: Whether or not to show the axes indicator, which will only be
visible when the projectionDir is also at the default.
strokeWidth: Width of the line that visible edges are drawn with.
strokeColor: Color of the line that visible edges are drawn with.
hiddenColor: Color of the line that hidden edges are drawn with.
showHidden: Whether or not to show hidden lines.
focus: If specified, creates a perspective SVG with the projector
at the distance specified.
"""
# Available options and their defaults
d = {
"width": 800,
"height": 240,
"marginLeft": 200,
"marginTop": 20,
"projectionDir": (-1.75, 1.1, 5),
"showAxes": True,
"strokeWidth": -1.0, # -1 = calculated based on unitScale
"strokeColor": (0, 0, 0), # RGB 0-255
"hiddenColor": (160, 160, 160), # RGB 0-255
"showHidden": True,
"focus": None,
}
if opts:
d.update(opts)
# need to guess the scale and the coordinate center
uom = guessUnitOfMeasure(shape)
# Handle the case where the height or width are None
width = d["width"]
if width != None:
width = float(d["width"])
height = d["height"]
if d["height"] != None:
height = float(d["height"])
marginLeft = float(d["marginLeft"])
marginTop = float(d["marginTop"])
projectionDir = tuple(d["projectionDir"])
showAxes = bool(d["showAxes"])
strokeWidth = float(d["strokeWidth"])
strokeColor = tuple(d["strokeColor"])
hiddenColor = tuple(d["hiddenColor"])
showHidden = bool(d["showHidden"])
focus = float(d["focus"]) if d.get("focus") else None
hlr = HLRBRep_Algo()
hlr.Add(shape.wrapped)
coordinate_system = gp_Ax2(gp_Pnt(), gp_Dir(*projectionDir))
if focus is not None:
projector = HLRAlgo_Projector(coordinate_system, focus)
else:
projector = HLRAlgo_Projector(coordinate_system)
hlr.Projector(projector)
hlr.Update()
hlr.Hide()
hlr_shapes = HLRBRep_HLRToShape(hlr)
visible = []
visible_sharp_edges = hlr_shapes.VCompound()
if not visible_sharp_edges.IsNull():
visible.append(visible_sharp_edges)
visible_smooth_edges = hlr_shapes.Rg1LineVCompound()
if not visible_smooth_edges.IsNull():
visible.append(visible_smooth_edges)
visible_contour_edges = hlr_shapes.OutLineVCompound()
if not visible_contour_edges.IsNull():
visible.append(visible_contour_edges)
hidden = []
hidden_sharp_edges = hlr_shapes.HCompound()
if not hidden_sharp_edges.IsNull():
hidden.append(hidden_sharp_edges)
hidden_contour_edges = hlr_shapes.OutLineHCompound()
if not hidden_contour_edges.IsNull():
hidden.append(hidden_contour_edges)
# Fix the underlying geometry - otherwise we will get segfaults
for el in visible:
BRepLib.BuildCurves3d_s(el, TOLERANCE)
for el in hidden:
BRepLib.BuildCurves3d_s(el, TOLERANCE)
# convert to native CQ objects
visible = list(map(Shape, visible))
hidden = list(map(Shape, hidden))
(hiddenPaths, visiblePaths) = getPaths(visible, hidden)
# get bounding box -- these are all in 2D space
bb = Compound.makeCompound(hidden + visible).BoundingBox()
# Determine whether the user wants to fit the drawing to the bounding box
if width == None or height == None:
# Fit image to specified width (or height)
if width == None:
width = (height - (2.0 * marginTop)) * (
bb.xlen / bb.ylen
) + 2.0 * marginLeft
else:
height = (width - 2.0 * marginLeft) * (bb.ylen / bb.xlen) + 2.0 * marginTop
# width pixels for x, height pixels for y
unitScale = (width - 2.0 * marginLeft) / bb.xlen
else:
bb_scale = 0.75
# width pixels for x, height pixels for y
unitScale = min(width / bb.xlen * bb_scale, height / bb.ylen * bb_scale)
# compute amount to translate-- move the top left into view
(xTranslate, yTranslate) = (
(0 - bb.xmin) + marginLeft / unitScale,
(0 - bb.ymax) - marginTop / unitScale,
)
# If the user did not specify a stroke width, calculate it based on the unit scale
if strokeWidth == -1.0:
strokeWidth = 1.0 / unitScale
# compute paths
hiddenContent = ""
# Prevent hidden paths from being added if the user disabled them
if showHidden:
for p in hiddenPaths:
hiddenContent += PATHTEMPLATE % p
visibleContent = ""
for p in visiblePaths:
visibleContent += PATHTEMPLATE % p
# If the caller wants the axes indicator and is using the default direction, add in the indicator
if showAxes and projectionDir == (-1.75, 1.1, 5):
axesIndicator = AXES_TEMPLATE % (
{"unitScale": str(unitScale), "textboxY": str(height - 30), "uom": str(uom)}
)
else:
axesIndicator = ""
svg = SVG_TEMPLATE % (
{
"unitScale": str(unitScale),
"strokeWidth": str(strokeWidth),
"strokeColor": ",".join([str(x) for x in strokeColor]),
"hiddenColor": ",".join([str(x) for x in hiddenColor]),
"hiddenContent": hiddenContent,
"visibleContent": visibleContent,
"xTranslate": str(xTranslate),
"yTranslate": str(yTranslate),
"width": str(width),
"height": str(height),
"textboxY": str(height - 30),
"uom": str(uom),
"axesIndicator": axesIndicator,
}
)
return svg
def exportSVG(shape, fileName: str, opts=None):
"""
Accept a cadquery shape, and export it to the provided file
TODO: should use file-like objects, not a fileName, and/or be able to return a string instead
export a view of a part to svg
"""
svg = getSVG(shape.val(), opts)
f = open(fileName, "w")
f.write(svg)
f.close()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,523 | CadQuery/cadquery | refs/heads/master | /tests/test_exporters.py | """
Tests exporters
"""
# core modules
import os
import io
from pathlib import Path
import re
import sys
import math
import pytest
import ezdxf
from pytest import approx
# my modules
from cadquery import (
exporters,
importers,
Sketch,
Workplane,
Edge,
Vertex,
Assembly,
Plane,
Location,
Vector,
Color,
)
from cadquery.occ_impl.exporters.dxf import DxfDocument
from cadquery.occ_impl.exporters.utils import toCompound
from tests import BaseTest
from OCP.GeomConvert import GeomConvert
from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeEdge
@pytest.fixture(scope="module")
def tmpdir(tmp_path_factory):
return tmp_path_factory.mktemp("out")
@pytest.fixture(scope="module")
def testdatadir():
return Path(__file__).parent.joinpath("testdata")
@pytest.fixture()
def box123():
return Workplane().box(1, 2, 3)
def test_step_options(tmpdir):
"""
Exports a box using the options to decrease STEP file size and
then imports that STEP to validate it.
"""
# Use a temporary directory
box_path = os.path.join(tmpdir, "out.step")
# Simple object to export
box = Workplane().box(1, 1, 1)
# Export the STEP with the size-saving options and then import it back in
box.val().exportStep(box_path, write_pcurves=False, precision_mode=0)
w = importers.importStep(box_path)
# Make sure there was a valid box in the exported file
assert w.solids().size() == 1
assert w.faces().size() == 6
def test_fused_assembly(tmpdir):
"""
Exports as simple assembly using the "fused" STEP export mode
and then imports that STEP again to validate it.
"""
# Create the sample assembly
assy = Assembly()
body = Workplane().box(10, 10, 10)
assy.add(body, color=Color(1, 0, 0), name="body")
pin = Workplane().center(2, 2).cylinder(radius=2, height=20)
assy.add(pin, color=Color(0, 1, 0), name="pin")
# Export the assembly
step_path = os.path.join(tmpdir, "fused.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 1
def test_fused_not_touching_assembly(tmpdir):
"""
Exports as simple assembly using the "fused" STEP export mode
and then imports that STEP again to validate it. This tests whether
or not the fuse method correctly handles fusing solids to do not touch.
"""
# Create the sample assembly
assy = Assembly()
body = Workplane().box(10, 10, 10)
assy.add(body, color=Color(1, 0, 0), name="body")
pin = Workplane().center(8, 8).cylinder(radius=2, height=20)
assy.add(pin, color=Color(0, 1, 0), name="pin")
# Export the assembly
step_path = os.path.join(tmpdir, "fused_not_touching.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 2
def test_nested_fused_assembly(tmpdir):
"""
Tests a nested assembly being exported as a single, fused solid.
The resulting STEP is imported again to test it.
"""
# Create the nested assembly
assy = Assembly()
body = Workplane().box(10, 10, 10)
assy.add(body, color=Color(1, 0, 0), name="body")
pins = Assembly()
pin1 = Workplane().center(8, 8).cylinder(radius=2, height=20)
pin2 = Workplane().center(-8, -8).cylinder(radius=2, height=20)
pins.add(pin1, color=Color(0, 1, 0), name="pin1")
pins.add(pin2, color=Color(0, 0, 1), name="pin2")
assy.add(pins, name="pins")
# Export the assembly
step_path = os.path.join(tmpdir, "nested_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 3
def test_fused_assembly_with_one_part(tmpdir):
"""
Tests the ability to fuse an assembly with only one part present.
The resulting STEP is imported again to test it.
"""
# Create the single-part assembly
assy = Assembly()
body = Workplane().box(10, 10, 10)
assy.add(body, color=Color(1, 0, 0), name="body")
# Export the assembly
step_path = os.path.join(tmpdir, "single_part_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 1
def test_fused_assembly_glue_tol(tmpdir):
"""
Tests the glue and tol settings of the fused assembly export.
The resulting STEP is imported again to test it.
"""
# Create the sample assembly
assy = Assembly()
body = Workplane().box(10, 10, 10)
assy.add(body, color=Color(1, 0, 0), name="body")
pin = Workplane().center(8, 8).cylinder(radius=2, height=20)
assy.add(pin, color=Color(0, 1, 0), name="pin")
# Export the assembly
step_path = os.path.join(tmpdir, "fused_glue_tol.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
fuzzy_tol=0.1,
glue=True,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 2
def test_fused_assembly_top_level_only(tmpdir):
"""
Tests the assembly with only a top level shape and no children.
The resulting STEP is imported again to test it.
"""
# Create the assembly
body = Workplane().box(10, 10, 10)
assy = Assembly(body)
# Export the assembly
step_path = os.path.join(tmpdir, "top_level_only_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 1
def test_fused_assembly_top_level_with_children(tmpdir):
"""
Tests the assembly with a top level shape and multiple children.
The resulting STEP is imported again to test it.
"""
# Create the assembly
body = Workplane().box(10, 10, 10)
assy = Assembly(body)
mark = Workplane().center(3, 3).cylinder(radius=1, height=10)
assy.add(mark, color=Color(1, 0, 0), name="mark")
pin = Workplane().center(-5, -5).cylinder(radius=2, height=20)
assy.add(pin, loc=Location(Vector(0, 0, 15)), color=Color(0, 1, 0), name="pin")
# Export the assembly
step_path = os.path.join(tmpdir, "top_level_with_children_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
# Import the assembly and make sure it acts as expected
model = importers.importStep(step_path)
assert model.solids().size() == 1
assert model.faces(">Z").val().Center().z == approx(25)
def test_fused_empty_assembly(tmpdir):
"""
Tests that a save of an empty fused assembly will fail.
"""
# Create the assembly
assy = Assembly()
# Make sure an export with no top level shape raises an exception
with pytest.raises(Exception):
# Export the assembly
step_path = os.path.join(tmpdir, "empty_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode=exporters.assembly.ExportModes.FUSED,
)
def test_fused_invalid_mode(tmpdir):
"""
Tests that an exception is raised when a user passes a bad mode
for assembly export to STEP.
"""
# Create the assembly
body = Workplane().box(10, 10, 10)
assy = Assembly(body)
# Make sure an export with an invalid export mode raises an exception
with pytest.raises(Exception):
# Export the assembly
step_path = os.path.join(tmpdir, "invalid_mode_fused_assembly.step")
assy.save(
path=str(step_path),
exportType=exporters.ExportTypes.STEP,
mode="INCORRECT",
)
class TestDxfDocument(BaseTest):
"""Test class DxfDocument."""
def test_line(self):
workplane = Workplane().line(1, 1)
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
edges = shape.Edges()
result = DxfDocument._dxf_line(edges[0])
expected = ("LINE", {"start": (0.0, 0.0, 0.0), "end": (1.0, 1.0, 0.0)})
self.assertEqual(expected, result)
def test_circle(self):
workplane = Workplane().circle(1)
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
edges = shape.Edges()
result = DxfDocument._dxf_circle(edges[0])
expected = ("CIRCLE", {"center": (0.0, 0.0, 0.0), "radius": 1.0})
self.assertEqual(expected, result)
def test_arc(self):
workplane = Workplane().radiusArc((1, 1), 1)
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
edges = shape.Edges()
result_type, result_attributes = DxfDocument._dxf_circle(edges[0])
expected_type, expected_attributes = (
"ARC",
{"center": (1, 0, 0), "radius": 1, "start_angle": 90, "end_angle": 180,},
)
self.assertEqual(expected_type, result_type)
self.assertTupleAlmostEquals(
expected_attributes["center"], result_attributes["center"], 3
)
self.assertAlmostEqual(
expected_attributes["radius"], approx(result_attributes["radius"])
)
self.assertAlmostEqual(
expected_attributes["start_angle"], result_attributes["start_angle"]
)
self.assertAlmostEqual(
expected_attributes["end_angle"], result_attributes["end_angle"]
)
def test_ellipse(self):
workplane = Workplane().ellipse(2, 1, 0)
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
edges = shape.Edges()
result_type, result_attributes = DxfDocument._dxf_ellipse(edges[0])
expected_type, expected_attributes = (
"ELLIPSE",
{
"center": (0, 0, 0),
"major_axis": (2.0, 0, 0),
"ratio": 0.5,
"start_param": 0,
"end_param": 6.283185307179586,
},
)
self.assertEqual(expected_type, result_type)
self.assertEqual(expected_attributes["center"], result_attributes["center"])
self.assertEqual(
expected_attributes["major_axis"], result_attributes["major_axis"]
)
self.assertEqual(expected_attributes["ratio"], result_attributes["ratio"])
self.assertEqual(
expected_attributes["start_param"], result_attributes["start_param"]
)
self.assertAlmostEqual(
expected_attributes["end_param"], result_attributes["end_param"]
)
def test_spline(self):
pts = [(0, 0), (0, 0.5), (1, 1)]
workplane = (
Workplane().spline(pts).close().extrude(1).edges("|Z").fillet(0.1).section()
)
plane = workplane.plane
shape = toCompound(workplane).transformShape(plane.fG)
edges = shape.Edges()
result_type, result_attributes = DxfDocument._dxf_spline(edges[0], plane)
expected_type, expected_attributes = (
"SPLINE",
{
"control_points": [
(-0.032010295564216654, 0.2020130195642037, 0.0),
(-0.078234124721739, 0.8475143728081896, 0.0),
(0.7171193004814275, 0.9728923786984539, 0.0),
],
"order": 3,
"knots": [
0.18222956891558767,
0.18222956891558767,
0.18222956891558767,
1.416096480384525,
1.416096480384525,
1.416096480384525,
],
"weights": None,
},
)
self.assertEqual(expected_type, result_type)
self.assertAlmostEqual(
expected_attributes["control_points"], result_attributes["control_points"]
)
self.assertEqual(expected_attributes["order"], result_attributes["order"])
self.assertEqual(expected_attributes["knots"], result_attributes["knots"])
self.assertEqual(expected_attributes["weights"], result_attributes["weights"])
def test_add_layer_definition(self):
dxf = DxfDocument()
dxf.add_layer("layer_1")
self.assertIn("layer_1", dxf.document.layers)
def test_add_layer_definition_with_color(self):
dxf = DxfDocument()
dxf.add_layer("layer_1", color=2)
layer = dxf.document.layers.get("layer_1")
self.assertEqual(2, layer.color)
def test_add_layer_definition_with_linetype(self):
dxf = DxfDocument(setup=True)
dxf.add_layer("layer_1", linetype="CENTER")
layer = dxf.document.layers.get("layer_1")
self.assertEqual("CENTER", layer.dxf.linetype)
def test_add_shape_to_layer(self):
line = Workplane().line(0, 10)
dxf = DxfDocument(setup=True)
default_layer_names = set()
for layer in dxf.document.layers:
default_layer_names.add(layer.dxf.name)
dxf = dxf.add_layer("layer_1").add_shape(line, "layer_1")
expected_layer_names = default_layer_names.copy()
expected_layer_names.add("layer_1")
self.assertEqual({"0", "Defpoints"}, default_layer_names)
self.assertEqual(1, len(dxf.msp))
self.assertEqual({"0", "Defpoints", "layer_1"}, expected_layer_names)
self.assertEqual("layer_1", dxf.msp[0].dxf.layer)
self.assertEqual("LINE", dxf.msp[0].dxftype())
def test_set_dxf_version(self):
dxfversion = "AC1032"
dxf_default = DxfDocument()
dxf = DxfDocument(dxfversion=dxfversion)
self.assertNotEqual(dxfversion, dxf_default.document.dxfversion)
self.assertEqual(dxfversion, dxf.document.dxfversion)
def test_set_units(self):
doc_units = 17
dxf_default = DxfDocument()
dxf = DxfDocument(doc_units=17)
self.assertNotEqual(doc_units, dxf_default.document.units)
self.assertEqual(doc_units, dxf.document.units)
def test_set_metadata(self):
metadata = {"CUSTOM_KEY": "custom value"}
dxf = DxfDocument(metadata=metadata)
self.assertEqual(
metadata["CUSTOM_KEY"], dxf.document.ezdxf_metadata().get("CUSTOM_KEY"),
)
def test_add_shape_line(self):
workplane = Workplane().line(1, 1)
dxf = DxfDocument()
dxf.add_shape(workplane)
result = dxf.msp.query("LINE")[0]
expected = ezdxf.entities.line.Line.new(
dxfattribs={"start": (0.0, 0.0, 0.0), "end": (1.0, 1.0, 0.0),},
)
self.assertEqual(expected.dxf.start, result.dxf.start)
self.assertEqual(expected.dxf.end, result.dxf.end)
def test_DxfDocument_import(self):
assert isinstance(exporters.DxfDocument(), DxfDocument)
class TestExporters(BaseTest):
def _exportBox(self, eType, stringsToFind, tolerance=0.1, angularTolerance=0.1):
"""
Exports a test object, and then looks for
all of the supplied strings to be in the result
returns the result in case the case wants to do more checks also
"""
p = Workplane("XY").box(1, 2, 3)
if eType in (exporters.ExportTypes.AMF, exporters.ExportTypes.THREEMF):
s = io.BytesIO()
else:
s = io.StringIO()
exporters.exportShape(
p, eType, s, tolerance=tolerance, angularTolerance=angularTolerance
)
result = "{}".format(s.getvalue())
for q in stringsToFind:
self.assertTrue(result.find(q) > -1)
return result
def _box(self):
return Workplane().box(1, 1, 1)
def testSTL(self):
# New STL tests have been added; Keep this to test deprecated exportShape
self._exportBox(exporters.ExportTypes.STL, ["facet normal"])
def testSVG(self):
self._exportBox(exporters.ExportTypes.SVG, ["<svg", "<g transform"])
exporters.export(self._box(), "out.svg")
def testSVGOptions(self):
self._exportBox(exporters.ExportTypes.SVG, ["<svg", "<g transform"])
exporters.export(
self._box(),
"out.svg",
opt={
"width": 100,
"height": None,
"marginLeft": 10,
"marginTop": 10,
"showAxes": False,
"projectionDir": (0, 0, 1),
"strokeWidth": 0.25,
"strokeColor": (255, 0, 0),
"hiddenColor": (0, 0, 255),
"showHidden": True,
"focus": 4,
},
)
exporters.export(
self._box(),
"out.svg",
opt={
"width": None,
"height": 100,
"marginLeft": 10,
"marginTop": 10,
"showAxes": False,
"projectionDir": (0, 0, 1),
"strokeWidth": 0.25,
"strokeColor": (255, 0, 0),
"hiddenColor": (0, 0, 255),
"showHidden": True,
"focus": 4,
},
)
def testAMF(self):
self._exportBox(exporters.ExportTypes.AMF, ["<amf units", "</object>"])
exporters.export(self._box(), "out.amf")
def testSTEP(self):
self._exportBox(exporters.ExportTypes.STEP, ["FILE_SCHEMA"])
exporters.export(self._box(), "out.step")
def test3MF(self):
self._exportBox(
exporters.ExportTypes.THREEMF,
["3D/3dmodel.model", "[Content_Types].xml", "_rels/.rels"],
)
exporters.export(self._box(), "out1.3mf") # Compound
exporters.export(self._box().val(), "out2.3mf") # Solid
# No zlib support
import zlib
sys.modules["zlib"] = None
exporters.export(self._box(), "out3.3mf")
sys.modules["zlib"] = zlib
def testTJS(self):
self._exportBox(
exporters.ExportTypes.TJS, ["vertices", "formatVersion", "faces"]
)
exporters.export(self._box(), "out.tjs")
def testVRML(self):
exporters.export(self._box(), "out.vrml")
with open("out.vrml") as f:
res = f.read(10)
assert res.startswith("#VRML V2.0")
# export again to trigger all paths in the code
exporters.export(self._box(), "out.vrml")
def testVTP(self):
exporters.export(self._box(), "out.vtp")
with open("out.vtp") as f:
res = f.read(100)
assert res.startswith('<?xml version="1.0"?>\n<VTKFile')
def testDXF(self):
exporters.export(self._box().section(), "out.dxf")
with self.assertRaises(ValueError):
exporters.export(self._box().val(), "out.dxf")
s1 = (
Workplane("XZ")
.polygon(10, 10)
.ellipse(1, 2)
.extrude(1)
.edges("|Y")
.fillet(1)
.section()
)
exporters.dxf.exportDXF(s1, "res1.dxf")
s1_i = importers.importDXF("res1.dxf")
self.assertAlmostEqual(s1.val().Area(), s1_i.val().Area(), 6)
self.assertAlmostEqual(s1.edges().size(), s1_i.edges().size())
pts = [(0, 0), (0, 0.5), (1, 1)]
s2 = (
Workplane().spline(pts).close().extrude(1).edges("|Z").fillet(0.1).section()
)
exporters.dxf.exportDXF(s2, "res2.dxf")
s2_i = importers.importDXF("res2.dxf")
self.assertAlmostEqual(s2.val().Area(), s2_i.val().Area(), 6)
self.assertAlmostEqual(s2.edges().size(), s2_i.edges().size())
s3 = (
Workplane("XY")
.ellipseArc(1, 2, 0, 180)
.close()
.extrude(1)
.edges("|Z")
.fillet(0.1)
.section()
)
exporters.dxf.exportDXF(s3, "res3.dxf")
s3_i = importers.importDXF("res3.dxf")
self.assertAlmostEqual(s3.val().Area(), s3_i.val().Area(), 6)
self.assertAlmostEqual(s3.edges().size(), s3_i.edges().size())
cyl = Workplane("XY").circle(22).extrude(10, both=True).translate((-50, 0, 0))
s4 = Workplane("XY").box(80, 60, 5).cut(cyl).section()
exporters.dxf.exportDXF(s4, "res4.dxf")
s4_i = importers.importDXF("res4.dxf")
self.assertAlmostEqual(s4.val().Area(), s4_i.val().Area(), 6)
self.assertAlmostEqual(s4.edges().size(), s4_i.edges().size())
# test periodic spline
w = Workplane().spline([(1, 1), (2, 2), (3, 2), (3, 1)], periodic=True)
exporters.dxf.exportDXF(w, "res5.dxf")
w_i = importers.importDXF("res5.dxf")
self.assertAlmostEqual(w.val().Length(), w_i.wires().val().Length(), 6)
# test rational spline
c = Edge.makeCircle(1)
adaptor = c._geomAdaptor()
curve = GeomConvert.CurveToBSplineCurve_s(adaptor.Curve().Curve())
e = Workplane().add(Edge(BRepBuilderAPI_MakeEdge(curve).Shape()))
exporters.dxf.exportDXF(e, "res6.dxf")
e_i = importers.importDXF("res6.dxf")
self.assertAlmostEqual(e.val().Length(), e_i.wires().val().Length(), 6)
# test non-planar section
s5 = (
Workplane()
.spline([(0, 0), (1, 0), (1, 1), (0, 1)])
.close()
.extrude(1, both=True)
.translate((-3, -4, 0))
)
s5.plane = Plane(origin=(0, 0.1, 0.5), normal=(0.05, 0.05, 1))
s5 = s5.section()
exporters.dxf.exportDXF(s5, "res7.dxf")
s5_i = importers.importDXF("res7.dxf")
self.assertAlmostEqual(s5.val().Area(), s5_i.val().Area(), 4)
def testTypeHandling(self):
with self.assertRaises(ValueError):
exporters.export(self._box(), "out.random")
with self.assertRaises(ValueError):
exporters.export(self._box(), "out.stl", "STP")
@pytest.mark.parametrize(
"id, opt, matchvals",
[
(0, {"ascii": True}, ["solid", "facet normal"]),
(1, {"ASCII": True}, ["solid", "facet normal"]),
(2, {"unknown_opt": 1, "ascii": True}, ["solid", "facet normal"]),
(3, {"ASCII": False, "ascii": True}, ["solid", "facet normal"]),
],
)
def test_stl_ascii(tmpdir, box123, id, opt, matchvals):
"""
:param tmpdir: temporary directory fixture
:param box123: box fixture
:param id: The index or id; output filename is <test name>_<id>.stl
:param opt: The export opt dict
:param matchval: List of strings to match at start of file
"""
fpath = tmpdir.joinpath(f"stl_ascii_{id}.stl").resolve()
assert not fpath.exists()
assert matchvals
exporters.export(box123, str(fpath), None, 0.1, 0.1, opt)
with open(fpath, "r") as f:
for i, line in enumerate(f):
if i > len(matchvals) - 1:
break
assert line.find(matchvals[i]) > -1
@pytest.mark.parametrize(
"id, opt, matchval",
[
(0, None, b"STL Exported by Open CASCADE"),
(1, {"ascii": False}, b"STL Exported by Open CASCADE"),
(2, {"ASCII": False}, b"STL Exported by Open CASCADE"),
(3, {"unknown_opt": 1}, b"STL Exported by Open CASCADE"),
(4, {"unknown_opt": 1, "ascii": False}, b"STL Exported by Open CASCADE"),
],
)
def test_stl_binary(tmpdir, box123, id, opt, matchval):
"""
:param tmpdir: temporary directory fixture
:param box123: box fixture
:param id: The index or id; output filename is <test name>_<id>.stl
:param opt: The export opt dict
:param matchval: Check that the file starts with the specified value
"""
fpath = tmpdir.joinpath(f"stl_binary_{id}.stl").resolve()
assert not fpath.exists()
assert matchval
exporters.export(box123, str(fpath), None, 0.1, 0.1, opt)
with open(fpath, "rb") as f:
r = f.read(len(matchval))
assert r == matchval
def test_assy_vtk_rotation(tmpdir):
v0 = Vertex.makeVertex(1, 0, 0)
assy = Assembly()
assy.add(
v0, name="v0", loc=Location(Vector(0, 0, 0), Vector(1, 0, 0), 90),
)
fwrl = Path(tmpdir, "v0.wrl")
assert not fwrl.exists()
assy.save(str(fwrl), "VRML")
assert fwrl.exists()
matched_rot = False
with open(fwrl) as f:
pat_rot = re.compile("""rotation 1 0 0 1.5707963267""")
for line in f:
if m := re.search(pat_rot, line):
matched_rot = True
break
assert matched_rot
def test_tessellate(box123):
verts, triangles = box123.val().tessellate(1e-6)
assert len(verts) == 24
assert len(triangles) == 12
def _dxf_spline_max_degree(fname):
dxf = ezdxf.readfile(fname)
msp = dxf.modelspace()
rv = 0
for el in msp:
if isinstance(el, ezdxf.entities.Spline):
rv = el.dxf.degree if el.dxf.degree > rv else rv
return rv
def _check_dxf_no_spline(fname):
dxf = ezdxf.readfile(fname)
msp = dxf.modelspace()
for el in msp:
if isinstance(el, ezdxf.entities.Spline):
return False
return True
def test_dxf_approx():
pts = [(0, 0), (0, 0.5), (1, 1)]
w1 = Workplane().spline(pts).close().extrude(1).edges("|Z").fillet(0.1).section()
exporters.exportDXF(w1, "orig.dxf")
assert _dxf_spline_max_degree("orig.dxf") == 6
exporters.exportDXF(w1, "limit1.dxf", approx="spline")
w1_i1 = importers.importDXF("limit1.dxf")
assert _dxf_spline_max_degree("limit1.dxf") == 3
assert w1.val().Area() == approx(w1_i1.val().Area(), 1e-3)
assert w1.edges().size() == w1_i1.edges().size()
exporters.exportDXF(w1, "limit2.dxf", approx="arc")
w1_i2 = importers.importDXF("limit2.dxf")
assert _check_dxf_no_spline("limit2.dxf")
assert w1.val().Area() == approx(w1_i2.val().Area(), 1e-3)
def test_dxf_text(tmpdir, testdatadir):
w1 = (
Workplane("XZ")
.box(8, 8, 1)
.faces("<Y")
.workplane()
.text(
",,", 10, -1, True, fontPath=str(Path(testdatadir, "OpenSans-Regular.ttf")),
)
)
fname = tmpdir.joinpath(f"dxf_text.dxf").resolve()
exporters.exportDXF(w1.section(), fname)
s2 = Sketch().importDXF(fname)
w2 = Workplane("XZ", origin=(0, -0.5, 0)).placeSketch(s2).extrude(-1)
assert w1.val().Volume() == approx(59.983287, 1e-2)
assert w2.val().Volume() == approx(w1.val().Volume(), 1e-2)
assert w2.intersect(w1).val().Volume() == approx(w1.val().Volume(), 1e-2)
def test_dxf_ellipse_arc(tmpdir):
normal = (0, 1, 0)
plane = Plane((0, 0, 0), (1, 0, 0), normal=normal)
w1 = Workplane(plane)
r = 10
normal_reversed = (0, -1, 0)
e1 = Edge.makeEllipse(r, r, (0, 0, 0), normal_reversed, (1, 0, 1), 90, 135)
e2 = Edge.makeEllipse(r, r, (0, 0, 0), normal, (0, 0, -1), 45, 90)
e3 = Edge.makeLine(
(0, 0, 0), (-r * math.sin(math.pi / 4), 0, r * math.sin(math.pi / 4))
)
e4 = Edge.makeLine(
(0, 0, 0), (-r * math.sin(math.pi / 4), 0, -r * math.sin(math.pi / 4))
)
w1.add([e1, e2, e3, e4])
dxf = exporters.dxf.DxfDocument()
dxf.add_layer("layer1", color=1)
dxf.add_shape(w1, "layer1")
fname = tmpdir.joinpath("ellipse_arc.dxf").resolve()
dxf.document.saveas(fname)
s1 = Sketch().importDXF(fname)
w2 = Workplane("XZ", origin=(0, 0, 0)).placeSketch(s1).extrude(1)
assert w2.val().isValid()
assert w2.val().Volume() == approx(math.pi * r ** 2 / 4)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,524 | CadQuery/cadquery | refs/heads/master | /tests/test_assembly.py | import pytest
import os
from itertools import product
from math import degrees
import copy
from pathlib import Path, PurePath
import re
import cadquery as cq
from cadquery.occ_impl.exporters.assembly import (
exportAssembly,
exportCAF,
exportVTKJS,
exportVRML,
)
from cadquery.occ_impl.assembly import toJSON, toCAF, toFusedCAF
from cadquery.occ_impl.shapes import Face
from cadquery.occ_impl.geom import Location
from OCP.gp import gp_XYZ
from OCP.TDocStd import TDocStd_Document
from OCP.TDataStd import TDataStd_Name
from OCP.TCollection import TCollection_ExtendedString
from OCP.XCAFPrs import (
XCAFPrs_DocumentExplorer,
XCAFPrs_DocumentExplorerFlags_None,
XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes,
XCAFPrs_Style,
)
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType
from OCP.XCAFApp import XCAFApp_Application
from OCP.STEPCAFControl import STEPCAFControl_Reader
from OCP.IFSelect import IFSelect_RetDone
from OCP.TDF import TDF_ChildIterator
from OCP.Quantity import Quantity_ColorRGBA, Quantity_TOC_RGB
from OCP.TopAbs import TopAbs_ShapeEnum
@pytest.fixture(scope="module")
def tmpdir(tmp_path_factory):
return tmp_path_factory.mktemp("assembly")
@pytest.fixture
def simple_assy():
b1 = cq.Solid.makeBox(1, 1, 1)
b2 = cq.Workplane().box(1, 1, 2)
b3 = cq.Workplane().pushPoints([(0, 0), (-2, -5)]).box(1, 1, 3)
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(2, -5, 0)))
assy.add(b2, loc=cq.Location(cq.Vector(1, 1, 0)))
assy.add(b3, loc=cq.Location(cq.Vector(2, 3, 0)))
return assy
@pytest.fixture
def nested_assy():
b1 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("top_face").end()
b2 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("bottom_face").end()
b3 = (
cq.Workplane()
.pushPoints([(-2, 0), (2, 0)])
.tag("pts")
.box(1, 1, 0.5)
.tag("boxes")
)
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(0, 0, 0)), name="TOP")
assy2 = cq.Assembly(b2, loc=cq.Location(cq.Vector(0, 4, 0)), name="SECOND")
assy2.add(b3, loc=cq.Location(cq.Vector(0, 4, 0)), name="BOTTOM")
assy.add(assy2, color=cq.Color("green"))
return assy
@pytest.fixture
def nested_assy_sphere():
b1 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("top_face").end()
b2 = cq.Workplane().box(1, 1, 1).faces("<Z").tag("bottom_face").end()
b3 = cq.Workplane().pushPoints([(-2, 0), (2, 0)]).tag("pts").sphere(1).tag("boxes")
assy = cq.Assembly(b1, loc=cq.Location(cq.Vector(0, 0, 0)), name="TOP")
assy2 = cq.Assembly(b2, loc=cq.Location(cq.Vector(0, 4, 0)), name="SECOND")
assy2.add(b3, loc=cq.Location(cq.Vector(0, 4, 0)), name="BOTTOM")
assy.add(assy2, color=cq.Color("green"))
return assy
@pytest.fixture
def empty_top_assy():
b1 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b1, color=cq.Color("green"))
return assy
@pytest.fixture
def box_and_vertex():
box_wp = cq.Workplane().box(1, 2, 3)
assy = cq.Assembly(box_wp, name="box")
vertex_wp = cq.Workplane().newObject([cq.Vertex.makeVertex(0, 0, 0)])
assy.add(vertex_wp, name="vertex")
return assy
@pytest.fixture
def metadata_assy():
b1 = cq.Solid.makeBox(1, 1, 1)
b2 = cq.Workplane().box(1, 1, 2)
assy = cq.Assembly(
b1,
loc=cq.Location(cq.Vector(2, -5, 0)),
name="base",
metadata={"b1": "base-data"},
)
sub_assy = cq.Assembly(
b2, loc=cq.Location(cq.Vector(1, 1, 1)), name="sub", metadata={"b2": "sub-data"}
)
assy.add(sub_assy)
sub_assy2 = cq.Assembly(name="sub2", metadata={"mykey": "sub2-data"})
sub_assy2.add(
b1, name="sub2-0", loc=cq.Location((1, 0, 0)), metadata={"mykey": "sub2-0-data"}
)
sub_assy2.add(
b1, name="sub2-1", loc=cq.Location((2, 0, 0)), metadata={"mykey": "sub2-1-data"}
)
assy.add(
sub_assy2, metadata={"mykey": "sub2-data-add"}
) # override metadata mykey:sub2-data
return assy
@pytest.fixture
def simple_assy2():
b1 = cq.Workplane().box(1, 1, 1)
b2 = cq.Workplane().box(2, 1, 1)
assy = cq.Assembly()
assy.add(b1, name="b1")
assy.add(b2, loc=cq.Location(cq.Vector(0, 0, 4)), name="b2")
return assy
@pytest.fixture
def single_compound0_assy():
b0 = cq.Workplane().rect(1, 2).extrude(3, both=True)
assy = cq.Assembly(name="single_compound0")
assy.add(b0, color=cq.Color(1, 0, 0, 0.8))
return assy
@pytest.fixture
def single_compound1_assy():
b0 = cq.Workplane().circle(1).extrude(2)
b1 = cq.Workplane().circle(1).extrude(-2)
assy = cq.Assembly(name="single_compound1")
assy.add(
cq.Compound.makeCompound([b0.val(), b1.val()]), color=cq.Color(1, 0, 0, 0.8)
)
return assy
@pytest.fixture
def boxes0_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", color=cq.Color("red"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes1_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly(name="boxes", color=cq.Color("red"))
assy.add(b0, name="box0")
assy.add(b0, name="box1", loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes2_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes3_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box0", color=cq.Color("red"))
assy.add(b0, name="box1", loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes4_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box_0", color=cq.Color("red"))
assy.add(b0, name="box_1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes5_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box:a", color=cq.Color("red"))
assy.add(b0, name="box:b", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes6_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box__0", color=cq.Color("red"))
assy.add(b0, name="box__1", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
return assy
@pytest.fixture
def boxes7_assy():
b0 = cq.Workplane().box(1, 1, 1)
assy = cq.Assembly()
assy.add(b0, name="box_0", color=cq.Color("red"))
assy.add(b0, name="box", color=cq.Color("green"), loc=cq.Location((1, 0, 0)))
assy.add(
b0,
name="another box",
color=cq.Color(0.23, 0.26, 0.26, 0.6),
loc=cq.Location((2, 0, 0)),
)
return assy
@pytest.fixture
def spheres0_assy():
b0 = cq.Workplane().sphere(1)
assy = cq.Assembly(name="spheres0")
assy.add(b0, name="a", color=cq.Color(1, 0, 0, 0.2))
assy.add(b0, name="b", color=cq.Color(0, 1, 0, 0.2), loc=cq.Location((2.1, 0, 0)))
return assy
@pytest.fixture
def chassis0_assy():
r_wheel = 25
w_wheel = 10
l_axle = 80
l_chassis = 100
wheel = cq.Workplane("YZ").circle(r_wheel).extrude(w_wheel, both=True)
axle = cq.Workplane("YZ").circle(r_wheel / 10).extrude(l_axle / 2, both=True)
wheel_axle = cq.Assembly(name="wheel-axle")
wheel_axle.add(
wheel,
name="wheel:left",
color=cq.Color("red"),
loc=cq.Location((-l_axle / 2 - w_wheel, 0, 0)),
)
wheel_axle.add(
wheel,
name="wheel:right",
color=cq.Color("red"),
loc=cq.Location((l_axle / 2 + w_wheel, 0, 0)),
)
wheel_axle.add(axle, name="axle", color=cq.Color("green"))
chassis = cq.Assembly(name="chassis")
chassis.add(
wheel_axle, name="wheel-axle-front", loc=cq.Location((0, l_chassis / 2, 0))
)
chassis.add(
wheel_axle, name="wheel-axle-rear", loc=cq.Location((0, -l_chassis / 2, 0))
)
return chassis
def read_step(stepfile) -> TDocStd_Document:
"""Read STEP file, return XCAF document"""
app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("XmlOcaf"))
app.InitDocument(doc)
reader = STEPCAFControl_Reader()
status = reader.ReadFile(str(stepfile))
assert status == IFSelect_RetDone
reader.Transfer(doc)
return doc
def get_doc_nodes(doc, leaf=False):
"""Read document and return list of nodes (dicts)"""
if leaf:
flags = XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes
else:
flags = XCAFPrs_DocumentExplorerFlags_None
expl = XCAFPrs_DocumentExplorer(doc, flags, XCAFPrs_Style())
tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
nodes = []
while expl.More():
node = expl.Current()
ctool = expl.ColorTool()
style = node.Style
label = node.RefLabel
name_att = TDataStd_Name()
label.FindAttribute(TDataStd_Name.GetID_s(), name_att)
name = TCollection_ExtendedString(name_att.Get()).ToExtString()
color = style.GetColorSurfRGBA()
shape = expl.FindShapeFromPathId_s(doc, node.Id)
color_shape = Quantity_ColorRGBA()
ctool.GetColor(shape, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_shape)
# on STEP import colors applied to subshapes; and fused export mode
color_subshapes = None
color_subshapes_set = set()
faces = []
if not node.IsAssembly:
it = TDF_ChildIterator(label)
i = 0
while it.More():
child = it.Value()
child_shape = tool.GetShape_s(child)
if child_shape.ShapeType() == TopAbs_ShapeEnum.TopAbs_FACE:
face = Face(child_shape)
color_subshape = Quantity_ColorRGBA()
face_color = None
if ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorGen, color_subshape
) or ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_subshape
):
face_color = (
*color_subshape.GetRGB().Values(Quantity_TOC_RGB),
color_subshape.Alpha(),
)
faces.append(
{"center": face.Center().toTuple(), "color": face_color}
)
else:
color_subshape = Quantity_ColorRGBA()
if ctool.GetColor_s(
child, XCAFDoc_ColorType.XCAFDoc_ColorSurf, color_subshape
):
color_subshapes_set.add(
(
*color_subshape.GetRGB().Values(Quantity_TOC_RGB),
color_subshape.Alpha(),
)
)
it.Next()
if color_subshapes_set:
color_subshapes = color_subshapes_set.pop()
nodes.append(
{
"path": PurePath(node.Id.ToCString()),
"name": TCollection_ExtendedString(name_att.Get()).ToExtString(),
"color": (*color.GetRGB().Values(Quantity_TOC_RGB), color.Alpha()),
"color_shape": (
*color_shape.GetRGB().Values(Quantity_TOC_RGB),
color_shape.Alpha(),
),
"color_subshapes": color_subshapes,
"faces": faces,
}
)
expl.Next()
return nodes
def find_node(node_list, name_path):
"""Return node(s) matching node name path
:param node_list: list of nodes (output of get_doc_nodes)
:param name_path: list of node names (corresponding to path)
"""
def purepath_is_relative_to(p0, p1):
"""Alternative to PurePath.is_relative_to for Python 3.8
PurePath.is_relative_to is new in Python 3.9
"""
try:
if p0.relative_to(p1):
is_relative_to = True
except ValueError:
is_relative_to = False
return is_relative_to
def get_nodes(node_list, name, parents):
if parents:
nodes = []
for parent in parents:
nodes.extend(
[
p
for p in node_list
# if p["path"].is_relative_to(parent["path"])
if purepath_is_relative_to(p["path"], parent["path"])
and len(p["path"].relative_to(parent["path"]).parents) == 1
and re.fullmatch(name, p["name"])
and p not in nodes
]
)
else:
nodes = [p for p in node_list if re.fullmatch(name, p["name"])]
return nodes
parents = None
for name in name_path:
nodes = get_nodes(node_list, name, parents)
parents = nodes
return nodes
def test_metadata(metadata_assy):
"""Verify the metadata is present in both the base and sub assemblies"""
assert metadata_assy.metadata["b1"] == "base-data"
# The metadata should be able to be modified
metadata_assy.metadata["b2"] = 0
assert len(metadata_assy.metadata) == 2
# Test that metadata was copied by _copy() during the processing of adding the subassembly
assert metadata_assy.children[0].metadata["b2"] == "sub-data"
assert metadata_assy.children[1].metadata["mykey"] == "sub2-data-add"
assert metadata_assy.children[1].children[0].metadata["mykey"] == "sub2-0-data"
assert metadata_assy.children[1].children[1].metadata["mykey"] == "sub2-1-data"
def solve_result_check(solve_result: dict) -> bool:
checks = [
solve_result["success"] == True,
solve_result["iterations"]["inf_pr"][-1] < 1e-9,
]
return all(checks)
def test_color():
c1 = cq.Color("red")
assert c1.wrapped.GetRGB().Red() == 1
assert c1.wrapped.Alpha() == 1
c2 = cq.Color(1, 0, 0)
assert c2.wrapped.GetRGB().Red() == 1
assert c2.wrapped.Alpha() == 1
c3 = cq.Color(1, 0, 0, 0.5)
assert c3.wrapped.GetRGB().Red() == 1
assert c3.wrapped.Alpha() == 0.5
c4 = cq.Color()
with pytest.raises(ValueError):
cq.Color("?????")
with pytest.raises(ValueError):
cq.Color(1, 2, 3, 4, 5)
def test_assembly(simple_assy, nested_assy):
# basic checks
assert len(simple_assy.objects) == 3
assert len(simple_assy.children) == 2
assert len(simple_assy.shapes) == 1
assert len(nested_assy.objects) == 3
assert len(nested_assy.children) == 1
assert nested_assy.objects["SECOND"].parent is nested_assy
# bottom-up traversal
kvs = list(nested_assy.traverse())
assert kvs[0][0] == "BOTTOM"
assert len(kvs[0][1].shapes[0].Solids()) == 2
assert kvs[-1][0] == "TOP"
@pytest.mark.parametrize(
"assy_fixture, root_name", [("simple_assy", None), ("nested_assy", "TOP")],
)
def test_assy_root_name(assy_fixture, root_name, request):
assy = request.getfixturevalue(assy_fixture)
_, doc = toCAF(assy, True)
root = get_doc_nodes(doc, False)[0]
if root_name:
assert root["name"] == root_name
else:
# When a name is not user-specifed, the name is assigned a UUID
m = re.findall(r"[0-9a-f]+", root["name"])
assert list(map(len, m)) == [8, 4, 4, 4, 12]
def test_step_export(nested_assy, tmp_path_factory):
# Use a temporary directory
tmpdir = tmp_path_factory.mktemp("out")
nested_path = os.path.join(tmpdir, "nested.step")
nested_options_path = os.path.join(tmpdir, "nested_options.step")
exportAssembly(nested_assy, nested_path)
exportAssembly(
nested_assy, nested_options_path, write_pcurves=False, precision_mode=0
)
w = cq.importers.importStep(nested_path)
o = cq.importers.importStep(nested_options_path)
assert w.solids().size() == 4
assert o.solids().size() == 4
# check that locations were applied correctly
c = cq.Compound.makeCompound(w.solids().vals()).Center()
c.toTuple()
assert pytest.approx(c.toTuple()) == (0, 4, 0)
c2 = cq.Compound.makeCompound(o.solids().vals()).Center()
c2.toTuple()
assert pytest.approx(c2.toTuple()) == (0, 4, 0)
def test_native_export(simple_assy):
exportCAF(simple_assy, "assy.xml")
# only sanity check for now
assert os.path.exists("assy.xml")
def test_vtkjs_export(nested_assy):
exportVTKJS(nested_assy, "assy")
# only sanity check for now
assert os.path.exists("assy.zip")
def test_vrml_export(simple_assy):
exportVRML(simple_assy, "assy.wrl")
# only sanity check for now
assert os.path.exists("assy.wrl")
def test_toJSON(simple_assy, nested_assy, empty_top_assy):
r1 = toJSON(simple_assy)
r2 = toJSON(simple_assy)
r3 = toJSON(empty_top_assy)
assert len(r1) == 3
assert len(r2) == 3
assert len(r3) == 1
@pytest.mark.parametrize(
"extension, args",
[
("step", ()),
("xml", ()),
("stp", ("STEP",)),
("caf", ("XML",)),
("wrl", ("VRML",)),
("stl", ("STL",)),
],
)
def test_save(extension, args, nested_assy, nested_assy_sphere):
filename = "nested." + extension
nested_assy.save(filename, *args)
assert os.path.exists(filename)
def test_save_gltf(nested_assy_sphere):
nested_assy_sphere.save("nested.glb", "GLTF")
assert os.path.exists("nested.glb")
assert os.path.getsize("nested.glb") > 50 * 1024
def test_save_gltf_boxes2(boxes2_assy, tmpdir, capfd):
"""
Output must not contain:
RWGltf_CafWriter skipped node '<name>' without triangulation data
"""
boxes2_assy.save(str(Path(tmpdir, "boxes2_assy.glb")), "GLTF")
output = capfd.readouterr()
assert output.out == ""
assert output.err == ""
def test_save_vtkjs(nested_assy):
nested_assy.save("nested", "VTKJS")
assert os.path.exists("nested.zip")
def test_save_raises(nested_assy):
with pytest.raises(ValueError):
nested_assy.save("nested.dxf")
with pytest.raises(ValueError):
nested_assy.save("nested.step", "DXF")
@pytest.mark.parametrize(
"assy_fixture, count",
[("simple_assy", 3), ("nested_assy", 3), ("empty_top_assy", 1),],
)
def test_leaf_node_count(assy_fixture, count, request):
assy = request.getfixturevalue(assy_fixture)
_, doc = toCAF(assy, True)
assert len(get_doc_nodes(doc, True)) == count
@pytest.mark.parametrize(
"assy_fixture, expected",
[
(
"chassis0_assy",
[
(
["chassis", "wheel-axle.*", "wheel:.*"],
{
"color": (1.0, 0.0, 0.0, 1.0),
"color_shape": (1.0, 0.0, 0.0, 1.0),
"num_nodes": 4,
},
),
(
["chassis", "wheel-axle.*", "wheel:.*", "wheel.*_part"],
{"color": (1.0, 0.0, 0.0, 1.0), "num_nodes": 4},
),
(
["chassis", "wheel-axle.*", "axle"],
{
"color": (0.0, 1.0, 0.0, 1.0),
"color_shape": (0.0, 1.0, 0.0, 1.0),
"num_nodes": 2,
},
),
(
["chassis", "wheel-axle.*", "axle", "axle_part"],
{"color": (0.0, 1.0, 0.0, 1.0), "num_nodes": 2},
),
],
),
],
)
def test_colors_assy0(assy_fixture, expected, request):
"""Validate assembly colors with document explorer.
Check toCAF wth color shape parameter False.
"""
def check_nodes(doc, expected):
allnodes = get_doc_nodes(doc, False)
for name_path, props in expected:
nodes = find_node(allnodes, name_path)
if "num_nodes" in props:
assert len(nodes) == props["num_nodes"]
props.pop("num_nodes")
else:
assert len(nodes) > 0
for n in nodes:
for k, v in props.items():
assert pytest.approx(n[k], abs=1e-3) == v
assy = request.getfixturevalue(assy_fixture)
_, doc = toCAF(assy, False)
check_nodes(doc, expected)
@pytest.mark.parametrize(
"assy_fixture, expected",
[
(
"nested_assy",
[
(
["TOP", "SECOND", "SECOND_part"],
{"color_shape": (0.0, 1.0, 0.0, 1.0)},
),
(
["TOP", "SECOND", "BOTTOM", "BOTTOM_part"],
{
"color_shape": (0.0, 1.0, 0.0, 1.0),
"color_subshapes": (0.0, 1.0, 0.0, 1.0),
},
),
],
),
("empty_top_assy", [([".*_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),]),
(
"boxes0_assy",
[
(["box0", "box0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box1", "box1_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
],
),
(
"boxes1_assy",
[
(["box0", "box0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box1", "box0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
],
),
(
"boxes2_assy",
[
(["box0", "box0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box1", "box1_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),
],
),
(
"boxes3_assy",
[
(["box0", "box0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(
["box1", "box1_part"],
{"color_shape": cq.Color().toTuple()},
), # default color when unspecified
],
),
(
"boxes4_assy",
[
(["box_0", "box_0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box_1", "box_1_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),
],
),
(
"boxes5_assy",
[
(["box:a", "box:a_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box:b", "box:b_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),
],
),
(
"boxes6_assy",
[
(["box__0", "box__0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box__1", "box__1_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),
],
),
(
"boxes7_assy",
[
(["box_0", "box_0_part"], {"color_shape": (1.0, 0.0, 0.0, 1.0)}),
(["box", "box_part"], {"color_shape": (0.0, 1.0, 0.0, 1.0)}),
(
["another box", "another box_part"],
{"color_shape": (0.23, 0.26, 0.26, 0.6)},
),
],
),
(
"chassis0_assy",
[
(
["chassis", "wheel-axle-front", "wheel:left", "wheel:left_part"],
{"color_shape": (1.0, 0.0, 0.0, 1.0)},
),
(
["chassis", "wheel-axle-front", "wheel:right", "wheel:right_part"],
{"color_shape": (1.0, 0.0, 0.0, 1.0)},
),
(
["chassis", "wheel-axle-rear", "wheel:left", "wheel:left_part"],
{"color_shape": (1.0, 0.0, 0.0, 1.0)},
),
(
["chassis", "wheel-axle-rear", "wheel:right", "wheel:right_part"],
{"color_shape": (1.0, 0.0, 0.0, 1.0)},
),
(
["chassis", "wheel-axle-front", "axle", "axle_part"],
{"color_shape": (0.0, 1.0, 0.0, 1.0)},
),
(
["chassis", "wheel-axle-rear", "axle", "axle_part"],
{"color_shape": (0.0, 1.0, 0.0, 1.0)},
),
],
),
],
)
def test_colors_assy1(assy_fixture, expected, request, tmpdir):
"""Validate assembly colors with document explorer.
Check both documents created with toCAF and STEP export round trip.
"""
def check_nodes(doc, expected, is_STEP=False):
expected = copy.deepcopy(expected)
allnodes = get_doc_nodes(doc, False)
for name_path, props in expected:
nodes = find_node(allnodes, name_path)
if "num_nodes" in props:
assert len(nodes) == props["num_nodes"]
props.pop("num_nodes")
else:
assert len(nodes) > 0
for n in nodes:
if not is_STEP:
if "color_subshapes" in props:
props.pop("color_subshapes")
for k, v in props.items():
if (
k == "color_shape"
and "color_subshapes" in props
and props["color_subshapes"]
):
continue
assert pytest.approx(n[k], abs=1e-3) == v
assy = request.getfixturevalue(assy_fixture)
_, doc = toCAF(assy, True)
check_nodes(doc, expected)
# repeat color check again - after STEP export round trip
stepfile = Path(tmpdir, assy_fixture).with_suffix(".step")
if not stepfile.exists():
assy.save(str(stepfile))
doc = read_step(stepfile)
check_nodes(doc, expected, True)
@pytest.mark.parametrize(
"assy_fixture, expected",
[
(
"empty_top_assy",
{
"faces": [
{"center": (-0.5, 0, 0), "color": (0, 1, 0, 1)},
{"center": (0.5, 0, 0), "color": (0, 1, 0, 1)},
{"center": (0, -0.5, 0), "color": (0, 1, 0, 1)},
{"center": (0, 0.5, 0), "color": (0, 1, 0, 1)},
{"center": (0, 0, -0.5), "color": (0, 1, 0, 1)},
{"center": (0, 0, 0.5), "color": (0, 1, 0, 1)},
]
},
),
(
"single_compound0_assy",
{
"name": "single_compound0",
"faces": [
{"center": (-0.5, 0, 0), "color": (1, 0, 0, 0.8)},
{"center": (0.5, 0, 0), "color": (1, 0, 0, 0.8)},
{"center": (0, -1.0, 0), "color": (1, 0, 0, 0.8)},
{"center": (0, 1.0, 0), "color": (1, 0, 0, 0.8)},
{"center": (0, 0, -3.0), "color": (1, 0, 0, 0.8)},
{"center": (0, 0, 3.0), "color": (1, 0, 0, 0.8)},
],
},
),
(
"single_compound1_assy",
{
"faces": [
{"center": (0, 0, -1.0), "color": (1, 0, 0, 0.8)},
{"center": (0, 0, 1.0), "color": (1, 0, 0, 0.8)},
{"center": (0, 0, -2.0), "color": (1, 0, 0, 0.8)},
{"center": (0, 0, 2.0), "color": (1, 0, 0, 0.8)},
]
},
),
(
"spheres0_assy",
{
"faces": [
{"center": (0, 0, 0), "color": (1, 0, 0, 0.2)},
{"center": (2.1, 0, 0), "color": (0, 1, 0, 0.2)},
]
},
),
(
"boxes2_assy",
{
"faces": [
{"center": (-0.5, 0, 0), "color": (1, 0, 0, 1)},
{"center": (0, -0.5, 0), "color": (1, 0, 0, 1)},
{"center": (0, 0, 0.5), "color": (1, 0, 0, 1)},
{"center": (0, 0.5, 0), "color": (1, 0, 0, 1)},
{"center": (0, 0, -0.5), "color": (1, 0, 0, 1)},
{"center": (1.0, -0.5, 0), "color": (0, 1, 0, 1)},
{"center": (1.0, 0, 0.5), "color": (0, 1, 0, 1)},
{"center": (1.0, 0.5, 0), "color": (0, 1, 0, 1)},
{"center": (1.0, 0, -0.5), "color": (0, 1, 0, 1)},
{"center": (1.5, 0, 0), "color": (0, 1, 0, 1)},
]
},
),
(
"chassis0_assy",
{
"faces": [
# wheel
{"center": (-40.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-45.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-55.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-60.0, 50.0, 0), "color": (1, 0, 0, 1)},
# wheel
{"center": (40.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (45.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (55.0, 50.0, 0), "color": (1, 0, 0, 1)},
{"center": (60.0, 50.0, 0), "color": (1, 0, 0, 1)},
# axle
{"center": (-20.0, 50.0, 0), "color": (0, 1, 0, 1)},
{"center": (20.0, 50.0, 0), "color": (0, 1, 0, 1)},
# wheel
{"center": (-40.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-45.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-55.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (-60.0, -50.0, 0), "color": (1, 0, 0, 1)},
# wheel
{"center": (40.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (45.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (55.0, -50.0, 0), "color": (1, 0, 0, 1)},
{"center": (60.0, -50.0, 0), "color": (1, 0, 0, 1)},
# axle
{"center": (-20.0, -50.0, 0), "color": (0, 1, 0, 1)},
{"center": (20.0, -50.0, 0), "color": (0, 1, 0, 1)},
]
},
),
],
)
def test_colors_fused_assy(assy_fixture, expected, request, tmpdir):
def check_nodes(doc, expected):
nodes = get_doc_nodes(doc, False)
assert len(nodes) == 1
count_face = 0
if "name" in expected:
assert expected["name"] == nodes[0]["name"]
for props in expected["faces"]:
for props_doc in nodes[0]["faces"]:
if (
pytest.approx(props["center"], abs=1e-6) == props_doc["center"]
and pytest.approx(props["color"], abs=1e-3) == props_doc["color"]
):
count_face += 1
assert len(expected["faces"]) == count_face
assy = request.getfixturevalue(assy_fixture)
_, doc = toFusedCAF(assy, False)
check_nodes(doc, expected)
# repeat color check again - after STEP export round trip
stepfile = Path(tmpdir, f"{assy_fixture}_fused").with_suffix(".step")
if not stepfile.exists():
assy.save(str(stepfile), mode=cq.exporters.assembly.ExportModes.FUSED)
doc = read_step(stepfile)
check_nodes(doc, expected)
def test_constrain(simple_assy, nested_assy):
subassy1 = simple_assy.children[0]
subassy2 = simple_assy.children[1]
b1 = simple_assy.obj
b2 = subassy1.obj
b3 = subassy2.obj
simple_assy.constrain(
simple_assy.name, b1.Faces()[0], subassy1.name, b2.faces("<Z").val(), "Plane"
)
simple_assy.constrain(
simple_assy.name, b1.Faces()[0], subassy2.name, b3.faces("<Z").val(), "Axis"
)
simple_assy.constrain(
subassy1.name,
b2.faces(">Z").val(),
subassy2.name,
b3.faces("<Z").val(),
"Point",
)
assert len(simple_assy.constraints) == 3
nested_assy.constrain("TOP@faces@>Z", "SECOND/BOTTOM@faces@<Z", "Plane")
nested_assy.constrain("TOP@faces@>X", "SECOND/BOTTOM@faces@<X", "Axis")
assert len(nested_assy.constraints) == 2
constraint = nested_assy.constraints[0]
assert constraint.objects == ("TOP", "SECOND")
assert (
constraint.sublocs[0]
.wrapped.Transformation()
.TranslationPart()
.IsEqual(gp_XYZ(), 1e-9)
)
assert constraint.sublocs[1].wrapped.IsEqual(
nested_assy.objects["SECOND/BOTTOM"].loc.wrapped
)
simple_assy.solve()
assert solve_result_check(simple_assy._solve_result)
assert (
simple_assy.loc.wrapped.Transformation()
.TranslationPart()
.IsEqual(gp_XYZ(2, -5, 0), 1e-9)
)
assert (
simple_assy.children[0]
.loc.wrapped.Transformation()
.TranslationPart()
.IsEqual(gp_XYZ(-1, 0.5, 0.5), 1e-6)
)
nested_assy.solve()
assert solve_result_check(nested_assy._solve_result)
assert (
nested_assy.children[0]
.loc.wrapped.Transformation()
.TranslationPart()
.IsEqual(gp_XYZ(2, -4, 0.75), 1e-6)
)
def test_constrain_with_tags(nested_assy):
nested_assy.add(None, name="dummy")
nested_assy.constrain("TOP?top_face", "SECOND/BOTTOM", "Point")
assert len(nested_assy.constraints) == 1
# test selection of a non-shape object
with pytest.raises(ValueError):
nested_assy.constrain("SECOND/BOTTOM ? pts", "dummy", "Plane")
def test_duplicate_name(nested_assy):
with pytest.raises(ValueError):
nested_assy.add(None, name="SECOND")
def test_empty_solve(nested_assy):
with pytest.raises(ValueError):
nested_assy.solve()
def test_expression_grammar(nested_assy):
nested_assy.constrain(
"TOP@faces@>Z", "SECOND/BOTTOM@vertices@>X and >Y and >Z", "Point"
)
def test_PointInPlane_constraint(box_and_vertex):
# add first constraint
box_and_vertex.constrain(
"vertex",
box_and_vertex.children[0].obj.val(),
"box",
box_and_vertex.obj.faces(">X").val(),
"PointInPlane",
param=0,
)
box_and_vertex.solve()
solve_result_check(box_and_vertex._solve_result)
x_pos = (
box_and_vertex.children[0].loc.wrapped.Transformation().TranslationPart().X()
)
assert x_pos == pytest.approx(0.5)
# add a second PointInPlane constraint
box_and_vertex.constrain("vertex", "box@faces@>Y", "PointInPlane", param=0)
box_and_vertex.solve()
solve_result_check(box_and_vertex._solve_result)
vertex_translation_part = (
box_and_vertex.children[0].loc.wrapped.Transformation().TranslationPart()
)
# should still be on the >X face from the first constraint
assert vertex_translation_part.X() == pytest.approx(0.5)
# now should additionally be on the >Y face
assert vertex_translation_part.Y() == pytest.approx(1)
# add a third PointInPlane constraint
box_and_vertex.constrain("vertex", "box@faces@>Z", "PointInPlane", param=0)
box_and_vertex.solve()
solve_result_check(box_and_vertex._solve_result)
# should now be on the >X and >Y and >Z corner
assert (
box_and_vertex.children[0]
.loc.wrapped.Transformation()
.TranslationPart()
.IsEqual(gp_XYZ(0.5, 1, 1.5), 1e-6)
)
def test_PointInPlane_3_parts(box_and_vertex):
cylinder_height = 2
cylinder = cq.Workplane().circle(0.1).extrude(cylinder_height)
box_and_vertex.add(cylinder, name="cylinder")
box_and_vertex.constrain("box@faces@>Z", "cylinder@faces@<Z", "Plane")
box_and_vertex.constrain("vertex", "cylinder@faces@>Z", "PointInPlane")
box_and_vertex.constrain("vertex", "box@faces@>X", "PointInPlane")
box_and_vertex.solve()
solve_result_check(box_and_vertex._solve_result)
vertex_translation_part = (
box_and_vertex.children[0].loc.wrapped.Transformation().TranslationPart()
)
assert vertex_translation_part.Z() == pytest.approx(1.5 + cylinder_height)
assert vertex_translation_part.X() == pytest.approx(0.5)
@pytest.mark.parametrize("param1", [-1, 0, 2])
@pytest.mark.parametrize("param0", [-2, 0, 0.01])
def test_PointInPlane_param(box_and_vertex, param0, param1):
box_and_vertex.constrain("vertex", "box@faces@>Z", "PointInPlane", param=param0)
box_and_vertex.constrain("vertex", "box@faces@>X", "PointInPlane", param=param1)
box_and_vertex.solve()
solve_result_check(box_and_vertex._solve_result)
vertex_translation_part = (
box_and_vertex.children[0].loc.wrapped.Transformation().TranslationPart()
)
assert vertex_translation_part.Z() - 1.5 == pytest.approx(param0, abs=1e-6)
assert vertex_translation_part.X() - 0.5 == pytest.approx(param1, abs=1e-6)
def test_constraint_getPln():
"""
Test that _getPln does the right thing with different arguments
"""
ids = (0, 1)
sublocs = (cq.Location(), cq.Location())
def make_constraint(shape0):
return cq.Constraint(ids, (shape0, shape0), sublocs, "PointInPlane", 0)
def fail_this(shape0):
with pytest.raises(ValueError):
make_constraint(shape0)
def resulting_pln(shape0):
c0 = make_constraint(shape0)
return c0._getPln(c0.args[0])
def resulting_plane(shape0):
p0 = resulting_pln(shape0)
return cq.Plane(
cq.Vector(p0.Location()),
cq.Vector(p0.XAxis().Direction()),
cq.Vector(p0.Axis().Direction()),
)
# point should fail
fail_this(cq.Vertex.makeVertex(0, 0, 0))
# line should fail
fail_this(cq.Edge.makeLine(cq.Vector(1, 0, 0), cq.Vector(0, 0, 0)))
# planar edge (circle) should succeed
origin = cq.Vector(1, 2, 3)
direction = cq.Vector(4, 5, 6).normalized()
p1 = resulting_plane(cq.Edge.makeCircle(1, pnt=origin, dir=direction))
assert p1.zDir == direction
assert p1.origin == origin
# planar edge (spline) should succeed
# it's a touch risky calling a spline a planar edge, but lets see if it's within tolerance
points0 = [cq.Vector(x) for x in [(-1, 0, 1), (0, 1, 1), (1, 0, 1), (0, -1, 1)]]
planar_spline = cq.Edge.makeSpline(points0, periodic=True)
p2 = resulting_plane(planar_spline)
assert p2.origin == planar_spline.Center()
assert p2.zDir == cq.Vector(0, 0, 1)
# non-planar edge should fail
points1 = [cq.Vector(x) for x in [(-1, 0, -1), (0, 1, 1), (1, 0, -1), (0, -1, 1)]]
nonplanar_spline = cq.Edge.makeSpline(points1, periodic=True)
fail_this(nonplanar_spline)
# planar wire should succeed
# make a triangle in the XZ plane
points2 = [cq.Vector(x) for x in [(-1, 0, -1), (0, 0, 1), (1, 0, -1)]]
points2.append(points2[0])
triangle = cq.Wire.makePolygon(points2)
p3 = resulting_plane(triangle)
assert p3.origin == triangle.Center()
assert p3.zDir == cq.Vector(0, 1, 0)
# non-planar wire should fail
points3 = [cq.Vector(x) for x in [(-1, 0, -1), (0, 1, 1), (1, 0, 0), (0, -1, 1)]]
wonky_shape = cq.Wire.makePolygon(points3)
fail_this(wonky_shape)
# all makePlane faces should succeed
for length, width in product([None, 10], [None, 11]):
f0 = cq.Face.makePlane(
length=length, width=width, basePnt=(1, 2, 3), dir=(1, 0, 0)
)
p4 = resulting_plane(f0)
if length and width:
assert p4.origin == cq.Vector(1, 2, 3)
assert p4.zDir == cq.Vector(1, 0, 0)
f1 = cq.Face.makeFromWires(triangle, [])
p5 = resulting_plane(f1)
# not sure why, but the origins only roughly line up
assert (p5.origin - triangle.Center()).Length < 0.1
assert p5.zDir == cq.Vector(0, 1, 0)
# shell... not sure?
# solid should fail
fail_this(cq.Solid.makeBox(1, 1, 1))
def test_toCompound(simple_assy, nested_assy):
c0 = simple_assy.toCompound()
assert isinstance(c0, cq.Compound)
assert len(c0.Solids()) == 4
c1 = nested_assy.toCompound()
assert isinstance(c1, cq.Compound)
assert len(c1.Solids()) == 4
# check nested assy location appears in compound
# create four boxes, stack them on top of each other, check highest face is in final compound
box0 = cq.Workplane().box(1, 1, 3, centered=(True, True, False))
box1 = cq.Workplane().box(1, 1, 4)
box2 = cq.Workplane().box(1, 1, 5)
box3 = cq.Workplane().box(1, 1, 6)
# top level assy
assy0 = cq.Assembly(box0, name="box0")
assy0.add(box1, name="box1")
assy0.constrain("box0@faces@>Z", "box1@faces@<Z", "Plane")
# subassy
assy1 = cq.Assembly()
assy1.add(box2, name="box2")
assy1.add(box3, name="box3")
assy1.constrain("box2@faces@>Z", "box3@faces@<Z", "Plane")
assy1.solve()
assy0.add(assy1, name="assy1")
assy0.constrain("box1@faces@>Z", "assy1/box2@faces@<Z", "Plane")
# before solving there should be no face with Center = (0, 0, 18)
c2 = assy0.toCompound()
assert not cq.Vector(0, 0, 18) in [x.Center() for x in c2.Faces()]
# after solving there should be a face with Center = (0, 0, 18)
assy0.solve()
c3 = assy0.toCompound()
assert cq.Vector(0, 0, 18) in [x.Center() for x in c3.Faces()]
# also check with bounding box
assert c3.BoundingBox().zlen == pytest.approx(18)
@pytest.mark.parametrize("origin", [(0, 0, 0), (10, -10, 10)])
@pytest.mark.parametrize("normal", [(0, 0, 1), (-1, -1, 1)])
def test_infinite_face_constraint_PointInPlane(origin, normal):
"""
An OCCT infinite face has a center at (1e99, 1e99), but when a user uses it
in a constraint, the center should be basePnt.
"""
f0 = cq.Face.makePlane(length=None, width=None, basePnt=origin, dir=normal)
c0 = cq.assembly.Constraint(
("point", "plane"),
(cq.Vertex.makeVertex(10, 10, 10), f0),
sublocs=(cq.Location(), cq.Location()),
kind="PointInPlane",
)
p0 = c0._getPln(c0.args[1]) # a gp_Pln
derived_origin = cq.Vector(p0.Location())
assert derived_origin == cq.Vector(origin)
@pytest.mark.parametrize("kind", ["Plane", "PointInPlane", "Point"])
def test_infinite_face_constraint_Plane(kind):
assy = cq.Assembly(cq.Workplane().sphere(1), name="part0")
assy.add(cq.Workplane().sphere(1), name="part1")
assy.constrain(
"part0", cq.Face.makePlane(), "part1", cq.Face.makePlane(), kind,
)
assy.solve()
assert solve_result_check(assy._solve_result)
def test_unary_constraints(simple_assy2):
assy = simple_assy2
assy.constrain("b1", "Fixed")
assy.constrain("b2", "FixedPoint", (0, 0, -3))
assy.constrain("b2@faces@>Z", "FixedAxis", (0, 1, 1))
assy.solve()
w = cq.Workplane().add(assy.toCompound())
assert w.solids(">Z").val().Center().Length == pytest.approx(0)
assert w.solids("<Z").val().Center().z == pytest.approx(-3)
assert w.solids("<Z").edges(">Z").size() == 1
def test_fixed_rotation(simple_assy2):
assy = simple_assy2
assy.constrain("b1", "Fixed")
assy.constrain("b2", "FixedPoint", (0, 0, -3))
assy.constrain("b2@faces@>Z", "FixedRotation", (45, 0, 0))
assy.solve()
w = cq.Workplane().add(assy.toCompound())
assert w.solids(">Z").val().Center().Length == pytest.approx(0)
assert w.solids("<Z").val().Center().z == pytest.approx(-3)
assert w.solids("<Z").edges(">Z").size() == 1
def test_constraint_validation(simple_assy2):
with pytest.raises(ValueError):
simple_assy2.constrain("b1", "Fixed?")
with pytest.raises(ValueError):
cq.assembly.Constraint((), (), (), "Fixed?")
def test_single_unary_constraint(simple_assy2):
with pytest.raises(ValueError):
simple_assy2.constrain("b1", "FixedRotation", (45, 0, 45))
simple_assy2.solve()
def test_point_on_line(simple_assy2):
assy = simple_assy2
assy.constrain("b1", "Fixed")
assy.constrain("b2@faces@>Z", "FixedAxis", (0, 2, 1))
assy.constrain("b2@faces@>X", "FixedAxis", (1, 0, 0))
assy.constrain("b2@faces@>X", "b1@edges@>>Z and >>Y", "PointOnLine")
assy = assy.solve()
w = cq.Workplane().add(assy.toCompound())
assert w.solids("<Z").val().Center().Length == pytest.approx(0)
assert w.solids(">Z").val().Center().z == pytest.approx(0.5)
assert w.solids(">Z").val().Center().y == pytest.approx(0.5)
assert w.solids(">Z").val().Center().x == pytest.approx(0.0)
def test_axis_constraint(simple_assy2):
assy = simple_assy2
assy.constrain("b1@faces@>Z", "b2@faces@>Z", "Axis", 0)
assy.constrain("b1@faces@>X", "b2@faces@>X", "Axis", 45)
assy.solve()
q2 = assy.children[1].loc.wrapped.Transformation().GetRotation()
assert degrees(q2.GetRotationAngle()) == pytest.approx(45)
def test_point_constraint(simple_assy2):
assy = simple_assy2
assy.constrain("b1", "b2", "Point", 1)
assy.solve()
t2 = assy.children[1].loc.wrapped.Transformation().TranslationPart()
assert t2.Modulus() == pytest.approx(1)
@pytest.fixture
def touching_assy():
b1 = cq.Workplane().box(1, 1, 1)
b2 = cq.Workplane(origin=(1, 0, 0)).box(1, 1, 1)
return cq.Assembly().add(b1).add(b2)
@pytest.fixture
def disjoint_assy():
b1 = cq.Workplane().box(1, 1, 1)
b2 = cq.Workplane(origin=(2, 0, 0)).box(1, 1, 1)
return cq.Assembly().add(b1).add(b2)
def test_imprinting(touching_assy, disjoint_assy):
# normal usecase
r, o = cq.occ_impl.assembly.imprint(touching_assy)
assert len(r.Solids()) == 2
assert len(r.Faces()) == 11
for s in r.Solids():
assert s in o
# edge usecase
r, o = cq.occ_impl.assembly.imprint(disjoint_assy)
assert len(r.Solids()) == 2
assert len(r.Faces()) == 12
for s in r.Solids():
assert s in o
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,525 | CadQuery/cadquery | refs/heads/master | /tests/test_selectors.py | __author__ = "dcowden"
"""
Tests for CadQuery Selectors
These tests do not construct any solids, they test only selectors that query
an existing solid
"""
import math
import unittest
import sys
import os.path
# my modules
from tests import BaseTest, makeUnitCube, makeUnitSquareWire
from cadquery import *
from cadquery import selectors
class TestCQSelectors(BaseTest):
def testWorkplaneCenter(self):
"Test Moving workplane center"
s = Workplane(Plane.XY())
# current point and world point should be equal
self.assertTupleAlmostEquals((0.0, 0.0, 0.0), s.plane.origin.toTuple(), 3)
# move origin and confirm center moves
s = s.center(-2.0, -2.0)
# current point should be 0,0, but
self.assertTupleAlmostEquals((-2.0, -2.0, 0.0), s.plane.origin.toTuple(), 3)
def testVertices(self):
t = makeUnitSquareWire() # square box
c = CQ(t)
self.assertEqual(4, c.vertices().size())
self.assertEqual(4, c.edges().size())
self.assertEqual(0, c.vertices().edges().size()) # no edges on any vertices
# but selecting all edges still yields all vertices
self.assertEqual(4, c.edges().vertices().size())
self.assertEqual(1, c.wires().size()) # just one wire
self.assertEqual(0, c.faces().size())
# odd combinations all work but yield no results
self.assertEqual(0, c.vertices().faces().size())
self.assertEqual(0, c.edges().faces().size())
self.assertEqual(0, c.edges().vertices().faces().size())
def testEnd(self):
c = CQ(makeUnitSquareWire())
# 4 because there are 4 vertices
self.assertEqual(4, c.vertices().size())
# 1 because we started with 1 wire
self.assertEqual(1, c.vertices().end().size())
def testAll(self):
"all returns a list of CQ objects, so that you can iterate over them individually"
c = CQ(makeUnitCube())
self.assertEqual(6, c.faces().size())
self.assertEqual(6, len(c.faces().all()))
self.assertEqual(4, c.faces().all()[0].vertices().size())
def testFirst(self):
c = CQ(makeUnitCube())
self.assertEqual(type(c.vertices().first().val()), Vertex)
self.assertEqual(type(c.vertices().first().first().first().val()), Vertex)
def testCompounds(self):
c = CQ(makeUnitSquareWire())
self.assertEqual(0, c.compounds().size())
self.assertEqual(0, c.shells().size())
self.assertEqual(0, c.solids().size())
def testSolid(self):
c = CQ(makeUnitCube(False))
# make sure all the counts are right for a cube
self.assertEqual(1, c.solids().size())
self.assertEqual(6, c.faces().size())
self.assertEqual(12, c.edges().size())
self.assertEqual(8, c.vertices().size())
self.assertEqual(0, c.compounds().size())
# now any particular face should result in 4 edges and four vertices
self.assertEqual(4, c.faces().first().edges().size())
self.assertEqual(1, c.faces().first().size())
self.assertEqual(4, c.faces().first().vertices().size())
self.assertEqual(4, c.faces().last().edges().size())
def testFaceTypesFilter(self):
"Filters by face type"
c = CQ(makeUnitCube())
self.assertEqual(c.faces().size(), c.faces("%PLANE").size())
self.assertEqual(c.faces().size(), c.faces("%plane").size())
self.assertEqual(0, c.faces("%sphere").size())
self.assertEqual(0, c.faces("%cone").size())
self.assertEqual(0, c.faces("%SPHERE").size())
def testEdgeTypesFilter(self):
"Filters by edge type"
c = Workplane().ellipse(3, 4).circle(1).extrude(1)
self.assertEqual(2, c.edges("%Ellipse").size())
self.assertEqual(2, c.edges("%circle").size())
self.assertEqual(2, c.edges("%LINE").size())
self.assertEqual(0, c.edges("%Bspline").size())
self.assertEqual(0, c.edges("%Offset").size())
self.assertEqual(0, c.edges("%HYPERBOLA").size())
def testPerpendicularDirFilter(self):
c = CQ(makeUnitCube())
perp_edges = c.edges("#Z")
self.assertEqual(8, perp_edges.size()) # 8 edges are perp. to z
# dot product of perpendicular vectors is zero
for e in perp_edges.vals():
self.assertAlmostEqual(e.tangentAt(0).dot(Vector(0, 0, 1)), 0.0)
perp_faces = c.faces("#Z")
self.assertEqual(4, perp_faces.size()) # 4 faces are perp to z too!
for f in perp_faces.vals():
self.assertAlmostEqual(f.normalAt(None).dot(Vector(0, 0, 1)), 0.0)
def testFaceDirFilter(self):
c = CQ(makeUnitCube())
# a cube has one face in each direction
self.assertEqual(1, c.faces("+Z").size())
self.assertTupleAlmostEquals(
(0, 0, 1), c.faces("+Z").val().Center().toTuple(), 3
)
self.assertEqual(1, c.faces("-Z").size())
self.assertTupleAlmostEquals(
(0, 0, 0), c.faces("-Z").val().Center().toTuple(), 3
)
self.assertEqual(1, c.faces("+X").size())
self.assertTupleAlmostEquals(
(0.5, 0, 0.5), c.faces("+X").val().Center().toTuple(), 3
)
self.assertEqual(1, c.faces("-X").size())
self.assertTupleAlmostEquals(
(-0.5, 0, 0.5), c.faces("-X").val().Center().toTuple(), 3
)
self.assertEqual(1, c.faces("+Y").size())
self.assertTupleAlmostEquals(
(0, 0.5, 0.5), c.faces("+Y").val().Center().toTuple(), 3
)
self.assertEqual(1, c.faces("-Y").size())
self.assertTupleAlmostEquals(
(0, -0.5, 0.5), c.faces("-Y").val().Center().toTuple(), 3
)
self.assertEqual(0, c.faces("XY").size())
self.assertEqual(1, c.faces("X").size()) # should be same as +X
self.assertEqual(c.faces("+X").val().Center(), c.faces("X").val().Center())
self.assertNotEqual(c.faces("+X").val().Center(), c.faces("-X").val().Center())
def testBaseDirSelector(self):
# BaseDirSelector isn't intended to be instantiated, use subclass
# ParallelDirSelector to test the code in BaseDirSelector
loose_selector = ParallelDirSelector(Vector(0, 0, 1), tolerance=10)
c = Workplane(makeUnitCube(centered=True))
# BaseDirSelector should filter out everything but Faces and Edges with
# geomType LINE
self.assertNotEqual(c.vertices().size(), 0)
self.assertEqual(c.vertices(loose_selector).size(), 0)
# This has an edge that is not a LINE
c_curves = Workplane().sphere(1)
self.assertNotEqual(c_curves.edges(), 0)
self.assertEqual(c_curves.edges(loose_selector).size(), 0)
# this has a Face that is not a PLANE
face_dir = c_curves.faces().val().normalAt(None)
self.assertNotEqual(c_curves.faces(), 0)
self.assertEqual(
c_curves.faces(ParallelDirSelector(face_dir, tolerance=10)).size(), 0
)
self.assertNotEqual(c.solids().size(), 0)
self.assertEqual(c.solids(loose_selector).size(), 0)
comp = Workplane(makeUnitCube()).workplane().move(10, 10).box(1, 1, 1)
self.assertNotEqual(comp.compounds().size(), 0)
self.assertEqual(comp.compounds(loose_selector).size(), 0)
def testParallelPlaneFaceFilter(self):
c = CQ(makeUnitCube(centered=False))
# faces parallel to Z axis
# these two should produce the same behaviour:
for s in ["|Z", selectors.ParallelDirSelector(Vector(0, 0, 1))]:
parallel_faces = c.faces(s)
self.assertEqual(2, parallel_faces.size())
for f in parallel_faces.vals():
self.assertAlmostEqual(abs(f.normalAt(None).dot(Vector(0, 0, 1))), 1)
self.assertEqual(
2, c.faces(selectors.ParallelDirSelector(Vector((0, 0, -1)))).size()
) # same thing as above
# just for fun, vertices on faces parallel to z
self.assertEqual(8, c.faces("|Z").vertices().size())
# check that the X & Y center of these faces is the same as the box (ie. we haven't selected the wrong face)
faces = c.faces(selectors.ParallelDirSelector(Vector((0, 0, 1)))).vals()
for f in faces:
c = f.Center()
self.assertAlmostEqual(c.x, 0.5)
self.assertAlmostEqual(c.y, 0.5)
def testParallelEdgeFilter(self):
c = CQ(makeUnitCube())
for sel, vec in zip(
["|X", "|Y", "|Z"], [Vector(1, 0, 0), Vector(0, 1, 0), Vector(0, 0, 1)]
):
edges = c.edges(sel)
# each direction should have 4 edges
self.assertEqual(4, edges.size())
# each edge should be parallel with vec and have a cross product with a length of 0
for e in edges.vals():
self.assertAlmostEqual(e.tangentAt(0).cross(vec).Length, 0.0)
def testCenterNthSelector(self):
sel = selectors.CenterNthSelector
nothing = Workplane()
self.assertEqual(nothing.solids().size(), 0)
with self.assertRaises(ValueError):
nothing.solids(sel(Vector(0, 0, 1), 0))
c = Workplane(makeUnitCube(centered=True))
bottom_face = c.faces(sel(Vector(0, 0, 1), 0))
self.assertEqual(bottom_face.size(), 1)
self.assertTupleAlmostEquals((0, 0, 0), bottom_face.val().Center().toTuple(), 3)
side_faces = c.faces(sel(Vector(0, 0, 1), 1))
self.assertEqual(side_faces.size(), 4)
for f in side_faces.vals():
self.assertAlmostEqual(0.5, f.Center().z)
top_face = c.faces(sel(Vector(0, 0, 1), 2))
self.assertEqual(top_face.size(), 1)
self.assertTupleAlmostEquals((0, 0, 1), top_face.val().Center().toTuple(), 3)
with self.assertRaises(IndexError):
c.faces(sel(Vector(0, 0, 1), 3))
left_face = c.faces(sel(Vector(1, 0, 0), 0))
self.assertEqual(left_face.size(), 1)
self.assertTupleAlmostEquals(
(-0.5, 0, 0.5), left_face.val().Center().toTuple(), 3
)
middle_faces = c.faces(sel(Vector(1, 0, 0), 1))
self.assertEqual(middle_faces.size(), 4)
for f in middle_faces.vals():
self.assertAlmostEqual(0, f.Center().x)
right_face = c.faces(sel(Vector(1, 0, 0), 2))
self.assertEqual(right_face.size(), 1)
self.assertTupleAlmostEquals(
(0.5, 0, 0.5), right_face.val().Center().toTuple(), 3
)
with self.assertRaises(IndexError):
c.faces(sel(Vector(1, 0, 0), 3))
# lower corner faces
self.assertEqual(c.faces(sel(Vector(1, 1, 1), 0)).size(), 3)
# upper corner faces
self.assertEqual(c.faces(sel(Vector(1, 1, 1), 1)).size(), 3)
with self.assertRaises(IndexError):
c.faces(sel(Vector(1, 1, 1), 2))
for idx, z_val in zip([0, 1, 2], [0, 0.5, 1]):
edges = c.edges(sel(Vector(0, 0, 1), idx))
self.assertEqual(edges.size(), 4)
for e in edges.vals():
self.assertAlmostEqual(z_val, e.Center().z)
with self.assertRaises(IndexError):
c.edges(sel(Vector(0, 0, 1), 3))
for idx, z_val in zip([0, 1], [0, 1]):
vertices = c.vertices(sel(Vector(0, 0, 1), idx))
self.assertEqual(vertices.size(), 4)
for e in vertices.vals():
self.assertAlmostEqual(z_val, e.Z)
with self.assertRaises(IndexError):
c.vertices(sel(Vector(0, 0, 1), 3))
# test string version
face1 = c.faces(">>X[-1]")
face2 = c.faces("<<(2,0,1)[0]")
face3 = c.faces("<<X[0]")
face4 = c.faces(">>X")
self.assertTrue(face1.val().isSame(face2.val()))
self.assertTrue(face1.val().isSame(face3.val()))
self.assertTrue(face1.val().isSame(face4.val()))
prism = Workplane().rect(2, 2).extrude(1, taper=30)
# CenterNth disregards orientation
edges1 = prism.edges(">>Z[-2]")
self.assertEqual(len(edges1.vals()), 4)
# DirectionNth does not
with self.assertRaises(ValueError):
prism.edges(">Z[-2]")
# select a non-linear edge
part = (
Workplane()
.rect(10, 10, centered=False)
.extrude(1)
.faces(">Z")
.workplane(centerOption="CenterOfMass")
.move(-3, 0)
.hole(2)
)
hole = part.faces(">Z").edges(sel(Vector(1, 0, 0), 1))
# have we selected a single hole?
self.assertEqual(1, hole.size())
self.assertAlmostEqual(1, hole.val().radius())
# can we select a non-planar face?
hole_face = part.faces(sel(Vector(1, 0, 0), 1))
self.assertEqual(hole_face.size(), 1)
self.assertNotEqual(hole_face.val().geomType(), "PLANE")
# select solids
box0 = Workplane().box(1, 1, 1, centered=(True, True, True))
box1 = Workplane("XY", origin=(10, 10, 10)).box(
1, 1, 1, centered=(True, True, True)
)
part = box0.add(box1)
self.assertEqual(part.solids().size(), 2)
for direction in [(0, 0, 1), (0, 1, 0), (1, 0, 0)]:
box0_selected = part.solids(sel(Vector(direction), 0))
self.assertEqual(1, box0_selected.size())
self.assertTupleAlmostEquals(
(0, 0, 0), box0_selected.val().Center().toTuple(), 3
)
box1_selected = part.solids(sel(Vector(direction), 1))
self.assertEqual(1, box0_selected.size())
self.assertTupleAlmostEquals(
(10, 10, 10), box1_selected.val().Center().toTuple(), 3
)
def testMaxDistance(self):
c = CQ(makeUnitCube())
# should select the topmost face
self.assertEqual(1, c.faces(">Z").size())
self.assertEqual(4, c.faces(">Z").vertices().size())
# vertices should all be at z=1, if this is the top face
self.assertEqual(4, len(c.faces(">Z").vertices().vals()))
for v in c.faces(">Z").vertices().vals():
self.assertAlmostEqual(1.0, v.Z, 3)
# test the case of multiple objects at the same distance
el = c.edges(">Z").vals()
self.assertEqual(4, len(el))
for e in el:
self.assertAlmostEqual(e.Center().z, 1)
def testMinDistance(self):
c = CQ(makeUnitCube())
# should select the bottom face
self.assertEqual(1, c.faces("<Z").size())
self.assertEqual(4, c.faces("<Z").vertices().size())
# vertices should all be at z=0, if this is the bottom face
self.assertEqual(4, len(c.faces("<Z").vertices().vals()))
for v in c.faces("<Z").vertices().vals():
self.assertAlmostEqual(0.0, v.Z, 3)
# test the case of multiple objects at the same distance
el = c.edges("<Z").vals()
self.assertEqual(4, len(el))
for e in el:
self.assertAlmostEqual(e.Center().z, 0)
def testNthDistance(self):
c = Workplane("XY").pushPoints([(-2, 0), (2, 0)]).box(1, 1, 1)
# 2nd face
val = c.faces(selectors.DirectionNthSelector(Vector(1, 0, 0), 1)).val()
self.assertAlmostEqual(val.Center().x, -1.5)
# 2nd face with inversed selection vector
val = c.faces(selectors.DirectionNthSelector(Vector(-1, 0, 0), 1)).val()
self.assertAlmostEqual(val.Center().x, 1.5)
# 2nd last face
val = c.faces(selectors.DirectionNthSelector(Vector(1, 0, 0), -2)).val()
self.assertAlmostEqual(val.Center().x, 1.5)
# Last face
val = c.faces(selectors.DirectionNthSelector(Vector(1, 0, 0), -1)).val()
self.assertAlmostEqual(val.Center().x, 2.5)
# check if the selected face if normal to the specified Vector
self.assertAlmostEqual(val.normalAt().cross(Vector(1, 0, 0)).Length, 0.0)
# repeat the test using string based selector
# 2nd face
val = c.faces(">(1,0,0)[1]").val()
self.assertAlmostEqual(val.Center().x, -1.5)
val = c.faces(">X[1]").val()
self.assertAlmostEqual(val.Center().x, -1.5)
# 2nd face with inversed selection vector
val = c.faces(">(-1,0,0)[1]").val()
self.assertAlmostEqual(val.Center().x, 1.5)
val = c.faces("<X[1]").val()
self.assertAlmostEqual(val.Center().x, 1.5)
# 2nd last face
val = c.faces(">X[-2]").val()
self.assertAlmostEqual(val.Center().x, 1.5)
# Last face
val = c.faces(">X[-1]").val()
self.assertAlmostEqual(val.Center().x, 2.5)
# check if the selected face if normal to the specified Vector
self.assertAlmostEqual(val.normalAt().cross(Vector(1, 0, 0)).Length, 0.0)
# test selection of multiple faces with the same distance
c = (
Workplane("XY")
.box(1, 4, 1, centered=(False, True, False))
.faces("<Z")
.box(2, 2, 2, centered=(True, True, False))
.faces(">Z")
.box(1, 1, 1, centered=(True, True, False))
)
# select 2nd from the bottom (NB python indexing is 0-based)
vals = c.faces(">Z[1]").vals()
self.assertEqual(len(vals), 2)
val = c.faces(">Z[1]").val()
self.assertAlmostEqual(val.Center().z, 1)
# do the same but by selecting 3rd from the top
vals = c.faces("<Z[2]").vals()
self.assertEqual(len(vals), 2)
val = c.faces("<Z[2]").val()
self.assertAlmostEqual(val.Center().z, 1)
# do the same but by selecting 2nd last from the bottom
vals = c.faces("<Z[-2]").vals()
self.assertEqual(len(vals), 2)
val = c.faces("<Z[-2]").val()
self.assertAlmostEqual(val.Center().z, 1)
# note that .val() will return the workplane center if the objects list
# is empty, so to make sure this test fails with a selector that
# selects nothing, use .vals()[0]
# verify that <Z[-1] is equivalent to <Z
val1 = c.faces("<Z[-1]").vals()[0]
val2 = c.faces("<Z").vals()[0]
self.assertTupleAlmostEquals(
val1.Center().toTuple(), val2.Center().toTuple(), 3
)
# verify that >Z[-1] is equivalent to >Z
val1 = c.faces(">Z[-1]").vals()[0]
val2 = c.faces(">Z").vals()[0]
self.assertTupleAlmostEquals(
val1.Center().toTuple(), val2.Center().toTuple(), 3
)
# DirectionNthSelector should not select faces that are not perpendicular
twisted_boxes = (
Workplane()
.box(1, 1, 1, centered=(True, True, False))
.transformed(rotate=(45, 0, 0), offset=(0, 0, 3))
.box(1, 1, 1)
)
self.assertTupleAlmostEquals(
twisted_boxes.faces(">Z[-1]").val().Center().toTuple(), (0, 0, 1), 3
)
# this should select a face on the upper/rotated cube, not the lower/unrotated cube
self.assertGreater(twisted_boxes.faces("<(0, 1, 1)[-1]").val().Center().z, 1)
# verify that >Z[-1] is equivalent to >Z
self.assertTupleAlmostEquals(
twisted_boxes.faces(">(0, 1, 1)[0]").vals()[0].Center().toTuple(),
twisted_boxes.faces("<(0, 1, 1)[-1]").vals()[0].Center().toTuple(),
3,
)
def testNearestTo(self):
c = CQ(makeUnitCube(centered=False))
# nearest vertex to origin is (0,0,0)
t = (0.1, 0.1, 0.1)
v = c.vertices(selectors.NearestToPointSelector(t)).vals()[0]
self.assertTupleAlmostEquals((0.0, 0.0, 0.0), (v.X, v.Y, v.Z), 3)
t = (0.1, 0.1, 0.2)
# nearest edge is the vertical side edge, 0,0,0 -> 0,0,1
e = c.edges(selectors.NearestToPointSelector(t)).vals()[0]
v = c.edges(selectors.NearestToPointSelector(t)).vertices().vals()
self.assertEqual(2, len(v))
# nearest solid is myself
s = c.solids(selectors.NearestToPointSelector(t)).vals()
self.assertEqual(1, len(s))
def testBox(self):
c = CQ(makeUnitCube(centered=False))
# test vertice selection
test_data_vertices = [
# box point0, box point1, selected vertice
((0.9, 0.9, 0.9), (1.1, 1.1, 1.1), (1.0, 1.0, 1.0)),
((-0.1, 0.9, 0.9), (0.9, 1.1, 1.1), (0.0, 1.0, 1.0)),
((-0.1, -0.1, 0.9), (0.1, 0.1, 1.1), (0.0, 0.0, 1.0)),
((-0.1, -0.1, -0.1), (0.1, 0.1, 0.1), (0.0, 0.0, 0.0)),
((0.9, -0.1, -0.1), (1.1, 0.1, 0.1), (1.0, 0.0, 0.0)),
((0.9, 0.9, -0.1), (1.1, 1.1, 0.1), (1.0, 1.0, 0.0)),
((-0.1, 0.9, -0.1), (0.1, 1.1, 0.1), (0.0, 1.0, 0.0)),
((0.9, -0.1, 0.9), (1.1, 0.1, 1.1), (1.0, 0.0, 1.0)),
]
for d in test_data_vertices:
vl = c.vertices(selectors.BoxSelector(d[0], d[1])).vals()
self.assertEqual(1, len(vl))
v = vl[0]
self.assertTupleAlmostEquals(d[2], (v.X, v.Y, v.Z), 3)
# this time box points are swapped
vl = c.vertices(selectors.BoxSelector(d[1], d[0])).vals()
self.assertEqual(1, len(vl))
v = vl[0]
self.assertTupleAlmostEquals(d[2], (v.X, v.Y, v.Z), 3)
# test multiple vertices selection
vl = c.vertices(
selectors.BoxSelector((-0.1, -0.1, 0.9), (0.1, 1.1, 1.1))
).vals()
self.assertEqual(2, len(vl))
vl = c.vertices(
selectors.BoxSelector((-0.1, -0.1, -0.1), (0.1, 1.1, 1.1))
).vals()
self.assertEqual(4, len(vl))
# test edge selection
test_data_edges = [
# box point0, box point1, edge center
((0.4, -0.1, -0.1), (0.6, 0.1, 0.1), (0.5, 0.0, 0.0)),
((-0.1, -0.1, 0.4), (0.1, 0.1, 0.6), (0.0, 0.0, 0.5)),
((0.9, 0.9, 0.4), (1.1, 1.1, 0.6), (1.0, 1.0, 0.5)),
((0.4, 0.9, 0.9), (0.6, 1.1, 1.1,), (0.5, 1.0, 1.0),),
]
for d in test_data_edges:
el = c.edges(selectors.BoxSelector(d[0], d[1])).vals()
self.assertEqual(1, len(el))
ec = el[0].Center()
self.assertTupleAlmostEquals(d[2], (ec.x, ec.y, ec.z), 3)
# test again by swapping box points
el = c.edges(selectors.BoxSelector(d[1], d[0])).vals()
self.assertEqual(1, len(el))
ec = el[0].Center()
self.assertTupleAlmostEquals(d[2], (ec.x, ec.y, ec.z), 3)
# test multiple edge selection
el = c.edges(selectors.BoxSelector((-0.1, -0.1, -0.1), (0.6, 0.1, 0.6))).vals()
self.assertEqual(2, len(el))
el = c.edges(selectors.BoxSelector((-0.1, -0.1, -0.1), (1.1, 0.1, 0.6))).vals()
self.assertEqual(3, len(el))
# test face selection
test_data_faces = [
# box point0, box point1, face center
((0.4, -0.1, 0.4), (0.6, 0.1, 0.6), (0.5, 0.0, 0.5)),
((0.9, 0.4, 0.4), (1.1, 0.6, 0.6), (1.0, 0.5, 0.5)),
((0.4, 0.4, 0.9), (0.6, 0.6, 1.1), (0.5, 0.5, 1.0)),
((0.4, 0.4, -0.1), (0.6, 0.6, 0.1), (0.5, 0.5, 0.0)),
]
for d in test_data_faces:
fl = c.faces(selectors.BoxSelector(d[0], d[1])).vals()
self.assertEqual(1, len(fl))
fc = fl[0].Center()
self.assertTupleAlmostEquals(d[2], (fc.x, fc.y, fc.z), 3)
# test again by swapping box points
fl = c.faces(selectors.BoxSelector(d[1], d[0])).vals()
self.assertEqual(1, len(fl))
fc = fl[0].Center()
self.assertTupleAlmostEquals(d[2], (fc.x, fc.y, fc.z), 3)
# test multiple face selection
fl = c.faces(selectors.BoxSelector((0.4, 0.4, 0.4), (0.6, 1.1, 1.1))).vals()
self.assertEqual(2, len(fl))
fl = c.faces(selectors.BoxSelector((0.4, 0.4, 0.4), (1.1, 1.1, 1.1))).vals()
self.assertEqual(3, len(fl))
# test boundingbox option
el = c.edges(
selectors.BoxSelector((-0.1, -0.1, -0.1), (1.1, 0.1, 0.6), True)
).vals()
self.assertEqual(1, len(el))
fl = c.faces(
selectors.BoxSelector((0.4, 0.4, 0.4), (1.1, 1.1, 1.1), True)
).vals()
self.assertEqual(0, len(fl))
fl = c.faces(
selectors.BoxSelector((-0.1, 0.4, -0.1), (1.1, 1.1, 1.1), True)
).vals()
self.assertEqual(1, len(fl))
def testRadiusNthSelector(self):
# test the key method behaves
rad = 2.3
arc = Edge.makeCircle(radius=rad)
sel = selectors.RadiusNthSelector(0)
self.assertAlmostEqual(rad, sel.key(arc), 3)
line = Edge.makeLine(Vector(0, 0, 0), Vector(1, 1, 1))
with self.assertRaises(ValueError):
sel.key(line)
solid = makeUnitCube()
with self.assertRaises(ValueError):
sel.key(solid)
part = (
Workplane()
.box(10, 10, 1)
.edges(">(1, 1, 0) and |Z")
.fillet(1)
.edges(">(-1, 1, 0) and |Z")
.fillet(1)
.edges(">(-1, -1, 0) and |Z")
.fillet(2)
.edges(">(1, -1, 0) and |Z")
.fillet(3)
.faces(">Z")
)
# smallest radius is 1.0
self.assertAlmostEqual(
part.edges(selectors.RadiusNthSelector(0)).val().radius(), 1.0
)
# there are two edges with the smallest radius
self.assertEqual(len(part.edges(selectors.RadiusNthSelector(0)).vals()), 2)
# next radius is 2.0
self.assertAlmostEqual(
part.edges(selectors.RadiusNthSelector(1)).val().radius(), 2.0
)
# largest radius is 3.0
self.assertAlmostEqual(
part.edges(selectors.RadiusNthSelector(-1)).val().radius(), 3.0
)
# accessing index 3 should be an IndexError
with self.assertRaises(IndexError):
part.edges(selectors.RadiusNthSelector(3))
# reversed
self.assertAlmostEqual(
part.edges(selectors.RadiusNthSelector(0, directionMax=False))
.val()
.radius(),
3.0,
)
# test the selector on wires
wire_circles = (
Workplane()
.circle(2)
.moveTo(10, 0)
.circle(2)
.moveTo(20, 0)
.circle(4)
.consolidateWires()
)
self.assertEqual(
len(wire_circles.wires(selectors.RadiusNthSelector(0)).vals()), 2
)
self.assertEqual(
len(wire_circles.wires(selectors.RadiusNthSelector(1)).vals()), 1
)
self.assertAlmostEqual(
wire_circles.wires(selectors.RadiusNthSelector(0)).val().radius(), 2
)
self.assertAlmostEqual(
wire_circles.wires(selectors.RadiusNthSelector(1)).val().radius(), 4
)
def testLengthNthSelector_EmptyEdgesList(self):
"""
LengthNthSelector should raise ValueError when
applied to an empty list
"""
with self.assertRaises(ValueError):
Workplane().edges(selectors.LengthNthSelector(0))
def testLengthNthSelector_Faces(self):
"""
LengthNthSelector should produce empty list when applied
to list of unsupported Shapes (Faces)
"""
with self.assertRaises(IndexError):
Workplane().box(1, 1, 1).faces(selectors.LengthNthSelector(0))
def testLengthNthSelector_EdgesOfUnitCube(self):
"""
Selecting all edges of unit cube
"""
w1 = Workplane(makeUnitCube()).edges(selectors.LengthNthSelector(0))
self.assertEqual(
12,
w1.size(),
msg="Failed to select edges of a unit cube: wrong number of edges",
)
def testLengthNthSelector_EdgesOf123Cube(self):
"""
Selecting 4 edges of length 2 belonging to 1x2x3 box
"""
w1 = Workplane().box(1, 2, 3).edges(selectors.LengthNthSelector(1))
self.assertEqual(
4,
w1.size(),
msg="Failed to select edges of length 2 belonging to 1x2x3 box: wrong number of edges",
)
self.assertTupleAlmostEquals(
(2, 2, 2, 2),
(edge.Length() for edge in w1.vals()),
5,
msg="Failed to select edges of length 2 belonging to 1x2x3 box: wrong length",
)
def testLengthNthSelector_PlateWithHoles(self):
"""
Creating 10x10 plate with 4 holes (dia=1)
and using LengthNthSelector to select hole rims
and plate perimeter wire on the top surface/
"""
w2 = (
Workplane()
.box(10, 10, 1)
.faces(">Z")
.workplane()
.rarray(4, 4, 2, 2)
.hole(1)
.faces(">Z")
)
hole_rims = w2.wires(selectors.LengthNthSelector(0))
self.assertEqual(4, hole_rims.size())
self.assertEqual(
4, hole_rims.size(), msg="Failed to select hole rims: wrong N edges",
)
hole_circumference = math.pi * 1
self.assertTupleAlmostEquals(
[hole_circumference] * 4,
(edge.Length() for edge in hole_rims.vals()),
5,
msg="Failed to select hole rims: wrong length",
)
plate_perimeter = w2.wires(selectors.LengthNthSelector(1))
self.assertEqual(
1,
plate_perimeter.size(),
msg="Failed to select plate perimeter wire: wrong N wires",
)
self.assertAlmostEqual(
10 * 4,
plate_perimeter.val().Length(),
5,
msg="Failed to select plate perimeter wire: wrong length",
)
def testLengthNthSelector_UnsupportedShapes(self):
"""
No length defined for a face, shell, solid or compound
"""
w0 = Workplane().rarray(2, 2, 2, 1).box(1, 1, 1)
for val in [w0.faces().val(), w0.shells().val(), w0.compounds().val()]:
with self.assertRaises(ValueError):
selectors.LengthNthSelector(0).key(val)
def testLengthNthSelector_UnitEdgeAndWire(self):
"""
Checks that key() method of LengthNthSelector
calculates lengths of unit edge correctly
"""
unit_edge = Edge.makeLine(Vector(0, 0, 0), Vector(0, 0, 1))
self.assertAlmostEqual(1, selectors.LengthNthSelector(0).key(unit_edge), 5)
unit_edge = Wire.assembleEdges([unit_edge])
self.assertAlmostEqual(1, selectors.LengthNthSelector(0).key(unit_edge), 5)
def testAreaNthSelector_Vertices(self):
"""
Using AreaNthSelector on unsupported Shapes (Vertices)
should produce empty list
"""
with self.assertRaises(IndexError):
Workplane("XY").box(10, 10, 10).vertices(selectors.AreaNthSelector(0))
def testAreaNthSelector_Edges(self):
"""
Using AreaNthSelector on unsupported Shapes (Edges)
should produce empty list
"""
with self.assertRaises(IndexError):
Workplane("XY").box(10, 10, 10).edges(selectors.AreaNthSelector(0))
def testAreaNthSelector_NestedWires(self):
"""
Tests key parts of case seam leap creation algorithm
(see example 26)
- Selecting top outer wire
- Applying Offset2D and extruding a "lid"
- Selecting the innermost of three wires in preparation to
cut through the lid and leave a lip on the case seam
"""
# selecting top outermost wire of square box
wp = (
Workplane("XY")
.rect(50, 50)
.extrude(50)
.faces(">Z")
.shell(-5, "intersection")
.faces(">Z")
.wires(selectors.AreaNthSelector(-1))
)
self.assertEqual(
len(wp.vals()),
1,
msg="Failed to select top outermost wire of the box: wrong N wires",
)
self.assertAlmostEqual(
Face.makeFromWires(wp.val()).Area(),
50 * 50,
msg="Failed to select top outermost wire of the box: wrong wire area",
)
# preparing to add an inside lip to the box
wp = wp.toPending().workplane().offset2D(-2).extrude(1).faces(">Z[-2]")
# workplane now has 2 faces selected:
# a square and a thin rectangular frame
wp_outer_wire = wp.wires(selectors.AreaNthSelector(-1))
self.assertEqual(
len(wp_outer_wire.vals()),
1,
msg="Failed to select outermost wire of 2 faces: wrong N wires",
)
self.assertAlmostEqual(
Face.makeFromWires(wp_outer_wire.val()).Area(),
50 * 50,
msg="Failed to select outermost wire of 2 faces: wrong area",
)
wp_mid_wire = wp.wires(selectors.AreaNthSelector(1))
self.assertEqual(
len(wp_mid_wire.vals()),
1,
msg="Failed to select middle wire of 2 faces: wrong N wires",
)
self.assertAlmostEqual(
Face.makeFromWires(wp_mid_wire.val()).Area(),
(50 - 2 * 2) * (50 - 2 * 2),
msg="Failed to select middle wire of 2 faces: wrong area",
)
wp_inner_wire = wp.wires(selectors.AreaNthSelector(0))
self.assertEqual(
len(wp_inner_wire.vals()),
1,
msg="Failed to select inner wire of 2 faces: wrong N wires",
)
self.assertAlmostEqual(
Face.makeFromWires(wp_inner_wire.val()).Area(),
(50 - 5 * 2) * (50 - 5 * 2),
msg="Failed to select inner wire of 2 faces: wrong area",
)
def testAreaNthSelector_NonplanarWire(self):
"""
AreaNthSelector should raise ValueError when
used on non-planar wires so that they are ignored by
_NthSelector.
Non-planar wires in stack should not prevent selection of
planar wires.
"""
wp = Workplane("XY").circle(10).extrude(50)
with self.assertRaises(IndexError):
wp.wires(selectors.AreaNthSelector(1))
cylinder_flat_ends = wp.wires(selectors.AreaNthSelector(0))
self.assertEqual(
len(cylinder_flat_ends.vals()),
2,
msg="Failed to select cylinder flat end wires: wrong N wires",
)
self.assertTupleAlmostEquals(
[math.pi * 10 ** 2] * 2,
[Face.makeFromWires(wire).Area() for wire in cylinder_flat_ends.vals()],
5,
msg="Failed to select cylinder flat end wires: wrong area",
)
def testAreaNthSelector_Faces(self):
"""
Selecting two faces of 10x20x30 box with intermediate area.
"""
wp = Workplane("XY").box(10, 20, 30).faces(selectors.AreaNthSelector(1))
self.assertEqual(
len(wp.vals()),
2,
msg="Failed to select two faces of 10-20-30 box "
"with intermediate area: wrong N faces",
)
self.assertTupleAlmostEquals(
(wp.vals()[0].Area(), wp.vals()[1].Area()),
(10 * 30, 10 * 30),
7,
msg="Failed to select two faces of 10-20-30 box "
"with intermediate area: wrong area",
)
def testAreaNthSelector_Shells(self):
"""
Selecting one of three shells with the smallest surface area
"""
sizes_iter = iter([10.0, 20.0, 30.0])
def next_box_shell(loc):
size = next(sizes_iter)
return Workplane().box(size, size, size).val().located(loc)
workplane_shells = Workplane().rarray(10, 1, 3, 1).eachpoint(next_box_shell)
selected_shells = workplane_shells.shells(selectors.AreaNthSelector(0))
self.assertEqual(
len(selected_shells.vals()),
1,
msg="Failed to select the smallest shell: wrong N shells",
)
self.assertAlmostEqual(
selected_shells.val().Area(),
10 * 10 * 6,
msg="Failed to select the smallest shell: wrong area",
)
def testAreaNthSelector_Solids(self):
"""
Selecting 2 of 3 solids by surface area
"""
sizes_iter = iter([10.0, 20.0, 20.0])
def next_box(loc):
size = next(sizes_iter)
return Workplane().box(size, size, size).val().located(loc)
workplane_solids = Workplane().rarray(30, 1, 3, 1).eachpoint(next_box)
selected_solids = workplane_solids.solids(selectors.AreaNthSelector(1))
self.assertEqual(
len(selected_solids.vals()),
2,
msg="Failed to select two larger solids: wrong N shells",
)
self.assertTupleAlmostEquals(
[20 * 20 * 6] * 2,
[solid.Area() for solid in selected_solids.vals()],
5,
msg="Failed to select two larger solids: wrong area",
)
def testAndSelector(self):
c = CQ(makeUnitCube())
S = selectors.StringSyntaxSelector
BS = selectors.BoxSelector
el = c.edges(
selectors.AndSelector(S("|X"), BS((-2, -2, 0.1), (2, 2, 2)))
).vals()
self.assertEqual(2, len(el))
# test 'and' (intersection) operator
el = c.edges(S("|X") & BS((-2, -2, 0.1), (2, 2, 2))).vals()
self.assertEqual(2, len(el))
# test using extended string syntax
v = c.vertices(">X and >Y").vals()
self.assertEqual(2, len(v))
def testSumSelector(self):
c = CQ(makeUnitCube())
S = selectors.StringSyntaxSelector
fl = c.faces(selectors.SumSelector(S(">Z"), S("<Z"))).vals()
self.assertEqual(2, len(fl))
el = c.edges(selectors.SumSelector(S("|X"), S("|Y"))).vals()
self.assertEqual(8, len(el))
# test the sum operator
fl = c.faces(S(">Z") + S("<Z")).vals()
self.assertEqual(2, len(fl))
el = c.edges(S("|X") + S("|Y")).vals()
self.assertEqual(8, len(el))
# test using extended string syntax
fl = c.faces(">Z or <Z").vals()
self.assertEqual(2, len(fl))
el = c.edges("|X or |Y").vals()
self.assertEqual(8, len(el))
def testSubtractSelector(self):
c = CQ(makeUnitCube())
S = selectors.StringSyntaxSelector
fl = c.faces(selectors.SubtractSelector(S("#Z"), S(">X"))).vals()
self.assertEqual(3, len(fl))
# test the subtract operator
fl = c.faces(S("#Z") - S(">X")).vals()
self.assertEqual(3, len(fl))
# test using extended string syntax
fl = c.faces("#Z exc >X").vals()
self.assertEqual(3, len(fl))
def testInverseSelector(self):
c = CQ(makeUnitCube())
S = selectors.StringSyntaxSelector
fl = c.faces(selectors.InverseSelector(S(">Z"))).vals()
self.assertEqual(5, len(fl))
el = c.faces(">Z").edges(selectors.InverseSelector(S(">X"))).vals()
self.assertEqual(3, len(el))
# test invert operator
fl = c.faces(-S(">Z")).vals()
self.assertEqual(5, len(fl))
el = c.faces(">Z").edges(-S(">X")).vals()
self.assertEqual(3, len(el))
# test using extended string syntax
fl = c.faces("not >Z").vals()
self.assertEqual(5, len(fl))
el = c.faces(">Z").edges("not >X").vals()
self.assertEqual(3, len(el))
def testComplexStringSelector(self):
c = CQ(makeUnitCube())
v = c.vertices("(>X and >Y) or (<X and <Y)").vals()
self.assertEqual(4, len(v))
def testFaceCount(self):
c = CQ(makeUnitCube())
self.assertEqual(6, c.faces().size())
self.assertEqual(2, c.faces("|Z").size())
def testVertexFilter(self):
"test selecting vertices on a face"
c = CQ(makeUnitCube(centered=False))
# TODO: filters work ok, but they are in global coordinates which sux. it would be nice
# if they were available in coordinates local to the selected face
v2 = c.faces("+Z").vertices("<XY")
self.assertEqual(1, v2.size()) # another way
# make sure the vertex is the right one
self.assertTupleAlmostEquals((0.0, 0.0, 1.0), v2.val().toTuple(), 3)
def testGrammar(self):
"""
Test if reasonable string selector expressions parse without an error
"""
gram = selectors._expression_grammar
expressions = [
"+X ",
"-Y",
"|(1,0,0)",
"|(-1, -0.1 , 2. )",
"#(1.,1.4114,-0.532)",
"%Plane",
">XZ",
"<Z[-2]",
"<<Z[2]",
">>(1,1,0)",
">(1,4,55.)[20]",
"|XY",
"<YZ[0]",
"front",
"back",
"left",
"right",
"top",
"bottom",
"not |(1,1,0) and >(0,0,1) or XY except >(1,1,1)[-1]",
"(not |(1,1,0) and >(0,0,1)) exc XY and (Z or X)",
"not ( <X or >X or <Y or >Y )",
]
for e in expressions:
gram.parseString(e, parseAll=True)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,526 | CadQuery/cadquery | refs/heads/master | /examples/Ex022_Revolution.py | import cadquery as cq
# The dimensions of the model. These can be modified rather than changing the
# shape's code directly.
rectangle_width = 10.0
rectangle_length = 10.0
angle_degrees = 360.0
# Revolve a cylinder from a rectangle
# Switch comments around in this section to try the revolve operation with different parameters
result = cq.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve()
# result = cq.Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve(angle_degrees)
# result = cq.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5))
# result = cq.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5, -5),(-5, 5))
# result = cq.Workplane("XY").rect(rectangle_width, rectangle_length).revolve(angle_degrees,(-5,-5),(-5,5), False)
# Revolve a donut with square walls
# result = cq.Workplane("XY").rect(rectangle_width, rectangle_length, True).revolve(angle_degrees, (20, 0), (20, 10))
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,527 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/importers/__init__.py | from math import pi
from typing import List, Literal
import OCP.IFSelect
from OCP.STEPControl import STEPControl_Reader
from ... import cq
from ..shapes import Shape
from .dxf import _importDXF
RAD2DEG = 360.0 / (2 * pi)
class ImportTypes:
STEP = "STEP"
DXF = "DXF"
class UNITS:
MM = "mm"
IN = "in"
def importShape(
importType: Literal["STEP", "DXF"], fileName: str, *args, **kwargs
) -> "cq.Workplane":
"""
Imports a file based on the type (STEP, STL, etc)
:param importType: The type of file that we're importing
:param fileName: The name of the file that we're importing
"""
# Check to see what type of file we're working with
if importType == ImportTypes.STEP:
return importStep(fileName)
elif importType == ImportTypes.DXF:
return importDXF(fileName, *args, **kwargs)
else:
raise RuntimeError("Unsupported import type: {!r}".format(importType))
# Loads a STEP file into a CQ.Workplane object
def importStep(fileName: str) -> "cq.Workplane":
"""
Accepts a file name and loads the STEP file into a cadquery Workplane
:param fileName: The path and name of the STEP file to be imported
"""
# Now read and return the shape
reader = STEPControl_Reader()
readStatus = reader.ReadFile(fileName)
if readStatus != OCP.IFSelect.IFSelect_RetDone:
raise ValueError("STEP File could not be loaded")
for i in range(reader.NbRootsForTransfer()):
reader.TransferRoot(i + 1)
occ_shapes = []
for i in range(reader.NbShapes()):
occ_shapes.append(reader.Shape(i + 1))
# Make sure that we extract all the solids
solids = []
for shape in occ_shapes:
solids.append(Shape.cast(shape))
return cq.Workplane("XY").newObject(solids)
def importDXF(
filename: str, tol: float = 1e-6, exclude: List[str] = [], include: List[str] = []
) -> "cq.Workplane":
"""
Loads a DXF file into a Workplane.
All layers are imported by default. Provide a layer include or exclude list
to select layers. Layer names are handled as case-insensitive.
:param filename: The path and name of the DXF file to be imported
:param tol: The tolerance used for merging edges into wires
:param exclude: a list of layer names not to import
:param include: a list of layer names to import
"""
faces = _importDXF(filename, tol, exclude, include)
return cq.Workplane("XY").newObject(faces)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,528 | CadQuery/cadquery | refs/heads/master | /examples/Ex024_Sweep_With_Multiple_Sections.py | import cadquery as cq
# X axis line length 20.0
path = cq.Workplane("XZ").moveTo(-10, 0).lineTo(10, 0)
# Sweep a circle from diameter 2.0 to diameter 1.0 to diameter 2.0 along X axis length 10.0 + 10.0
defaultSweep = (
cq.Workplane("YZ")
.workplane(offset=-10.0)
.circle(2.0)
.workplane(offset=10.0)
.circle(1.0)
.workplane(offset=10.0)
.circle(2.0)
.sweep(path, multisection=True)
)
# We can sweep through different shapes
recttocircleSweep = (
cq.Workplane("YZ")
.workplane(offset=-10.0)
.rect(2.0, 2.0)
.workplane(offset=8.0)
.circle(1.0)
.workplane(offset=4.0)
.circle(1.0)
.workplane(offset=8.0)
.rect(2.0, 2.0)
.sweep(path, multisection=True)
)
circletorectSweep = (
cq.Workplane("YZ")
.workplane(offset=-10.0)
.circle(1.0)
.workplane(offset=7.0)
.rect(2.0, 2.0)
.workplane(offset=6.0)
.rect(2.0, 2.0)
.workplane(offset=7.0)
.circle(1.0)
.sweep(path, multisection=True)
)
# Placement of the Shape is important otherwise could produce unexpected shape
specialSweep = (
cq.Workplane("YZ")
.circle(1.0)
.workplane(offset=10.0)
.rect(2.0, 2.0)
.sweep(path, multisection=True)
)
# Switch to an arc for the path : line l=5.0 then half circle r=4.0 then line l=5.0
path = (
cq.Workplane("XZ")
.moveTo(-5, 4)
.lineTo(0, 4)
.threePointArc((4, 0), (0, -4))
.lineTo(-5, -4)
)
# Placement of different shapes should follow the path
# cylinder r=1.5 along first line
# then sweep along arc from r=1.5 to r=1.0
# then cylinder r=1.0 along last line
arcSweep = (
cq.Workplane("YZ")
.workplane(offset=-5)
.moveTo(0, 4)
.circle(1.5)
.workplane(offset=5, centerOption="CenterOfMass")
.circle(1.5)
.moveTo(0, -8)
.circle(1.0)
.workplane(offset=-5, centerOption="CenterOfMass")
.circle(1.0)
.sweep(path, multisection=True)
)
# Translate the resulting solids so that they do not overlap and display them left to right
show_object(defaultSweep)
show_object(circletorectSweep.translate((0, 5, 0)))
show_object(recttocircleSweep.translate((0, 10, 0)))
show_object(specialSweep.translate((0, 15, 0)))
show_object(arcSweep.translate((0, -5, 0)))
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,529 | CadQuery/cadquery | refs/heads/master | /examples/Ex006_Moving_the_Current_Working_Point.py | import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
circle_radius = 3.0 # The outside radius of the plate
thickness = 0.25 # The thickness of the plate
# Make a plate with two cutouts in it by moving the workplane center point
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 1b. The initial workplane center point is the center of the circle, at (0,0).
# 2. A circle is created at the center of the workplane
# 2a. Notice that circle() takes a radius and not a diameter
result = cq.Workplane("front").circle(circle_radius)
# 3. The work center is movide to (1.5, 0.0) by calling center().
# 3a. The new center is specified relative to the previous center,not
# relative to global coordinates.
# 4. A 0.5mm x 0.5mm 2D square is drawn inside the circle.
# 4a. The plate has not been extruded yet, only 2D geometry is being created.
result = result.center(1.5, 0.0).rect(0.5, 0.5)
# 5. The work center is moved again, this time to (-1.5, 1.5).
# 6. A 2D circle is created at that new center with a radius of 0.25mm.
result = result.center(-1.5, 1.5).circle(0.25)
# 7. All 2D geometry is extruded to the specified thickness of the plate.
# 7a. The small circle and the square are enclosed in the outer circle of the
# plate and so it is assumed that we want them to be cut out of the plate.
# A separate cut operation is not needed.
result = result.extrude(thickness)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,530 | CadQuery/cadquery | refs/heads/master | /cadquery/cqgi.py | """
The CadQuery Gateway Interface.
Provides classes and tools for executing CadQuery scripts
"""
import ast
import traceback
import time
import cadquery
CQSCRIPT = "<cqscript>"
def parse(script_source):
"""
Parses the script as a model, and returns a model.
If you would prefer to access the underlying model without building it,
for example, to inspect its available parameters, construct a CQModel object.
:param script_source: the script to run. Must be a valid cadquery script
:return: a CQModel object that defines the script and allows execution
"""
model = CQModel(script_source)
return model
class CQModel(object):
"""
Represents a Cadquery Script.
After construction, the metadata property contains
a ScriptMetaData object, which describes the model in more detail,
and can be used to retrieve the parameters defined by the model.
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.
:param script_source: a python script to parse
"""
self.metadata = ScriptMetadata()
self.ast_tree = ast.parse(script_source, CQSCRIPT)
self.script_source = script_source
self._find_vars()
# TODO: pick up other script metadata:
# describe
# pick up validation methods
self._find_descriptions()
def _find_vars(self):
"""
Parse the script, and populate variables that appear to be
overridable.
"""
# assumption here: we assume that variable declarations
# are only at the top level of the script. IE, we'll ignore any
# variable definitions at lower levels of the script
# we don't want to use the visit interface because here we explicitly
# want to walk only the top level of the tree.
assignment_finder = ConstantAssignmentFinder(self.metadata)
for node in self.ast_tree.body:
if isinstance(node, ast.Assign):
assignment_finder.visit_Assign(node)
def _find_descriptions(self):
description_finder = ParameterDescriptionFinder(self.metadata)
description_finder.visit(self.ast_tree)
def validate(self, params):
"""
Determine if the supplied parameters are valid.
NOT IMPLEMENTED YET-- raises NotImplementedError
:param params: a dictionary of parameters
"""
raise NotImplementedError("not yet implemented")
def build(self, build_parameters=None, build_options=None):
"""
Executes the script, using the optional parameters to override those in the model
:param build_parameters: a dictionary of variables. The variables must be
assignable to the underlying variable type. These variables override default values in the script
:param build_options: build options for how to build the model. Build options include things like
timeouts, tessellation tolerances, etc
:raises: Nothing. If there is an exception, it will be on the exception property of the result.
This is the interface so that we can return other information on the result, such as the build time
:return: a BuildResult object, which includes the status of the result, and either
a resulting shape or an exception
"""
if not build_parameters:
build_parameters = {}
start = time.perf_counter()
result = BuildResult()
try:
self.set_param_values(build_parameters)
collector = ScriptCallback()
env = (
EnvironmentBuilder()
.with_real_builtins()
.with_cadquery_objects()
.add_entry("__name__", "__cqgi__")
.add_entry("show_object", collector.show_object)
.add_entry("debug", collector.debug)
.add_entry("describe_parameter", collector.describe_parameter)
.build()
)
c = compile(self.ast_tree, CQSCRIPT, "exec")
exec(c, env)
result.set_debug(collector.debugObjects)
result.set_success_result(collector.outputObjects)
result.env = env
except Exception as ex:
result.set_failure_result(ex)
end = time.perf_counter()
result.buildTime = end - start
return result
def set_param_values(self, params):
model_parameters = self.metadata.parameters
for k, v in params.items():
if k not in model_parameters:
raise InvalidParameterError(
"Cannot set value '%s': not a parameter of the model." % k
)
p = model_parameters[k]
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.
The success property contains whether the execution was successful.
If successful, the results property contains a list of all results,
and the first_result property contains the first result.
If unsuccessful, the exception property contains a reference to
the stack trace that occurred.
"""
def __init__(self):
self.buildTime = None
self.results = [] # list of ShapeResult
self.debugObjects = [] # list of ShapeResult
self.first_result = None
self.success = False
self.exception = None
def set_failure_result(self, ex):
self.exception = ex
self.success = False
def set_debug(self, debugObjects):
self.debugObjects = debugObjects
def set_success_result(self, results):
self.results = results
if len(self.results) > 0:
self.first_result = self.results[0]
self.success = True
class ScriptMetadata(object):
"""
Defines the metadata for a parsed CQ Script.
the parameters property is a dict of InputParameter objects.
"""
def __init__(self):
self.parameters = {}
def add_script_parameter(self, p):
self.parameters[p.name] = p
def add_parameter_description(self, name, description):
p = self.parameters[name]
p.desc = description
class ParameterType(object):
pass
class NumberParameterType(ParameterType):
pass
class StringParameterType(ParameterType):
pass
class BooleanParameterType(ParameterType):
pass
class InputParameter:
"""
Defines a parameter that can be supplied when the model is executed.
Name, varType, and default_value are always available, because they are computed
from a variable assignment line of code:
The others are only available if the script has used define_parameter() to
provide additional metadata
"""
def __init__(self):
#: the default value for the variable.
self.default_value = None
#: the name of the parameter.
self.name = None
#: type of the variable: BooleanParameter, StringParameter, NumericParameter
self.varType = None
#: help text describing the variable. Only available if the script used describe_parameter()
self.desc = None
#: valid values for the variable. Only available if the script used describe_parameter()
self.valid_values = []
self.ast_node = None
@staticmethod
def create(
ast_node, var_name, var_type, default_value, valid_values=None, desc=None
):
if valid_values is None:
valid_values = []
p = InputParameter()
p.ast_node = ast_node
p.default_value = default_value
p.name = var_name
p.desc = desc
p.varType = var_type
p.valid_values = valid_values
return p
def set_value(self, new_value):
if len(self.valid_values) > 0 and new_value not in self.valid_values:
raise InvalidParameterError(
"Cannot set value '{0:s}' for parameter '{1:s}': not a valid value. Valid values are {2:s} ".format(
str(new_value), self.name, str(self.valid_values)
)
)
if self.varType == NumberParameterType:
try:
# Sometimes a value must stay as an int for the script to work properly
if isinstance(new_value, int):
f = int(new_value)
else:
f = float(new_value)
self.ast_node.n = f
except ValueError:
raise InvalidParameterError(
"Cannot set value '{0:s}' for parameter '{1:s}': parameter must be numeric.".format(
str(new_value), self.name
)
)
elif self.varType == StringParameterType:
self.ast_node.s = str(new_value)
elif self.varType == BooleanParameterType:
if new_value:
if hasattr(ast, "NameConstant"):
self.ast_node.value = True
else:
self.ast_node.id = "True"
else:
if hasattr(ast, "NameConstant"):
self.ast_node.value = False
else:
self.ast_node.id = "False"
else:
raise ValueError("Unknown Type of var: ", str(self.varType))
def __str__(self):
return "InputParameter: {name=%s, type=%s, defaultValue=%s" % (
self.name,
str(self.varType),
str(self.default_value),
)
class ScriptCallback(object):
"""
Allows a script to communicate with the container
the show_object() method is exposed to CQ scripts, to allow them
to return objects to the execution environment
"""
def __init__(self):
self.outputObjects = []
self.debugObjects = []
def show_object(self, shape, options={}, **kwargs):
"""
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 environment
"""
options.update(kwargs)
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.
"""
s = ShapeResult()
s.shape = obj
s.options = args
self.debugObjects.append(s)
def describe_parameter(self, var_data):
"""
Do Nothing-- we parsed the ast ahead of execution to get what we need.
"""
pass
def add_error(self, param, field_list):
"""
Not implemented yet: allows scripts to indicate that there are problems with inputs
"""
pass
def has_results(self):
return len(self.outputObjects) > 0
class InvalidParameterError(Exception):
"""
Raised when an attempt is made to provide a new parameter value
that cannot be assigned to the model
"""
pass
class NoOutputError(Exception):
"""
Raised when the script does not execute the show_object() method to
return a solid
"""
pass
class ScriptExecutionError(Exception):
"""
Represents a script syntax error.
Useful for helping clients pinpoint issues with the script
interactively
"""
def __init__(self, line=None, message=None):
if line is None:
self.line = 0
else:
self.line = line
if message is None:
self.message = "Unknown Script Error"
else:
self.message = message
def full_message(self):
return self.__repr__()
def __str__(self):
return self.__repr__()
def __repr__(self):
return "ScriptError [Line %s]: %s" % (self.line, self.message)
class EnvironmentBuilder(object):
"""
Builds an execution environment for a cadquery script.
The environment includes the builtins, as well as
the other methods the script will need.
"""
def __init__(self):
self.env = {}
def with_real_builtins(self):
return self.with_builtins(__builtins__)
def with_builtins(self, env_dict):
self.env["__builtins__"] = env_dict
return self
def with_cadquery_objects(self):
self.env["cadquery"] = cadquery
self.env["cq"] = cadquery
return self
def add_entry(self, name, value):
self.env[name] = value
return self
def build(self):
return self.env
class ParameterDescriptionFinder(ast.NodeTransformer):
"""
Visits a parse tree, looking for function calls to describe_parameter(var, description )
"""
def __init__(self, cq_model):
self.cqModel = cq_model
def visit_Call(self, node):
"""
Called when we see a function call. Is it describe_parameter?
"""
try:
if node.func.id == "describe_parameter":
# looks like we have a call to our function.
# first parameter is the variable,
# second is the description
varname = node.args[0].id
desc = node.args[1].s
self.cqModel.add_parameter_description(varname, desc)
except:
# print "Unable to handle function call"
pass
return node
class ConstantAssignmentFinder(ast.NodeTransformer):
"""
Visits a parse tree, and adds script parameters to the cqModel
"""
def __init__(self, cq_model):
self.cqModel = cq_model
def handle_assignment(self, var_name, value_node):
try:
if type(value_node) == ast.Num:
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, NumberParameterType, value_node.n
)
)
elif type(value_node) == ast.Str:
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, StringParameterType, value_node.s
)
)
elif type(value_node) == ast.Name:
if value_node.id == "True":
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, BooleanParameterType, True
)
)
elif value_node.id == "False":
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, BooleanParameterType, False
)
)
elif hasattr(ast, "NameConstant") and type(value_node) == ast.NameConstant:
if value_node.value == True:
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, BooleanParameterType, True
)
)
else:
self.cqModel.add_script_parameter(
InputParameter.create(
value_node, var_name, BooleanParameterType, False
)
)
elif hasattr(ast, "Constant") and type(value_node) == ast.Constant:
type_dict = {
bool: BooleanParameterType,
str: StringParameterType,
float: NumberParameterType,
int: NumberParameterType,
}
self.cqModel.add_script_parameter(
InputParameter.create(
value_node,
var_name,
type_dict[type(value_node.value)],
value_node.value,
)
)
except:
print("Unable to handle assignment for variable '%s'" % var_name)
pass
def visit_Assign(self, node):
try:
left_side = node.targets[0]
# do not handle attribute assignments
if isinstance(left_side, ast.Attribute):
return
# Handle the NamedConstant type that is only present in Python 3
astTypes = [ast.Num, ast.Str, ast.Name]
if hasattr(ast, "NameConstant"):
astTypes.append(ast.NameConstant)
if hasattr(ast, "Constant"):
astTypes.append(ast.Constant)
if type(node.value) in astTypes:
self.handle_assignment(left_side.id, node.value)
elif type(node.value) == ast.Tuple:
if isinstance(left_side, ast.Name):
# skip unsupported parameter type
pass
else:
# we have a multi-value assignment
for n, v in zip(left_side.elts, node.value.elts):
self.handle_assignment(n.id, v)
except:
traceback.print_exc()
print("Unable to handle assignment for node '%s'" % ast.dump(left_side))
return node
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,531 | CadQuery/cadquery | refs/heads/master | /cadquery/occ_impl/assembly.py | from typing import (
Union,
Iterable,
Iterator,
Tuple,
Dict,
overload,
Optional,
Any,
List,
cast,
)
from typing_extensions import Protocol
from math import degrees
from OCP.TDocStd import TDocStd_Document
from OCP.TCollection import TCollection_ExtendedString
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType, XCAFDoc_ColorGen
from OCP.XCAFApp import XCAFApp_Application
from OCP.TDataStd import TDataStd_Name
from OCP.TDF import TDF_Label
from OCP.TopLoc import TopLoc_Location
from OCP.Quantity import Quantity_ColorRGBA
from OCP.BRepAlgoAPI import BRepAlgoAPI_Fuse
from OCP.TopTools import TopTools_ListOfShape
from OCP.BOPAlgo import BOPAlgo_GlueEnum, BOPAlgo_MakeConnected
from OCP.TopoDS import TopoDS_Shape
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper as vtkMapper,
vtkRenderer,
)
from vtkmodules.vtkFiltersExtraction import vtkExtractCellsByType
from vtkmodules.vtkCommonDataModel import VTK_TRIANGLE, VTK_LINE, VTK_VERTEX
from .geom import Location
from .shapes import Shape, Solid, Compound
from .exporters.vtk import toString
from ..cq import Workplane
# type definitions
AssemblyObjects = Union[Shape, Workplane, None]
class Color(object):
"""
Wrapper for the OCCT color object Quantity_ColorRGBA.
"""
wrapped: Quantity_ColorRGBA
@overload
def __init__(self, name: str):
"""
Construct a Color from a name.
:param name: name of the color, e.g. green
"""
...
@overload
def __init__(self, r: float, g: float, b: float, a: float = 0):
"""
Construct a Color from RGB(A) values.
:param r: red value, 0-1
:param g: green value, 0-1
:param b: blue value, 0-1
:param a: alpha value, 0-1 (default: 0)
"""
...
@overload
def __init__(self):
"""
Construct a Color with default value.
"""
...
def __init__(self, *args, **kwargs):
if len(args) == 0:
self.wrapped = Quantity_ColorRGBA()
elif len(args) == 1:
self.wrapped = Quantity_ColorRGBA()
exists = Quantity_ColorRGBA.ColorFromName_s(args[0], self.wrapped)
if not exists:
raise ValueError(f"Unknown color name: {args[0]}")
elif len(args) == 3:
r, g, b = args
self.wrapped = Quantity_ColorRGBA(r, g, b, 1)
if kwargs.get("a"):
self.wrapped.SetAlpha(kwargs.get("a"))
elif len(args) == 4:
r, g, b, a = args
self.wrapped = Quantity_ColorRGBA(r, g, b, a)
else:
raise ValueError(f"Unsupported arguments: {args}, {kwargs}")
def toTuple(self) -> Tuple[float, float, float, float]:
"""
Convert Color to RGB tuple.
"""
a = self.wrapped.Alpha()
rgb = self.wrapped.GetRGB()
return (rgb.Red(), rgb.Green(), rgb.Blue(), a)
class AssemblyProtocol(Protocol):
@property
def loc(self) -> Location:
...
@loc.setter
def loc(self, value: Location) -> None:
...
@property
def name(self) -> str:
...
@property
def parent(self) -> Optional["AssemblyProtocol"]:
...
@property
def color(self) -> Optional[Color]:
...
@property
def obj(self) -> AssemblyObjects:
...
@property
def shapes(self) -> Iterable[Shape]:
...
@property
def children(self) -> Iterable["AssemblyProtocol"]:
...
def traverse(self) -> Iterable[Tuple[str, "AssemblyProtocol"]]:
...
def __iter__(
self,
loc: Optional[Location] = None,
name: Optional[str] = None,
color: Optional[Color] = None,
) -> Iterator[Tuple[Shape, str, Location, Optional[Color]]]:
...
def setName(l: TDF_Label, name: str, tool):
TDataStd_Name.Set_s(l, TCollection_ExtendedString(name))
def setColor(l: TDF_Label, color: Color, tool):
tool.SetColor(l, color.wrapped, XCAFDoc_ColorType.XCAFDoc_ColorSurf)
def toCAF(
assy: AssemblyProtocol,
coloredSTEP: bool = False,
mesh: bool = False,
tolerance: float = 1e-3,
angularTolerance: float = 0.1,
) -> Tuple[TDF_Label, TDocStd_Document]:
# prepare a doc
app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("XmlOcaf"))
app.InitDocument(doc)
tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
tool.SetAutoNaming_s(False)
ctool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
# used to store labels with unique part-color combinations
unique_objs: Dict[Tuple[Color, AssemblyObjects], TDF_Label] = {}
# used to cache unique, possibly meshed, compounds; allows to avoid redundant meshing operations if same object is referenced multiple times in an assy
compounds: Dict[AssemblyObjects, Compound] = {}
def _toCAF(el, ancestor, color) -> TDF_Label:
# create a subassy
subassy = tool.NewShape()
setName(subassy, el.name, tool)
# define the current color
current_color = el.color if el.color else color
# add a leaf with the actual part if needed
if el.obj:
# get/register unique parts referenced in the assy
key0 = (current_color, el.obj) # (color, shape)
key1 = el.obj # shape
if key0 in unique_objs:
lab = unique_objs[key0]
else:
lab = tool.NewShape()
if key1 in compounds:
compound = compounds[key1].copy(mesh)
else:
compound = Compound.makeCompound(el.shapes)
if mesh:
compound.mesh(tolerance, angularTolerance)
compounds[key1] = compound
tool.SetShape(lab, compound.wrapped)
setName(lab, f"{el.name}_part", tool)
unique_objs[key0] = lab
# handle colors when exporting to STEP
if coloredSTEP and current_color:
setColor(lab, current_color, ctool)
tool.AddComponent(subassy, lab, TopLoc_Location())
# handle colors when *not* exporting to STEP
if not coloredSTEP and current_color:
setColor(subassy, current_color, ctool)
# add children recursively
for child in el.children:
_toCAF(child, subassy, current_color)
if ancestor:
# add the current subassy to the higher level assy
tool.AddComponent(ancestor, subassy, el.loc.wrapped)
return subassy
# process the whole assy recursively
top = _toCAF(assy, None, None)
tool.UpdateAssemblies()
return top, doc
def toVTK(
assy: AssemblyProtocol,
color: Tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0),
tolerance: float = 1e-3,
angularTolerance: float = 0.1,
) -> vtkRenderer:
renderer = vtkRenderer()
for shape, _, loc, col_ in assy:
col = col_.toTuple() if col_ else color
trans, rot = loc.toTuple()
data = shape.toVtkPolyData(tolerance, angularTolerance)
# extract faces
extr = vtkExtractCellsByType()
extr.SetInputDataObject(data)
extr.AddCellType(VTK_LINE)
extr.AddCellType(VTK_VERTEX)
extr.Update()
data_edges = extr.GetOutput()
# extract edges
extr = vtkExtractCellsByType()
extr.SetInputDataObject(data)
extr.AddCellType(VTK_TRIANGLE)
extr.Update()
data_faces = extr.GetOutput()
# remove normals from edges
data_edges.GetPointData().RemoveArray("Normals")
# add both to the renderer
mapper = vtkMapper()
mapper.AddInputDataObject(data_faces)
actor = vtkActor()
actor.SetMapper(mapper)
actor.SetPosition(*trans)
actor.SetOrientation(*map(degrees, rot))
actor.GetProperty().SetColor(*col[:3])
actor.GetProperty().SetOpacity(col[3])
renderer.AddActor(actor)
mapper = vtkMapper()
mapper.AddInputDataObject(data_edges)
actor = vtkActor()
actor.SetMapper(mapper)
actor.SetPosition(*trans)
actor.SetOrientation(*map(degrees, rot))
actor.GetProperty().SetColor(0, 0, 0)
actor.GetProperty().SetLineWidth(2)
renderer.AddActor(actor)
return renderer
def toJSON(
assy: AssemblyProtocol,
color: Tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0),
tolerance: float = 1e-3,
) -> List[Dict[str, Any]]:
"""
Export an object to a structure suitable for converting to VTK.js JSON.
"""
rv = []
for shape, _, loc, col_ in assy:
val: Any = {}
data = toString(shape, tolerance)
trans, rot = loc.toTuple()
val["shape"] = data
val["color"] = col_.toTuple() if col_ else color
val["position"] = trans
val["orientation"] = rot
rv.append(val)
return rv
def toFusedCAF(
assy: AssemblyProtocol, glue: bool = False, tol: Optional[float] = None,
) -> Tuple[TDF_Label, TDocStd_Document]:
"""
Converts the assembly to a fused compound and saves that within the document
to be exported in a way that preserves the face colors. Because of the use of
boolean operations in this method, performance may be slow in some cases.
:param assy: Assembly that is being converted to a fused compound for the document.
"""
# Prepare the document
app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("XmlOcaf"))
app.InitDocument(doc)
# Shape and color tools
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
color_tool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
# To fuse the parts of the assembly together
fuse_op = BRepAlgoAPI_Fuse()
args = TopTools_ListOfShape()
tools = TopTools_ListOfShape()
# If there is only one solid, there is no reason to fuse, and it will likely cause problems anyway
top_level_shape = None
# Walk the entire assembly, collecting the located shapes and colors
shapes: List[Shape] = []
colors = []
for shape, _, loc, color in assy:
shapes.append(shape.moved(loc).copy())
colors.append(color)
# Initialize with a dummy value for mypy
top_level_shape = cast(TopoDS_Shape, None)
# If the tools are empty, it means we only had a single shape and do not need to fuse
if not shapes:
raise Exception(f"Error: Assembly {assy.name} has no shapes.")
elif len(shapes) == 1:
# There is only one shape and we only need to make sure it is a Compound
# This seems to be needed to be able to add subshapes (i.e. faces) correctly
sh = shapes[0]
if sh.ShapeType() != "Compound":
top_level_shape = Compound.makeCompound((sh,)).wrapped
elif sh.ShapeType() == "Compound":
sh = sh.fuse(glue=glue, tol=tol)
top_level_shape = Compound.makeCompound((sh,)).wrapped
shapes = [sh]
else:
# Set the shape lists up so that the fuse operation can be performed
args.Append(shapes[0].wrapped)
for shape in shapes[1:]:
tools.Append(shape.wrapped)
# Allow the caller to configure the fuzzy and glue settings
if tol:
fuse_op.SetFuzzyValue(tol)
if glue:
fuse_op.SetGlue(BOPAlgo_GlueEnum.BOPAlgo_GlueShift)
fuse_op.SetArguments(args)
fuse_op.SetTools(tools)
fuse_op.Build()
top_level_shape = fuse_op.Shape()
# Add the fused shape as the top level object in the document
top_level_lbl = shape_tool.AddShape(top_level_shape, False)
TDataStd_Name.Set_s(top_level_lbl, TCollection_ExtendedString(assy.name))
# Walk the assembly->part->shape->face hierarchy and add subshapes for all the faces
for color, shape in zip(colors, shapes):
for face in shape.Faces():
# See if the face can be treated as-is
cur_lbl = shape_tool.AddSubShape(top_level_lbl, face.wrapped)
if color and not cur_lbl.IsNull() and not fuse_op.IsDeleted(face.wrapped):
color_tool.SetColor(cur_lbl, color.wrapped, XCAFDoc_ColorGen)
# Handle any modified faces
modded_list = fuse_op.Modified(face.wrapped)
for mod in modded_list:
# Add the face as a subshape and set its color to match the parent assembly component
cur_lbl = shape_tool.AddSubShape(top_level_lbl, mod)
if color and not cur_lbl.IsNull() and not fuse_op.IsDeleted(mod):
color_tool.SetColor(cur_lbl, color.wrapped, XCAFDoc_ColorGen)
# Handle any generated faces
gen_list = fuse_op.Generated(face.wrapped)
for gen in gen_list:
# Add the face as a subshape and set its color to match the parent assembly component
cur_lbl = shape_tool.AddSubShape(top_level_lbl, gen)
if color and not cur_lbl.IsNull():
color_tool.SetColor(cur_lbl, color.wrapped, XCAFDoc_ColorGen)
return top_level_lbl, doc
def imprint(assy: AssemblyProtocol) -> Tuple[Shape, Dict[Shape, Tuple[str, ...]]]:
"""
Imprint all the solids and construct a dictionary mapping imprinted solids to names from the input assy.
"""
# make the id map
id_map = {}
for obj, name, loc, _ in assy:
for s in obj.moved(loc).Solids():
id_map[s] = name
# connect topologically
bldr = BOPAlgo_MakeConnected()
bldr.SetRunParallel(True)
bldr.SetUseOBB(True)
for obj in id_map:
bldr.AddArgument(obj.wrapped)
bldr.Perform()
res = Shape(bldr.Shape())
# make the connected solid -> id map
origins: Dict[Shape, Tuple[str, ...]] = {}
for s in res.Solids():
ids = tuple(id_map[Solid(el)] for el in bldr.GetOrigins(s.wrapped))
# if GetOrigins yields nothing, solid was not modified
origins[s] = ids if ids else (id_map[s],)
return res, origins
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,532 | CadQuery/cadquery | refs/heads/master | /examples/Ex011_Mirroring_Symmetric_Geometry.py | import cadquery as cq
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. A horizontal line is drawn on the workplane with the hLine function.
# 2a. 1.0 is the distance, not coordinate. hLineTo allows using xCoordinate
# not distance.
r = cq.Workplane("front").hLine(1.0)
# 3. Draw a series of vertical and horizontal lines with the vLine and hLine
# functions.
r = r.vLine(0.5).hLine(-0.25).vLine(-0.25).hLineTo(0.0)
# 4. Mirror the geometry about the Y axis and extrude it into a 3D object.
result = r.mirrorY().extrude(0.25)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,533 | CadQuery/cadquery | refs/heads/master | /examples/Ex018_Making_Lofts.py | import cadquery as cq
# Create a lofted section between a rectangle and a circular section.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects the top-most Z face of the box.
# 4. Draws a 2D circle at the center of the the top-most face of the box.
# 5. Creates a workplane 3 mm above the face the circle was drawn on.
# 6. Draws a 2D circle on the new, offset workplane.
# 7. Creates a loft between the circle and the rectangle.
result = (
cq.Workplane("front")
.box(4.0, 4.0, 0.25)
.faces(">Z")
.circle(1.5)
.workplane(offset=3.0)
.rect(0.75, 0.5)
.loft(combine=True)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,534 | CadQuery/cadquery | refs/heads/master | /examples/Ex019_Counter_Sunk_Holes.py | import cadquery as cq
# Create a plate with 4 counter-sunk holes in it.
# 1. Establishes a workplane using an XY object instead of a named plane.
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects the top-most face of the box and established a workplane on that.
# 4. Draws a for-construction rectangle on the workplane which only exists for
# placing other geometry.
# 5. Selects the corner vertices of the rectangle and places a counter-sink
# hole, using each vertex as the center of a hole using the cskHole()
# function.
# 5a. When the depth of the counter-sink hole is set to None, the hole will be
# cut through.
result = (
cq.Workplane(cq.Plane.XY())
.box(4, 2, 0.5)
.faces(">Z")
.workplane()
.rect(3.5, 1.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82.0, depth=None)
)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,535 | CadQuery/cadquery | refs/heads/master | /cadquery/selectors.py | """
Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC
This file is part of CadQuery.
CadQuery is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
CadQuery 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 Lesser General Public
License along with this library; If not, see <http://www.gnu.org/licenses/>
"""
from abc import abstractmethod, ABC
import math
from .occ_impl.geom import Vector
from .occ_impl.shapes import (
Shape,
Edge,
Face,
Wire,
Shell,
Solid,
geom_LUT_EDGE,
geom_LUT_FACE,
)
from pyparsing import (
pyparsing_common,
Literal,
Word,
nums,
Optional,
Combine,
oneOf,
CaselessLiteral,
Group,
infixNotation,
opAssoc,
Forward,
ZeroOrMore,
Keyword,
)
from functools import reduce
from typing import List, Union, Sequence
class Selector(object):
"""
Filters a list of objects.
Filters must provide a single method that filters objects.
"""
def filter(self, objectList):
"""
Filter the provided list.
The default implementation returns the original list unfiltered.
:param objectList: list to filter
:type objectList: list of OCCT primitives
:return: filtered list
"""
return objectList
def __and__(self, other):
return AndSelector(self, other)
def __add__(self, other):
return SumSelector(self, other)
def __sub__(self, other):
return SubtractSelector(self, other)
def __neg__(self):
return InverseSelector(self)
class NearestToPointSelector(Selector):
"""
Selects object nearest the provided point.
If the object is a vertex or point, the distance
is used. For other kinds of shapes, the center of mass
is used to to compute which is closest.
Applicability: All Types of Shapes
Example::
CQ(aCube).vertices(NearestToPointSelector((0, 1, 0)))
returns the vertex of the unit cube closest to the point x=0,y=1,z=0
"""
def __init__(self, pnt):
self.pnt = pnt
def filter(self, objectList):
def dist(tShape):
return tShape.Center().sub(Vector(*self.pnt)).Length
# if tShape.ShapeType == 'Vertex':
# return tShape.Point.sub(toVector(self.pnt)).Length
# else:
# return tShape.CenterOfMass.sub(toVector(self.pnt)).Length
return [min(objectList, key=dist)]
class BoxSelector(Selector):
"""
Selects objects inside the 3D box defined by 2 points.
If `boundingbox` is True only the objects that have their bounding
box inside the given box is selected. Otherwise only center point
of the object is tested.
Applicability: all types of shapes
Example::
CQ(aCube).edges(BoxSelector((0, 1, 0), (1, 2, 1)))
"""
def __init__(self, point0, point1, boundingbox=False):
self.p0 = Vector(*point0)
self.p1 = Vector(*point1)
self.test_boundingbox = boundingbox
def filter(self, objectList):
result = []
x0, y0, z0 = self.p0.toTuple()
x1, y1, z1 = self.p1.toTuple()
def isInsideBox(p):
# using XOR for checking if x/y/z is in between regardless
# of order of x/y/z0 and x/y/z1
return (
((p.x < x0) ^ (p.x < x1))
and ((p.y < y0) ^ (p.y < y1))
and ((p.z < z0) ^ (p.z < z1))
)
for o in objectList:
if self.test_boundingbox:
bb = o.BoundingBox()
if isInsideBox(Vector(bb.xmin, bb.ymin, bb.zmin)) and isInsideBox(
Vector(bb.xmax, bb.ymax, bb.zmax)
):
result.append(o)
else:
if isInsideBox(o.Center()):
result.append(o)
return result
class BaseDirSelector(Selector):
"""
A selector that handles selection on the basis of a single direction vector.
"""
def __init__(self, vector: Vector, tolerance: float = 0.0001):
self.direction = vector
self.tolerance = tolerance
def test(self, vec: Vector) -> bool:
"Test a specified vector. Subclasses override to provide other implementations"
return True
def filter(self, objectList: Sequence[Shape]) -> List[Shape]:
"""
There are lots of kinds of filters, but for planes they are always
based on the normal of the plane, and for edges on the tangent vector
along the edge
"""
r = []
for o in objectList:
# no really good way to avoid a switch here, edges and faces are simply different!
if isinstance(o, Face) and o.geomType() == "PLANE":
# a face is only parallel to a direction if it is a plane, and
# its normal is parallel to the dir
test_vector = o.normalAt(None)
elif isinstance(o, Edge) and o.geomType() == "LINE":
# an edge is parallel to a direction if its underlying geometry is plane or line
test_vector = o.tangentAt()
else:
continue
if self.test(test_vector):
r.append(o)
return r
class ParallelDirSelector(BaseDirSelector):
r"""
Selects objects parallel with the provided direction.
Applicability:
Linear Edges
Planar Faces
Use the string syntax shortcut \|(X|Y|Z) if you want to select based on a cardinal direction.
Example::
CQ(aCube).faces(ParallelDirSelector((0, 0, 1)))
selects faces with the normal parallel to the z direction, and is equivalent to::
CQ(aCube).faces("|Z")
"""
def test(self, vec: Vector) -> bool:
return self.direction.cross(vec).Length < self.tolerance
class DirectionSelector(BaseDirSelector):
"""
Selects objects aligned with the provided direction.
Applicability:
Linear Edges
Planar Faces
Use the string syntax shortcut +/-(X|Y|Z) if you want to select based on a cardinal direction.
Example::
CQ(aCube).faces(DirectionSelector((0, 0, 1)))
selects faces with the normal in the z direction, and is equivalent to::
CQ(aCube).faces("+Z")
"""
def test(self, vec: Vector) -> bool:
return self.direction.getAngle(vec) < self.tolerance
class PerpendicularDirSelector(BaseDirSelector):
"""
Selects objects perpendicular with the provided direction.
Applicability:
Linear Edges
Planar Faces
Use the string syntax shortcut #(X|Y|Z) if you want to select based on a
cardinal direction.
Example::
CQ(aCube).faces(PerpendicularDirSelector((0, 0, 1)))
selects faces with the normal perpendicular to the z direction, and is equivalent to::
CQ(aCube).faces("#Z")
"""
def test(self, vec: Vector) -> bool:
return abs(self.direction.getAngle(vec) - math.pi / 2) < self.tolerance
class TypeSelector(Selector):
"""
Selects objects having the prescribed geometry type.
Applicability:
Faces: PLANE, CYLINDER, CONE, SPHERE, TORUS, BEZIER, BSPLINE, REVOLUTION, EXTRUSION, OFFSET, OTHER
Edges: LINE, CIRCLE, ELLIPSE, HYPERBOLA, PARABOLA, BEZIER, BSPLINE, OFFSET, OTHER
You can use the string selector syntax. For example this::
CQ(aCube).faces(TypeSelector("PLANE"))
will select 6 faces, and is equivalent to::
CQ(aCube).faces("%PLANE")
"""
def __init__(self, typeString: str):
self.typeString = typeString.upper()
def filter(self, objectList: Sequence[Shape]) -> List[Shape]:
r = []
for o in objectList:
if o.geomType() == self.typeString:
r.append(o)
return r
class _NthSelector(Selector, ABC):
"""
An abstract class that provides the methods to select the Nth object/objects of an ordered list.
"""
def __init__(self, n: int, directionMax: bool = True, tolerance: float = 0.0001):
self.n = n
self.directionMax = directionMax
self.tolerance = tolerance
def filter(self, objectlist: Sequence[Shape]) -> List[Shape]:
"""
Return the nth object in the objectlist sorted by self.key and
clustered if within self.tolerance.
"""
if len(objectlist) == 0:
# nothing to filter
raise ValueError("Can not return the Nth element of an empty list")
clustered = self.cluster(objectlist)
if not self.directionMax:
clustered.reverse()
try:
out = clustered[self.n]
except IndexError:
raise IndexError(
f"Attempted to access index {self.n} of a list with length {len(clustered)}"
)
return out
@abstractmethod
def key(self, obj: Shape) -> float:
"""
Return the key for ordering. Can raise a ValueError if obj can not be
used to create a key, which will result in obj being dropped by the
clustering method.
"""
raise NotImplementedError
def cluster(self, objectlist: Sequence[Shape]) -> List[List[Shape]]:
"""
Clusters the elements of objectlist if they are within tolerance.
"""
key_and_obj = []
for obj in objectlist:
# Need to handle value errors, such as what occurs when you try to
# access the radius of a straight line
try:
key = self.key(obj)
except ValueError:
# forget about this element and continue
continue
key_and_obj.append((key, obj))
key_and_obj.sort(key=lambda x: x[0])
clustered = [[]] # type: List[List[Shape]]
start = key_and_obj[0][0]
for key, obj in key_and_obj:
if abs(key - start) <= self.tolerance:
clustered[-1].append(obj)
else:
clustered.append([obj])
start = key
return clustered
class RadiusNthSelector(_NthSelector):
"""
Select the object with the Nth radius.
Applicability:
All Edge and Wires.
Will ignore any shape that can not be represented as a circle or an arc of
a circle.
"""
def key(self, obj: Shape) -> float:
if isinstance(obj, (Edge, Wire)):
return obj.radius()
else:
raise ValueError("Can not get a radius from this object")
class CenterNthSelector(_NthSelector):
"""
Sorts objects into a list with order determined by the distance of their center projected onto the specified direction.
Applicability:
All Shapes.
"""
def __init__(
self,
vector: Vector,
n: int,
directionMax: bool = True,
tolerance: float = 0.0001,
):
super().__init__(n, directionMax, tolerance)
self.direction = vector
def key(self, obj: Shape) -> float:
return obj.Center().dot(self.direction)
class DirectionMinMaxSelector(CenterNthSelector):
"""
Selects objects closest or farthest in the specified direction.
Applicability:
All object types. for a vertex, its point is used. for all other kinds
of objects, the center of mass of the object is used.
You can use the string shortcuts >(X|Y|Z) or <(X|Y|Z) if you want to select
based on a cardinal direction.
For example this::
CQ(aCube).faces(DirectionMinMaxSelector((0, 0, 1), True))
Means to select the face having the center of mass farthest in the positive
z direction, and is the same as::
CQ(aCube).faces(">Z")
"""
def __init__(
self, vector: Vector, directionMax: bool = True, tolerance: float = 0.0001
):
super().__init__(
n=-1, vector=vector, directionMax=directionMax, tolerance=tolerance
)
# inherit from CenterNthSelector to get the CenterNthSelector.key method
class DirectionNthSelector(ParallelDirSelector, CenterNthSelector):
"""
Filters for objects parallel (or normal) to the specified direction then returns the Nth one.
Applicability:
Linear Edges
Planar Faces
"""
def __init__(
self,
vector: Vector,
n: int,
directionMax: bool = True,
tolerance: float = 0.0001,
):
ParallelDirSelector.__init__(self, vector, tolerance)
_NthSelector.__init__(self, n, directionMax, tolerance)
def filter(self, objectlist: Sequence[Shape]) -> List[Shape]:
objectlist = ParallelDirSelector.filter(self, objectlist)
objectlist = _NthSelector.filter(self, objectlist)
return objectlist
class LengthNthSelector(_NthSelector):
"""
Select the object(s) with the Nth length
Applicability:
All Edge and Wire objects
"""
def key(self, obj: Shape) -> float:
if isinstance(obj, (Edge, Wire)):
return obj.Length()
else:
raise ValueError(
f"LengthNthSelector supports only Edges and Wires, not {type(obj).__name__}"
)
class AreaNthSelector(_NthSelector):
"""
Selects the object(s) with Nth area
Applicability:
- Faces, Shells, Solids - Shape.Area() is used to compute area
- closed planar Wires - a temporary face is created to compute area
Will ignore non-planar or non-closed wires.
Among other things can be used to select one of
the nested coplanar wires or faces.
For example to create a fillet on a shank::
result = (
cq.Workplane("XY")
.circle(5)
.extrude(2)
.circle(2)
.extrude(10)
.faces(">Z[-2]")
.wires(AreaNthSelector(0))
.fillet(2)
)
Or to create a lip on a case seam::
result = (
cq.Workplane("XY")
.rect(20, 20)
.extrude(10)
.edges("|Z or <Z")
.fillet(2)
.faces(">Z")
.shell(2)
.faces(">Z")
.wires(AreaNthSelector(-1))
.toPending()
.workplane()
.offset2D(-1)
.extrude(1)
.faces(">Z[-2]")
.wires(AreaNthSelector(0))
.toPending()
.workplane()
.cutBlind(2)
)
"""
def key(self, obj: Shape) -> float:
if isinstance(obj, (Face, Shell, Solid)):
return obj.Area()
elif isinstance(obj, Wire):
try:
return abs(Face.makeFromWires(obj).Area())
except Exception as ex:
raise ValueError(
f"Can not compute area of the Wire: {ex}. AreaNthSelector supports only closed planar Wires."
)
else:
raise ValueError(
f"AreaNthSelector supports only Wires, Faces, Shells and Solids, not {type(obj).__name__}"
)
class BinarySelector(Selector):
"""
Base class for selectors that operates with two other
selectors. Subclass must implement the :filterResults(): method.
"""
def __init__(self, left, right):
self.left = left
self.right = right
def filter(self, objectList):
return self.filterResults(
self.left.filter(objectList), self.right.filter(objectList)
)
def filterResults(self, r_left, r_right):
raise NotImplementedError
class AndSelector(BinarySelector):
"""
Intersection selector. Returns objects that is selected by both selectors.
"""
def filterResults(self, r_left, r_right):
# return intersection of lists
return list(set(r_left) & set(r_right))
class SumSelector(BinarySelector):
"""
Union selector. Returns the sum of two selectors results.
"""
def filterResults(self, r_left, r_right):
# return the union (no duplicates) of lists
return list(set(r_left + r_right))
class SubtractSelector(BinarySelector):
"""
Difference selector. Subtract results of a selector from another
selectors results.
"""
def filterResults(self, r_left, r_right):
return list(set(r_left) - set(r_right))
class InverseSelector(Selector):
"""
Inverts the selection of given selector. In other words, selects
all objects that is not selected by given selector.
"""
def __init__(self, selector):
self.selector = selector
def filter(self, objectList):
# note that Selector() selects everything
return SubtractSelector(Selector(), self.selector).filter(objectList)
def _makeGrammar():
"""
Define the simple string selector grammar using PyParsing
"""
# float definition
point = Literal(".")
plusmin = Literal("+") | Literal("-")
number = Word(nums)
integer = Combine(Optional(plusmin) + number)
floatn = Combine(integer + Optional(point + Optional(number)))
# vector definition
lbracket = Literal("(")
rbracket = Literal(")")
comma = Literal(",")
vector = Combine(
lbracket + floatn("x") + comma + floatn("y") + comma + floatn("z") + rbracket,
adjacent=False,
)
# direction definition
simple_dir = oneOf(["X", "Y", "Z", "XY", "XZ", "YZ"])
direction = simple_dir("simple_dir") | vector("vector_dir")
# CQ type definition
cqtype = oneOf(
set(geom_LUT_EDGE.values()) | set(geom_LUT_FACE.values()), caseless=True,
)
cqtype = cqtype.setParseAction(pyparsing_common.upcaseTokens)
# type operator
type_op = Literal("%")
# direction operator
direction_op = oneOf([">", "<"])
# center Nth operator
center_nth_op = oneOf([">>", "<<"])
# index definition
ix_number = Group(Optional("-") + Word(nums))
lsqbracket = Literal("[").suppress()
rsqbracket = Literal("]").suppress()
index = lsqbracket + ix_number("index") + rsqbracket
# other operators
other_op = oneOf(["|", "#", "+", "-"])
# named view
named_view = oneOf(["front", "back", "left", "right", "top", "bottom"])
return (
direction("only_dir")
| (type_op("type_op") + cqtype("cq_type"))
| (direction_op("dir_op") + direction("dir") + Optional(index))
| (center_nth_op("center_nth_op") + direction("dir") + Optional(index))
| (other_op("other_op") + direction("dir"))
| named_view("named_view")
)
_grammar = _makeGrammar() # make a grammar instance
class _SimpleStringSyntaxSelector(Selector):
"""
This is a private class that converts a parseResults object into a simple
selector object
"""
def __init__(self, parseResults):
# define all token to object mappings
self.axes = {
"X": Vector(1, 0, 0),
"Y": Vector(0, 1, 0),
"Z": Vector(0, 0, 1),
"XY": Vector(1, 1, 0),
"YZ": Vector(0, 1, 1),
"XZ": Vector(1, 0, 1),
}
self.namedViews = {
"front": (Vector(0, 0, 1), True),
"back": (Vector(0, 0, 1), False),
"left": (Vector(1, 0, 0), False),
"right": (Vector(1, 0, 0), True),
"top": (Vector(0, 1, 0), True),
"bottom": (Vector(0, 1, 0), False),
}
self.operatorMinMax = {
">": True,
">>": True,
"<": False,
"<<": False,
}
self.operator = {
"+": DirectionSelector,
"-": lambda v: DirectionSelector(-v),
"#": PerpendicularDirSelector,
"|": ParallelDirSelector,
}
self.parseResults = parseResults
self.mySelector = self._chooseSelector(parseResults)
def _chooseSelector(self, pr):
"""
Sets up the underlying filters accordingly
"""
if "only_dir" in pr:
vec = self._getVector(pr)
return DirectionSelector(vec)
elif "type_op" in pr:
return TypeSelector(pr.cq_type)
elif "dir_op" in pr:
vec = self._getVector(pr)
minmax = self.operatorMinMax[pr.dir_op]
if "index" in pr:
return DirectionNthSelector(
vec, int("".join(pr.index.asList())), minmax
)
else:
return DirectionMinMaxSelector(vec, minmax)
elif "center_nth_op" in pr:
vec = self._getVector(pr)
minmax = self.operatorMinMax[pr.center_nth_op]
if "index" in pr:
return CenterNthSelector(vec, int("".join(pr.index.asList())), minmax)
else:
return CenterNthSelector(vec, -1, minmax)
elif "other_op" in pr:
vec = self._getVector(pr)
return self.operator[pr.other_op](vec)
else:
args = self.namedViews[pr.named_view]
return DirectionMinMaxSelector(*args)
def _getVector(self, pr):
"""
Translate parsed vector string into a CQ Vector
"""
if "vector_dir" in pr:
vec = pr.vector_dir
return Vector(float(vec.x), float(vec.y), float(vec.z))
else:
return self.axes[pr.simple_dir]
def filter(self, objectList):
r"""
selects minimum, maximum, positive or negative values relative to a direction
``[+|-|<|>|] <X|Y|Z>``
"""
return self.mySelector.filter(objectList)
def _makeExpressionGrammar(atom):
"""
Define the complex string selector grammar using PyParsing (which supports
logical operations and nesting)
"""
# define operators
and_op = Literal("and")
or_op = Literal("or")
delta_op = oneOf(["exc", "except"])
not_op = Literal("not")
def atom_callback(res):
return _SimpleStringSyntaxSelector(res)
# construct a simple selector from every matched
atom.setParseAction(atom_callback)
# define callback functions for all operations
def and_callback(res):
# take every secend items, i.e. all operands
items = res.asList()[0][::2]
return reduce(AndSelector, items)
def or_callback(res):
# take every secend items, i.e. all operands
items = res.asList()[0][::2]
return reduce(SumSelector, items)
def exc_callback(res):
# take every secend items, i.e. all operands
items = res.asList()[0][::2]
return reduce(SubtractSelector, items)
def not_callback(res):
right = res.asList()[0][1] # take second item, i.e. the operand
return InverseSelector(right)
# construct the final grammar and set all the callbacks
expr = infixNotation(
atom,
[
(and_op, 2, opAssoc.LEFT, and_callback),
(or_op, 2, opAssoc.LEFT, or_callback),
(delta_op, 2, opAssoc.LEFT, exc_callback),
(not_op, 1, opAssoc.RIGHT, not_callback),
],
)
return expr
_expression_grammar = _makeExpressionGrammar(_grammar)
class StringSyntaxSelector(Selector):
r"""
Filter lists objects using a simple string syntax. All of the filters available in the string syntax
are also available ( usually with more functionality ) through the creation of full-fledged
selector objects. see :py:class:`Selector` and its subclasses
Filtering works differently depending on the type of object list being filtered.
:param selectorString: A two-part selector string, [selector][axis]
:return: objects that match the specified selector
***Modifiers*** are ``('|','+','-','<','>','%')``
:\|:
parallel to ( same as :py:class:`ParallelDirSelector` ). Can return multiple objects.
:#:
perpendicular to (same as :py:class:`PerpendicularDirSelector` )
:+:
positive direction (same as :py:class:`DirectionSelector` )
:-:
negative direction (same as :py:class:`DirectionSelector` )
:>:
maximize (same as :py:class:`DirectionMinMaxSelector` with directionMax=True)
:<:
minimize (same as :py:class:`DirectionMinMaxSelector` with directionMax=False )
:%:
curve/surface type (same as :py:class:`TypeSelector`)
***axisStrings*** are: ``X,Y,Z,XY,YZ,XZ`` or ``(x,y,z)`` which defines an arbitrary direction
It is possible to combine simple selectors together using logical operations.
The following operations are supported
:and:
Logical AND, e.g. >X and >Y
:or:
Logical OR, e.g. \|X or \|Y
:not:
Logical NOT, e.g. not #XY
:exc(ept):
Set difference (equivalent to AND NOT): \|X exc >Z
Finally, it is also possible to use even more complex expressions with nesting
and arbitrary number of terms, e.g.
(not >X[0] and #XY) or >XY[0]
Selectors are a complex topic: see :ref:`selector_reference` for more information
"""
def __init__(self, selectorString):
"""
Feed the input string through the parser and construct an relevant complex selector object
"""
self.selectorString = selectorString
parse_result = _expression_grammar.parseString(selectorString, parseAll=True)
self.mySelector = parse_result.asList()[0]
def filter(self, objectList):
"""
Filter give object list through th already constructed complex selector object
"""
return self.mySelector.filter(objectList)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,536 | CadQuery/cadquery | refs/heads/master | /examples/Ex021_Splitting_an_Object.py | import cadquery as cq
# Create a simple block with a hole through it that we can split.
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the X and Y origins to define the workplane, meaning that the
# positive Z direction is "up", and the negative Z direction is "down".
# 2. Creates a plain box to base future geometry on with the box() function.
# 3. Selects the top-most face of the box and establishes a workplane on it
# that new geometry can be built on.
# 4. Draws a 2D circle on the new workplane and then uses it to cut a hole
# all the way through the box.
c = cq.Workplane("XY").box(1, 1, 1).faces(">Z").workplane().circle(0.25).cutThruAll()
# 5. Selects the face furthest away from the origin in the +Y axis direction.
# 6. Creates an offset workplane that is set in the center of the object.
# 6a. One possible improvement to this script would be to make the dimensions
# of the box variables, and then divide the Y-axis dimension by 2.0 and
# use that to create the offset workplane.
# 7. Uses the embedded workplane to split the object, keeping only the "top"
# portion.
result = c.faces(">Y").workplane(-0.5).split(keepTop=True)
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,537 | CadQuery/cadquery | refs/heads/master | /cadquery/cq.py | """
Copyright (C) 2011-2015 Parametric Products Intellectual Holdings, LLC
This file is part of CadQuery.
CadQuery is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
CadQuery 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 Lesser General Public
License along with this library; If not, see <http://www.gnu.org/licenses/>
"""
import math
from copy import copy
from itertools import chain
from typing import (
overload,
Sequence,
TypeVar,
Union,
Tuple,
Optional,
Any,
Iterable,
Callable,
List,
cast,
Dict,
)
from typing_extensions import Literal
from inspect import Parameter, Signature
from .occ_impl.geom import Vector, Plane, Location
from .occ_impl.shapes import (
Shape,
Edge,
Wire,
Face,
Solid,
Compound,
wiresToFaces,
)
from .occ_impl.exporters.svg import getSVG, exportSVG
from .utils import deprecate, deprecate_kwarg_name
from .selectors import (
Selector,
StringSyntaxSelector,
)
from .sketch import Sketch
CQObject = Union[Vector, Location, Shape, Sketch]
VectorLike = Union[Tuple[float, float], Tuple[float, float, float], Vector]
CombineMode = Union[bool, Literal["cut", "a", "s"]] # a : additive, s: subtractive
TOL = 1e-6
T = TypeVar("T", bound="Workplane")
"""A type variable used to make the return type of a method the same as the
type of `self` or another argument.
This is useful when you want to allow a class to derive from
:class:`.Workplane`, and you want a (fluent) method in the derived class to
return an instance of the derived class, rather than of :class:`.Workplane`.
"""
def _selectShapes(objects: Iterable[Any]) -> List[Shape]:
return [el for el in objects if isinstance(el, Shape)]
class CQContext(object):
"""
A shared context for modeling.
All objects in the same CQ chain share a reference to this same object instance
which allows for shared state when needed.
"""
pendingWires: List[Wire]
pendingEdges: List[Edge]
firstPoint: Optional[Vector]
tolerance: float
tags: Dict[str, "Workplane"]
def __init__(self):
self.pendingWires = (
[]
) # a list of wires that have been created and need to be extruded
# a list of created pending edges that need to be joined into wires
self.pendingEdges = []
# a reference to the first point for a set of edges.
# Used to determine how to behave when close() is called
self.firstPoint = None
self.tolerance = 0.0001 # user specified tolerance
self.tags = {}
def popPendingEdges(self, errorOnEmpty: bool = True) -> List[Edge]:
"""
Get and clear pending edges.
:raises ValueError: if errorOnEmpty is True and no edges are present.
"""
if errorOnEmpty and not self.pendingEdges:
raise ValueError("No pending edges present")
out = self.pendingEdges
self.pendingEdges = []
return out
def popPendingWires(self, errorOnEmpty: bool = True) -> List[Wire]:
"""
Get and clear pending wires.
:raises ValueError: if errorOnEmpty is True and no wires are present.
"""
if errorOnEmpty and not self.pendingWires:
raise ValueError("No pending wires present")
out = self.pendingWires
self.pendingWires = []
return out
class Workplane(object):
"""
Defines a coordinate system in space, in which 2D coordinates can be used.
:param plane: the plane in which the workplane will be done
:type plane: a Plane object, or a string in (XY|YZ|XZ|front|back|top|bottom|left|right)
:param origin: the desired origin of the new workplane
:type origin: a 3-tuple in global coordinates, or None to default to the origin
:param obj: an object to use initially for the stack
:type obj: a CAD primitive, or None to use the centerpoint of the plane as the initial
stack value.
:raises: ValueError if the provided plane is not a plane, a valid named workplane
:return: A Workplane object, with coordinate system matching the supplied plane.
The most common use is::
s = Workplane("XY")
After creation, the stack contains a single point, the origin of the underlying plane,
and the *current point* is on the origin.
.. note::
You can also create workplanes on the surface of existing faces using
:meth:`workplane`
"""
objects: List[CQObject]
ctx: CQContext
parent: Optional["Workplane"]
plane: Plane
_tag: Optional[str]
@overload
def __init__(self, obj: CQObject) -> None:
...
@overload
def __init__(
self,
inPlane: Union[Plane, str] = "XY",
origin: VectorLike = (0, 0, 0),
obj: Optional[CQObject] = None,
) -> None:
...
def __init__(self, inPlane="XY", origin=(0, 0, 0), obj=None):
"""
make a workplane from a particular plane
:param inPlane: the plane in which the workplane will be done
:type inPlane: a Plane object, or a string in (XY|YZ|XZ|front|back|top|bottom|left|right)
:param origin: the desired origin of the new workplane
:type origin: a 3-tuple in global coordinates, or None to default to the origin
:param obj: an object to use initially for the stack
:type obj: a CAD primitive, or None to use the centerpoint of the plane as the initial
stack value.
:raises: ValueError if the provided plane is not a plane, or one of XY|YZ|XZ
:return: A Workplane object, with coordinate system matching the supplied plane.
The most common use is::
s = Workplane("XY")
After creation, the stack contains a single point, the origin of the underlying plane, and
the *current point* is on the origin.
"""
if isinstance(inPlane, Plane):
tmpPlane = inPlane
elif isinstance(inPlane, str):
tmpPlane = Plane.named(inPlane, origin)
elif isinstance(inPlane, (Vector, Location, Shape)):
obj = inPlane
tmpPlane = Plane.named("XY", origin)
else:
raise ValueError(
"Provided value {} is not a valid work plane".format(inPlane)
)
self.plane = tmpPlane
# Changed so that workplane has the center as the first item on the stack
if obj:
self.objects = [obj]
else:
self.objects = []
self.parent = None
self.ctx = CQContext()
self._tag = None
def tag(self: T, name: str) -> T:
"""
Tags the current CQ object for later reference.
:param name: the name to tag this object with
:returns: self, a CQ object with tag applied
"""
self._tag = name
self.ctx.tags[name] = self
return self
def _collectProperty(self, propName: str) -> List[CQObject]:
"""
Collects all of the values for propName,
for all items on the stack.
OCCT objects do not implement id correctly,
so hashCode is used to ensure we don't add the same
object multiple times.
One weird use case is that the stack could have a solid reference object
on it. This is meant to be a reference to the most recently modified version
of the context solid, whatever it is.
"""
all = {}
for o in self.objects:
# tricky-- if an object is a compound of solids,
# do not return all of the solids underneath-- typically
# then we'll keep joining to ourself
if (
propName == "Solids"
and isinstance(o, Solid)
and o.ShapeType() == "Compound"
):
for i in getattr(o, "Compounds")():
all[i.hashCode()] = i
else:
if hasattr(o, propName):
for i in getattr(o, propName)():
all[i.hashCode()] = i
return list(all.values())
@overload
def split(self: T, keepTop: bool = False, keepBottom: bool = False) -> T:
...
@overload
def split(self: T, splitter: Union[T, Shape]) -> T:
...
def split(self: T, *args, **kwargs) -> T:
"""
Splits a solid on the stack into two parts, optionally keeping the separate parts.
:param bool keepTop: True to keep the top, False or None to discard it
:param bool keepBottom: True to keep the bottom, False or None to discard it
:raises ValueError: if keepTop and keepBottom are both false.
:raises ValueError: if there is no solid in the current stack or parent chain
:returns: CQ object with the desired objects on the stack.
The most common operation splits a solid and keeps one half. This sample creates
a split bushing::
# drill a hole in the side
c = Workplane().box(1, 1, 1).faces(">Z").workplane().circle(0.25).cutThruAll()
# now cut it in half sideways
c = c.faces(">Y").workplane(-0.5).split(keepTop=True)
"""
# split using an object
if len(args) == 1 and isinstance(args[0], (Workplane, Shape)):
arg = args[0]
solid = self.findSolid()
tools = (
(arg,)
if isinstance(arg, Shape)
else [v for v in arg.vals() if isinstance(v, Shape)]
)
rv = [solid.split(*tools)]
if isinstance(arg, Workplane):
self._mergeTags(arg)
# split using the current workplane
else:
# boilerplate for arg/kwarg parsing
sig = Signature(
(
Parameter(
"keepTop", Parameter.POSITIONAL_OR_KEYWORD, default=False
),
Parameter(
"keepBottom", Parameter.POSITIONAL_OR_KEYWORD, default=False
),
)
)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
keepTop = bound_args.arguments["keepTop"]
keepBottom = bound_args.arguments["keepBottom"]
if (not keepTop) and (not keepBottom):
raise ValueError("You have to keep at least one half")
solid = self.findSolid()
maxDim = solid.BoundingBox().DiagonalLength * 10.0
topCutBox = self.rect(maxDim, maxDim)._extrude(maxDim)
bottomCutBox = self.rect(maxDim, maxDim)._extrude(-maxDim)
top = solid.cut(bottomCutBox)
bottom = solid.cut(topCutBox)
if keepTop and keepBottom:
# Put both on the stack, leave original unchanged.
rv = [top, bottom]
else:
# Put the one we are keeping on the stack, and also update the
# context solid to the one we kept.
if keepTop:
rv = [top]
else:
rv = [bottom]
return self.newObject(rv)
@deprecate()
def combineSolids(
self, otherCQToCombine: Optional["Workplane"] = None
) -> "Workplane":
"""
!!!DEPRECATED!!! use union()
Combines all solids on the current stack, and any context object, together
into a single object.
After the operation, the returned solid is also the context solid.
:param otherCQToCombine: another CadQuery to combine.
:return: a CQ object with the resulting combined solid on the stack.
Most of the time, both objects will contain a single solid, which is
combined and returned on the stack of the new object.
"""
# loop through current stack objects, and combine them
toCombine = cast(List[Solid], self.solids().vals())
if otherCQToCombine:
otherSolids = cast(List[Solid], otherCQToCombine.solids().vals())
for obj in otherSolids:
toCombine.append(obj)
if len(toCombine) < 1:
raise ValueError("Cannot Combine: at least one solid required!")
# get context solid and we don't want to find our own objects
ctxSolid = self._findType(
(Solid, Compound), searchStack=False, searchParents=True
)
if ctxSolid is None:
ctxSolid = toCombine.pop(0)
# now combine them all. make sure to save a reference to the ctxSolid pointer!
s: Shape = ctxSolid
if toCombine:
s = s.fuse(*_selectShapes(toCombine))
return self.newObject([s])
def all(self: T) -> List[T]:
"""
Return a list of all CQ objects on the stack.
useful when you need to operate on the elements
individually.
Contrast with vals, which returns the underlying
objects for all of the items on the stack
"""
return [self.newObject([o]) for o in self.objects]
def size(self) -> int:
"""
Return the number of objects currently on the stack
"""
return len(self.objects)
def vals(self) -> List[CQObject]:
"""
get the values in the current list
:rtype: list of occ_impl objects
:returns: the values of the objects on the stack.
Contrast with :meth:`all`, which returns CQ objects for all of the items on the stack
"""
return self.objects
@overload
def add(self: T, obj: "Workplane") -> T:
...
@overload
def add(self: T, obj: CQObject) -> T:
...
@overload
def add(self: T, obj: Iterable[CQObject]) -> T:
...
def add(self, obj):
"""
Adds an object or a list of objects to the stack
:param obj: an object to add
:type obj: a Workplane, CAD primitive, or list of CAD primitives
:return: a Workplane with the requested operation performed
If a Workplane object, the values of that object's stack are added. If
a list of cad primitives, they are all added. If a single CAD primitive
then it is added.
Used in rare cases when you need to combine the results of several CQ
results into a single Workplane object.
"""
if isinstance(obj, list):
self.objects.extend(obj)
elif isinstance(obj, Workplane):
self.objects.extend(obj.objects)
self._mergeTags(obj)
else:
self.objects.append(obj)
return self
def val(self) -> CQObject:
"""
Return the first value on the stack. If no value is present, current plane origin is returned.
:return: the first value on the stack.
:rtype: A CAD primitive
"""
return self.objects[0] if self.objects else self.plane.origin
def _getTagged(self, name: str) -> "Workplane":
"""
Search the parent chain for an object with tag == name.
:param name: the tag to search for
:returns: the Workplane object with tag == name
:raises: ValueError if no object tagged name
"""
rv = self.ctx.tags.get(name)
if rv is None:
raise ValueError(f"No Workplane object named {name} in chain")
return rv
def _mergeTags(self: T, obj: "Workplane") -> T:
"""
Merge tags
This is automatically called when performing boolean ops.
"""
if self.ctx != obj.ctx:
self.ctx.tags = {**obj.ctx.tags, **self.ctx.tags}
return self
def toOCC(self) -> Any:
"""
Directly returns the wrapped OCCT object.
:return: The wrapped OCCT object
:rtype: TopoDS_Shape or a subclass
"""
v = self.val()
return v._faces if isinstance(v, Sketch) else v.wrapped
def workplane(
self: T,
offset: float = 0.0,
invert: bool = False,
centerOption: Literal[
"CenterOfMass", "ProjectedOrigin", "CenterOfBoundBox"
] = "ProjectedOrigin",
origin: Optional[VectorLike] = None,
) -> T:
"""
Creates a new 2D workplane, located relative to the first face on the stack.
:param offset: offset for the workplane in its normal direction . Default
:param invert: invert the normal direction from that of the face.
:param centerOption: how local origin of workplane is determined.
:param origin: origin for plane center, requires 'ProjectedOrigin' centerOption.
:type centerOption: string or None='ProjectedOrigin'
:rtype: Workplane object
The first element on the stack must be a face, a set of
co-planar faces or a vertex. If a vertex, then the parent
item on the chain immediately before the vertex must be a
face.
The result will be a 2D working plane
with a new coordinate system set up as follows:
* The centerOption parameter sets how the center is defined.
Options are 'CenterOfMass', 'CenterOfBoundBox', or 'ProjectedOrigin'.
'CenterOfMass' and 'CenterOfBoundBox' are in relation to the selected
face(s) or vertex (vertices). 'ProjectedOrigin' uses by default the current origin
or the optional origin parameter (if specified) and projects it onto the plane
defined by the selected face(s).
* The Z direction will be the normal of the face, computed
at the center point.
* The X direction will be parallel to the x-y plane. If the workplane is parallel to
the global x-y plane, the x direction of the workplane will co-incide with the
global x direction.
Most commonly, the selected face will be planar, and the workplane lies in the same plane
of the face ( IE, offset=0). Occasionally, it is useful to define a face offset from
an existing surface, and even more rarely to define a workplane based on a face that is
not planar.
"""
def _isCoPlanar(f0, f1):
"""Test if two faces are on the same plane."""
p0 = f0.Center()
p1 = f1.Center()
n0 = f0.normalAt()
n1 = f1.normalAt()
# test normals (direction of planes)
if not (
(abs(n0.x - n1.x) < self.ctx.tolerance)
or (abs(n0.y - n1.y) < self.ctx.tolerance)
or (abs(n0.z - n1.z) < self.ctx.tolerance)
):
return False
# test if p1 is on the plane of f0 (offset of planes)
return abs(n0.dot(p0.sub(p1)) < self.ctx.tolerance)
def _computeXdir(normal):
"""
Figures out the X direction based on the given normal.
:param normal: The direction that's normal to the plane.
:type normal: A Vector
:return A vector representing the X direction.
"""
xd = Vector(0, 0, 1).cross(normal)
if xd.Length < self.ctx.tolerance:
# this face is parallel with the x-y plane, so choose x to be in global coordinates
xd = Vector(1, 0, 0)
return xd
if centerOption not in {"CenterOfMass", "ProjectedOrigin", "CenterOfBoundBox"}:
raise ValueError("Undefined centerOption value provided.")
if len(self.objects) > 1:
objs: List[Face] = [o for o in self.objects if isinstance(o, Face)]
if not all(o.geomType() in ("PLANE", "CIRCLE") for o in objs) or len(
objs
) < len(self.objects):
raise ValueError(
"If multiple objects selected, they all must be planar faces."
)
# are all faces co-planar with each other?
if not all(_isCoPlanar(self.objects[0], f) for f in self.objects[1:]):
raise ValueError("Selected faces must be co-planar.")
if centerOption in {"CenterOfMass", "ProjectedOrigin"}:
center = Shape.CombinedCenter(_selectShapes(self.objects))
elif centerOption == "CenterOfBoundBox":
center = Shape.CombinedCenterOfBoundBox(_selectShapes(self.objects))
normal = objs[0].normalAt()
xDir = _computeXdir(normal)
else:
obj = self.val()
if isinstance(obj, Face):
if centerOption in {"CenterOfMass", "ProjectedOrigin"}:
center = obj.Center()
elif centerOption == "CenterOfBoundBox":
center = obj.CenterOfBoundBox()
normal = obj.normalAt(center)
xDir = _computeXdir(normal)
elif isinstance(obj, (Shape, Vector)):
if centerOption in {"CenterOfMass", "ProjectedOrigin"}:
center = obj.Center()
elif centerOption == "CenterOfBoundBox":
center = (
obj.CenterOfBoundBox()
if isinstance(obj, Shape)
else obj.Center()
)
val = self.parent.val() if self.parent else None
if isinstance(val, Face):
normal = val.normalAt(center)
xDir = _computeXdir(normal)
else:
normal = self.plane.zDir
xDir = self.plane.xDir
else:
raise ValueError("Needs a face or a vertex or point on a work plane")
# update center to projected origin if desired
if centerOption == "ProjectedOrigin":
orig: Vector
if origin is None:
orig = self.plane.origin
elif isinstance(origin, tuple):
orig = Vector(origin)
else:
orig = origin
center = orig.projectToPlane(Plane(center, xDir, normal))
# invert if requested
if invert:
normal = normal.multiply(-1.0)
# offset origin if desired
offsetVector = normal.normalized().multiply(offset)
offsetCenter = center.add(offsetVector)
# make the new workplane
plane = Plane(offsetCenter, xDir, normal)
s = self.__class__(plane)
s.parent = self
s.ctx = self.ctx
# a new workplane has the center of the workplane on the stack
return s
def copyWorkplane(self, obj: T) -> T:
"""
Copies the workplane from obj.
:param obj: an object to copy the workplane from
:type obj: a CQ object
:returns: a CQ object with obj's workplane
"""
out = obj.__class__(obj.plane)
out.parent = self
out.ctx = self.ctx
return out
def workplaneFromTagged(self, name: str) -> "Workplane":
"""
Copies the workplane from a tagged parent.
:param name: tag to search for
:returns: a CQ object with name's workplane
"""
tagged = self._getTagged(name)
out = self.copyWorkplane(tagged)
return out
def first(self: T) -> T:
"""
Return the first item on the stack
:returns: the first item on the stack.
:rtype: a CQ object
"""
return self.newObject(self.objects[0:1])
def item(self: T, i: int) -> T:
"""
Return the ith item on the stack.
:rtype: a CQ object
"""
return self.newObject([self.objects[i]])
def last(self: T) -> T:
"""
Return the last item on the stack.
:rtype: a CQ object
"""
return self.newObject([self.objects[-1]])
def end(self, n: int = 1) -> "Workplane":
"""
Return the nth parent of this CQ element
:param n: number of ancestor to return (default: 1)
:rtype: a CQ object
:raises: ValueError if there are no more parents in the chain.
For example::
CQ(obj).faces("+Z").vertices().end()
will return the same as::
CQ(obj).faces("+Z")
"""
rv = self
for _ in range(n):
if rv.parent:
rv = rv.parent
else:
raise ValueError("Cannot End the chain-- no parents!")
return rv
def _findType(self, types, searchStack=True, searchParents=True):
if searchStack:
rv = [s for s in self.objects if isinstance(s, types)]
if rv and types == (Solid, Compound):
return Compound.makeCompound(rv)
elif rv:
return rv[0]
if searchParents and self.parent is not None:
return self.parent._findType(types, searchStack=True, searchParents=True)
return None
def findSolid(
self, searchStack: bool = True, searchParents: bool = True
) -> Union[Solid, Compound]:
"""
Finds the first solid object in the chain, searching from the current node
backwards through parents until one is found.
:param searchStack: should objects on the stack be searched first?
:param searchParents: should parents be searched?
:raises ValueError: if no solid is found
This function is very important for chains that are modifying a single parent object,
most often a solid.
Most of the time, a chain defines or selects a solid, and then modifies it using workplanes
or other operations.
Plugin Developers should make use of this method to find the solid that should be modified,
if the plugin implements a unary operation, or if the operation will automatically merge its
results with an object already on the stack.
"""
found = self._findType((Solid, Compound), searchStack, searchParents)
if found is None:
message = "on the stack or " if searchStack else ""
raise ValueError(
"Cannot find a solid {}in the parent chain".format(message)
)
return found
@deprecate()
def findFace(self, searchStack: bool = True, searchParents: bool = True) -> Face:
"""
Finds the first face object in the chain, searching from the current node
backwards through parents until one is found.
:param searchStack: should objects on the stack be searched first.
:param searchParents: should parents be searched?
:returns: A face or None if no face is found.
"""
found = self._findType(Face, searchStack, searchParents)
if found is None:
message = "on the stack or " if searchStack else ""
raise ValueError("Cannot find a face {}in the parent chain".format(message))
return found
def _selectObjects(
self: T,
objType: Any,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Filters objects of the selected type with the specified selector,and returns results
:param objType: the type of object we are searching for
:type objType: string: (Vertex|Edge|Wire|Solid|Shell|Compound|CompSolid)
:param tag: if set, search the tagged CQ object instead of self
:return: a CQ object with the selected objects on the stack.
**Implementation Note**: This is the base implementation of the vertices,edges,faces,
solids,shells, and other similar selector methods. It is a useful extension point for
plugin developers to make other selector methods.
"""
self_as_workplane: Workplane = self
cq_obj = self._getTagged(tag) if tag else self_as_workplane
# A single list of all faces from all objects on the stack
toReturn = cq_obj._collectProperty(objType)
selectorObj: Selector
if selector:
if isinstance(selector, str):
selectorObj = StringSyntaxSelector(selector)
else:
selectorObj = selector
toReturn = selectorObj.filter(toReturn)
return self.newObject(toReturn)
def vertices(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the vertices of objects on the stack, optionally filtering the selection. If there
are multiple objects on the stack, the vertices of all objects are collected and a list of
all the distinct vertices is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains the *distinct* vertices of *all* objects on the
current stack, after being filtered by the selector, if provided
If there are no vertices for any objects on the current stack, an empty CQ object
is returned
The typical use is to select the vertices of a single object on the stack. For example::
Workplane().box(1, 1, 1).faces("+Z").vertices().size()
returns 4, because the topmost face of a cube will contain four vertices. While this::
Workplane().box(1, 1, 1).faces().vertices().size()
returns 8, because a cube has a total of 8 vertices
**Note** Circles are peculiar, they have a single vertex at the center!
"""
return self._selectObjects("Vertices", selector, tag)
def faces(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the faces of objects on the stack, optionally filtering the selection. If there are
multiple objects on the stack, the faces of all objects are collected and a list of all the
distinct faces is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* faces of *all* objects on
the current stack, filtered by the provided selector.
If there are no faces for any objects on the current stack, an empty CQ object
is returned.
The typical use is to select the faces of a single object on the stack. For example::
Workplane().box(1, 1, 1).faces("+Z").size()
returns 1, because a cube has one face with a normal in the +Z direction. Similarly::
Workplane().box(1, 1, 1).faces().size()
returns 6, because a cube has a total of 6 faces, And::
Workplane().box(1, 1, 1).faces("|Z").size()
returns 2, because a cube has 2 faces having normals parallel to the z direction
"""
return self._selectObjects("Faces", selector, tag)
def edges(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the edges of objects on the stack, optionally filtering the selection. If there are
multiple objects on the stack, the edges of all objects are collected and a list of all the
distinct edges is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* edges of *all* objects on
the current stack, filtered by the provided selector.
If there are no edges for any objects on the current stack, an empty CQ object is returned
The typical use is to select the edges of a single object on the stack. For example::
Workplane().box(1, 1, 1).faces("+Z").edges().size()
returns 4, because the topmost face of a cube will contain four edges. Similarly::
Workplane().box(1, 1, 1).edges().size()
returns 12, because a cube has a total of 12 edges, And::
Workplane().box(1, 1, 1).edges("|Z").size()
returns 4, because a cube has 4 edges parallel to the z direction
"""
return self._selectObjects("Edges", selector, tag)
def wires(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the wires of objects on the stack, optionally filtering the selection. If there are
multiple objects on the stack, the wires of all objects are collected and a list of all the
distinct wires is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* wires of *all* objects on
the current stack, filtered by the provided selector.
If there are no wires for any objects on the current stack, an empty CQ object is returned
The typical use is to select the wires of a single object on the stack. For example::
Workplane().box(1, 1, 1).faces("+Z").wires().size()
returns 1, because a face typically only has one outer wire
"""
return self._selectObjects("Wires", selector, tag)
def solids(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the solids of objects on the stack, optionally filtering the selection. If there are
multiple objects on the stack, the solids of all objects are collected and a list of all the
distinct solids is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* solids of *all* objects on
the current stack, filtered by the provided selector.
If there are no solids for any objects on the current stack, an empty CQ object is returned
The typical use is to select a single object on the stack. For example::
Workplane().box(1, 1, 1).solids().size()
returns 1, because a cube consists of one solid.
It is possible for a single CQ object ( or even a single CAD primitive ) to contain
multiple solids.
"""
return self._selectObjects("Solids", selector, tag)
def shells(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select the shells of objects on the stack, optionally filtering the selection. If there are
multiple objects on the stack, the shells of all objects are collected and a list of all the
distinct shells is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* shells of *all* objects on
the current stack, filtered by the provided selector.
If there are no shells for any objects on the current stack, an empty CQ object is returned
Most solids will have a single shell, which represents the outer surface. A shell will
typically be composed of multiple faces.
"""
return self._selectObjects("Shells", selector, tag)
def compounds(
self: T,
selector: Optional[Union[Selector, str]] = None,
tag: Optional[str] = None,
) -> T:
"""
Select compounds on the stack, optionally filtering the selection. If there are multiple
objects on the stack, they are collected and a list of all the distinct compounds
is returned.
:param selector: optional Selector object, or string selector expression
(see :class:`StringSyntaxSelector`)
:param tag: if set, search the tagged object instead of self
:return: a CQ object who's stack contains all of the *distinct* compounds of *all* objects on
the current stack, filtered by the provided selector.
A compound contains multiple CAD primitives that resulted from a single operation, such as
a union, cut, split, or fillet. Compounds can contain multiple edges, wires, or solids.
"""
return self._selectObjects("Compounds", selector, tag)
def toSvg(self, opts: Any = None) -> str:
"""
Returns svg text that represents the first item on the stack.
for testing purposes.
:param opts: svg formatting options
:type opts: dictionary, width and height
:return: a string that contains SVG that represents this item.
"""
return getSVG(self.val(), opts)
def exportSvg(self, fileName: str) -> None:
"""
Exports the first item on the stack as an SVG file
For testing purposes mainly.
:param fileName: the filename to export, absolute path to the file
"""
exportSVG(self, fileName)
def rotateAboutCenter(self: T, axisEndPoint: VectorLike, angleDegrees: float) -> T:
"""
Rotates all items on the stack by the specified angle, about the specified axis
The center of rotation is a vector starting at the center of the object on the stack,
and ended at the specified point.
:param axisEndPoint: the second point of axis of rotation
:type axisEndPoint: a three-tuple in global coordinates
:param angleDegrees: the rotation angle, in degrees
:returns: a CQ object, with all items rotated.
WARNING: This version returns the same CQ object instead of a new one-- the
old object is not accessible.
Future Enhancements:
* A version of this method that returns a transformed copy, rather than modifying
the originals
* This method doesn't expose a very good interface, because the axis of rotation
could be inconsistent between multiple objects. This is because the beginning
of the axis is variable, while the end is fixed. This is fine when operating on
one object, but is not cool for multiple.
"""
# center point is the first point in the vector
endVec = Vector(axisEndPoint)
def _rot(obj):
startPt = obj.Center()
endPt = startPt + endVec
return obj.rotate(startPt, endPt, angleDegrees)
return self.each(_rot, False, False)
def rotate(
self: T,
axisStartPoint: VectorLike,
axisEndPoint: VectorLike,
angleDegrees: float,
) -> T:
"""
Returns a copy of all of the items on the stack rotated through and angle around the axis
of rotation.
:param axisStartPoint: The first point of the axis of rotation
:type axisStartPoint: a 3-tuple of floats
:param axisEndPoint: The second point of the axis of rotation
:type axisEndPoint: a 3-tuple of floats
:param angleDegrees: the rotation angle, in degrees
:returns: a CQ object
"""
return self.newObject(
[
o.rotate(Vector(axisStartPoint), Vector(axisEndPoint), angleDegrees)
if isinstance(o, Shape)
else o
for o in self.objects
]
)
def mirror(
self: T,
mirrorPlane: Union[
Literal["XY", "YX", "XZ", "ZX", "YZ", "ZY"], VectorLike, Face, "Workplane"
] = "XY",
basePointVector: Optional[VectorLike] = None,
union: bool = False,
) -> T:
"""
Mirror a single CQ object.
:param mirrorPlane: the plane to mirror about
:type mirrorPlane: string, one of "XY", "YX", "XZ", "ZX", "YZ", "ZY" the planes
or the normal vector of the plane eg (1,0,0) or a Face object
:param basePointVector: the base point to mirror about (this is overwritten if a Face is passed)
:param union: If true will perform a union operation on the mirrored object
"""
mp: Union[Literal["XY", "YX", "XZ", "ZX", "YZ", "ZY"], Vector]
bp: Vector
face: Optional[Face] = None
# handle mirrorPLane
if isinstance(mirrorPlane, Workplane):
val = mirrorPlane.val()
if isinstance(val, Face):
mp = val.normalAt()
face = val
else:
raise ValueError(f"Face required, got {val}")
elif isinstance(mirrorPlane, Face):
mp = mirrorPlane.normalAt()
face = mirrorPlane
elif not isinstance(mirrorPlane, str):
mp = Vector(mirrorPlane)
else:
mp = mirrorPlane
# handle basePointVector
if face and basePointVector is None:
bp = face.Center()
elif basePointVector is None:
bp = Vector()
else:
bp = Vector(basePointVector)
newS = self.newObject(
[obj.mirror(mp, bp) for obj in self.vals() if isinstance(obj, Shape)]
)
if union:
return self.union(newS)
else:
return newS
def translate(self: T, vec: VectorLike) -> T:
"""
Returns a copy of all of the items on the stack moved by the specified translation vector.
:param tupleDistance: distance to move, in global coordinates
:type tupleDistance: a 3-tuple of float
:returns: a CQ object
"""
return self.newObject(
[
o.translate(Vector(vec)) if isinstance(o, Shape) else o
for o in self.objects
]
)
def shell(
self: T, thickness: float, kind: Literal["arc", "intersection"] = "arc"
) -> T:
"""
Remove the selected faces to create a shell of the specified thickness.
To shell, first create a solid, and *in the same chain* select the faces you wish to remove.
:param thickness: thickness of the desired shell.
Negative values shell inwards, positive values shell outwards.
:param kind: kind of join, arc or intersection (default: arc).
:raises ValueError: if the current stack contains objects that are not faces of a solid
further up in the chain.
:returns: a CQ object with the resulting shelled solid selected.
This example will create a hollowed out unit cube, where the top most face is open,
and all other walls are 0.2 units thick::
Workplane().box(1, 1, 1).faces("+Z").shell(0.2)
You can also select multiple faces at once. Here is an example that creates a three-walled
corner, by removing three faces of a cube::
Workplane().box(10, 10, 10).faces(">Z or >X or <Y").shell(1)
**Note**: When sharp edges are shelled inwards, they remain sharp corners, but **outward**
shells are automatically filleted (unless kind="intersection"), because an outward offset
from a corner generates a radius.
"""
solidRef = self.findSolid()
faces = [f for f in self.objects if isinstance(f, Face)]
s = solidRef.shell(faces, thickness, kind=kind)
return self.newObject([s])
def fillet(self: T, radius: float) -> T:
"""
Fillets a solid on the selected edges.
The edges on the stack are filleted. The solid to which the edges belong must be in the
parent chain of the selected edges.
:param radius: the radius of the fillet, must be > zero
:raises ValueError: if at least one edge is not selected
:raises ValueError: if the solid containing the edge is not in the chain
:returns: CQ object with the resulting solid selected.
This example will create a unit cube, with the top edges filleted::
s = Workplane().box(1, 1, 1).faces("+Z").edges().fillet(0.1)
"""
# TODO: ensure that edges selected actually belong to the solid in the chain, otherwise,
# TODO: we segfault
solid = self.findSolid()
edgeList = cast(List[Edge], self.edges().vals())
if len(edgeList) < 1:
raise ValueError("Fillets requires that edges be selected")
s = solid.fillet(radius, edgeList)
return self.newObject([s.clean()])
def chamfer(self: T, length: float, length2: Optional[float] = None) -> T:
"""
Chamfers a solid on the selected edges.
The edges on the stack are chamfered. The solid to which the
edges belong must be in the parent chain of the selected
edges.
Optional parameter `length2` can be supplied with a different
value than `length` for a chamfer that is shorter on one side
longer on the other side.
:param length: the length of the chamfer, must be greater than zero
:param length2: optional parameter for asymmetrical chamfer
:raises ValueError: if at least one edge is not selected
:raises ValueError: if the solid containing the edge is not in the chain
:returns: CQ object with the resulting solid selected.
This example will create a unit cube, with the top edges chamfered::
s = Workplane("XY").box(1, 1, 1).faces("+Z").chamfer(0.1)
This example will create chamfers longer on the sides::
s = Workplane("XY").box(1, 1, 1).faces("+Z").chamfer(0.2, 0.1)
"""
solid = self.findSolid()
edgeList = cast(List[Edge], self.edges().vals())
if len(edgeList) < 1:
raise ValueError("Chamfer requires that edges be selected")
s = solid.chamfer(length, length2, edgeList)
return self.newObject([s])
def transformed(
self: T, rotate: VectorLike = (0, 0, 0), offset: VectorLike = (0, 0, 0)
) -> T:
"""
Create a new workplane based on the current one.
The origin of the new plane is located at the existing origin+offset vector, where offset is
given in coordinates local to the current plane
The new plane is rotated through the angles specified by the components of the rotation
vector.
:param rotate: 3-tuple of angles to rotate, in degrees relative to work plane coordinates
:param offset: 3-tuple to offset the new plane, in local work plane coordinates
:return: a new work plane, transformed as requested
"""
# old api accepted a vector, so we'll check for that.
if isinstance(rotate, Vector):
rotate = rotate.toTuple()
if isinstance(offset, Vector):
offset = offset.toTuple()
p = self.plane.rotated(rotate)
p.origin = self.plane.toWorldCoords(offset)
ns = self.newObject([p.origin])
ns.plane = p
return ns
def newObject(self: T, objlist: Iterable[CQObject]) -> T:
"""
Create a new workplane object from this one.
Overrides CQ.newObject, and should be used by extensions, plugins, and
subclasses to create new objects.
:param objlist: new objects to put on the stack
:type objlist: a list of CAD primitives
:return: a new Workplane object with the current workplane as a parent.
"""
# copy the current state to the new object
ns = self.__class__()
ns.plane = copy(self.plane)
ns.parent = self
ns.objects = list(objlist)
ns.ctx = self.ctx
return ns
def _findFromPoint(self, useLocalCoords: bool = False) -> Vector:
"""
Finds the start point for an operation when an existing point
is implied. Examples include 2d operations such as lineTo,
which allows specifying the end point, and implicitly use the
end of the previous line as the starting point
:return: a Vector representing the point to use, or none if
such a point is not available.
:param useLocalCoords: selects whether the point is returned
in local coordinates or global coordinates.
The algorithm is this:
* If an Edge is on the stack, its end point is used.yp
* if a vector is on the stack, it is used
WARNING: only the last object on the stack is used.
"""
obj = self.objects[-1] if self.objects else self.plane.origin
if isinstance(obj, Edge):
p = obj.endPoint()
elif isinstance(obj, Vector):
p = obj
else:
raise RuntimeError("Cannot convert object type '%s' to vector " % type(obj))
if useLocalCoords:
return self.plane.toLocalCoords(p)
else:
return p
def _findFromEdge(self, useLocalCoords: bool = False) -> Edge:
"""
Finds the previous edge for an operation that needs it, similar to
method _findFromPoint. Examples include tangentArcPoint.
:param useLocalCoords: selects whether the point is returned
in local coordinates or global coordinates.
:return: an Edge
"""
obj = self.objects[-1] if self.objects else self.plane.origin
if not isinstance(obj, Edge):
raise RuntimeError(
"Previous Edge requested, but the previous object was of "
+ f"type {type(obj)}, not an Edge."
)
rv: Edge = obj
if useLocalCoords:
rv = self.plane.toLocalCoords(rv)
return rv
def rarray(
self: T,
xSpacing: float,
ySpacing: float,
xCount: int,
yCount: int,
center: Union[bool, Tuple[bool, bool]] = True,
) -> T:
"""
Creates an array of points and pushes them onto the stack.
If you want to position the array at another point, create another workplane
that is shifted to the position you would like to use as a reference
:param xSpacing: spacing between points in the x direction ( must be > 0)
:param ySpacing: spacing between points in the y direction ( must be > 0)
:param xCount: number of points ( > 0 )
:param yCount: number of points ( > 0 )
:param center: If True, the array will be centered around the workplane center.
If False, the lower corner will be on the reference point and the array will
extend in the positive x and y directions. Can also use a 2-tuple to specify
centering along each axis.
"""
if xSpacing <= 0 or ySpacing <= 0 or xCount < 1 or yCount < 1:
raise ValueError("Spacing and count must be > 0 ")
if isinstance(center, bool):
center = (center, center)
lpoints = [] # coordinates relative to bottom left point
for x in range(xCount):
for y in range(yCount):
lpoints.append(Vector(xSpacing * x, ySpacing * y))
# shift points down and left relative to origin if requested
offset = Vector()
if center[0]:
offset += Vector(-xSpacing * (xCount - 1) * 0.5, 0)
if center[1]:
offset += Vector(0, -ySpacing * (yCount - 1) * 0.5)
lpoints = [x + offset for x in lpoints]
return self.pushPoints(lpoints)
def polarArray(
self: T,
radius: float,
startAngle: float,
angle: float,
count: int,
fill: bool = True,
rotate: bool = True,
) -> T:
"""
Creates a polar array of points and pushes them onto the stack.
The zero degree reference angle is located along the local X-axis.
:param radius: Radius of the array.
:param startAngle: Starting angle (degrees) of array. Zero degrees is
situated along the local X-axis.
:param angle: The angle (degrees) to fill with elements. A positive
value will fill in the counter-clockwise direction. If fill is
False, angle is the angle between elements.
:param count: Number of elements in array. (count >= 1)
:param fill: Interpret the angle as total if True (default: True).
:param rotate: Rotate every item (default: True).
"""
if count < 1:
raise ValueError(f"At least 1 element required, requested {count}")
# Calculate angle between elements
if fill:
if abs(math.remainder(angle, 360)) < TOL:
angle = angle / count
else:
# Inclusive start and end
angle = angle / (count - 1) if count > 1 else startAngle
locs = []
# Add elements
for i in range(0, count):
phi_deg = startAngle + (angle * i)
phi = math.radians(phi_deg)
x = radius * math.cos(phi)
y = radius * math.sin(phi)
if rotate:
loc = Location(Vector(x, y), Vector(0, 0, 1), phi_deg)
else:
loc = Location(Vector(x, y))
locs.append(loc)
return self.pushPoints(locs)
def pushPoints(self: T, pntList: Iterable[Union[VectorLike, Location]]) -> T:
"""
Pushes a list of points onto the stack as vertices.
The points are in the 2D coordinate space of the workplane face
:param pntList: a list of points to push onto the stack
:type pntList: list of 2-tuples, in *local* coordinates
:return: a new workplane with the desired points on the stack.
A common use is to provide a list of points for a subsequent operation, such as creating
circles or holes. This example creates a cube, and then drills three holes through it,
based on three points::
s = (
Workplane()
.box(1, 1, 1)
.faces(">Z")
.workplane()
.pushPoints([(-0.3, 0.3), (0.3, 0.3), (0, 0)])
)
body = s.circle(0.05).cutThruAll()
Here the circle function operates on all three points, and is then extruded to create three
holes. See :meth:`circle` for how it works.
"""
vecs: List[Union[Location, Vector]] = []
for pnt in pntList:
vecs.append(
pnt if isinstance(pnt, Location) else self.plane.toWorldCoords(pnt)
)
return self.newObject(vecs)
def center(self: T, x: float, y: float) -> T:
"""
Shift local coordinates to the specified location.
The location is specified in terms of local coordinates.
:param x: the new x location
:param y: the new y location
:returns: the Workplane object, with the center adjusted.
The current point is set to the new center.
This method is useful to adjust the center point after it has been created automatically on
a face, but not where you'd like it to be.
In this example, we adjust the workplane center to be at the corner of a cube, instead of
the center of a face, which is the default::
# this workplane is centered at x=0.5,y=0.5, the center of the upper face
s = Workplane().box(1, 1, 1).faces(">Z").workplane()
s = s.center(-0.5, -0.5) # move the center to the corner
t = s.circle(0.25).extrude(0.2)
assert t.faces().size() == 9 # a cube with a cylindrical nub at the top right corner
The result is a cube with a round boss on the corner
"""
new_origin = self.plane.toWorldCoords((x, y))
n = self.newObject([new_origin])
n.plane.setOrigin2d(x, y)
return n
def lineTo(self: T, x: float, y: float, forConstruction: bool = False) -> T:
"""
Make a line from the current point to the provided point
:param x: the x point, in workplane plane coordinates
:param y: the y point, in workplane plane coordinates
:return: the Workplane object with the current point at the end of the new line
See :meth:`line` if you want to use relative dimensions to make a line instead.
"""
startPoint = self._findFromPoint(False)
endPoint = self.plane.toWorldCoords((x, y))
p = Edge.makeLine(startPoint, endPoint)
if not forConstruction:
self._addPendingEdge(p)
return self.newObject([p])
# line a specified incremental amount from current point
def line(self: T, xDist: float, yDist: float, forConstruction: bool = False) -> T:
"""
Make a line from the current point to the provided point, using
dimensions relative to the current point
:param xDist: x distance from current point
:param yDist: y distance from current point
:return: the workplane object with the current point at the end of the new line
see :meth:`lineTo` if you want to use absolute coordinates to make a line instead.
"""
p = self._findFromPoint(True) # return local coordinates
return self.lineTo(p.x + xDist, yDist + p.y, forConstruction)
def vLine(self: T, distance: float, forConstruction: bool = False) -> T:
"""
Make a vertical line from the current point the provided distance
:param distance: (y) distance from current point
:return: the Workplane object with the current point at the end of the new line
"""
return self.line(0, distance, forConstruction)
def hLine(self: T, distance: float, forConstruction: bool = False) -> T:
"""
Make a horizontal line from the current point the provided distance
:param distance: (x) distance from current point
:return: the Workplane object with the current point at the end of the new line
"""
return self.line(distance, 0, forConstruction)
def vLineTo(self: T, yCoord: float, forConstruction: bool = False) -> T:
"""
Make a vertical line from the current point to the provided y coordinate.
Useful if it is more convenient to specify the end location rather than distance,
as in :meth:`vLine`
:param yCoord: y coordinate for the end of the line
:return: the Workplane object with the current point at the end of the new line
"""
p = self._findFromPoint(True)
return self.lineTo(p.x, yCoord, forConstruction)
def hLineTo(self: T, xCoord: float, forConstruction: bool = False) -> T:
"""
Make a horizontal line from the current point to the provided x coordinate.
Useful if it is more convenient to specify the end location rather than distance,
as in :meth:`hLine`
:param xCoord: x coordinate for the end of the line
:return: the Workplane object with the current point at the end of the new line
"""
p = self._findFromPoint(True)
return self.lineTo(xCoord, p.y, forConstruction)
def polarLine(
self: T, distance: float, angle: float, forConstruction: bool = False
) -> T:
"""
Make a line of the given length, at the given angle from the current point
:param distance: distance of the end of the line from the current point
:param angle: angle of the vector to the end of the line with the x-axis
:return: the Workplane object with the current point at the end of the new line
"""
x = math.cos(math.radians(angle)) * distance
y = math.sin(math.radians(angle)) * distance
return self.line(x, y, forConstruction)
def polarLineTo(
self: T, distance: float, angle: float, forConstruction: bool = False
) -> T:
"""
Make a line from the current point to the given polar coordinates
Useful if it is more convenient to specify the end location rather than
the distance and angle from the current point
:param distance: distance of the end of the line from the origin
:param angle: angle of the vector to the end of the line with the x-axis
:return: the Workplane object with the current point at the end of the new line
"""
x = math.cos(math.radians(angle)) * distance
y = math.sin(math.radians(angle)) * distance
return self.lineTo(x, y, forConstruction)
# absolute move in current plane, not drawing
def moveTo(self: T, x: float = 0, y: float = 0) -> T:
"""
Move to the specified point, without drawing.
:param x: desired x location, in local coordinates
:type x: float, or none for zero
:param y: desired y location, in local coordinates
:type y: float, or none for zero.
Not to be confused with :meth:`center`, which moves the center of the entire
workplane, this method only moves the current point ( and therefore does not affect objects
already drawn ).
See :meth:`move` to do the same thing but using relative dimensions
"""
newCenter = Vector(x, y, 0)
return self.newObject([self.plane.toWorldCoords(newCenter)])
# relative move in current plane, not drawing
def move(self: T, xDist: float = 0, yDist: float = 0) -> T:
"""
Move the specified distance from the current point, without drawing.
:param xDist: desired x distance, in local coordinates
:type xDist: float, or none for zero
:param yDist: desired y distance, in local coordinates
:type yDist: float, or none for zero.
Not to be confused with :meth:`center`, which moves the center of the entire
workplane, this method only moves the current point ( and therefore does not affect objects
already drawn ).
See :meth:`moveTo` to do the same thing but using absolute coordinates
"""
p = self._findFromPoint(True)
newCenter = p + Vector(xDist, yDist, 0)
return self.newObject([self.plane.toWorldCoords(newCenter)])
def slot2D(self: T, length: float, diameter: float, angle: float = 0) -> T:
"""
Creates a rounded slot for each point on the stack.
:param diameter: desired diameter, or width, of slot
:param length: desired end to end length of slot
:param angle: angle of slot in degrees, with 0 being along x-axis
:return: a new CQ object with the created wires on the stack
Can be used to create arrays of slots, such as in cooling applications::
Workplane().box(10, 25, 1).rarray(1, 2, 1, 10).slot2D(8, 1, 0).cutThruAll()
"""
radius = diameter / 2
p1 = Vector((-length / 2) + radius, diameter / 2)
p2 = p1 + Vector(length - diameter, 0)
p3 = p1 + Vector(length - diameter, -diameter)
p4 = p1 + Vector(0, -diameter)
arc1 = p2 + Vector(radius, -radius)
arc2 = p4 + Vector(-radius, radius)
edges = [(Edge.makeLine(p1, p2))]
edges.append(Edge.makeThreePointArc(p2, arc1, p3))
edges.append(Edge.makeLine(p3, p4))
edges.append(Edge.makeThreePointArc(p4, arc2, p1))
slot = Wire.assembleEdges(edges)
slot = slot.rotate(Vector(), Vector(0, 0, 1), angle)
return self.eachpoint(lambda loc: slot.moved(loc), True)
def _toVectors(
self, pts: Iterable[VectorLike], includeCurrent: bool
) -> List[Vector]:
vecs = [self.plane.toWorldCoords(p) for p in pts]
if includeCurrent:
gstartPoint = self._findFromPoint(False)
allPoints = [gstartPoint] + vecs
else:
allPoints = vecs
return allPoints
def spline(
self: T,
listOfXYTuple: Iterable[VectorLike],
tangents: Optional[Sequence[VectorLike]] = None,
periodic: bool = False,
parameters: Optional[Sequence[float]] = None,
scale: bool = True,
tol: Optional[float] = None,
forConstruction: bool = False,
includeCurrent: bool = False,
makeWire: bool = False,
) -> T:
"""
Create a spline interpolated through the provided points (2D or 3D).
:param listOfXYTuple: points to interpolate through
:param tangents: vectors specifying the direction of the tangent to the
curve at each of the specified interpolation points.
If only 2 tangents are given, they will be used as the initial and
final tangent.
If some tangents are not specified (i.e., are None), no tangent
constraint will be applied to the corresponding interpolation point.
The spline will be C2 continuous at the interpolation points where
no tangent constraint is specified, and C1 continuous at the points
where a tangent constraint is specified.
:param periodic: creation of periodic curves
:param parameters: the value of the parameter at each interpolation point.
(The interpolated curve is represented as a vector-valued function of a
scalar parameter.)
If periodic == True, then len(parameters) must be
len(interpolation points) + 1, otherwise len(parameters) must be equal to
len(interpolation points).
:param scale: whether to scale the specified tangent vectors before
interpolating.
Each tangent is scaled, so it's length is equal to the derivative of
the Lagrange interpolated curve.
I.e., set this to True, if you want to use only the direction of
the tangent vectors specified by ``tangents``, but not their magnitude.
:param tol: tolerance of the algorithm (consult OCC documentation)
Used to check that the specified points are not too close to each
other, and that tangent vectors are not too short. (In either case
interpolation may fail.)
Set to None to use the default tolerance.
:param includeCurrent: use current point as a starting point of the curve
:param makeWire: convert the resulting spline edge to a wire
:return: a Workplane object with the current point at the end of the spline
The spline will begin at the current point, and end with the last point in the
XY tuple list.
This example creates a block with a spline for one side::
s = Workplane(Plane.XY())
sPnts = [
(2.75, 1.5),
(2.5, 1.75),
(2.0, 1.5),
(1.5, 1.0),
(1.0, 1.25),
(0.5, 1.0),
(0, 1.0),
]
r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close()
r = r.extrude(0.5)
*WARNING* It is fairly easy to create a list of points
that cannot be correctly interpreted as a spline.
"""
allPoints = self._toVectors(listOfXYTuple, includeCurrent)
if tangents:
tangents_g: Optional[Sequence[Vector]] = [
self.plane.toWorldCoords(t) - self.plane.origin
if t is not None
else None
for t in tangents
]
else:
tangents_g = None
e = Edge.makeSpline(
allPoints,
tangents=tangents_g,
periodic=periodic,
parameters=parameters,
scale=scale,
**({"tol": tol} if tol else {}),
)
if makeWire:
rv_w = Wire.assembleEdges([e])
if not forConstruction:
self._addPendingWire(rv_w)
else:
if not forConstruction:
self._addPendingEdge(e)
return self.newObject([rv_w if makeWire else e])
def splineApprox(
self: T,
points: Iterable[VectorLike],
tol: Optional[float] = 1e-6,
minDeg: int = 1,
maxDeg: int = 6,
smoothing: Optional[Tuple[float, float, float]] = (1, 1, 1),
forConstruction: bool = False,
includeCurrent: bool = False,
makeWire: bool = False,
) -> T:
"""
Create a spline interpolated through the provided points (2D or 3D).
:param points: points to interpolate through
:param tol: tolerance of the algorithm (default: 1e-6)
:param minDeg: minimum spline degree (default: 1)
:param maxDeg: maximum spline degree (default: 6)
:param smoothing: optional parameters for the variational smoothing algorithm (default: (1,1,1))
:param includeCurrent: use current point as a starting point of the curve
:param makeWire: convert the resulting spline edge to a wire
:return: a Workplane object with the current point at the end of the spline
*WARNING* for advanced users.
"""
allPoints = self._toVectors(points, includeCurrent)
e = Edge.makeSplineApprox(
allPoints,
minDeg=minDeg,
maxDeg=maxDeg,
smoothing=smoothing,
**({"tol": tol} if tol else {}),
)
if makeWire:
rv_w = Wire.assembleEdges([e])
if not forConstruction:
self._addPendingWire(rv_w)
else:
if not forConstruction:
self._addPendingEdge(e)
return self.newObject([rv_w if makeWire else e])
def parametricCurve(
self: T,
func: Callable[[float], VectorLike],
N: int = 400,
start: float = 0,
stop: float = 1,
tol: float = 1e-6,
minDeg: int = 1,
maxDeg: int = 6,
smoothing: Optional[Tuple[float, float, float]] = (1, 1, 1),
makeWire: bool = True,
) -> T:
"""
Create a spline curve approximating the provided function.
:param func: function f(t) that will generate (x,y,z) pairs
:type func: float --> (float,float,float)
:param N: number of points for discretization
:param start: starting value of the parameter t
:param stop: final value of the parameter t
:param tol: tolerance of the algorithm (default: 1e-6)
:param minDeg: minimum spline degree (default: 1)
:param maxDeg: maximum spline degree (default: 6)
:param smoothing: optional parameters for the variational smoothing algorithm (default: (1,1,1))
:param makeWire: convert the resulting spline edge to a wire
:return: a Workplane object with the current point unchanged
"""
diff = stop - start
allPoints = self._toVectors(
(func(start + diff * t / N) for t in range(N + 1)), False
)
e = Edge.makeSplineApprox(
allPoints, tol=tol, smoothing=smoothing, minDeg=minDeg, maxDeg=maxDeg
)
if makeWire:
rv_w = Wire.assembleEdges([e])
self._addPendingWire(rv_w)
else:
self._addPendingEdge(e)
return self.newObject([rv_w if makeWire else e])
def parametricSurface(
self: T,
func: Callable[[float, float], VectorLike],
N: int = 20,
start: float = 0,
stop: float = 1,
tol: float = 1e-2,
minDeg: int = 1,
maxDeg: int = 6,
smoothing: Optional[Tuple[float, float, float]] = (1, 1, 1),
) -> T:
"""
Create a spline surface approximating the provided function.
:param func: function f(u,v) that will generate (x,y,z) pairs
:type func: (float,float) --> (float,float,float)
:param N: number of points for discretization in one direction
:param start: starting value of the parameters u,v
:param stop: final value of the parameters u,v
:param tol: tolerance used by the approximation algorithm (default: 1e-3)
:param minDeg: minimum spline degree (default: 1)
:param maxDeg: maximum spline degree (default: 3)
:param smoothing: optional parameters for the variational smoothing algorithm (default: (1,1,1))
:return: a Workplane object with the current point unchanged
This method might be unstable and may require tuning of the tol parameter.
"""
diff = stop - start
allPoints = []
for i in range(N + 1):
generator = (
func(start + diff * i / N, start + diff * j / N) for j in range(N + 1)
)
allPoints.append(self._toVectors(generator, False))
f = Face.makeSplineApprox(
allPoints, tol=tol, smoothing=smoothing, minDeg=minDeg, maxDeg=maxDeg
)
return self.newObject([f])
def ellipseArc(
self: T,
x_radius: float,
y_radius: float,
angle1: float = 360,
angle2: float = 360,
rotation_angle: float = 0.0,
sense: Literal[-1, 1] = 1,
forConstruction: bool = False,
startAtCurrent: bool = True,
makeWire: bool = False,
) -> T:
"""Draw an elliptical arc with x and y radiuses either with start point at current point or
or current point being the center of the arc
:param x_radius: x radius of the ellipse (along the x-axis of plane the ellipse should lie in)
:param y_radius: y radius of the ellipse (along the y-axis of plane the ellipse should lie in)
:param angle1: start angle of arc
:param angle2: end angle of arc (angle2 == angle1 return closed ellipse = default)
:param rotation_angle: angle to rotate the created ellipse / arc
:param sense: clockwise (-1) or counter clockwise (1)
:param startAtCurrent: True: start point of arc is moved to current point; False: center of
arc is on current point
:param makeWire: convert the resulting arc edge to a wire
"""
# Start building the ellipse with the current point as center
center = self._findFromPoint(useLocalCoords=False)
e = Edge.makeEllipse(
x_radius,
y_radius,
center,
self.plane.zDir,
self.plane.xDir,
angle1,
angle2,
sense,
)
# Rotate if necessary
if rotation_angle != 0.0:
e = e.rotate(center, center.add(self.plane.zDir), rotation_angle)
# Move the start point of the ellipse onto the last current point
if startAtCurrent:
startPoint = e.startPoint()
e = e.translate(center.sub(startPoint))
if makeWire:
rv_w = Wire.assembleEdges([e])
if not forConstruction:
self._addPendingWire(rv_w)
else:
if not forConstruction:
self._addPendingEdge(e)
return self.newObject([rv_w if makeWire else e])
def threePointArc(
self: T, point1: VectorLike, point2: VectorLike, forConstruction: bool = False,
) -> T:
"""
Draw an arc from the current point, through point1, and ending at point2
:param point1: point to draw through
:type point1: 2-tuple, in workplane coordinates
:param point2: end point for the arc
:type point2: 2-tuple, in workplane coordinates
:return: a workplane with the current point at the end of the arc
Future Enhancements:
provide a version that allows an arc using relative measures
provide a centerpoint arc
provide tangent arcs
"""
gstartPoint = self._findFromPoint(False)
gpoint1 = self.plane.toWorldCoords(point1)
gpoint2 = self.plane.toWorldCoords(point2)
arc = Edge.makeThreePointArc(gstartPoint, gpoint1, gpoint2)
if not forConstruction:
self._addPendingEdge(arc)
return self.newObject([arc])
def sagittaArc(
self: T, endPoint: VectorLike, sag: float, forConstruction: bool = False,
) -> T:
"""
Draw an arc from the current point to endPoint with an arc defined by the sag (sagitta).
:param endPoint: end point for the arc
:type endPoint: 2-tuple, in workplane coordinates
:param sag: the sagitta of the arc
:type sag: float, perpendicular distance from arc center to arc baseline.
:return: a workplane with the current point at the end of the arc
The sagitta is the distance from the center of the arc to the arc base.
Given that a closed contour is drawn clockwise;
A positive sagitta means convex arc and negative sagitta means concave arc.
See `<https://en.wikipedia.org/wiki/Sagitta_(geometry)>`_ for more information.
"""
startPoint = self._findFromPoint(useLocalCoords=True)
endPoint = Vector(endPoint)
midPoint = endPoint.add(startPoint).multiply(0.5)
sagVector = endPoint.sub(startPoint).normalized().multiply(abs(sag))
if sag > 0:
sagVector.x, sagVector.y = (
-sagVector.y,
sagVector.x,
) # Rotate sagVector +90 deg
else:
sagVector.x, sagVector.y = (
sagVector.y,
-sagVector.x,
) # Rotate sagVector -90 deg
sagPoint = midPoint.add(sagVector)
return self.threePointArc(sagPoint, endPoint, forConstruction)
def radiusArc(
self: T, endPoint: VectorLike, radius: float, forConstruction: bool = False,
) -> T:
"""
Draw an arc from the current point to endPoint with an arc defined by the radius.
:param endPoint: end point for the arc
:type endPoint: 2-tuple, in workplane coordinates
:param radius: the radius of the arc
:type radius: float, the radius of the arc between start point and end point.
:return: a workplane with the current point at the end of the arc
Given that a closed contour is drawn clockwise;
A positive radius means convex arc and negative radius means concave arc.
"""
startPoint = self._findFromPoint(useLocalCoords=True)
endPoint = Vector(endPoint)
# Calculate the sagitta from the radius
length = endPoint.sub(startPoint).Length / 2.0
try:
sag = abs(radius) - math.sqrt(radius ** 2 - length ** 2)
except ValueError:
raise ValueError("Arc radius is not large enough to reach the end point.")
# Return a sagittaArc
if radius > 0:
return self.sagittaArc(endPoint, sag, forConstruction)
else:
return self.sagittaArc(endPoint, -sag, forConstruction)
def tangentArcPoint(
self: T,
endpoint: VectorLike,
forConstruction: bool = False,
relative: bool = True,
) -> T:
"""
Draw an arc as a tangent from the end of the current edge to endpoint.
:param endpoint: point for the arc to end at
:type endpoint: 2-tuple, 3-tuple or Vector
:param relative: True if endpoint is specified relative to the current point, False if endpoint is in workplane coordinates
:return: a Workplane object with an arc on the stack
Requires the the current first object on the stack is an Edge, as would
be the case after a lineTo operation or similar.
"""
if not isinstance(endpoint, Vector):
endpoint = Vector(endpoint)
if relative:
endpoint = endpoint + self._findFromPoint(useLocalCoords=True)
endpoint = self.plane.toWorldCoords(endpoint)
previousEdge = self._findFromEdge()
arc = Edge.makeTangentArc(
previousEdge.endPoint(), previousEdge.tangentAt(1), endpoint
)
if not forConstruction:
self._addPendingEdge(arc)
return self.newObject([arc])
def mirrorY(self: T) -> T:
"""
Mirror entities around the y axis of the workplane plane.
:return: a new object with any free edges consolidated into as few wires as possible.
All free edges are collected into a wire, and then the wire is mirrored,
and finally joined into a new wire
Typically used to make creating wires with symmetry easier. This line of code::
s = Workplane().lineTo(2, 2).threePointArc((3, 1), (2, 0)).mirrorX().extrude(0.25)
Produces a flat, heart shaped object
"""
# convert edges to a wire, if there are pending edges
n = self.wire(forConstruction=False)
# attempt to consolidate wires together.
consolidated = n.consolidateWires()
mirroredWires = self.plane.mirrorInPlane(consolidated.wires().vals(), "Y")
for w in mirroredWires:
consolidated.objects.append(w)
consolidated._addPendingWire(w)
# attempt again to consolidate all of the wires
return consolidated.consolidateWires()
def mirrorX(self: T) -> T:
"""
Mirror entities around the x axis of the workplane plane.
:return: a new object with any free edges consolidated into as few wires as possible.
All free edges are collected into a wire, and then the wire is mirrored,
and finally joined into a new wire
Typically used to make creating wires with symmetry easier.
"""
# convert edges to a wire, if there are pending edges
n = self.wire(forConstruction=False)
# attempt to consolidate wires together.
consolidated = n.consolidateWires()
mirroredWires = self.plane.mirrorInPlane(consolidated.wires().vals(), "X")
for w in mirroredWires:
consolidated.objects.append(w)
consolidated._addPendingWire(w)
# attempt again to consolidate all of the wires
return consolidated.consolidateWires()
def _addPendingEdge(self, edge: Edge) -> None:
"""
Queues an edge for later combination into a wire.
"""
self.ctx.pendingEdges.append(edge)
if self.ctx.firstPoint is None:
self.ctx.firstPoint = self.plane.toLocalCoords(edge.startPoint())
def _addPendingWire(self, wire: Wire) -> None:
"""
Queue a Wire for later extrusion
Internal Processing Note. In OCCT, edges-->wires-->faces-->solids.
but users do not normally care about these distinctions. Users 'think' in terms
of edges, and solids.
CadQuery tracks edges as they are drawn, and automatically combines them into wires
when the user does an operation that needs it.
Similarly, CadQuery tracks pending wires, and automatically combines them into faces
when necessary to make a solid.
"""
self.ctx.pendingWires.append(wire)
def _consolidateWires(self) -> List[Wire]:
# note: do not use CQContext.popPendingEdges or Wires here, this method does not
# clear pending edges or wires.
wires = cast(
List[Union[Edge, Wire]],
[el for el in chain(self.ctx.pendingEdges, self.ctx.pendingWires)],
)
if not wires:
return []
return Wire.combine(wires)
def consolidateWires(self: T) -> T:
"""
Attempt to consolidate wires on the stack into a single.
If possible, a new object with the results are returned.
if not possible, the wires remain separated
"""
w = self._consolidateWires()
if not w:
return self
# ok this is a little tricky. if we consolidate wires, we have to actually
# modify the pendingWires collection to remove the original ones, and replace them
# with the consolidate done
# since we are already assuming that all wires could be consolidated, its easy, we just
# clear the pending wire list
r = self.newObject(w)
r.ctx.pendingWires = w
r.ctx.pendingEdges = []
return r
def wire(self: T, forConstruction: bool = False) -> T:
"""
Returns a CQ object with all pending edges connected into a wire.
All edges on the stack that can be combined will be combined into a single wire object,
and other objects will remain on the stack unmodified. If there are no pending edges,
this method will just return self.
:param forConstruction: whether the wire should be used to make a solid, or if it is just
for reference
This method is primarily of use to plugin developers making utilities for 2D construction.
This method should be called when a user operation implies that 2D construction is
finished, and we are ready to begin working in 3d.
SEE '2D construction concepts' for a more detailed explanation of how CadQuery handles
edges, wires, etc.
Any non edges will still remain.
"""
# do not consolidate if there are no free edges
if len(self.ctx.pendingEdges) == 0:
return self
edges = self.ctx.popPendingEdges()
w = Wire.assembleEdges(edges)
if not forConstruction:
self._addPendingWire(w)
others = [e for e in self.objects if not isinstance(e, Edge)]
return self.newObject(others + [w])
def each(
self: T,
callback: Callable[[CQObject], Shape],
useLocalCoordinates: bool = False,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Runs the provided function on each value in the stack, and collects the return values into
a new CQ object.
Special note: a newly created workplane always has its center point as its only stack item
:param callBackFunction: the function to call for each item on the current stack.
:param useLocalCoordinates: should values be converted from local coordinates first?
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
The callback function must accept one argument, which is the item on the stack, and return
one object, which is collected. If the function returns None, nothing is added to the stack.
The object passed into the callBackFunction is potentially transformed to local coordinates,
if useLocalCoordinates is true
useLocalCoordinates is very useful for plugin developers.
If false, the callback function is assumed to be working in global coordinates. Objects
created are added as-is, and objects passed into the function are sent in using global
coordinates
If true, the calling function is assumed to be working in local coordinates. Objects are
transformed to local coordinates before they are passed into the callback method, and result
objects are transformed to global coordinates after they are returned.
This allows plugin developers to create objects in local coordinates, without worrying
about the fact that the working plane is different than the global coordinate system.
TODO: wrapper object for Wire will clean up forConstruction flag everywhere
"""
results = []
for obj in self.objects:
if useLocalCoordinates:
# TODO: this needs to work for all types of objects, not just vectors!
r = callback(self.plane.toLocalCoords(obj))
r = r.transformShape(self.plane.rG)
else:
r = callback(obj)
if isinstance(r, Wire):
if not r.forConstruction:
self._addPendingWire(r)
results.append(r)
return self._combineWithBase(results, combine, clean)
def eachpoint(
self: T,
callback: Callable[[Location], Shape],
useLocalCoordinates: bool = False,
combine: CombineMode = False,
clean: bool = True,
) -> T:
"""
Same as each(), except each item on the stack is converted into a point before it
is passed into the callback function.
:return: CadQuery object which contains a list of vectors (points ) on its stack.
:param useLocalCoordinates: should points be in local or global coordinates
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
The resulting object has a point on the stack for each object on the original stack.
Vertices and points remain a point. Faces, Wires, Solids, Edges, and Shells are converted
to a point by using their center of mass.
If the stack has zero length, a single point is returned, which is the center of the current
workplane/coordinate system
"""
# convert stack to a list of points
pnts = []
plane = self.plane
loc = self.plane.location
if len(self.objects) == 0:
# nothing on the stack. here, we'll assume we should operate with the
# origin as the context point
pnts.append(Location())
else:
for o in self.objects:
if isinstance(o, (Vector, Shape)):
pnts.append(loc.inverse * Location(plane, o.Center()))
elif isinstance(o, Sketch):
pnts.append(loc.inverse * Location(plane, o._faces.Center()))
else:
pnts.append(o)
if useLocalCoordinates:
res = [callback(p).move(loc) for p in pnts]
else:
res = [callback(p * loc) for p in pnts]
for r in res:
if isinstance(r, Wire) and not r.forConstruction:
self._addPendingWire(r)
return self._combineWithBase(res, combine, clean)
def rect(
self: T,
xLen: float,
yLen: float,
centered: Union[bool, Tuple[bool, bool]] = True,
forConstruction: bool = False,
) -> T:
"""
Make a rectangle for each item on the stack.
:param xLen: length in the x direction (in workplane coordinates)
:param yLen: length in the y direction (in workplane coordinates)
:param centered: If True, the rectangle will be centered around the reference
point. If False, the corner of the rectangle will be on the reference point and
it will extend in the positive x and y directions. Can also use a 2-tuple to
specify centering along each axis.
:param forConstruction: should the new wires be reference geometry only?
:type forConstruction: true if the wires are for reference, false if they are creating part
geometry
:return: a new CQ object with the created wires on the stack
A common use case is to use a for-construction rectangle to define the centers of a hole
pattern::
s = Workplane().rect(4.0, 4.0, forConstruction=True).vertices().circle(0.25)
Creates 4 circles at the corners of a square centered on the origin.
Negative values for xLen and yLen are permitted, although they only have an effect when
centered is False.
Future Enhancements:
* project points not in the workplane plane onto the workplane plane
"""
if isinstance(centered, bool):
centered = (centered, centered)
offset = Vector()
if not centered[0]:
offset += Vector(xLen / 2, 0, 0)
if not centered[1]:
offset += Vector(0, yLen / 2, 0)
points = [
Vector(xLen / -2.0, yLen / -2.0, 0),
Vector(xLen / 2.0, yLen / -2.0, 0),
Vector(xLen / 2.0, yLen / 2.0, 0),
Vector(xLen / -2.0, yLen / 2.0, 0),
]
points = [x + offset for x in points]
# close the wire
points.append(points[0])
w = Wire.makePolygon(points, forConstruction)
return self.eachpoint(lambda loc: w.moved(loc), True)
# circle from current point
def circle(self: T, radius: float, forConstruction: bool = False) -> T:
"""
Make a circle for each item on the stack.
:param radius: radius of the circle
:param forConstruction: should the new wires be reference geometry only?
:type forConstruction: true if the wires are for reference, false if they are creating
part geometry
:return: a new CQ object with the created wires on the stack
A common use case is to use a for-construction rectangle to define the centers of a
hole pattern::
s = Workplane().rect(4.0, 4.0, forConstruction=True).vertices().circle(0.25)
Creates 4 circles at the corners of a square centered on the origin. Another common case is
to use successive circle() calls to create concentric circles. This works because the
center of a circle is its reference point::
s = Workplane().circle(2.0).circle(1.0)
Creates two concentric circles, which when extruded will form a ring.
Future Enhancements:
better way to handle forConstruction
project points not in the workplane plane onto the workplane plane
"""
c = Wire.makeCircle(radius, Vector(), Vector(0, 0, 1))
c.forConstruction = forConstruction
return self.eachpoint(lambda loc: c.moved(loc), True)
# ellipse from current point
def ellipse(
self: T,
x_radius: float,
y_radius: float,
rotation_angle: float = 0.0,
forConstruction: bool = False,
) -> T:
"""
Make an ellipse for each item on the stack.
:param x_radius: x radius of the ellipse (x-axis of plane the ellipse should lie in)
:param y_radius: y radius of the ellipse (y-axis of plane the ellipse should lie in)
:param rotation_angle: angle to rotate the ellipse
:param forConstruction: should the new wires be reference geometry only?
:type forConstruction: true if the wires are for reference, false if they are creating
part geometry
:return: a new CQ object with the created wires on the stack
*NOTE* Due to a bug in opencascade (https://tracker.dev.opencascade.org/view.php?id=31290)
the center of mass (equals center for next shape) is shifted. To create concentric ellipses
use::
Workplane("XY").center(10, 20).ellipse(100, 10).center(0, 0).ellipse(50, 5)
"""
e = Wire.makeEllipse(
x_radius,
y_radius,
Vector(),
Vector(0, 0, 1),
Vector(1, 0, 0),
rotation_angle=rotation_angle,
)
e.forConstruction = forConstruction
return self.eachpoint(lambda loc: e.moved(loc), True)
def polygon(
self: T,
nSides: int,
diameter: float,
forConstruction: bool = False,
circumscribed: bool = False,
) -> T:
"""
Make a polygon for each item on the stack.
By default, each polygon is created by inscribing it in a circle of the
specified diameter, such that the first vertex is oriented in the x direction.
Alternatively, each polygon can be created by circumscribing it around
a circle of the specified diameter, such that the midpoint of the first edge
is oriented in the x direction. Circumscribed polygons are thus rotated by
pi/nSides radians relative to the inscribed polygon. This ensures the extent
of the polygon along the positive x-axis is always known.
This has the advantage of not requiring additional formulae for purposes such as
tiling on the x-axis (at least for even sided polygons).
:param nSides: number of sides, must be >= 3
:param diameter: the diameter of the circle for constructing the polygon
:param circumscribed: circumscribe the polygon about a circle
:type circumscribed: true to create the polygon by circumscribing it about a circle,
false to create the polygon by inscribing it in a circle
:return: a polygon wire
"""
# pnt is a vector in local coordinates
angle = 2.0 * math.pi / nSides
radius = diameter / 2.0
if circumscribed:
radius /= math.cos(angle / 2.0)
pnts = []
for i in range(nSides + 1):
o = angle * i
if circumscribed:
o += angle / 2.0
pnts.append(Vector(radius * math.cos(o), radius * math.sin(o), 0,))
p = Wire.makePolygon(pnts, forConstruction)
return self.eachpoint(lambda loc: p.moved(loc), True)
def polyline(
self: T,
listOfXYTuple: Sequence[VectorLike],
forConstruction: bool = False,
includeCurrent: bool = False,
) -> T:
"""
Create a polyline from a list of points
:param listOfXYTuple: a list of points in Workplane coordinates (2D or 3D)
:param forConstruction: whether or not the edges are used for reference
:type forConstruction: true if the edges are for reference, false if they are for creating geometry
part geometry
:param includeCurrent: use current point as a starting point of the polyline
:return: a new CQ object with a list of edges on the stack
*NOTE* most commonly, the resulting wire should be closed.
"""
# Our list of new edges that will go into a new CQ object
edges = []
if includeCurrent:
startPoint = self._findFromPoint(False)
points = listOfXYTuple
else:
startPoint = self.plane.toWorldCoords(listOfXYTuple[0])
points = listOfXYTuple[1:]
# Draw a line for each set of points, starting from the from-point of the original CQ object
for curTuple in points:
endPoint = self.plane.toWorldCoords(curTuple)
edges.append(Edge.makeLine(startPoint, endPoint))
# We need to move the start point for the next line that we draw or we get stuck at the same startPoint
startPoint = endPoint
if not forConstruction:
self._addPendingEdge(edges[-1])
return self.newObject(edges)
def close(self: T) -> T:
"""
End construction, and attempt to build a closed wire.
:return: a CQ object with a completed wire on the stack, if possible.
After 2D (or 3D) drafting with methods such as lineTo, threePointArc,
tangentArcPoint and polyline, it is necessary to convert the edges
produced by these into one or more wires.
When a set of edges is closed, CadQuery assumes it is safe to build
the group of edges into a wire. This example builds a simple triangular
prism::
s = Workplane().lineTo(1, 0).lineTo(1, 1).close().extrude(0.2)
"""
endPoint = self._findFromPoint(True)
if self.ctx.firstPoint is None:
raise ValueError("No start point specified - cannot close")
else:
startPoint = self.ctx.firstPoint
# Check if there is a distance between startPoint and endPoint
# that is larger than what is considered a numerical error.
# If so; add a line segment between endPoint and startPoint
if endPoint.sub(startPoint).Length > 1e-6:
self.polyline([endPoint, startPoint])
# Need to reset the first point after closing a wire
self.ctx.firstPoint = None
return self.wire()
def largestDimension(self) -> float:
"""
Finds the largest dimension in the stack.
Used internally to create thru features, this is how you can compute
how long or wide a feature must be to make sure to cut through all of the material
:raises ValueError: if no solids or compounds are found
:return: A value representing the largest dimension of the first solid on the stack
"""
# Get all the solids contained within this CQ object
compound = self.findSolid()
return compound.BoundingBox().DiagonalLength
def cutEach(
self: T,
fcn: Callable[[Location], Shape],
useLocalCoords: bool = False,
clean: bool = True,
) -> T:
"""
Evaluates the provided function at each point on the stack (ie, eachpoint)
and then cuts the result from the context solid.
:param fcn: a function suitable for use in the eachpoint method: ie, that accepts a vector
:param useLocalCoords: same as for :meth:`eachpoint`
:param clean: call :meth:`clean` afterwards to have a clean shape
:raises ValueError: if no solids or compounds are found in the stack or parent chain
:return: a CQ object that contains the resulting solid
"""
ctxSolid = self.findSolid()
# will contain all of the counterbores as a single compound
results = cast(List[Shape], self.eachpoint(fcn, useLocalCoords).vals())
s = ctxSolid.cut(*results)
if clean:
s = s.clean()
return self.newObject([s])
# TODO: almost all code duplicated!
# but parameter list is different so a simple function pointer won't work
def cboreHole(
self: T,
diameter: float,
cboreDiameter: float,
cboreDepth: float,
depth: Optional[float] = None,
clean: bool = True,
) -> T:
"""
Makes a counterbored hole for each item on the stack.
:param diameter: the diameter of the hole
:param cboreDiameter: the diameter of the cbore, must be greater than hole diameter
:param cboreDepth: depth of the counterbore
:type cboreDepth: float > 0
:param depth: the depth of the hole
:type depth: float > 0 or None to drill thru the entire part
:param clean: call :meth:`clean` afterwards to have a clean shape
The surface of the hole is at the current workplane plane.
One hole is created for each item on the stack. A very common use case is to use a
construction rectangle to define the centers of a set of holes, like so::
s = (
Workplane()
.box(2, 4, 0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cboreHole(0.125, 0.25, 0.125, depth=None)
)
This sample creates a plate with a set of holes at the corners.
**Plugin Note**: this is one example of the power of plugins. Counterbored holes are quite
time consuming to create, but are quite easily defined by users.
see :meth:`cskHole` to make countersinks instead of counterbores
"""
if depth is None:
depth = self.largestDimension()
boreDir = Vector(0, 0, -1)
center = Vector()
# first make the hole
hole = Solid.makeCylinder(
diameter / 2.0, depth, center, boreDir
) # local coordinates!
# add the counter bore
cbore = Solid.makeCylinder(cboreDiameter / 2.0, cboreDepth, Vector(), boreDir)
r = hole.fuse(cbore)
return self.cutEach(lambda loc: r.moved(loc), True, clean)
# TODO: almost all code duplicated!
# but parameter list is different so a simple function pointer won't work
def cskHole(
self: T,
diameter: float,
cskDiameter: float,
cskAngle: float,
depth: Optional[float] = None,
clean: bool = True,
) -> T:
"""
Makes a countersunk hole for each item on the stack.
:param diameter: the diameter of the hole
:type diameter: float > 0
:param cskDiameter: the diameter of the countersink, must be greater than hole diameter
:param cskAngle: angle of the countersink, in degrees ( 82 is common )
:type cskAngle: float > 0
:param depth: the depth of the hole
:type depth: float > 0 or None to drill thru the entire part.
:param clean: call :meth:`clean` afterwards to have a clean shape
The surface of the hole is at the current workplane.
One hole is created for each item on the stack. A very common use case is to use a
construction rectangle to define the centers of a set of holes, like so::
s = (
Workplane()
.box(2, 4, 0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.cskHole(0.125, 0.25, 82, depth=None)
)
This sample creates a plate with a set of holes at the corners.
**Plugin Note**: this is one example of the power of plugins. CounterSunk holes are quite
time consuming to create, but are quite easily defined by users.
see :meth:`cboreHole` to make counterbores instead of countersinks
"""
if depth is None:
depth = self.largestDimension()
boreDir = Vector(0, 0, -1)
center = Vector()
# first make the hole
hole = Solid.makeCylinder(
diameter / 2.0, depth, center, boreDir
) # local coords!
r = cskDiameter / 2.0
h = r / math.tan(math.radians(cskAngle / 2.0))
csk = Solid.makeCone(r, 0.0, h, center, boreDir)
res = hole.fuse(csk)
return self.cutEach(lambda loc: res.moved(loc), True, clean)
# TODO: almost all code duplicated!
# but parameter list is different so a simple function pointer won't work
def hole(
self: T, diameter: float, depth: Optional[float] = None, clean: bool = True,
) -> T:
"""
Makes a hole for each item on the stack.
:param diameter: the diameter of the hole
:param depth: the depth of the hole
:type depth: float > 0 or None to drill thru the entire part.
:param clean: call :meth:`clean` afterwards to have a clean shape
The surface of the hole is at the current workplane.
One hole is created for each item on the stack. A very common use case is to use a
construction rectangle to define the centers of a set of holes, like so::
s = (
Workplane()
.box(2, 4, 0.5)
.faces(">Z")
.workplane()
.rect(1.5, 3.5, forConstruction=True)
.vertices()
.hole(0.125, 0.25, 82, depth=None)
)
This sample creates a plate with a set of holes at the corners.
**Plugin Note**: this is one example of the power of plugins. CounterSunk holes are quite
time consuming to create, but are quite easily defined by users.
see :meth:`cboreHole` and :meth:`cskHole` to make counterbores or countersinks
"""
if depth is None:
depth = self.largestDimension()
boreDir = Vector(0, 0, -1)
# first make the hole
h = Solid.makeCylinder(
diameter / 2.0, depth, Vector(), boreDir
) # local coordinates!
return self.cutEach(lambda loc: h.moved(loc), True, clean)
# TODO: duplicated code with _extrude and extrude
def twistExtrude(
self: T,
distance: float,
angleDegrees: float,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Extrudes a wire in the direction normal to the plane, but also twists by the specified
angle over the length of the extrusion.
The center point of the rotation will be the center of the workplane.
See extrude for more details, since this method is the same except for the the addition
of the angle. In fact, if angle=0, the result is the same as a linear extrude.
**NOTE** This method can create complex calculations, so be careful using it with
complex geometries
:param distance: the distance to extrude normal to the workplane
:param angle: angle (in degrees) to rotate through the extrusion
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:return: a CQ object with the resulting solid selected.
"""
faces = self._getFaces()
# compute extrusion vector and extrude
eDir = self.plane.zDir.multiply(distance)
# one would think that fusing faces into a compound and then extruding would work,
# but it doesn't-- the resulting compound appears to look right, ( right number of faces, etc)
# but then cutting it from the main solid fails with BRep_NotDone.
# the work around is to extrude each and then join the resulting solids, which seems to work
# underlying cad kernel can only handle simple bosses-- we'll aggregate them if there
# are multiple sets
shapes: List[Shape] = []
for f in faces:
thisObj = Solid.extrudeLinearWithRotation(
f, self.plane.origin, eDir, angleDegrees
)
shapes.append(thisObj)
r = Compound.makeCompound(shapes).fuse()
return self._combineWithBase(r, combine, clean)
def extrude(
self: T,
until: Union[float, Literal["next", "last"], Face],
combine: CombineMode = True,
clean: bool = True,
both: bool = False,
taper: Optional[float] = None,
) -> T:
"""
Use all un-extruded wires in the parent chain to create a prismatic solid.
:param until: The distance to extrude, normal to the workplane plane. When a float is
passed, the extrusion extends this far and a negative value is in the opposite direction
to the normal of the plane. The string "next" extrudes until the next face orthogonal to
the wire normal. "last" extrudes to the last face. If a object of type Face is passed then
the extrusion will extend until this face. **Note that the Workplane must contain a Solid for extruding to a given face.**
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:param both: extrude in both directions symmetrically
:param taper: angle for optional tapered extrusion
:return: a CQ object with the resulting solid selected.
The returned object is always a CQ object, and depends on whether combine is True, and
whether a context solid is already defined:
* if combine is False, the new value is pushed onto the stack. Note that when extruding
until a specified face, combine can not be False
* if combine is true, the value is combined with the context solid if it exists,
and the resulting solid becomes the new context solid.
"""
# If subtractive mode is requested, use cutBlind
if combine in ("cut", "s"):
return self.cutBlind(until, clean, both, taper)
# Handle `until` multiple values
elif until in ("next", "last") and combine in (True, "a"):
if until == "next":
faceIndex = 0
elif until == "last":
faceIndex = -1
r = self._extrude(None, both=both, taper=taper, upToFace=faceIndex)
elif isinstance(until, Face) and combine:
r = self._extrude(None, both=both, taper=taper, upToFace=until)
elif isinstance(until, (int, float)):
r = self._extrude(until, both=both, taper=taper, upToFace=None)
elif isinstance(until, (str, Face)) and combine is False:
raise ValueError(
"`combine` can't be set to False when extruding until a face"
)
else:
raise ValueError(
f"Do not know how to handle until argument of type {type(until)}"
)
return self._combineWithBase(r, combine, clean)
def revolve(
self: T,
angleDegrees: float = 360.0,
axisStart: Optional[VectorLike] = None,
axisEnd: Optional[VectorLike] = None,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Use all un-revolved wires in the parent chain to create a solid.
:param angleDegrees: the angle to revolve through.
:type angleDegrees: float, anything less than 360 degrees will leave the shape open
:param axisStart: the start point of the axis of rotation
:param axisEnd: the end point of the axis of rotation
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:return: a CQ object with the resulting solid selected.
The returned object is always a CQ object, and depends on whether combine is True, and
whether a context solid is already defined:
* if combine is False, the new value is pushed onto the stack.
* if combine is true, the value is combined with the context solid if it exists,
and the resulting solid becomes the new context solid.
.. note::
Keep in mind that `axisStart` and `axisEnd` are defined relative to the current Workplane center position.
So if for example you want to revolve a circle centered at (10,0,0) around the Y axis, be sure to either :meth:`move` (or :meth:`moveTo`)
the current Workplane position or specify `axisStart` and `axisEnd` with the correct vector position.
In this example (0,0,0), (0,1,0) as axis coords would fail.
"""
# Make sure we account for users specifying angles larger than 360 degrees
angleDegrees %= 360.0
# Compensate for OCCT not assuming that a 0 degree revolve means a 360 degree revolve
angleDegrees = 360.0 if angleDegrees == 0 else angleDegrees
# The default start point of the vector defining the axis of rotation will be the origin
# of the workplane
if axisStart is None:
axisStart = self.plane.toWorldCoords((0, 0)).toTuple()
else:
axisStart = self.plane.toWorldCoords(axisStart).toTuple()
# The default end point of the vector defining the axis of rotation should be along the
# normal from the plane
if axisEnd is None:
# Make sure we match the user's assumed axis of rotation if they specified an start
# but not an end
if axisStart[1] != 0:
axisEnd = self.plane.toWorldCoords((0, axisStart[1])).toTuple()
else:
axisEnd = self.plane.toWorldCoords((0, 1)).toTuple()
else:
axisEnd = self.plane.toWorldCoords(axisEnd).toTuple()
# returns a Solid (or a compound if there were multiple)
r = self._revolve(angleDegrees, axisStart, axisEnd)
return self._combineWithBase(r, combine, clean)
def sweep(
self: T,
path: Union["Workplane", Wire, Edge],
multisection: bool = False,
sweepAlongWires: Optional[bool] = None,
makeSolid: bool = True,
isFrenet: bool = False,
combine: CombineMode = True,
clean: bool = True,
transition: Literal["right", "round", "transformed"] = "right",
normal: Optional[VectorLike] = None,
auxSpine: Optional["Workplane"] = None,
) -> T:
"""
Use all un-extruded wires in the parent chain to create a swept solid.
:param path: A wire along which the pending wires will be swept
:param multiSection: False to create multiple swept from wires on the chain along path.
True to create only one solid swept along path with shape following the list of wires on the chain
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:param transition: handling of profile orientation at C1 path discontinuities. Possible values are {'transformed','round', 'right'} (default: 'right').
:param normal: optional fixed normal for extrusion
:param auxSpine: a wire defining the binormal along the extrusion path
:return: a CQ object with the resulting solid selected.
"""
if not sweepAlongWires is None:
multisection = sweepAlongWires
from warnings import warn
warn(
"sweepAlongWires keyword argument is deprecated and will "
"be removed in the next version; use multisection instead",
DeprecationWarning,
)
r = self._sweep(
path.wire() if isinstance(path, Workplane) else path,
multisection,
makeSolid,
isFrenet,
transition,
normal,
auxSpine,
) # returns a Solid (or a compound if there were multiple)
return self._combineWithBase(r, combine, clean)
def _combineWithBase(
self: T,
obj: Union[Shape, Iterable[Shape]],
mode: CombineMode = True,
clean: bool = False,
) -> T:
"""
Combines the provided object with the base solid, if one can be found.
:param obj: The object to be combined with the context solid
:param mode: The mode to combine with the base solid (True, False, "cut", "a" or "s")
:return: a new object that represents the result of combining the base object with obj,
or obj if one could not be found
"""
if mode:
# since we are going to do something convert the iterable if needed
if not isinstance(obj, Shape):
obj = Compound.makeCompound(obj)
# dispatch on the mode
if mode in ("cut", "s"):
newS = self._cutFromBase(obj)
elif mode in (True, "a"):
newS = self._fuseWithBase(obj)
else:
# do not combine branch
newS = self.newObject(obj if not isinstance(obj, Shape) else [obj])
if clean:
# NB: not calling self.clean() to not pollute the parents
newS.objects = [
obj.clean() if isinstance(obj, Shape) else obj for obj in newS.objects
]
return newS
def _fuseWithBase(self: T, obj: Shape) -> T:
"""
Fuse the provided object with the base solid, if one can be found.
:param obj:
:return: a new object that represents the result of combining the base object with obj,
or obj if one could not be found
"""
baseSolid = self._findType(
(Solid, Compound), searchStack=True, searchParents=True
)
r = obj
if baseSolid is not None:
r = baseSolid.fuse(obj)
elif isinstance(obj, Compound):
r = obj.fuse()
return self.newObject([r])
def _cutFromBase(self: T, obj: Shape) -> T:
"""
Cuts the provided object from the base solid, if one can be found.
:param obj:
:return: a new object that represents the result of combining the base object with obj,
or obj if one could not be found
"""
baseSolid = self._findType((Solid, Compound), True, True)
r = obj
if baseSolid is not None:
r = baseSolid.cut(obj)
return self.newObject([r])
def combine(
self: T, clean: bool = True, glue: bool = False, tol: Optional[float] = None,
) -> T:
"""
Attempts to combine all of the items on the stack into a single item.
WARNING: all of the items must be of the same type!
:param clean: call :meth:`clean` afterwards to have a clean shape
:param glue: use a faster gluing mode for non-overlapping shapes (default False)
:param tol: tolerance value for fuzzy bool operation mode (default None)
:raises: ValueError if there are no items on the stack, or if they cannot be combined
:return: a CQ object with the resulting object selected
"""
items: List[Shape] = [o for o in self.objects if isinstance(o, Shape)]
s = items.pop(0)
if items:
s = s.fuse(*items, glue=glue, tol=tol)
if clean:
s = s.clean()
return self.newObject([s])
def union(
self: T,
toUnion: Optional[Union["Workplane", Solid, Compound]] = None,
clean: bool = True,
glue: bool = False,
tol: Optional[float] = None,
) -> T:
"""
Unions all of the items on the stack of toUnion with the current solid.
If there is no current solid, the items in toUnion are unioned together.
:param toUnion: a solid object, or a Workplane object having a solid
:param clean: call :meth:`clean` afterwards to have a clean shape (default True)
:param glue: use a faster gluing mode for non-overlapping shapes (default False)
:param tol: tolerance value for fuzzy bool operation mode (default None)
:raises: ValueError if there is no solid to add to in the chain
:return: a Workplane object with the resulting object selected
"""
# first collect all of the items together
newS: List[Shape]
if isinstance(toUnion, Workplane):
newS = cast(List[Shape], toUnion.solids().vals())
if len(newS) < 1:
raise ValueError(
"Workplane object must have at least one solid on the stack to union!"
)
self._mergeTags(toUnion)
elif isinstance(toUnion, (Solid, Compound)):
newS = [toUnion]
else:
raise ValueError("Cannot union type '{}'".format(type(toUnion)))
# now combine with existing solid, if there is one
# look for parents to cut from
solidRef = self._findType(
(Solid, Compound), searchStack=True, searchParents=True
)
if solidRef is not None:
r = solidRef.fuse(*newS, glue=glue, tol=tol)
elif len(newS) > 1:
r = newS.pop(0).fuse(*newS, glue=glue, tol=tol)
else:
r = newS[0]
if clean:
r = r.clean()
return self.newObject([r])
def __or__(self: T, toUnion: Union["Workplane", Solid, Compound]) -> T:
"""
Syntactic sugar for union.
Notice that :code:`r = a | b` is equivalent to :code:`r = a.union(b)` and :code:`r = a + b`.
Example::
Box = Workplane("XY").box(1, 1, 1, centered=(False, False, False))
Sphere = Workplane("XY").sphere(1)
result = Box | Sphere
"""
return self.union(toUnion)
def __add__(self: T, toUnion: Union["Workplane", Solid, Compound]) -> T:
"""
Syntactic sugar for union.
Notice that :code:`r = a + b` is equivalent to :code:`r = a.union(b)` and :code:`r = a | b`.
"""
return self.union(toUnion)
def cut(
self: T,
toCut: Union["Workplane", Solid, Compound],
clean: bool = True,
tol: Optional[float] = None,
) -> T:
"""
Cuts the provided solid from the current solid, IE, perform a solid subtraction.
:param toCut: a solid object, or a Workplane object having a solid
:param clean: call :meth:`clean` afterwards to have a clean shape
:param tol: tolerance value for fuzzy bool operation mode (default None)
:raises ValueError: if there is no solid to subtract from in the chain
:return: a Workplane object with the resulting object selected
"""
# look for parents to cut from
solidRef = self.findSolid(searchStack=True, searchParents=True)
solidToCut: Sequence[Shape]
if isinstance(toCut, Workplane):
solidToCut = _selectShapes(toCut.vals())
self._mergeTags(toCut)
elif isinstance(toCut, (Solid, Compound)):
solidToCut = (toCut,)
else:
raise ValueError("Cannot cut type '{}'".format(type(toCut)))
newS = solidRef.cut(*solidToCut, tol=tol)
if clean:
newS = newS.clean()
return self.newObject([newS])
def __sub__(self: T, toUnion: Union["Workplane", Solid, Compound]) -> T:
"""
Syntactic sugar for cut.
Notice that :code:`r = a - b` is equivalent to :code:`r = a.cut(b)`.
Example::
Box = Workplane("XY").box(1, 1, 1, centered=(False, False, False))
Sphere = Workplane("XY").sphere(1)
result = Box - Sphere
"""
return self.cut(toUnion)
def intersect(
self: T,
toIntersect: Union["Workplane", Solid, Compound],
clean: bool = True,
tol: Optional[float] = None,
) -> T:
"""
Intersects the provided solid from the current solid.
:param toIntersect: a solid object, or a Workplane object having a solid
:param clean: call :meth:`clean` afterwards to have a clean shape
:param tol: tolerance value for fuzzy bool operation mode (default None)
:raises ValueError: if there is no solid to intersect with in the chain
:return: a Workplane object with the resulting object selected
"""
# look for parents to intersect with
solidRef = self.findSolid(searchStack=True, searchParents=True)
solidToIntersect: Sequence[Shape]
if isinstance(toIntersect, Workplane):
solidToIntersect = _selectShapes(toIntersect.vals())
self._mergeTags(toIntersect)
elif isinstance(toIntersect, (Solid, Compound)):
solidToIntersect = (toIntersect,)
else:
raise ValueError("Cannot intersect type '{}'".format(type(toIntersect)))
newS = solidRef.intersect(*solidToIntersect, tol=tol)
if clean:
newS = newS.clean()
return self.newObject([newS])
def __and__(self: T, toUnion: Union["Workplane", Solid, Compound]) -> T:
"""
Syntactic sugar for intersect.
Notice that :code:`r = a & b` is equivalent to :code:`r = a.intersect(b)`.
Example::
Box = Workplane("XY").box(1, 1, 1, centered=(False, False, False))
Sphere = Workplane("XY").sphere(1)
result = Box & Sphere
"""
return self.intersect(toUnion)
def cutBlind(
self: T,
until: Union[float, Literal["next", "last"], Face],
clean: bool = True,
both: bool = False,
taper: Optional[float] = None,
) -> T:
"""
Use all un-extruded wires in the parent chain to create a prismatic cut from existing solid.
Specify either a distance value, or one of "next", "last" to indicate a face to cut to.
Similar to extrude, except that a solid in the parent chain is required to remove material
from. cutBlind always removes material from a part.
:param until: The distance to cut to, normal to the workplane plane. When a negative float
is passed the cut extends this far in the opposite direction to the normal of the plane
(i.e in the solid). The string "next" cuts until the next face orthogonal to the wire
normal. "last" cuts to the last face. If an object of type Face is passed, then the cut
will extend until this face.
:param clean: call :meth:`clean` afterwards to have a clean shape
:param both: cut in both directions symmetrically
:param taper: angle for optional tapered extrusion
:raises ValueError: if there is no solid to subtract from in the chain
:return: a CQ object with the resulting object selected
see :meth:`cutThruAll` to cut material from the entire part
"""
# Handling of `until` passed values
s: Union[Compound, Solid, Shape]
if isinstance(both, float) and taper == None:
# Because inserting a new parameter "both" in front of "taper",
# existing code calling this function with position arguments will
# pass the taper argument (float) to the "both" argument. This
# warning is to catch that.
from warnings import warn
warn(
"cutBlind added a new keyword argument `both=True`. "
"The signature is changed from "
"(until, clean, taper) -> (until, clean, both, taper)",
DeprecationWarning,
)
# assign 3rd argument value to taper
taper = both
both = False
if isinstance(until, str) and until in ("next", "last"):
if until == "next":
faceIndex = 0
elif until == "last":
faceIndex = -1
s = self._extrude(
None, both=both, taper=taper, upToFace=faceIndex, additive=False
)
elif isinstance(until, Face):
s = self._extrude(
None, both=both, taper=taper, upToFace=until, additive=False
)
elif isinstance(until, (int, float)):
toCut = self._extrude(
until, both=both, taper=taper, upToFace=None, additive=False
)
solidRef = self.findSolid()
s = solidRef.cut(toCut)
else:
raise ValueError(
f"Do not know how to handle until argument of type {type(until)}"
)
if clean:
s = s.clean()
return self.newObject([s])
def cutThruAll(self: T, clean: bool = True, taper: float = 0) -> T:
"""
Use all un-extruded wires in the parent chain to create a prismatic cut from existing solid.
Cuts through all material in both normal directions of workplane.
Similar to extrude, except that a solid in the parent chain is required to remove material
from. cutThruAll always removes material from a part.
:param clean: call :meth:`clean` afterwards to have a clean shape
:raises ValueError: if there is no solid to subtract from in the chain
:raises ValueError: if there are no pending wires to cut with
:return: a CQ object with the resulting object selected
see :meth:`cutBlind` to cut material to a limited depth
"""
solidRef = self.findSolid()
s = solidRef.dprism(
None, self._getFaces(), thruAll=True, additive=False, taper=-taper
)
if clean:
s = s.clean()
return self.newObject([s])
def loft(
self: T, ruled: bool = False, combine: CombineMode = True, clean: bool = True
) -> T:
"""
Make a lofted solid, through the set of wires.
:param ruled: When set to `True` connects each section linearly and without continuity
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:return: a Workplane object containing the created loft
"""
if self.ctx.pendingWires:
wiresToLoft = self.ctx.popPendingWires()
else:
wiresToLoft = [f.outerWire() for f in self._getFaces()]
if not wiresToLoft:
raise ValueError("Nothing to loft")
r: Shape = Solid.makeLoft(wiresToLoft, ruled)
newS = self._combineWithBase(r, combine, clean)
return newS
def _getFaces(self) -> List[Face]:
"""
Convert pending wires or sketches to faces for subsequent operation
"""
rv: List[Face] = []
for el in self.objects:
if isinstance(el, Sketch):
rv.extend(el)
if not rv:
rv.extend(wiresToFaces(self.ctx.popPendingWires()))
return rv
def _extrude(
self,
distance: Optional[float] = None,
both: bool = False,
taper: Optional[float] = None,
upToFace: Optional[Union[int, Face]] = None,
additive: bool = True,
) -> Union[Solid, Compound]:
"""
Make a prismatic solid from the existing set of pending wires.
:param distance: distance to extrude
:param both: extrude in both directions symmetrically
:param upToFace: if specified, extrude up to a face: 0 for the next, -1 for the last face
:param additive: specify if extruding or cutting, required param for uptoface algorithm
:return: OCCT solid(s), suitable for boolean operations.
This method is a utility method, primarily for plugin and internal use.
It is the basis for cutBlind, extrude, cutThruAll, and all similar methods.
"""
def getFacesList(face, eDir, direction, both=False):
"""
Utility function to make the code further below more clean and tidy
Performs some test and raise appropriate error when no Faces are found for extrusion
"""
facesList = self.findSolid().facesIntersectedByLine(
face.Center(), eDir, direction=direction
)
if len(facesList) == 0 and both:
raise ValueError(
"Couldn't find a face to extrude/cut to for at least one of the two required directions of extrusion/cut."
)
if len(facesList) == 0:
# if we don't find faces in the workplane normal direction we try the other
# direction (as the user might have created a workplane with wrong orientation)
facesList = self.findSolid().facesIntersectedByLine(
face.Center(), eDir.multiply(-1.0), direction=direction
)
if len(facesList) == 0:
raise ValueError(
"Couldn't find a face to extrude/cut to. Check your workplane orientation."
)
return facesList
# process sketches or pending wires
faces = self._getFaces()
# check for nested geometry and tapered extrusion
for face in faces:
if taper and face.innerWires():
raise ValueError("Inner wires not allowed with tapered extrusion")
# compute extrusion vector and extrude
if upToFace is not None:
eDir = self.plane.zDir
elif distance is not None:
eDir = self.plane.zDir.multiply(distance)
direction = "AlongAxis" if additive else "Opposite"
taper = 0.0 if taper is None else taper
if upToFace is not None:
res = self.findSolid()
for face in faces:
if isinstance(upToFace, int):
facesList = getFacesList(face, eDir, direction, both=both)
if (
res.isInside(face.outerWire().Center())
and additive
and upToFace == 0
):
upToFace = 1 # extrude until next face outside the solid
limitFace = facesList[upToFace]
else:
limitFace = upToFace
res = res.dprism(
None, [face], taper=taper, upToFace=limitFace, additive=additive,
)
if both:
facesList2 = getFacesList(
face, eDir.multiply(-1.0), direction, both=both
)
limitFace2 = facesList2[upToFace]
res = res.dprism(
None,
[face],
taper=taper,
upToFace=limitFace2,
additive=additive,
)
else:
toFuse = []
for face in faces:
s1 = Solid.extrudeLinear(face, eDir, taper=taper)
if both:
s2 = Solid.extrudeLinear(face, eDir.multiply(-1.0), taper=taper)
toFuse.append(s1.fuse(s2, glue=True))
else:
toFuse.append(s1)
res = Compound.makeCompound(toFuse)
return res
def _revolve(
self, angleDegrees: float, axisStart: VectorLike, axisEnd: VectorLike
) -> Compound:
"""
Make a solid from the existing set of pending wires.
:param angleDegrees: the angle to revolve through.
:type angleDegrees: float, anything less than 360 degrees will leave the shape open
:param axisStart: the start point of the axis of rotation
:param axisEnd: the end point of the axis of rotation
:return: a OCCT solid(s), suitable for boolean operations.
This method is a utility method, primarily for plugin and internal use.
"""
# Revolve, make a compound out of them and then fuse them
toFuse = []
for f in self._getFaces():
thisObj = Solid.revolve(f, angleDegrees, Vector(axisStart), Vector(axisEnd))
toFuse.append(thisObj)
return Compound.makeCompound(toFuse)
def _sweep(
self,
path: Union["Workplane", Wire, Edge],
multisection: bool = False,
makeSolid: bool = True,
isFrenet: bool = False,
transition: Literal["right", "round", "transformed"] = "right",
normal: Optional[VectorLike] = None,
auxSpine: Optional["Workplane"] = None,
) -> Compound:
"""
Makes a swept solid from an existing set of pending wires.
:param path: A wire along which the pending wires will be swept
:param multisection:
False to create multiple swept from wires on the chain along path
True to create only one solid swept along path with shape following the list of wires on the chain
:param transition:
handling of profile orientation at C1 path discontinuities.
Possible values are {'transformed','round', 'right'} (default: 'right').
:param normal: optional fixed normal for extrusion
:param auxSpine: a wire defining the binormal along the extrusion path
:return: a solid, suitable for boolean operations
"""
toFuse = []
p = path.val() if isinstance(path, Workplane) else path
if not isinstance(p, (Wire, Edge)):
raise ValueError("Wire or Edge instance required")
mode: Union[Vector, Edge, Wire, None] = None
if normal:
mode = Vector(normal)
elif auxSpine:
wire = auxSpine.val()
if not isinstance(wire, (Edge, Wire)):
raise ValueError("Wire or Edge instance required")
mode = wire
if not multisection:
for f in self._getFaces():
thisObj = Solid.sweep(f, p, makeSolid, isFrenet, mode, transition)
toFuse.append(thisObj)
else:
sections = self.ctx.popPendingWires()
thisObj = Solid.sweep_multi(sections, p, makeSolid, isFrenet, mode)
toFuse.append(thisObj)
return Compound.makeCompound(toFuse)
def interpPlate(
self: T,
surf_edges: Union[
Sequence[VectorLike], Sequence[Union[Edge, Wire]], "Workplane"
],
surf_pts: Sequence[VectorLike] = [],
thickness: float = 0,
combine: CombineMode = False,
clean: bool = True,
degree: int = 3,
nbPtsOnCur: int = 15,
nbIter: int = 2,
anisotropy: bool = False,
tol2d: float = 0.00001,
tol3d: float = 0.0001,
tolAng: float = 0.01,
tolCurv: float = 0.1,
maxDeg: int = 8,
maxSegments: int = 9,
) -> T:
"""
Returns a plate surface that is 'thickness' thick, enclosed by 'surf_edge_pts' points, and going
through 'surf_pts' points. Using pushPoints directly with interpPlate and combine=True, can be
very resource intensive depending on the complexity of the shape. In this case set combine=False.
:param surf_edges: list of [x,y,z] ordered coordinates or list of ordered or unordered edges, wires
:param surf_pts: list of points (uses only edges if [])
:param thickness: value may be negative or positive depending on thickening direction (2D surface if 0)
:param combine: should the results be combined with other solids on the stack (and each other)?
:param clean: call :meth:`clean` afterwards to have a clean shape
:param degree: >= 2
:param nbPtsOnCur: number of points on curve >= 15
:param nbIter: number of iterations >= 2
:param anisotropy: = bool Anisotropy
:param tol2d: 2D tolerance
:param tol3d: 3D tolerance
:param tolAng: angular tolerance
:param tolCurv: tolerance for curvature
:param maxDeg: highest polynomial degree >= 2
:param maxSegments: greatest number of segments >= 2
"""
# convert points to edges if needed
edges: List[Union[Edge, Wire]] = []
points = []
if isinstance(surf_edges, Workplane):
edges.extend(cast(Edge, el) for el in surf_edges.edges().objects)
else:
for el in surf_edges:
if isinstance(el, (Edge, Wire)):
edges.append(el)
else:
points.append(el)
# Creates interpolated plate
f: Face = Face.makeNSidedSurface(
edges if not points else [Wire.makePolygon(points, False, True)],
surf_pts,
degree=degree,
nbPtsOnCur=nbPtsOnCur,
nbIter=nbIter,
anisotropy=anisotropy,
tol2d=tol2d,
tol3d=tol3d,
tolAng=tolAng,
tolCurv=tolCurv,
maxDeg=maxDeg,
maxSegments=maxSegments,
)
# thicken if needed
s = f.thicken(thickness) if thickness > 0 else f
return self.eachpoint(lambda loc: s.moved(loc), True, combine, clean)
def box(
self: T,
length: float,
width: float,
height: float,
centered: Union[bool, Tuple[bool, bool, bool]] = True,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Return a 3d box with specified dimensions for each object on the stack.
:param length: box size in X direction
:param width: box size in Y direction
:param height: box size in Z direction
:param centered: If True, the box will be centered around the reference point.
If False, the corner of the box will be on the reference point and it will
extend in the positive x, y and z directions. Can also use a 3-tuple to
specify centering along each axis.
:param combine: should the results be combined with other solids on the stack
(and each other)?
:param clean: call :meth:`clean` afterwards to have a clean shape
One box is created for each item on the current stack. If no items are on the stack, one box
using the current workplane center is created.
If combine is true, the result will be a single object on the stack. If a solid was found
in the chain, the result is that solid with all boxes produced fused onto it otherwise, the
result is the combination of all the produced boxes.
If combine is false, the result will be a list of the boxes produced.
Most often boxes form the basis for a part::
# make a single box with lower left corner at origin
s = Workplane().box(1, 2, 3, centered=False)
But sometimes it is useful to create an array of them::
# create 4 small square bumps on a larger base plate:
s = (
Workplane()
.box(4, 4, 0.5)
.faces(">Z")
.workplane()
.rect(3, 3, forConstruction=True)
.vertices()
.box(0.25, 0.25, 0.25, combine=True)
)
"""
if isinstance(centered, bool):
centered = (centered, centered, centered)
offset = Vector()
if centered[0]:
offset += Vector(-length / 2, 0, 0)
if centered[1]:
offset += Vector(0, -width / 2, 0)
if centered[2]:
offset += Vector(0, 0, -height / 2)
box = Solid.makeBox(length, width, height, offset)
return self.eachpoint(lambda loc: box.moved(loc), True, combine, clean)
def sphere(
self: T,
radius: float,
direct: VectorLike = (0, 0, 1),
angle1: float = -90,
angle2: float = 90,
angle3: float = 360,
centered: Union[bool, Tuple[bool, bool, bool]] = True,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Returns a 3D sphere with the specified radius for each point on the stack.
:param radius: The radius of the sphere
:param direct: The direction axis for the creation of the sphere
:type direct: A three-tuple
:param angle1: The first angle to sweep the sphere arc through
:type angle1: float > 0
:param angle2: The second angle to sweep the sphere arc through
:type angle2: float > 0
:param angle3: The third angle to sweep the sphere arc through
:type angle3: float > 0
:param centered: If True, the sphere will be centered around the reference point. If False,
the corner of a bounding box around the sphere will be on the reference point and it
will extend in the positive x, y and z directions. Can also use a 3-tuple to specify
centering along each axis.
:param combine: Whether the results should be combined with other solids on the stack
(and each other)
:type combine: true to combine shapes, false otherwise
:param clean: call :meth:`clean` afterwards to have a clean shape
:return: A sphere object for each point on the stack
One sphere is created for each item on the current stack. If no items are on the stack, one
box using the current workplane center is created.
If combine is true, the result will be a single object on the stack. If a solid was found
in the chain, the result is that solid with all spheres produced fused onto it otherwise,
the result is the combination of all the produced spheres.
If combine is false, the result will be a list of the spheres produced.
"""
# Convert the direction tuple to a vector, if needed
if isinstance(direct, tuple):
direct = Vector(direct)
if isinstance(centered, bool):
centered = (centered, centered, centered)
offset = Vector()
if not centered[0]:
offset += Vector(radius, 0, 0)
if not centered[1]:
offset += Vector(0, radius, 0)
if not centered[2]:
offset += Vector(0, 0, radius)
s = Solid.makeSphere(radius, offset, direct, angle1, angle2, angle3)
# We want a sphere for each point on the workplane
return self.eachpoint(lambda loc: s.moved(loc), True, combine, clean)
def cylinder(
self: T,
height: float,
radius: float,
direct: Vector = Vector(0, 0, 1),
angle: float = 360,
centered: Union[bool, Tuple[bool, bool, bool]] = True,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Returns a cylinder with the specified radius and height for each point on the stack
:param height: The height of the cylinder
:param radius: The radius of the cylinder
:param direct: The direction axis for the creation of the cylinder
:type direct: A three-tuple
:param angle: The angle to sweep the cylinder arc through
:type angle: float > 0
:param centered: If True, the cylinder will be centered around the reference point. If False,
the corner of a bounding box around the cylinder will be on the reference point and it
will extend in the positive x, y and z directions. Can also use a 3-tuple to specify
centering along each axis.
:param combine: Whether the results should be combined with other solids on the stack
(and each other)
:type combine: true to combine shapes, false otherwise
:param clean: call :meth:`clean` afterwards to have a clean shape
:return: A cylinder object for each point on the stack
One cylinder is created for each item on the current stack. If no items are on the stack, one
cylinder is created using the current workplane center.
If combine is true, the result will be a single object on the stack. If a solid was found
in the chain, the result is that solid with all cylinders produced fused onto it otherwise,
the result is the combination of all the produced cylinders.
If combine is false, the result will be a list of the cylinders produced.
"""
if isinstance(centered, bool):
centered = (centered, centered, centered)
offset = Vector()
if not centered[0]:
offset += Vector(radius, 0, 0)
if not centered[1]:
offset += Vector(0, radius, 0)
if centered[2]:
offset += Vector(0, 0, -height / 2)
s = Solid.makeCylinder(radius, height, offset, direct, angle)
# We want a cylinder for each point on the workplane
return self.eachpoint(lambda loc: s.moved(loc), True, combine, clean)
def wedge(
self: T,
dx: float,
dy: float,
dz: float,
xmin: float,
zmin: float,
xmax: float,
zmax: float,
pnt: VectorLike = Vector(0, 0, 0),
dir: VectorLike = Vector(0, 0, 1),
centered: Union[bool, Tuple[bool, bool, bool]] = True,
combine: CombineMode = True,
clean: bool = True,
) -> T:
"""
Returns a 3D wedge with the specified dimensions for each point on the stack.
:param dx: Distance along the X axis
:param dy: Distance along the Y axis
:param dz: Distance along the Z axis
:param xmin: The minimum X location
:param zmin: The minimum Z location
:param xmax: The maximum X location
:param zmax: The maximum Z location
:param pnt: A vector (or tuple) for the origin of the direction for the wedge
:param dir: The direction vector (or tuple) for the major axis of the wedge
:param centered: If True, the wedge will be centered around the reference point.
If False, the corner of the wedge will be on the reference point and it will
extend in the positive x, y and z directions. Can also use a 3-tuple to
specify centering along each axis.
:param combine: Whether the results should be combined with other solids on the stack
(and each other)
:param clean: True to attempt to have the kernel clean up the geometry, False otherwise
:return: A wedge object for each point on the stack
One wedge is created for each item on the current stack. If no items are on the stack, one
wedge using the current workplane center is created.
If combine is True, the result will be a single object on the stack. If a solid was found
in the chain, the result is that solid with all wedges produced fused onto it otherwise,
the result is the combination of all the produced wedges.
If combine is False, the result will be a list of the wedges produced.
"""
# Convert the point tuple to a vector, if needed
if isinstance(pnt, tuple):
pnt = Vector(pnt)
# Convert the direction tuple to a vector, if needed
if isinstance(dir, tuple):
dir = Vector(dir)
if isinstance(centered, bool):
centered = (centered, centered, centered)
offset = Vector()
if centered[0]:
offset += Vector(-dx / 2, 0, 0)
if centered[1]:
offset += Vector(0, -dy / 2, 0)
if centered[2]:
offset += Vector(0, 0, -dz / 2)
w = Solid.makeWedge(dx, dy, dz, xmin, zmin, xmax, zmax, offset, dir)
# We want a wedge for each point on the workplane
return self.eachpoint(lambda loc: w.moved(loc), True, combine, clean)
def clean(self: T) -> T:
"""
Cleans the current solid by removing unwanted edges from the
faces.
Normally you don't have to call this function. It is
automatically called after each related operation. You can
disable this behavior with `clean=False` parameter if method
has any. In some cases this can improve performance
drastically but is generally dis-advised since it may break
some operations such as fillet.
Note that in some cases where lots of solid operations are
chained, `clean()` may actually improve performance since
the shape is 'simplified' at each step and thus next operation
is easier.
Also note that, due to limitation of the underlying engine,
`clean` may fail to produce a clean output in some cases such as
spherical faces.
"""
cleanObjects = [
obj.clean() if isinstance(obj, Shape) else obj for obj in self.objects
]
return self.newObject(cleanObjects)
@deprecate_kwarg_name("cut", "combine='cut'")
def text(
self: T,
txt: str,
fontsize: float,
distance: float,
cut: bool = True,
combine: CombineMode = False,
clean: bool = True,
font: str = "Arial",
fontPath: Optional[str] = None,
kind: Literal["regular", "bold", "italic"] = "regular",
halign: Literal["center", "left", "right"] = "center",
valign: Literal["center", "top", "bottom"] = "center",
) -> T:
"""
Returns a 3D text.
:param txt: text to be rendered
:param fontsize: size of the font in model units
:param distance: the distance to extrude or cut, normal to the workplane plane
:type distance: float, negative means opposite the normal direction
:param cut: True to cut the resulting solid from the parent solids if found
:param combine: True or "a" to combine the resulting solid with parent solids if found,
"cut" or "s" to remove the resulting solid from the parent solids if found.
False to keep the resulting solid separated from the parent solids.
:param clean: call :meth:`clean` afterwards to have a clean shape
:param font: font name
:param fontPath: path to font file
:param kind: font type
:param halign: horizontal alignment
:param valign: vertical alignment
:return: a CQ object with the resulting solid selected
The returned object is always a Workplane object, and depends on whether combine is True, and
whether a context solid is already defined:
* if combine is False, the new value is pushed onto the stack.
* if combine is true, the value is combined with the context solid if it exists,
and the resulting solid becomes the new context solid.
Examples::
cq.Workplane().text("CadQuery", 5, 1)
Specify the font (name), and kind to use an installed system font::
cq.Workplane().text("CadQuery", 5, 1, font="Liberation Sans Narrow", kind="italic")
Specify fontPath to use a font from a given file::
cq.Workplane().text("CadQuery", 5, 1, fontPath="/opt/fonts/texgyrecursor-bold.otf")
Cutting text into a solid::
cq.Workplane().box(8, 8, 8).faces(">Z").workplane().text("Z", 5, -1.0)
"""
r = Compound.makeText(
txt,
fontsize,
distance,
font=font,
fontPath=fontPath,
kind=kind,
halign=halign,
valign=valign,
position=self.plane,
)
if cut:
combine = "cut"
return self._combineWithBase(r, combine, clean)
def section(self: T, height: float = 0.0) -> T:
"""
Slices current solid at the given height.
:param height: height to slice at (default: 0)
:raises ValueError: if no solids or compounds are found
:return: a CQ object with the resulting face(s).
"""
solidRef = self.findSolid(searchStack=True, searchParents=True)
plane = Face.makePlane(
basePnt=self.plane.origin + self.plane.zDir * height, dir=self.plane.zDir
)
r = solidRef.intersect(plane)
return self.newObject([r])
def toPending(self: T) -> T:
"""
Adds wires/edges to pendingWires/pendingEdges.
:return: same CQ object with updated context.
"""
self.ctx.pendingWires.extend(el for el in self.objects if isinstance(el, Wire))
self.ctx.pendingEdges.extend(el for el in self.objects if isinstance(el, Edge))
return self
def offset2D(
self: T,
d: float,
kind: Literal["arc", "intersection", "tangent"] = "arc",
forConstruction: bool = False,
) -> T:
"""
Creates a 2D offset wire.
:param d: thickness. Negative thickness denotes offset to inside.
:param kind: offset kind. Use "arc" for rounded and "intersection" for sharp edges (default: "arc")
:param forConstruction: Should the result be added to pending wires?
:return: CQ object with resulting wire(s).
"""
ws = self._consolidateWires()
rv = list(chain.from_iterable(w.offset2D(d, kind) for w in ws))
self.ctx.pendingEdges = []
if forConstruction:
for wire in rv:
wire.forConstruction = True
self.ctx.pendingWires = []
else:
self.ctx.pendingWires = rv
return self.newObject(rv)
def _locs(self: T) -> List[Location]:
"""
Convert items on the stack into locations.
"""
plane = self.plane
locs: List[Location] = []
for obj in self.objects:
if isinstance(obj, (Vector, Shape)):
locs.append(Location(plane, obj.Center()))
elif isinstance(obj, Location):
locs.append(obj)
if not locs:
locs.append(self.plane.location)
return locs
def sketch(self: T) -> Sketch:
"""
Initialize and return a sketch
:return: Sketch object with the current workplane as a parent.
"""
parent = self.newObject([])
rv = Sketch(parent=parent, locs=self._locs())
parent.objects.append(rv)
return rv
def placeSketch(self: T, *sketches: Sketch) -> T:
"""
Place the provided sketch(es) based on the current items on the stack.
:return: Workplane object with the sketch added.
"""
rv = []
for s in sketches:
s_new = s.copy()
s_new.locs = self._locs()
rv.append(s_new)
return self.newObject(rv)
def _repr_javascript_(self) -> Any:
"""
Special method for rendering current object in a jupyter notebook
"""
if type(self.val()) is Vector:
return "< {} >".format(self.__repr__()[1:-1])
else:
return Compound.makeCompound(
_selectShapes(self.objects)
)._repr_javascript_()
# alias for backward compatibility
CQ = Workplane
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,538 | CadQuery/cadquery | refs/heads/master | /tests/test_cad_objects.py | # system modules
import math
import pytest
import unittest
from tests import BaseTest
from OCP.gp import gp_Vec, gp_Pnt, gp_Ax2, gp_Circ, gp_Elips, gp, gp_XYZ, gp_Trsf
from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeEdge
from cadquery import *
DEG2RAD = math.pi / 180
RAD2DEG = 180 / math.pi
class TestCadObjects(BaseTest):
def _make_circle(self):
circle = gp_Circ(gp_Ax2(gp_Pnt(1, 2, 3), gp.DZ_s()), 2.0)
return Shape.cast(BRepBuilderAPI_MakeEdge(circle).Edge())
def _make_ellipse(self):
ellipse = gp_Elips(gp_Ax2(gp_Pnt(1, 2, 3), gp.DZ_s()), 4.0, 2.0)
return Shape.cast(BRepBuilderAPI_MakeEdge(ellipse).Edge())
def testVectorConstructors(self):
v1 = Vector(1, 2, 3)
v2 = Vector((1, 2, 3))
v3 = Vector(gp_Vec(1, 2, 3))
v4 = Vector([1, 2, 3])
v5 = Vector(gp_XYZ(1, 2, 3))
for v in [v1, v2, v3, v4, v5]:
self.assertTupleAlmostEquals((1, 2, 3), v.toTuple(), 4)
v6 = Vector((1, 2))
v7 = Vector([1, 2])
v8 = Vector(1, 2)
for v in [v6, v7, v8]:
self.assertTupleAlmostEquals((1, 2, 0), v.toTuple(), 4)
v9 = Vector()
self.assertTupleAlmostEquals((0, 0, 0), v9.toTuple(), 4)
v9.x = 1.0
v9.y = 2.0
v9.z = 3.0
self.assertTupleAlmostEquals((1, 2, 3), (v9.x, v9.y, v9.z), 4)
with self.assertRaises(TypeError):
Vector("vector")
with self.assertRaises(TypeError):
Vector(1, 2, 3, 4)
def testVertex(self):
"""
Tests basic vertex functions
"""
v = Vertex.makeVertex(1, 1, 1)
self.assertEqual(1, v.X)
self.assertEqual(Vector, type(v.Center()))
def testBasicBoundingBox(self):
v = Vertex.makeVertex(1, 1, 1)
v2 = Vertex.makeVertex(2, 2, 2)
self.assertEqual(BoundBox, type(v.BoundingBox()))
self.assertEqual(BoundBox, type(v2.BoundingBox()))
bb1 = v.BoundingBox().add(v2.BoundingBox())
# OCC uses some approximations
self.assertAlmostEqual(bb1.xlen, 1.0, 1)
# Test adding to an existing bounding box
v0 = Vertex.makeVertex(0, 0, 0)
bb2 = v0.BoundingBox().add(v.BoundingBox())
bb3 = bb1.add(bb2)
self.assertTupleAlmostEquals((2, 2, 2), (bb3.xlen, bb3.ylen, bb3.zlen), 7)
bb3 = bb2.add((3, 3, 3))
self.assertTupleAlmostEquals((3, 3, 3), (bb3.xlen, bb3.ylen, bb3.zlen), 7)
bb3 = bb2.add(Vector(3, 3, 3))
self.assertTupleAlmostEquals((3, 3, 3), (bb3.xlen, bb3.ylen, bb3.zlen), 7)
# Test 2D bounding boxes
bb1 = (
Vertex.makeVertex(1, 1, 0)
.BoundingBox()
.add(Vertex.makeVertex(2, 2, 0).BoundingBox())
)
bb2 = (
Vertex.makeVertex(0, 0, 0)
.BoundingBox()
.add(Vertex.makeVertex(3, 3, 0).BoundingBox())
)
bb3 = (
Vertex.makeVertex(0, 0, 0)
.BoundingBox()
.add(Vertex.makeVertex(1.5, 1.5, 0).BoundingBox())
)
# Test that bb2 contains bb1
self.assertEqual(bb2, BoundBox.findOutsideBox2D(bb1, bb2))
self.assertEqual(bb2, BoundBox.findOutsideBox2D(bb2, bb1))
# Test that neither bounding box contains the other
self.assertIsNone(BoundBox.findOutsideBox2D(bb1, bb3))
# Test creation of a bounding box from a shape - note the low accuracy comparison
# as the box is a little larger than the shape
bb1 = BoundBox._fromTopoDS(Solid.makeCylinder(1, 1).wrapped, optimal=False)
self.assertTupleAlmostEquals((2, 2, 1), (bb1.xlen, bb1.ylen, bb1.zlen), 1)
def testEdgeWrapperCenter(self):
e = self._make_circle()
self.assertTupleAlmostEquals((1.0, 2.0, 3.0), e.Center().toTuple(), 3)
def testEdgeWrapperEllipseCenter(self):
e = self._make_ellipse()
w = Wire.assembleEdges([e])
self.assertTupleAlmostEquals(
(1.0, 2.0, 3.0), Face.makeFromWires(w).Center().toTuple(), 3
)
def testEdgeWrapperMakeCircle(self):
halfCircleEdge = Edge.makeCircle(
radius=10, pnt=(0, 0, 0), dir=(0, 0, 1), angle1=0, angle2=180
)
# self.assertTupleAlmostEquals((0.0, 5.0, 0.0), halfCircleEdge.CenterOfBoundBox(0.0001).toTuple(),3)
self.assertTupleAlmostEquals(
(10.0, 0.0, 0.0), halfCircleEdge.startPoint().toTuple(), 3
)
self.assertTupleAlmostEquals(
(-10.0, 0.0, 0.0), halfCircleEdge.endPoint().toTuple(), 3
)
def testEdgeWrapperMakeTangentArc(self):
tangent_arc = Edge.makeTangentArc(
Vector(1, 1), # starts at 1, 1
Vector(0, 1), # tangent at start of arc is in the +y direction
Vector(2, 1), # arc curves 180 degrees and ends at 2, 1
)
self.assertTupleAlmostEquals((1, 1, 0), tangent_arc.startPoint().toTuple(), 3)
self.assertTupleAlmostEquals((2, 1, 0), tangent_arc.endPoint().toTuple(), 3)
self.assertTupleAlmostEquals(
(0, 1, 0), tangent_arc.tangentAt(locationParam=0).toTuple(), 3
)
self.assertTupleAlmostEquals(
(1, 0, 0), tangent_arc.tangentAt(locationParam=0.5).toTuple(), 3
)
self.assertTupleAlmostEquals(
(0, -1, 0), tangent_arc.tangentAt(locationParam=1).toTuple(), 3
)
def testEdgeWrapperMakeEllipse1(self):
# Check x_radius > y_radius
x_radius, y_radius = 20, 10
angle1, angle2 = -75.0, 90.0
arcEllipseEdge = Edge.makeEllipse(
x_radius=x_radius,
y_radius=y_radius,
pnt=(0, 0, 0),
dir=(0, 0, 1),
angle1=angle1,
angle2=angle2,
)
start = (
x_radius * math.cos(angle1 * DEG2RAD),
y_radius * math.sin(angle1 * DEG2RAD),
0.0,
)
end = (
x_radius * math.cos(angle2 * DEG2RAD),
y_radius * math.sin(angle2 * DEG2RAD),
0.0,
)
self.assertTupleAlmostEquals(start, arcEllipseEdge.startPoint().toTuple(), 3)
self.assertTupleAlmostEquals(end, arcEllipseEdge.endPoint().toTuple(), 3)
def testEdgeWrapperMakeEllipse2(self):
# Check x_radius < y_radius
x_radius, y_radius = 10, 20
angle1, angle2 = 0.0, 45.0
arcEllipseEdge = Edge.makeEllipse(
x_radius=x_radius,
y_radius=y_radius,
pnt=(0, 0, 0),
dir=(0, 0, 1),
angle1=angle1,
angle2=angle2,
)
start = (
x_radius * math.cos(angle1 * DEG2RAD),
y_radius * math.sin(angle1 * DEG2RAD),
0.0,
)
end = (
x_radius * math.cos(angle2 * DEG2RAD),
y_radius * math.sin(angle2 * DEG2RAD),
0.0,
)
self.assertTupleAlmostEquals(start, arcEllipseEdge.startPoint().toTuple(), 3)
self.assertTupleAlmostEquals(end, arcEllipseEdge.endPoint().toTuple(), 3)
def testEdgeWrapperMakeCircleWithEllipse(self):
# Check x_radius == y_radius
x_radius, y_radius = 20, 20
angle1, angle2 = 15.0, 60.0
arcEllipseEdge = Edge.makeEllipse(
x_radius=x_radius,
y_radius=y_radius,
pnt=(0, 0, 0),
dir=(0, 0, 1),
angle1=angle1,
angle2=angle2,
)
start = (
x_radius * math.cos(angle1 * DEG2RAD),
y_radius * math.sin(angle1 * DEG2RAD),
0.0,
)
end = (
x_radius * math.cos(angle2 * DEG2RAD),
y_radius * math.sin(angle2 * DEG2RAD),
0.0,
)
self.assertTupleAlmostEquals(start, arcEllipseEdge.startPoint().toTuple(), 3)
self.assertTupleAlmostEquals(end, arcEllipseEdge.endPoint().toTuple(), 3)
def testFaceWrapperMakePlane(self):
mplane = Face.makePlane(10, 10)
self.assertTupleAlmostEquals((0.0, 0.0, 1.0), mplane.normalAt().toTuple(), 3)
def testCenterOfBoundBox(self):
pass
def testCombinedCenterOfBoundBox(self):
pass
def testCompoundCenter(self):
"""
Tests whether or not a proper weighted center can be found for a compound
"""
def cylinders(self, radius, height):
c = Solid.makeCylinder(radius, height, Vector())
# Combine all the cylinders into a single compound
r = self.eachpoint(lambda loc: c.located(loc), True).combineSolids()
return r
Workplane.cyl = cylinders
# Now test. here we want weird workplane to see if the objects are transformed right
s = (
Workplane("XY")
.rect(2.0, 3.0, forConstruction=True)
.vertices()
.cyl(0.25, 0.5)
)
self.assertEqual(4, len(s.val().Solids()))
self.assertTupleAlmostEquals((0.0, 0.0, 0.25), s.val().Center().toTuple(), 3)
def testDot(self):
v1 = Vector(2, 2, 2)
v2 = Vector(1, -1, 1)
self.assertEqual(2.0, v1.dot(v2))
def testVectorAdd(self):
result = Vector(1, 2, 0) + Vector(0, 0, 3)
self.assertTupleAlmostEquals((1.0, 2.0, 3.0), result.toTuple(), 3)
def testVectorOperators(self):
result = Vector(1, 1, 1) + Vector(2, 2, 2)
self.assertEqual(Vector(3, 3, 3), result)
result = Vector(1, 2, 3) - Vector(3, 2, 1)
self.assertEqual(Vector(-2, 0, 2), result)
result = Vector(1, 2, 3) * 2
self.assertEqual(Vector(2, 4, 6), result)
result = 3 * Vector(1, 2, 3)
self.assertEqual(Vector(3, 6, 9), result)
result = Vector(2, 4, 6) / 2
self.assertEqual(Vector(1, 2, 3), result)
self.assertEqual(Vector(-1, -1, -1), -Vector(1, 1, 1))
self.assertEqual(0, abs(Vector(0, 0, 0)))
self.assertEqual(1, abs(Vector(1, 0, 0)))
self.assertEqual((1 + 4 + 9) ** 0.5, abs(Vector(1, 2, 3)))
def testVectorEquals(self):
a = Vector(1, 2, 3)
b = Vector(1, 2, 3)
c = Vector(1, 2, 3.000001)
self.assertEqual(a, b)
self.assertEqual(a, c)
def testVectorProject(self):
"""
Test line projection and plane projection methods of cq.Vector
"""
decimal_places = 9
normal = Vector(1, 2, 3)
base = Vector(5, 7, 9)
x_dir = Vector(1, 0, 0)
# test passing Plane object
point = Vector(10, 11, 12).projectToPlane(Plane(base, x_dir, normal))
self.assertTupleAlmostEquals(
point.toTuple(), (59 / 7, 55 / 7, 51 / 7), decimal_places
)
# test line projection
vec = Vector(10, 10, 10)
line = Vector(3, 4, 5)
angle = vec.getAngle(line)
vecLineProjection = vec.projectToLine(line)
self.assertTupleAlmostEquals(
vecLineProjection.normalized().toTuple(),
line.normalized().toTuple(),
decimal_places,
)
self.assertAlmostEqual(
vec.Length * math.cos(angle), vecLineProjection.Length, decimal_places
)
def testVectorNotImplemented(self):
v = Vector(1, 2, 3)
with self.assertRaises(NotImplementedError):
v.distanceToLine()
with self.assertRaises(NotImplementedError):
v.distanceToPlane()
def testVectorSpecialMethods(self):
v = Vector(1, 2, 3)
self.assertEqual(repr(v), "Vector: (1.0, 2.0, 3.0)")
self.assertEqual(str(v), "Vector: (1.0, 2.0, 3.0)")
def testMatrixCreationAndAccess(self):
def matrix_vals(m):
return [[m[r, c] for c in range(4)] for r in range(4)]
# default constructor creates a 4x4 identity matrix
m = Matrix()
identity = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
self.assertEqual(identity, matrix_vals(m))
vals4x4 = [
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 2.0],
[0.0, 0.0, 1.0, 3.0],
[0.0, 0.0, 0.0, 1.0],
]
vals4x4_tuple = tuple(tuple(r) for r in vals4x4)
# test constructor with 16-value input
m = Matrix(vals4x4)
self.assertEqual(vals4x4, matrix_vals(m))
m = Matrix(vals4x4_tuple)
self.assertEqual(vals4x4, matrix_vals(m))
# test constructor with 12-value input (the last 4 are an implied
# [0,0,0,1])
m = Matrix(vals4x4[:3])
self.assertEqual(vals4x4, matrix_vals(m))
m = Matrix(vals4x4_tuple[:3])
self.assertEqual(vals4x4, matrix_vals(m))
# Test 16-value input with invalid values for the last 4
invalid = [
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 2.0],
[0.0, 0.0, 1.0, 3.0],
[1.0, 2.0, 3.0, 4.0],
]
with self.assertRaises(ValueError):
Matrix(invalid)
# Test input with invalid type
with self.assertRaises(TypeError):
Matrix("invalid")
# Test input with invalid size / nested types
with self.assertRaises(TypeError):
Matrix([[1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4]])
with self.assertRaises(TypeError):
Matrix([1, 2, 3])
# Invalid sub-type
with self.assertRaises(TypeError):
Matrix([[1, 2, 3, 4], "abc", [1, 2, 3, 4]])
# test out-of-bounds access
m = Matrix()
with self.assertRaises(IndexError):
m[0, 4]
with self.assertRaises(IndexError):
m[4, 0]
with self.assertRaises(IndexError):
m["ab"]
# test __repr__ methods
m = Matrix(vals4x4)
mRepr = "Matrix([[1.0, 0.0, 0.0, 1.0],\n [0.0, 1.0, 0.0, 2.0],\n [0.0, 0.0, 1.0, 3.0],\n [0.0, 0.0, 0.0, 1.0]])"
self.assertEqual(repr(m), mRepr)
self.assertEqual(str(eval(repr(m))), mRepr)
def testMatrixFunctionality(self):
# Test rotate methods
def matrix_almost_equal(m, target_matrix):
for r, row in enumerate(target_matrix):
for c, target_value in enumerate(row):
self.assertAlmostEqual(m[r, c], target_value)
root_3_over_2 = math.sqrt(3) / 2
m_rotate_x_30 = [
[1, 0, 0, 0],
[0, root_3_over_2, -1 / 2, 0],
[0, 1 / 2, root_3_over_2, 0],
[0, 0, 0, 1],
]
mx = Matrix()
mx.rotateX(30 * DEG2RAD)
matrix_almost_equal(mx, m_rotate_x_30)
m_rotate_y_30 = [
[root_3_over_2, 0, 1 / 2, 0],
[0, 1, 0, 0],
[-1 / 2, 0, root_3_over_2, 0],
[0, 0, 0, 1],
]
my = Matrix()
my.rotateY(30 * DEG2RAD)
matrix_almost_equal(my, m_rotate_y_30)
m_rotate_z_30 = [
[root_3_over_2, -1 / 2, 0, 0],
[1 / 2, root_3_over_2, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
mz = Matrix()
mz.rotateZ(30 * DEG2RAD)
matrix_almost_equal(mz, m_rotate_z_30)
# Test matrix multipy vector
v = Vector(1, 0, 0)
self.assertTupleAlmostEquals(
mz.multiply(v).toTuple(), (root_3_over_2, 1 / 2, 0), 7
)
# Test matrix multipy matrix
m_rotate_xy_30 = [
[root_3_over_2, 0, 1 / 2, 0],
[1 / 4, root_3_over_2, -root_3_over_2 / 2, 0],
[-root_3_over_2 / 2, 1 / 2, 3 / 4, 0],
[0, 0, 0, 1],
]
mxy = mx.multiply(my)
matrix_almost_equal(mxy, m_rotate_xy_30)
# Test matrix inverse
vals4x4 = [[1, 2, 3, 4], [5, 1, 6, 7], [8, 9, 1, 10], [0, 0, 0, 1]]
vals4x4_invert = [
[-53 / 144, 25 / 144, 1 / 16, -53 / 144],
[43 / 144, -23 / 144, 1 / 16, -101 / 144],
[37 / 144, 7 / 144, -1 / 16, -107 / 144],
[0, 0, 0, 1],
]
m = Matrix(vals4x4).inverse()
matrix_almost_equal(m, vals4x4_invert)
def testTranslate(self):
e = Edge.makeCircle(2, (1, 2, 3))
e2 = e.translate(Vector(0, 0, 1))
self.assertTupleAlmostEquals((1.0, 2.0, 4.0), e2.Center().toTuple(), 3)
def testVertices(self):
e = Shape.cast(BRepBuilderAPI_MakeEdge(gp_Pnt(0, 0, 0), gp_Pnt(1, 1, 0)).Edge())
self.assertEqual(2, len(e.Vertices()))
def testPlaneEqual(self):
# default orientation
self.assertEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)),
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)),
)
# moved origin
self.assertEqual(
Plane(origin=(2, 1, -1), xDir=(1, 0, 0), normal=(0, 0, 1)),
Plane(origin=(2, 1, -1), xDir=(1, 0, 0), normal=(0, 0, 1)),
)
# moved x-axis
self.assertEqual(
Plane(origin=(0, 0, 0), xDir=(1, 1, 0), normal=(0, 0, 1)),
Plane(origin=(0, 0, 0), xDir=(1, 1, 0), normal=(0, 0, 1)),
)
# moved z-axis
self.assertEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 1, 1)),
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 1, 1)),
)
def testPlaneNotEqual(self):
# type difference
for value in [None, 0, 1, "abc"]:
self.assertNotEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)), value
)
# origin difference
self.assertNotEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)),
Plane(origin=(0, 0, 1), xDir=(1, 0, 0), normal=(0, 0, 1)),
)
# x-axis difference
self.assertNotEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)),
Plane(origin=(0, 0, 0), xDir=(1, 1, 0), normal=(0, 0, 1)),
)
# z-axis difference
self.assertNotEqual(
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 1)),
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 1, 1)),
)
def testInvalidPlane(self):
# Test plane creation error handling
with self.assertRaises(ValueError):
Plane.named("XX", (0, 0, 0))
with self.assertRaises(ValueError):
Plane(origin=(0, 0, 0), xDir=(0, 0, 0), normal=(0, 1, 1))
with self.assertRaises(ValueError):
Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 0, 0))
def testPlaneMethods(self):
# Test error checking
p = Plane(origin=(0, 0, 0), xDir=(1, 0, 0), normal=(0, 1, 0))
with self.assertRaises(ValueError):
p.toLocalCoords("box")
with self.assertRaises(NotImplementedError):
p.mirrorInPlane([Solid.makeBox(1, 1, 1)], "Z")
# Test translation to local coordinates
local_box = Workplane(p.toLocalCoords(Solid.makeBox(1, 1, 1)))
local_box_vertices = [(v.X, v.Y, v.Z) for v in local_box.vertices().vals()]
target_vertices = [
(0, -1, 0),
(0, 0, 0),
(0, -1, 1),
(0, 0, 1),
(1, -1, 0),
(1, 0, 0),
(1, -1, 1),
(1, 0, 1),
]
for i, target_point in enumerate(target_vertices):
self.assertTupleAlmostEquals(target_point, local_box_vertices[i], 7)
# Test mirrorInPlane
mirror_box = Workplane(p.mirrorInPlane([Solid.makeBox(1, 1, 1)], "Y")[0])
mirror_box_vertices = [(v.X, v.Y, v.Z) for v in mirror_box.vertices().vals()]
target_vertices = [
(0, 0, 1),
(0, 0, 0),
(0, -1, 1),
(0, -1, 0),
(-1, 0, 1),
(-1, 0, 0),
(-1, -1, 1),
(-1, -1, 0),
]
for i, target_point in enumerate(target_vertices):
self.assertTupleAlmostEquals(target_point, mirror_box_vertices[i], 7)
def testLocation(self):
# Tuple
loc0 = Location((0, 0, 1))
T = loc0.wrapped.Transformation().TranslationPart()
self.assertTupleAlmostEquals((T.X(), T.Y(), T.Z()), (0, 0, 1), 6)
# Vector
loc1 = Location(Vector(0, 0, 1))
T = loc1.wrapped.Transformation().TranslationPart()
self.assertTupleAlmostEquals((T.X(), T.Y(), T.Z()), (0, 0, 1), 6)
# rotation + translation
loc2 = Location(Vector(0, 0, 1), Vector(0, 0, 1), 45)
angle = loc2.wrapped.Transformation().GetRotation().GetRotationAngle() * RAD2DEG
self.assertAlmostEqual(45, angle)
# gp_Trsf
T = gp_Trsf()
T.SetTranslation(gp_Vec(0, 0, 1))
loc3 = Location(T)
assert (
loc1.wrapped.Transformation().TranslationPart().Z()
== loc3.wrapped.Transformation().TranslationPart().Z()
)
# Test creation from the OCP.gp.gp_Trsf object
loc4 = Location(gp_Trsf())
self.assertTupleAlmostEquals(loc4.toTuple()[0], (0, 0, 0), 7)
self.assertTupleAlmostEquals(loc4.toTuple()[1], (0, 0, 0), 7)
# Test composition
loc4 = Location((0, 0, 0), Vector(0, 0, 1), 15)
loc5 = loc1 * loc4
loc6 = loc4 * loc4
loc7 = loc4 ** 2
T = loc5.wrapped.Transformation().TranslationPart()
self.assertTupleAlmostEquals((T.X(), T.Y(), T.Z()), (0, 0, 1), 6)
angle5 = (
loc5.wrapped.Transformation().GetRotation().GetRotationAngle() * RAD2DEG
)
self.assertAlmostEqual(15, angle5)
angle6 = (
loc6.wrapped.Transformation().GetRotation().GetRotationAngle() * RAD2DEG
)
self.assertAlmostEqual(30, angle6)
angle7 = (
loc7.wrapped.Transformation().GetRotation().GetRotationAngle() * RAD2DEG
)
self.assertAlmostEqual(30, angle7)
# Test error handling on creation
with self.assertRaises(TypeError):
Location([0, 0, 1])
with self.assertRaises(TypeError):
Location("xy_plane")
def testEdgeWrapperRadius(self):
# get a radius from a simple circle
e0 = Edge.makeCircle(2.4)
self.assertAlmostEqual(e0.radius(), 2.4)
# radius of an arc
e1 = Edge.makeCircle(1.8, pnt=(5, 6, 7), dir=(1, 1, 1), angle1=20, angle2=30)
self.assertAlmostEqual(e1.radius(), 1.8)
# test value errors
e2 = Edge.makeEllipse(10, 20)
with self.assertRaises(ValueError):
e2.radius()
# radius from a wire
w0 = Wire.makeCircle(10, Vector(1, 2, 3), (-1, 0, 1))
self.assertAlmostEqual(w0.radius(), 10)
# radius from a wire with multiple edges
rad = 2.3
pnt = (7, 8, 9)
direction = (1, 0.5, 0.1)
w1 = Wire.assembleEdges(
[
Edge.makeCircle(rad, pnt, direction, 0, 10),
Edge.makeCircle(rad, pnt, direction, 10, 25),
Edge.makeCircle(rad, pnt, direction, 25, 230),
]
)
self.assertAlmostEqual(w1.radius(), rad)
# test value error from wire
w2 = Wire.makePolygon([Vector(-1, 0, 0), Vector(0, 1, 0), Vector(1, -1, 0),])
with self.assertRaises(ValueError):
w2.radius()
# (I think) the radius of a wire is the radius of it's first edge.
# Since this is stated in the docstring better make sure.
no_rad = Wire.assembleEdges(
[
Edge.makeLine(Vector(0, 0, 0), Vector(0, 1, 0)),
Edge.makeCircle(1.0, angle1=90, angle2=270),
]
)
with self.assertRaises(ValueError):
no_rad.radius()
yes_rad = Wire.assembleEdges(
[
Edge.makeCircle(1.0, angle1=90, angle2=270),
Edge.makeLine(Vector(0, -1, 0), Vector(0, 1, 0)),
]
)
self.assertAlmostEqual(yes_rad.radius(), 1.0)
many_rad = Wire.assembleEdges(
[
Edge.makeCircle(1.0, angle1=0, angle2=180),
Edge.makeCircle(3.0, pnt=Vector(2, 0, 0), angle1=180, angle2=359),
]
)
self.assertAlmostEqual(many_rad.radius(), 1.0)
@pytest.mark.parametrize(
"points, close, expected_edges",
[
(((0, 0, 0), (0, 1, 0), (1, 0, 0)), False, 2),
(((0, 0, 0), (0, 1, 0), (1, 0, 0)), True, 3),
(((0, 0, 0), (0, 1, 0), (1, 0, 0), (0, 0, 0)), False, 3),
(((0, 0, 0), (0, 1, 0), (1, 0, 0), (0, 0, 0)), True, 3),
],
)
def test_wire_makepolygon(points, close, expected_edges):
assert len(Wire.makePolygon(points, False, close).Edges()) == expected_edges
if __name__ == "__main__":
unittest.main()
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,539 | CadQuery/cadquery | refs/heads/master | /examples/Ex013_Locating_a_Workplane_on_a_Vertex.py | import cadquery as cq
# 1. Establishes a workplane that an object can be built on.
# 1a. Uses the named plane orientation "front" to define the workplane, meaning
# that the positive Z direction is "up", and the negative Z direction
# is "down".
# 2. Creates a 3D box that will have a hole placed in it later.
result = cq.Workplane("front").box(3, 2, 0.5)
# 3. Select the lower left vertex and make a workplane.
# 3a. The top-most Z face is selected using the >Z selector.
# 3b. The lower-left vertex of the faces is selected with the <XY selector.
# 3c. A new workplane is created on the vertex to build future geometry on.
result = result.faces(">Z").vertices("<XY").workplane(centerOption="CenterOfMass")
# 4. A circle is drawn with the selected vertex as its center.
# 4a. The circle is cut down through the box to cut the corner out.
result = result.circle(1.0).cutThruAll()
# Displays the result of this script
show_object(result)
| {"/cadquery/hull.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex017_Shelling_to_Create_Thin_Features.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/threemf.py": ["/cadquery/cq.py"], "/tests/test_sketch.py": ["/cadquery/sketch.py", "/cadquery/selectors.py"], "/cadquery/__init__.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/selectors.py", "/cadquery/sketch.py", "/cadquery/cq.py", "/cadquery/assembly.py"], "/cadquery/sketch.py": ["/cadquery/hull.py", "/cadquery/selectors.py", "/cadquery/types.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/importers/dxf.py", "/cadquery/occ_impl/sketch_solver.py"], "/examples/Ex004_Extruded_Cylindrical_Plate.py": ["/cadquery/__init__.py"], "/cadquery/cq_directive.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/solver.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/cadquery/occ_impl/exporters/utils.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex025_Swept_Helix.py": ["/cadquery/__init__.py"], "/cadquery/assembly.py": ["/cadquery/cq.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/solver.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/selectors.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_workplanes.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex100_Lego_Brick.py": ["/cadquery/__init__.py"], "/examples/Ex012_Creating_Workplanes_on_Faces.py": ["/cadquery/__init__.py"], "/examples/Ex002_Block_With_Bored_Center_Hole.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/vtk.py": ["/cadquery/occ_impl/shapes.py"], "/examples/Ex005_Extruded_Lines_and_Arcs.py": ["/cadquery/__init__.py"], "/tests/test_cadquery.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_cqgi.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/tests/test_utils.py": ["/cadquery/utils.py"], "/examples/Ex001_Simple_Block.py": ["/cadquery/__init__.py"], "/doc/gen_colors.py": ["/cadquery/__init__.py"], "/tests/test_hull.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/__init__.py": ["/cadquery/cq.py", "/cadquery/utils.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/occ_impl/exporters/json.py", "/cadquery/occ_impl/exporters/amf.py", "/cadquery/occ_impl/exporters/threemf.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/exporters/utils.py"], "/examples/Ex026_Case_Seam_Lip.py": ["/cadquery/__init__.py", "/cadquery/selectors.py"], "/tests/__init__.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/jupyter_tools.py": ["/cadquery/occ_impl/exporters/vtk.py", "/cadquery/occ_impl/shapes.py", "/cadquery/assembly.py", "/cadquery/occ_impl/assembly.py"], "/examples/Ex015_Rotated_Workplanes.py": ["/cadquery/__init__.py"], "/examples/Ex003_Pillow_Block_With_Counterbored_Holes.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/dxf.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex009_Polylines.py": ["/cadquery/__init__.py"], "/examples/Ex007_Using_Point_Lists.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/dxf.py": ["/cadquery/cq.py", "/cadquery/units.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/utils.py"], "/cadquery/occ_impl/sketch_solver.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/types.py"], "/tests/test_jupyter.py": ["/tests/__init__.py", "/cadquery/__init__.py", "/cadquery/occ_impl/jupyter_tools.py"], "/tests/test_examples.py": ["/cadquery/__init__.py", "/cadquery/cq_directive.py"], "/examples/Ex014_Offset_Workplanes.py": ["/cadquery/__init__.py"], "/tests/test_importers.py": ["/cadquery/__init__.py", "/tests/__init__.py"], "/examples/Ex101_InterpPlate.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/exporters/assembly.py": ["/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/geom.py"], "/examples/Ex020_Rounding_Corners_with_Fillets.py": ["/cadquery/__init__.py"], "/examples/Ex008_Polygon_Creation.py": ["/cadquery/__init__.py"], "/tests/test_vis.py": ["/cadquery/__init__.py", "/cadquery/vis.py", "/cadquery/occ_impl/exporters/assembly.py"], "/examples/Ex023_Sweep.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/geom.py": ["/cadquery/types.py", "/cadquery/occ_impl/shapes.py"], "/cadquery/occ_impl/shapes.py": ["/cadquery/occ_impl/geom.py", "/cadquery/utils.py", "/cadquery/occ_impl/jupyter_tools.py"], "/examples/Ex010_Defining_an_Edge_with_a_Spline.py": ["/cadquery/__init__.py"], "/cadquery/vis.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/jupyter_tools.py"], "/cadquery/occ_impl/exporters/svg.py": ["/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_exporters.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/dxf.py", "/cadquery/occ_impl/exporters/utils.py", "/tests/__init__.py"], "/tests/test_assembly.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/exporters/assembly.py", "/cadquery/occ_impl/assembly.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/geom.py"], "/tests/test_selectors.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex022_Revolution.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/importers/__init__.py": ["/cadquery/__init__.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/importers/dxf.py"], "/examples/Ex024_Sweep_With_Multiple_Sections.py": ["/cadquery/__init__.py"], "/examples/Ex006_Moving_the_Current_Working_Point.py": ["/cadquery/__init__.py"], "/cadquery/cqgi.py": ["/cadquery/__init__.py"], "/cadquery/occ_impl/assembly.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/vtk.py", "/cadquery/cq.py"], "/examples/Ex011_Mirroring_Symmetric_Geometry.py": ["/cadquery/__init__.py"], "/examples/Ex018_Making_Lofts.py": ["/cadquery/__init__.py"], "/examples/Ex019_Counter_Sunk_Holes.py": ["/cadquery/__init__.py"], "/cadquery/selectors.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py"], "/examples/Ex021_Splitting_an_Object.py": ["/cadquery/__init__.py"], "/cadquery/cq.py": ["/cadquery/occ_impl/geom.py", "/cadquery/occ_impl/shapes.py", "/cadquery/occ_impl/exporters/svg.py", "/cadquery/utils.py", "/cadquery/selectors.py", "/cadquery/sketch.py"], "/tests/test_cad_objects.py": ["/tests/__init__.py", "/cadquery/__init__.py"], "/examples/Ex013_Locating_a_Workplane_on_a_Vertex.py": ["/cadquery/__init__.py"]} |
44,552 | AlysonBasilio/Alfred | refs/heads/master | /app/run.py | import flask
import psycopg2
import flask_login
from app.models.User import User
app = flask.Flask(__name__, static_url_path='')
app.secret_key = 'comp18'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
con = psycopg2.connect(port="5432", host="localhost", user="alyson", password="123456",
dbname="alfredsDB")
cursor = con.cursor()
def validate(username):
completion = False
cursor.execute("SELECT \"Name\" FROM public.\"Users\"")
rows = cursor.fetchall()
for row in rows:
dbUser = row[0]
if dbUser==username:
completion=True
break
return completion
@login_manager.user_loader
def user_loader(email):
if not validate(email):
return
user = User(email)
return user
@login_manager.request_loader
def request_loader(request):
email = request.form.get('email')
if not validate(email):
return
user = User(email)
# DO NOT ever store passwords in plaintext and always compare password
# hashes using constant-time comparison!
user.authenticate(request.form['password'])
return user
@app.route('/')
def redirect():
return flask.redirect(flask.url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if flask.request.method == 'GET':
return flask.render_template("login.html")
if flask.request.method == 'POST':
print(flask.request.form)
email = flask.request.form['username']
user = User(email)
user.authenticate(flask.request.form['password'])
if user.is_authenticated():
flask_login.login_user(user)
return flask.redirect(flask.url_for('index'))
return 'Bad login'
@app.route('/logout')
def logout():
flask_login.logout_user()
return 'Logged out'
@login_manager.unauthorized_handler
def unauthorized_handler():
return 'Unauthorized'
@app.route('/index', methods=['GET', 'POST'])
@flask_login.login_required
def index():
if flask.request.method == 'POST':
print(flask.request.form)
if not InsertActivitiesOfDay(flask.request.form['hour'],flask.request.form['day'], flask.request.form['description'], flask.request.form['priority'], flask.request.form['tag']):
return "<p>Você já tem um compromisso nesse dia e horário. <a href='/index'>Retornar</a></p>"
return flask.render_template("index.html")
def InsertActivitiesOfDay(hour, day, description, priority, tag):
try:
cursor.execute(""" INSERT INTO public.\"Alfreds\"(\"Description\", \"Tag\", \"Priority\", day_of_week, \"Time\", username)
VALUES ('"""+description+"""','"""+tag+"""','"""+priority+"""','"""+day+"""','"""+hour+"""', '"""+flask_login.current_user.username+"""')""")
con.commit()
return True
except Exception as e:
con.commit()
print(e)
return False
@app.route('/static/<path:path>')
def send_js(path):
return flask.send_from_directory('static', path)
@app.route('/loadbadges')
@flask_login.login_required
def background_process():
try:
cursor.execute(""" SELECT day_of_week
FROM public.\"Alfreds\"
WHERE username = '"""+flask_login.current_user.username+"""'""")
list = {'MON':0,
'TUE':0,
'WED':0,
'THU':0,
'FRI':0,
'SAT':0,
'SUN':0}
alarms = cursor.fetchall()
for i in alarms:
list[i[0]]+=1
print(list)
json = flask.jsonify(list)
return json
except Exception as e:
print(e)
return flask.jsonify(error=str(e))
@app.route('/getActivitiesOfDay')
@flask_login.login_required
def getActivitiesOfDay():
try:
text = str(flask.request.args.get('day_of_week'))
print(text)
cursor.execute(""" SELECT *
FROM public.\"Alfreds\"
WHERE day_of_week = '"""+text+"""'
AND username = '"""+flask_login.current_user.username+"""'""")
alarms = cursor.fetchall()
list=[]
for i in alarms:
list.append({
'hour':i[4],
'description':i[0],
'priority':i[2],
'tag':i[1]
})
json = flask.jsonify(list)
return json
except Exception as e:
print(e)
return flask.jsonify(error=str(e))
@app.route('/register', methods=['GET', 'POST'])
def register():
if flask.request.method == 'POST':
if not addNewUser(flask.request.form['username'], flask.request.form['password']):
return "<p>Usuário já existente: <a href='/register'>Voltar</a></p>"
return "<p>Registrated: <a href='/login'>Login</a></p>"
return flask.render_template("register.html")
def addNewUser(username,password):
try:
cursor.execute(""" INSERT INTO public.\"Users\"(\"Name\", \"Password\")
VALUES ('""" + username + """','""" +
password + """')""")
con.commit()
return True
except Exception as e:
con.commit()
print(e)
return False
if __name__ == "__main__":
print("Entrou aqui")
app.run(host='0.0.0.0') | {"/app/run.py": ["/app/models/User.py"]} |
44,553 | AlysonBasilio/Alfred | refs/heads/master | /app/models/User.py | import psycopg2
class User:
def __init__(self,username):
self.username = username
self.auth = False
self.active = False
def authenticate(self,password):
con = psycopg2.connect(port="5432", host="localhost", user="alyson", password="123456",
dbname="alfredsDB")
cursor = con.cursor()
cursor.execute("SELECT * FROM public.\"Users\" WHERE \"Name\"='"+self.username+"'")
result = cursor.fetchone()
print(result)
if result[1]==password:
self.auth = True
else:
self.auth = False
def is_authenticated(self):
return self.auth
def is_active(self):
return self.active
def is_anonymous(self):
return False
def get_id(self):
return self.username | {"/app/run.py": ["/app/models/User.py"]} |
44,554 | shellydeforte/deconstruct_lc | refs/heads/master | /deconstruct_lc/drosophila/run_drosophila.py | import os
import pandas as pd
from deconstruct_lc import read_config
from deconstruct_lc import tools_fasta
from deconstruct_lc.scores.norm_score import NormScore
class Drosophila(object):
def __init__(self):
config = read_config.read_config()
data_dp = os.path.join(config['fps']['data_dp'])
self.fpi = os.path.join(data_dp, '..', 'drosophila_llps', 'candidate_drosophila.fasta')
self.cand_fpo = os.path.join(data_dp, '..', 'drosophila_llps', 'candidate_drosophila.tsv')
self.all_fpi = os.path.join(data_dp, '..', 'drosophila_llps',
'all_drosophila.fasta')
self.all_fpo = os.path.join(data_dp, '..', 'drosophila_llps', 'all_drosophila.tsv')
def write_scores(self):
ids, seqs = tools_fasta.fasta_to_id_seq(self.all_fpi)
ns = NormScore()
scores = ns.lc_norm_score(seqs)
df_out = pd.DataFrame({'Protein ID': ids,
'LC Score': scores},
columns=['Protein ID', 'LC Score'])
df_out = df_out.sort_values(by='LC Score', ascending=False)
print(df_out)
df_out.to_csv(self.all_fpo, sep='\t')
def main():
d = Drosophila()
d.write_scores()
if __name__ == '__main__':
main() | {"/deconstruct_lc/drosophila/run_drosophila.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/write_marcotte_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/hexandiol.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/run.py": ["/deconstruct_lc/data_pdb/ssdis_to_fasta.py", "/deconstruct_lc/data_pdb/filter_pdb.py", "/deconstruct_lc/data_pdb/norm_all_to_tsv.py", "/deconstruct_lc/data_pdb/write_pdb_analysis.py"], "/deconstruct_lc/rohit/plot_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/kelil/run_display.py": ["/deconstruct_lc/kelil/display_motif.py"], "/deconstruct_lc/analysis_bc/score_profile.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/old/experiment/marcotte.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/puncta/puncta_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/experiment/write_yeast.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sup35.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/analysis_bc/write_bc_score.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/remove_structure/remove_pfam.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/biogrid/format.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/format_gfp.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sandbox.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/write_pdb_analysis.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/scores/write_scores.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/write_details.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/experiment/labels.py"], "/deconstruct_lc/lp/lp_proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/len_norm/adjust_b.py": ["/deconstruct_lc/scores/norm_score.py"]} |
44,555 | shellydeforte/deconstruct_lc | refs/heads/master | /deconstruct_lc/experiment/write_marcotte_scores.py | import os
import pandas as pd
from deconstruct_lc import read_config
from deconstruct_lc import tools_fasta
from deconstruct_lc.scores.norm_score import NormScore
class MarcotteScores(object):
def __init__(self):
config = read_config.read_config()
data_dp = os.path.join(config['fps']['data_dp'])
self.marcotte_fpi = os.path.join(data_dp, 'experiment',
'marcotte_puncta_proteins.xlsx')
self.orf_trans = os.path.join(data_dp, 'proteomes', 'orf_trans.fasta')
self.puncta_fpo = os.path.join(data_dp, 'experiment', 'marcotte_puncta_scores.tsv')
self.npuncta_fpo = os.path.join(data_dp, 'experiment', 'marcotte_nopuncta_scores.tsv')
def write_puncta(self):
df = pd.read_excel(self.marcotte_fpi, 'ST1')
yeast_ids = list(df['ORF'])
genes = list(df['Gene'])
pids, seqs = tools_fasta.get_yeast_seq_from_ids(self.orf_trans, yeast_ids)
lengths = [len(seq) for seq in seqs]
ns = NormScore()
scores = ns.lc_norm_score(seqs)
df_out = pd.DataFrame({'Gene': genes, 'ORF': pids,
'LC Score': scores, 'Sequence': seqs,
'Length': lengths},
columns=['Gene', 'ORF', 'LC Score', 'Length', 'Sequence'])
print(df_out.head())
df_out.to_csv(self.puncta_fpo, sep='\t')
def write_nopuncta(self):
"""{'YEL014C', 'YDR250C', 'YOR199W', 'YJL017W'} are not included"""
df = pd.read_excel(self.marcotte_fpi, 'NoPuncta')
yeast_ids = list(df['ORF'])
seqs, ngenes, orfs = tools_fasta.get_yeast_seq_gene_from_ids(self.orf_trans, yeast_ids)
lengths = [len(seq) for seq in seqs]
print(set(yeast_ids) - set(orfs))
ns = NormScore()
scores = ns.lc_norm_score(seqs)
df_out = pd.DataFrame({'Gene': ngenes, 'ORF': orfs,
'LC Score': scores, 'Sequence': seqs,
'Length': lengths},
columns=['Gene', 'ORF', 'LC Score', 'Length', 'Sequence'])
print(df_out.head())
df_out.to_csv(self.npuncta_fpo, sep='\t')
def main():
ms = MarcotteScores()
ms.write_puncta()
if __name__ == '__main__':
main() | {"/deconstruct_lc/drosophila/run_drosophila.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/write_marcotte_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/hexandiol.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/run.py": ["/deconstruct_lc/data_pdb/ssdis_to_fasta.py", "/deconstruct_lc/data_pdb/filter_pdb.py", "/deconstruct_lc/data_pdb/norm_all_to_tsv.py", "/deconstruct_lc/data_pdb/write_pdb_analysis.py"], "/deconstruct_lc/rohit/plot_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/kelil/run_display.py": ["/deconstruct_lc/kelil/display_motif.py"], "/deconstruct_lc/analysis_bc/score_profile.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/old/experiment/marcotte.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/puncta/puncta_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/experiment/write_yeast.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sup35.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/analysis_bc/write_bc_score.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/remove_structure/remove_pfam.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/biogrid/format.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/format_gfp.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sandbox.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/write_pdb_analysis.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/scores/write_scores.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/write_details.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/experiment/labels.py"], "/deconstruct_lc/lp/lp_proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/len_norm/adjust_b.py": ["/deconstruct_lc/scores/norm_score.py"]} |
44,556 | shellydeforte/deconstruct_lc | refs/heads/master | /deconstruct_lc/experiment/hexandiol.py | import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from Bio.SeqUtils.ProtParam import ProteinAnalysis
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from deconstruct_lc import read_config
from deconstruct_lc import tools_fasta
from deconstruct_lc.scores.norm_score import NormScore
from deconstruct_lc import tools_lc
class Hexandiol(object):
def __init__(self):
config = read_config.read_config()
data_dp = os.path.join(config['fps']['data_dp'])
self.marcotte_fpi = os.path.join(data_dp, 'experiment',
'marcotte_puncta_proteins.xlsx')
self.orf_trans = os.path.join(data_dp, 'proteomes', 'orf_trans.fasta')
self.hex_fpi = os.path.join(data_dp, 'experiment', '180803_HD.xls')
self.tht_fpi = os.path.join(data_dp, 'experiment', '180803_ThT.xls')
self.puncta_fpi = os.path.join(data_dp, 'experiment', 'marcotte_puncta_scores.tsv')
self.npuncta_fpi = os.path.join(data_dp, 'experiment', 'marcotte_nopuncta_scores.tsv')
self.nofasta = os.path.join(data_dp, 'experiment', 'hex_nop.fasta')
self.yesfasta = os.path.join(data_dp, 'experiment', 'hex_yesp.fasta')
self.sg_ann = os.path.join(data_dp, 'experiment', 'cytoplasmic_stress_granule_annotations.txt')
def remove_sg(self):
sg = pd.read_csv(self.sg_ann, sep='\t')
sg_orfs = list(sg['Gene Systematic Name'])
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
no_orf = list(no_df['ORF'])
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
yes_orf = list(yes_df['ORF'])
sg_in = [pid for pid in no_orf if pid in sg_orfs]
yes_orf = list(set(yes_orf) - set(sg_orfs))
no_orf = list(set(no_orf) - set(sg_orfs))
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_scores = list(yes_lc['LC Score'])
no_scores = list(no_lc['LC Score'])
sg_lc = lc_df[lc_df['ORF'].isin(sg_in)]
print(sg_lc[['ORF', 'LC Score']])
plt.xlabel('LC scores')
plt.ylabel('Number of proteins')
plt.hist(yes_scores, bins=20, range=(-60, 200), alpha=0.5, label='Does not dissolve with hexanediol')
plt.hist(no_scores, bins=20, range=(-60, 200), alpha=0.5, label='Dissolves with hexanediol')
plt.legend()
#plt.show()
def remove_subunit(self):
headers, seqs = tools_fasta.fasta_to_head_seq(self.nofasta)
print(len(headers))
total = 0
nosub_seqs = []
sub_seqs = []
sub_heads = []
ns = NormScore()
lengths = []
for header, seq in zip(headers, seqs):
if 'kinase' in header:
total += 1
sub_seqs.append(seq)
sub_heads.append(header)
lengths.append(len(seq))
else:
nosub_seqs.append(seq)
scores = ns.lc_norm_score(nosub_seqs)
sub_scores = ns.lc_norm_score(sub_seqs)
print(total)
print(np.mean(scores))
print(np.mean(sub_scores))
print(sub_scores)
for head, sub_score, length in zip(sub_heads, sub_scores, lengths):
print(head)
print(sub_score)
print(length)
print()
def score_hist(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.tht_fpi, sheetname='Hoja1')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes') | (hex_df['180708 48h'] == 'yes?')]
#no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
no_df = hex_df[hex_df['180809 ThT'] == 'no']
no_orf = list(no_df['ORF'])
#yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
yes_df = hex_df[hex_df['180809 ThT'] == 'yes']
yes_orf = list(yes_df['ORF'])
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_scores = list(yes_lc['LC Score'])
no_scores = list(no_lc['LC Score'])
plt.xlabel('LC scores')
plt.ylabel('Number of proteins')
plt.hist(yes_scores, bins=20, range=(-60, 200), alpha=0.5, normed=True, label='Stains with ThT')
plt.hist(no_scores, bins=20, range=(-60, 200), alpha=0.5, normed=True, label='Does not Stain with ThT')
plt.legend()
plt.show()
def write_fasta(self):
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
no_orf = list(no_df['ORF'])
yes_orf = list(yes_df['ORF'])
tools_fasta.yeast_write_fasta_from_ids(self.orf_trans, no_orf, self.nofasta)
tools_fasta.yeast_write_fasta_from_ids(self.orf_trans, yes_orf, self.yesfasta)
def read_files(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no') & (hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes') & (hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
qyes_df = hex_df[hex_df['180803 48h HD 1h'] == 'yes?']
yyy_df = hex_df[(hex_df['180706 6h '] == 'yes')]
no_no_df = hex_df[hex_df['180708 48h'] == 'no']
no_orf = list(no_df['ORF'])
yes_orf = list(yes_df['ORF'])
qyes_orf = list(qyes_df['ORF'])
nono_orf = list(no_no_df['ORF'])
all_orf = list(hex_df['ORF'])
yyy_orf = list(yyy_df['ORF'])
no_scores = []
no_lens = []
for item in no_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
no_scores.append(lc_score)
no_lens.append(len(str(list(ndf['Sequence'])[0])))
yes_scores = []
yes_lens = []
for item in yes_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
yes_scores.append(lc_score)
yes_lens.append(len(str(list(ndf['Sequence'])[0])))
print(no_lens)
print(yes_lens)
qyes_scores = []
for item in qyes_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
qyes_scores.append(lc_score)
nono_scores = []
for item in nono_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
nono_scores.append(lc_score)
all_scores = []
for item in all_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
all_scores.append(lc_score)
yyy_scores = []
for item in yyy_orf:
ndf = lc_df[lc_df['ORF'] == item]
if len(ndf) > 0:
lc_score = float(ndf['LC Score'])
yyy_scores.append(lc_score)
print(len(yes_scores))
print(len(no_scores))
print(np.mean(yes_scores))
print(np.mean(no_scores))
#plt.hist(all_scores, bins=20, range=(-60, 200), normed=True)
plt.hist(yes_lens, bins=20, normed=True, alpha=0.5)
#plt.hist(nono_scores, bins=10, range=(-60, 200), alpha=0.5)
#plt.hist(qyes_scores, bins=10)
plt.hist(no_lens, bins=20, alpha=0.5, normed=True)
print(yyy_scores)
plt.show()
def stubborn_puncta(self):
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
yyy_df = hex_df[(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'yes') & (hex_df['180803 48h HD 1h'] == 'yes')]
yyy_orf = list(yyy_df['ORF'])
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
ndf = lc_df[lc_df['ORF'].isin(yyy_orf)]
print(list(ndf['Sequence']))
def high_scoring_agg(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
no_orf = list(no_df['ORF'])
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
yes_orf = list(yes_df['ORF'])
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_lc = yes_lc[yes_lc['LC Score'] > 0]
no_lc = no_lc[no_lc['LC Score'] > 0]
no_seqs = list(no_lc['Sequence'])
yes_seqs = list(yes_lc['Sequence'])
for seq in no_seqs:
analysed_seq = ProteinAnalysis(seq)
adict = analysed_seq.get_amino_acids_percent()
qn = adict['Q'] + adict['N']
if qn > 0.15:
print(seq)
print()
for seq in yes_seqs:
analysed_seq = ProteinAnalysis(seq)
adict = analysed_seq.get_amino_acids_percent()
qn = adict['Q'] + adict['N']
if qn > 0.15:
print(seq)
def ml_approach(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
hex_df = hex_df[
(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
no_orf = list(no_df['ORF'])
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
yes_orf = list(yes_df['ORF'])
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_lc = yes_lc[yes_lc['LC Score'] > 0]
no_lc = no_lc[no_lc['LC Score'] > 0]
no_seqs = list(no_lc['Sequence'])
no_scores = list(no_lc['LC Score'])
yes_seqs = list(yes_lc['Sequence'])
yes_scores = list(yes_lc['LC Score'])
all_vals = {'R': [], 'T': [], 'L': [], 'S': [], 'V': [], 'Y': [],
'M': [], 'W': [], 'E': [], 'K': [], 'G': [], 'F': [],
'Q': [], 'I': [], 'C': [], 'P': [], 'H': [], 'score': [],
'D': [], 'N': [], 'A': []}
aclass = []
for seq, score in zip(no_seqs, no_scores):
analysed_seq = ProteinAnalysis(seq)
adict = analysed_seq.get_amino_acids_percent()
adict['score'] = score
for item in adict:
all_vals[item].append(adict[item])
aclass.append(0)
for seq, score in zip(yes_seqs, yes_scores):
analysed_seq = ProteinAnalysis(seq)
adict = analysed_seq.get_amino_acids_percent()
adict['score'] = score
for item in adict:
all_vals[item].append(adict[item])
aclass.append(1)
df = pd.DataFrame(all_vals)
df = df[['Y']]
#print(df.head())
#print(df.describe())
clf = RandomForestClassifier(n_estimators=10, random_state=1)
clf = clf.fit(df, aclass)
#yp = clf.predict(df, aclass)
scores = cross_val_score(clf, df, aclass)
print(scores)
print(scores.mean())
def check_scores(self):
ns = NormScore()
seq = 'MSTSASGPEHEFVSKFLTLATLTEPKLPKSYTKPLKDVTNLGVPLPTLKYKYKQNRAKKL' \
'KLHQDQQGQDNAAVHLTLKKIQAPKFSIEHDFSPSDTILQIKQHLISEEKASHISEIKLL' \
'LKGKVLHDNLFLSDLKVTPANSTITVMIKPNPTISKEPEAEKSTNSPAPAPPQELTVPWD' \
'DIEALLKNNFENDQAAVRQVMERLQKGWSLAK'
print(ns.lc_norm_score([seq])[0])
def check_tht(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.tht_fpi, sheetname='Hoja1')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes')]
# aggregates
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
no_df = no_df[no_df['180809 ThT'] == 'no']
no_orf = list(no_df['ORF'])
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
yes_df = yes_df[yes_df['180809 ThT'] == 'no']
yes_orf = list(yes_df['ORF'])
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_scores = list(yes_lc['LC Score'])
no_scores = list(no_lc['LC Score'])
plt.xlabel('LC scores')
plt.ylabel('Number of proteins')
print(len(yes_scores))
print(len(no_scores))
yes_lc = yes_lc.sort_values(by='LC Score')
print(yes_lc[['ORF', 'LC Score']])
plt.hist(yes_scores, bins=20, range=(-60, 200), alpha=0.5, normed=True, label='dissolves with hexandiol')
plt.hist(no_scores, bins=20, range=(-60, 200), alpha=0.5, normed=True, label='no hexanediol, no Tht')
plt.legend()
plt.show()
class TyrMotifs(object):
def __init__(self):
config = read_config.read_config()
data_dp = os.path.join(config['fps']['data_dp'])
self.k = 6
self.lce = 1.6
self.lca = 'SGEQAPDTNKR'
self.lc_m = 0.06744064704548541
self.lc_b = 16.5
self.hex_fpi = os.path.join(data_dp, 'experiment', '180803_HD.xls')
self.puncta_fpi = os.path.join(data_dp, 'experiment', 'marcotte_puncta_scores.tsv')
def count_tyr(self):
yes_seqs, no_seqs = self.load_seqs()
all_tyr = []
tyr_counts = []
asp_counts = []
for seq in yes_seqs:
tyr_motifs = self.detect_tyr(seq)
all_tyr.append(tyr_motifs)
tyr_counts.append(seq.count('Y'))
asp_counts.append(seq.count('N'))
print(np.mean(all_tyr))
print(all_tyr)
print(np.mean(tyr_counts))
print(tyr_counts)
print(np.mean(asp_counts))
print(asp_counts)
all_tyr = []
tyr_counts = []
asp_counts = []
for seq in no_seqs:
tyr_motifs = self.detect_tyr(seq)
all_tyr.append(tyr_motifs)
tyr_counts.append(seq.count('Y'))
asp_counts.append(seq.count('N'))
print(np.mean(all_tyr))
print(all_tyr)
print(np.mean(tyr_counts))
print(tyr_counts)
print(np.mean(asp_counts))
print(asp_counts)
def detect_tyr(self, seq):
tyr_motifs = 0
indexes = tools_lc.lc_to_indexes(seq, self.k, self.lca, self.lce)
tyr_ind = [pos for pos, char in enumerate(seq) if char == 'Y']
for i in tyr_ind:
for j in range(i-2, i+3):
if j in indexes:
tyr_motifs += 1
break
return tyr_motifs
def load_seqs(self):
lc_df = pd.read_csv(self.puncta_fpi, sep='\t', index_col=0)
hex_df = pd.read_excel(self.hex_fpi, sheetname='Hoja2')
hex_df = hex_df[(hex_df['180708 48h'] == 'yes') & (hex_df['180706 6h '] == 'no')]
no_df = hex_df[(hex_df['180803 48h HD 1h'] == 'no')]
no_orf = list(no_df['ORF'])
yes_df = hex_df[(hex_df['180803 48h HD 1h'] == 'yes')]
yes_orf = list(yes_df['ORF'])
no_lc = lc_df[lc_df['ORF'].isin(no_orf)]
yes_lc = lc_df[lc_df['ORF'].isin(yes_orf)]
yes_lc = yes_lc[yes_lc['LC Score'] > 100]
no_lc = no_lc[no_lc['LC Score'] > 100]
no_seqs = list(no_lc['Sequence'])
no_scores = list(no_lc['LC Score'])
yes_seqs = list(yes_lc['Sequence'])
yes_scores = list(yes_lc['LC Score'])
seqs = list(yes_lc['Sequence'])
for seq in seqs:
print(seq)
print(yes_lc.head())
return yes_seqs, no_seqs
def n_clumps(self, seq):
pass
def main():
tm = Hexandiol()
tm.score_hist()
if __name__ == '__main__':
main() | {"/deconstruct_lc/drosophila/run_drosophila.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/write_marcotte_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/hexandiol.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/run.py": ["/deconstruct_lc/data_pdb/ssdis_to_fasta.py", "/deconstruct_lc/data_pdb/filter_pdb.py", "/deconstruct_lc/data_pdb/norm_all_to_tsv.py", "/deconstruct_lc/data_pdb/write_pdb_analysis.py"], "/deconstruct_lc/rohit/plot_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/kelil/run_display.py": ["/deconstruct_lc/kelil/display_motif.py"], "/deconstruct_lc/analysis_bc/score_profile.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/old/experiment/marcotte.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/puncta/puncta_scores.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/old/experiment/write_yeast.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sup35.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/analysis_bc/write_bc_score.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/remove_structure/remove_pfam.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/biogrid/format.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/format_gfp.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/examples/sandbox.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/data_pdb/write_pdb_analysis.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/experiment/proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/scores/write_scores.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/analysis_bc/write_bc_score.py"], "/deconstruct_lc/experiment/write_details.py": ["/deconstruct_lc/scores/norm_score.py", "/deconstruct_lc/experiment/labels.py"], "/deconstruct_lc/lp/lp_proteins.py": ["/deconstruct_lc/scores/norm_score.py"], "/deconstruct_lc/len_norm/adjust_b.py": ["/deconstruct_lc/scores/norm_score.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.