repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/washers.py
src/cqparts_fasteners/washers.py
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/bolts.py
src/cqparts_fasteners/bolts.py
from cqparts.params import * from .male import MaleFastenerPart from .params import * class Bolt(MaleFastenerPart): length = PositiveFloat(20, doc="length from xy plane to tip") head = HeadType( default=('hex', { 'width': 8, 'height': 3.0, }), doc="head type and parameters", ) drive = DriveType(doc="screw drive type and parameters") thread = ThreadType( default=('iso68', { # M5 'diameter': 5.0, 'pitch': 0.5, }), doc="thread type and parameters", ) class SquareBolt(Bolt): head = HeadType( default=('square', { 'width': 8, 'height': 3.0, }), doc="head type and parameters", ) class HexBolt(Bolt): head = HeadType( default=('hex', { 'width': 8, 'height': 3.0, }), doc="head type and parameters", )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/nuts.py
src/cqparts_fasteners/nuts.py
from cqparts.params import * from .female import FemaleFastenerPart class SquareNut(FemaleFastenerPart): edges = PositiveInt(4, doc="number of sides") class HexNut(FemaleFastenerPart): edges = PositiveInt(6, doc="number of sides") class HexFlangeNut(FemaleFastenerPart): edges = PositiveInt(6, doc="number of sides") chamfer_base = Boolean(False, doc="if chamfer is set, base edges are chamfered") washer = Boolean(True, doc="if True, washer created at base")
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/female.py
src/cqparts_fasteners/female.py
from .params import * from .solidtypes.fastener_heads.driven import DrivenFastenerHead from cqparts.params import * class FemaleFastenerPart(DrivenFastenerHead): """ Female fastener part; with an internal thread. A female fastener part can only be externally driven, which is why this object inherits from :class:`DrivenFastenerHead`. .. doctest:: from cqparts_fasteners.female import FemaleFastenerPart from cqparts.display import display nut = FemaleFastenerPart() display(nut) # doctest: +SKIP .. image:: /_static/img/fastenerpart/female.default.png You can also simplify the internal thread for rendering purposes with:: nut.thread._simple = True .. image:: /_static/img/fastenerpart/female.default.simple.png Instances of this class can also be customized during instantiation. For example:: nut = FemaleFastenerPart( width=8.1, # distance between parallel edges edges=6, # hex bolt washer=True, # washer as part of the bolt washer_diameter=11, washer_height=0.5, chamfer_base=False, # don't chamfer under the washer thread=('triangular', { 'diameter': 6, 'diameter_core': 4.5, 'pitch': 1.3, 'angle': 20, }), ) display(nut) .. image:: /_static/img/fastenerpart/female.hex_flange.png """ width = PositiveFloat(8, doc="width of tool reqiured to fasten nut") height = PositiveFloat(3, doc="height of nut") chamfer_top = Boolean(True, doc="if chamfer is set, top edges are chamfered") chamfer_base = Boolean(True, doc="if chamfer is set, base edges are chamfered") thread = ThreadType( default=('iso68', { # M5 'diameter': 5, 'pitch': 0.5, }), doc="thread type and parameters", ) def initialize_parameters(self): super(FemaleFastenerPart, self).initialize_parameters() # force thread parameters self.thread.inner = True self.thread.length = self.height + 0.001 if self._simple: # if nut is simplified, thread must also be simplified self.thread._simple = True def make(self): # mirror inherited object nut = super(FemaleFastenerPart, self).make() \ .rotate((0, 0, 0), (1, 0, 0), 180) # +z direction is maintained for male & female parts, but the object # resides on the opposite side of the XY plane # Cut thread thread = self.thread.local_obj.translate((0, 0, -self.height)) nut = nut.cut(thread) return nut def make_simple(self): return super(FemaleFastenerPart, self).make_simple() \ .rotate((0, 0, 0), (1, 0, 0), 180) def make_cutter(self): return super(FemaleFastenerPart, self).make_cutter() \ .rotate((0, 0, 0), (1, 0, 0), 180)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/__init__.py
src/cqparts_fasteners/__init__.py
""" Copyright 2018 Peter Boin 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. """ # =========================== Package Information =========================== # Version Planning: # 0.1.x - Development Status :: 2 - Pre-Alpha # 0.2.x - Development Status :: 3 - Alpha # 0.3.x - Development Status :: 4 - Beta # 1.x - Development Status :: 5 - Production/Stable # <any above>.y - developments on that version (pre-release) # <any above>*.dev* - development release (intended purely to test deployment) __version__ = '0.1.0' __title__ = 'cqparts_fasteners' __description__ = 'Nuts, Bolts and Screws content library for cqparts' __url__ = 'https://github.com/fragmuffin/cqparts/tree/master/src/cqparts_fasteners' __author__ = 'Peter Boin' __email__ = 'peter.boin+cqparts@gmail.com' __license__ = 'Apache Public License 2.0' __keywords__ = ['cadquery', 'cad', '3d', 'modeling', 'fasteners'] __package_data__ = ['catalogue/*.json'] # =========================== Functional =========================== __all__ = [ 'utils', 'fasteners', ] from . import utils from . import fasteners
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/screws.py
src/cqparts_fasteners/screws.py
from cqparts.params import * from .male import MaleFastenerPart from .params import HeadType, DriveType, ThreadType from .solidtypes import threads import logging log = logging.getLogger(__name__) class Screw(MaleFastenerPart): """ Part representing a single screw """ head = HeadType( default=('countersunk', { 'diameter': 9.5, 'height': 3.5, }), doc="head type and parameters" ) drive = DriveType( default=('phillips', { 'diameter': 5.5, 'depth': 2.5, 'width': 1.15, }), doc="screw drive type and parameters" ) thread = ThreadType( default=('triangular', { 'diameter': 5, 'pitch': 2, 'angle': 20, }), doc="thread type and parameters", ) neck_taper = FloatRange(0, 90, 15, doc="angle of neck's taper (0 is parallel with neck)") neck_length = PositiveFloat(7.5, doc="length of neck") length = PositiveFloat(25, doc="screw's length") tip_length = PositiveFloat(5, doc="length of taper on a pointed tip")
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/male.py
src/cqparts_fasteners/male.py
from math import tan, radians import cadquery import cqparts from cqparts.params import * from cqparts.utils import CoordSystem from .solidtypes import threads from .params import * import logging log = logging.getLogger(__name__) class MaleFastenerPart(cqparts.Part): r""" Male fastener part; with an external thread :: _________ __ head height | \/ \/ | z=0 __ _________ |_/\___/\_| __ z=0 (on x/y plane, +z is up) \ / | | head height __ \ / | | | | | | __ neck length (excludes taper) -\---/- -\---/- -|---|- -|---|- -|---|- -|---|- -|---|- -|---|- __ tip (length from bottom) -\---/- -\---/- \_/ \_/ __ length .. warning:: Tip thread tapering has not been implemented, except in the simplified model. This part can be heavily customized to match many common fastener male parts you'll find. The default is a 4.5mm long M3 screw, with a pan head and phillips screw drive: .. doctest:: from cqparts_fasteners.male import MaleFastenerPart from cqparts.display import display male = MaleFastenerPart() display(male) # doctest: +SKIP .. figure:: /_static/img/fastenerpart/male.default.png (literally the first screw I found on my desk) To simplify rendering, we can also simplify the thread with:: male = MaleFastenerPart() male.thread._simple = True display(male) .. image:: /_static/img/fastenerpart/male.default.simple.png This class can be heavily customized during instantiation. For the first example, we can make a screw with a countersunk head, and a neck. .. doctest:: screw = MaleFastenerPart( head=('countersunk_raised', { 'diameter': 8, # mm 'height': 3.5, 'raised': 2, }), drive=('french_recess', { 'diameter': 4, 'depth': 3.5, 'width': 1, }), thread=('triangular', { 'diameter': 4, 'angle': 40, 'pitch': 2.2, }), neck_diam=4.2, neck_length=5, neck_taper=45, length=12, tip_length=2, _render={'alpha': 0.5}, ) display(screw) # doctest: +SKIP .. image:: /_static/img/fastenerpart/male.custom01.png We can also make a bolt. .. doctest:: bolt = MaleFastenerPart( head=('hex_flange', { 'width': 10, 'height': 5.3, 'washer_diameter': 15, 'washer_height': 1.5, }), drive=None, thread=('ball_screw', { 'diameter': 6, 'ball_radius': 1, 'pitch': 5, }), neck_length=12, neck_taper=20, length=20, _render={'alpha': 0.5} ) display(bolt) # doctest: +SKIP .. image:: /_static/img/fastenerpart/male.custom02.png Although this won't create *every* bolt or screw you find, it's a good starting point. """ length = PositiveFloat(4.5, doc="length from xy plane to tip") neck_length = PositiveFloat(0, doc="length of neck, includes taper") neck_taper = FloatRange(0, 90, 30, doc="angle of neck's taper (90 is perpendicular to neck)") neck_diam = PositiveFloat(None, doc="neck radius, defaults to thread's outer radius") tip_length = PositiveFloat(0, doc="length of taper on a pointed tip") tip_diameter = PositiveFloat(None, doc="diameter of tip's point") head = HeadType( default=('pan', { 'diameter': 5.2, 'height': 2.0, 'fillet': 1.0, }), doc="head type and parameters", ) drive = DriveType( default=('phillips', { 'diameter': 3, 'depth': 2.0, 'width': 0.6, }), doc="screw drive type and parameters", ) thread = ThreadType( default=('iso68', { # M3 'diameter': 3.0, 'pitch': 0.35, }), doc="thread type and parameters", ) def initialize_parameters(self): (inner_radius, outer_radius) = self.thread.get_radii() if self.neck_length and (not self.neck_diam): self.neck_diam = outer_radius * 2 if self.tip_length and (self.tip_diameter is None): self.tip_diameter = outer_radius / 5 # thread offset ensures a small overlap with mating surface face_z_offset = self.head.get_face_offset()[2] thread_offset = 0 cmp = lambda a, b: (a > b) - (a < b) # necessary for py3.x if not self.neck_length: thread_offset = [face_z_offset - 0.01, -0.01, 0.01][cmp(face_z_offset, 0)+1] # build Thread (and union it to to the head) if self.length <= self.neck_length: raise ValueError("screw's neck (%g) is longer than the thread (%g)" % ( self.neck_length, self.length, )) # (change thread's length before building... not the typical flow, but # it works all the same) self.thread.length = (self.length - self.neck_length) + thread_offset self.local_obj = None # clear to force build after parameter change def make(self): # build Head obj = self.head.make() # (screw drive indentation is made last) # build neck (inner_radius, outer_radius) = self.thread.get_radii() if self.neck_length: # neck neck = cadquery.Workplane( 'XY', origin=(0, 0, -self.neck_length) ).circle(self.neck_diam / 2).extrude(self.neck_length) obj = obj.union(neck) # neck -> taper to thread's inner radius taper_length = 0 if 0 < self.neck_taper < 90: taper_length = ((self.neck_diam / 2) - inner_radius) / tan(radians(self.neck_taper)) if taper_length > 0: neck_taper = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeCone( radius1=(self.neck_diam / 2), radius2=inner_radius, height=taper_length, dir=cadquery.Vector(0,0,-1), )).translate((0, 0, -self.neck_length)) ) obj = obj.union(neck_taper) # build thread thread = self.thread.local_obj.translate((0, 0, -self.length)) obj = obj.union(thread) # Sharpen to a point if self.tip_length: # create "cutter" tool shape tip_cutter = cadquery.Workplane('XY').box( (outer_radius * 2) + 10, (outer_radius * 2) + 10, self.tip_length, centered=(True, True, False), ) tip_template = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeCone( radius1=(self.tip_diameter / 2), radius2=outer_radius, height=self.tip_length, dir=cadquery.Vector(0,0,1), )) ) tip_cutter = tip_cutter.cut(tip_template) # move & cut obj.cut(tip_cutter.translate((0, 0, -self.length))) # apply screw drive (if there is one) if self.drive: obj = self.drive.apply(obj, world_coords=CoordSystem(origin=self.head.get_face_offset()) ) return obj #def make_simple(self): # pass def make_cutter(self): """ Makes a shape to be used as a negative; it can be cut away from other shapes to make a perfectly shaped pocket for this part. For example, for a countersunk screw with a neck, the following cutter would be generated. .. image:: /_static/img/fastenerpart/male.cutter.png If the head were an externally driven shape (like a hex bolt), then the cutter's head would be wide enough to accommodate a tool to fasten it. """ # head obj = self.head.make_cutter() # neck if self.neck_length: # neck cut diameter (if thread is larger than the neck, thread must fit through) (inner_radius, outer_radius) = self.thread.get_radii() neck_cut_radius = max(outer_radius, self.neck_diam / 2) neck = cadquery.Workplane( 'XY', origin=(0, 0, -self.neck_length) ).circle(neck_cut_radius).extrude(self.neck_length) obj = obj.union(neck) # thread (pilot hole) pilot_hole = self.thread.make_pilothole_cutter() \ .translate((0, 0, -self.length)) obj = obj.union(pilot_hole) return obj
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/catalogue/scripts/boltdepot.py
src/cqparts_fasteners/catalogue/scripts/boltdepot.py
#!/usr/bin/env python import os import sys import inspect import scrapy import scrapy.crawler import scrapy.exporters import re import argparse import logging import fnmatch import json import csv import itertools import six import progressbar # cqparts import cqparts # cqparts_fasteners import cqparts_fasteners import cqparts_fasteners.screws import cqparts_fasteners.bolts import cqparts_fasteners.nuts import cqparts_fasteners.solidtypes from cqparts_fasteners.solidtypes.fastener_heads import find as find_head from cqparts_fasteners.solidtypes.screw_drives import find as find_drive from cqparts_fasteners.solidtypes.threads import find as find_thread # ---------- Constants ---------- STORE_NAME = 'BoltDepot' STORE_URL = 'https://www.boltdepot.com' # ---------- Utilities ---------- def split_url(url): match = re.search(r'^(?P<base>.*)\?(?P<params>.*)$', url, flags=re.I) return ( match.group('base'), {k: v for (k, v) in (p.split('=') for p in match.group('params').split('&'))} ) def join_url(base, params): return "{base}?{params}".format( base=base, params='&'.join('%s=%s' % (k, v) for (k, v) in params.items()), ) def utf8encoded(d): return {k.encode('utf-8'): v.encode('utf-8') for (k, v) in d.items()} def us2mm(value): if isinstance(value, six.string_types): # valid string formats include: # 1-3/4", 1/2", -5/9", 17/64", 1", 0.34", .34", 6ft match = re.search( r'''^ (?P<neg>-)? (?P<whole>(\d+)?(\.\d+)?)?? -? ((?P<numerator>\d+)/(?P<denominator>\d+))? \s*(?P<unit>("|ft)) $''', value, flags=re.MULTILINE | re.VERBOSE, ) # calculate value (as decimal quantity) value = float(match.group('whole') or 0) + ( float(match.group('numerator') or 0) / \ float(match.group('denominator') or 1) ) if match.group('neg'): value *= -1 if match.group('unit') == 'ft': value *= 12 else: # numeric value given: # assumption: value given in inches pass return value * 25.4 def mm2mm(value): if isinstance(value, six.string_types): # valid string formats include: # 1mm, -4mm, -0.3mm, -.3mm, 1m match = re.search(r'^(?P<value>[\-0-9\.]+)\s*(?P<unit>(mm|m|))$', value.lower()) value = float(match.group('value')) if match.group('unit') == 'm': value *= 1000 return float(value) UNIT_FUNC_MAP = { 'metric': mm2mm, 'us': us2mm, } def unit2mm(value, unit): unit = unit.strip().lower() if unit in UNIT_FUNC_MAP: return UNIT_FUNC_MAP[unit](value) else: raise ValueError("invalid unit: %r" % unit) # ---------- Scraper Spiders ---------- class BoltDepotSpider(scrapy.Spider): prefix = '' # no prefix by default name = None # no name, should raise exception if not set FEED_URI = "%(prefix)sscrape-%(name)s.json" @classmethod def get_feed_uri(cls): return cls.FEED_URI % {k: getattr(cls, k) for k in dir(cls)} @classmethod def get_data(cls): if not hasattr(cls, '_data'): with open(cls.get_feed_uri(), 'r') as fh: setattr(cls, '_data', json.load(fh)) return cls._data @classmethod def get_data_item(cls, key, criteria=lambda i: True, cast=lambda v: v): # utility function to get data out of a json dict list easily valid_data = [] for item in cls.get_data(): if criteria(item): try: valid_data.append(cast(item[key])) except AttributeError: raise ValueError("%r value %r invalid (cannot be cast)" % (key, item[key])) assert len(valid_data) == 1, "%r" % valid_data return valid_data[0] class BoltDepotProductSpider(BoltDepotSpider): # criteria added to every cqparts.catalogue.JSONCatalogue entry common_catalogue_criteria = { 'store': STORE_NAME, 'store_url': STORE_URL, } def parse(self, response): # Look for : Product catalogue table product_catalogue = response.css('table.product-catalog-table') if product_catalogue: for catalogue_link in product_catalogue.css('li a'): next_page_url = catalogue_link.css('::attr("href")').extract_first() yield response.follow(next_page_url, self.parse) # Look for : Product list table product_list = response.css('#product-list-table') if product_list: for product in product_list.css('td.cell-prod-no'): next_page_url = product.css('a::attr("href")').extract_first() yield response.follow(next_page_url, self.parse_product_detail) def parse_product_detail(self, response): heading = response.css('#catalog-header-title h1::text').extract_first() print("Product: %s" % heading) sys.stdout.flush() (url_base, url_params) = split_url(response.url) # details table detail_table = response.css('#product-property-list') details = {} for row in detail_table.css('tr'): key = row.css('td.name span::text').extract_first() value = row.css('td.value span::text').extract_first() if key and value: (key, value) = (key.strip('\n\r\t '), value.strip('\n\r\t ')) if key and value: details[key] = value product_data = { 'id': url_params['product'], 'name': heading, 'url': response.url, 'details': details, } # Image url image_url = response.css('.catalog-header-product-image::attr("src")').extract_first() if image_url: product_data.update({'image_url': image_url}) yield product_data # --- cqparts catalogue building specific functions # These functions are kept with the spider as a means to encapsulate # component-specific logic. @classmethod def add_to_catalogue(cls, data, catalogue): criteria = cls.item_criteria(data) criteria.update(cls.common_catalogue_criteria) criteria.update({'scraperclass': cls.__name__}) catalogue.add( id=data['id'], obj=cls.build_component(data), criteria=criteria, _check_id=False, ) @classmethod def item_criteria(cls, data): return {} # should be overridden @classmethod def build_component(cls, data): from cqparts_misc.basic.primatives import Cube return Cube() # should be overridden CATALOGUE_URI = "%(prefix)s%(name)s.json" CATALOGUE_CLASS = cqparts.catalogue.JSONCatalogue @classmethod def get_catalogue_uri(cls): filename = cls.CATALOGUE_URI % {k: getattr(cls, k) for k in dir(cls)} return os.path.join('..', filename) @classmethod def get_catalogue(cls, **kwargs): return cls.CATALOGUE_CLASS(cls.get_catalogue_uri(), **kwargs) @classmethod def get_item_str(cls, data): return "[%(id)s] %(name)s" % data class WoodScrewSpider(BoltDepotProductSpider): name = 'woodscrews' start_urls = [ 'https://www.boltdepot.com/Wood_screws_Phillips_flat_head.aspx', 'https://www.boltdepot.com/Wood_screws_Slotted_flat_head.aspx', ] @classmethod def item_criteria(cls, data): criteria = { 'name': data['name'], 'url': data['url'], } criteria_content = [ # (<key>, <header>), ... ('units', 'Units:'), ('diameter', 'Diameter:'), ('material', 'Material:'), ('plating', 'Plating:'), ] for (key, header) in criteria_content: value = data['details'].get(header, None) if value is not None: criteria[key] = value.lower() return criteria @classmethod def build_component(cls, data): details = data['details'] # --- Head head = None if details['Head style:'] == 'Flat': # countersunk head_diam = ( # averaged min/max unit2mm(details['Head diameter Min:'], details['Units:']) + \ unit2mm(details['Head diameter Max:'], details['Units:']) ) / 2 head = find_head(name='countersunk')( diameter=head_diam, bugle=False, raised=0, # TODO: details['Head angle:'] usually 82deg ) else: raise ValueError("head style %r not supported" % details['Head style:']) # --- Drive drive = None if details['Drive type:'] == 'Phillips': # FIXME: use actual drive sizes from DataPhillipsDriveSizes to shape drive = find_drive(name='phillips')( diameter=head_diam * 0.6 ) elif details['Drive type:'] == 'Slotted': drive = find_drive(name='slot')( diameter=head_diam, ) else: raise ValueError("drive type %r not supported" % details['Drive type:']) # --- Thread # Accuracy is Questionable: # Exact screw thread specs are very difficult to find, so some # of this is simply observed from screws I've salvaged / bought. thread_diam = DataWoodScrewDiam.get_data_item( 'Decimal', criteria=lambda i: i['Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) thread = find_thread(name='triangular')( diameter=thread_diam, pitch=thread_diam * 0.6, ) # --- Build screw screw_length = unit2mm(details['Length:'], details['Units:']) screw = cqparts_fasteners.screws.Screw( drive=drive, head=head, thread=thread, length=screw_length, neck_length=screw_length * 0.25, tip_length=1.5 * thread_diam, ) return screw class BoltSpider(BoltDepotProductSpider): name = 'bolts' start_urls = [ 'https://www.boltdepot.com/Hex_bolts_2.aspx', 'https://www.boltdepot.com/Metric_hex_bolts_2.aspx', ] @classmethod def item_criteria(cls, data): criteria = { 'name': data['name'], 'url': data['url'], } criteria_content = [ # (<key>, <header>), ... ('units', 'Units:'), ('diameter', 'Diameter:'), ('material', 'Material:'), ('plating', 'Plating:'), ('finish', 'Finish:'), ('color', 'Color:'), ] for (key, header) in criteria_content: value = data['details'].get(header, None) if value is not None: criteria[key] = value.lower() return criteria @classmethod def build_component(cls, data): details = data['details'] # --- Thread thread = None thread_diam = unit2mm(details['Diameter:'], details['Units:']) if details['Units:'].lower() == 'us': thread_pitch = unit2mm(1, 'us') / int(details['Thread count:']) elif details['Units:'].lower() == 'metric': thread_pitch = unit2mm(details['Thread pitch:'], details['Units:']) # ISO 68 thread: not accurate for imperial bolts, but close enough # FIXME: imperial threads? thread = find_thread(name='iso68')( diameter=thread_diam, pitch=thread_pitch, lefthand=details['Thread direction:'] == 'Left hand', ) # --- Head head = None if details['Head style:'].lower() == 'hex': # countersunk # Width Across Flats try: if details['Units:'].lower() == 'us': across_flats = DataUSBoltHeadSize.get_data_item( 'Hex Bolt - Lag Bolt - Square Bolt', criteria=lambda i: i['Bolt Diameter'] == details['Diameter:'], cast=lambda v: DataUSBoltHeadSize.unit_cast(v), ) elif details['Units:'].lower() == 'metric': try: across_flats = DataMetricBoltHeadSize.get_data_item( 'ANSI/ISO', criteria=lambda i: i['Bolt Diameter (mm)'] == ("%g" % unit2mm(details['Diameter:'], 'metric')), cast=lambda v: unit2mm(v, 'metric'), ) except (ValueError, AttributeError): # assumption: 'ANSI/ISO' field is non-numeirc, use 'DIN' instead across_flats = DataMetricBoltHeadSize.get_data_item( 'DIN', criteria=lambda i: i['Bolt Diameter (mm)'] == ("%g" % unit2mm(details['Diameter:'], 'metric')), cast=lambda v: unit2mm(v, 'metric'), ) else: raise ValueError('unsupported units %r' % details['Units:']) except (AssertionError, AttributeError): # assumption: table lookup unsuccessful, see if it's explicitly specified across_flats = unit2mm(details['Width across the flats:'], details['Units:']) # raises KeyError if 'Width across the flats:' is not specified # Head Height head_height = 0.63 * thread_diam # average height of all bolts with a defined head height head = find_head(name='hex')( width=across_flats, height=head_height, washer=False, # TODO: details['Head angle:'] usually 82deg ) else: raise ValueError("head style %r not supported" % details['Head style:']) # --- Build bolt length = unit2mm(details['Length:'], details['Units:']) # Neck & Thread length neck_len = None try: neck_len = unit2mm(details['Body length Min:'], details['Units:']) except KeyError: pass # 'Body length Min:' not specified thread_len = length try: thread_len = unit2mm(details['Thread length Min:'], details['Units:']) if neck_len is None: neck_len = length - thread_len else: neck_len = (neck_len + (length - thread_len)) / 2 except KeyError: if neck_len is None: neck_len = 0 bolt = cqparts_fasteners.bolts.Bolt( head=head, thread=thread, length=length, neck_length=neck_len, ) return bolt class NutSpider(BoltDepotProductSpider): name = 'nuts' start_urls = [ 'https://www.boltdepot.com/Hex_nuts.aspx', 'https://www.boltdepot.com/Square_nuts.aspx', 'https://www.boltdepot.com/Metric_hex_nuts.aspx', ] @classmethod def item_criteria(cls, data): criteria = { 'name': data['name'], 'url': data['url'], } criteria_content = [ # (<key>, <header>), ... ('units', 'Units:'), ('diameter', 'Diameter:'), ('material', 'Material:'), ('plating', 'Plating:'), ('finish', 'Finish:'), ('color', 'Color:'), ] for (key, header) in criteria_content: value = data['details'].get(header, None) if value is not None: criteria[key] = value.lower() return criteria @classmethod def build_component(cls, data): details = data['details'] # --- Thread thread = None # diameter try: thread_diam = unit2mm(details['Diameter:'], details['Units:']) except AttributeError: # assumption: non-numeric diameter if details['Units:'] == 'US': thread_diam = DataUSThreadSize.get_data_item( 'Decimal', criteria=lambda i: i['Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) else: raise # pitch if details['Units:'].lower() == 'us': thread_pitch = unit2mm(1, 'us') / int(details['Thread count:']) elif details['Units:'].lower() == 'metric': thread_pitch = unit2mm(details['Thread pitch:'], details['Units:']) # ISO 68 thread: not accurate for imperial bolts, but close enough # FIXME: imperial threads? thread = find_thread(name='iso68')( diameter=thread_diam, pitch=thread_pitch, lefthand=details['Thread direction:'] == 'Left hand', inner=True, ) # --- build nut try: nut_width = unit2mm(details['Width across the flats:'], details['Units:']) except KeyError: # assumption: 'Width across the flats:' not supplied if details['Units:'] == 'US': try: nut_width = DataUSNutSize.get_data_item( 'Diameter*:Hex Nut', criteria=lambda i: i['Size:Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) except ValueError: nut_width = DataUSNutSize.get_data_item( 'Diameter*:Machine Screw Nut', # only use if 'Hex Nut' not available criteria=lambda i: i['Size:Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) else: raise # height try: nut_height = unit2mm(details['Height:'], details['Units:']) except KeyError: # assumption: 'Height:' not specified if details['Units:'] == 'US': try: nut_height = DataUSNutSize.get_data_item( 'Height:Hex Nut', criteria=lambda i: i['Size:Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) except ValueError: nut_height = DataUSNutSize.get_data_item( 'Height:Machine Screw Nut', # only use if 'Hex Nut' not available criteria=lambda i: i['Size:Size'] == details['Diameter:'], cast=lambda v: unit2mm(v, 'us'), ) else: raise if details['Subcategory:'] == 'Hex nuts': nut_class = cqparts_fasteners.nuts.HexNut elif details['Subcategory:'] == 'Square nuts': nut_class = cqparts_fasteners.nuts.SquareNut else: raise ValueError("unsupported nut class %r" % details['Subcategory:']) nut = nut_class( thread=thread, width=nut_width, height=nut_height, washer=False, ) return nut SPIDERS = [ WoodScrewSpider, BoltSpider, NutSpider, ] SPIDER_MAP = { cls.name: cls for cls in SPIDERS } class GrowingList(list): """ A list that will automatically expand if indexed beyond its limit. (the list equivalent of collections.defaultdict) """ def __init__(self, *args, **kwargs): self._default_type = kwargs.pop('default_type', lambda: None) super(GrowingList, self).__init__(*args, **kwargs) def __getitem__(self, index): if index >= len(self): self.extend([self._default_type() for i in range(index + 1 - len(self))]) return super(GrowingList, self).__getitem__(index) def __setitem__(self, index, value): if index >= len(self): self.extend([self._default_type() for i in range(index + 1 - len(self))]) super(GrowingList, self).__setitem__(index, value) class BoltDepotDataSpider(BoltDepotSpider): # set to True if the last header row does not uniquely identify each column merge_headers = False @staticmethod def table_data(table): # Pull data out of a table into a 2d list. # Merged Cells: # any merged cells (using rowspan / colspan) will have duplicate # data over each cell. # "merging cells does not a database make" said me, just now def push_data(row, i, val): # push data into next available slot in the given list # return the index used (will be >= i) assert isinstance(row, GrowingList), "%r" % row assert val is not None try: while row[i] is not None: i += 1 except IndexError: pass row[i] = val return i data = GrowingList(default_type=GrowingList) # nested growing list header_count = 0 for (i, row) in enumerate(table.css('tr')): j = 0 is_header_row = True for cell in row.css('th, td'): # cell data value = ' '.join([v.strip() for v in cell.css('::text').extract()]) if value is None: value = '' value = value.rstrip('\r\n\t ') rowspan = int(cell.css('::attr("rowspan")').extract_first() or 1) colspan = int(cell.css('::attr("colspan")').extract_first() or 1) # is header row? if cell.root.tag != 'th': is_header_row = False # populate data (duplicate merged content) j = push_data(data[i], j, value) for di in range(rowspan): for dj in range(colspan): data[i + di][j + dj] = value j += 1 if is_header_row: header_count += 1 return (data, header_count) def parse(self, response): table = response.css('table.fastener-info-table') (data, header_count) = self.table_data(table) if self.merge_headers: header = [ # join all headers per column ':'.join(data[i][j] for i in range(header_count)) for j in range(len(data[0])) ] else: header = data[header_count - 1] # last header row for row in data[header_count:]: row_data = dict(zip(header, row)) if any(v for v in row_data.values()): # don't yield if there's no data yield row_data class DataWoodScrewDiam(BoltDepotDataSpider): name = 'd-woodscrew-diam' start_urls = [ 'https://www.boltdepot.com/fastener-information/Wood-Screws/Wood-Screw-Diameter.aspx', ] class DataUSBoltThreadLen(BoltDepotDataSpider): name = 'd-us-bolt-thread-len' start_urls = [ 'https://www.boltdepot.com/fastener-information/Bolts/US-Thread-Length.aspx', ] class DataUSThreadPerInch(BoltDepotDataSpider): name = 'd-us-tpi' start_urls = [ 'https://www.boltdepot.com/fastener-information/Measuring/US-TPI.aspx', ] class DataUSBoltHeadSize(BoltDepotDataSpider): name = 'd-us-boltheadsize' start_urls = [ 'https://www.boltdepot.com/fastener-information/Bolts/US-Bolt-Head-Size.aspx', ] @staticmethod def unit_cast(value): # special case for the '7/16" or 3/8"' cell return unit2mm(re.split('\s*or\s*', value)[-1], 'us') # last value class DataUSNutSize(BoltDepotDataSpider): name = 'd-us-nutsize' start_urls = [ 'https://www.boltdepot.com/fastener-information/Nuts-Washers/US-Nut-Dimensions.aspx', ] merge_headers = True # header 'Hex Nut' is repeated class DataUSThreadSize(BoltDepotDataSpider): name = 'd-us-threadsize' start_urls = [ 'https://www.boltdepot.com/fastener-information/Machine-Screws/Machine-Screw-Diameter.aspx', ] class DataMetricThreadPitch(BoltDepotDataSpider): name = 'd-met-threadpitch' start_urls = [ 'https://www.boltdepot.com/fastener-information/Measuring/Metric-Thread-Pitch.aspx', ] class DataMetricBoltHeadSize(BoltDepotDataSpider): name = 'd-met-boltheadsize' start_urls = [ 'https://www.boltdepot.com/fastener-information/Bolts/Metric-Bolt-Head-Size.aspx', ] class DataPhillipsDriveSizes(BoltDepotDataSpider): name = 'd-drivesizes-phillips' start_urls = [ 'https://www.boltdepot.com/fastener-information/Driver-Bits/Phillips-Driver-Sizes.aspx', ] METRICS_SPIDERS = [ DataWoodScrewDiam, DataUSBoltThreadLen, DataUSThreadPerInch, DataUSBoltHeadSize, DataUSNutSize, DataUSThreadSize, DataMetricThreadPitch, DataMetricBoltHeadSize, DataPhillipsDriveSizes, ] # ---------- Command-line Arguments Parser ---------- DEFAULT_PREFIX = os.path.splitext(os.path.basename( os.path.abspath(inspect.getfile(inspect.currentframe())) ))[0] + '-' parser = argparse.ArgumentParser( description='Build Bolt Depot catalogue by crawling their website', epilog=""" Actions: scrape scrape product details from website csv convert scraped output to csv [optional] build builds catalogue from scraped data all (run all above actions) Note: Actions will always be performed in the order shown above, even if they're not listed in that order on commandline. """, formatter_class=argparse.RawTextHelpFormatter, ) VALID_ACTIONS = set(['scrape', 'csv', 'build', 'all']) def action_type(value): value = value.lower() if value not in VALID_ACTIONS: raise argparse.ArgumentError() return value parser.add_argument( 'actions', metavar='action', type=action_type, nargs='*', help='action(s) to perform' ) # Scraper arguments parser.add_argument( '--prefix', '-p', dest='prefix', default=DEFAULT_PREFIX, help="scraper file prefix (default: '%s')" % DEFAULT_PREFIX, ) parser.add_argument( '--onlymetrics', '-om', dest='onlymetrics', action='store_const', const=True, default=False, help="if set, when scraping, only metrics data is scraped" ) # Catalogues parser.add_argument( '--list', '-l', dest='list', default=False, action='store_const', const=True, help="list catalogues to build", ) def catalogues_list_type(value): catalogues_all = set(SPIDER_MAP.keys()) catalogues = set() for filter_str in value.split(','): catalogues |= set(fnmatch.filter(catalogues_all, filter_str)) return sorted(catalogues) parser.add_argument( '--catalogues', '-c', dest='catalogues', type=catalogues_list_type, default=catalogues_list_type('*'), help="csv list of catalogues to act on", ) parser.add_argument( '--strict', '-s', dest='strict', default=False, action='store_const', const=True, help="if set, exceptions during a build stop progress", ) args = parser.parse_args() args.actions = set(args.actions) # convert to set BoltDepotSpider.prefix = args.prefix # list catalogues & exit if args.list: print("Catalogues:") for name in args.catalogues: print(" - %s" % name) exit(0) # no actions, print help & exit if not args.actions: parser.print_help() exit(1) # ----- Start Crawl ----- if {'all', 'scrape'} & args.actions: print("----- Scrape: %s (+ metrics)" % (', '.join(args.catalogues))) sys.stdout.flush() # --- Clear feed files feed_names = [] if not args.onlymetrics: feed_names += args.catalogues feed_names += [cls.name for cls in METRICS_SPIDERS] for name in feed_names: feed_filename = BoltDepotSpider.FEED_URI % { 'prefix': args.prefix, 'name': name, } if os.path.exists(feed_filename): os.unlink(feed_filename) # remove feed file to populate from scratch # --- Create Crawlers process = scrapy.crawler.CrawlerProcess( settings={ 'LOG_LEVEL': logging.INFO, 'FEED_FORMAT': "json", 'FEED_URI': BoltDepotSpider.FEED_URI, }, ) # product crawlers if not args.onlymetrics: for name in args.catalogues: process.crawl(SPIDER_MAP[name]) # metrics crawlers for metrics_spider in METRICS_SPIDERS: process.crawl(metrics_spider) # --- Start Scraping process.start() # ----- Convert to CSV ----- # Conversion of json files to csv is optional, csv's are easy to open # in a 3rd party application to visualise the data that was scraped. if {'all', 'csv'} & args.actions: def flatten_dict(dict_in): # flatten nested dicts using '.' separated keys def inner(d, key_prefix=''): for (k, v) in d.items(): if isinstance(v, dict): for (k1, v1) in inner(v, k + '.'): yield (k1, v1) else: yield (key_prefix + k, v) return dict(inner(dict_in)) for cls in itertools.chain([SPIDER_MAP[n] for n in args.catalogues], METRICS_SPIDERS): print("----- CSV: %s" % cls.name) feed_json = cls.get_feed_uri() feed_csv = "%s.csv" % os.path.splitext(feed_json)[0] print(" %s --> %s" % (feed_json, feed_csv)) data = cls.get_data() # pull out all possible keys to build header row headers = set(itertools.chain(*[ tuple(str(k) for (k, v) in flatten_dict(row).items()) for row in data ])) # Write row by row with open(feed_csv, 'w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=headers) writer.writeheader() for rowdata in data: writer.writerow(utf8encoded(flatten_dict(rowdata))) # ----- Build Catalogues ----- if {'all', 'build'} & args.actions: for name in args.catalogues: cls = SPIDER_MAP[name] print("----- Build: %s" % name) catalogue_file = os.path.join( '..', "%s.json" % os.path.splitext(cls.get_feed_uri())[0] ) catalogue = cls.get_catalogue(clean=True) data = cls.get_data() sys.stdout.flush() # make sure prints come through before bar renders bar = progressbar.ProgressBar() for item_data in bar(data): try: cls.add_to_catalogue(item_data, catalogue) except Exception as e: print("couldn't add: %s" % cls.get_item_str(item_data)) print("%s: %s" % (type(e).__name__, e)) sys.stdout.flush() if args.strict: raise
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/catalogue/scripts/bunnings.py
src/cqparts_fasteners/catalogue/scripts/bunnings.py
#!/usr/bin/env python import os import inspect import scrapy import scrapy.crawler import scrapy.exporters import re import argparse import logging import fnmatch import json import csv # ---------- Utilities ---------- def split_url(url): match = re.search(r'^(?P<base>.*)\?(?P<params>.*)$', url, flags=re.I) return ( match.group('base'), {k: v for (k, v) in (p.split('=') for p in match.group('params').split('&'))} ) def join_url(base, params): return "{base}?{params}".format( base=base, params='&'.join('%s=%s' % (k, v) for (k, v) in params.items()), ) # ---------- Scraper Spiders ---------- class BunningsProductSpider(scrapy.Spider): def parse(self, response): """Parse pagenated list of products""" # Check if page is out of range no_more_products = re.search( r'No matching products were found', response.css('div.paged-results').extract_first(), flags=re.I ) if no_more_products: pass # no more pages to populate, stop scraping else: # Scrape products list for product in response.css('article.product-list__item'): product_url = product.css('a::attr("href")').extract_first() yield response.follow(product_url, self.parse_detail) (base, params) = split_url(response.url) params.update({'page': int(params.get('page', '1')) + 1}) next_page_url = join_url(base, params) self.logger.info(next_page_url) yield response.follow(next_page_url, self.parse) def parse_detail(self, response): """Parse individual product's detail""" # Product Information (a start) product_data = { 'url': response.url, 'name': response.css('div.page-title h1::text').extract_first(), } # Inventory Number inventory_number = re.search( r'(?P<inv_num>\d+)$', response.css('span.product-in::text').extract_first(), ).group('inv_num') product_data.update({'in': inventory_number}) # Specifications (arbitrary key:value pairs) specs_table = response.css('#tab-specs dl') for row in specs_table.css('div.spec-row'): keys = row.css('dt::text').extract() values = row.css('dd::text').extract() product_data.update({ key: value for (key, value) in zip(keys, values) }) self.logger.info(product_data['name']) yield product_data class ScrewSpider(BunningsProductSpider): name = 'screws' start_urls = [ 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/decking?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/batten?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/wood?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/metal-fix?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/chipboard?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/treated-pine?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/plasterboard?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/roofing?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/screws/general-purpose?page=1', ] class BoltSpider(BunningsProductSpider): name = 'bolts' start_urls = [ 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/bolts/cup-head-bolts?page=1', 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/bolts/hex-head-bolts?page=1', ] class NutSpider(BunningsProductSpider): name = 'nuts' start_urls = [ 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/bolts/nuts?page=1', ] class ThreadedRodSpider(BunningsProductSpider): name = 'threaded-rods' start_urls = [ 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/bolts/threaded-rod?page=1', ] class WasherSpider(BunningsProductSpider): name = 'washers' start_urls = [ 'https://www.bunnings.com.au/our-range/building-hardware/fixings-fasteners/bolts/washers?page=1', ] SPIDERS = [ ScrewSpider, BoltSpider, NutSpider, ThreadedRodSpider, WasherSpider, ] SPIDER_MAP = { cls.name: cls for cls in SPIDERS } # ---------- Command-line Arguments Parser ---------- DEFAULT_PREFIX = os.path.splitext(os.path.basename( os.path.abspath(inspect.getfile(inspect.currentframe())) ))[0] + '-' parser = argparse.ArgumentParser( description='Build Bunnings catalogue by crawling their website', epilog=""" WORK IN PROGRESS At this time, this script will scrape the Bunnings website for fasteners, however it will not create a catalogue. This is because there is not enough information on the website to accurately determine fastener geometry. Actions: scrape scrape product details from website csv convert scraped output to csv [optional] build builds catalogue from scraped data Note: Actions will always be performed in the order shown above, even if they're not listed in that order on commandline. """, formatter_class=argparse.RawTextHelpFormatter, ) VALID_ACTIONS = set(['scrape', 'csv', 'build']) def action_type(value): value = value.lower() if value not in VALID_ACTIONS: raise argparse.ArgumentError() return value parser.add_argument( 'actions', metavar='action', type=action_type, nargs='*', help='action(s) to perform' ) # Scraper arguments parser.add_argument( '--prefix', '-p', dest='prefix', default=DEFAULT_PREFIX, help="scraper file prefix (default: '%s')" % DEFAULT_PREFIX, ) # Catalogues parser.add_argument( '--list', '-l', dest='list', default=False, action='store_const', const=True, help="list catalogues to build", ) def catalogues_list_type(value): catalogues_all = set(SPIDER_MAP.keys()) catalogues = set() for filter_str in value.split(','): catalogues |= set(fnmatch.filter(catalogues_all, filter_str)) return sorted(catalogues) parser.add_argument( '--catalogues', '-c', dest='catalogues', type=catalogues_list_type, default=catalogues_list_type('*'), help="csv list of catalogues to act on", ) args = parser.parse_args() BunningsProductSpider.prefix = args.prefix # list catalogues & exit if args.list: for name in args.catalogues: print(name) exit(0) # no actions, print help & exit if not args.actions: parser.print_help() exit(1) FEED_URI = "%(prefix)sscrape-%(name)s.json" # ----- Start Crawl ----- if 'scrape' in args.actions: print("----- Scrape: %s" % (', '.join(args.catalogues))) # Clear feed files for name in args.catalogues: feed_filename = FEED_URI % { 'prefix': args.prefix, 'name': name, } if os.path.exists(feed_filename): os.unlink(feed_filename) # remove feed file to populate from scratch # Create Crawlers process = scrapy.crawler.CrawlerProcess( settings={ 'LOG_LEVEL': logging.INFO, 'FEED_FORMAT': "json", 'FEED_URI': FEED_URI, }, ) for name in args.catalogues: process.crawl(SPIDER_MAP[name]) # Start Scraping process.start() # ----- Convert to CSV ----- if 'csv' in args.actions: for name in args.catalogues: print("----- CSV: %s" % name) feed_json = FEED_URI % { 'prefix': args.prefix, 'name': name, } with open(feed_json, 'r') as json_file: data = json.load(json_file) # Pull out headers headers = set() for item in data: headers |= set(item.keys()) # Write Output def utf8encoded(d): return {k.encode('utf-8'): v.encode('utf-8') for (k, v) in d.items()} feed_csv = "%s.csv" % os.path.splitext(feed_json)[0] with open(feed_csv, 'w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=headers) writer.writeheader() for item in data: writer.writerow(utf8encoded(item)) # ----- Build Catalogues ----- def build_screw(row): # Required Parameters: # - drive # - # - head # - <countersunk> # - <> # - thread <triangular> # - diameter # - diameter_core (defaults to 2/3 diameter) # - pitch # - angle (defaults to 30deg) # - length # - neck_diam # - neck_length # - neck_taper # - tip_diameter # - tip_length pass if 'build' in args.actions: print("BUILD ACTION NOT IMPLEMENTED") print('\n'.join([ "The information on conventional commercial web-pages is too iratic and", "inaccurate to formulate a quality catalogue.", "At the time of writing this, I've abandoned this idea, (at least for the", "bunnings.com.au website anyway)" ]) + '\n') raise NotImplementedError("'build' action") #for name in args.catalogues: # print("----- Build: %s" % name)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/__init__.py
src/cqparts_fasteners/solidtypes/__init__.py
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/iso68.py
src/cqparts_fasteners/solidtypes/threads/iso68.py
import cadquery from math import pi, sin, cos, tan, sqrt from cqparts.params import * from .base import Thread, register @register(name='iso68') class ISO68Thread(Thread): """ .. image:: /_static/img/threads/iso68.png """ # rounding ratio: # 0.0 = no rounding; peaks and valeys are flat # 1.0 = fillet is flush with thread's edges # rounding is applied to: # - peak for inner threads # - valley for outer threads rounding_ratio = FloatRange(0, 1, 0.5) def build_profile(self): """ Build a thread profile in specified by ISO 68 .. image:: /_static/img/threads/iso68.profile.png """ # height of sawtooth profile (along x axis) # (to be trunkated to make a trapezoidal thread) height = self.pitch * cos(pi/6) # ISO 68 r_maj = self.diameter / 2 r_min = r_maj - ((5./8) * height) profile = cadquery.Workplane("XZ").moveTo(r_min, 0) # --- rising edge profile = profile.lineTo(r_maj, (5./16) * self.pitch) # --- peak if self.inner and (self.rounding_ratio > 0): # undercut radius (to fit flush with thread) # (effective radius will be altered by rounding_ratio) cut_radius = (self.pitch / 16) / cos(pi/6) # circle's center relative to r_maj cut_center_under_r_maj = (self.pitch / 16) * tan(pi/6) undercut_depth = self.rounding_ratio * (cut_radius - cut_center_under_r_maj) profile = profile.threePointArc( (r_maj + undercut_depth, (6./16) * self.pitch), (r_maj, (7./16) * self.pitch) ) else: profile = profile.lineTo(r_maj, (7./16) * self.pitch) # --- falling edge profile = profile.lineTo(r_min, (12./16) * self.pitch) # --- valley if self.inner and (self.rounding_ratio > 0): profile = profile.lineTo(r_min, self.pitch) else: # undercut radius (to fit flush with thread) # (effective radius will be altered by rounding_ratio) cut_radius = (self.pitch / 8) / cos(pi/6) # circle's center relative to r_maj cut_center_under_r_maj = (self.pitch / 8) * tan(pi/6) undercut_depth = self.rounding_ratio * (cut_radius - cut_center_under_r_maj) profile = profile.threePointArc( (r_min - undercut_depth, (14./16) * self.pitch), (r_min, self.pitch) ) return profile.wire() def get_radii(self): # irrespective of self.inner flag height = self.pitch * cos(pi/6) return ( (self.diameter / 2) - ((5./8) * height), # inner self.diameter / 2 # outer )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/__init__.py
src/cqparts_fasteners/solidtypes/threads/__init__.py
__all__ = [ 'Thread', 'register', 'find', 'search', # Thread Types 'ball_screw', 'iso68', 'triangular', ] from .base import Thread, register, find, search # Thread Types from . import ball_screw from . import iso68 from . import triangular
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/ball_screw.py
src/cqparts_fasteners/solidtypes/threads/ball_screw.py
import cadquery from cqparts.params import * from .base import Thread, register @register(name='ball_screw') class BallScrewThread(Thread): """ .. image:: /_static/img/threads/ball_screw.png """ ball_radius = Float(0.25, doc="ball's radius") def build_profile(self): """ .. image:: /_static/img/threads/ball_screw.profile.png """ profile = cadquery.Workplane("XZ") \ .moveTo(self.diameter / 2, self.pitch - self.ball_radius) # cylindrical face if (2 * self.ball_radius) < self.pitch: profile = profile.lineTo(self.diameter / 2, self.ball_radius) # rail for balls profile = profile.threePointArc( ((self.diameter / 2) - self.ball_radius, 0), (self.diameter / 2, -self.ball_radius) ) return profile.wire() def get_radii(self): return ( (self.diameter / 2) - self.ball_radius, # inner self.diameter / 2, # outer )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/base.py
src/cqparts_fasteners/solidtypes/threads/base.py
import six from math import ceil, sin, cos, pi import os import cadquery import FreeCAD import Part as FreeCADPart import cqparts from cqparts.params import * from cqparts.errors import SolidValidityError import logging log = logging.getLogger(__name__) # Creating a thread can be done in a number of ways: # - cross-section helical sweep # - can't be tapered # - profile helical sweep # - difficult (or impossible) to do without tiny gaps, and a complex # internal helical structure forming the entire thread # - negative profile helical sweep cut from cylinder # - expensive, helical sweept object is only used to do an expensive cut def profile_to_cross_section(profile, lefthand=False, start_count=1, min_vertices=20): r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is expected to be of 1 thread rotation, so it's height (along the Z-axis) is the thread's "pitch". If start_count > 1, then the profile will effectively be duplicated. The resulting cross-section is designed to be swept along a helical path with a pitch of the thread's "lead" (which is {the height of the given profile} * start_count) **Method:** Each edge of the profile is converted to a bezier spline, aproximating its polar plot equivalent. **Resolution:** (via `min_vertices` parameter) Increasing the number of vertices used to define the bezier will increase the resulting thread's accuracy, but cost more to render. min_vertices may also be expressed as a list to set the number of vertices to set for each wire. where: len(min_vertices) == number of edges in profile **Example** .. doctest:: import cadquery from cqparts_fasteners.solidtypes.threads.base import profile_to_cross_section from Helpers import show # doctest: +SKIP profile = cadquery.Workplane("XZ") \ .moveTo(1, 0) \ .lineTo(2, 1).lineTo(1, 2) \ .wire() cross_section = profile_to_cross_section(profile) show(profile) # doctest: +SKIP show(cross_section) # doctest: +SKIP Will result in: .. image:: /_static/img/solidtypes.threads.base.profile_to_cross_section.01.png :param profile: workplane containing wire of thread profile. :type profile: :class:`cadquery.Workplane` :param lefthand: if True, cross-section is made backwards. :type lefthand: :class:`bool` :param start_count: profile is duplicated this many times. :type start_count: :class:`int` :param min_vertices: int or tuple of the desired resolution. :type min_vertices: :class:`int` or :class:`tuple` :return: workplane with a face ready to be swept into a thread. :rtype: :class:`cadquery.Workplane` :raises TypeError: if a problem is found with the given parameters. :raises ValueError: if ``min_vertices`` is a list with elements not equal to the numbmer of wire edges. """ # verify parameter(s) if not isinstance(profile, cadquery.Workplane): raise TypeError("profile %r must be a %s instance" % (profile, cadquery.Workplane)) if not isinstance(min_vertices, (int, list, tuple)): raise TypeError("min_vertices %r must be an int, list, or tuple" % (min_vertices)) # get wire from Workplane wire = profile.val() # cadquery.Wire if not isinstance(wire, cadquery.Wire): raise TypeError("a valid profile Wire type could not be found in the given Workplane") profile_bb = wire.BoundingBox() pitch = profile_bb.zmax - profile_bb.zmin lead = pitch * start_count # determine vertices count per edge edges = wire.Edges() vertices_count = None if isinstance(min_vertices, int): # evenly spread vertices count along profile wire # (weighted by the edge's length) vertices_count = [ int(ceil(round(e.Length() / wire.Length(), 7) * min_vertices)) for e in edges ] # rounded for desired contrived results # (trade-off: an error of 1 is of no great consequence) else: # min_vertices is defined per edge (already what we want) if len(min_vertices) != len(edges): raise ValueError( "min_vertices list size does not match number of profile edges: " "len(%r) != %i" % (min_vertices, len(edges)) ) vertices_count = min_vertices # Utilities for building cross-section def get_xz(vertex): if isinstance(vertex, cadquery.Vector): vertex = vertex.wrapped # TODO: remove this, it's messy # where isinstance(vertex, FreeCAD.Base.Vector) return (vertex.x, vertex.z) def cart2polar(x, z, z_offset=0): """ Convert cartesian coordinates to polar coordinates. Uses thread's lead height to give full 360deg translation. """ radius = x angle = ((z + z_offset) / lead) * (2 * pi) # radians if not lefthand: angle = -angle return (radius, angle) def transform(vertex, z_offset=0): # where isinstance(vertex, FreeCAD.Base.Vector) """ Transform profile vertex on the XZ plane to it's equivalent on the cross-section's XY plane """ (radius, angle) = cart2polar(*get_xz(vertex), z_offset=z_offset) return (radius * cos(angle), radius * sin(angle)) # Conversion methods def apply_spline(wp, edge, vert_count, z_offset=0): """ Trace along edge and create a spline from the transformed verteces. """ curve = edge.wrapped.Curve # FreeCADPart.Geom* (depending on type) if edge.geomType() == 'CIRCLE': iter_dist = edge.wrapped.ParameterRange[1] / vert_count else: iter_dist = edge.Length() / vert_count points = [] for j in range(vert_count): dist = (j + 1) * iter_dist vert = curve.value(dist) points.append(transform(vert, z_offset)) return wp.spline(points) def apply_arc(wp, edge, z_offset=0): """ Create an arc using edge's midpoint and endpoint. Only intended for use for vertical lines on the given profile. """ return wp.threePointArc( point1=transform(edge.wrapped.valueAt(edge.Length() / 2), z_offset), point2=transform(edge.wrapped.valueAt(edge.Length()), z_offset), ) def apply_radial_line(wp, edge, z_offset=0): """ Create a straight radial line """ return wp.lineTo(*transform(edge.endPoint(), z_offset)) # Build cross-section start_v = edges[0].startPoint().wrapped cross_section = cadquery.Workplane("XY") \ .moveTo(*transform(start_v)) for i in range(start_count): z_offset = i * pitch for (j, edge) in enumerate(wire.Edges()): # where: isinstance(edge, cadquery.Edge) if (edge.geomType() == 'LINE') and (edge.startPoint().x == edge.endPoint().x): # edge is a vertical line, plot a circular arc cross_section = apply_arc(cross_section, edge, z_offset) elif (edge.geomType() == 'LINE') and (edge.startPoint().z == edge.endPoint().z): # edge is a horizontal line, plot a radial line cross_section = apply_radial_line(cross_section, edge, z_offset) else: # create bezier spline along transformed points (default) cross_section = apply_spline(cross_section, edge, vertices_count[j], z_offset) return cross_section.close() def helical_path(pitch, length, radius, angle=0, lefthand=False): # FIXME: update to master branch of cadquery wire = cadquery.Wire(FreeCADPart.makeHelix(pitch, length, radius, angle, lefthand)) #wire = cadquery.Wire.makeHelix(pitch, length, radius, angle=angle, lefthand=lefthand) shape = cadquery.Wire.combine([wire]) path = cadquery.Workplane("XY").newObject([shape]) return path class MinVerticiesParam(Parameter): _doc_type = ":class:`int` or list(:class:`int`)" def type(self, value): if isinstance(value, int): return max(2, value) elif isinstance(value, (tuple, list)): cast_value = [] for v in value: if isinstance(v, int): cast_value.append(self.type(v)) else: raise ParameterError("list contains at least one value that isn't an integer: %r" % v) return cast_value else: raise ParameterError("min_vertices must be an integer, or a list of integers: %r" % value) class Thread(cqparts.Part): # Base parameters pitch = PositiveFloat(1.0, doc="thread's pitch") start_count = IntRange(1, None, 1, doc="number of thread starts") min_vertices = MinVerticiesParam(20, doc="minimum vertices used cross-section's wire") diameter = PositiveFloat(3.0, doc="thread's diameter") length = PositiveFloat(2, doc="thread's length") inner = Boolean(False, doc="if True, thread is to be cut from a solid to form an inner thread") lefthand = Boolean(False, doc="if True, thread is spun in the opposite direction") pilothole_ratio = Float(0.5, doc=r"sets thread's pilot hole using *inner* and *outer* thread radii: :math:`radius = inner + ratio \times (outer-inner)`") pilothole_radius = PositiveFloat(None, doc="explicitly set pilothole radius, overrides ``pilothole_ratio``") _simple = Boolean( default=(os.environ.get('CQPARTS_COMPLEX_THREADS', 'no') == 'no'), doc="if set, simplified geometry is built", ) # FIXME: see bug #1 def __init__(self, *args, **kwargs): super(Thread, self).__init__(*args, **kwargs) self._profile = None def build_profile(self): r""" Build the thread's profile in a cadquery.Workplace as a wire on the :math:`XZ` plane. It will be used as an input to :meth:`profile_to_cross_section <cqparts.solidtypes.threads.base.profile_to_cross_section>` .. note:: This function must be overridden by the inheriting class in order to construct a thread. Without overriding, this function rases a :class:`NotImplementedError` exception. example implementation:: import cadquery from cqparts.solidtypes.threads.base import Thread class MyThread(Thread): def build_profile(self): points = [ (2, 0), (3, 0.5), (3, 1), (2, 1.5), (2, 2) ] profile = cadquery.Workplane("XZ") \ .moveTo(*points[0]).polyline(points[1:]) return profile.wire() # .wire() is mandatory :return: thread profile as a wire on the XZ plane :rtype: :class:`cadquery.Workplane` .. warning:: Wire must be built on the :math:`XZ` plane (as shown in the example). If it is not, the thread *may* not be generated correctly. """ raise NotImplementedError("build_profile function not overridden in %s" % type(self)) @property def profile(self): """ Buffered result of :meth:`build_profile` """ if self._profile is None: self._profile = self.build_profile() return self._profile def get_radii(self): """ Get the inner and outer radii of the thread. :return: (<inner radius>, <outer radius>) :rtype: :class:`tuple` .. note:: Ideally this method is overridden in inheriting classes to mathematically determine the radii. Default action is to generate the profile, then use the bounding box to determine min & max radii. However this method is prone to small numeric error. """ bb = self.profile.val().BoundingBox() return (bb.xmin, bb.xmax) def make(self): # Make cross-section cross_section = profile_to_cross_section( self.profile, lefthand=self.lefthand, start_count=self.start_count, min_vertices=self.min_vertices, ) # Make helical path profile_bb = self.profile.val().BoundingBox() #lead = (profile_bb.zmax - profile_bb.zmin) * self.start_count lead = self.pitch * self.start_count path = helical_path(lead, self.length, 1, lefthand=self.lefthand) # Sweep into solid thread = cross_section.sweep(path, isFrenet=True) # Making thread a valid solid # FIXME: this should be implemented inside cadquery itself thread_shape = thread.objects[0].wrapped if not thread_shape.isValid(): log.warning("thread shape not valid") new_thread = thread_shape.copy() new_thread.sewShape() thread.objects[0].wrapped = FreeCADPart.Solid(new_thread) if not thread.objects[0].wrapped.isValid(): log.error("sewn thread STILL not valid") raise SolidValidityError( "created thread solid cannot be made watertight" ) #solid = thread.val().wrapped #face = App.ActiveDocument.Face.Shape.copy() return thread def make_simple(self): """ Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2` """ (inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY') \ .circle(radius).extrude(self.length) def make_pilothole_cutter(self): """ Make a solid to subtract from an interfacing solid to bore a pilot-hole. """ # get pilothole ratio # note: not done in .initialize_parameters() because this would cause # the thread's profile to be created at initialisation (by default). pilothole_radius = self.pilothole_radius if pilothole_radius is None: (inner_radius, outer_radius) = self.get_radii() pilothole_radius = inner_radius + self.pilothole_ratio * (outer_radius - inner_radius) return cadquery.Workplane('XY') \ .circle(pilothole_radius) \ .extrude(self.length) # ------ Registration from cqparts.search import ( find as _find, search as _search, register as _register, ) from cqparts.search import common_criteria module_criteria = { 'module': __name__, } register = common_criteria(**module_criteria)(_register) search = common_criteria(**module_criteria)(_search) find = common_criteria(**module_criteria)(_find)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/triangular.py
src/cqparts_fasteners/solidtypes/threads/triangular.py
import cadquery from math import radians, tan from cqparts.params import * from .base import Thread, register @register(name='triangular') class TriangularThread(Thread): """ .. image:: /_static/img/threads/triangular.png """ diameter_core = Float(None, doc="diamter of core") angle = PositiveFloat(30, doc="pressure angle of thread") def initialize_parameters(self): super(TriangularThread, self).initialize_parameters() if self.diameter_core is None: self.diameter_core = self.diameter * (2. / 3) def build_profile(self): """ .. image:: /_static/img/threads/triangular.profile.png """ # Determine thread's length along z-axis thread_height = tan(radians(self.angle)) * (self.diameter - self.diameter_core) if thread_height > self.pitch: raise ValueError("thread's core diameter of %g cannot be achieved with an outer diameter of %g and an angle of %g" % ( self.diameter_core, self.diameter, self.angle )) points = [ (self.diameter_core / 2, 0), (self.diameter / 2, thread_height / 2), (self.diameter_core / 2, thread_height), ] if thread_height < self.pitch: points.append((self.diameter_core / 2, self.pitch)) profile = cadquery.Workplane("XZ") \ .moveTo(*points[0]).polyline(points[1:]) \ .wire() return profile def get_radii(self): # irrespective of self.inner flag return ( self.diameter_core / 2, # inner self.diameter / 2 # outer )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/counter_sunk.py
src/cqparts_fasteners/solidtypes/fastener_heads/counter_sunk.py
import cadquery from math import pi, cos, sin, sqrt from cqparts.params import * from .base import FastenerHead, register # pull FreeCAD module from cadquery (workaround for torus) FreeCAD = cadquery.freecad_impl.FreeCAD @register(name='countersunk') class CounterSunkFastenerHead(FastenerHead): """ .. image:: /_static/img/fastenerheads/countersunk.png """ chamfer = PositiveFloat(None) # default to diameter / 20 raised = PositiveFloat(0.0) # if None, defaults to diameter / 10 bugle = Boolean(False) bugle_ratio = FloatRange(0, 1, 0.5) def initialize_parameters(self): super(CounterSunkFastenerHead, self).initialize_parameters() if self.raised is None: self.raised = self.diameter / 10. if self.chamfer is None: self.chamfer = self.diameter / 20 def make(self): cone_radius = self.diameter / 2 cone_height = cone_radius # to achieve a 45deg angle cylinder_radius = cone_radius - self.chamfer cylinder_height = self.height shaft_radius = (self.diameter / 2.) - self.height cone = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeCone(0, cone_radius, cone_height)) \ .translate((0, 0, -cone_height)) ) cylinder = cadquery.Workplane("XY") \ .circle(cylinder_radius).extrude(-cylinder_height) head = cone.intersect(cylinder) # Raised bubble (if given) if self.raised: sphere_radius = ((self.raised ** 2) + (cylinder_radius ** 2)) / (2 * self.raised) sphere = cadquery.Workplane("XY").workplane(offset=-(sphere_radius - self.raised)) \ .sphere(sphere_radius) raised_cylinder = cadquery.Workplane("XY").circle(cylinder_radius).extrude(self.raised) from Helpers import show raised_bubble = sphere.intersect(raised_cylinder) head = head.union(raised_bubble) # Bugle Head if self.bugle and (0 <= self.bugle_ratio < 1.0): # bugle_angle = angle head material makes with chamfer cylinder on top bugle_angle = (pi / 4) * self.bugle_ratio # face_span = longest straight distance along flat conical face (excluding chamfer) face_span = sqrt(2) * (((self.diameter / 2.) - self.chamfer) - shaft_radius) r2 = (face_span / 2.) / sin((pi / 4) - bugle_angle) d_height = r2 * sin(bugle_angle) r1 = (r2 * cos(bugle_angle)) + shaft_radius torus = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeTorus( r1, r2, # radii pnt=FreeCAD.Base.Vector(0,0,0), dir=FreeCAD.Base.Vector(0,0,1), angleDegrees1=0., angleDegrees2=360. )).translate((0, 0, -(self.height + d_height))) ) head = head.cut(torus) return head def make_cutter(self): """ Add countersunk cone to cutter """ obj = super(CounterSunkFastenerHead, self).make_cutter() cone = cadquery.CQ(cadquery.Solid.makeCone( radius1=self.diameter / 2, radius2=0, height=self.height, dir=cadquery.Vector(0,0,-1), )) return obj.union(cone) def get_face_offset(self): return (0, 0, self.raised) @register(name='countersunk_raised') class CounterSunkRaisedFastenerHead(CounterSunkFastenerHead): """ .. image:: /_static/img/fastenerheads/countersunk_raised.png """ raised = PositiveFloat(None) # defaults to diameter / 10 @register(name='countersunk_bugle') class CounterSunkBugleFastenerHead(CounterSunkFastenerHead): """ .. image:: /_static/img/fastenerheads/countersunk_bugle.png """ bugle = Boolean(True)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/driven.py
src/cqparts_fasteners/solidtypes/fastener_heads/driven.py
import cadquery from math import pi, cos, sin, sqrt from cqparts.params import * from .base import FastenerHead, register class DrivenFastenerHead(FastenerHead): chamfer = PositiveFloat(None, doc="chamfer value (default: :math:`d/15`)") # default to diameter / 10 chamfer_top = Boolean(True, doc="if chamfer is set, top edges are chamfered (conical)") chamfer_base = Boolean(False, doc="if chamfer is set, base edges are chamfered (conical)") edges = PositiveInt(4, doc="number of edges on fastener head") width = PositiveFloat(None, doc="distance between flats") # defaults based on number of edges, and diameter # Washer (optional) washer = Boolean(False) washer_height = PositiveFloat(None) # default to height / 6 washer_diameter = PositiveFloat(None) # default to diameter * 1.2 def initialize_parameters(self): if self.width is not None: # Set diameter based on witdh (ignore given diameter) # (width is the size of the wrench used to drive it) self.diameter = self.width / cos(pi / self.edges) if self.chamfer is None: self.chamfer = self.diameter / 15 if self.washer_height is None: self.washer_height = self.height / 6 if self.washer_diameter is None: self.washer_diameter = self.diameter * 1.2 super(DrivenFastenerHead, self).initialize_parameters() def _default_access_diameter(self): # driven heads need more clearance if self.washer: return max(( # the greater of... self.diameter * 1.5, # 150% head's diameter self.washer_diameter * 1.1 # 110% washer diameter )) return self.diameter * 1.2 def get_cross_section_points(self): points = [] d_angle = pi / self.edges radius = self.diameter / 2. for i in range(self.edges): angle = d_angle + ((2 * d_angle) * i) points.append(( sin(angle) * radius, cos(angle) * radius )) return points def make(self): points = self.get_cross_section_points() head = cadquery.Workplane("XY") \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.height) if self.chamfer: cone_height = ((self.diameter / 2.) - self.chamfer) + self.height cone_radius = (self.diameter / 2.) + (self.height - self.chamfer) if self.chamfer_top: cone = cadquery.Workplane('XY').union(cadquery.CQ(cadquery.Solid.makeCone( cone_radius, 0, cone_height, pnt=cadquery.Vector(0, 0, 0), dir=cadquery.Vector(0, 0, 1), ))) head = head.intersect(cone) if self.chamfer_base: cone = cadquery.Workplane('XY').union(cadquery.CQ(cadquery.Solid.makeCone( cone_radius, 0, cone_height, pnt=cadquery.Vector(0, 0, self.height), dir=cadquery.Vector(0, 0, -1), ))) head = head.intersect(cone) # Washer if self.washer: washer = cadquery.Workplane("XY") \ .circle(self.washer_diameter / 2) \ .extrude(self.washer_height) head = head.union(washer) return head @register(name='square') class SquareFastenerHead(DrivenFastenerHead): """ .. image:: /_static/img/fastenerheads/square.png """ edges = PositiveInt(4) @register(name='hex') class HexFastenerHead(DrivenFastenerHead): """ .. image:: /_static/img/fastenerheads/hex.png """ edges = PositiveInt(6) @register(name='hex_flange') class HexFlangeFastenerHead(DrivenFastenerHead): """ .. image:: /_static/img/fastenerheads/hex_flange.png """ edges = PositiveInt(6) washer = Boolean(True)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/__init__.py
src/cqparts_fasteners/solidtypes/fastener_heads/__init__.py
__all__ = [ 'FastenerHead', 'register', 'find', 'search', # Fastener Head Types 'counter_sunk', 'cylindrical', 'driven', ] from .base import FastenerHead, register, find, search # Fastener Head Types from . import counter_sunk from . import cylindrical from . import driven
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/base.py
src/cqparts_fasteners/solidtypes/fastener_heads/base.py
import six import cadquery # relative imports import cqparts from cqparts.params import * import logging log = logging.getLogger(__name__) class FastenerHead(cqparts.Part): diameter = PositiveFloat(5.2, doc="fastener head diameter") height = PositiveFloat(2.0, doc="fastener head height") # tool access access_diameter = PositiveFloat(None, doc="diameter of circle allowing tool access above fastener (defaults to diameter)") access_height = PositiveFloat(1000, doc="depth of hole providing access (default 1m)") def initialize_parameters(self): if self.access_diameter is None: self.access_diameter = self._default_access_diameter() def _default_access_diameter(self): return self.diameter def make_cutter(self): """ Create solid to subtract from material to make way for the fastener's head (just the head) """ return cadquery.Workplane('XY') \ .circle(self.access_diameter / 2) \ .extrude(self.access_height) def get_face_offset(self): """ Returns the screw drive origin offset relative to bolt's origin """ return (0, 0, self.height) # ------ Registration from cqparts.search import ( find as _find, search as _search, register as _register, ) from cqparts.search import common_criteria module_criteria = { 'module': __name__, } register = common_criteria(**module_criteria)(_register) search = common_criteria(**module_criteria)(_search) find = common_criteria(**module_criteria)(_find)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/cylindrical.py
src/cqparts_fasteners/solidtypes/fastener_heads/cylindrical.py
import cadquery from math import pi, cos, sin, sqrt from cqparts.params import * from .base import FastenerHead, register class CylindricalFastenerHead(FastenerHead): fillet = PositiveFloat(None) # defaults to diameter / 10 # Dome on top ? domed = Boolean(False) dome_ratio = PositiveFloat(0.25) # ratio of head's height def initialize_parameters(self): super(CylindricalFastenerHead, self).initialize_parameters() if self.fillet is None: self.fillet = self.diameter / 10 def make(self): head = cadquery.Workplane("XY") \ .circle(self.diameter / 2.).extrude(self.height) if self.domed: dome_height = self.height * self.dome_ratio sphere_radius = ((dome_height ** 2) + ((self.diameter / 2.) ** 2)) / (2 * dome_height) sphere = cadquery.Workplane("XY") \ .workplane(offset=self.height - sphere_radius) \ .sphere(sphere_radius) head = head.intersect(sphere) else: # Fillet top face if self.fillet: head = head.faces(">Z").edges().fillet(self.fillet) return head @register(name='cheese') class CheeseFastenerHead(CylindricalFastenerHead): """ .. image:: /_static/img/fastenerheads/cheese.png """ fillet = PositiveFloat(0.0) domed = Boolean(False) @register(name='pan') class PanFastenerHead(CylindricalFastenerHead): """ .. image:: /_static/img/fastenerheads/pan.png """ domed = Boolean(False) @register(name='dome') class DomeFastenerHead(CylindricalFastenerHead): """ .. image:: /_static/img/fastenerheads/dome.png """ domed = Boolean(True) @register(name='round') class RoundFastenerHead(CylindricalFastenerHead): """ .. image:: /_static/img/fastenerheads/round.png """ domed = Boolean(True) dome_ratio = PositiveFloat(1) # Coach Head coach_head = Boolean(False) coach_width = PositiveFloat(None) # default = diameter / 2 coach_height = PositiveFloat(None) # default = height coach_chamfer = PositiveFloat(None) # default = coach_width / 6 def initialize_parameters(self): super(RoundFastenerHead, self).initialize_parameters() if self.coach_width is None: self.coach_width = self.diameter / 2 if self.coach_height is None: self.coach_height = self.height if self.coach_chamfer is None: self.coach_chamfer = self.coach_width / 6 def make(self): head = super(RoundFastenerHead, self).make() # Add chamfered square block beneath fastener head if self.coach_head: cone_radius = ((self.coach_width / 2.) + self.coach_height) - self.coach_chamfer cone_height = cone_radius box = cadquery.Workplane("XY").rect(self.coach_width, self.coach_width).extrude(-self.coach_height) cone = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeCone(0, cone_radius, cone_height)) \ .translate((0, 0, -cone_height)) ) head = head.union(box.intersect(cone)) return head @register(name='round_coach') class RoundCoachFastenerHead(RoundFastenerHead): """ .. image:: /_static/img/fastenerheads/round_coach.png """ coach_head = Boolean(True) @register(name='trapezoidal') class TrapezoidalFastenerHead(FastenerHead): """ .. image:: /_static/img/fastenerheads/trapezoidal.png """ diameter_top = PositiveFloat(None) # default to diameter * 0.75 def initialize_parameters(self): super(TrapezoidalFastenerHead, self).initialize_parameters() if self.diameter_top is None: self.diameter_top = self.diameter * 0.75 def make(self, offset=(0, 0, 0)): r1 = self.diameter / 2. r2 = self.diameter_top / 2. head = cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeCone(r1, r2, self.height)) ) return head.translate(offset)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/hex.py
src/cqparts_fasteners/solidtypes/screw_drives/hex.py
import cadquery from math import sqrt, pi, sin, cos from copy import copy from cqparts.params import * from .base import ScrewDrive, register @register(name='hex') @register(name='allen') class HexScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/hex.png """ diameter = PositiveFloat(None) width = PositiveFloat(ScrewDrive.diameter.default * cos(pi / 6)) # if set, defines diameter count = IntRange(1, None, 1) # number of hexagon cutouts # Tamper resistance pin pin = Boolean(False) # if True, a pin is placed in the center pin_height = None # defaults to depth pin_diameter = None # defaults to diameter / 3 def initialize_parameters(self): if self.width is not None: # Set diameter from hexagon's width (ignore given diameter) self.diameter = self.width / cos(pi / 6) super(HexScrewDrive, self).initialize_parameters() if self.pin_height is None: self.pin_height = self.depth if self.pin_diameter is None: self.pin_diameter = self.diameter / 3 def get_hexagon_vertices(self): """ Generate the points of a hexagon :param diameter: Diameter of hexagon :return: list of tuples [(x1, y1), (x2, y2), ... ] """ radius = self.diameter / 2.0 points = [] for i in range(6): theta = (i + 0.5) * (pi / 3) points.append((cos(theta) * radius, sin(theta) * radius)) return points def make(self): # Single hex as template points = self.get_hexagon_vertices() tool_template = cadquery.Workplane("XY") \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(-self.depth) # Create tool (rotate & duplicate template) tool = copy(tool_template) for i in range(1, self.count): angle = i * (60.0 / self.count) tool = tool.union( copy(tool_template).rotate((0, 0, 0), (0, 0, 1), angle) ) # Tamper Resistance Pin if self.pin: tool = tool.faces("<Z").circle(self.pin_diameter / 2.).cutBlind(self.pin_height) return tool @register(name='double_hex') @register(name='2hex') class DoubleHexScrewDrive(HexScrewDrive): """ .. image:: /_static/img/screwdrives/double_hex.png """ count = IntRange(1, None, 2) @register(name='hexalobular') class HexalobularScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/hexalobular.png """ count = IntRange(1, None, 6) gap = PositiveFloat(None) # gap between circles at diameter (defaults to diameter / 8) fillet = PositiveFloat(None) # defaults to gap / 2 # Tamper resistance pin pin = Boolean(False) # if True, a pin is placed in the center pin_height = PositiveFloat(None) # defaults to depth pin_diameter = PositiveFloat(None) # defaults to diameter / 3 def initialize_parameters(self): super(HexalobularScrewDrive, self).initialize_parameters() if self.gap is None: self.gap = self.diameter / 8 if self.fillet is None: self.fillet = self.gap / 2 if self.pin_height is None: self.pin_height = self.depth if self.pin_diameter is None: self.pin_diameter = self.diameter / 3 def make(self): # Start with a circle with self.diameter tool = cadquery.Workplane("XY") \ .circle(self.diameter / 2).extrude(-self.depth) # Cut cylinders from circumference wedge_angle = (2 * pi) / self.count outer_radius = (self.diameter / 2.) / cos(wedge_angle / 2) cut_radius = (outer_radius * sin(wedge_angle / 2)) - (self.gap / 2) cylinder_template = cadquery.Workplane("XY") \ .center(0, outer_radius) \ .circle(cut_radius) \ .extrude(-self.depth) for i in range(self.count): angle = (360. / self.count) * i tool = tool.cut(cylinder_template.rotate((0, 0, 0), (0, 0, 1), angle)) # Fillet the edges before cutting if self.fillet: tool = tool.edges("|Z").fillet(self.fillet) # Tamper Resistance Pin if self.pin: tool.faces("<Z").circle(self.pin_diameter / 2.).cutBlind(self.pin_height) return tool
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/square.py
src/cqparts_fasteners/solidtypes/screw_drives/square.py
import cadquery from math import sqrt, pi, sin, cos from copy import copy from cqparts.params import * from .base import ScrewDrive, register @register(name='square') @register(name='robertson') class SquareScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/square.png """ width = PositiveFloat(None) count = IntRange(1, None, 1) def initialize_parameters(self): super(SquareScrewDrive, self).initialize_parameters() if self.width is None: self.width = self.diameter / sqrt(2) else: # Set diameter from square's width (ignore given diameter) self.diameter = self.width / cos(pi / 6) def get_square(self, angle=0): return cadquery.Workplane('XY') \ .rect(self.width, self.width).extrude(-self.depth) \ .rotate((0,0,0), (0,0,1), angle) def make(self): # Single square as template tool_template = cadquery.Workplane("XY") \ .rect(self.width, self.width).extrude(-self.depth) # Create tool (rotate & duplicate template) tool = cadquery.Workplane('XY') for i in range(self.count): tool = tool.union( self.get_square(angle=i * (90.0 / self.count)) ) return tool @register(name='double_square') @register(name='2square') class DoubleSquareScrewDrive(SquareScrewDrive): """ .. image:: /_static/img/screwdrives/double_square.png """ count = IntRange(1, None, 2) @register(name='triple_square') @register(name='3square') class TrippleSquareScrewDrive(SquareScrewDrive): """ .. image:: /_static/img/screwdrives/triple_square.png """ count = IntRange(1, None, 3)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/slotted.py
src/cqparts_fasteners/solidtypes/screw_drives/slotted.py
import cadquery from cqparts.params import * from .base import ScrewDrive, register @register(name='slot') class SlotScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/slot.png """ width = PositiveFloat(None, doc="slot width") def initialize_parameters(self): if self.width is None: self.width = self.diameter / 8 if self.depth is None: self.depth = self.width * 1.5 super(SlotScrewDrive, self).initialize_parameters() def make(self): tool = cadquery.Workplane("XY") \ .rect(self.width, self.diameter).extrude(-self.depth) return tool @register(name='cross') class CrossScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/cross.png """ width = PositiveFloat(None, doc="slot width") def initialize_parameters(self): if self.width is None: self.width = self.diameter / 8 if self.depth is None: self.depth = self.width * 1.5 super(CrossScrewDrive, self).initialize_parameters() def make(self): tool = cadquery.Workplane("XY") \ .rect(self.width, self.diameter).extrude(-self.depth) \ .faces(">Z") \ .rect(self.diameter, self.width).extrude(-self.depth) return tool
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/__init__.py
src/cqparts_fasteners/solidtypes/screw_drives/__init__.py
__all__ = [ 'ScrewDrive', 'register', 'find', 'search', # Screw Drive types 'cruciform', 'hex', 'slotted', 'square', 'tamper_resistant', ] from .base import ScrewDrive, register, find, search # Screw Drive types from . import cruciform from . import hex from . import slotted from . import square from . import tamper_resistant
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/base.py
src/cqparts_fasteners/solidtypes/screw_drives/base.py
import six import cadquery import cqparts from cqparts.params import * from cqparts.utils import CoordSystem class ScrewDrive(cqparts.Part): diameter = PositiveFloat(3.0, doc="screw drive's diameter") depth = PositiveFloat(None, doc="depth of recess into driven body") def initialize_parameters(self): super(ScrewDrive, self).initialize_parameters() if self.depth is None: self.depth = self.diameter # default to be as deep as it is wide def make(self): """ Make the solid to use as a cutter, to make the screw-drive impression in another solid. :return: cutter solid :rtype: :class:`cadquery.Workplane` """ raise NotImplementedError("%r implements no solid to subtract" % type(self)) def apply(self, workplane, world_coords=CoordSystem()): """ Application of screwdrive indentation into a workplane (centred on the given world coordinates). :param workplane: workplane with solid to alter :type workplane: :class:`cadquery.Workplane` :param world_coords: coorindate system relative to ``workplane`` to move cutter before it's cut from the ``workplane`` :type world_coords: :class:`CoordSystem` """ self.world_coords = world_coords return workplane.cut(self.world_obj) # ------ Registration from cqparts.search import ( find as _find, search as _search, register as _register, ) from cqparts.search import common_criteria module_criteria = { 'module': __name__, } register = common_criteria(**module_criteria)(_register) search = common_criteria(**module_criteria)(_search) find = common_criteria(**module_criteria)(_find)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/cruciform.py
src/cqparts_fasteners/solidtypes/screw_drives/cruciform.py
import cadquery from cadquery import BoxSelector from math import pi, cos, sqrt from cqparts.params import * from .base import ScrewDrive, register @register(name='frearson') class FrearsonScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/frearson.png """ width = PositiveFloat(0.5) def make(self): points = [ (self.diameter / 2., 0), (self.width / 2., -self.depth), (-self.width / 2., -self.depth), (-self.diameter / 2., 0), ] tool_cross_x = cadquery.Workplane("XZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) tool_cross_y = cadquery.Workplane("YZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) tool = tool_cross_x.union(tool_cross_y) return tool @register(name='phillips') class PhillipsScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/phillips.png """ width = PositiveFloat(None, doc="blade width") chamfer = PositiveFloat(None, "chamfer at top of cross section") def initialize_parameters(self): super(PhillipsScrewDrive, self).initialize_parameters() if self.width is None: self.width = self.diameter / 6 if self.chamfer is None: self.chamfer = self.width / 2 def make(self): # Frearson style cross from center points = [ (self.diameter / 2., 0), (self.width / 2., -self.depth), (-self.width / 2., -self.depth), (-self.diameter / 2., 0), ] tool_cross_x = cadquery.Workplane("XZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) tool_cross_y = cadquery.Workplane("YZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) # Trapezoidal pyramid 45deg rotated cutout of center # alternative: lofting 2 squares, but that was taking ~7 times longer to process tz_top = (sqrt(2) * self.width) + ((self.chamfer / sqrt(2)) * 2) tz_base = self.width / sqrt(2) # to fit inside square at base points = [ (tz_top / 2., 0), (tz_base / 2., -self.depth), (-tz_base / 2., -self.depth), (-tz_top / 2., 0), ] tool_tzpy1 = cadquery.Workplane("XZ").workplane(offset=-tz_top / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(tz_top) tool_tzpy2 = cadquery.Workplane("YZ").workplane(offset=-tz_top / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(tz_top) tool_tzpy = tool_tzpy1.intersect(tool_tzpy2) \ .rotate((0, 0, 0), (0, 0, 1), 45) tool = cadquery.Workplane("XY") \ .union(tool_cross_x) \ .union(tool_cross_y) \ .union(tool_tzpy) return tool @register(name='french_recess') class FrenchRecessScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/french_recess.png """ width = PositiveFloat(0.5, doc="blade width") step_depth = PositiveFloat(None, doc="depth the step diameter takes effect") # default to depth / 2 step_diameter = PositiveFloat(None, doc="diameter at depth") # default to 2/3 diameter def initialize_parameters(self): super(FrenchRecessScrewDrive, self).initialize_parameters() if self.step_depth is None: self.step_depth = self.depth / 2 if self.step_diameter is None: self.step_diameter = self.diameter * (2./3) def make(self): tool = cadquery.Workplane("XY") \ .rect(self.width, self.diameter).extrude(-self.step_depth) \ .faces(">Z") \ .rect(self.diameter, self.width).extrude(-self.step_depth) \ .faces("<Z") \ .rect(self.width, self.step_diameter).extrude(-(self.depth - self.step_depth)) \ .faces("<Z") \ .rect(self.step_diameter, self.width).extrude(self.depth - self.step_depth) return tool @register(name='mortorq') class MortorqScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/mortorq.png """ width = PositiveFloat(1.0) count = PositiveInt(4) fillet = PositiveFloat(0.3) def make(self): points = [ (self.width / 2, self.width / 2), (self.width / 2, -self.width / 2), (-self.diameter / 2, -self.width / 2), (-self.diameter / 2, self.width / 2), ] rect = cadquery.Workplane("XY") \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(-self.depth) cylinder = cadquery.Workplane("XY") \ .center(self.width - (self.diameter / 2.), self.width / 2.) \ .circle(self.width).extrude(-self.depth) blade = rect.intersect(cylinder) tool = cadquery.Workplane("XY").rect(self.width, self.width).extrude(-self.depth) for i in range(self.count): angle = i * (360. / self.count) tool = tool.union(blade.rotate((0, 0, 0), (0, 0, 1), angle)) if self.fillet: tool = tool.edges("|Z").fillet(self.fillet) return tool @register(name='pozidriv') class PozidrivScrewDrive(ScrewDrive): """ .. image:: /_static/img/screwdrives/pozidriv.png """ width = PositiveFloat(0.5) inset_cut = PositiveFloat(None) # defaults to width / 2 # cross-shaped marking to indicate "Posidriv" screw drive markings = Boolean(True) # if false, marking is not shown marking_width = PositiveFloat(0.1) marking_depth = PositiveFloat(0.1) def initialize_parameters(self): super(PozidrivScrewDrive, self).initialize_parameters() if self.inset_cut is None: self.inset_cut = self.width / 2 def make(self): # Frearson style cross from center points = [ (self.diameter / 2., 0), (self.width / 2., -self.depth), (-self.width / 2., -self.depth), (-self.diameter / 2., 0), ] tool_cross_x = cadquery.Workplane("XZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) tool_cross_y = cadquery.Workplane("YZ").workplane(offset=-self.width / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) # Trapezoidal pyramid inset # alternative: lofting 2 squares, but that was taking ~7 times longer to process tz_top = self.width + (2 * self.inset_cut) tz_base = self.width points = [ (tz_top / 2., 0), (tz_base / 2., -self.depth), (-tz_base / 2., -self.depth), (-tz_top / 2., 0), ] tool_tzpy1 = cadquery.Workplane("XZ").workplane(offset=-tz_top / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(tz_top) tool_tzpy2 = cadquery.Workplane("YZ").workplane(offset=-tz_top / 2.) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(tz_top) tool_tzpy = tool_tzpy1.intersect(tool_tzpy2) tool = cadquery.Workplane("XY") \ .union(tool_cross_x) \ .union(tool_cross_y) \ .union(tool_tzpy) # Cross-shaped marking if self.markings: markings = cadquery.Workplane("XY") \ .rect(self.diameter, self.marking_width).extrude(-self.marking_depth) \ .faces(">Z") \ .rect(self.marking_width, self.diameter).extrude(-self.marking_depth) \ .rotate((0, 0, 0), (0, 0, 1), 45) tool = tool.union(markings) return tool
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/tamper_resistant.py
src/cqparts_fasteners/solidtypes/screw_drives/tamper_resistant.py
import cadquery from cadquery import BoxSelector from math import pi, cos, sqrt from cqparts.params import * from .base import ScrewDrive, register class AcentricWedgesScrewDrive(ScrewDrive): count = IntRange(1, None, 4) width = PositiveFloat(0.5) acentric_radius = PositiveFloat(None) # defaults to width / 2 def initialize_parameters(self): super(AcentricWedgesScrewDrive, self).initialize_parameters() if self.acentric_radius is None: self.acentric_radius = self.width / 2 def make(self): # Start with a cylindrical pin down the center tool = cadquery.Workplane("XY") \ .circle(self.width / 2).extrude(-self.depth) # Create a single blade points = [ (0, 0), (0, -self.depth), (-self.width / 2, -self.depth), (-self.diameter / 2, 0), ] blade = cadquery.Workplane("XZ").workplane(offset=self.acentric_radius - (self.width / 2)) \ .moveTo(*points[0]).polyline(points[1:]).close() \ .extrude(self.width) for i in range(self.count): angle = i * (360. / self.count) tool = tool.union( blade.translate((0, 0, 0)) \ .rotate((0, 0, 0), (0, 0, 1), angle) ) return tool @register(name='tri_point') class TripointScrewDrive(AcentricWedgesScrewDrive): """ .. image:: /_static/img/screwdrives/tri_point.png """ count = IntRange(1, None, 3) acentric_radius = PositiveFloat(0.0) # yeah, not my best class design, but it works @register(name='torq_set') class TorqsetScrewDrive(AcentricWedgesScrewDrive): """ .. image:: /_static/img/screwdrives/torq_set.png """ count = IntRange(1, None, 4)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/fasteners/screw.py
src/cqparts_fasteners/fasteners/screw.py
from cqparts.constraint import Mate, Coincident from .base import Fastener from ..screws import Screw from ..utils import VectorEvaluator, Selector, Applicator class ScrewFastener(Fastener): """ Screw fastener assembly. Example usage can be found here: :ref:`cqparts_fasteners.built-in.screw` """ Evaluator = VectorEvaluator class Selector(Selector): ratio = 0.8 def get_components(self): end_effect = self.evaluator.eval[-1] end_point = end_effect.start_point + (end_effect.end_point - end_effect.start_point) * self.ratio return {'screw': Screw( head=('countersunk', { 'diameter': 9.5, 'height': 3.5, }), neck_length=abs(self.evaluator.eval[-1].start_point - self.evaluator.eval[0].start_point), # only the length after the neck is threaded length=abs(end_point - self.evaluator.eval[0].start_point), #length=abs(self.evaluator.eval[-1].end_point - self.evaluator.eval[0].start_point), )} def get_constraints(self): # bind fastener relative to its anchor; the part holding it in. anchor_part = self.evaluator.eval[-1].part # last effected part return [Coincident( self.components['screw'].mate_origin, Mate(anchor_part, self.evaluator.eval[0].start_coordsys - anchor_part.world_coords) )] class Applicator(Applicator): def apply_alterations(self): screw = self.selector.components['screw'] cutter = screw.make_cutter() # cutter in local coords for effect in self.evaluator.eval: relative_coordsys = screw.world_coords - effect.part.world_coords local_cutter = relative_coordsys + cutter effect.part.local_obj = effect.part.local_obj.cut(local_cutter)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/fasteners/nutbolt.py
src/cqparts_fasteners/fasteners/nutbolt.py
from cqparts.constraint import Mate, Coincident from .base import Fastener from ..utils import VectorEvaluator, Selector, Applicator from ..nuts import HexNut from ..bolts import HexBolt class NutAndBoltFastener(Fastener): """ Nut and Bolt fastener assembly. Example usage can be found here: :ref:`cqparts_fasteners.built-in.nut-bolt` """ Evaluator = VectorEvaluator class Selector(Selector): def get_components(self): effect_length = abs(self.evaluator.eval[-1].end_point - self.evaluator.eval[0].start_point) nut = HexNut() bolt = HexBolt( length=effect_length + nut.height, ) return { 'bolt': bolt, 'nut': nut, } def get_constraints(self): # bind fastener relative to its anchor; the part holding it in. first_part = self.evaluator.eval[0].part last_part = self.evaluator.eval[-1].part # last effected part return [ Coincident( self.components['bolt'].mate_origin, Mate(first_part, self.evaluator.eval[0].start_coordsys - first_part.world_coords) ), Coincident( self.components['nut'].mate_origin, Mate(last_part, self.evaluator.eval[-1].end_coordsys - last_part.world_coords) ), ] class Applicator(Applicator): def apply_alterations(self): bolt = self.selector.components['bolt'] nut = self.selector.components['nut'] bolt_cutter = bolt.make_cutter() # cutter in local coords nut_cutter = nut.make_cutter() for effect in self.evaluator.eval: # bolt bolt_coordsys = bolt.world_coords - effect.part.world_coords effect.part.local_obj = effect.part.local_obj.cut(bolt_coordsys + bolt_cutter) # nut nut_coordsys = nut.world_coords - effect.part.world_coords effect.part.local_obj = effect.part.local_obj.cut(nut_coordsys + nut_cutter)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/fasteners/__init__.py
src/cqparts_fasteners/fasteners/__init__.py
__all__ = [ 'Fastener', ] from .base import Fastener
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/fasteners/base.py
src/cqparts_fasteners/fasteners/base.py
import six from math import tan from math import radians import cadquery import cqparts from cqparts.params import * from ..utils import Evaluator, Selector, Applicator import logging log = logging.getLogger(__name__) # ----------------- Fastener Base --------------- class Fastener(cqparts.Assembly): # Parameters parts = PartsList(doc="List of parts being fastened") # Class assignment Evaluator = Evaluator Selector = Selector Applicator = Applicator def make_components(self): # --- Run evaluation self.evaluator = self.Evaluator( parts=self.parts, location=self.world_coords, parent=self, ) # --- Select fastener (based on evaluation) self.selector = self.Selector( evaluator=self.evaluator, parent=self, ) # --- Add components return self.selector.components def make_constraints(self): # --- Place fastener parts return self.selector.constraints def make_alterations(self): # --- Make alterations based on evaluation and selection self.applicator = self.Applicator( evaluator=self.evaluator, selector=self.selector, parent=self, ) self.applicator.apply_alterations()
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/applicator.py
src/cqparts_fasteners/utils/applicator.py
from .evaluator import VectorEvaluator, CylinderEvaluator class Applicator(object): """ The *applicator* performs 2 roles to *apply* a fastener to workpieces #. Translate & rotate given *fastener* #. Change workpieces to suit a given *fastener* Translation is done first because the fastener is sometimes used as a cutting tool to subtract from mating part(s) (eg: thread tapping). """ def __init__(self, evaluator, selector, parent=None): """ :param evaluator: evaluator for fastener :type evaluator: :class:`Evaluator <cqparts_fasteners.utils.Evaluator>` :param selector: selector for fastener :type selector: :class:`Selector <cqparts_fasteners.utils.Selector>` :param parent: parent object :type parent: :class:`Fastener <cqparts_fasteners.fasteners.base.Fastener>` """ self.evaluator = evaluator self.selector = selector self.parent = parent def apply_alterations(self): """ Apply alterations to relevant parts based on the selected parts """ pass
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py
src/cqparts_fasteners/utils/evaluator.py
import cadquery from copy import copy import logging from cqparts.utils import CoordSystem from cqparts.utils.misc import property_buffered from . import _casting log = logging.getLogger(__name__) # --------------------- Effect ---------------------- class Effect(object): pass class VectorEffect(Effect): """ An evaluator effect is the conclusion to an evaluation with regard to a single solid. Effects are sortable (based on proximity to evaluation origin) """ def __init__(self, location, part, result): """ :param location: where the fastener is to be applied (eg: for a screw application will be along the -Z axis) :type location: :class:`CoordSystem` :param part: effected solid :type part: cadquery.Workplane :param result: result of evaluation :type result: cadquery.Workplane """ self.location = location self.part = part self.result = result @property def start_point(self): """ Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center() @property def start_coordsys(self): """ Coordinate system at start of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's start point. :return: coordinate system at start of effect :rtype: :class:`CoordSys` """ coordsys = copy(self.location) coordsys.origin = self.start_point return coordsys @property def end_point(self): """ End vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[-1] return edge.Vertices()[-1].Center() @property def end_coordsys(self): """ Coordinate system at end of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's end point. :return: coordinate system at end of effect :rtype: :class:`CoordSys` """ coordsys = copy(self.location) coordsys.origin = self.end_point return coordsys @property def origin_displacement(self): """ planar distance of start point from self.location along :math:`-Z` axis """ return self.start_point.sub(self.location.origin).dot(-self.location.zDir) @property def wire(self): edge = cadquery.Edge.makeLine(self.start_point, self.end_point) return cadquery.Wire.assembleEdges([edge]) @property def _wire_wp(self): """Put self.wire in it's own workplane for display purposes""" return cadquery.Workplane('XY').newObject([self.wire]) # bool def __bool__(self): if self.result.edges().objects: return True return False __nonzero__ = __bool__ # Comparisons def __lt__(self, other): return self.origin_displacement < other.origin_displacement def __le__(self, other): return self.origin_displacement <= other.origin_displacement def __gt__(self, other): return self.origin_displacement > other.origin_displacement def __ge__(self, other): return self.origin_displacement >= other.origin_displacement # --------------------- Evaluator ---------------------- class Evaluator(object): """ An evaluator determines which parts may be effected by a fastener, and how. """ # Constructor def __init__(self, parts, parent=None): """ :param parts: parts involved in fastening :type parts: list of :class:`cqparts.Part` :param parent: parent object :type parent: :class:`Fastener <cqparts_fasteners.fasteners.base.Fastener>` """ # All evaluators will take a list of parts self.parts = parts self.parent = parent def perform_evaluation(self): """ Evaluate the given parts using any additional parameters passed to this instance. .. note:: Override this function in your *evaluator* class to assess what parts are effected, and how. Default behaviour: do nothing, return nothing :return: ``None`` """ return None @property_buffered def eval(self): """ Return the result of :meth:`perform_evaluation`, and buffer it so it's only run once per :class:`Evaluator` instance. :return: result from :meth:`perform_evaluation` """ return self.perform_evaluation() class VectorEvaluator(Evaluator): effect_class = VectorEffect def __init__(self, parts, location, parent=None): """ :param parts: parts involved in fastening :type parts: list of :class:`cqparts.Part` :param location: where the fastener is to be applied (eg: for a screw application will be along the -Z axis) :type location: :class:`CoordSystem` :param parent: parent object :type parent: :class:`Fastener <cqparts_fasteners.fasteners.base.Fastener>` **Location** The orientation of ``location`` may not be important; it may be for a basic application of a screw, in which case the :math:`-Z` axis will be used to perform the evaluation, and the :math:`X` and :math`Y` axes are of no consequence. For *some* fasteners, the orientation of ``location`` will be important. """ super(VectorEvaluator, self).__init__( parts=parts, parent=parent, ) self.location = location @property_buffered def max_effect_length(self): """ :return: The longest possible effect vector length. :rtype: float In other words, the *radius* of a sphere: - who's center is at ``start``. - all ``parts`` are contained within the sphere. """ # Method: using each solid's bounding box: # - get vector from start to bounding box center # - get vector from bounding box center to any corner # - add the length of both vectors # - return the maximum of these from all solids def max_length_iter(): for part in self.parts: if part.local_obj.findSolid(): bb = part.local_obj.findSolid().BoundingBox() yield abs(bb.center - self.location.origin) + (bb.DiagonalLength / 2) try: return max(max_length_iter()) except ValueError as e: # if iter returns before yielding anything return 0 def perform_evaluation(self): """ Determine which parts lie along the given vector, and what length :return: effects on the given parts (in order of the distance from the start point) :rtype: list(:class:`VectorEffect`) """ # Create effect vector (with max length) if not self.max_effect_length: # no effect is possible, return an empty list return [] edge = cadquery.Edge.makeLine( self.location.origin, self.location.origin + (self.location.zDir * -(self.max_effect_length + 1)) # +1 to avoid rounding errors ) wire = cadquery.Wire.assembleEdges([edge]) wp = cadquery.Workplane('XY').newObject([wire]) effect_list = [] # list of self.effect_class instances for part in self.parts: solid = part.world_obj.translate((0, 0, 0)) intersection = solid.intersect(copy(wp)) effect = self.effect_class( location=self.location, part=part, result=intersection, ) if effect: effect_list.append(effect) return sorted(effect_list) class CylinderEvaluator(Evaluator): effect_class = VectorEffect
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/__init__.py
src/cqparts_fasteners/utils/__init__.py
__all__ = [ # Evaluators 'Evaluator', 'VectorEvaluator', 'CylinderEvaluator', # Selectors 'Selector', # Applicators 'Applicator', ] # Evaluators from .evaluator import Evaluator from .evaluator import VectorEvaluator, CylinderEvaluator # Selectors from .selector import Selector # Applicators from .applicator import Applicator
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/_casting.py
src/cqparts_fasteners/utils/_casting.py
# Casting utilities are only intended to be used locally # (ie: within the cqparts_fasteners.utils sub-modules). # Each cast is designed to take a variety of inputs, and output # the same class instance each time, or raise a fault import cadquery class CastingError(Exception): """ Raised if there's any problem casting one object type to another. """ pass def solid(solid_in): """ :return: cadquery.Solid instance """ if isinstance(solid_in, cadquery.Solid): return solid_in elif isinstance(solid_in, cadquery.CQ): return solid_in.val() raise CastingError( "Cannot cast object type of {!r} to a solid".format(solid_in) ) def vector(vect_in): """ :return: cadquery.Vector instance """ if isinstance(vect_in, cadquery.Vector): return vect_in elif isinstance(vect_in, (tuple, list)): return cadquery.Vector(vect_in) raise CastingError( "Cannot cast object type of {!r} to a vector".format(vect_in) )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/selector.py
src/cqparts_fasteners/utils/selector.py
from .evaluator import Evaluator class Selector(object): """ Facilitates the selection and placement of a *fastener's* components based on an *evaluation*. Each *selector* instance has an :class:`Evaluator` for reference, and must have both the methods :meth:`get_components` and :meth:`get_constraints` overridden. """ def __init__(self, evaluator, parent=None): """ :param evaluator: evaluator of fastener parts :type evaluator: :class:`Evaluator` :param parent: parent object :type parent: :class:`Fastener <cqparts_fasteners.fasteners.base.Fastener>` """ self.evaluator = evaluator self.parent = parent self._components = None self._constraints = None # ---- Components def get_components(self): """ Return fastener's components .. note:: Must be overridden by inheriting class. Read :ref:`cqparts_fasteners.build_cycle` to learn more. :return: components for the *fastener* :rtype: :class:`dict` of :class:`Component <cqparts.Component>` instances """ return {} @property def components(self): if self._components is None: self._components = self.get_components() return self._components # ---- Constraints def get_constraints(self): """ Return fastener's constraints .. note:: Must be overridden by inheriting class. Read :ref:`cqparts_fasteners.build_cycle` to learn more. :return: list of *constraints* :rtype: :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances """ return [] @property def constraints(self): if self._constraints is None: self._constraints = self.get_constraints() return self._constraints
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_bearings/ball.py
src/cqparts_bearings/ball.py
from math import pi, radians, sin, cos, asin import cadquery import cqparts from cqparts.params import * from cqparts import constraint from cqparts.constraint import Mate from cqparts.utils import CoordSystem from . import register class _Ring(cqparts.Part): # Basic shape outer_radius = PositiveFloat(10, doc="outside radius") inner_radius = PositiveFloat(8, doc="inside radius") width = PositiveFloat(5, doc="ring's width") # Ball rails ball_radius = PositiveFloat(3, doc="ball bearing radius") rolling_radius = PositiveFloat(6, doc="distance of ball's center from bearing's axis") @classmethod def get_ball_torus(cls, rolling_radius, ball_radius): return cadquery.Workplane("XY").union( cadquery.CQ(cadquery.Solid.makeTorus( rolling_radius, ball_radius, # radii pnt=cadquery.Vector(0,0,0).wrapped, dir=cadquery.Vector(0,0,1).wrapped, angleDegrees1=0., angleDegrees2=360., )) ) def get_ring(self): return cadquery.Workplane('XY', origin=(0, 0, -self.width / 2)) \ .circle(self.outer_radius).circle(self.inner_radius) \ .extrude(self.width) def make(self): ring = self.get_ring() torus = self.get_ball_torus(self.rolling_radius, self.ball_radius) return ring.cut(torus) def make_simple(self): return self.get_ring() def get_mate_center(self, angle=0): """ Mate at ring's center rotated ``angle`` degrees. :param angle: rotation around z-axis (unit: deg) :type angle: :class:`float` :return: mate in ring's center rotated about z-axis :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem.from_plane( cadquery.Plane( origin=(0, 0, self.width / 2), xDir=(1, 0, 0), normal=(0, 0, 1), ).rotated((0, 0, angle)) # rotate about z-axis )) class _Ball(cqparts.Part): radius = PositiveFloat(10, doc="radius of sphere") def make(self): return cadquery.Workplane('XY').sphere(self.radius) class _BallRing(cqparts.Assembly): rolling_radius = PositiveFloat(8, doc="radius at which the balls roll (default: half way between outer & inner radii)") ball_diam = PositiveFloat(3, doc="diameter of ball bearings (default: distance between outer and inner radii / 2)") ball_count = IntRange(3, None, 8, doc="number of ball bearings in ring") angle = Float(0, doc="bearing's inner ring's rotation (unit: deg)") @classmethod def ball_name(cls, index): return 'ball_%03i' % index @classmethod def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int` """ min_arc = asin(((ball_diam + min_gap) / 2) / rolling_radius) * 2 return int((2 * pi) / min_arc) def make_components(self): components = {} for i in range(self.ball_count): components[self.ball_name(i)] = _Ball(radius=self.ball_diam / 2) return components def make_constraints(self): constraints = [] ball_angle = -radians(self.angle * 2) rail_angle_delta = radians(self.angle / 2) for i in range(self.ball_count): # crude, innacruate calculation. justification: ball position is just illustrative ball = self.components[self.ball_name(i)] arc_angle = i * ((pi * 2) / self.ball_count) rail_angle = arc_angle + rail_angle_delta constraints.append(constraint.Fixed( ball.mate_origin, CoordSystem( origin=( self.rolling_radius * cos(rail_angle), self.rolling_radius * sin(rail_angle), 0, ), xDir=(cos(ball_angle), sin(ball_angle), 0), normal=(0, 0, 1), ) )) return constraints @register(name='ballbearing') class BallBearing(cqparts.Assembly): """ Ball bearing .. image:: /_static/img/bearings/ball-bearing.png """ # Inner & Outer Rings outer_diam = PositiveFloat(30, doc="outer diameter") outer_width = PositiveFloat(None, doc="outer ring's thickness (default maximum / 3)") inner_diam = PositiveFloat(10, doc="inner diameter") inner_width = PositiveFloat(None, doc="inner ring's thickness (default maximum / 3)") width = PositiveFloat(5, doc="bearing width") # Rolling Elements ball_diam = PositiveFloat(None, doc="diameter of ball bearings (default: distance between outer and inner radii / 2)") rolling_radius = PositiveFloat(None, doc="radius at which the balls roll (default: half way between outer & inner radii)") tolerance = PositiveFloat(0.001, doc="gap between rolling elements and their tracks") ball_count = IntRange(3, None, None, doc="number of ball bearings") ball_min_gap = PositiveFloat(None, doc="minimum gap between balls (measured along vector between spherical centers) (default: ``ball_diam`` / 10)") # Dynamic angle = Float(0, doc="bearing's inner ring's rotation (unit: deg)") def initialize_parameters(self): if self.inner_diam >= self.outer_diam: raise ValueError("inner diameter exceeds outer: %r >= %r" % ( self.inner_diam, self.outer_diam )) # --- Inner & Outer Rings if self.outer_width is None: self.outer_width = ((self.outer_diam - self.inner_diam) / 2) / 3 if self.inner_width is None: self.inner_width = ((self.outer_diam - self.inner_diam) / 2) / 3 # --- Rolling elements if self.rolling_radius is None: self.rolling_radius = (((self.outer_diam - self.inner_diam) / 2) + self.inner_diam) / 2 if self.ball_diam is None: self.ball_diam = (self.outer_diam - self.inner_diam) / 4 if (self.rolling_radius + (self.ball_diam / 2)) > (self.outer_diam / 2): raise ValueError("rolling elements will protrude through outer ring") elif (self.rolling_radius - (self.ball_diam / 2)) < (self.inner_diam / 2): raise ValueError("rolling elements will protrude through inner ring") if self.ball_min_gap is None: self.ball_min_gap = self.ball_diam / 10 if self.ball_count is None: self.ball_count = _BallRing.get_max_ballcount( ball_diam=self.ball_diam, rolling_radius=self.rolling_radius, min_gap=self.ball_min_gap, ) else: max_ballcount = _BallRing.get_max_ballcount( ball_diam=self.ball_diam, rolling_radius=self.rolling_radius, ) if self.ball_count > max_ballcount: raise ValueError("%r balls cannot fit in bearing" % self.ball_count) super(BallBearing, self).initialize_parameters() def make_components(self): return { 'outer_ring': _Ring( outer_radius=self.outer_diam / 2, inner_radius=(self.outer_diam / 2) - self.outer_width, width=self.width, ball_radius=(self.ball_diam / 2) + self.tolerance, rolling_radius=self.rolling_radius, ), 'inner_ring': _Ring( outer_radius=(self.inner_diam / 2) + self.inner_width, inner_radius=self.inner_diam / 2, width=self.width, ball_radius=(self.ball_diam / 2) + self.tolerance, rolling_radius=self.rolling_radius, ), 'rolling_elements': _BallRing( rolling_radius=self.rolling_radius, ball_diam=self.ball_diam, ball_count=self.ball_count, angle=self.angle, ), } def make_constraints(self): outer = self.components['outer_ring'] inner = self.components['inner_ring'] ring = self.components['rolling_elements'] constraints = [ constraint.Fixed(outer.mate_origin), constraint.Coincident( inner.get_mate_center(angle=0), outer.get_mate_center(angle=self.angle) ), constraint.Coincident(ring.mate_origin, outer.mate_origin), ] # rolling elements # FIXME: use a more sensible constraint when available (see issue #30) return constraints def get_cutter(self): cutter = cadquery.Workplane('XY', origin=(0, 0, -self.width / 2)) \ .circle(self.outer_diam / 2).extrude(self.width) if self.ball_diam > self.width: cutter = cutter.union(_Ring.get_ball_torus(self.rolling_radius, self.ball_diam / 2)) return cutter @property def mate_axis_start(self): return Mate(self, CoordSystem(origin=(0, 0, -self.width / 2))) @property def mate_axis_center(self): return self.mate_origin @property def mate_axis_end(self): return Mate(self, CoordSystem(origin=(0, 0, self.width / 2)))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_bearings/__init__.py
src/cqparts_bearings/__init__.py
""" Copyright 2018 Peter Boin 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. """ # =========================== Package Information =========================== # Version Planning: # 0.1.x - Development Status :: 2 - Pre-Alpha # 0.2.x - Development Status :: 3 - Alpha # 0.3.x - Development Status :: 4 - Beta # 1.x - Development Status :: 5 - Production/Stable # <any above>.y - developments on that version (pre-release) # <any above>*.dev* - development release (intended purely to test deployment) __version__ = '0.1.0' __title__ = 'cqparts_bearings' __description__ = 'Bearings content library for cqparts' __url__ = 'https://github.com/fragmuffin/cqparts' __author__ = 'Peter Boin' __email__ = 'peter.boin+cqparts@gmail.com' __license__ = 'Apache Public License 2.0' __keywords__ = ['cadquery', 'cad', '3d', 'modeling', 'bearings'] # not text-parsable import datetime _now = datetime.date.today() __copyright__ = "Copyright {year} {author}".format(year=_now.year, author=__author__) # =========================== Functional =========================== from cqparts.search import ( register as _register, search as _search, find as _find, ) from cqparts.search import common_criteria module_criteria = { 'module': __name__, } register = common_criteria(**module_criteria)(_register) search = common_criteria(**module_criteria)(_search) find = common_criteria(**module_criteria)(_find)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_bearings/tapered_roller.py
src/cqparts_bearings/tapered_roller.py
from math import pi, radians from math import sin, cos, tan, asin, atan2 from math import sqrt import cadquery import cqparts from cqparts.params import * from cqparts import constraint from cqparts.utils import CoordSystem from . import register class _InnerRing(cqparts.Part): inner_diam = PositiveFloat(None, doc="inside diameter") height = PositiveFloat(None, doc="height of ring") base_height = Float(None, doc="base location on Z axis (usually negative)") # cone parameters roller_surface_radius = PositiveFloat(None, doc="radius of rolling surface at XY plane") roller_surface_gradient = Float(None, doc="rolling surface gradient along +Z axis") def make(self): cone_radius_at = lambda z: self.roller_surface_radius + (self.roller_surface_gradient * z) cone_radius_base = cone_radius_at(self.base_height) cone_radius_top = cone_radius_at(self.base_height + self.height) # ring base shape inner_ring = cadquery.Workplane('XY', origin=(0, 0, self.base_height)) \ .circle(max(cone_radius_base, cone_radius_top)) \ .circle(self.inner_diam / 2) \ .extrude(self.height) # intersect cone with base shape (provides conical rolling surface) if abs(self.roller_surface_gradient) > 1e-6: cone = cadquery.CQ(cadquery.Solid.makeCone( radius1=cone_radius_base, radius2=cone_radius_top, height=self.height, dir=cadquery.Vector(0, 0, 1), )).translate((0, 0, self.base_height)) inner_ring = inner_ring.intersect(cone) return inner_ring class _OuterRing(cqparts.Part): outer_diam = PositiveFloat(None, doc="outside diameter") height = PositiveFloat(None, doc="height of ring") base_height = Float(None, doc="base location on Z axis (usually negative)") # cone parameters roller_surface_radius = PositiveFloat(None, doc="radius of rolling surface at XY plane") roller_surface_gradient = Float(None, doc="rolling surface gradient along +Z axis") def make(self): # cone radii cone_radius_at = lambda z: self.roller_surface_radius + (self.roller_surface_gradient * z) cone_radius_base = cone_radius_at(self.base_height) cone_radius_top = cone_radius_at(self.base_height + self.height) # ring base shape outer_ring = cadquery.Workplane('XY', origin=(0, 0, self.base_height)) \ .circle(self.outer_diam / 2).extrude(self.height) # cut cone from base shape (provides conical rolling surface) if abs(self.roller_surface_gradient) > 1e-6: cone = cadquery.CQ(cadquery.Solid.makeCone( radius1=cone_radius_base, radius2=cone_radius_top, height=self.height, dir=cadquery.Vector(0, 0, 1), )).translate((0, 0, self.base_height)) outer_ring = outer_ring.cut(cone) else: outer_ring = outer_ring.faces('>Z') \ .circle(self.roller_surface_radius).cutThruAll() return outer_ring class _Roller(cqparts.Part): height = PositiveFloat(None, doc="roller height") radius = PositiveFloat(None, doc="radius of roller at XY plane intersection") gradient = Float(None, doc="conical surface gradient (zero is cylindrical)") base_height = Float(None, doc="height along Z axis of roller base") def make(self): cone_radius_at = lambda z: self.radius + (self.gradient * z) cone_radius_base = cone_radius_at(self.base_height) cone_radius_top = cone_radius_at(self.base_height + self.height) # intersect cone with base shape (provides conical rolling surface) if abs(self.gradient) > 1e-6: roller = cadquery.CQ(cadquery.Solid.makeCone( radius1=cone_radius_base, radius2=cone_radius_top, height=self.height, dir=cadquery.Vector(0, 0, 1), )).translate((0, 0, self.base_height)) else: roller = cadquery.Workplane('XY', origin=(0, 0, self.base_height)) \ .circle(self.radius).extrude(self.height) return roller class _RollerRing(cqparts.Assembly): rolling_radius = PositiveFloat(None, doc="distance from bearing center to rolling element rotation axis along XY plane") roller_diam = PositiveFloat(None, doc="diamter of roller at cross-section perpendicular to roller's rotation axis where bearing's axis meets XY plane") roller_height = PositiveFloat(None, doc="length of roller along its rotational axis") roller_angle = Float(None, doc="tilt of roller's rotation axis (unit: degrees)") roller_count = IntRange(3, None, None, doc="number of rollers") def _roller_params(self): # Conical rollers focal_length = tan(radians(90 - self.roller_angle)) * self.rolling_radius cone_angle = atan2( # 1/2 angle made by cone's point (unit: radians) (self.roller_diam / 2), sqrt(focal_length ** 2 + self.rolling_radius ** 2) ) gradient = -tan(cone_angle) * (1 if self.roller_angle > 0 else -1) return { 'height': self.roller_height, 'radius': self.roller_diam / 2, 'gradient': gradient, 'base_height': -self.roller_height / 2, } @classmethod def _roller_name(cls, index): return 'roller_%03i' % index def make_components(self): roller_params = self._roller_params() return { self._roller_name(i): _Roller(**roller_params) for i in range(self.roller_count) } def make_constraints(self): constraints = [] for i in range(self.roller_count): obj = self.components[self._roller_name(i)] angle = i * (360. / self.roller_count) constraints.append(constraint.Fixed( obj.mate_origin, CoordSystem().rotated((0, 0, angle)) + CoordSystem( origin=(self.rolling_radius, 0, 0), ).rotated((0, -self.roller_angle, 0)) )) return constraints @register(name='taperedrollerbearing') class TaperedRollerBearing(cqparts.Assembly): """ Taperd roller bearing, with conical rolling elements .. image:: /_static/img/bearings/tapered-roller-bearing.png """ inner_diam = PositiveFloat(20, doc="inner diameter") outer_diam = PositiveFloat(50, doc="outer diameter") height = PositiveFloat(10, doc="bearing height") # roller parameters rolling_radius = PositiveFloat(None, doc="distance from bearing center to rolling element rotation axis along XY plane") roller_diam = PositiveFloat(None, doc="diamter of roller at cross-section perpendicular to roller's rotation axis where bearing's axis meets XY plane") roller_height = PositiveFloat(8, doc="length of roller along its rotational axis") roller_angle = FloatRange(-45, 45, 10, doc="tilt of roller's rotation axis (unit: degrees)") roller_min_gap = PositiveFloat(None, doc="minimum gap between rollers") roller_count = IntRange(3, None, None, doc="number of rollers") tolerance = PositiveFloat(0.001, doc="gap between rollers and their tracks") def initialize_parameters(self): if self.roller_diam is None: self.roller_diam = ((self.outer_diam - self.inner_diam) / 2) / 3 if self.rolling_radius is None: radial_depth = (self.outer_diam - self.inner_diam) / 2 self.rolling_radius = (self.inner_diam / 2) + (0.5 * radial_depth) if self.roller_min_gap is None: self.roller_min_gap = self.roller_diam * 0.1 # default 10% roller diameter if self.roller_count is None: self.roller_count = min(self.max_roller_count, 12) @property def max_roller_count(self): """ The maximum number of balls given ``rolling_radius`` and ``roller_diam`` :return: maximum roller count :rtype: :class:`int` .. note:: Calculation is inaccurate, it assumes the roller's cross-section on a horizontal plane is circular, however a rotated cone's cross-section will be closer to eliptical than circular. """ min_arc = asin(((self.roller_diam + self.roller_min_gap) / 2) / self.rolling_radius) * 2 return int((2 * pi) / min_arc) def _roller_surface_params(self, inner): """ Inner & outer conical parameters derrived from higher-level parameters :param inner: if True inner conical surface parameters given, else outer :type inner: :class:`bool` :return: ``**kwargs`` style dict for use in ring parts :rtype: :class:`dict` return example:: { 'roller_surface_radius': 25, # radius of cone at XY plane 'roller_surface_gradient': 0.1, # rate of change of radius along z axis. } """ if self.roller_angle == 0: # Rollers are cylindrical, the maths gets a lot simpler radius_delta = (self.roller_diam / 2) + self.tolerance gradient = 0 if inner: radius = self.rolling_radius - radius_delta else: radius = self.rolling_radius + radius_delta else: # Conical rollers focal_length = tan(radians(90 - self.roller_angle)) * self.rolling_radius cone_angle = atan2( # 1/2 angle made by cone's point (unit: radians) (self.roller_diam / 2), sqrt(focal_length ** 2 + self.rolling_radius ** 2) ) multiplier = 1 multiplier *= -1 if inner else 1 multiplier *= 1 if (self.roller_angle > 0) else -1 gradient = -tan(radians(self.roller_angle) + (cone_angle * multiplier)) radius = gradient * -focal_length radius = radius + (-self.tolerance if inner else self.tolerance) return { 'roller_surface_radius': radius, # radius of cone at XY plane 'roller_surface_gradient': gradient, # rate of change of radius along z axis. } def make_components(self): return { 'inner_ring': _InnerRing( inner_diam=self.inner_diam, height=self.height, base_height=-self.height / 2, **self._roller_surface_params(inner=True) ), 'outer_ring': _OuterRing( outer_diam=self.outer_diam, height=self.height, base_height=-self.height / 2, **self._roller_surface_params(inner=False) ), 'rolling_elements': _RollerRing( rolling_radius=self.rolling_radius, roller_diam=self.roller_diam, roller_height=self.roller_height, roller_angle=self.roller_angle, roller_count=self.roller_count, ), } def make_constraints(self): inner = self.components['inner_ring'] outer = self.components['outer_ring'] return [ constraint.Fixed(inner.mate_origin), constraint.Coincident( outer.mate_origin, inner.mate_origin ), ]
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_torquelimiters/sheer_pin.py
src/cqparts_torquelimiters/sheer_pin.py
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_torquelimiters/__init__.py
src/cqparts_torquelimiters/__init__.py
""" Copyright 2018 Peter Boin 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. """ __release_ready__ = False # TODO: remove to stop blocking build
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_torquelimiters/ball_detent.py
src/cqparts_torquelimiters/ball_detent.py
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_gears/trapezoidal.py
src/cqparts_gears/trapezoidal.py
from math import pi, radians, sin, cos, acos import cadquery from cqparts.params import * from cqparts.utils import CoordSystem from cqparts.constraint import Mate from .base import Gear class TrapezoidalGear(Gear): """ Basic gear with trapezoidal tooth shape. .. image:: /_static/img/gears/trapezoidal.png """ tooth_height = PositiveFloat(None, doc="radial height of teeth") face_angle = PositiveFloat(30, doc="angle of tooth edge radial edge (unit: degrees)") spacing_ratio = FloatRange(0, 1, 0.5, doc="tooth thickness as a ratio of the distance between them") flat_top = Boolean(False, doc="if ``True`` the tops of teeth are flat") def initialize_parameters(self): super(TrapezoidalGear, self).initialize_parameters() if self.tooth_height is None: self.tooth_height = 0.2 * self.effective_radius # default: 20% effective radius def _make_tooth_template(self): """ Builds a single tooth including the cylinder with tooth faces tangential to its circumference. """ # parameters period_arc = (2 * pi) / self.tooth_count tooth_arc = period_arc * self.spacing_ratio # the arc between faces at effective_radius outer_radius = self.effective_radius + (self.tooth_height / 2) face_angle_rad = radians(self.face_angle) # cartesian isosceles trapezoid dimensions side_angle = face_angle_rad - (tooth_arc / 2) side_tangent_radius = sin(face_angle_rad) * self.effective_radius extra_side_angle = side_angle + acos(side_tangent_radius / outer_radius) tooth = cadquery.Workplane('XY', origin=(0, 0, -self.width / 2)) \ .moveTo( side_tangent_radius * cos(side_angle), side_tangent_radius * sin(side_angle) ) opposite_point = ( -side_tangent_radius * cos(side_angle), side_tangent_radius * sin(side_angle) ) if self.face_angle: tooth = tooth.lineTo(*opposite_point) #tooth = tooth.threePointArc( # (0, -side_tangent_radius), # opposite_point #) tooth = tooth.lineTo( -cos(extra_side_angle) * outer_radius, sin(extra_side_angle) * outer_radius ) opposite_point = ( cos(extra_side_angle) * outer_radius, sin(extra_side_angle) * outer_radius ) if self.flat_top: tooth = tooth.lineTo(*opposite_point) else: tooth = tooth.threePointArc((0, outer_radius), opposite_point) tooth = tooth.close().extrude(self.width) return tooth def make(self): # create inside cylinder inner_radius = self.effective_radius - (self.tooth_height / 2) gear = cadquery.Workplane('XY', origin=(0, 0, -self.width / 2)) \ .circle(inner_radius).extrude(self.width) # copy & rotate once per tooth tooth_template = self._make_tooth_template() period_arc = 360. / self.tooth_count for i in range(self.tooth_count): gear = gear.union( CoordSystem().rotated((0, 0, i * period_arc)) + tooth_template ) return gear @property def mate_top(self): return Mate(self, CoordSystem((0, 0, self.width / 2))) @property def mate_bottom(self): return Mate(self, CoordSystem((0, 0, -self.width / 2)))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_gears/__init__.py
src/cqparts_gears/__init__.py
""" Copyright 2018 Peter Boin 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. """ __all__ = [ 'trapezoidal', ] from . import trapezoidal
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_gears/base.py
src/cqparts_gears/base.py
import cadquery import cqparts from cqparts.params import * class Gear(cqparts.Part): effective_radius = PositiveFloat(25, doc="designed equivalent wheel radius") tooth_count = PositiveInt(12, doc="number of teeth") width = PositiveFloat(10, doc="gear thickness") def make_simple(self): return cadquery.Workplane('XY', origin=(0, 0, -self.width)) \ .circle(self.effective_radius).extrude(self.width)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py
src/cqparts/search.py
from collections import defaultdict from copy import copy from .errors import SearchMultipleFoundError, SearchNoneFoundError # Search Index # of the format: # index = { # <category>: { # <value>: set([<set of classes>]), # ... more values # }, # ... more categories # } index = defaultdict(lambda: defaultdict(set)) class_list = set() # class_criteria, of the format: # class_criteria = { # <Component class>: { # <category>: set([<set of values>]), # ... more categories # }, # ... more classes # } class_criteria = {} def register(**criteria): """ class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( type='motor', current_class='dc', part_number='ABC123X', ) class SomeMotor(cqparts.Assembly): shaft_diam = PositiveFloat(5) def make_components(self): return {} # build assembly content motor_class = cqparts.search.find(part_number='ABC123X') motor = motor_class(shaft_diam=6.0) Then use :meth:`find` &/or :meth:`search` to instantiate it. .. warning:: Multiple classes *can* be registered with identical criteria, but should be avoided. If multiple classes share the same criteria, :meth:`find` will never yield the part you want. Try adding unique criteria, such as *make*, *model*, *part number*, *library name*, &/or *author*. To avoid this, learn more in :ref:`tutorial_component-index`. """ def inner(cls): # Add class references to search index class_list.add(cls) for (category, value) in criteria.items(): index[category][value].add(cls) # Retain search criteria _entry = dict((k, set([v])) for (k, v) in criteria.items()) if cls not in class_criteria: class_criteria[cls] = _entry else: for key in _entry.keys(): class_criteria[cls][key] = class_criteria[cls].get(key, set()) | _entry[key] # Return class return cls return inner def search(**criteria): """ Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: from cqparts.search import search import cqparts_motors # example of a 3rd party lib # Get all DC motor classes dc_motors = search(type='motor', current_class='dc') # For more complex queries: air_cooled = search(cooling='air') non_aircooled_dcmotors = dc_motors - air_cooled # will be all DC motors that aren't air-cooled """ # Find all parts that match the given criteria results = copy(class_list) # start with full list for (category, value) in criteria.items(): results &= index[category][value] return results def find(**criteria): """ Find a single *component* class with the given criteria. Finds classes indexed with :meth:`register` :raises SearchMultipleFoundError: if more than one result found :raises SearchNoneFoundError: if nothing found :: from cqparts.search import find import cqparts_motors # example of a 3rd party lib # get a specific motor class motor_class = find(type='motor', part_number='ABC123X') motor = motor_class(shaft_diameter=6.0) """ # Find all parts that match the given criteria results = search(**criteria) # error cases if len(results) > 1: raise SearchMultipleFoundError("%i results found" % len(results)) elif not results: raise SearchNoneFoundError("%i results found" % len(results)) # return found Part|Assembly class return results.pop() def common_criteria(**common): """ Wrap a function to always call with the given ``common`` named parameters. :property common: criteria common to your function call :return: decorator function :rtype: :class:`function` .. doctest:: >>> import cqparts >>> from cqparts.search import register, search, find >>> from cqparts.search import common_criteria >>> # Somebody elses (boring) library may register with... >>> @register(a='one', b='two') ... class BoringThing(cqparts.Part): ... pass >>> # But your library is awesome; only registering with unique criteria... >>> lib_criteria = { ... 'author': 'your_name', ... 'libname': 'awesome_things', ... } >>> awesome_register = common_criteria(**lib_criteria)(register) >>> @awesome_register(a='one', b='two') # identical to BoringThing ... class AwesomeThing(cqparts.Part): ... pass >>> # So lets try a search >>> len(search(a='one', b='two')) # doctest: +SKIP 2 >>> # oops, that returned both classes >>> # To narrow it down, we add something unique: >>> len(search(a='one', b='two', libname='awesome_things')) # finds only yours # doctest: +SKIP 1 >>> # or, we could use common_criteria again... >>> awesome_search = common_criteria(**lib_criteria)(search) >>> awesome_find = common_criteria(**lib_criteria)(find) >>> len(awesome_search(a='one', b='two')) # doctest: +SKIP 1 >>> awesome_find(a='one', b='two').__name__ 'AwesomeThing' A good universal way to apply unique criteria is with .. testcode:: import cadquery, cqparts from cqparts.search import register, common_criteria _register = common_criteria(module=__name__)(register) @_register(shape='cube', scale='unit') class Cube(cqparts.Part): # just an example... def make(self): return cadquery.Workplane('XY').box(1, 1, 1) """ def decorator(func): def inner(*args, **kwargs): merged_kwargs = copy(common) merged_kwargs.update(kwargs) return func(*args, **merged_kwargs) return inner return decorator
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/part.py
src/cqparts/part.py
import cadquery import six from copy import copy from .params import Boolean from .display.material import ( RenderParam, TEMPLATE as RENDER_TEMPLATE, ) from .errors import MakeError, ParameterError, AssemblyFindError from .constraint import Constraint, Mate from .utils.geometry import CoordSystem import logging log = logging.getLogger(__name__) from .component import Component class Part(Component): # Parameters common to every Part _simple = Boolean(False, doc="if set, simplified geometry is built") _render = RenderParam(RENDER_TEMPLATE['default'], doc="render properties") def __init__(self, *largs, **kwargs): super(Part, self).__init__(*largs, **kwargs) # Initializing Instance State self._local_obj = None self._world_obj = None def make(self): """ Create and return solid part :return: cadquery.Workplane of the part in question :rtype: subclass of :class:`cadquery.CQ`, usually a :class:`cadquery.Workplane` .. important:: This must be overridden in your ``Part`` The outcome of this function should be accessed via cqparts.Part.object """ raise NotImplementedError("make function not implemented") def make_simple(self): """ Create and return *simplified* solid part. The simplified representation of a ``Part`` is to lower the export quality of an ``Assembly`` or ``Part`` for rendering. Overriding this is optional, but highly recommended. The default behaviour returns the full complexity object's bounding box. But to do this, theh full complexity object must be generated first. There are 2 main problems with this: #. building the full complexity part is not efficient. #. a bounding box may not be a good representation of the part. **Bolts** A good example of this is a bolt. * building a bolt's thread is not a trivial task; it can take some time to generate. * a box is not a good visual representation of a bolt So for the ``Fastener`` parts, all ``make_simple`` methods are overridden to provide 2 cylinders, one for the bolt's head, and another for the thread. """ complex_obj = self.make() bb = complex_obj.findSolid().BoundingBox() simple_obj = cadquery.Workplane('XY', origin=(bb.xmin, bb.ymin, bb.zmin)) \ .box(bb.xlen, bb.ylen, bb.zlen, centered=(False, False, False)) return simple_obj def build(self, recursive=False): """ Building a part buffers the ``local_obj`` attribute. Running ``.build()`` is optional, it's mostly used to test that there aren't any critical runtime issues with it's construction. :param recursive: (:class:`Part` has no children, parameter ignored) """ self.local_obj # force object's construction, but don't do anything with it # ----- Local Object @property def local_obj(self): """ Buffered result of :meth:`make` which is (probably) a :class:`cadquery.Workplane` instance. If ``_simple`` is ``True``, then :meth:`make_simple` is returned instead. .. note:: This is usually the correct way to get your part's object for rendering, exporting, or measuring. Only call :meth:`cqparts.Part.make` directly if you explicitly intend to re-generate the model from scratch, then dispose of it. """ if self._local_obj is None: # Simplified or Complex if self._simple: value = self.make_simple() else: value = self.make() # Verify type if not isinstance(value, cadquery.CQ): raise MakeError("invalid object type returned by make(): %r" % value) # Buffer object self._local_obj = value return self._local_obj @local_obj.setter def local_obj(self, value): self._local_obj = value self._world_obj = None # ----- World Object @property def world_obj(self): """ The :meth:`local_obj <local_obj>` object in the :meth:`world_coords <Component.world_coords>` coordinate system. .. note:: This is automatically generated when called, and :meth:`world_coords <Component.world_coords>` is not ``Null``. """ if self._world_obj is None: local_obj = self.local_obj world_coords = self.world_coords if (local_obj is not None) and (world_coords is not None): # Copy local object, apply transform to move to its new home. self._world_obj = world_coords + local_obj return self._world_obj @world_obj.setter def world_obj(self, value): # implemented just for this helpful message raise ValueError("can't set world_obj directly, set local_obj instead") @property def bounding_box(self): """ Generate a bounding box based on the full complexity part. :return: bounding box of part :rtype: cadquery.BoundBox """ if self.world_coords: return self.world_obj.findSolid().BoundingBox() return self.local_obj.findSolid().BoundingBox() def _placement_changed(self): self._world_obj = None
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/component.py
src/cqparts/component.py
from .params import ParametricObject from .constraint import Mate from .utils import CoordSystem class Component(ParametricObject): """ .. note:: Both the :class:`Part` and :class:`Assembly` classes inherit from ``Component``. Wherever the term "*component*" is used, it is in reference to an instance of either :class:`Part` **or** :class:`Assembly`. """ def __init__(self, *largs, **kwargs): super(Component, self).__init__(*largs, **kwargs) # Initializing Instance State self._world_coords = None def build(self, recursive=True): """ :raises NotImplementedError: must be overridden by inheriting classes to function """ raise NotImplementedError("build not implemented for %r" % type(self)) def _placement_changed(self): # called when: # - world_coords is set # (intended to be overridden by inheriting classes) pass @property def world_coords(self): """ Component's placement in word coordinates (:class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`) :return: coordinate system in the world, ``None`` if not set. :rtype: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` """ return self._world_coords @world_coords.setter def world_coords(self, value): self._world_coords = value self._placement_changed() @property def mate_origin(self): """ :return: mate at object's origin :rtype: :class:`Mate` """ return Mate(self, CoordSystem()) # ----- Export / Import def exporter(self, exporter_name=None): """ Get an exporter instance to write the component's content to file. :param exporter_name: registered name of exporter to use, see :meth:`register_exporter() <cqparts.codec.register_exporter>` for more information. :type exporter_name: :class:`str` For example, to get a :class:`ThreejsJSONExporter <cqparts.codec.ThreejsJSONExporter>` instance to import a ``json`` file: .. doctest:: >>> from cqparts_misc.basic.primatives import Box >>> box = Box() >>> json_exporter = box.exporter('json') >>> # then each exporter will behave differently >>> json_exporter('out.json') # doctest: +SKIP To learn more: :ref:`parts_import-export` """ from .codec import get_exporter return get_exporter(self, exporter_name) @classmethod def importer(cls, importer_name=None): """ Get an importer instance to instantiate a component from file. :param importer_name: registered name of importer to use, see :meth:`register_importer() <cqparts.codec.register_importer>` for more information. :type importer_name: :class:`str` For example, to get an importer to instantiate a :class:`Part` from a ``STEP`` file: .. doctest:: >>> from cqparts import Part >>> step_importer = Part.importer('step') >>> # then each importer will behave differently >>> my_part = step_importer('my_file.step') # doctest: +SKIP To learn more: :ref:`parts_import-export` """ from .codec import get_importer return get_importer(cls, importer_name)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/assembly.py
src/cqparts/assembly.py
import six import string import re from types import GeneratorType from .component import Component from .constraint import Constraint from .constraint.solver import solver from .utils.misc import indicate_last from .utils.geometry import merge_boundboxes from .errors import AssemblyFindError import logging log = logging.getLogger(__name__) # Component Name Validity, considering: # - chosen delimiter, and # - usage as filename VALID_NAME_CHARS = set( string.ascii_letters + string.digits + # alphanumeric '_()#@%^=+ ' ) # note: does not include # `.` - threejs removes '.' from filenames, leading to incompatability (see PR #147) # `-` - chosen delimiter class Assembly(Component): """ An assembly is a group of parts, and other assemblies (called components) """ def __init__(self, *largs, **kwargs): super(Assembly, self).__init__(*largs, **kwargs) self._components = None self._constraints = None def make_components(self): """ Create and return :class:`dict` of :class:`Component` instances. .. tip:: This **must** be overridden in inheriting class, read: * :ref:`parts_assembly-build-cycle` for details. * :ref:`tutorial_assembly` for an example. :return: {<name>: <Component>, ...} :rtype: :class:`dict` of :class:`Component` instances """ raise NotImplementedError("make_components function not implemented") def make_constraints(self): """ Create and return :class:`list` of :class:`Constraint <cqparts.constraint.base.Constraint>` instances .. tip:: This **must** be overridden in inheriting class, read: * :ref:`parts_assembly-build-cycle` for details. * :ref:`tutorial_assembly` for an example. :return: constraints for assembly children's placement :rtype: :class:`list` of :class:`Constraint <cqparts.constraint.base.Constraint>` instances Default behaviour returns an empty list; assumes assembly is entirely unconstrained. """ raise NotImplementedError("make_constraints function not implemented") def make_alterations(self): """ Make necessary changes to components after the constraints solver has completed. .. tip:: This *can* be overridden in inheriting class, read: * :ref:`parts_assembly-build-cycle` for details. * :ref:`tutorial_assembly` for an example. """ pass @property def components(self): """ Returns full :class:`dict` of :class:`Component` instances, after a successful :meth:`build` :return: dict of named :class:`Component` instances :rtype: :class:`dict` For more information read about the :ref:`parts_assembly-build-cycle` . """ if self._components is None: self.build(recursive=False) return self._components @property def constraints(self): """ Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after a successful :meth:`build` :return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances :rtype: :class:`list` For more information read about the :ref:`parts_assembly-build-cycle` . """ if self._constraints is None: self.build(recursive=False) return self._constraints def _placement_changed(self): """ Called when ``world_coords`` is changed. All components' ``world_coords`` must be updated based on the change; calls :meth:`solve`. """ self.solve() def solve(self): """ Run the solver and assign the solution's :class:`CoordSystem` instances as the corresponding part's world coordinates. """ if self.world_coords is None: log.warning("solving for Assembly without world coordinates set: %r", self) for (component, world_coords) in solver(self.constraints, self.world_coords): component.world_coords = world_coords @staticmethod def verify_components(components): """ Verify values returned from :meth:`make_components`. Used internally during the :meth:`build` process. :param components: value returned from :meth:`make_components` :type components: :class:`dict` :raises ValueError: if verification fails """ # verify returned type from user-defined function if not isinstance(components, dict): raise ValueError( "invalid type returned by make_components(): %r (must be a dict)" % components ) # check types for (name, component) pairs in dict for (name, component) in components.items(): # name is a string if not isinstance(name, str): raise ValueError(( "invalid name from make_components(): (%r, %r) " "(must be a (str, Component))" ) % (name, component)) # component is a Component instance if not isinstance(component, Component): raise ValueError(( "invalid component type from make_components(): (%r, %r) " "(must be a (str, Component))" ) % (name, component)) # check component name validity invalid_chars = set(name) - VALID_NAME_CHARS if invalid_chars: raise ValueError( "component name {!r} invalid; cannot include {!r}".format( name, invalid_chars ) ) @staticmethod def verify_constraints(constraints): """ Verify values returned from :meth:`make_constraints`. Used internally during the :meth:`build` process. :param constraints: value returned from :meth:`make_constraints` :type constraints: :class:`list` :raises ValueError: if verification fails """ # verify return is a list if not isinstance(constraints, list): raise ValueError( "invalid type returned by make_constraints: %r (must be a list)" % constraints ) # verify each list element is a Constraint instance for constraint in constraints: if not isinstance(constraint, Constraint): raise ValueError( "invalid constraint type: %r (must be a Constriant)" % constraint ) def build(self, recursive=True): """ Building an assembly buffers the :meth:`components` and :meth:`constraints`. Running ``build()`` is optional, it's automatically run when requesting :meth:`components` or :meth:`constraints`. Mostly it's used to test that there aren't any critical runtime issues with its construction, but doing anything like *displaying* or *exporting* will ultimately run a build anyway. :param recursive: if set, iterates through child components and builds those as well. :type recursive: :class:`bool` """ # initialize values self._components = {} self._constraints = [] def genwrap(obj, name, iter_type=None): # Force obj to act like a generator. # this wrapper will always yield at least once. if isinstance(obj, GeneratorType): for i in obj: if (iter_type is not None) and (not isinstance(i, iter_type)): raise TypeError("%s must yield a %r" % (name, iter_type)) yield i else: if (iter_type is not None) and (not isinstance(obj, iter_type)): raise TypeError("%s must return a %r" % (name, iter_type)) yield obj # Make Components components_iter = genwrap(self.make_components(), "make_components", dict) new_components = next(components_iter) self.verify_components(new_components) self._components.update(new_components) # Make Constraints constraints_iter = genwrap(self.make_constraints(), "make_components", list) new_constraints = next(constraints_iter) self.verify_constraints(new_constraints) self._constraints += new_constraints # Run solver : sets components' world coordinates self.solve() # Make Alterations alterations_iter = genwrap(self.make_alterations(), "make_alterations") next(alterations_iter) # return value is ignored while True: (s1, s2, s3) = (True, True, True) # stages # Make Components new_components = None try: new_components = next(components_iter) self.verify_components(new_components) self._components.update(new_components) except StopIteration: s1 = False # Make Constraints new_constraints = None try: new_constraints = next(constraints_iter) self.verify_constraints(new_constraints) self._constraints += new_constraints except StopIteration: s2 = False # Run solver : sets components' world coordinates if new_components or new_constraints: self.solve() # Make Alterations try: next(alterations_iter) # return value is ignored except StopIteration: s3 = False # end loop when all iters are finished if not any((s1, s2, s3)): break if recursive: for (name, component) in self._components.items(): component.build(recursive=recursive) @property def bounding_box(self): """ Bounding box for the combination of all components in this assembly. """ return merge_boundboxes(*( component.bounding_box for component in self.components.values() )) def find(self, keys, _index=0): """ :param keys: key path. ``'a.b'`` is equivalent to ``['a', 'b']`` :type keys: :class:`str` or :class:`list` Find a nested :class:`Component` by a "`.`" separated list of names. for example:: >>> motor.find('bearing.outer_ring') would return the Part instance of the motor bearing's outer ring. :: >>> bearing = motor.find('bearing') >>> ring = bearing.find('inner_ring') # equivalent of 'bearing.inner_ring' the above code does much the same thing, ``bearing`` is an :class:`Assembly`, and ``ring`` is a :class:`Part`. .. note:: For a key path of ``a.b.c`` the ``c`` key can referernce any :class:`Component` type. Everything prior (in this case ``a`` and ``b``) must reference an :class:`Assembly`. """ if isinstance(keys, six.string_types): keys = re.split(r'[\.-]+', keys) if _index >= len(keys): return self key = keys[_index] if key in self.components: component = self.components[key] if isinstance(component, Assembly): return component.find(keys, _index=(_index + 1)) elif _index == len(keys) - 1: # this is the last search key; component is a leaf, return it return component else: raise AssemblyFindError( "could not find '%s' (invalid type at [%i]: %r)" % ( '.'.join(keys), _index, component ) ) else: raise AssemblyFindError( "could not find '%s', '%s' is not a component of %r" % ( '.'.join(keys), key, self ) ) # Component Tree def tree_str(self, name=None, prefix='', add_repr=False, _depth=0): u""" Return string listing recursively the assembly hierarchy :param name: if set, names the tree's trunk, otherwise the object's :meth:`repr` names the tree :type name: :class:`str` :param prefix: string prefixed to each line, can be used to indent :type prefix: :class:`str` :param add_repr: if set, *component* :meth:`repr` is put after their names :type add_repr: :class:`bool` :return: Printable string of an assembly's component hierarchy. :rtype: :class:`str` Example output from `block_tree.py <https://github.com/fragmuffin/cqparts/blob/master/tests/manual/block_tree.py>`_ :: >>> log = logging.getLogger(__name__) >>> isinstance(block_tree, Assembly) True >>> log.info(block_tree.tree_str(name="block_tree")) block_tree \u251c\u25cb branch_lb \u251c\u25cb branch_ls \u251c\u2500 branch_r \u2502 \u251c\u25cb L \u2502 \u251c\u25cb R \u2502 \u251c\u25cb branch \u2502 \u251c\u2500 house \u2502 \u2502 \u251c\u25cb bar \u2502 \u2502 \u2514\u25cb foo \u2502 \u2514\u25cb split \u251c\u25cb trunk \u2514\u25cb trunk_split Where: * ``\u2500`` denotes an :class:`Assembly`, and * ``\u25cb`` denotes a :class:`Part` """ # unicode characters c_t = u'\u251c' c_l = u'\u2514' c_dash = u'\u2500' c_o = u'\u25cb' c_span = u'\u2502' output = u'' if not _depth: # first line output = prefix if name: output += (name + u': ') if add_repr else name if add_repr or not name: output += repr(self) output += '\n' # build tree for (is_last, (name, component)) in indicate_last(sorted(self.components.items(), key=lambda x: x[0])): branch_chr = c_l if is_last else c_t if isinstance(component, Assembly): # Assembly: also list nested components output += prefix + ' ' + branch_chr + c_dash + u' ' + name if add_repr: output += ': ' + repr(component) output += '\n' output += component.tree_str( prefix=(prefix + (u' ' if is_last else (u' ' + c_span + ' '))), add_repr=add_repr, _depth=_depth + 1, ) else: # Part (assumed): leaf node output += prefix + ' ' + branch_chr + c_o + u' ' + name if add_repr: output += ': ' + repr(component) output += '\n' return output
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/errors.py
src/cqparts/errors.py
# Build Exceptions class ParameterError(Exception): """Raised when an invalid parameter is specified""" class MakeError(Exception): """Raised when there are issues during the make() process of a Part or Assembly""" # Internal Search Exceptions class AssemblyFindError(Exception): """Raised when an assembly element cannot be found""" # Solids Validity class SolidValidityError(Exception): """Raised when an unrecoverable issue occurs with a solid""" # Search Exceptions class SearchError(Exception): """ Raised by search algithms, for example :meth:`cqparts.search.find` Parent of both :class:`SearchNoneFoundError` & :class:`SearchMultipleFoundError` .. doctest:: >>> from cqparts.errors import SearchError >>> from cqparts.search import find >>> try: ... part_a_class = find(a='common', b='criteria') # multiple results ... part_b_class = find(a="doesn't exist") # no results ... except SearchError: ... # error handling? ... pass """ class SearchNoneFoundError(SearchError): """Raised when no results are found by :meth:`cqparts.search.find`""" class SearchMultipleFoundError(SearchError): """Raised when multiple results are found by :meth:`cqparts.search.find`"""
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/__init__.py
src/cqparts/__init__.py
""" Copyright 2018 Peter Boin 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. """ # =========================== Package Information =========================== # Version Planning: # 0.1.x - Development Status :: 2 - Pre-Alpha # 0.2.x - Development Status :: 3 - Alpha # 0.3.x - Development Status :: 4 - Beta # 1.x - Development Status :: 5 - Production/Stable # <any above>.y - developments on that version (pre-release) # <any above>*.dev* - development release (intended purely to test deployment) __version__ = '0.2.2.dev1' __title__ = 'cqparts' __description__ = 'Hierarchical and deeply parametric models using cadquery' __url__ = 'https://github.com/cqparts/cqparts' __author__ = 'Peter Boin' __email__ = 'peter.boin+cqparts@gmail.com' __license__ = 'Apache Public License 2.0' __keywords__ = ['cadquery', 'cad', '3d', 'modeling'] # package_data import inspect as _inspect import os as _os _this_path = _os.path.dirname(_os.path.abspath(_inspect.getfile(_inspect.currentframe()))) __package_data__ = [] # append display/web-templates (recursive) _web_template_path = _os.path.join(_this_path, 'display', 'web-template') for (root, subdirs, files) in _os.walk(_web_template_path): dir_name = _os.path.relpath(root, _this_path) __package_data__.append(_os.path.join(dir_name, '*')) # not text-parsable import datetime _now = datetime.date.today() __copyright__ = "Copyright {year} {author}".format(year=_now.year, author=__author__) # =========================== Imports =========================== __all__ = [ # Sub-modules # bringing scope closer to cqparts for commonly used classes 'Component', 'Part', 'Assembly', # Modules 'catalogue', 'codec', 'constraint', 'display', 'errors', 'params', 'search', 'utils', ] # Sub-modules from .component import Component from .part import Part from .assembly import Assembly from . import catalogue from . import codec from . import constraint from . import display from . import errors from . import params from . import search from . import utils
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/gltf.py
src/cqparts/codec/gltf.py
import os import struct import base64 from io import BytesIO from itertools import chain from copy import copy, deepcopy import json from collections import defaultdict import numpy from cadquery import Vector from . import Exporter, register_exporter from .. import __version__ from .. import Component, Part, Assembly from ..utils import CoordSystem, measure_time import logging log = logging.getLogger(__name__) class WebGL: """ Enumeration container (nothing special). .. doctest:: >>> from cqparts.codec.gltf import WebGL >>> WebGL.ARRAY_BUFFER 34962 This class purely exists to make the code more readable. All enumerations transcribed from `the spec' <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0>`_ where needed. """ # accessor.componentType BYTE = 5120 UNSIGNED_BYTE = 5121 SHORT = 5122 UNSIGNED_SHORT = 5123 UNSIGNED_INT = 5125 FLOAT = 5126 # bufferView.target ARRAY_BUFFER = 34962 ELEMENT_ARRAY_BUFFER = 34963 # mesh.primative.mode POINTS = 0 LINES = 1 LINE_LOOP = 2 LINE_STRIP = 3 TRIANGLES = 4 TRIANGLE_STRIP = 5 TRIANGLE_FAN = 6 def _list3_min(l_a, l_b): return [min((a, b)) for (a, b) in zip(l_a if l_a else l_b, l_b)] def _list3_max(l_a, l_b): return [max((a, b)) for (a, b) in zip(l_a if l_a else l_b, l_b)] class ShapeBuffer(object): """ Write byte buffer for a set of polygons To create a buffer for a single polygon: .. doctest:: >>> from cqparts.codec.gltf import ShapeBuffer >>> sb = ShapeBuffer() >>> # Populate data >>> sb.add_vertex(0, 0, 0) # [0] >>> sb.add_vertex(1, 0, 0) # [1] >>> sb.add_vertex(0, 1, 0) # [2] >>> sb.add_poly_index(0, 1, 2) >>> # write to file >>> with open('single-poly.bin', 'wb') as fh: # doctest: +SKIP ... for chunk in sb.buffer_iter(): # doctest: +SKIP ... fh.write(chunk) # doctest: +SKIP >>> # get sizes (relevant for bufferViews, and accessors) >>> (sb.vert_len, sb.vert_offset, sb.vert_size) (36L, 0, 3L) >>> (sb.idx_len, sb.idx_offset, sb.idx_size) (3L, 36L, 3L) """ def __init__(self, max_index=0xff): """ :param max_index: maximum index number, if > 65535, 4-byte integers are used :type max_index: :class:`long` """ self.vert_data = BytesIO() # vertex positions self.idx_data = BytesIO() # indices connecting vertices into polygons # vertices min/max2 self.vert_min = None self.vert_max = None # indices number format self.max_index = max_index if max_index > 0xffff: (self.idx_fmt, self.idx_type, self.idx_bytelen) = ('<I', WebGL.UNSIGNED_INT, 4) elif max_index > 0xff: (self.idx_fmt, self.idx_type, self.idx_bytelen) = ('<H', WebGL.UNSIGNED_SHORT, 2) else: (self.idx_fmt, self.idx_type, self.idx_bytelen) = ('B', WebGL.UNSIGNED_BYTE, 1) @property def vert_len(self): """ Number of bytes in ``vert_data`` buffer. """ return int(self.vert_data.tell()) @property def vert_offset(self): """ Offset (in bytes) of the ``vert_data`` buffer. """ return 0 @property def vert_size(self): r""" Size of ``vert_data`` in groups of 3 floats (ie: number of :math:`3 \times 4` byte groups) See `Accessor Element Size <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#accessor-element-size>`_ in the glTF docs for clarification. """ # size of position buffer, in groups of 3 floats return int(self.vert_len / (3 * 4)) @property def idx_len(self): """ Number of bytes in ``idx_data`` buffer. """ return int(self.idx_data.tell()) @property def idx_offset(self): """ Offset (in bytes) of the ``idx_data`` buffer. """ # after vert_data return self.vert_offset + self.vert_len @property def idx_size(self): """ Number of ``idx_data`` elements. (ie: number of 2 or 4 byte groups) See `Accessor Element Size <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#accessor-element-size>`_ in the glTF docs for clarification. """ return int(self.idx_len / self.idx_bytelen) def __len__(self): return self.vert_len + self.idx_len def add_vertex(self, x, y, z): """ Add a ``VEC3`` of ``floats`` to the ``vert_data`` buffer """ self.vert_data.write( struct.pack('<f', x) + struct.pack('<f', y) + struct.pack('<f', z) ) # retain min/max values self.vert_min = _list3_min(self.vert_min, (x, y, z)) self.vert_max = _list3_max(self.vert_max, (x, y, z)) def add_poly_index(self, i, j, k): """ Add 3 ``SCALAR`` of ``uint`` to the ``idx_data`` buffer. """ self.idx_data.write( struct.pack(self.idx_fmt, i) + struct.pack(self.idx_fmt, j) + struct.pack(self.idx_fmt, k) ) def buffer_iter(self, block_size=1024): """ Iterate through chunks of the vertices, and indices buffers seamlessly. .. note:: To see a usage example, look at the :class:`ShapeBuffer` description. """ streams = ( self.vert_data, self.idx_data, ) # Chain streams seamlessly for stream in streams: stream.seek(0) while True: chunk = stream.read(block_size) if chunk: yield chunk else: break # When complete, each stream position should be reset; # back to the end of the stream. def read(self): """ Read buffer out as a single stream. .. warning:: Avoid using this function! **Why?** This is a *convenience* function; it doesn't encourage good memory management. All memory required for a mesh is duplicated, and returned as a single :class:`str`. So at best, using this function will double the memory required for a single model. **Instead:** Wherever possible, please use :meth:`buffer_iter`. """ buffer = BytesIO() for chunk in self.buffer_iter(): log.debug('buffer.write(%r)', chunk) buffer.write(chunk) buffer.seek(0) return buffer.read() @register_exporter('gltf', Component) class GLTFExporter(Exporter): u""" Export :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to a *glTF 2.0* format. =============== ====================== **Name** ``gltf`` **Exports** :class:`Part <cqparts.Part>` & :class:`Assembly <cqparts.Assembly>` **Spec** `glTF 2.0 <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0>`_ =============== ====================== **Exporting a Box:** For this example we'll instantiate an existing ``Part`` class, a simple :class:`Box <cqparts_misc.basic.primatives.Box>`:: >>> import cpqarts >>> from cqparts_misc.basic.primatives import Box >>> box = Box() >>> box.exporter('gltf')('box.gltf', embed=True) Will export a single file ``box.gltf`` with mesh data encoded into it as a string. **Embedding vs .bin Files:** default generates ``.bin`` files If ``embed`` is ``True`` when :meth:`calling <__call__>`, then all data is stored in the output ``.gltf`` file. However this is very inefficient, for larger, more complex models when loading on a web-interface. When not embedded, all geometry will be stored as binary ``.bin`` files in the same directory as the root ``.gltf`` file. For example, if we use the ``car`` from :ref:`tutorial_assembly`, with the hierarchy:: >>> car = Car() >>> print(car.tree_str(name='car')) car \u251c\u25cb chassis \u251c\u2500 front_axle \u2502 \u251c\u25cb axle \u2502 \u251c\u25cb left_wheel \u2502 \u2514\u25cb right_wheel \u2514\u2500 rear_axle \u251c\u25cb axle \u251c\u25cb left_wheel \u2514\u25cb right_wheel >>> car.exporter('gltf')('car.gltf', embed=False) When exported, a ``.bin`` file will be created for each :class:`Part <cqparts.Part>` (denoted by a ``\u25cb``). So the following files will be generated:: car.gltf car.chassis.bin car.front_axle.axle.bin car.front_axle.left_wheel.bin car.front_axle.right_wheel.bin car.rear_axle.axle.bin car.rear_axle.left_wheel.bin car.rear_axle.right_wheel.bin The ``car.gltf`` will reference each of the ``.bin`` files. The ``car.gltf`` and **all** ``.bin`` files should be web-hosted to serve the scene correctly. .. todo:: In this example, all *wheels* and *axles* are the same, they should only generate a single buffer. But how to definitively determine :class:`Part <cqparts.Part>` instance equality? """ scale = 0.001 # mm to meters TEMPLATE = { # Static values "asset": { "generator": "cqparts_%s" % __version__, "version": "2.0" # glTF version }, "scene": 0, # Populated by adding parts "scenes": [{"nodes": [0]}], "nodes": [ { "children": [], # will be appended to before writing to file # scene rotation to suit glTF coordinate system # ref: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#coordinate-system-and-units "matrix": [ 1.0 * scale, 0.0, 0.0, 0.0, 0.0, 0.0,-1.0 * scale, 0.0, 0.0, 1.0 * scale, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, ], }, ], "meshes": [], "accessors": [], "materials": [], "bufferViews": [], "buffers": [], } # error tolerance of vertices to true face value, only relevant for curved surfaces. default_tolerance = 0.01 def __init__(self, *args, **kwargs): self.tolerance = kwargs.pop('tolerance', self.default_tolerance) super(GLTFExporter, self).__init__(*args, **kwargs) # Initialize self.gltf_dict = deepcopy(self.TEMPLATE) self.scene_min = None self.scene_max = None def __call__(self, filename='out.gltf', embed=False, tolerance=None): """ :param filename: name of ``.gltf`` file to export :type filename: :class:`str` :param embed: if True, binary content is embedded in json object. :type embed: :class:`bool` :param tolerance: maximum polygonal error (optional) :type tolerance: :class:`float` """ if tolerance is None: tolerance = self.tolerance def add(obj, filename, name, origin, parent_node_index=0): split = os.path.splitext(filename) if isinstance(obj, Assembly): # --- Assembly obj_world_coords = obj.world_coords if obj_world_coords is None: obj_world_coords = CoordSystem() relative_coordsys = obj_world_coords - origin # Add empty node to serve as a parent node_index = len(self.gltf_dict['nodes']) node = {} node.update(self.coordsys_dict(relative_coordsys)) if name: node['name'] = name self.gltf_dict['nodes'].append(node) # Add this node to its parent parent_node = self.gltf_dict['nodes'][parent_node_index] parent_node['children'] = parent_node.get('children', []) + [node_index] for (child_name, child) in obj.components.items(): # Full name of child (including '.' separated list of all parents) full_name = "%s-%s" % (name, child_name) # Recursively add children add( child, filename="%s-%s%s" % (split[0], child_name, split[1]), name="%s-%s" % (name, child_name), origin=obj_world_coords, parent_node_index=node_index, ) else: # --- Part self.add_part( obj, filename=None if embed else filename, name=name, origin=origin, parent_idx=parent_node_index, tolerance=tolerance, ) split = os.path.splitext(filename) if self.obj.world_coords is None: self.obj.world_coords = CoordSystem() if isinstance(self.obj, Assembly): self.obj.solve() # should this be obj.build()? add( obj=self.obj, filename="%s.bin" % split[0], origin=self.obj.world_coords, name=os.path.splitext(os.path.basename(filename))[0], ) # Write self.gltf_dict to file as JSON string with open(filename, 'w') as fh: fh.write(json.dumps(self.gltf_dict, indent=2, sort_keys=True)) @classmethod def coordsys_dict(cls, coord_sys, matrix=True): """ Return coordinate system as `gltf node transform <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#transformations>`_ :param coord_sys: Coordinate system to transform :type coord_sys: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` :return: node transform keys & values :rtype: :class:`dict` """ node_update = {} if matrix: m = coord_sys.local_to_world_transform # FreeCAD.Base.Matrix node_update.update({ # glTF matrix is column major; needs to be tranposed 'matrix': m.transposed().A, }) else: raise NotImplementedError("only matrix export is supported (for now)") # The plan is to support something more like: # { # "rotation": [0, 0, 0, 1], # "scale": [1, 1, 1], # "translation": [-17.7082, -11.4156, 2.0922] # } # This is preferable since it's more human-readable. return node_update @classmethod def part_mesh(cls, part, tolerance=None): """ Convert a part's object to a mesh. :param part: part being converted to a mesh :type part: :class:`Part <cqparts.Part>` :param tolerance: maximum polygonal error (optional) :type tolerance: :class:`float` :return: list of (<vertices>, <indexes>) :rtype: :class:`tuple` ``tolerance`` must be greater than zero, this is because for a curved surface, the only way to achieve an error of zero is to have an infinite number of polygons representing that surface. Returned mesh format:: <return value> = ( [FreeCAD.Base.Vector(x, y, z), ... ], # list of vertices [(i, j, k), ... ], # indexes of vertices making a polygon ) """ if tolerance is None: tolerance = cls.default_tolerance with measure_time(log, 'buffers.part_mesh'): workplane = part.local_obj # cadquery.CQ instance shape = workplane.val() # expecting a cadquery.Solid instance tess = shape.tessellate(tolerance) return tess @classmethod def part_buffer(cls, part, tolerance=None): """ Export part's geometry as a `glTF 2.0 <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0>`_ asset binary stream. :param part: part being converted to a mesh :type part: :class:`Part <cqparts.Part>` :param tolerance: maximum polygonal error (optional) :type tolerance: :class:`float` :return: byte sream of exported geometry :rtype: :class:`ShapeBuffer` To embed binary model data into a 'uri', you can: .. doctest:: >>> import cqparts >>> from cqparts_misc.basic.primatives import Cube >>> cube = Cube() >>> buff = cube.exporter('gltf').part_buffer(cube) >>> import base64 >>> {'uri': "data:{mimetype};base64,{data}".format( ... mimetype="application/octet-stream", ... data=base64.b64encode(buff.read()).decode('ascii'), ... )} {'uri': 'data:application/octet-stream;base64,AAAAvwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAL8AAAC/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAC/AAECAQMCBAUGBAcFAwcCAgcEAAUBBgUAAwEHBwEFBAACBgAE'} """ # binary save done here: # https://github.com/KhronosGroup/glTF-Blender-Exporter/blob/master/scripts/addons/io_scene_gltf2/gltf2_export.py#L112 if tolerance is None: tolerance = cls.default_tolerance # Get shape's mesh (vertices, indices) = cls.part_mesh(part, tolerance=tolerance) # Create ShapeBuffer buff = ShapeBuffer( max_index=numpy.matrix(indices).max(), ) # Push mesh to ShapeBuffer for vert in vertices: buff.add_vertex(vert.x, vert.y, vert.z) for (i, j, k) in indices: buff.add_poly_index(i, j, k) return buff def add_part(self, part, filename=None, name=None, origin=None, parent_idx=0, tolerance=None): """ Adds the given ``part`` to ``self.gltf_dict``. :param part: part to add to gltf export :type part: :class:`Part <cqparts.Part>` :param filename: name of binary file to store buffer, if ``None``, binary data is embedded in the *buffer's 'uri'* :type filename: :class:`str` :param name: name given to exported mesh (optional) :type name: :class:`str` :param parent_idx: index of parent node (everything is added to a hierarchy) :type parent_idx: :class:`int` :param tolerance: maximum polygonal error (optional) :type tolerance: :class:`float` :return: information about additions to the gltf dict :rtype: :class:`dict` **Return Format:** The returned :class:`dict` is an account of what objects were added to the gltf dict, and the index they may be referenced:: <return format> = { 'buffers': [(<index>, <object>), ... ], 'bufferViews': [(<index>, <object>), ... ], 'accessors': [(<index>, <object>), ... ], 'materials': [(<index>, <object>), ... ], 'meshes': [(<index>, <object>), ... ], 'nodes': [(<index>, <object>), ... ], } .. note:: The format of the returned :class:`dict` **looks similar** to the gltf format, but it **is not**. """ if tolerance is None: tolerance = self.tolerance info = defaultdict(list) log.debug("gltf export: %r", part) # ----- Adding to: buffers with measure_time(log, 'buffers'): buff = self.part_buffer(part, tolerance=tolerance) self.scene_min = _list3_min( self.scene_min, (Vector(buff.vert_min) + part.world_coords.origin).toTuple() ) self.scene_max = _list3_max( self.scene_max, (Vector(buff.vert_max) + part.world_coords.origin).toTuple() ) buffer_index = len(self.gltf_dict['buffers']) buffer_dict = { "byteLength": len(buff), } if filename: # write file with open(filename, 'wb') as fh: for chunk in buff.buffer_iter(): fh.write(chunk) buffer_dict['uri'] = os.path.basename(filename) else: # embed buffer data in URI buffer_dict['uri'] = "data:{mimetype};base64,{data}".format( mimetype="application/octet-stream", data=base64.b64encode(buff.read()).decode('ascii'), ) self.gltf_dict['buffers'].append(buffer_dict) info['buffers'].append((buffer_index, buffer_dict)) # ----- Adding: bufferViews with measure_time(log, 'bufferViews'): bufferView_index = len(self.gltf_dict['bufferViews']) # vertices view view = { "buffer": buffer_index, "byteOffset": buff.vert_offset, "byteLength": buff.vert_len, "byteStride": 12, "target": WebGL.ARRAY_BUFFER, } self.gltf_dict['bufferViews'].append(view) bufferView_index_vertices = bufferView_index info['bufferViews'].append((bufferView_index_vertices, view)) # indices view view = { "buffer": buffer_index, "byteOffset": buff.idx_offset, "byteLength": buff.idx_len, "target": WebGL.ELEMENT_ARRAY_BUFFER, } self.gltf_dict['bufferViews'].append(view) bufferView_index_indices = bufferView_index + 1 info['bufferViews'].append((bufferView_index_indices, view)) # ----- Adding: accessors with measure_time(log, 'accessors'): accessor_index = len(self.gltf_dict['accessors']) # vertices accessor accessor = { "bufferView": bufferView_index_vertices, "byteOffset": 0, "componentType": WebGL.FLOAT, "count": buff.vert_size, "min": [v - 0.1 for v in buff.vert_min], "max": [v + 0.1 for v in buff.vert_max], "type": "VEC3", } self.gltf_dict['accessors'].append(accessor) accessor_index_vertices = accessor_index info['accessors'].append((accessor_index_vertices, accessor)) # indices accessor accessor = { "bufferView": bufferView_index_indices, "byteOffset": 0, "componentType": buff.idx_type, "count": buff.idx_size, "type": "SCALAR", } self.gltf_dict['accessors'].append(accessor) accessor_index_indices = accessor_index + 1 info['accessors'].append((accessor_index_indices, accessor)) # ----- Adding: materials with measure_time(log, 'materials'): material_index = len(self.gltf_dict['materials']) material = part._render.gltf_material self.gltf_dict['materials'].append(material) info['materials'].append((material_index, material)) # ----- Adding: meshes with measure_time(log, 'meshes'): mesh_index = len(self.gltf_dict['meshes']) mesh = { "primitives": [ { "attributes": { "POSITION": accessor_index_vertices, }, "indices": accessor_index_indices, "mode": WebGL.TRIANGLES, "material": material_index, } ], } if name: mesh['name'] = name self.gltf_dict['meshes'].append(mesh) info['meshes'].append((mesh_index, mesh)) # ----- Adding: nodes with measure_time(log, 'nodes'): node_index = len(self.gltf_dict['nodes']) node = { "mesh": mesh_index, } if name: node['name'] = name if origin: node.update(self.coordsys_dict(part.world_coords - origin)) self.gltf_dict['nodes'].append(node) info['nodes'].append((node_index, node)) # Appending child index to its parent's children list parent_node = self.gltf_dict['nodes'][parent_idx] parent_node['children'] = parent_node.get('children', []) + [node_index] return info
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/svg.py
src/cqparts/codec/svg.py
import re import cadquery from . import Exporter, register_exporter from .. import Part @register_exporter('svg', Part) class SVGExporter(Exporter): """ Export shape to AMF format. =============== ====================== **Name** ``svg`` **Exports** :class:`Part` =============== ====================== .. note:: Object is passed to :meth:`cadquery.freecad_impl.exporters.exportShape` for exporting. """ def __call__(self, filename='out.svg', world=False): # Getting cadquery Shape workplane = self.obj.world_obj if world else self.obj.local_obj shape = workplane.val() # call cadquery exporter with open(filename, 'w') as fh: cadquery.freecad_impl.exporters.exportShape( shape=shape, exportType='SVG', fileLike=fh, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/threejs_json.py
src/cqparts/codec/threejs_json.py
import os import json from io import StringIO import logging log = logging.getLogger(__name__) import cadquery from . import Exporter, register_exporter from .. import Component, Part, Assembly @register_exporter('json', Part) class ThreejsJSONExporter(Exporter): """ Export the :class:`Part <cqparts.Part>` to a *three.js JSON v3* file format. =============== ====================== **Name** ``json`` **Exports** :class:`Part <cqparts.Part>` **Spec** `three.js JSON model format v3 specification <https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3>`_ =============== ====================== For information on how to load in a webpage, look to your WebGL framework of choice: * ThreeJS: https://threejs.org/docs/#api/loaders/ObjectLoader * A-Frame: https://aframe.io/docs/0.7.0/core/asset-management-system.html#lt-a-asset-item-gt """ def __call__(self, filename="out.json", world=False): """ Write to file. :param filename: file to write :type filename: :class:`str` :param world: if True, use world coordinates, otherwise use local :type world: :class:`bool` """ log.debug("exporting: %r", self.obj) log.debug(" to: %s", filename) with open(filename, 'w') as fh: fh.write(self.get_str(world=world)) def get_str(self, *args, **kwargs): """ Get file string. (same arguments as :meth:`get_export_gltf_dict`) :return: JSON string :rtype: :class:`str` """ data = self.get_dict(*args, **kwargs) return json.dumps(data) def get_dict(self, world=False): """ Get the part's geometry as a :class:`dict` :param world: if True, use world coordinates, otherwise use local :type world: :class:`bool` :return: JSON model format :rtype: :class:`dict` """ data = {} with StringIO() as stream: obj = self.obj.world_obj if world else self.obj.local_obj cadquery.exporters.exportShape(obj, 'TJS', stream) stream.seek(0) data = json.load(stream) # Change diffuse colour to that in render properties data['materials'][0]['colorDiffuse'] = [ val / 255. for val in self.obj._render.rgb ] data['materials'][0]['transparency'] = self.obj._render.alpha return data @register_exporter('json', Assembly) class ThreejsJSONAssemblyExporter(Exporter): """ Export an :class:`Assembly` into **multiple** ``json`` files. =============== ====================== **Name** ``json`` **Exports** :class:`Assembly` **Spec** `three.js JSON model format v3 specification <https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3>`_ =============== ====================== .. warning:: The *three.js JSON v3* format does not support multiple models (or, at least, not as far as I can tell). So this exporter will create multiple files, one per part. If you're after a more modern WebGL supported export, consider using :class:`GLTFExporter <cqparts.codec.GLTFExporter>` instead. """ def __call__(self, filename='out.json', world=False): self._write_file(self.obj, filename, world=world) @classmethod def _write_file(cls, obj, filename, world=False): # recursive method to iterate through children if isinstance(obj, Assembly): # Object has no geometry, iter through components obj.solve() for (name, child) in obj.components.items(): s = os.path.splitext(filename) cls._write_file(child, "%s.%s%s" % (s[0], name, s[1]), world=True) else: ThreejsJSONExporter(obj)(filename, world=world)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/stl.py
src/cqparts/codec/stl.py
import re import cadquery from . import Exporter, register_exporter from .. import Part @register_exporter('stl', Part) class STLExporter(Exporter): """ Export shape to STL format. =============== ====================== **Name** ``stl`` **Exports** :class:`Part` =============== ====================== .. note:: Object is passed to :meth:`cadquery.freecad_impl.exporters.exportShape` for exporting. """ def __call__(self, filename='out.stl', world=False, tolerance=0.1): # Getting cadquery Shape workplane = self.obj.world_obj if world else self.obj.local_obj shape = workplane.val() # call cadquery exporter with open(filename, 'w') as fh: cadquery.freecad_impl.exporters.exportShape( shape=shape, exportType='STL', fileLike=fh, tolerance=tolerance, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/__init__.py
src/cqparts/codec/__init__.py
from collections import defaultdict from .. import Component # ----------------- Exporting ----------------- class Exporter(object): def __init__(self, obj): self.obj = obj def __call__(self): raise NotImplementedError("%r exporter is not callable" % (type(self))) exporter_index = defaultdict(dict) # format: {<name>: {<class_base>: <exporter_class>}} def register_exporter(name, base_class): """ Register an exporter to use for a :class:`Part <cqparts.Part>`, :class:`Assembly <cqparts.Assembly>`, or both (with :class:`Component <cqparts.Component>`). Registration is necessary to use with :meth:`Component.exporter() <cqparts.Component.exporter>`. :param name: name (or 'key') of exporter :type name: :class:`str` :param base_class: class of :class:`Component <cqparts.Component>` to export :type base_class: :class:`type` .. doctest:: >>> from cqparts import Part >>> from cqparts.codec import Exporter, register_exporter >>> @register_exporter('my_type', Part) ... class MyExporter(Exporter): ... def __call__(self, filename='out.mytype'): ... print("export %r to %s" % (self.obj, filename)) >>> from cqparts_misc.basic.primatives import Sphere >>> thing = Sphere(radius=5) >>> thing.exporter('my_type')('some-file.mytype') export <Sphere: radius=5.0> to some-file.mytype """ # Verify params if not isinstance(name, str) or (not name): raise TypeError("invalid name: %r" % name) if not issubclass(base_class, Component): raise TypeError("invalid base_class: %r, must be a %r subclass" % (base_class, Component)) def decorator(cls): # --- Verify # Can only be registered once if base_class in exporter_index[name]: raise TypeError("'%s' exporter type %r has already been registered" % ( name, base_class )) # Verify class hierarchy will not conflict # (so you can't have an exporter for a Component, and a Part. must be # an Assembly, and a Part, respectively) for key in exporter_index[name].keys(): if issubclass(key, base_class) or issubclass(base_class, key): raise TypeError("'%s' exporter type %r is in conflict with %r" % ( name, base_class, key, )) # --- Index exporter_index[name][base_class] = cls return cls return decorator def get_exporter(obj, name): """ Get an exporter for the :param obj: object to export :type obj: :class:`Component <cqparts.Component>` :param name: registered name of exporter :type name: :class:`str` :return: an exporter instance of the given type :rtype: :class:`Exporter` :raises TypeError: if exporter cannot be found """ if name not in exporter_index: raise TypeError( ("exporter type '%s' is not registered: " % name) + ("registered types: %r" % sorted(exporter_index.keys())) ) for base_class in exporter_index[name]: if isinstance(obj, base_class): return exporter_index[name][base_class](obj) raise TypeError("exporter type '%s' for a %r is not registered" % ( name, type(obj) )) # ----------------- Importing ----------------- class Importer(object): def __init__(self, cls): self.cls = cls importer_index = defaultdict(dict) # format: {<name>: {<class_base>: <importer_class>}} def register_importer(name, base_class): # Verify params if not isinstance(name, str) or (not name): raise TypeError("invalid name: %r" % name) if not issubclass(base_class, Component): raise TypeError("invalid base_class: %r, must be a %r subclass" % (base_class, Component)) def decorator(cls): # --- Verify # Can only be registered once if base_class in importer_index[name]: raise TypeError("'%s' importer type %r has already been registered" % ( name, base_class )) # Verify class hierarchy will not conflict # (so you can't have an importer for a Component, and a Part. must be # an Assembly, and a Part, respectively) for key in importer_index[name].keys(): if issubclass(key, base_class) or issubclass(base_class, key): raise TypeError("'%s' importer type %r is in conflict with %r" % ( name, base_class, key, )) # --- Index importer_index[name][base_class] = cls return cls return decorator def get_importer(cls, name): """ Get an importer for the given registered type. :param cls: class to import :type cls: :class:`type` :param name: registered name of importer :type name: :class:`str` :return: an importer instance of the given type :rtype: :class:`Importer` :raises TypeError: if importer cannot be found """ if name not in importer_index: raise TypeError( ("importer type '%s' is not registered: " % name) + ("registered types: %r" % sorted(importer_index.keys())) ) for base_class in importer_index[name]: if issubclass(cls, base_class): return importer_index[name][base_class](cls) raise TypeError("importer type '%s' for a %r is not registered" % ( name, cls )) # ----------------- housekeeping ----------------- __all__ = [ # Tools 'Exporter', 'register_exporter', 'get_exporter', 'Importer', 'register_importer', 'get_importer', # Codecs 'AMFExporter', 'GLTFExporter', 'STEPExporter', 'STEPImporter', 'STLExporter', 'SVGExporter', 'ThreejsJSONExporter', 'ThreejsJSONAssemblyExporter', ] from .amf import AMFExporter from .gltf import GLTFExporter from .step import STEPExporter, STEPPartImporter, STEPAssemblyImporter from .stl import STLExporter from .svg import SVGExporter from .threejs_json import ThreejsJSONExporter, ThreejsJSONAssemblyExporter
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/amf.py
src/cqparts/codec/amf.py
import re import cadquery from . import Exporter, register_exporter from .. import Part @register_exporter('amf', Part) class AMFExporter(Exporter): """ Export shape to AMF format. =============== ====================== **Name** ``amf`` **Exports** :class:`Part` =============== ====================== .. note:: Object is passed to :meth:`cadquery.freecad_impl.exporters.exportShape` for exporting. """ def __call__(self, filename='out.amf', world=False, tolerance=0.1): # Getting cadquery Shape workplane = self.obj.world_obj if world else self.obj.local_obj shape = workplane.val() # call cadquery exporter with open(filename, 'wb') as fh: cadquery.freecad_impl.exporters.exportShape( shape=shape, exportType='AMF', fileLike=fh, tolerance=tolerance, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/step.py
src/cqparts/codec/step.py
import os import re import cadquery from . import Exporter, register_exporter from . import Importer, register_importer from .. import Part, Assembly from ..constraint import Fixed @register_exporter('step', Part) class STEPExporter(Exporter): """ Export shape to STEP format. =============== ====================== **Name** ``step`` **Exports** :class:`Part <cqparts.Part>` =============== ====================== .. note:: Object is passed to :meth:`cadquery.freecad_impl.exporters.exportShape` for exporting. """ def __call__(self, filename='out.step', world=False): # Getting cadquery Shape workplane = self.obj.world_obj if world else self.obj.local_obj shape = workplane.val() # call cadquery exporter with cadquery.freecad_impl.suppress_stdout_stderr(): with open(filename, 'w') as fh: cadquery.freecad_impl.exporters.exportShape( shape=shape, exportType='STEP', fileLike=fh, ) class _STEPImporter(Importer): """ Abstraction layer to avoid duplicate code for :meth:`_mangled_filename`. """ @classmethod def _mangled_filename(cls, name): # ignore sub-directories name = os.path.basename(name) # encode to ascii (for a clean class name) name = name.encode('ascii', 'ignore') if type(name).__name__ == 'bytes': # a python3 thing name = name.decode() # type: bytes -> str # if begins with a number, inject a '_' at the beginning if re.search(r'^\d', name): name = '_' + name # replace non alpha-numeric characters with a '_' name = re.sub(r'[^a-z0-9_]', '_', name, flags=re.I) return name @register_importer('step', Part) class STEPPartImporter(_STEPImporter): """ Import a shape from a STEP formatted file. =============== ====================== **Name** ``step`` **Imports** :class:`Part <cqparts.Part>` =============== ====================== .. note:: Step file is passed to :meth:`cadquery.freecad_impl.importers.importShape` to do the hard work of extracting geometry. **Multi-part STEP** If the ``STEP`` file has multiple parts, all parts are unioned together to form a single :class:`Part <cqparts.Part>`. """ def __call__(self, filename): if not os.path.exists(filename): raise ValueError("given file does not exist: '%s'" % filename) def make(self): return cadquery.freecad_impl.importers.importShape( importType='STEP', fileName=filename, ).combine() # Create a class inheriting from our class imported_type = type(self._mangled_filename(filename), (self.cls,), { 'make': make, }) return imported_type() @register_importer('step', Assembly) class STEPAssemblyImporter(_STEPImporter): """ Import a shape from a STEP formatted file. =============== ====================== **Name** ``step`` **Imports** :class:`Assembly <cqparts.Assembly>` =============== ====================== .. note:: Step file is passed to :meth:`cadquery.freecad_impl.importers.importShape` to do the hard work of extracting geometry. **Multi-part STEP** This importer is intended for ``STEP`` files with multiple separated meshes defined. Each mesh is imported into a nested :class:`Part <cqparts.Part>` component. """ def __call__(self, filename): if not os.path.exists(filename): raise ValueError("given file does not exist: '%s'" % filename) mangled_name = self._mangled_filename(filename) def make_components(self): # Part Builder def _get_make(nested_obj): def make(self): return cadquery.Workplane("XY").newObject([nested_obj]) return make # Import file obj = cadquery.freecad_impl.importers.importShape( importType='STEP', fileName=filename, ) components = {} for (i, o) in enumerate(obj.objects): idstr = '{:03g}'.format(i) part_clsname = "%s_part%s" % (mangled_name, idstr) part_cls = type(part_clsname, (Part, ), { 'make': _get_make(o), }) components['{:03g}'.format(i)] = part_cls() return components def make_constraints(self): constraints = [] for (key, part) in self.components.items(): constraints.append(Fixed(part.mate_origin)) return constraints # Create a class inheriting from our class imported_type = type(mangled_name, (self.cls,), { 'make_components': make_components, 'make_constraints': make_constraints, }) return imported_type()
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/catalogue.py
src/cqparts/catalogue/catalogue.py
class Catalogue(object): def iter_items(self): """ Iterate through every item in the catalogue. :return: iterator for every item :rtype: generator .. note:: Must be overridden by inheriting class """ raise NotImplementedError("iter_items not implemented for %r" % type(self))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/__init__.py
src/cqparts/catalogue/__init__.py
__all__ = [ 'Catalogue', 'JSONCatalogue', ] from .catalogue import Catalogue from .json import JSONCatalogue
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/json.py
src/cqparts/catalogue/json.py
import tinydb import os import re from distutils.version import LooseVersion from .. import __version__ from .. import Component from ..errors import SearchError, SearchNoneFoundError, SearchMultipleFoundError from ..params import ParametricObject from ..utils import property_buffered from .catalogue import Catalogue class JSONCatalogue(Catalogue): """ Catalogue with JSON storage using :mod:`tinydb`. For more information, read :ref:`cqparts.catalogue`. """ # database information: # remember: before aligning the above version, check information below... # if changes have been made to this class, the below version should # be incremented. _version = '0.1' _dbinfo_name = '_dbinfo' def __init__(self, filename, clean=False): """ :param filename: name of catalogue file :type filename: :class:`str` :param clean: if set, catalogue is deleted, to be re-populatd from scratch :type clean: :class:`bool` If a new database is created, a ``_dbinfo`` table is added with version & module information to assist backward compatibility. """ self.filename = filename self.name = re.sub( r'[^a-z0-9\._\-+]', '_', os.path.splitext(os.path.basename(filename))[0], flags=re.IGNORECASE, ) if clean and os.path.exists(self.filename): with open(self.filename, 'w'): pass # remove file's content, then close self.db = tinydb.TinyDB(filename, default_table='items') self.items = self.db.table('items') if self._dbinfo_name not in self.db.tables(): # info table does not exist; database is new. self._dbinfo_table.insert({ 'module': type(self).__module__, 'name': type(self).__name__, 'ver': self._version, 'lib': 'cqparts', 'lib_version': __version__, }) def close(self): """ Close the database, and commit any changes to file. """ self.db.close() @property def _dbinfo_table(self): return self.db.table(self._dbinfo_name) @property def dbinfo(self): """ Database information (at time of creation), mainly intended for future-proofing. :return: information about database's initial creation :rtype: :class:`dict` """ return self._dbinfo_table.all()[0] def get_query(self): """ Passthrough to return a :class:`tinydb.Query` instance. (mostly implemented so importing :mod:`tinydb` is not mandatory to search the catalogue) :return: :mod:`tinydb` query instance :rtype: :class:`tinydb.Query` """ return tinydb.Query() # ------- Searching ------- def search(self, *args, **kwargs): """ Passthrough to :meth:`Table.search() <tinydb.database.Table.search>` for the ``items`` table. So ``catalogue.search(...)`` equivalent to ``catalogue.db.table('items').search(...)``. :return: entries in ``items`` table that positively match given search criteria. :rtype: :class:`list` of ``items`` table entries """ return self.items.search(*args, **kwargs) def find(self, *args, **kwargs): """ Performs the same action as :meth:`search` but asserts a single result. :return: :raises SearchNoneFoundError: if nothing was found :raises SearchMultipleFoundError: if more than one result is found """ result = self.search(*args, **kwargs) if len(result) == 0: raise SearchNoneFoundError("nothing found") elif len(result) > 1: raise SearchMultipleFoundError("more than one result found") return result[0] # ------- Adding items ------- def add(self, id, obj, criteria={}, force=False, _check_id=True): """ Add a :class:`Component <cqparts.Component>` instance to the database. :param id: unique id of entry, can be anything :type id: :class:`str` :param obj: component to be serialized, then added to the catalogue :type obj: :class:`Component <cqparts.Component>` :param criteria: arbitrary search criteria for the entry :type criteria: :class:`dict` :param force: if ``True``, entry is forcefully overwritten if it already exists. Otherwise an exception is raised :type force: :class:`bool` :param _check_id: if ``False``, duplicate ``id`` is not tested :type _check_id: :class:`bool` :raises TypeError: on parameter issues :raises ValueError: if a duplicate db entry is detected (and ``force`` is not set) :return: index of new entry :rtype: :class:`int` """ # Verify component if not isinstance(obj, Component): raise TypeError("can only add(%r), component is a %r" % ( Component, type(obj) )) # Serialize object obj_data = obj.serialize() # Add to database q = tinydb.Query() if (force or _check_id) and self.items.count(q.id == id): if force: self.items.remove(q.id == id) else: raise ValueError("entry with id '%s' already exists" % (id)) index = self.items.insert({ 'id': id, # must be unique 'criteria': criteria, 'obj': obj_data, }) return index def iter_items(self): """ Iterate through all items in the catalogue :return: iterator for each item :rtype: generator """ for item in self.items.all(): yield item # ------- Getting Items ------- def deserialize_item(self, data): """ Create a :class:`Component <cqparts.Component>` from a database search result. :param data: result from :meth:`find`, or an element of :meth:`search` :type data: :class:`dict` :return: deserialized object instance :rtype: :class:`Component <cqparts.Component>` """ return ParametricObject.deserialize(data.get('obj')) def get(self, *args, **kwargs): """ Combination of :meth:`find` and :meth:`deserialize_item`; the result from :meth:`find` is deserialized and returned. Input is a :mod:`tinydb` query. :return: deserialized object instance :rtype: :class:`Component <cqparts.Component>` """ result = self.find(*args, **kwargs) return self.deserialize_item(result)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parameter.py
src/cqparts/params/parameter.py
import six class Parameter(object): """ Used to set parameters of a :class:`ParametricObject <parametric_object.ParametricObject>`. All instances of this class defined in a class' ``__dict__`` will be valid input to the object's constructor. **Creating your own Parameter** To create your own parameter type, inherit from this class and override the :meth:`type` method. To demonstrate, let's create a parameter that takes an integer, and multiplies it by 10. .. doctest:: >>> from cqparts.params import Parameter >>> class Tens(Parameter): ... _doc_type = ":class:`int`" ... def type(self, value): ... return int(value) * 10 Now to use it in a :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>` .. doctest:: >>> from cqparts.params import ParametricObject >>> class Foo(ParametricObject): ... a = Tens(5, doc="a in groups of ten") ... def bar(self): ... print("a = %i" % self.a) >>> f = Foo(a=8) >>> f.bar() a = 80 """ def __init__(self, default=None, doc=None): """ :param default: default value, will cast before storing """ self.default = self.cast(default) self.doc = doc @classmethod def new(cls, default=None): """ Create new instance of the parameter with a new default ``doc`` :param default: new parameter instance default value """ return cls(default=default) def cast(self, value): """ First layer of type casting, used for high-level verification. If ``value`` is ``None``, :meth:`type` is not called to cast the value further. :param value: the value given to the :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>`'s constructor :return: ``value`` or ``None`` :raises ParameterError: if type is invalid """ if value is None: return None return self.type(value) def type(self, value): """ Second layer of type casting, usually overridden to change the given ``value`` into the parameter's type. Casts given value to the type dictated by this parameter type. Raise a :class:`ParameterError` on errors. :param value: the value given to the :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>`'s constructor :return: ``value`` cast to parameter's type :raises ParameterError: if type is invalid """ return value # sphinx documentation helpers def _param(self): # for a sphinx line: # :param my_param: <return is published here> if not isinstance(self.doc, six.string_types): return "[no description]" return self.doc _doc_type = '[unknown]' def _type(self): # for a sphinx line: # :type my_param: <return is published here> return self._doc_type # Serializing / Deserializing @classmethod def serialize(cls, value): r""" Converts value to something serializable by :mod:`json`. :param value: value to convert :return: :mod:`json` serializable equivalent By default, returns ``value``, to pass straight to :mod:`json` .. warning:: :meth:`serialize` and :meth:`deserialize` **are not** symmetrical. **Example of serializing then deserializing a custom object** Let's create our own ``Color`` class we'd like to represent as a parameter. .. doctest:: >>> class Color(object): ... def __init__(self, r, g, b): ... self.r = r ... self.g = g ... self.b = b ... ... def __eq__(self, other): ... return ( ... type(self) == type(other) and \ ... self.r == other.r and \ ... self.g == other.g and \ ... self.b == other.b ... ) ... ... def __repr__(self): ... return "<Color: %i, %i, %i>" % (self.r, self.g, self.b) >>> from cqparts.params import Parameter >>> class ColorParam(Parameter): ... _doc_type = ":class:`list`" # for sphinx documentation ... def type(self, value): ... (r, g, b) = value ... return Color(r, g, b) ... ... @classmethod ... def serialize(cls, value): ... # the default serialize will fail, we know this ... # because json.dumps(Color(0,0,0)) raises an exception ... if value is None: # parameter is nullable ... return None ... return [value.r, value.g, value.b] ... ... @classmethod ... def deserialize(cls, value): ... # the de-serialized rgb list is good to pass to type ... return value Note that ``json_deserialize`` does not return a ``Color`` instance. Instead, it returns a *list* to be used as an input to :meth:`cast` (which is ultimately passed to :meth:`type`) This is because when the values are deserialized, they're used as the default values for a newly created :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>` class. So now when we use them in a :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>`: .. doctest:: >>> from cqparts.params import ParametricObject, Float >>> class MyObject(ParametricObject): ... color = ColorParam(default=[127, 127, 127]) # default 50% grey ... height = Float(10) >>> my_object = MyObject(color=[100, 200, 255]) >>> my_object.color # is a Color instance (not a list) <Color: 100, 200, 255> Now to demonstrate how a parameter goes in and out of being serialized, we'll create a ``test`` method that, doesn't do anything, except that it should *not* throw any exceptions from its assertions, or the call to :meth:`json.dumps` .. doctest:: >>> import json >>> def test(value, obj_class=Color, param_class=ColorParam): ... orig_obj = param_class().cast(value) ... ... # serialize ... if value is None: ... assert orig_obj == None ... else: ... assert isinstance(orig_obj, obj_class) ... serialized = json.dumps(param_class.serialize(orig_obj)) ... ... # show serialized value ... print(serialized) # as a json string ... ... # deserialize ... ds_value = param_class.deserialize(json.loads(serialized)) ... new_obj = param_class().cast(ds_value) ... ... # now orig_obj and new_obj should be identical ... assert orig_obj == new_obj ... print("all good") >>> test([1, 2, 3]) [1, 2, 3] all good >>> test(None) null all good These are used to serialize and deserialize :class:`ParametricObject <cqparts.params.parametric_object.ParametricObject>` instances, so they may be added to a catalogue, then re-created. To learn more, go to :meth:`ParametricObject.serialize() <cqparts.params.parametric_object.ParametricObject.serialize>` """ return value @classmethod def deserialize(cls, value): """ Converts :mod:`json` deserialized value to its python equivalent. :param value: :mod:`json` deserialized value :return: python equivalent of ``value`` .. important:: ``value`` must be deserialized to be a valid input to :meth:`cast` More information on this in :meth:`serialize` """ return value
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py
src/cqparts/params/parametric_object.py
from importlib import import_module from copy import copy from .parameter import Parameter from .. import __version__ from ..errors import ParameterError import logging log = logging.getLogger(__name__) class ParametricObject(object): """ Parametric objects may be defined like so: .. doctest:: >>> from cqparts.params import ( ... ParametricObject, ... PositiveFloat, IntRange, ... ) >>> class Foo(ParametricObject): ... x = PositiveFloat(5) ... i = IntRange(1, 10, 3) # between 1 and 10, defaults to 3 ... blah = 100 >>> a = Foo(i=8) >>> (a.x, a.i) (5.0, 8) >>> a = Foo(i=11) # raises exception # doctest: +SKIP ParameterError: value of 11 outside the range {1, 10} >>> a = Foo(z=1) # raises exception # doctest: +SKIP ParameterError: <class 'Foo'> does not accept parameter(s): z >>> a = Foo(x='123', i='2') >>> (a.x, a.i) (123.0, 2) >>> a = Foo(blah=200) # raises exception, parameters must be Parameter types # doctest: +SKIP ParameterError: <class 'Foo'> does not accept any of the parameters: blah >>> a = Foo(x=None) # a.x is None, a.i=3 >>> (a.x, a.i) (None, 3) Internally to the object, parameters may be accessed simply with self.x, self.i These will always return the type defined """ def __init__(self, **kwargs): # get all available parameters (recurse through inherited classes) params = self.class_params(hidden=True) # parameters explicitly defined during intantiation defined_params = set(kwargs.keys()) # only accept a subset of params invalid_params = defined_params - set(params.keys()) if invalid_params: raise ParameterError("{cls} does not accept parameter(s): {keys}".format( cls=repr(type(self)), keys=', '.join(sorted(invalid_params)), )) # Cast parameters into this instance for (name, param) in params.items(): if name in kwargs: value = param.cast(kwargs[name]) else: value = copy(param.default) setattr(self, name, value) self.initialize_parameters() @classmethod def class_param_names(cls, hidden=True): """ Return the names of all class parameters. :param hidden: if ``False``, excludes parameters with a ``_`` prefix. :type hidden: :class:`bool` :return: set of parameter names :rtype: :class:`set` """ param_names = set( k for (k, v) in cls.__dict__.items() if isinstance(v, Parameter) ) for parent in cls.__bases__: if hasattr(parent, 'class_param_names'): param_names |= parent.class_param_names(hidden=hidden) if not hidden: param_names = set(n for n in param_names if not n.startswith('_')) return param_names @classmethod def class_params(cls, hidden=True): """ Gets all class parameters, and their :class:`Parameter` instances. :return: dict of the form: ``{<name>: <Parameter instance>, ... }`` :rtype: :class:`dict` .. note:: The :class:`Parameter` instances returned do not have a value, only a default value. To get a list of an **instance's** parameters and values, use :meth:`params` instead. """ param_names = cls.class_param_names(hidden=hidden) return dict( (name, getattr(cls, name)) for name in param_names ) def params(self, hidden=True): """ Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict` """ param_names = self.class_param_names(hidden=hidden) return dict( (name, getattr(self, name)) for name in param_names ) def __repr__(self): # Returns string of the form: # <ClassName: diameter=3.0, height=2.0, twist=0.0> params = self.params(hidden=False) return "<{cls}: {params}>".format( cls=type(self).__name__, params=", ".join( "%s=%r" % (k, v) for (k, v) in sorted(params.items(), key=lambda x: x[0]) # sort by name ), ) def initialize_parameters(self): """ A place to set default parameters more intelligently than just a simple default value (does nothing by default) :return: ``None`` Executed just prior to exiting the :meth:`__init__` function. When overriding, strongly consider calling :meth:`super`. """ pass # Serialize / Deserialize def serialize(self): """ Encode a :class:`ParametricObject` instance to an object that can be encoded by the :mod:`json` module. :return: a dict of the format: :rtype: :class:`dict` :: { 'lib': { # library information 'name': 'cqparts', 'version': '0.1.0', }, 'class': { # importable class 'module': 'yourpartslib.submodule', # module containing class 'name': 'AwesomeThing', # class being serialized }, 'params': { # serialized parameters of AwesomeThing 'x': 10, 'y': 20, } } value of ``params`` key comes from :meth:`serialize_parameters` .. important:: Serialize pulls the class name from the classes ``__name__`` parameter. This must be the same name of the object holding the class data, or the instance cannot be re-instantiated by :meth:`deserialize`. **Examples (good / bad)** .. doctest:: >>> from cqparts.params import ParametricObject, Int >>> # GOOD Example >>> class A(ParametricObject): ... x = Int(10) >>> A().serialize()['class']['name'] 'A' >>> # BAD Example >>> B = type('Foo', (ParametricObject,), {'x': Int(10)}) >>> B().serialize()['class']['name'] # doctest: +SKIP 'Foo' In the second example, the classes import name is expected to be ``B``. But instead, the *name* ``Foo`` is recorded. This mismatch will be irreconcilable when attempting to :meth:`deserialize`. """ return { # Encode library information (future-proofing) 'lib': { 'name': 'cqparts', 'version': __version__, }, # class & name record, for automated import when decoding 'class': { 'module': type(self).__module__, 'name': type(self).__name__, }, 'params': self.serialize_parameters(), } def serialize_parameters(self): """ Get the parameter data in its serialized form. Data is serialized by each parameter's :meth:`Parameter.serialize` implementation. :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}`` :rtype: :class:`dict` """ # Get parameter data class_params = self.class_params() instance_params = self.params() # Serialize each parameter serialized = {} for name in class_params.keys(): param = class_params[name] value = instance_params[name] serialized[name] = param.serialize(value) return serialized @staticmethod def deserialize(data): """ Create instance from serial data """ # Import module & get class try: module = import_module(data.get('class').get('module')) cls = getattr(module, data.get('class').get('name')) except ImportError: raise ImportError("No module named: %r" % data.get('class').get('module')) except AttributeError: raise ImportError("module %r does not contain class %r" % ( data.get('class').get('module'), data.get('class').get('name') )) # Deserialize parameters class_params = cls.class_params(hidden=True) params = dict( (name, class_params[name].deserialize(value)) for (name, value) in data.get('params').items() ) # Instantiate new instance return cls(**params)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/utils.py
src/cqparts/params/utils.py
from .parameter import Parameter from .types import NonNullParameter # ------------ decorator(s) --------------- def as_parameter(nullable=True, strict=True): """ Decorate a container class as a functional :class:`Parameter` class for a :class:`ParametricObject`. :param nullable: if set, parameter's value may be Null :type nullable: :class:`bool` .. doctest:: >>> from cqparts.params import as_parameter, ParametricObject >>> @as_parameter(nullable=True) ... class Stuff(object): ... def __init__(self, a=1, b=2, c=3): ... self.a = a ... self.b = b ... self.c = c ... @property ... def abc(self): ... return (self.a, self.b, self.c) >>> class Thing(ParametricObject): ... foo = Stuff({'a': 10, 'b': 100}, doc="controls stuff") >>> thing = Thing(foo={'a': 20}) >>> thing.foo.a 20 >>> thing.foo.abc (20, 2, 3) """ def decorator(cls): base_class = Parameter if nullable else NonNullParameter return type(cls.__name__, (base_class,), { # Preserve text for documentation '__name__': cls.__name__, '__doc__': cls.__doc__, '__module__': cls.__module__, # Sphinx doc type string '_doc_type': ":class:`{class_name} <{module}.{class_name}>`".format( class_name=cls.__name__, module=__name__ ), # 'type': lambda self, value: cls(**value) }) return decorator
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/__init__.py
src/cqparts/params/__init__.py
__all__ = [ # Core classes 'Parameter', 'ParametricObject', # Parameter Types 'Boolean', 'ComponentRef', 'Float', 'FloatRange', 'Int', 'IntRange', 'LowerCaseString', 'NonNullParameter', 'PartsList', 'PositiveFloat', 'PositiveInt', 'String', 'UpperCaseString', # Utilities 'as_parameter', ] # Core classes from .parameter import Parameter from .parametric_object import ParametricObject # Parameter Types from .types import Boolean from .types import ComponentRef from .types import Float from .types import FloatRange from .types import Int from .types import IntRange from .types import LowerCaseString from .types import NonNullParameter from .types import PartsList from .types import PositiveFloat from .types import PositiveInt from .types import String from .types import UpperCaseString # Utilities from .utils import as_parameter
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/types.py
src/cqparts/params/types.py
from .parameter import Parameter from ..errors import ParameterError # ------------ float types ------------ class Float(Parameter): """ Floating point """ _doc_type = ':class:`float`' def type(self, value): try: cast_value = float(value) except ValueError: raise ParameterError("value cannot be cast to a float: %r" % value) return cast_value class PositiveFloat(Float): """ Floating point >= 0 """ def type(self, value): cast_value = super(PositiveFloat, self).type(value) if cast_value < 0: raise ParameterError("value is not positive: %g" % cast_value) return cast_value class FloatRange(Float): """ Floating point in the given range (inclusive) """ def __init__(self, min, max, default, doc="[no description]"): """ {``min`` <= value <= ``max``} :param min: minimum value :type min: float :param max: maximum value :type max: float """ self.min = min self.max = max super(FloatRange, self).__init__(default, doc=doc) def type(self, value): cast_value = super(FloatRange, self).type(value) # Check range (min/max value of None is equivalent to -inf/inf) inside_range = True if (self.min is not None) and (cast_value < self.min): inside_range = False if (self.max is not None) and (cast_value > self.max): inside_range = False if not inside_range: raise ParameterError("value of %g outside the range {%s, %s}" % ( cast_value, self.min, self.max )) return cast_value # ------------ int types --------------- class Int(Parameter): """ Integer value """ _doc_type = ":class:`int`" def type(self, value): try: cast_value = int(value) except ValueError: raise ParameterError("value cannot be cast to an integer: %r" % value) return cast_value class PositiveInt(Int): """ Integer >= 0 """ def type(self, value): cast_value = super(PositiveInt, self).type(value) if cast_value < 0: raise ParameterError("value is not positive: %g" % cast_value) return cast_value class IntRange(Int): """ Integer in the given range (inclusive) """ def __init__(self, min, max, default, doc="[no description]"): """ {``min`` <= value <= ``max``} :param min: minimum value :type min: int :param max: maximum value :type max: int """ self.min = min self.max = max super(IntRange, self).__init__(default, doc=doc) def type(self, value): cast_value = super(IntRange, self).type(value) # Check range (min/max value of None is equivalent to -inf/inf) inside_range = True if (self.min is not None) and (cast_value < self.min): inside_range = False if (self.max is not None) and (cast_value > self.max): inside_range = False if not inside_range: raise ParameterError("value of %g outside the range {%s, %s}" % ( cast_value, self.min, self.max )) return cast_value # ------------ boolean types ------------ class Boolean(Parameter): """ Boolean value """ _doc_type = ':class:`bool`' def type(self, value): try: cast_value = bool(value) except ValueError: raise ParameterError("value cannot be cast to bool: %r" % value) return cast_value # ------------ string types ------------ class String(Parameter): """ String value """ _doc_type = ":class:`str`" def type(self, value): try: cast_value = str(value) except ValueError: raise ParameterError("value cannot be cast to string: %r" % value) return cast_value class LowerCaseString(String): """ Lower case string """ def type(self, value): cast_value = super(LowerCaseString, self).type(value) return cast_value.lower() class UpperCaseString(String): """ Upper case string """ def type(self, value): cast_value = super(UpperCaseString, self).type(value) return cast_value.upper() # ------------ others --------------- class NonNullParameter(Parameter): """ Non-nullable parameter """ def cast(self, value): if value is None: raise ParameterError("value cannot be None") return self.type(value) class PartsList(Parameter): _doc_type = ":class:`list` of :class:`Part <cqparts.Part>` instances" def type(self, value): # Verify, raise exception for any problems if isinstance(value, (list, tuple)): from .. import Part # avoid circular dependency for part in value: if not isinstance(part, Part): raise ParameterError("value must be a list of Part instances") else: raise ParameterError("value must be a list") return value class ComponentRef(Parameter): """ Reference to a Component Initially introduced as a means to reference a sub-component's parent .. doctest:: import cadquery from cqparts import Part, Component from cqparts.params import * class Eighth(Part): parent = ComponentRef(doc="part's parent") def make(self): size = self.parent.size / 2. return cadquery.Workplane('XY').box(size, size, size) class Cube(Assembly): size = PositiveFloat(10, doc="cube size") def make_components(self): # create a single cube 1/8 the volume of the whole cube return { 'a': Eighth(parent=self), } def make_constraints(self): return [ Fixed(self.components['a'].mate_origin), ] """ def type(self, value): # Verify, raise exception for any problems from .. import Component # avoid circular dependency if not isinstance(value, Component): raise ParameterError("value must be a Component") return value
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/web.py
src/cqparts/display/web.py
import os import sys import inspect import tempfile import shutil import jinja2 import time # web content if sys.version_info[0] >= 3: # python 3.x import http.server as SimpleHTTPServer import socketserver as SocketServer else: # python 2.x import SimpleHTTPServer import SocketServer import threading import webbrowser import logging log = logging.getLogger(__name__) from ..utils import working_dir from .environment import map_environment, DisplayEnvironment # Get this file's location _this_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # Set template web-content directory # note: can be changed prior to calling web_display() # # >>> from cqparts.display import web # >>> web.TEMPLATE_CONTENT_DIR = './my/alternative/template' # >>> web.web_display(some_thing) # # This would typically be used for testing, or development purposes. TEMPLATE_CONTENT_DIR = os.path.join(_this_path, 'web-template') SocketServer.TCPServer.allow_reuse_address = True # stops crash on re-use of port @map_environment( # named 'cmdline'? # This is a fallback display environment if no other method is available. # Therefore it's assumed that the environment that's been detected is a # no-frills command line. name='cmdline', order=99, condition=lambda: True, # fallback ) class WebDisplayEnv(DisplayEnvironment): """ Display given component in a browser window This display exports the model, then exposes a http service on *localhost* for a browser to use. The http service does not know when the browser window has been closed, so it will continue to serve the model's data until the user halts the process with a :class:`KeyboardInterrupt` (by pressing ``Ctrl+C``) When run, you should see output similar to:: >>> from cqparts.display import WebDisplayEnv >>> from cqparts_misc.basic.primatives import Cube >>> WebDisplayEnv().display(Cube()) press [ctrl+c] to stop server 127.0.0.1 - - [27/Dec/2017 16:06:37] "GET / HTTP/1.1" 200 - Created new window in existing browser session. 127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.gltf HTTP/1.1" 200 - 127.0.0.1 - - [27/Dec/2017 16:06:39] "GET /model/out.bin HTTP/1.1" 200 - A new browser window should appear with a render that looks like: .. image:: /_static/img/web_display.cube.png Then, when you press ``Ctrl+C``, you should see:: ^C[server shutdown successfully] and any further request on the opened browser window will return an errorcode 404 (file not found), because the http service has stopped. """ def display_callback(self, component, **kwargs): """ :param component: the component to render :type component: :class:`Component <cqparts.Component>` :param port: port to expose http service on :type port: :class:`int` :param autorotate: if ``True``, rendered component will rotate as if on a turntable. :type autorotate: :class:`bool` :param tolerance: Sets tolerance used during glTF export. :type tolerance: :class:`float` """ # Verify Parameter(s) from .. import Component if not isinstance(component, Component): raise TypeError("given component must be a %r, not a %r" % ( Component, type(component) )) # Parameter defaults port = kwargs.pop('port', 9041) autorotate = kwargs.pop('autorotate', False) tolerance = kwargs.pop('tolerance', None) # None uses default value # Create temporary file to host files temp_dir = tempfile.mkdtemp() host_dir = os.path.join(temp_dir, 'html') print("host temp folder: %s" % host_dir) # Copy template content to temporary location shutil.copytree(TEMPLATE_CONTENT_DIR, host_dir) # Export model exporter = component.exporter('gltf') exporter( filename=os.path.join(host_dir, 'model', 'out.gltf'), embed=False, tolerance=tolerance, ) # Modify templated content # index.html with open(os.path.join(host_dir, 'index.html'), 'r') as fh: index_template = jinja2.Template(fh.read()) with open(os.path.join(host_dir, 'index.html'), 'w') as fh: # camera location & target cam_t = [ (((a + b) / 2.0) / 1000) # midpoint (unit: meters) for (a, b) in zip(exporter.scene_min, exporter.scene_max) ] cam_p = [ (((b - a) * 1.0) / 1000) + t # max point * 200% (unit: meters) for (a, b, t) in zip(exporter.scene_min, exporter.scene_max, cam_t) ] # write xzy = lambda a: (a[0], a[2], -a[1]) # x,z,y coordinates (not x,y,z) fh.write(index_template.render( model_filename='model/out.gltf', autorotate = str(autorotate).lower(), camera_target=','.join("%g" % (val) for val in xzy(cam_t)), camera_pos=','.join("%g" % (val) for val in xzy(cam_p)), )) try: # Start web-service (loop forever) server = SocketServer.ThreadingTCPServer( server_address=("0.0.0.0", port), RequestHandlerClass=SimpleHTTPServer.SimpleHTTPRequestHandler, ) server_addr = "http://%s:%i/" % server.server_address def thread_target(): with working_dir(host_dir): server.serve_forever() print("serving: %s" % server_addr) sys.stdout.flush() server_thread = threading.Thread(target=thread_target) server_thread.daemon = True server_thread.start() # Open in browser print("opening in browser: %s" % server_addr) sys.stdout.flush() webbrowser.open(server_addr) # workaround for https://github.com/dcowden/cadquery/issues/211 import signal def _handler_sigint(signum, frame): raise KeyboardInterrupt() signal.signal(signal.SIGINT, _handler_sigint) print("press [ctrl+c] to stop server") sys.stdout.flush() while True: # wait for Ctrl+C time.sleep(1) except KeyboardInterrupt: log.info("\n[keyboard interrupt]") sys.stdout.flush() finally: # Stop web-service server.shutdown() server.server_close() server_thread.join() print("[server shutdown successfully]") # Delete temporary content if os.path.exists(os.path.join(host_dir, 'cqparts-display.txt')): # just making sure we're deleting the right folder shutil.rmtree(temp_dir)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/freecad.py
src/cqparts/display/freecad.py
import cadquery import os import logging log = logging.getLogger(__name__) from .environment import map_environment, DisplayEnvironment @map_environment( name="freecad", order=10, condition=lambda: 'MYSCRIPT_DIR' in os.environ, ) class FreeCADDisplayEnv(DisplayEnvironment): """ Display given component in FreeCAD Only works from within FreeCAD :mod:`cadquery` script; using this to display a :class:`Component <cqparts.Component>` will not open FreeCAD. """ def display_callback(self, component, **kwargs): """ Display given component in FreeCAD :param component: the component to render :type component: :class:`Component <cqparts.Component>` """ from .. import Part, Assembly import cadquery from Helpers import show def inner(obj, _depth=0): log.debug("display obj: %r: %r", type(self), obj) if isinstance(obj, Part): if _depth: # Assembly being displayed, parts need to be placed show(obj.world_obj, obj._render.rgbt) else: # Part being displayed, just show in local coords show(obj.local_obj, obj._render.rgbt) elif isinstance(obj, Assembly): obj.solve() for (name, component) in obj.components.items(): inner(component, _depth=_depth + 1) elif isinstance(obj, cadquery.CQ): show(obj) inner(component)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/cqparts_server.py
src/cqparts/display/cqparts_server.py
""" generate the files and notify the cqparts server look at https://github.com/zignig/cqparts-server copied and edited from web.py Copyright 2018 Peter Boin and Simon Kirkby 2018 """ import os import time import tempfile import shutil import logging import requests from .environment import map_environment, DisplayEnvironment log = logging.getLogger(__name__) ENVVAR_SERVER = 'CQPARTS_SERVER' @map_environment( name='cqparts_server', order=50, condition=lambda: ENVVAR_SERVER in os.environ, ) class CQPartsServerDisplayEnv(DisplayEnvironment): """ Display given component in a `cqps-server <https://github.com/zignig/cqparts-server>`_ window. """ @classmethod def _mkdir(cls, *path_parts): # Make a new directory, if it doesn't exist already dir_path = os.path.join(*path_parts) if not os.path.isdir(dir_path): os.mkdir(dir_path) return dir_path def display_callback(self, component, **kwargs): """ :param component: the component to render :type component: :class:`Component <cqparts.Component>` """ # Check environmental assumptions if ENVVAR_SERVER not in os.environ: raise KeyError("environment variable '%s' not set" % ENVVAR_SERVER) # get the server from the environment server_url = os.environ[ENVVAR_SERVER] # Verify Parameter(s) # check that it is a component from .. import Component if not isinstance(component, Component): raise TypeError("given component must be a %r, not a %r" % ( Component, type(component) )) # check that the server is running try: requests.get(server_url + '/status') #TODO inspect response for actual status and do stuff except requests.exceptions.ConnectionError: print('cqpart-server unavailable') return # get the name of the object cp_name = type(component).__name__ # create temporary folder temp_dir = tempfile.mkdtemp() base_dir = self._mkdir(temp_dir, cp_name) try: # export the files to the name folder start_time = time.time() exporter = component.exporter('gltf') exporter( filename=os.path.join(base_dir, 'out.gltf'), embed=False, ) finish_time = time.time() duration = finish_time - start_time # create the list of files to upload file_list = os.listdir(base_dir) file_load_list = [] for i in file_list: # path of file to upload file_name = os.path.join(base_dir, i) # short reference to file file_ref = os.path.join(cp_name, i) # make dict for file upload file_load_list.append( ('objs', (file_ref, open(file_name, 'rb'))) ) # upload the files as multipart upload requests.post(server_url + '/upload', files=file_load_list) # close file-handles for fl in file_load_list: fl[1][1].close() # notify the cq parts server # TODO more data in post, bounding box , other data requests.post(server_url + '/notify', data={ 'duration': duration, 'name': cp_name, }) finally: # finally check that it's sane and delete if os.path.isdir(temp_dir): shutil.rmtree(temp_dir)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/material.py
src/cqparts/display/material.py
from ..params import NonNullParameter # Templates (may be used optionally) COLOR = { # primary colours 'red': (255, 0, 0), 'green': (0, 255, 0), 'blue': (0, 0, 255), 'cyan': (0, 255, 255), 'magenta': (255, 0, 255), 'yellow': (255, 255, 0), # woods 'wood_light': (235, 152, 78), 'wood': (235, 152, 78), # == wood_light 'wood_dark': (169, 50, 38), # metals 'aluminium': (192, 192, 192), 'aluminum': (192, 192, 192), # == aluminium 'steel': (84, 84, 84), 'steel_blue': (35, 107, 142), 'copper': (184, 115, 51), 'silver': (230, 232, 250), 'gold': (205, 127, 50), } TEMPLATE = dict( (k, {'color': v, 'alpha': 1}) for (k, v) in COLOR.items() ) TEMPLATE.update({ 'default': {'color': COLOR['aluminium'], 'alpha': 1.0}, 'glass': {'color': (200, 200, 255), 'alpha': 0.2}, }) # -------------------- Parameter(s) -------------------- class RenderProps(object): """ Properties for rendering. This class provides a :class:`RenderParam` instance as a :class:`Parameter <cqparts.params.Parameter>` for a :class:`ParametricObject <cqparts.params.ParametricObject>`. .. doctest:: >>> from cqparts.params import ParametricObject >>> from cqparts.display.material import RenderParam, TEMPLATE, COLOR >>> class Thing(ParametricObject): ... _render = RenderParam(TEMPLATE['red'], doc="render params") >>> thing = Thing() >>> thing._render.color (255, 0, 0) >>> thing._render.alpha 1.0 >>> thing = Thing(_render={'color': COLOR['green'], 'alpha': 0.5}) >>> thing._render.color (0, 255, 0) >>> thing._render.alpha 0.5 >>> thing._render.dict {'color': (0, 255, 0), 'alpha': 0.5} The ``TEMPLATE`` and ``COLOR`` dictionaries provide named templates to display your creations quickly, but you can also provide custom properties. """ def __init__(self, color=(200, 200, 200), alpha=1): """ :param color: 3-tuple of RGB in the bounds: ``{0 <= val <= 255}`` :type color: :class:`tuple` :param alpha: object alpha in the range ``{0 <= alpha <= 1}`` where ``0`` is transparent, and ``1`` is opaque :type alpha: :class:`float` """ self.color = tuple(color) self.alpha = max(0., min(float(alpha), 1.)) @property def dict(self): """ Return a :class:`dict` of this instance. Can be used to set a property based on the property of another. :return: dict of render attributes :rtype: :class:`dict` """ return { 'color': self.color, 'alpha': self.alpha, } def __hash__(self): hash(frozenset(self.dict.items())) def __eq__(self, other): return self.dict == other.dict def __ne__(self, other): return self.dict != other.dict @property def transparency(self): """ :return: transparency value, 1 is invisible, 0 is opaque :rtype: :class:`float` """ return 1. - self.alpha @property def rgb(self): """ Red, Green, Blue :return: red, green, blue values :rtype: :class:`tuple` synonym for ``color`` """ return self.color @property def rgba(self): """ Red, Green, Blue, Alpha :return: red, green, blue, alpha values :rtype: :class:`tuple` .. doctest:: >>> from cqparts.display import RenderProps >>> r = RenderProps(color=(1,2,3), alpha=0.2) >>> r.rgba (1, 2, 3, 0.2) """ return self.color + (self.alpha,) @property def rgbt(self): """ Red, Green, Blue, Transparency :return: red, green, blue, transparency values :rtype: :class:`tuple` .. doctest:: >>> from cqparts.display import RenderProps >>> r = RenderProps(color=(1,2,3), alpha=0.2) >>> r.rgbt (1, 2, 3, 0.8) """ return self.color + (self.transparency,) @property def gltf_material(self): """ :return: `glTF Material <https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materials>`_ :rtype: :class:`dict` """ # There's a lot of room for improvement here return { "pbrMetallicRoughness": { "baseColorFactor": [round(val / 255., 4) for val in self.rgb] + [self.alpha], "metallicFactor": 0.1, "roughnessFactor": 0.7, }, 'alphaMode': 'BLEND', 'alphaCutoff': 1.0, #"name": "red", } class RenderParam(NonNullParameter): _doc_type = "kwargs for :class:`RenderProps <cqparts.display.material.RenderProps>`" def type(selv, value): return RenderProps(**value) # Serialize / Deserialize @classmethod def serialize(cls, value): return value.dict def render_props(**kwargs): """ Return a valid property for cleaner referencing in :class:`Part <cqparts.Part>` child classes. :param template: name of template to use (any of ``TEMPLATE.keys()``) :type template: :class:`str` :param doc: description of parameter for sphinx docs :type doc: :class:`str` :return: render property instance :rtype: :class:`RenderParam` .. doctest:: >>> import cadquery >>> from cqparts.display import render_props >>> import cqparts >>> class Box(cqparts.Part): ... # let's make semi-transparent aluminium (it's a thing!) ... _render = render_props(template='aluminium', alpha=0.8) >>> box = Box() >>> box._render.rgba (192, 192, 192, 0.8) The tools in :mod:`cqparts.display` will use this colour and alpha information to display the part. """ # Pop named args template = kwargs.pop('template', 'default') doc = kwargs.pop('doc', "render properties") params = {} # Template parameters if template in TEMPLATE: params.update(TEMPLATE[template]) # override template with any additional params params.update(kwargs) # return parameter instance return RenderParam(params, doc=doc)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/__init__.py
src/cqparts/display/__init__.py
__all__ = [ 'render_props', 'RenderProps', 'RenderParam', # display 'display', 'get_display_environment', # environment 'environment', ] import functools # material from .material import RenderProps, RenderParam from .material import render_props # envionrment from . import environment # Specific Environments from .freecad import FreeCADDisplayEnv from .web import WebDisplayEnv from .cqparts_server import CQPartsServerDisplayEnv def get_display_environment(): """ Get the first qualifying display environment. :return: highest priority valid display environment :rtype: :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>` see :meth:`@map_environment <cqparts.display.environment.map_environment>` for more information. This method is a common way to change script behaviour based on the environment it's running in. For example, if you wish to display a model when run in one environment, but export it to file when run in another, you could:: from cqparts.display import get_display_environment, display from cqparts_misc.basic.primatives import Cube obj = Cube() env_name = get_display_environment().name if env_name == 'freecad': # Render the object in a FreeCAD window display(obj) else: # Export the object to a file. obj.exporter('gltf')('my_object.gltf') This is useful when creating a sort of "build environment" for your models. """ for disp_env in environment.display_environments: if disp_env.condition(): return disp_env return None # Generic display function def display(component, **kwargs): """ Display the given component based on the environment it's run from. See :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>` documentation for more details. :param component: component to display :type component: :class:`Component <cqparts.Component>` Additional parameters may be used by the chosen :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>` """ disp_env = get_display_environment() if disp_env is None: raise LookupError('valid display environment could not be found') disp_env.display(component, **kwargs)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/environment.py
src/cqparts/display/environment.py
__all__ = [ 'display_environments', 'map_environment', 'DisplayEnvironment', ] import logging log = logging.getLogger(__name__) display_environments = [] def map_environment(**kwargs): """ Decorator to map a DisplayEnvironment for displaying components. The decorated environment will be chosen if its condition is ``True``, and its order is the smallest. :param add_to: if set to ``globals()``, display environment's constructor may reference its own type. :type add_to: :class:`dict` Any additional named parameters will be passed to the constructor of the decorated DisplayEnvironment. See :class:`DisplayEnvironment` for example usage. **NameError on importing** The following code:: @map_environment( name='abc', order=10, condition=lambda: True, ) class SomeDisplayEnv(DisplayEnvironment): def __init__(self, *args, **kwargs): super(SomeDisplayEnv, self).__init__(*args, **kwargs) Will raise the Exception:: NameError: global name 'SomeDisplayEnv' is not defined Because this ``map_environment`` decorator attempts to instantiate this class before it's returned to populate the ``global()`` dict. To cicrumvent this problem, set ``add_to`` to ``globals()``:: @map_environment( name='abc', order=10, condition=lambda: True, add_to=globals(), ) class SomeDisplayEnv(DisplayEnvironment): ... as above """ def inner(cls): global display_environments assert issubclass(cls, DisplayEnvironment), "can only map DisplayEnvironment classes" # Add class to it's local globals() so constructor can reference # its own type add_to = kwargs.pop('add_to', {}) add_to[cls.__name__] = cls # Create display environment disp_env = cls(**kwargs) # is already mappped? try: i = display_environments.index(disp_env) # raises ValueError # report duplicate raise RuntimeError( ("environment %r already mapped, " % display_environments[i]) + ("can't map duplicate %r" % disp_env) ) except ValueError: pass # as expected # map class display_environments = sorted(display_environments + [disp_env]) return cls return inner class DisplayEnvironment(object): def __init__(self, name=None, order=0, condition=lambda: True): self.name = name self.order = order self.condition = condition def __repr__(self): return "<{cls}: {name}, {order}>".format( cls=type(self).__name__, name=self.name, order=self.order, ) def __lt__(self, other): # sort only uses __lt__ return self.order < other.order def __eq__(self, other): return self.name == other.name def display(self, *args, **kwargs): return self.display_callback(*args, **kwargs) def display_callback(self, component, **kwargs): """ Display given component in this environment. .. note:: To be overridden by inheriting classes An example of a introducing a custom display environment. .. doctest:: import cqparts from cqparts.display.environment import DisplayEnvironment, map_environment def is_text_env(): # function that returns True if it's run in the # desired environment. import sys # Python 2.x if sys.version_info[0] == 2: return isinstance(sys.stdout, file) # Python 3.x import io return isinstance(sys.stdout, io.TextIOWrapper) @map_environment( name="text", order=0, # force display to be first priority condition=is_text_env, ) class TextDisplay(DisplayEnvironment): def display_callback(self, component, **kwargs): # Print component details to STDOUT if isinstance(component, cqparts.Assembly): sys.stdout.write(component.tree_str(add_repr=True)) else: # assumed to be a cqparts.Part sys.stdout.write("%r\\n" % (component)) ``is_text_env()`` checks if there's a valid ``sys.stdout`` to write to, ``TextDisplay`` defines how to display any given component, and the ``@map_environment`` decorator adds the display paired with its environment test function. When using :meth:`display() <cqparts.display.display>`, this display will be used if ``is_text_env()`` returns ``True``, and no previously mapped environment with a smaller ``order`` tested ``True``: .. doctest:: # create component to display from cqparts_misc.basic.primatives import Cube cube = Cube() # display component from cqparts.display import display display(cube) The ``display_callback`` will be called via :meth:`display() <DisplayEnvironment.display>`. So to call this display method directly: .. doctest:: TextDisplay().display(cube) :raises: NotImplementedError if not overridden """ if type(self) is DisplayEnvironment: raise RuntimeError( ("%r is not a functional display environment, " % (type(self))) + "it's meant to be inherited by an implemented environment" ) raise NotImplementedError( "display_callback function not overridden by %r" % (type(self)) )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/constraints.py
src/cqparts/constraint/constraints.py
from .base import Constraint from .mate import Mate from ..utils.geometry import CoordSystem class Fixed(Constraint): """ Sets a component's world coordinates so the given ``mate`` is positioned and orientated to the given ``world_coords``. There is only 1 possible solution. """ def __init__(self, mate, world_coords=None): """ :param mate: mate to lock :type mate: :class:`Mate <cqparts.constraint.Mate>` :param world_coords: world coordinates to lock ``mate`` to :type world_coords: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` :raises TypeError: if an invalid parameter type is passed If the ``world_coords`` parameter is set as a :class:`Mate <cqparts.constraint.Mate>` instance, the mate's ``.world_coords`` is used. If ``world_coords`` is ``None``, the object is locked to the origin. """ # mate if isinstance(mate, Mate): self.mate = mate else: raise TypeError("mate must be a %r, not a %r" % (Mate, type(mate))) # world_coords if isinstance(world_coords, CoordSystem): self.world_coords = world_coords elif isinstance(world_coords, Mate): self.world_coords = world_coords.world_coords elif world_coords is None: self.world_coords = CoordSystem() else: raise TypeError( "world_coords must be a %r or %r, not a %r" % (Mate, CoordSystem, type(world_coords)) ) class Coincident(Constraint): """ Set a component's world coordinates of ``mate.component`` so that ``mate.world_coords`` == ``to_mate.world_coords``. To successfully determine the component's location, the relative component must be solvable. .. note:: An :class:`Assembly <cqparts.Assembly>` **cannot** solely rely on relative locks to place its components. This is because every component will be waiting for another component to be placed, a circular problem. At least one of them must use the :class:`Fixed` """ def __init__(self, mate, to_mate): """ :param mate: mate to lock :type mate: :class:`Mate <cqparts.constraint.Mate>` :param to_mate: mate to lock ``mate`` to :type to_mate: :class:`Mate <cqparts.constraint.Mate>` """ # mate if isinstance(mate, Mate): self.mate = mate else: raise TypeError("mate must be a %r, not a %r" % (Mate, type(mate))) # to_mate if isinstance(to_mate, Mate): self.to_mate = to_mate else: raise TypeError("to_mate must be a %r, not a %r" % (Mate, type(to_mate)))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/mate.py
src/cqparts/constraint/mate.py
from copy import copy from ..utils.geometry import CoordSystem from ..utils.misc import property_buffered class Mate(object): """ A mate is a coordinate system relative to a component's origin. """ def __init__(self, component, local_coords=None): """ :param component: component the mate is relative to :type component: :class:`Component <cqparts.Component>` :param local_coords: coordinate system of mate relative to component's origin :type local_coords: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` If ``component`` is explicitly set to None, the mate's :meth:`world_coords` == ``local_coords``. If ``local_coords`` is not set, the component's origin is used (ie: coords at ``0,0,0``, with no rotation) """ from ..component import Component # avoids circular dependency # component if isinstance(component, Component): self.component = component elif component is None: self.component = None else: raise TypeError("component must be a %r, got a %r" % (Component, component)) # local_coords if isinstance(local_coords, CoordSystem): self.local_coords = local_coords elif local_coords is None: self.local_coords = CoordSystem() else: raise TypeError("local_coords must be a %r, got a %r" %(CoordSystem, local_coords)) @property_buffered def world_coords(self): """ :return: world coordinates of mate. :rtype: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` :raises ValueError: if ``.component`` does not have valid world coordinates. If ``.component`` is ``None``, then the ``.local_coords`` are returned. """ if self.component is None: # no component, world == local return copy(self.local_coords) else: cmp_origin = self.component.world_coords if cmp_origin is None: raise ValueError( "mate's component does not have world coordinates; " "cannot get mate's world coordinates" ) return cmp_origin + self.local_coords def __add__(self, other): """ :param other: the object being added Behaviour based on type being added: :class:`Mate` + :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`: Return a copy of ``self`` with ``other`` added to ``.local_coords`` :raises TypeError: if type of ``other`` is not supported """ if isinstance(other, CoordSystem): return type(self)( component=self.component, local_coords=self.local_coords + other, ) else: raise TypeError("addition of %r + %r is not supported" % ( type(self), type(other) )) def __repr__(self): return "<{cls_name}:\n component={component}\n local_coords={local_coords}\n>".format( cls_name=type(self).__name__, component=self.component, local_coords=self.local_coords, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/solver.py
src/cqparts/constraint/solver.py
from ..utils.geometry import CoordSystem from .base import Constraint from .constraints import Fixed, Coincident def solver(constraints, coord_sys=None): """ Solve constraints. Solutions pair :class:`Constraint <cqparts.constraint.Constraint>` instances with their suitable :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` world coordinates. :param constraints: constraints to solve :type constraints: iterable of :class:`Constraint <cqparts.constraint.Constraint>` :param coord_sys: coordinate system to offset solutions (default: no offset) :type coord_sys: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` :return: generator of (:class:`Component <cqparts.Component>`, :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`) tuples. """ if coord_sys is None: coord_sys = CoordSystem() # default # Verify list contains constraints for constraint in constraints: if not isinstance(constraint, Constraint): raise ValueError("{!r} is not a constraint".format(constraint)) solved_count = 0 indexed = list(constraints) # Continue running solver until no solution is found while indexed: indexes_solved = [] for (i, constraint) in enumerate(indexed): # Fixed if isinstance(constraint, Fixed): indexes_solved.append(i) yield ( constraint.mate.component, coord_sys + constraint.world_coords + (CoordSystem() - constraint.mate.local_coords) ) # Coincident elif isinstance(constraint, Coincident): try: relative_to = constraint.to_mate.world_coords except ValueError: relative_to = None if relative_to is not None: indexes_solved.append(i) # note: relative_to are world coordinates; adding coord_sys is not necessary yield ( constraint.mate.component, relative_to + (CoordSystem() - constraint.mate.local_coords) ) if not indexes_solved: # no solutions found # At least 1 solution must be found each iteration. # if not, we'll just be looping forever. break else: # remove constraints from indexed list (so they're not solved twice) for j in reversed(indexes_solved): del indexed[j] if indexed: raise ValueError("not all constraints could be solved")
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/__init__.py
src/cqparts/constraint/__init__.py
__all__ = [ 'Mate', 'Constraint', # Constraints 'Fixed', 'Coincident', 'solver', ] from .mate import Mate from . import solver # Constraints from .base import Constraint from .constraints import ( Fixed, Coincident, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/base.py
src/cqparts/constraint/base.py
class Constraint(object): """ A means to limit the relative position &/or motion of 1 or more components. Constraints are combined and solved to set world coordinates of the components within an assembly. """
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/wrappers.py
src/cqparts/utils/wrappers.py
def as_part(func): """ Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance. """ from .. import Part def inner(*args, **kwargs): part_class = type(func.__name__, (Part,), { 'make': lambda self: func(*args, **kwargs), }) return part_class() inner.__doc__ = func.__doc__ return inner
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/sphinx.py
src/cqparts/utils/sphinx.py
""" This module is only to be referenced from your project's sphinx autodoc configuration. http://www.sphinx-doc.org/en/stable/ext/autodoc.html """ from ..params import ParametricObject, Parameter def _add_lines(lines, new_lines, prepend=False, separator=True): # Adding / Removing Lines: # sphinx callbacks require the passed ``lines`` parameter to have it's # initial ``id(lines)``, so doing things like ``lines = ['new thing'] + lines`` # changes it's ``id`` (allocating new memory), and the new lines list is # forgotten and garbage collected (... sigh). # # So the only way to *prepend* / *append* text to the ``lines`` parameter is # to use ``lines.insert(0, new_line)`` / ``lines.append(new_line`` respectively. # # To remove lines, use ``del lines[0]`` # # If in doubt: ``id(lines)`` should return the same number at the start, and # end of the function call. has_original_content = bool(lines) if prepend: # add to the beginning of __doc__ for (i, new_line) in enumerate(new_lines): lines.insert(i, new_line) if separator and (new_lines and has_original_content): # add blank line between newly added lines and original content lines.insert(len(new_lines), '') else: # append to the end of __doc__ if separator and (new_lines and has_original_content): # add blank line between newly added lines and original content lines.append('') for new_line in new_lines: lines.append(new_line) def _cls_name(cls): return "{}.{}".format(cls.__module__, cls.__name__) # -------------- autodoc-process-docstring -------------- def add_parametric_object_params(prepend=False, hide_private=True): """ Add :class:`ParametricObject <cqparts.params.ParametricObject>` parameters in a list to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_parametric_object_params def setup(app): app.connect("autodoc-process-docstring", add_parametric_object_params()) Then, when documenting your :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` the :class:`ParametricObject <cqparts.params.ParametricObject>` parameters will also be documented in the output. :param prepend: if True, parameters are added to the beginning of the *docstring*. otherwise, they're appended at the end. :type prepend: :class:`bool` :param hide_private: if True, parameters with a ``_`` prefix are not documented. :type hide_private: :class:`bool` """ from ..params import ParametricObject def param_lines(app, obj): params = obj.class_params(hidden=(not hide_private)) # Header doc_lines = [] if params: # only add a header if it's relevant doc_lines += [ ":class:`ParametricObject <cqparts.params.ParametricObject>` constructor parameters:", "", ] for (name, param) in sorted(params.items(), key=lambda x: x[0]): # sort by name doc_lines.append(':param {name}: {doc}'.format( name=name, doc=param._param(), )) doc_lines.append(':type {name}: {doc}'.format( name=name, doc=param._type(), )) return doc_lines # Conditions for running above `param_lines` function (in order) conditions = [ # (all conditions must be met) lambda o: type(o) == type, lambda o: o is not ParametricObject, lambda o: issubclass(o, ParametricObject), ] def callback(app, what, name, obj, options, lines): # sphinx callback # (this method is what actually gets sent to the sphinx runtime) if all(c(obj) for c in conditions): new_lines = param_lines(app, obj) _add_lines(lines, new_lines, prepend=prepend) return callback def add_search_index_criteria(prepend=False): """ Add the search criteria used when calling :meth:`register() <cqparts.search.register>` on a :class:`Component <cqparts.Component>` as a table to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_search_index_criteria def setup(app): app.connect("autodoc-process-docstring", add_search_index_criteria()) Then, when documenting your :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` the search criteria will also be documented in the output. :param prepend: if True, table is added to the beginning of the *docstring*. otherwise, it's appended at the end. :type prepend: :class:`bool` """ from ..search import class_criteria from .. import Component COLUMN_INFO = [ # (<title>, <width>, <method>), ('Key', 50, lambda k, v: "``%s``" % k), ('Value', 10, lambda k, v: ', '.join("``%s``" % w for w in v)), ] # note: last column width is irrelevant def param_lines(app, obj): doc_lines = [] criteria = class_criteria.get(obj, {}) row_seperator = ' '.join(('=' * w) for (_, w, _) in COLUMN_INFO) # Header if criteria: # only add a header if it's relevant doc_lines += [ "**Search Criteria:**", "", "This object can be found with :meth:`find() <cqparts.search.find>` ", "and :meth:`search() <cqparts.search.search>` using the following ", "search criteria.", "", row_seperator, ' '.join((("%%-%is" % w) % t) for (t, w, _) in COLUMN_INFO), row_seperator, ] # Add criteria for (key, value) in sorted(criteria.items(), key=lambda x: x[0]): doc_lines.append(' '.join( ("%%-%is" % w) % m(key, value) for (_, w, m) in COLUMN_INFO )) # Footer if criteria: doc_lines += [ row_seperator, "", ] return doc_lines # Conditions for running above `param_lines` function (in order) conditions = [ # (all conditions must be met) lambda o: type(o) == type, lambda o: o is not Component, lambda o: issubclass(o, Component), ] def callback(app, what, name, obj, options, lines): # sphinx callback # (this method is what actually gets sent to the sphinx runtime) if all(c(obj) for c in conditions): new_lines = param_lines(app, obj) _add_lines(lines, new_lines, prepend=prepend) return callback # -------------- autodoc-skip-member -------------- def skip_class_parameters(): """ Can be used with :meth:`add_parametric_object_params`, this removes duplicate variables cluttering the sphinx docs. This is only intended to be used with *sphinx autodoc* In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import skip_class_parameters def setup(app): app.connect("autodoc-skip-member", skip_class_parameters()) """ from ..params import Parameter def callback(app, what, name, obj, skip, options): if (what == 'class') and isinstance(obj, Parameter): return True # yes, skip this object return None return callback
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/misc.py
src/cqparts/utils/misc.py
import os from time import time from contextlib import contextmanager import jinja2 class property_buffered(object): """ Buffer the result of a method on the class instance, similar to python builtin ``@property``, but the result is kept in memory until it's explicitly deleted. .. doctest:: >>> from cqparts.utils.misc import property_buffered >>> class A(object): ... @property_buffered ... def x(self): ... print("x called") ... return 100 >>> a = A() >>> a.x x called 100 >>> a.x 100 >>> del a.x >>> a.x x called 100 Basis of class was sourced from the `funkybob/antfarm <https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/utils/functional.py>`_ project. thanks to `@funkybob <https://github.com/funkybob>`_. """ def __init__(self, getter, name=None): self.name = name or getter.__name__ self.getter = getter self.__doc__ = getter.__doc__ # preserve sphinx autodoc docstring def __get__(self, instance, owner): if instance is None: # pragma: no cover return self value = self.getter(instance) instance.__dict__[self.name] = value return value def indicate_last(items): """ iterate through list and indicate which item is the last, intended to assist tree displays of hierarchical content. :return: yielding (<bool>, <item>) where bool is True only on last entry :rtype: generator """ last_index = len(items) - 1 for (i, item) in enumerate(items): yield (i == last_index, item) @contextmanager def working_dir(path): """ Change working directory within a context:: >>> import os >>> from cqparts.utils import working_dir >>> print(os.getcwd()) /home/myuser/temp >>> with working_dir('..'): ... print(os.getcwd()) ... /home/myuser :param path: working path to use while in context :type path: :class:`str` """ initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_path) @contextmanager def measure_time(log, name): start_time = time() yield taken = time() - start_time log.debug(" %-25s (took: %gms)", name, round(taken * 1000, 3))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/__init__.py
src/cqparts/utils/__init__.py
__all__ = [ # env 'get_env_name', # geometry 'CoordSystem', # misc 'property_buffered', 'indicate_last', 'working_dir', 'measure_time', # wrappers 'as_part', ] from .geometry import CoordSystem from .misc import property_buffered from .misc import indicate_last from .misc import working_dir from .misc import measure_time from .wrappers import as_part #from . import test # Nope!, test is only intended to be imported by testcases, so it's not # imported automatically when cqparts.utils is referenced
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/geometry.py
src/cqparts/utils/geometry.py
import cadquery import random # FIXME: remove freecad dependency from this module... # right now I'm just trying to get it working. import FreeCAD def merge_boundboxes(*bb_list): """ Combine bounding boxes to result in a single BoundBox that encloses all of them. :param bb_list: List of bounding boxes :type bb_list: :class:`list` of :class:`cadquery.BoundBox` """ # Verify types if not all(isinstance(x, cadquery.BoundBox) for x in bb_list): raise TypeError( "parameters must be cadquery.BoundBox instances: {!r}".format(bb_list) ) if len(bb_list) <= 1: return bb_list[0] # if only 1, nothing to merge; simply return it # Find the smallest bounding box to enclose each of those given min_params = list(min(*vals) for vals in zip( # minimum for each axis *((bb.xmin, bb.ymin, bb.zmin) for bb in bb_list) )) max_params = list(max(*vals) for vals in zip( # maximum for each axis *((bb.xmax, bb.ymax, bb.zmax) for bb in bb_list) )) #__import__('ipdb').set_trace() # Create new object with combined parameters WrappedType = type(bb_list[0].wrapped) # assuming they're all the same wrapped_bb = WrappedType(*(min_params + max_params)) return cadquery.BoundBox(wrapped_bb) class CoordSystem(cadquery.Plane): """ Defines the location, and rotation of an orthogonal 3 dimensional coordinate system. """ def __init__(self, origin=(0,0,0), xDir=(1,0,0), normal=(0,0,1)): # impose a default to: XY plane, zero offset super(CoordSystem, self).__init__(origin, xDir, normal) @classmethod def from_plane(cls, plane): """ :param plane: cadquery plane instance to base coordinate system on :type plane: :class:`cadquery.Plane` :return: duplicate of the given plane, in this class :rtype: :class:`CoordSystem` usage example: .. doctest:: >>> import cadquery >>> from cqparts.utils.geometry import CoordSystem >>> obj = cadquery.Workplane('XY').circle(1).extrude(5) >>> plane = obj.faces(">Z").workplane().plane >>> isinstance(plane, cadquery.Plane) True >>> coord_sys = CoordSystem.from_plane(plane) >>> isinstance(coord_sys, CoordSystem) True >>> coord_sys.origin.z 5.0 """ return cls( origin=plane.origin.toTuple(), xDir=plane.xDir.toTuple(), normal=plane.zDir.toTuple(), ) @classmethod def from_transform(cls, matrix): r""" :param matrix: 4x4 3d affine transform matrix :type matrix: :class:`FreeCAD.Matrix` :return: a unit, zero offset coordinate system transformed by the given matrix :rtype: :class:`CoordSystem` Individual rotation & translation matricies are: .. math:: R_z & = \begin{bmatrix} cos(\alpha) & -sin(\alpha) & 0 & 0 \\ sin(\alpha) & cos(\alpha) & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \qquad & R_y & = \begin{bmatrix} cos(\beta) & 0 & sin(\beta) & 0 \\ 0 & 1 & 0 & 0 \\ -sin(\beta) & 0 & cos(\beta) & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \\ \\ R_x & = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & cos(\gamma) & -sin(\gamma) & 0 \\ 0 & sin(\gamma) & cos(\gamma) & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \qquad & T_{\text{xyz}} & = \begin{bmatrix} 1 & 0 & 0 & \delta x \\ 0 & 1 & 0 & \delta y \\ 0 & 0 & 1 & \delta z \\ 0 & 0 & 0 & 1 \end{bmatrix} The ``transform`` is the combination of these: .. math:: transform = T_{\text{xyz}} \cdot R_z \cdot R_y \cdot R_x = \begin{bmatrix} a & b & c & \delta x \\ d & e & f & \delta y \\ g & h & i & \delta z \\ 0 & 0 & 0 & 1 \end{bmatrix} Where: .. math:: a & = cos(\alpha) cos(\beta) \\ b & = cos(\alpha) sin(\beta) sin(\gamma) - sin(\alpha) cos(\gamma) \\ c & = cos(\alpha) sin(\beta) cos(\gamma) + sin(\alpha) sin(\gamma) \\ d & = sin(\alpha) cos(\beta) \\ e & = sin(\alpha) sin(\beta) sin(\gamma) + cos(\alpha) cos(\gamma) \\ f & = sin(\alpha) sin(\beta) cos(\gamma) - cos(\alpha) sin(\gamma) \\ g & = -sin(\beta) \\ h & = cos(\beta) sin(\gamma) \\ i & = cos(\beta) cos(\gamma) """ # Create reference points at origin offset = FreeCAD.Vector(0, 0, 0) x_vertex = FreeCAD.Vector(1, 0, 0) # vertex along +X-axis z_vertex = FreeCAD.Vector(0, 0, 1) # vertex along +Z-axis # Transform reference points offset = matrix.multiply(offset) x_vertex = matrix.multiply(x_vertex) z_vertex = matrix.multiply(z_vertex) # Get axis vectors (relative to offset vertex) x_axis = x_vertex - offset z_axis = z_vertex - offset # Return new instance vect_tuple = lambda v: (v.x, v.y, v.z) return cls( origin=vect_tuple(offset), xDir=vect_tuple(x_axis), normal=vect_tuple(z_axis), ) @classmethod def random(cls, span=1, seed=None): """ Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of the :math:`XYZ` axes. Positioning it randomly by setting its ``world_coords`` shows that each box is always positioned orthogonally to the other two. .. doctest:: from cqparts_misc.basic.indicators import CoordSysIndicator from cqparts.display import display from cqparts.utils import CoordSystem cs = CoordSysIndicator() cs.world_coords = CoordSystem.random() display(cs) # doctest: +SKIP :param span: origin of return will be :math:`\pm span` per axis :param seed: if supplied, return is psudorandom (repeatable) :type seed: hashable object :return: randomized coordinate system :rtype: :class:`CoordSystem` """ if seed is not None: random.seed(seed) def rand_vect(min, max): return ( random.uniform(min, max), random.uniform(min, max), random.uniform(min, max), ) while True: try: return cls( origin=rand_vect(-span, span), xDir=rand_vect(-1, 1), normal=rand_vect(-1, 1), ) except RuntimeError: # Base.FreeCADError inherits from RuntimeError # Raised if xDir & normal vectors are parallel. # (the chance is very low, but it could happen) continue @property def world_to_local_transform(self): """ :return: 3d affine transform matrix to convert world coordinates to local coordinates. :rtype: :class:`cadquery.Matrix` For matrix structure, see :meth:`from_transform`. """ return self.fG @property def local_to_world_transform(self): """ :return: 3d affine transform matrix to convert local coordinates to world coordinates. :rtype: :class:`cadquery.Matrix` For matrix structure, see :meth:`from_transform`. """ return self.rG def __add__(self, other): """ For ``A`` + ``B``. Where ``A`` is this coordinate system, and ``B`` is ``other``. :raises TypeError: if addition for the given type is not supported Supported types: ``A`` (:class:`CoordSystem`) + ``B`` (:class:`CoordSystem`): :return: world coordinates of ``B`` in ``A``'s coordinates :rtype: :class:`CoordSystem` ``A`` (:class:`CoordSystem`) + ``B`` (:class:`cadquery.Vector`): :return: world coordinates of ``B`` represented in ``A``'s coordinate system :rtype: :class:`cadquery.Vector` ``A`` (:class:`CoordSystem`) + ``B`` (:class:`cadquery.CQ`): remember: :class:`cadquery.Workplane` inherits from :class:`cadquery.CQ` :return: content of ``B`` moved to ``A``'s coordinate system :rtype: :class:`cadquery.Workplane` """ if isinstance(other, CoordSystem): # CoordSystem + CoordSystem self_transform = self.local_to_world_transform other_transform = other.local_to_world_transform return self.from_transform( self_transform.multiply(other_transform) ) elif isinstance(other, cadquery.Vector): # CoordSystem + cadquery.Vector transform = self.local_to_world_transform return type(other)( transform.multiply(other.wrapped) ) elif isinstance(other, cadquery.CQ): # CoordSystem + cadquery.CQ transform = self.local_to_world_transform return other.newObject([ obj.transformShape(transform) for obj in other.objects ]) else: raise TypeError("adding a {other_cls!r} to a {self_cls!r} is not supported".format( self_cls=type(self), other_cls=type(other), )) def __sub__(self, other): """ For ``A`` - ``B``. Where ``A`` is this coordinate system, and ``B`` is ``other``. :raises TypeError: if subtraction for the given type is not supported Supported types: ``A`` (:class:`CoordSystem`) + ``B`` (:class:`CoordSystem`): :return: local coordinate system of ``A`` from ``B``'s coordinate system :rtype: :class:`CoordSystem` """ if isinstance(other, CoordSystem): # CoordSystem - CoordSystem self_transform = self.local_to_world_transform other_transform = other.world_to_local_transform return self.from_transform( other_transform.multiply(self_transform) ) else: raise TypeError("subtracting a {other_cls!r} from a {self_cls!r} is not supported".format( self_cls=type(self), other_cls=type(other), )) def __repr__(self): return "<{cls_name}: origin={origin} xDir={xDir} zDir={zDir}>".format( cls_name=type(self).__name__, origin="(%s)" % (', '.join("%g" % (round(v, 3)) for v in self.origin.toTuple())), xDir="(%s)" % (', '.join("%g" % (round(v, 3)) for v in self.xDir.toTuple())), zDir="(%s)" % (', '.join("%g" % (round(v, 3)) for v in self.zDir.toTuple())), )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/test.py
src/cqparts/utils/test.py
import unittest import re import inspect from .. import Component, Part, Assembly class ComponentTest(unittest.TestCase): """ Generic testcase with utilities for testing :class:`Part <cqparts.Part>` and :class:`Assembly <cqparts.Assembly>` instances. For example: .. doctest:: import cqparts import cadquery from cqparts.utils.test import ComponentTest class Box(cqparts.Part): def make(self): return cadquery.Workplane('XY').box(1,1,1) class BoxTest(ComponentTest): def test_box(self): box = Box() self.assertComponent(box) """ # ----- Assertion utilities def assertPartBoundingBox(self, obj): assert isinstance(obj, Part), "assertion only relevant for Part instances" self.assertGreater(obj.bounding_box.DiagonalLength, 0) def assertPartHasVolume(self, obj): self.assertGreater(obj.local_obj.val().wrapped.Volume, 0) # has volume def assertAssembyHasComponents(self, obj): self.assertGreater(len(obj.components), 0) # has components # ----- Class-wide utilities def assertPart(self, obj): """ Assert criteria common to any fully formed Part. :param obj: part under test :type obj: :class:`Part <cqparts.Part>` """ self.assertPartBoundingBox(obj) self.assertPartHasVolume(obj) # TODO: more def assertAssembly(self, obj): """ Assert criteria common to any fully formed Assembly. :param obj: assembly under test :type obj: :class:`Assembly <cqparts.Assembly>` """ self.assertAssembyHasComponents(obj) # TODO: more def assertComponent(self, obj, recursive=True, _depth=0): """ Assert criteria common to any fully formed Component. :param obj: component under test :type obj: :class:`Component <cqparts.Component>` :param recursive: if ``True`` sub-components will also be tested :type recursive: :class:`bool` """ self.assertIsInstance(obj, Component) if _depth == 0: obj.build() if isinstance(obj, Part): self.assertPart(obj) elif isinstance(obj, Assembly): self.assertAssembly(obj) if recursive: for (name, child) in obj.components.items(): self.assertComponent(child, recursive=recursive, _depth=_depth+1) else: self.fail("unsupported class %r, only Part & Assembly should inherit directly from Component" % (type(obj))) class CatalogueTest(ComponentTest): catalogue = None @classmethod def create_from(cls, catalogue, add_to={}, id_mangler=None, include_cond=None, exclude_cond=None): """ Create a testcase class that will run generic tests on each item in the given :class:`Catalogue <cqparts.catalogue.Catalogue>`. :param catalogue: catalogue to generatea tests from :type catalogue: :class:`Catalogue <cqparts.catalogue.Catalogue>` :param add_to: dict to add resulting class to (usually ``globals()``. :type add_to: :class:`dict` :param id_mangler: convert item id to a valid python method name :type id_mangler: :class:`function` :param include_cond: returns true if item should be tested :type include_cond: :class:`function` :param exclude_cond: returns true if item should not be tested :type exclude_cond: :class:`function` :return: a testcase class to be discovered and run by :mod:`unittest` :rtype: :class:`unittest.TestCase` sub-class (a class, **not** an instance) To create a test-case, and add the class with the catalogue's name to the ``globals()`` namespace:: from cqparts.utils.test import CatalogueTest from cqparts.catalogue import JSONCatalogue catalogue = JSONCatalogue('my_catalogue.json') CatalogueTest.create_from(catalogue, add_to=globals()) Alternatively, to control your class name a bit more traditionally:: # alternatively MyTestCase = CatalogueTest.create_from(catalogue) **Test Names / Catalogue IDs** Each test is named for its item's ``id``. By default, to translate the ids into valid python method names, this is done by replacing any *non-alpha-numeric* characters with a ``_``. To illustrate with some examples: =============== =================== ======================= id mangled id test name =============== =================== ======================= ``abc123`` ``abc123`` (same) ``test_abc123`` ``3.14159`` ``3_14159`` ``test_3_14159`` ``%$#*_yeah!`` ``_____yeah_`` ``test______yeah_`` ``_(@@)yeah&`` ``_____yeah_`` ``test______yeah_`` =============== =================== ======================= So you can see why a python method name of ``test_%$#*_yeah!`` might be a problem, which is why this is done. But you may also spot that the last 2, although their IDs are unique, the test method names are the same. To change the way ID's are mangled into test method names, set the ``id_mangler`` parameter:: def mangle_id(id_str): return id_str.replace('a', 'X') CatalogueTest.create_from( catalogue, # as defined in the previous example add_to=globals(), id_mangler=mangle_id, ) That would change the first test name to ``test_Xbc123``. **Include / Exclude Items** If you intend on *including* or *excluding* certain items from the testlist, you can employ the ``include_cond`` and/or ``exclude_cond`` parameters:: def include_item(item): # include item if it has a specific id return item.get('id') in ['a', 'b', 'c'] def exclude_item(item): # exclude everything with a width > 100 return item.get('obj').get('params').get('width', 0) > 100 CatalogueTest.create_from( catalogue, # as defined in the previous example add_to=globals(), include_cond=include_item, exclude_cond=exclude_item, ) Tests will be created if the following conditions are met: =========== =========== ======================= excluded included test case generated? =========== =========== ======================= n/a n/a Yes : tests are generated if no include/exclude methods are set n/a ``True`` Yes n/a ``False`` No ``True`` n/a No ``False`` n/a Yes ``False`` ``False`` No : inclusion take precedence (or lack thereof) ``False`` ``True`` Yes ``True`` ``False`` No ``True`` ``True`` Yes : inclusion take precedence =========== =========== ======================= """ # runtime import? # cqparts.utils is intended to be imported from any other cqparts # module... circular dependency is likely, this mitigates that risk. from ..catalogue import Catalogue if not isinstance(catalogue, Catalogue): raise ValueError("invalid catalogue: %r" % catalogue) if id_mangler is None: id_mangler = lambda n: re.sub(r'[^a-z0-9]', '_', n, flags=re.I) # calling module caller_frame = inspect.stack()[1][0] caller_module = inspect.getmodule(caller_frame).__name__ cls_body = { 'catalogue': catalogue, '__module__': caller_module, } def mk_test_method(item_data): # Create test method run when test is executed def test_meth(self): obj = self.catalogue.deserialize_item(item_data) self.assertComponent(obj, recursive=True) return test_meth # Create 1 test per catalogue item for item in catalogue.iter_items(): #item = <item dict> # determine if item requires a testcase add_test = not bool(include_cond) if exclude_cond and exclude_cond(item): add_test = False if include_cond and include_cond(item): add_test = True if add_test: # Define test method test_meth = mk_test_method(item) # Add test method to class body test_name = "test_{id}".format( id=id_mangler(item.get('id')), ) test_meth.__name__ = test_name cls_body[test_name] = test_meth sub_cls = type( 'CatalogueTest_%s' % catalogue.name, (cls,), cls_body, ) add_to[sub_cls.__name__] = sub_cls return sub_cls
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_gearboxes/__init__.py
src/cqparts_gearboxes/__init__.py
""" Copyright 2018 Peter Boin 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. """ __release_ready__ = False # TODO: remove to stop blocking build
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_toys/__init__.py
src/cqparts_toys/__init__.py
""" Copyright 2018 Peter Boin 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. """ __release_ready__ = False # TODO: remove to stop blocking build
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_toys/train/__init__.py
src/cqparts_toys/train/__init__.py
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_toys/train/track.py
src/cqparts_toys/train/track.py
import cadquery import cqparts from cqparts.params import * from cqparts.utils import property_buffered from cqparts.display.material import render_props from cqparts.constraint import Mate from cqparts.utils import CoordSystem class _Track(cqparts.Part): double_sided = Boolean(True, doc="if set, track is cut from both sides") # Profile Metrics width = PositiveFloat(30, doc="track width") depth = PositiveFloat(8, doc="track thickness") track_guage = PositiveFloat(None, doc="distance between wheel centers") track_width = PositiveFloat(None, doc="wheel's width") track_depth = PositiveFloat(2, doc="depth each track is cut") track_chamfer = PositiveFloat(None, doc="chamfer at wheel's edges") # Connector conn_diam = PositiveFloat(None, doc="diameter of connector circle") conn_neck_width = PositiveFloat(None, doc="connector neck width") conn_neck_length = PositiveFloat(None, doc="connector neck length") conn_clearance = PositiveFloat(0.5, doc="clearance ") _render = render_props(template='wood') def initialize_parameters(self): super(_Track, self).initialize_parameters() if self.track_guage is None: self.track_guage = self.width * (2. / 3) if self.track_width is None: self.track_width = self.track_guage / 4 if self.track_depth is None: self.track_depth = self.track_width / 2 if self.track_chamfer is None: self.track_chamfer = self.track_depth / 3 if self.conn_diam is None: self.conn_diam = self.depth if self.conn_neck_width is None: self.conn_neck_width = self.conn_diam / 3 if self.conn_neck_length is None: self.conn_neck_length = self.conn_diam * 0.6 @property def _wheel_profile(self): if self.track_chamfer: left_side = (self.track_guage / 2) - (self.track_width / 2) points = [ (left_side - (self.track_chamfer * 2), (self.depth / 2) + self.track_depth), (left_side - (self.track_chamfer * 2), (self.depth / 2) + self.track_chamfer), (left_side, (self.depth / 2) - self.track_chamfer), # remove if self.track_chamfer == 0 (left_side, (self.depth / 2) - self.track_depth), ] # mirror over x = self.track_guage / 2 plane points += [(self.track_guage - x, y) for (x, y) in reversed(points)] else: # no chamfer, just plot the points for a rectangle points = [ ((self.track_guage / 2) - (self.track_width / 2), (self.depth / 2) + self.track_depth), ((self.track_guage / 2) - (self.track_width / 2), (self.depth / 2) - self.track_depth), ((self.track_guage / 2) + (self.track_width / 2), (self.depth / 2) - self.track_depth), ((self.track_guage / 2) + (self.track_width / 2), (self.depth / 2) + self.track_depth), ] flip = lambda p, xf, yf: (p[0] * xf, p[1] * yf) profile = cadquery.Workplane('XZ') \ .moveTo(*flip(points[0], 1, 1)).polyline([flip(p, 1, 1) for p in points[1:]]).close() \ .moveTo(*flip(points[0], -1, 1)).polyline([flip(p, -1, 1) for p in points[1:]]).close() if self.double_sided: profile = profile \ .moveTo(*flip(points[0], 1, -1)).polyline([flip(p, 1, -1) for p in points[1:]]).close() \ .moveTo(*flip(points[0], -1, -1)).polyline([flip(p, -1, -1) for p in points[1:]]).close() return profile @property def _track_profile(self): return cadquery.Workplane('XZ').rect(self.width, self.depth) def _get_connector(self, clearance=False): clear_dist = self.conn_clearance if clearance else 0. return cadquery.Workplane('XY').box( self.conn_neck_width + (clear_dist * 2), self.conn_neck_length + self.conn_diam / 2, self.depth, centered=(True, False, True), ).union(cadquery.Workplane('XY', origin=( 0, self.conn_neck_length + self.conn_diam / 2, -self.depth / 2 )).circle((self.conn_diam / 2) + clear_dist).extrude(self.depth)) @property def conn_length(self): return self.conn_neck_length + self.conn_diam class StraightTrack(_Track): """ .. image:: /_static/img/toys/track-straight.png """ length = PositiveFloat(100, doc="track length") def make(self): track = self._track_profile.extrude(self.length) \ .translate((0, self.length / 2, 0)) \ .union(self._get_connector().translate((0, self.length / 2, 0))) \ .cut(self._get_connector(True).translate((0, -self.length / 2, 0))) # cut tracks track = track.cut( self._wheel_profile \ .extrude(self.length + self.conn_length) \ .translate((0, self.length / 2 + self.conn_length, 0)) ) return track def make_simple(self): return self._track_profile.extrude(self.length) \ .translate((0, self.length / 2, 0)) @property def mate_start(self): return Mate(self, CoordSystem((0, -self.length / 2, 0))) @property def mate_end(self): return Mate(self, CoordSystem((0, self.length / 2, 0))) class CurvedTrack(_Track): """ .. image:: /_static/img/toys/track-curved.png """ turn_radius = Float(100, doc="radius of turn") turn_angle = FloatRange(0, 360, 45, doc="arc angle covered by track (unit: degrees)") def make(self): revolve_params = { 'angleDegrees': self.turn_angle, 'axisStart': (self.turn_radius, 0), 'axisEnd': (self.turn_radius, 1 if (self.turn_radius > 0) else -1), } track = self._track_profile.revolve(**revolve_params) \ .translate((-self.turn_radius, 0, 0)) \ .cut(self.mate_start.local_coords + self._get_connector(True)) \ .union(self.mate_end.local_coords + self._get_connector(False)) # cut tracks track = track.cut( self._wheel_profile.revolve(**revolve_params) \ .translate((-self.turn_radius, 0, 0)) ) track = track.cut( self.mate_end.local_coords + self._wheel_profile.extrude(-self.conn_length) ) return track #return self._wheel_profile.extrude(self.conn_length) def make_simple(self): return self._track_profile.revolve( angleDegrees=self.turn_angle, axisStart=(self.turn_radius, 0), axisEnd=(self.turn_radius, 1), ).translate((-self.turn_radius, 0, 0)) \ @property def mate_start(self): return Mate(self, CoordSystem((-self.turn_radius, 0, 0))) @property def mate_end(self): angle = self.turn_angle if (self.turn_radius < 0) else -self.turn_angle return Mate(self, CoordSystem().rotated((0, 0, angle)) + self.mate_start.local_coords)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_misc/__init__.py
src/cqparts_misc/__init__.py
""" Copyright 2018 Peter Boin 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. """ # =========================== Package Information =========================== # Version Planning: # 0.1.x - Development Status :: 2 - Pre-Alpha # 0.2.x - Development Status :: 3 - Alpha # 0.3.x - Development Status :: 4 - Beta # 1.x - Development Status :: 5 - Production/Stable # <any above>.y - developments on that version (pre-release) # <any above>*.dev* - development release (intended purely to test deployment) __version__ = '0.1.0' __title__ = 'cqparts_misc' __description__ = 'Miscelaneous content library for cqparts' __url__ = 'https://github.com/fragmuffin/cqparts/tree/master/src/cqparts_misc' __author__ = 'Peter Boin' __email__ = 'peter.boin+cqparts@gmail.com' __license__ = 'Apache Public License 2.0' __keywords__ = ['cadquery', 'cad', '3d', 'modeling'] # not text-parsable import datetime _now = datetime.date.today() __copyright__ = "Copyright {year} {author}".format(year=_now.year, author=__author__) # =========================== Functional =========================== __all__ = [ 'basic', ] from . import basic
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_misc/basic/primatives.py
src/cqparts_misc/basic/primatives.py
import cadquery import cqparts from cqparts.params import * from cqparts.search import register, common_criteria from cqparts.constraint import Mate from cqparts.utils import CoordSystem # basic.primatives registration utility module_criteria = { 'lib': 'basic', 'type': 'primative', 'module': __name__, } _register = common_criteria(**module_criteria)(register) # ------------- Primative Shapes ------------ @_register(shape='cube') class Cube(cqparts.Part): """ Cube centered on the XY plane """ size = PositiveFloat(1, doc="length of all sides") def make(self): return cadquery.Workplane('XY').box( self.size, self.size, self.size, ) @property def mate_top(self): """ :return: mate at top of cube, z-axis upward :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem((0, 0, self.size / 2))) @property def mate_bottom(self): """ :return: mate at base of cube, z-axis upward :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem((0, 0, -self.size / 2))) @property def mate_pos_x(self): """ :return: mate on positive X face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(self.size/2,0,0), xDir=(0,0,1), normal=(1,0,0) )) @property def mate_neg_x(self): """ :return: mate on negative X face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(-self.size/2,0,0), xDir=(0,0,1), normal=(-1,0,0) )) @property def mate_pos_y(self): """ :return: mate on positive Y face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(0,self.size/2,self.size/2), xDir=(0,0,1), normal=(0,1,0) )) @property def mate_neg_y(self): """ :return: mate on negative Y face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(0,-self.size/2,self.size/2), xDir=(0,0,1), normal=(0,-1,0) )) @_register(shape='box') class Box(cqparts.Part): """ Box with its base on XY plane. """ length = PositiveFloat(1, doc="box dimension along x-axis") width = PositiveFloat(1, doc="box dimension along y-axis") height = PositiveFloat(1, doc="box dimension along z-axis") def make(self): return cadquery.Workplane('XY').box( self.length, self.width, self.height, centered=(True, True, False) ) @property def mate_top(self): """ :return: mate at top of box :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem((0, 0, self.height))) @property def mate_bottom(self): """ :return: mate at base of box :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem((0, 0, 0))) @property def mate_pos_x(self): """ :return: mate on positive X face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(self.length/2,0,self.height/2), xDir=(0,0,1), normal=(1,0,0) )) @property def mate_neg_x(self): """ :return: mate on negative X face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(-self.length/2,0,self.height/2), xDir=(0,0,1), normal=(-1,0,0) )) @property def mate_pos_y(self): """ :return: mate on positive Y face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(0,self.width/2,self.height/2), xDir=(0,0,1), normal=(0,1,0) )) @property def mate_neg_y(self): """ :return: mate on negative Y face :rtype: :class:`Mate <cqparts.constraint.Mate>` """ return Mate(self, CoordSystem( origin=(0,-self.width/2,self.height/2), xDir=(0,0,1), normal=(0,-1,0) )) @_register(shape='sphere') class Sphere(cqparts.Part): """ Sphere sitting on the XY plane """ radius = PositiveFloat(1, doc="sphere radius") def make(self): return cadquery.Workplane('XY', origin=(0, 0, self.radius)) \ .sphere(self.radius) @_register(shape='cylinder') class Cylinder(cqparts.Part): """ Cylinder with its base on the XY plane """ radius = PositiveFloat(1, doc="cylinder radius") length = PositiveFloat(1, doc="cylinder length") def make(self): return cadquery.Workplane('XY') \ .circle(self.radius).extrude(self.length) @property def mate_bottom(self): return self.mate_origin @property def mate_top(self): return Mate(self, CoordSystem(origin=(0, 0, self.length)))
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_misc/basic/indicators.py
src/cqparts_misc/basic/indicators.py
import cadquery import cqparts from cqparts.params import * from cqparts.constraint import Fixed, Mate from cqparts.search import register, common_criteria from cqparts.utils.wrappers import as_part from cqparts.display.material import TEMPLATE # basic.primatives registration utility module_criteria = { 'lib': 'basic', 'type': 'indicator', 'module': __name__, } _register = common_criteria(**module_criteria)(register) # --------------- Indicators --------------- @_register(indicator='coord_sys') class CoordSysIndicator(cqparts.Assembly): """ Assembly of 3 rectangles indicating xyz axes. * X = red * Y = green * Z = blue """ length = PositiveFloat(10, doc="length of axis indicators") width = PositiveFloat(1, doc="width of axis indicators") class Rect(cqparts.Part): w = Float(1) (x, y, z) = (Float(), Float(), Float()) def initialize_parameters(self): self.x = self.x or self.w self.y = self.y or self.w self.z = self.z or self.w def make(self): return cadquery.Workplane('XY').box( self.x, self.y, self.z, centered=(self.x <= self.w, self.y <= self.w, self.z <= self.w), ) def make_components(self): return { 'x': self.Rect(w=self.width, x=self.length, _render=TEMPLATE['red']), 'y': self.Rect(w=self.width, y=self.length, _render=TEMPLATE['green']), 'z': self.Rect(w=self.width, z=self.length, _render=TEMPLATE['blue']), } def make_constraints(self): return [ Fixed(self.components[k].mate_origin) for k in 'xyz' ] @_register(indicator='plane') class PlaneIndicator(cqparts.Part): """ A thin plate spread over the given plane """ size = PositiveFloat(20, doc="size of square plate; length of one side") thickness = PositiveFloat(0.01, doc="thickness of indicator plate") name = String('XY', doc="name of plane, according to :meth:`cadquery.Plane.named`") def make(self): return cadquery.Workplane(self.name).box(self.size, self.size, self.thickness)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_misc/basic/__init__.py
src/cqparts_misc/basic/__init__.py
__all__ = [ 'indicators', 'primatives', ] from . import indicators from . import primatives
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/stepper.py
src/cqparts_motors/stepper.py
""" cqparts motors 2018 Simon Kirkby obeygiantrobot@gmail.com stepper motor generic """ # TODO # even 4 fasteners so it auto mounts to whatever it is parented to. import cadquery as cq import cqparts from cqparts.params import PositiveFloat from cqparts.constraint import Fixed, Coincident from cqparts.constraint import Mate from cqparts.display import render_props from cqparts.utils.geometry import CoordSystem from . import shaft from . import motor class _EndCap(cqparts.Part): # Parameters width = PositiveFloat(42.3, doc="Motor Size") length = PositiveFloat(10, doc="End length") cham = PositiveFloat(3, doc="chamfer") # _render = render_props(color=(50, 50, 50),alpha=0.4) def make(self): base = cq.Workplane("XY")\ .box(self.width, self.width, self.length)\ .edges("|Z")\ .chamfer(self.cham) return base @property def mate_top(self): " connect to the end of the top cap" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(0, 1, 0), normal=(0, 0, -1) )) @property def mate_bottom(self): " bottom of the top cap" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) )) class _Stator(cqparts.Part): # Parameters width = PositiveFloat(40.0, doc="Motor Size") length = PositiveFloat(20, doc="stator length") cham = PositiveFloat(3, doc="chamfer") _render = render_props(color=(50, 50, 50)) def make(self): base = cq.Workplane("XY")\ .box(self.width, self.width, self.length,centered=(True,True,True))\ .edges("|Z")\ .chamfer(self.cham) return base @property def mate_top(self): " top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) )) @property def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) )) class _StepperMount(_EndCap): spacing = PositiveFloat(31, doc="hole spacing") hole_size = PositiveFloat(3, doc="hole size") boss = PositiveFloat(22, doc="boss size") boss_length = PositiveFloat(2, doc="boss_length") def make(self): obj = super(_StepperMount, self).make() obj.faces(">Z").workplane() \ .rect(self.spacing, self.spacing, forConstruction=True)\ .vertices() \ .hole(self.hole_size) obj.faces(">Z").workplane()\ .circle(self.boss/2).extrude(self.boss_length) return obj @property def mate_top(self): " top of the mount" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) )) @property def mate_bottom(self): " bottom of the mount" return Mate(self, CoordSystem( origin=(0, 0,-self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) )) class _Back(_EndCap): spacing = PositiveFloat(31, doc="hole spacing") hole_size = PositiveFloat(3, doc="hole size") def make(self): obj = super(_Back, self).make() obj.faces(">Z").workplane() \ .rect(self.spacing, self.spacing, forConstruction=True)\ .vertices() \ .hole(self.hole_size) return obj class Stepper(motor.Motor): " Stepper Motor , simple rendering " shaft_type = shaft.Shaft width = PositiveFloat(42.3, doc="width and depth of the stepper") length = PositiveFloat(50, doc="length of the stepper") hole_spacing = PositiveFloat(31.0, doc="distance between centers") hole_size = PositiveFloat(3, doc="hole diameter , select screw with this") boss_size = PositiveFloat(22, doc="diameter of the raise circle") boss_length = PositiveFloat(2, doc="length away from the top surface") shaft_diam = PositiveFloat(5, doc="diameter of the the shaft ") shaft_length = PositiveFloat(24, doc="length from top surface") def get_shaft(self): return self.components['shaft'] def mount_points(self): " return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects def make_components(self): sec = self.length / 6 return { 'topcap': _StepperMount( width=self.width, length=sec, spacing=self.hole_spacing, hole_size=self.hole_size, boss=self.boss_size ), 'stator': _Stator(width=self.width-3, length=sec*4), 'botcap': _Back( width=self.width, length=sec, spacing=self.hole_spacing, hole_size=self.hole_size, ), 'shaft': self.shaft_type( length=self.shaft_length, diam=self.shaft_diam) } def make_constraints(self): return [ Fixed(self.components['topcap'].mate_top), Coincident( self.components['stator'].mate_top, self.components['topcap'].mate_bottom, ), Coincident( self.components['botcap'].mate_bottom, self.components['stator'].mate_bottom ), Coincident( self.components['shaft'].mate_origin, self.components['topcap'].mate_top ), ] def apply_cutout(self): " shaft cutout " stepper_shaft = self.components['shaft'] top = self.components['topcap'] local_obj = top.local_obj local_obj = local_obj.cut(stepper_shaft.get_cutout(clearance=0.5)) def make_alterations(self): self.apply_cutout() def boss_cutout(self,clearance=0): bc = cq.Workplane("XY")\ .circle(self.boss_size/2)\ .extrude(self.shaft_length) return bc def cut_boss(self,part,clearance=0): co = self.boss_cutout(clearance=clearance) lo = part.local_obj\ .cut((self.world_coords - part.world_coords)+co) if __name__ == "__main__": from cqparts.display import display st = Stepper() display(st)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/shaft.py
src/cqparts_motors/shaft.py
""" cp parts base shaft collection # 2018 Simon Kirkby obeygiantrobot@gmail.com """ # TODO # need tip , base and offset mate points # maybe shaft needs to go into it's own module # # there are lots of types of shafts and extras # need a clean way to build shafts import cadquery as cq import cqparts from cqparts.params import PositiveFloat from cqparts.display import render_props # base shaft type class Shaft(cqparts.Part): " base shaft , override ME" length = PositiveFloat(24, doc="shaft length") diam = PositiveFloat(5, doc="shaft diameter") _render = render_props(color=(50, 255, 255)) def make(self): shft = cq.Workplane("XY")\ .circle(self.diam/2)\ .extrude(self.length)\ .faces(">Z")\ .chamfer(0.4) return shft def cut_out(self): cutout = cq.Workplane("XY")\ .circle(self.diam/2)\ .extrude(self.length) return cutout # TODO , mate for shafts def get_cutout(self, clearance=0): " clearance cut out for shaft " return cq.Workplane('XY', origin=(0, 0, 0)) \ .circle((self.diam / 2) + clearance) \ .extrude(self.length*2)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/dc.py
src/cqparts_motors/dc.py
""" DC motor cqparts model 2018 Simon Kirkby obeygiantrobot@gmail.com """ import math import cadquery as cq import cqparts from cqparts.params import PositiveFloat, String from cqparts.display import render_props from cqparts.constraint import Fixed, Coincident from cqparts.constraint import Mate from cqparts.utils.geometry import CoordSystem from cqparts_motors import shaft, motor # defines the profile of the motor , returns a wire def _profile(shape, diam, thickness): work_plane = cq.Workplane("XY") if shape == "circle": profile = work_plane.circle(diam/2) if shape == "flat": radius = diam / 2 half_thickness = thickness / 2 intersect = math.sqrt(radius*radius-half_thickness*half_thickness) profile = work_plane.moveTo(0, half_thickness)\ .lineTo(intersect, half_thickness)\ .threePointArc((radius, 0), (intersect, -half_thickness))\ .lineTo(0, -half_thickness)\ .mirrorY() if shape == "rect": profile = work_plane.rect(thickness/2, diam/2) return profile # the motor cup class _Cup(cqparts.Part): height = PositiveFloat(25.1, doc="cup length") diam = PositiveFloat(20.4, doc="cup diameter") thickness = PositiveFloat(15.4, doc="cup thickness for flat profile") hole_spacing = PositiveFloat(12.4, doc="distance between the holes") hole_size = PositiveFloat(2, doc="hole size") step_diam = PositiveFloat(12, doc="step diameter") step_height = PositiveFloat(0, doc="height if step, if zero no step") bush_diam = PositiveFloat(6.15, doc="diameter of the bush") bush_height = PositiveFloat(1.6, doc="height of the bush") profile = String("flat", doc="profile shape (circle|flat|rect)") def make(self): # grab the correct profile work_plane = cq.Workplane("XY") cup = _profile(self.profile, self.diam, self.thickness)\ .extrude(-self.height) if self.step_height > 0: step = work_plane.circle(self.step_diam/2).extrude(self.step_height) cup = cup.union(step) bush = work_plane.workplane( offset=self.step_height)\ .circle(self.bush_diam/2)\ .extrude(self.bush_height) cup = cup.union(bush) return cup def get_cutout(self, clearance=0): " get the cutout for the shaft" return cq.Workplane('XY', origin=(0, 0, 0)) \ .circle((self.diam / 2) + clearance) \ .extrude(10) @property def mate_bottom(self): " connect to the bottom of the cup" return Mate(self, CoordSystem(\ origin=(0, 0, -self.height),\ xDir=(1, 0, 0),\ normal=(0, 0, 1))) class _BackCover(cqparts.Part): height = PositiveFloat(6, doc="back length") diam = PositiveFloat(20.4, doc="back diameter") thickness = PositiveFloat(15.4, doc="back thickness for flat profile") profile = String("flat", doc="profile shape (circle|flat|rect)") bush_diam = PositiveFloat(6.15, doc="diameter of the bush") bush_height = PositiveFloat(1.6, doc="height of the bush") _render = render_props(color=(50, 255, 255)) def make(self): # grab the correct profile work_plane = cq.Workplane("XY") back = work_plane.workplane(offset=-self.height)\ .circle(self.bush_diam/2)\ .extrude(-self.bush_height) if self.height > 0: back = _profile(self.profile, self.diam, self.thickness)\ .extrude(-self.height) back = back.union(back) return back class DCMotor(motor.Motor): """ DC motors for models .. image:: /_static/img/motors/DCMotor.png """ height = PositiveFloat(25.1, doc="motor length") diam = PositiveFloat(20.4, doc="motor diameter") thickness = PositiveFloat(15.4, doc="back thickness for flat profile") profile = String("flat", doc="profile shape (circle|flat|rect)") bush_diam = PositiveFloat(6.15, doc="diameter of the bush") bush_height = PositiveFloat(1.6, doc="height of the bush") shaft_type = shaft.Shaft #replace with other shaft shaft_length = PositiveFloat(11.55, doc="length of the shaft") shaft_diam = PositiveFloat(2, doc="diameter of the shaft") cover_height = PositiveFloat(0, doc="back cover height") # a step on the top surface step_height = PositiveFloat(0, doc="height if step, if zero no step") step_diam = PositiveFloat(12, doc="step diameter") def get_shaft(self): return self.shaft_type def mount_points(self): # TODO handle mount points pass def make_components(self): return { 'body': _Cup( height=self.height, thickness=self.thickness, diam=self.diam, profile=self.profile, bush_diam=self.bush_diam, bush_height=self.bush_height, step_height=self.step_height ), 'shaft': self.shaft_type(length=self.shaft_length, diam=self.shaft_diam), 'back': _BackCover( height=self.cover_height, thickness=self.thickness, diam=self.diam, profile=self.profile, bush_diam=self.bush_diam, bush_height=self.bush_height ) } def make_constraints(self): return [ Fixed(self.components['body'].mate_origin), Coincident( self.components['shaft'].mate_origin, self.components['body'].mate_origin, ), Coincident( self.components['back'].mate_origin, self.components['body'].mate_bottom, ) ]
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/motor.py
src/cqparts_motors/motor.py
# base motor class # # 2018 Simon Kirkby obeygiantrobot@gmail.com import cqparts # base motor class # TODO lift all motor things up to here class Motor(cqparts.Assembly): def mount_points(self): raise NotImplementedError("mount_points function not implemented") def get_shaft(self): raise NotImplementedError("get_shaft function not implemented")
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/__init__.py
src/cqparts_motors/__init__.py
""" Copyright 2018 Peter Boin 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. """ __release_ready__ = False # TODO: remove to stop blocking build
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/catalogue/scripts/stepper-nema.py
src/cqparts_motors/catalogue/scripts/stepper-nema.py
#!/usr/bin/env python # Catalogue Usage example: # >>> from cqparts.catalogue import JSONCatalogue # >>> import cqparts_motors # >>> filename = os.path.join( # ... os.path.dirname(cqparts_motors.__file__), # ... 'catalogue', 'stepper-nema.json', # ... ) # >>> catalogue = JSONCatalogue(filename) # >>> item = catalogue.get_query() # >>> stepper = catalogue.get(item.criteria.size == 17) # >>> from cqparts.display import display # >>> display(stepper) import os import cqparts from cqparts.catalogue import JSONCatalogue # Stepper from cqparts_motors.stepper import Stepper CATALOGUE_NAME = 'stepper-nema.json' # Sized motors , build into collection # http://www.osmtec.com/stepper_motors.htm is a good reference # sizes 8, 11, 14, 16, 17, 23, 24, 34, 42 # Stepper.class_params().keys() NEMA_SIZES = { 8 : { 'shaft_length': 10.0, 'hole_spacing': 15.4, 'hole_size': 2.0, 'length': 28.0, 'width': 20.3, 'boss_size': 16.0, 'shaft_diam': 4.0, 'boss_length': 1.5, }, 11 : { 'shaft_length': 20.0, 'hole_spacing': 23.0, 'hole_size': 2.5, 'length': 31.5, 'width': 28.2, 'boss_size': 22.0, 'shaft_diam': 4.0, 'boss_length': 2.0, }, 14 : { 'shaft_length': 24.0, 'hole_spacing': 26.0, 'hole_size': 3.0, 'length': 28.0, 'width': 35.2, 'boss_size': 22.0, 'shaft_diam': 5.0, 'boss_length': 2.0, }, 17 : { 'shaft_length': 24.0, 'hole_spacing': 31.0, 'hole_size': 3.0, 'length': 50.0, 'width': 42.0, 'boss_size': 22.0, 'shaft_diam': 5.0, 'boss_length': 2.0, }, 23 : { 'shaft_length': 21.0, 'hole_spacing': 47.0, 'hole_size': 5.0, 'length': 56.0, 'width': 57.0, 'boss_size': 38.0, 'shaft_diam': 6.35, 'boss_length': 1.6, }, } # Generate Catalogue catalogue = JSONCatalogue( filename=os.path.join('..', CATALOGUE_NAME), clean=True, # starts fresh ) # Create Steppers for (size, params) in NEMA_SIZES.items(): catalogue.add( id='NEMA_Stepper_%i' % size, obj=Stepper(**params), criteria={ 'type': 'motor', 'class': 'stepper', 'size': size, }, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/catalogue/scripts/dc-hobby.py
src/cqparts_motors/catalogue/scripts/dc-hobby.py
#!/usr/bin/env python # Catalogue Usage example: # >>> from cqparts.catalogue import JSONCatalogue # >>> import cqparts_motors # >>> filename = os.path.join( # ... os.path.dirname(cqparts_motors.__file__), # ... 'catalogue', 'dcmotor.json', # ... ) # >>> catalogue = JSONCatalogue(filename) # >>> item = catalogue.get_query() # >>> dc = catalogue.get(item.criteria.size == 304) # >>> from cqparts.display import display # >>> display(dc) import os import cqparts from cqparts.catalogue import JSONCatalogue # DC Motor from cqparts_motors.dc import DCMotor CATALOGUE_NAME = 'dcmotor.json' # DC Motor hobby examples # example only DC_HOBBY = { '130': { "profile": "flat", "diam": 20.4, "shaft_length": 11.55, "cover_height": 0.0, "thickness": 15.4, "bush_height": 1.6, "shaft_diam": 2.0, "bush_diam": 6.15, "height": 25.1 }, 'R140': { "profile": "circle", "diam": 20.4, "shaft_length": 11.55, "cover_height": 0.0, "step_diam": 12.0, "thickness": 15.4, "bush_height": 1.6, "step_height": 1, "shaft_diam": 2.0, "bush_diam": 6.15, "height": 25.1 }, 'slotcar': { "profile": "rect", "diam": 23, "shaft_length": 8, "cover_height": 0.0, "step_diam": 12.0, "thickness": 15.4, "bush_height": 1.6, "step_height": 0.0, "shaft_diam": 2.0, "bush_diam": 4, "height": 17 }, 'flat': { "profile": "circle", "diam": 20.4, "shaft_length": 6, "cover_height": 0.0, "step_diam": 12.0, "thickness": 15.4, "bush_height": 0.4, "step_height": 0.0, "shaft_diam": 2.0, "bush_diam": 6.15, "height": 10 } } # Generate Catalogue catalogue = JSONCatalogue( filename=os.path.join('..', CATALOGUE_NAME), clean=True, # starts fresh ) # Create Motors for (name, params) in DC_HOBBY.items(): catalogue.add( id= name, obj=DCMotor(**params), criteria={ 'type': 'motor', 'class': 'dc', 'diam': params['diam'], }, )
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_springs/__init__.py
src/cqparts_springs/__init__.py
""" Copyright 2018 Peter Boin 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. """ __release_ready__ = False # TODO: remove to stop blocking build
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false
cqparts/cqparts
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_template/search.py
src/cqparts_template/search.py
from cqparts.search import ( find as _find, search as _search, register as _register, ) from cqparts.search import common_criteria module_criteria = { 'module': __name__, } register = common_criteria(**module_criteria)(_register) search = common_criteria(**module_criteria)(_search) find = common_criteria(**module_criteria)(_find)
python
Apache-2.0
018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53
2026-01-05T07:14:41.025281Z
false