id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
25,500
conpot_cmdrsp.py
mushorg_conpot/conpot/protocols/snmp/conpot_cmdrsp.py
import sys import logging import random from pysnmp.entity.rfc3413 import cmdrsp from pysnmp.proto import error from pysnmp.proto.api import v2c import pysnmp.smi.error from pysnmp import debug import gevent import conpot.core as conpot_core from conpot.utils.networking import get_interface_ip logger = logging.getLogger(__name__) class conpot_extension(object): def _getStateInfo(self, snmpEngine, stateReference): for _, v in list(snmpEngine.messageProcessingSubsystems.items()): if stateReference in v._cache.__dict__["_Cache__stateReferenceIndex"]: state_dict = v._cache.__dict__["_Cache__stateReferenceIndex"][ stateReference ][0] addr = state_dict["transportAddress"] # msgVersion 0/1 to SNMPv1/2, msgversion 3 corresponds to SNMPv3 if state_dict["msgVersion"] < 3: snmp_version = state_dict["msgVersion"] + 1 else: snmp_version = state_dict["msgVersion"] return addr, snmp_version def log(self, version, msg_type, addr, req_varBinds, res_varBinds=None, sock=None): session = conpot_core.get_session( "snmp", addr[0], addr[1], get_interface_ip(addr[0]), sock.getsockname()[1] ) req_oid = req_varBinds[0][0] req_val = req_varBinds[0][1] event_type = "SNMPv{0} {1}".format(version, msg_type) request = {"oid": str(req_oid), "val": str(req_val)} response = None logger.info("%s request from %s: %s %s", event_type, addr, req_oid, req_val) if res_varBinds: res_oid = ".".join(map(str, res_varBinds[0][0])) res_val = res_varBinds[0][1] logger.info("%s response to %s: %s %s", event_type, addr, res_oid, res_val) response = {"oid": str(res_oid), "val": str(res_val)} session.add_event( {"type": event_type, "request": request, "response": response} ) def do_tarpit(self, delay): # sleeps the thread for $delay ( should be either 1 float to apply a static period of time to sleep, # or 2 floats seperated by semicolon to sleep a randomized period of time determined by ( rand[x;y] ) lbound, _, ubound = delay.partition(";") if not lbound or lbound is None: # no lower boundary found. Assume zero latency pass elif not ubound or ubound is None: # no upper boundary found. Assume static latency gevent.sleep(float(lbound)) else: # both boundaries found. Assume random latency between lbound and ubound gevent.sleep(random.uniform(float(lbound), float(ubound))) def check_evasive(self, state, threshold, addr, cmd): # checks if current states are > thresholds and returns True if the request # is considered to be a DoS request. state_individual, state_overall = state threshold_individual, _, threshold_overall = threshold.partition(";") if int(threshold_individual) > 0: if int(state_individual) > int(threshold_individual): logger.warning( "SNMPv%s: DoS threshold for %s exceeded (%s/%s).", cmd, addr, state_individual, threshold_individual, ) # DoS threshold exceeded. return True if int(threshold_overall) > 0: if int(state_overall) > int(threshold_overall): logger.warning( "SNMPv%s: DDoS threshold exceeded (%s/%s).", cmd, state_individual, threshold_overall, ) # DDoS threshold exceeded return True # This request will be answered return False class c_GetCommandResponder(cmdrsp.GetCommandResponder, conpot_extension): def __init__(self, snmpEngine, snmpContext, databus_mediator, host, port): self.databus_mediator = databus_mediator self.tarpit = "0;0" self.threshold = "0;0" self.host = host self.port = port cmdrsp.GetCommandResponder.__init__(self, snmpEngine, snmpContext) conpot_extension.__init__(self) def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): (acFun, acCtx) = acInfo # rfc1905: 4.2.1.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars varBinds = v2c.apiPDU.getVarBinds(PDU) addr, snmp_version = self._getStateInfo(snmpEngine, stateReference) evasion_state = self.databus_mediator.update_evasion_table(addr) if self.check_evasive( evasion_state, self.threshold, addr, str(snmp_version) + " Get" ): return None rspVarBinds = None try: # generate response rspVarBinds = mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx)) # determine the correct response class and update the dynamic value table reference_class = rspVarBinds[0][1].__class__.__name__ # reference_value = rspVarBinds[0][1] response = self.databus_mediator.get_response( reference_class, tuple(rspVarBinds[0][0]) ) if response: rspModBinds = [(tuple(rspVarBinds[0][0]), response)] rspVarBinds = rspModBinds finally: sock = snmpEngine.transportDispatcher.socket self.log(snmp_version, "Get", addr, varBinds, rspVarBinds, sock) # apply tarpit delay if self.tarpit != 0: self.do_tarpit(self.tarpit) # send response self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) self.releaseStateInformation(stateReference) class c_NextCommandResponder(cmdrsp.NextCommandResponder, conpot_extension): def __init__(self, snmpEngine, snmpContext, databus_mediator, host, port): self.databus_mediator = databus_mediator self.tarpit = "0;0" self.threshold = "0;0" self.host = host self.port = port cmdrsp.NextCommandResponder.__init__(self, snmpEngine, snmpContext) conpot_extension.__init__(self) def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): (acFun, acCtx) = acInfo # rfc1905: 4.2.2.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars varBinds = v2c.apiPDU.getVarBinds(PDU) addr, snmp_version = self._getStateInfo(snmpEngine, stateReference) evasion_state = self.databus_mediator.update_evasion_table(addr) if self.check_evasive( evasion_state, self.threshold, addr, str(snmp_version) + " GetNext" ): return None rspVarBinds = None try: while 1: rspVarBinds = mgmtFun(varBinds, (acFun, acCtx)) # determine the correct response class and update the dynamic value table reference_class = rspVarBinds[0][1].__class__.__name__ # reference_value = rspVarBinds[0][1] response = self.databus_mediator.get_response( reference_class, tuple(rspVarBinds[0][0]) ) if response: rspModBinds = [(tuple(rspVarBinds[0][0]), response)] rspVarBinds = rspModBinds # apply tarpit delay if self.tarpit != 0: self.do_tarpit(self.tarpit) # send response try: self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) except error.StatusInformation: idx = sys.exc_info()[1]["idx"] varBinds[idx] = (rspVarBinds[idx][0], varBinds[idx][1]) else: break finally: sock = snmpEngine.transportDispatcher.socket self.log(snmp_version, "GetNext", addr, varBinds, rspVarBinds, sock) self.releaseStateInformation(stateReference) class c_BulkCommandResponder(cmdrsp.BulkCommandResponder, conpot_extension): def __init__(self, snmpEngine, snmpContext, databus_mediator, host, port): self.databus_mediator = databus_mediator self.tarpit = "0;0" self.threshold = "0;0" self.host = host self.port = port cmdrsp.BulkCommandResponder.__init__(self, snmpEngine, snmpContext) conpot_extension.__init__(self) def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): (acFun, acCtx) = acInfo nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) if nonRepeaters < 0: nonRepeaters = 0 maxRepetitions = v2c.apiBulkPDU.getMaxRepetitions(PDU) if maxRepetitions < 0: maxRepetitions = 0 reqVarBinds = v2c.apiPDU.getVarBinds(PDU) addr, snmp_version = self._getStateInfo(snmpEngine, stateReference) evasion_state = self.databus_mediator.update_evasion_table(addr) if self.check_evasive( evasion_state, self.threshold, addr, str(snmp_version) + " Bulk" ): return None raise Exception("This class is not converted to new architecture") try: N = min(int(nonRepeaters), len(reqVarBinds)) M = int(maxRepetitions) R = max(len(reqVarBinds) - N, 0) if R: M = min(M, self.maxVarBinds / R) debug.logger & debug.flagApp and debug.logger( "handleMgmtOperation: N %d, M %d, R %d" % (N, M, R) ) mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars if N: rspVarBinds = mgmtFun(reqVarBinds[:N], (acFun, acCtx)) else: rspVarBinds = [] varBinds = reqVarBinds[-R:] while M and R: rspVarBinds.extend(mgmtFun(varBinds, (acFun, acCtx))) varBinds = rspVarBinds[-R:] M = M - 1 finally: sock = snmpEngine.transportDispatcher.socket self.log(snmp_version, "Bulk", addr, varBinds, rspVarBinds, sock) # apply tarpit delay if self.tarpit != 0: self.do_tarpit(self.tarpit) # send response if len(rspVarBinds): self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) self.releaseStateInformation(stateReference) else: raise pysnmp.smi.error.SmiError() class c_SetCommandResponder(cmdrsp.SetCommandResponder, conpot_extension): def __init__(self, snmpEngine, snmpContext, databus_mediator, host, port): self.databus_mediator = databus_mediator self.tarpit = "0;0" self.threshold = "0;0" self.host = host self.port = port conpot_extension.__init__(self) cmdrsp.SetCommandResponder.__init__(self, snmpEngine, snmpContext) def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): (acFun, acCtx) = acInfo mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars varBinds = v2c.apiPDU.getVarBinds(PDU) addr, snmp_version = self._getStateInfo(snmpEngine, stateReference) evasion_state = self.databus_mediator.update_evasion_table(addr) if self.check_evasive( evasion_state, self.threshold, addr, str(snmp_version) + " Set" ): return None # rfc1905: 4.2.5.1-13 rspVarBinds = None # apply tarpit delay if self.tarpit != 0: self.do_tarpit(self.tarpit) try: rspVarBinds = mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx)) # generate response self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) self.releaseStateInformation(stateReference) oid = tuple(rspVarBinds[0][0]) self.databus_mediator.set_value(oid, rspVarBinds[0][1]) except ( pysnmp.smi.error.NoSuchObjectError, pysnmp.smi.error.NoSuchInstanceError, ): e = pysnmp.smi.error.NotWritableError() e.update(sys.exc_info()[1]) raise e finally: sock = snmpEngine.transportDispatcher.socket self.log(snmp_version, "Set", addr, varBinds, rspVarBinds, sock)
12,612
Python
.py
272
34.959559
109
0.606325
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,501
databus.py
mushorg_conpot/conpot/core/databus.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import inspect # this is needed because we use it in the xml. import random import gevent import gevent.event from lxml import etree logger = logging.getLogger(__name__) class Databus(object): def __init__(self): self._data = {} self._observer_map = {} self.initialized = gevent.event.Event() # the idea here is that we can store both values and functions in the key value store # functions could be used if a profile wants to simulate a sensor, or the function # could interface with a real sensor def get_value(self, key): logger.debug("DataBus: Get value from key: [%s]", key) assert key in self._data item = self._data[key] if getattr(item, "get_value", None): # this could potentially generate a context switch, but as long the called method # does not "callback" the databus we should be fine value = item.get_value() logger.debug("(K, V): (%s, %s)" % (key, value)) return value elif hasattr(item, "__call__"): return item() else: # guaranteed to not generate context switch logger.debug("(K, V): (%s, %s)" % (key, item)) return item def set_value(self, key, value): logger.debug("DataBus: Storing key: [%s] value: [%s]", key, value) self._data[key] = value # notify observers if key in self._observer_map: gevent.spawn(self.notify_observers, key) def notify_observers(self, key): for cb in self._observer_map[key]: cb(key) def observe_value(self, key, callback): assert hasattr(callback, "__call__") assert len( inspect.getfullargspec(callback)[0] ) # depreciated in py3.5, un-depreciated in py3.6 if key not in self._observer_map: self._observer_map[key] = [] self._observer_map[key].append(callback) def initialize(self, config_file): self.reset() assert self.initialized.isSet() is False logger.debug("Initializing databus using %s.", config_file) dom = etree.parse(config_file) entries = dom.xpath("//core/databus/key_value_mappings/*") for entry in entries: key = entry.attrib["name"] value = entry.xpath("./value/text()")[0].strip() value_type = str(entry.xpath("./value/@type")[0]) assert key not in self._data logging.debug("Initializing %s with %s as a %s.", key, value, value_type) if value_type == "value": self.set_value(key, eval(value)) elif value_type == "function": namespace, _classname = value.rsplit(".", 1) params = entry.xpath("./value/@param") module = __import__(namespace, fromlist=[_classname]) _class = getattr(module, _classname) if len(params) > 0: # eval param to list params = eval(params[0]) self.set_value(key, _class(*(tuple(params)))) else: self.set_value(key, _class()) else: raise Exception("Unknown value type: {0}".format(value_type)) self.initialized.set() def reset(self): logger.debug("Resetting databus.") # if the class has a stop method call it. for value in list(self._data.values()): if getattr(value, "stop", None): value.stop() self._data.clear() self._observer_map.clear() self.initialized.clear()
4,440
Python
.py
102
34.696078
93
0.611381
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,502
virtual_fs.py
mushorg_conpot/conpot/core/virtual_fs.py
# Copyright (C) 2018 Abhinav Saxena <xandfury@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import os import sys import fs import conpot from fs import open_fs, subfs from conpot.core.filesystem import AbstractFS, SubAbstractFS logger = logging.getLogger(__name__) class VirtualFS(object): """ Conpot's virtual file system. Based on Pyfilesystem2, it would allow us to have arbitrary file uploads while sand boxing them for later analysis. This is how it should look like: [_conpot_vfs] | |-- data_fs (persistent) | |-- ftp/uploads | `-- misc. | `-- protocol_fs (temporary, refreshed at startup) |-- common |-- telnet |-- http |-- snmp `-- ftp etc. :param data_fs_path: Path for storing data_fs. A dictionary with attribute name _protocol_vfs stores all the fs folders made by all the individual protocols. :type data_fs_path: fs.open_fs """ def __init__(self, data_fs_path=None): self._conpot_vfs = ( dict() ) # dictionary to keep all the protocol vfs instances, maintain easy access for # individual mounted protocols with paths if data_fs_path is None: try: self.data_fs = open_fs( os.path.join( "/".join(conpot.__file__.split("/")[:-1]), "tests", "data", "data_temp_fs", ) ) except fs.errors.FSError: logger.exception( "Unable to create persistent storage for Conpot. Exiting" ) sys.exit(3) else: try: assert data_fs_path and isinstance(data_fs_path, str) self.data_fs = open_fs( data_fs_path ) # Specify the place where you would place the uploads except AssertionError: logger.exception( "Incorrect FS url specified. Please check documentation for more details." ) sys.exit(3) except fs.errors.CreateFailed: logger.exception("Unexpected error occurred while creating Conpot FS.") sys.exit(3) self.protocol_fs = None def initialize_vfs(self, fs_path=None, data_fs_path=None, temp_dir=None): if data_fs_path is not None: logger.info( "Opening path {} for persistent storage of files.".format(data_fs_path) ) self.__init__(data_fs_path=data_fs_path) if fs_path is None: fs_path = "tar://" + os.path.join( "/".join(conpot.__file__.split("/")[:-1]), "data.tar" ) logger.warning("Using default FS path. {}".format(fs_path)) self.protocol_fs = AbstractFS(src_path=fs_path, temp_dir=temp_dir) def add_protocol( self, protocol_name: str, data_fs_subdir: str, vfs_dst_path: str, src_path=None, owner_uid=0, group_gid=0, perms=0o755, ) -> (SubAbstractFS, subfs.SubFS): """ Method that would be used by protocols to initialize vfs. May be called by each protocol individually. This creates a chroot jail sub file system env which makes easier handling. It also creates a data_fs sub file system for managing protocol specific uploads. :param protocol_name: name of the protocol for which VFS is being created. :param data_fs_subdir: sub-folder name within data_fs that would be storing the uploads for later analysis :param vfs_dst_path: protocol specific sub-folder path in the fs. :param src_path: Source from where the files are to copied. :param owner_uid: UID of a registered user. This is the default owner in the sub file system :param group_gid: GID of a existing group. :param perms: Default permissions of the sub file system. :return: fs object **Note:** The owner_uid and group_gid must be already registered with the fs. Otherwise an exception would be raised. """ assert isinstance(protocol_name, str) and protocol_name assert isinstance(data_fs_subdir, str) and data_fs_subdir assert isinstance(vfs_dst_path, str) and vfs_dst_path if src_path: assert isinstance(src_path, str) if not os.path.isdir(src_path): logger.error("Protocol directory is not a valid directory.") sys.exit(3) logger.info( "Creating persistent data store for protocol: {}".format(protocol_name) ) # create a sub directory for persistent storage. if self.data_fs.isdir(data_fs_subdir): sub_data_fs = self.data_fs.opendir(path=data_fs_subdir) else: sub_data_fs = self.data_fs.makedir(path=data_fs_subdir) if protocol_name not in self._conpot_vfs.keys(): sub_protocol_fs = self.protocol_fs.mount_fs( vfs_dst_path, src_path, owner_uid, group_gid, perms ) self._conpot_vfs[protocol_name] = (sub_protocol_fs, sub_data_fs) return self._conpot_vfs[protocol_name] def close(self, force=False): """ Close the filesystem properly. Better and more graceful than __del__ :param force: Force close. This would close the AbstractFS instance - without close closing data_fs File Systems """ if self._conpot_vfs and (not force): for _fs in self._conpot_vfs.keys(): try: # First let us close all the data_fs instances. self._conpot_vfs[_fs][1].close() # Let us close the protocol_fs sub dirs for that protocol self._conpot_vfs[_fs][0].close() except fs.errors.FSError: logger.exception("Error occurred while closing FS {}".format(_fs)) del self._conpot_vfs[_fs][0] self.protocol_fs.close() self.protocol_fs.clean()
7,179
Python
.py
155
34.341935
120
0.582264
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,503
filesystem.py
mushorg_conpot/conpot/core/filesystem.py
# Copyright (C) 2018 Abhinav Saxena <xandfury@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import time import stat import tempfile import logging import contextlib import shutil import fs from stat import filemode from datetime import datetime from os import F_OK, R_OK, W_OK from typing import Optional, Union, Text, Any, List from fs import open_fs, mirror, errors, subfs, base from fs.mode import Mode from fs.wrapfs import WrapFS from fs.permissions import Permissions from fs.osfs import Info from types import FunctionType from conpot.core.fs_utils import ( _custom_conpot_file, SubAbstractFS, copy_files, FilesystemError, ) from conpot.core.fs_utils import FSOperationNotPermitted logger = logging.getLogger(__name__) months_map = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec", } # --------------------------------------------------- # Regarding Permissions: # --------------------------------------------------- # For directories: # - Read bit = You can read the names on the list. # - Write bit = You can {add,rename,delete} names on the list IF the execute bit is set too. # - Execute bit = You can make this directory your working directory. # --------------------------------------------------- # For files: # - Read bit = Grants the capability to read, i.e., view the contents of the file. # - Write bit = Grants the capability to modify, or remove the content of the file. # - Execute bit = User with execute permissions can run a file as a program. # --------------------------------------------------- class AbstractFS(WrapFS): """ AbstractFS distinguishes between "real" filesystem paths and "virtual" ftp paths emulating a UNIX chroot jail where the user can not escape its home directory (example: real "/home/user" path will be seen as "/" by the client) This class exposes common fs wrappers around all os.* calls involving operations against the filesystem like creating files or removing directories (such as listdir etc.) *Implementation Note:* When doing I/O - Always with the check_access and set_access context managers for safe operations. """ def __init__( self, src_path: str, create_mode: int = 0o777, # Default file system permissions. temp_dir: Union[str, None] = None, identifier: Optional[str] = "__conpot__", auto_clean: Optional[bool] = True, ignore_clean_errors: Optional[bool] = True, ) -> None: self._cwd = self.getcwd() # keep track of the current working directory self._cache = {} # Storing all cache of the file system self.identifier = identifier.replace("/", "-") self._auto_clean = auto_clean self._ignore_clean_errors = ignore_clean_errors self.temp_dir = temp_dir self._cleaned = False self.built_cache = False # Create our file system self._temp_dir = tempfile.mkdtemp( prefix=(self.identifier or "ConpotTempFS"), dir=self.temp_dir ) # open various filesystems that would be used by Conpot try: self.vfs = open_fs(self._temp_dir) super(AbstractFS, self).__init__(self.vfs) except fs.errors.FSError as fs_err: logger.exception("File System exception occurred! {}".format(fs_err)) # Copy all files from src_path into our file system logger.info( "Initializing Virtual File System at {}. Source specified : {}\n Please wait while the " "system copies all specified files".format(self._temp_dir, src_path) ) self.utime = self.settimes # utime maps to settimes # keep records related to users and groups self.default_uid = 0 self.default_gid = 0 self.default_perms = create_mode self._users = {0: {"user": "root"}} self._grps = {0: {"group": "root"}} # simple dictionary linking users to groups -> self._user_grps = {0: {0}} # --> gid: set(uids) self._initialize_fs(src_path=src_path) # fixme: kind of hack-ish. Find the correct way of doing this. self._wrap_fs._meta["supports_rename"] = False def norm_path(self, path): path = "/" if path == "." else path try: _path = ( self.validatepath(self._cwd + path) if self._cwd not in path else self.validatepath(path) ) return _path except fs.errors.FSError: logger.debug("Could not validate path: {}".format(path)) raise FilesystemError("Could not validate path: {}".format(path)) def _initialize_fs(self, src_path: str) -> None: """ Copies all data into Conpot's created fs folder and builds up the cache. :param src_path: FS URLS """ # copy all contents from the source path the filesystem. src_fs = open_fs(src_path) logger.debug( "Building up file system: copying contents from the source path {}".format( src_path ) ) with src_fs.lock(): mirror.mirror(src_fs=src_fs, dst_fs=self.vfs) self._cache.update( { path: info for path, info in self.walk.info( namespaces=["basic", "access", "details", "stat"] ) } ) self._cache["/"] = self._wrap_fs.getinfo( "/", namespaces=["basic", "access", "details", "stat", "link"] ) self.chown("/", self.default_uid, self.default_gid, recursive=True) self.chmod("/", self.default_perms, recursive=True) self.built_cache = ( True # FS has been built. Now all info must be accessed from cache. ) src_fs.close() del src_fs def __str__(self): return "<Conpot AbstractFS '{}'>".format(self._temp_dir) __repr__ = __str__ @property def users(self): return self._users @property def groups(self): return self._grps @property def user_groups(self): """gid: {set of uid of users.}""" return self._user_grps def getmeta(self, namespace="standard"): self.check() meta = self.delegate_fs().getmeta(namespace=namespace) meta["supports_rename"] = False return meta # ------- context managers for easier handling of fs @contextlib.contextmanager def check_access(self, path=None, user=None, perms=None): """ Checks whether the current user has permissions to do a specific operation. Raises FSOperationNotPermitted exception in case permissions are not satisfied. Handy utility to check whether the user with uid provided has permissions specified. Examples: >>> import conpot.core as conpot_core >>> _vfs, _ = conpot_core.get_vfs('ftp') >>> with _vfs.check_access(path='/', user=13, perms='rwx'): >>> _vfs.listdir('/') >>> with _vfs.check_access(path='/', user=45, perms='w'): >>> with _vfs.open('/test', mode='wb') as _file: >>> _file.write(b'Hello World!') """ if not self.access(path=path, name_or_id=user, required_perms=perms): raise FSOperationNotPermitted( "User {} does not have required permission to file/path: {}".format( user, path ) ) else: logger.debug( "File/Dir {} has the requested params : {}".format(path, (user, perms)) ) self.setinfo(path, {}) yield if self.vfs.isfile(path): logger.debug("yield file: {} after requested access.".format(path)) elif self.vfs.isdir(path): logger.debug("yield dir: {} after requested access.".format(path)) else: logger.debug( "yield unknown type: {} after requested access.".format(path) ) # ----------------------------------------------------------- # Custom "setter" methods overwriting behaviour FS library methods # We need to update our cache in such cases. # ----------------------------------------------------------- def setinfo(self, path, info): """ Higher level function to directly change values in the file system. Dictionary specified here changes cache values. :param path: path of the file that is to be changed :param info: Raw Info object. Please check pyfilesystem2's docs for more info. """ assert path and isinstance(path, str) path = self.norm_path(path) if "lstat" not in info: try: if "details" in info: details = info["details"] if "accessed" in details or "modified" in details: return self._wrap_fs.setinfo(path, info) finally: try: assert self._cache[path] except (AssertionError, KeyError): # This is the first time we have seen this file. Let us create this entry. logger.debug("Creating cache for file/directory : {}".format(path)) self._cache[path] = self._wrap_fs.getinfo( path, namespaces=["basic", "access", "details", "stat", "link"] ) # update the 'accessed' and 'modified' time. self.settimes(path) if "access" in info: access = info["access"] if "permissions" in access: self._cache[path].raw["access"]["permissions"] = access[ "permissions" ] self._cache[path].raw["details"]["metadata_changed"] = ( fs.time.datetime_to_epoch(datetime.now()) ) if "user" in access or "uid" in access: try: if "user" in access or ( "user" in access and "uid" in access ): self._cache[path].raw["access"]["user"] = access["user"] [_uid] = [ key for key, value in self._users.items() if value == {"user": access["user"]} ] self._cache[path].raw["access"]["uid"] = _uid self._cache[path].raw["details"]["metadata_changed"] = ( fs.time.datetime_to_epoch(datetime.now()) ) else: # Must be 'uid' that is available. _uid = int(access["uid"]) # type: ignore self._cache[path].raw["access"]["uid"] = _uid self._cache[path].raw["access"]["user"] = self._users[ _uid ]["user"] self._cache[path].raw["details"]["metadata_changed"] = ( fs.time.datetime_to_epoch(datetime.now()) ) except (TypeError, AssertionError, KeyError): raise if "group" in access or "gid" in access: try: if "group" in access or ( "group" in access and "gid" in access ): self._cache[path].raw["access"]["group"] = access[ "group" ] [_gid] = [ key for key, value in self._grps.items() if value == {"group": access["group"]} ] self._cache[path].raw["access"]["gid"] = _gid self._cache[path].raw["details"]["metadata_changed"] = ( fs.time.datetime_to_epoch(datetime.now()) ) else: # Must be 'gid' that is available. _gid = int(access["gid"]) # type: ignore self._cache[path].raw["access"]["gid"] = _gid self._cache[path].raw["access"]["group"] = self._grps[ _gid ]["group"] self._cache[path].raw["details"]["metadata_changed"] = ( fs.time.datetime_to_epoch(datetime.now()) ) except (TypeError, AssertionError, KeyError): raise else: raise FilesystemError("lstat is not currently supported!") def makedir( self, path, # type: Text permissions=None, # type: Optional[int] recreate=True, # type: bool ): # make a directory in the file system. Also, update the cache about the directory. _path = self.norm_path(path) # we always want to overwrite a directory if it already exists. recreate = True if recreate is False else recreate perms = permissions fs_err = None try: super(AbstractFS, self).makedir(_path, permissions=None, recreate=recreate) except fs.errors.FSError as err: fs_err = err finally: if not fs_err: dir_perms = perms if perms else self.default_perms dir_cache = { "access": { "permissions": Permissions.create(dir_perms), "uid": self.default_uid, "gid": self.default_gid, } } logger.debug("Created directory {}".format(_path)) self.setinfo(_path, info=dir_cache) else: raise fs_err def removedir(self, path, rf=True): """Remove a directory from the file system. :param path: directory path :param rf: remove directory recursively and forcefully. This removes directory even if there is any data in it. If set to False, an exception would be raised """ # removing a directory and finally block would clear the local cache. _path = self.norm_path(path) fs_err = None try: super(AbstractFS, self).removedir(_path) except fs.errors.FSError as err: fs_err = err finally: if not fs_err: rm_dir = self._cache.pop(_path) logger.debug("Removed directory {}".format(rm_dir)) else: if isinstance(fs_err, fs.errors.DirectoryNotEmpty) and rf is True: # delete the contents for the directory recursively self._wrap_fs.removetree(_path) # delete the all the _cache files in the directory. _files = [i for i in self._cache.keys() if _path in i] for _f in _files: file = self._cache.pop(_f) logger.debug("Removing file : {}".format(repr(file))) else: raise fs_err def remove(self, path): """Remove a file from the file system.""" _path = self.norm_path(path) fs_err = None try: super(AbstractFS, self).remove(_path) except fs.errors.FSError as err: fs_err = err finally: if not fs_err: rm_file = self._cache.pop(_path) logger.debug("Removed file {}".format(rm_file)) else: raise fs_err def openbin(self, path, mode="r", buffering=-1, **options): """ Open a file in the ConpotFS in binary mode. """ logger.debug("Opening file {} with mode {}".format(path, mode)) _path = self.norm_path(path) _bin_mode = Mode(mode).to_platform_bin() _bin_mode = _bin_mode.replace("t", "") if "t" in _bin_mode else _bin_mode _parent_fs = self.delegate_fs() self.check() binary_file = _custom_conpot_file( file_system=self, parent_fs=_parent_fs, path=_path, mode=_bin_mode, encoding=None, ) return binary_file def open( self, path, # type: Text mode="r", # type: Text buffering=-1, # type: int encoding=None, # type: Optional[Text] newline="", # type: Text line_buffering=False, # type: bool **options # type: Any ): _open_mode = Mode(mode) base.validate_open_mode(mode) self.check() _path = self.norm_path(path) _parent_fs = self.delegate_fs() _encoding = encoding or "utf-8" file = _custom_conpot_file( file_system=self, parent_fs=_parent_fs, path=_path, mode=_open_mode.to_platform(), buffering=buffering, encoding=encoding, newline=newline, line_buffering=line_buffering, ) return file def setbinfile(self, path, file): with self.openbin(path, "wb") as dst_file: copy_files(file, dst_file) self.setinfo(path, {}) def move(self, src_path, dst_path, overwrite=False): if self.getinfo(src_path).is_dir: raise fs.errors.FileExpected(src_path) with self.openbin(src_path, "rb") as read_file: with self.openbin(dst_path, "wb") as dst_file: copy_files(read_file, dst_file) self.setinfo(src_path, {}) self.setinfo(dst_path, {}) self.remove(src_path) def copy(self, src_path, dst_path, overwrite=False): if self.getinfo(src_path).is_dir: raise fs.errors.FileExpected(src_path) with self.openbin(src_path, "rb") as read_file: with self.openbin(dst_path, "wb") as dst_file: copy_files(read_file, dst_file) self.setinfo(src_path, {}) self.setinfo(dst_path, {}) # ----------------------------------------------------------- # Custom "getter" methods overwriting behaviour FS library methods # Data is retrieved from the cached file-system. # ----------------------------------------------------------- def opendir(self, path, factory=SubAbstractFS): return super(AbstractFS, self).opendir(path, factory=factory) def settimes(self, path, accessed=None, modified=None): if accessed or modified: self.delegate_fs().settimes(path, accessed, modified) self._cache[path].raw["details"]["accessed"] = fs.time.datetime_to_epoch( super(AbstractFS, self).getinfo(path, namespaces=["details"]).accessed ) self._cache[path].raw["details"]["modified"] = fs.time.datetime_to_epoch( super(AbstractFS, self).getinfo(path, namespaces=["details"]).modified ) def getinfo(self, path: str, get_actual: bool = False, namespaces=None): if get_actual or (not self.built_cache): return self._wrap_fs.getinfo(path, namespaces) else: try: # ensure that the path starts with '/' if path[0] != "/": path = "/" + path info = {"basic": self._cache[path].raw["basic"]} if namespaces is not None: if "details" in namespaces: info["details"] = self._cache[path].raw["details"] if "stat" in namespaces: stat_cache = { "st_uid": self._cache[path].raw["access"]["uid"], "st_gid": self._cache[path].raw["access"]["gid"], "st_atime": self._cache[path].raw["details"]["accessed"], "st_mtime": self._cache[path].raw["details"]["modified"], # TODO: Fix these to appropriate values "st_mtime_ns": None, "st_ctime_ns": None, "st_ctime": None, } if isinstance( self._cache[path].raw["access"]["permissions"], list ): stat_cache["st_mode"] = Permissions( self._cache[path].raw["access"]["permissions"] ).mode else: stat_cache["st_mode"] = ( self._cache[path].raw["access"]["permissions"].mode ) self._cache[path].raw["stat"].update(stat_cache) info["stat"] = self._cache[path].raw["stat"] # Note that we won't be keeping tabs on 'lstat' if "lstat" in namespaces: info["lstat"] = self._cache[path].raw["lstat"] info["lstat"] = self._cache[path].raw["lstat"] if "link" in namespaces: info["link"] = self._cache[path].raw["link"] if "access" in namespaces: info["access"] = self._cache[path].raw["access"] return Info(info) except KeyError: raise FilesystemError def listdir(self, path): logger.debug("Listing contents from directory: {}".format(self.norm_path(path))) self.setinfo(self.norm_path(path), {}) return super(AbstractFS, self).listdir(self.norm_path(path)) def getfile(self, path, file, chunk_size=None, **options): # check where there exists a copy in the cache if ( self.exists(self.norm_path(path)) and self.norm_path(path) in self._cache.keys() ): self.setinfo(self.norm_path(path), {}) return self._wrap_fs.getfile( self.norm_path(path), file, chunk_size, **options ) else: raise FilesystemError("Can't get. File does not exist!") def __del__(self): self._wrap_fs.close() if self._auto_clean: self.clean() # ----------------------------------------------------------- # Methods defined for our needs. # ----------------------------------------------------------- def create_jail(self, path): """Returns chroot jail sub system for a path""" logger.debug("Creating jail for path: {}".format(path)) return self.opendir(path) def getcwd(self): return "/" def take_snapshot(self): """Take snapshot of entire filesystem. :rtype: dict """ return { "date-time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "snapshot-data": self._cache, } def register_user(self, name: str, uid: int) -> None: """Store all user related data for the file system.""" assert name and isinstance(name, str) self._users[uid] = {"user": name} # let us check for duplicate usernames/group names if len(set([v["user"] for k, v in self._users.items()])) != len( self._users.keys() ): _uname = self._users.pop(uid)["user"] raise FilesystemError( "Can't add users with duplicate uname: {}.".format(_uname) ) def create_group(self, name: str, gid: int) -> None: """ Store all group related data for the file system. :param name: Name of the group :param gid: gid of the group """ assert name and isinstance(name, str) self._grps[gid] = {"group": name} if len(set([v["group"] for k, v in self._grps.items()])) != len( self._grps.keys() ): _gname = self._grps.pop(gid) raise FilesystemError( "Can't create groups with duplicate names: {}.".format(_gname) ) def add_users_to_group(self, gid: int, uids: List) -> None: """Add list of users to an existing group :param gid: Group id of the group. :param uids: List of registers users that belong to this group """ try: assert gid in self._grps.keys() for i in uids: if i not in self._users.keys(): raise AssertionError _uids = set(uids) if gid in self._user_grps.keys(): self._user_grps[gid] += _uids else: self._user_grps[gid] = _uids except AssertionError: raise FilesystemError( "uid/gid does not exist in the file system. Please register it via create_group/" "register_user method." ) def chown( self, fs_path: str, uid: int, gid: int, recursive: Optional[bool] = False ) -> None: """Change the owner of a specified file. Wrapper for os.chown :param fs_path: path or directory in the VFS where chown would be executed. :param uid: The `uid` of the user. **User must be a registered user on the filesystem or an exception would be thrown. :param gid: The `gid` of the group **Group must be a registered group on the filesystem or an exception would be thrown. :param recursive: If the given path is directory, then setting the recursive option to true would walk down the tree and recursive change permissions in the cache. ** `fs_path` needs to be the absolute path w.r.t to the vfs. If you are in a sub file system, please use `subvfs.getcwd()` to get the current directory. ** """ path = self.norm_path(fs_path) try: assert isinstance(uid, int) and isinstance(gid, int) except AssertionError: logger.exception("Integers expected got {} - {}".format(uid, gid)) if self.isdir(path) or self.isfile(path): assert self._grps[gid] and self._users[uid] chown_cache = { "access": { "user": self._users[uid]["user"], "uid": self._users[uid], "group": self._grps[gid]["group"], "gid": self._grps[gid], } } if self.isdir(path) and recursive: if self.norm_path(path) != "/": self.setinfo(path, chown_cache) sub_dir = self.opendir(path) for _path, _ in sub_dir.walk.info(): assert self._cache[self.norm_path(path + _path)] self.setinfo(path + _path, chown_cache) sub_dir.close() else: self.setinfo(path, chown_cache) else: # TODO: map this to the actual output of os.chown raise FilesystemError("File not found for chown") def clean(self): """Clean (delete) temporary files created by this filesystem.""" if self._cleaned: return try: logger.info( "Shutting down File System. Cleaning directories at {}".format( self._temp_dir ) ) shutil.rmtree(self._temp_dir) except Exception as error: if not self._ignore_clean_errors: raise errors.OperationFailed( msg="failed to remove temporary directory", exc=error ) self._cleaned = True @property def root(self): """The root directory - where the filesystem is stored""" return self._temp_dir def stat(self, path): """Perform a stat() system call on the given path. :param path: (str) must be protocol relative path """ assert path, isinstance(path, str) self.setinfo(self.norm_path(path), {}) return self.getinfo(path, namespaces=["stat"]).raw["stat"] def readlink(self, path): """Perform a readlink() system call. Return a string representing the path to which a symbolic link points. :param path: (str) must be protocol relative path """ assert path, isinstance(path, str) self.setinfo(self.norm_path(path), {}) return self.getinfo(path, get_actual=True, namespaces=["link"]).raw["link"][ "target" ] def format_list(self, basedir, listing): """ Return an iterator object that yields the entries of given directory emulating the "/bin/ls -lA" UNIX command output. This is how output should appear: -rw-rw-rw- 1 owner group 7045120 Sep 02 3:47 music.mp3 drwxrwxrwx 1 owner group 0 Aug 31 18:50 e-books -rw-rw-rw- 1 owner group 380 Sep 02 3:40 module.py :param basedir: (str) must be protocol relative path :param listing: (list) list of files to needed for output. """ assert isinstance(basedir, str), basedir basedir += "/" if basedir[-1:] != "/" else basedir now = time.time() for basename in listing: file = self.norm_path( basedir + basename ) # for e.g. basedir = '/' and basename = test.png. # So file is '/test.png' try: st = self.stat(file) except (fs.errors.FSError, FilesystemError): raise permission = filemode(Permissions.create(st["st_mode"]).mode) if self.isdir(file): permission = permission.replace("?", "d") elif self.isfile(file): permission = permission.replace("?", "-") elif self.islink(file): permission = permission.replace("?", "l") nlinks = st["st_nlink"] size = st["st_size"] # file-size uname = self.getinfo(path=file, namespaces=["access"]).user # |-> pwd.getpwuid(st['st_uid']).pw_name would fetch the user_name of the actual owner of these files. gname = self.getinfo(path=file, namespaces=["access"]).group # |-> grp.getgrgid(st['st_gid']).gr_name would fetch the user_name of the actual of these files. mtime = time.gmtime( fs.time.datetime_to_epoch( self.getinfo(file, namespaces=["details"]).modified ) ) if (now - st["st_mtime"]) > (180 * 24 * 60 * 60): fmtstr = "%d %Y" else: fmtstr = "%d %H:%M" mtimestr = "%s %s" % ( months_map[mtime.tm_mon], time.strftime(fmtstr, mtime), ) if (st["st_mode"] & 61440) == stat.S_IFLNK: # if the file is a symlink, resolve it, e.g. "symlink -> realfile" basename = basename + " -> " + self.readlink(file) # formatting is matched with proftpd ls output line = "%s %3s %-8s %-8s %8s %s %s\r\n" % ( permission, nlinks, uname, gname, size, mtimestr, basename, ) yield line def getmtime(self, path): """Return the last modified time as a number of seconds since the epoch.""" self.setinfo(self.norm_path(path), {}) return self.getinfo(path, namespaces=["details"]).modified # FIXME: refactor to os.access. Mode is missing from the params def access( self, path: str, name_or_id: Union[int, str] = None, required_perms: str = None ): """ Returns bool w.r.t the a user/group has permissions to read/write/execute a file. This is a wrapper around os.access. But it would accept name or id instead of of just ids. Also it can accept required permissions in the form of strings rather than os.F_OK, os.R_OK, os.W_OK etc. *Implementation Note*: First we would check whether the current user has the required permissions. If not, then we check the group to which this user belongs to. Finally if the user's group also does not meet the perms we check for other permissions. """ try: _path = self.norm_path(path) _perms = self.getinfo(_path, namespaces=["access"]).permissions _uid = self.getinfo(_path, namespaces=["access"]).uid _gid = self.getinfo(_path, namespaces=["access"]).gid if isinstance(required_perms, int): if required_perms == F_OK: return True elif required_perms == R_OK: required_perms = "r" elif required_perms == W_OK: required_perms = "w" # first we need to find the uid - in case username is provided instead of uid. if isinstance(name_or_id, str): # must be username or group name # fetch the uid/gid of that uname/gname [_id] = [k for k, v in self._users.items() if v == {"user": name_or_id}] else: _id = name_or_id # find the gid of this user. _grp_id = None # FIXME: The above operation can cause incorrect results if one user belongs to more than one group. for key, values in self._user_grps.items(): if _id in values: _grp_id = key if _id is not None: if _id == _uid: # provided id is the owner return all([_perms.check("u_" + i) for i in list(required_perms)]) elif _grp_id and (_grp_id == _gid): # provided id is not the owner but belongs to that grp. # That means we would check it's group permissions. return all([_perms.check("g_" + i) for i in list(required_perms)]) else: # id not equal to either in uid/gid # check other permissions return all([_perms.check("o_" + i) for i in list(required_perms)]) except (ValueError, AssertionError, KeyError, fs.errors.FSError) as err: logger.info("Exception has occurred while doing fs.access: {}".format(err)) logger.info("Returning False to avoid conpot crash") return False def get_permissions(self, path): """Get permissions for a particular user on a particular file/directory in 'rwxrx---' format""" _path = self.norm_path(path) self.setinfo(self.norm_path(path), {}) _perms = self.getinfo(_path, namespaces=["access"]).permissions return _perms.as_str() def chmod(self, path: str, mode: oct, recursive: bool = False) -> None: """Change file/directory mode. :param path: Path to be modified. :param mode: Operating-system mode bitfield. Must be in octal's form. Eg: chmod with (mode=0o755) = Permissions(user='rwx', group='rx', other='rx') :param recursive: If the path is directory, setting recursive to true would change permissions to sub folders and contained files. :type recursive: bool """ assert isinstance(mode, str) or isinstance(mode, int) if isinstance(mode, str): # convert mode to octal mode = int(mode, 8) chmod_cache_info = {"access": {"permissions": Permissions.create(mode)}} if self.isdir(path) and recursive: if path != "/": self.setinfo(path, chmod_cache_info) # create a walker sub_dir = self.opendir(path) for _path, _ in sub_dir.walk.info(): self.setinfo(path + _path, chmod_cache_info) sub_dir.close() else: self.setinfo(path, chmod_cache_info) def mount_fs( self, dst_path: str, fs_url: str = None, owner_uid: Optional[int] = 0, group_gid: Optional[int] = 0, perms: Optional[Union[Permissions, int]] = 0o755, ) -> subfs.SubFS: """ To be called to mount individual filesystems. :param fs_url: Location/URL for the file system that is to be mounted. :param dst_path: Place in the Conpot's file system where the files would be placed. This should be relative to FS root. :param owner_uid: The owner `user` **UID** of the directory and the sub directory. Default is root/ :param group_gid: The group 'group` to which the directory beings. Defaults to root. :param perms: Permission UMASK """ path = self.norm_path(dst_path) if self.exists(path) and self.isdir(path): if not fs_url: new_dir = self.create_jail(path) else: temp_fs = open_fs(fs_url=fs_url) with temp_fs.lock(): new_dir = self.opendir( self.norm_path(dst_path), factory=SubAbstractFS ) mirror.mirror(src_fs=temp_fs, dst_fs=new_dir) self._cache.update( { path: info for path, info in self.walk.info( namespaces=["basic", "access", "details", "stat"] ) } ) del temp_fs # delete the instance since no longer required new_dir.default_uid, new_dir.default_gid = owner_uid, group_gid new_dir.chown("/", uid=owner_uid, gid=group_gid, recursive=True) new_dir.chmod("/", mode=perms, recursive=True) return new_dir else: raise fs.errors.DirectoryExpected("{} path does not exist".format(path)) def __getattribute__(self, attr): # Restrict access to methods that are implemented in AbstractFS class - Calling methods from base class may # not be safe to use. # FIXME: Need to fix these for only allow methods that are defined here. if not WrapFS: return method_list = [x for x, y in WrapFS.__dict__.items() if type(y) == FunctionType] if attr in method_list: if attr in super(AbstractFS, self).__getattribute__( "__dict__" ).keys() or attr not in ["match", "settext"]: # These methods have been overwritten and are safe to use. try: return super(AbstractFS, self).__getattribute__(attr) except KeyError as ke: raise FilesystemError("Invalid Path : {}".format(ke)) else: raise NotImplementedError( "The method requested is not supported by Conpot's VFS" ) else: try: return super(AbstractFS, self).__getattribute__(attr) except KeyError as ke: raise FilesystemError("Invalid Path : {}".format(ke))
40,960
Python
.py
895
32.606704
120
0.526286
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,504
protocol_wrapper.py
mushorg_conpot/conpot/core/protocol_wrapper.py
# Copyright (C) 2018 Abhinav Saxena <xandfury@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from conpot.core import get_interface from datetime import datetime core_interface = get_interface() def conpot_protocol(cls): class Wrapper(object): def __init__(self, *args, **kwargs): self.wrapped = cls(*args, **kwargs) self.cls = cls if self.cls.__name__ not in "Proxy": if self.cls not in core_interface.protocols: core_interface.protocols[self.cls] = [] core_interface.protocols[self.cls].append(self.wrapped) self.__class__.__name__ = self.cls.__name__ def __getattr__(self, name): if name == "handle": # assuming that handle function from a class is only called when a client tries to connect with an # enabled protocol, update the last_active (last_attacked attribute) # FIXME: No handle function in HTTPServer core_interface.last_active = datetime.now().strftime( "%b %d %Y - %H:%M:%S" ) return self.wrapped.__getattribute__(name) def __repr__(self): return self.wrapped.__repr__() __doc__ = cls.__doc__ __module__ = cls.__module__ return Wrapper
2,018
Python
.py
43
39.093023
114
0.644784
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,505
attack_session.py
mushorg_conpot/conpot/core/attack_session.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import uuid from datetime import datetime logger = logging.getLogger(__name__) # one instance per connection class AttackSession(object): def __init__( self, protocol, source_ip, source_port, destination_ip, destination_port, log_queue, ): self.log_queue = log_queue self.id = uuid.uuid4() logger.info("New %s session from %s (%s)", protocol, source_ip, self.id) self.protocol = protocol self.source_ip = source_ip self.source_port = source_port self.destination_ip = destination_ip self.destination_port = destination_port self.timestamp = datetime.utcnow() self.public_ip = None self.data = dict() self._ended = False def _dump_data(self, data): return { "id": self.id, "remote": (self.source_ip, self.source_port), "src_ip": self.source_ip, "src_port": self.source_port, "local": (self.destination_ip, self.destination_port), "dst_ip": self.destination_ip, "dst_port": self.destination_port, "data_type": self.protocol, "timestamp": self.timestamp, "public_ip": self.public_ip, "data": data, } def add_event(self, event_data): sec_elapsed = (datetime.utcnow() - self.timestamp).total_seconds() elapse_ms = int(sec_elapsed * 1000) while elapse_ms in self.data: elapse_ms += 1 self.data[elapse_ms] = event_data # TODO: We should only log the session when it is finished self.log_queue.put(self._dump_data(event_data)) def dump(self): return self._dump_data(self.data) def set_ended(self): self._ended = True
2,606
Python
.py
69
30.811594
80
0.645289
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,506
session_manager.py
mushorg_conpot/conpot/core/session_manager.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from gevent.queue import Queue from conpot.core.attack_session import AttackSession # one instance only class SessionManager: def __init__(self): self._sessions = [] self.log_queue = Queue() def _find_sessions(self, protocol, source_ip): for session in self._sessions: if session.protocol == protocol: if session.source_ip == source_ip: return session return None def get_session( self, protocol, source_ip, source_port, destination_ip=None, destination_port=None, ): # around here we would inject dependencies into the attack session attack_session = self._find_sessions(protocol, source_ip) if not attack_session: attack_session = AttackSession( protocol, source_ip, source_port, destination_ip, destination_port, self.log_queue, ) self._sessions.append(attack_session) return attack_session def purge_sessions(self): # there is no native purge/clear mechanism for gevent queues, so... self.log_queue = Queue()
2,019
Python
.py
53
30.773585
75
0.661052
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,507
__init__.py
mushorg_conpot/conpot/core/__init__.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from typing import Tuple, Union, Optional from .databus import Databus from .internal_interface import Interface from .session_manager import SessionManager from .virtual_fs import VirtualFS, AbstractFS databus = Databus() sessionManager = SessionManager() virtualFS = VirtualFS() core_interface = Interface() # databus related -- def get_sessionManager(): return sessionManager def get_databus(): return databus def get_session(*args, **kwargs): return sessionManager.get_session(*args, **kwargs) # file-system related -- def initialize_vfs(fs_path=None, data_fs_path=None, temp_dir=None): return virtualFS.initialize_vfs( fs_path=fs_path, data_fs_path=data_fs_path, temp_dir=temp_dir ) def add_protocol( protocol_name: str, data_fs_subdir: str, vfs_dst_path: str, src_path=None, owner_uid: Optional[int] = 0, group_gid: Optional[int] = 0, perms: Optional[oct] = 0o755, ) -> Tuple: return virtualFS.add_protocol( protocol_name, data_fs_subdir, vfs_dst_path, src_path, owner_uid, group_gid, perms, ) def get_vfs(protocol_name: Optional[str] = None) -> Union[AbstractFS, Tuple]: """ Get the File System. :param protocol_name: Name of the protocol to be fetched """ if protocol_name: return virtualFS._conpot_vfs[protocol_name] else: return virtualFS.protocol_fs def close_fs(): """Close the file system. Remove all the temp files.""" virtualFS.close() # internal-interface related -- def get_interface(): return globals()["core_interface"]
2,410
Python
.py
70
30.628571
77
0.722366
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,508
internal_interface.py
mushorg_conpot/conpot/core/internal_interface.py
# Copyright (C) 2015 Lukas Rist <glaslos@gmail.com> # # Rewritten by Abhinav Saxena <xandfury@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from datetime import datetime class DotDict(dict): def __getattr__(self, name): return self[name] class Network(object): def __init__(self): self.public_ip = None self.hw_address = None # create attributes to interface on the fly. def __setattr__(self, attr, value): object.__setattr__(self, attr, value) # return default value in case an attribute cannot be found in the interface def __getattr__(self, attr): raise AttributeError("Interface.Network attribute does exist") class Interface(object): """Conpot's internal interface""" def __init__(self): self.network = Network() self.config = None self.protocols = DotDict() self.last_active = datetime.now().strftime("%b %d %Y - %H:%M:%S") @property def enabled(self): return [k for k in self.protocols.keys() if self.protocols[k] is not None] def __setattr__(self, attr, value): object.__setattr__(self, attr, value) def __getattr__(self, attr): raise AttributeError("Interface attribute does exist. Please check assignment") # FIXME: Do we really need this? def __repr__(self): s = """ Conpot: ICS/SCADA Honeypot (c) 2018, MushMush Foundation. --------------------------------------------- (1) Using Config : {} (2) Enabled Protocols : {} (3) Last Active (Attacked) on : {}""".format( self.config, self.enabled, self.last_active ) return s __str__ = __repr__
2,491
Python
.py
58
36.689655
87
0.626964
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,509
fs_utils.py
mushorg_conpot/conpot/core/fs_utils.py
# Copyright (C) 2018 Abhinav Saxena <xandfury@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Utils related to ConpotVFS """ import fs from typing import Optional, Union from fs.permissions import Permissions import typing from fs.subfs import SubFS from fs.error_tools import unwrap_errors import logging _F = typing.TypeVar("_F", bound="FS", covariant=True) logger = logging.getLogger(__name__) class FilesystemError(fs.errors.FSError): """Custom class for filesystem-related exceptions.""" class FSOperationNotPermitted(fs.errors.FSError): """Custom class for filesystem-related exceptions.""" def copy_files(source, dest, buffer_size=1024 * 1024): """ Copy a file from source to dest. source and dest must be file-like objects. """ while True: copy_buffer = source.read(buffer_size) if not copy_buffer: break dest.write(copy_buffer) class _custom_conpot_file(object): def __init__( self, file_system, parent_fs, path, mode, buffering=-1, encoding=None, newline="", line_buffering=False, ): self.file_system = file_system self._path = path self._file = parent_fs.open( path=self._path, mode=mode, buffering=buffering, encoding=encoding, newline=newline, line_buffering=line_buffering, ) self.mode = self._file.mode def __getattr__(self, item): return getattr(self._file, item) def __repr__(self): return "<conpot_fs cached file: {}>".format(self._file.__repr__()) __str__ = __repr__ @property def get_file(self): return self._file def close(self): self._file.close() if ( ("w" in self.mode) or ("a" in self.mode) or (self.file_system.built_cache is False) or ("x" in self.mode) ): self.file_system._cache.update( { self._path: self.file_system.getinfo( self._path, get_actual=True, namespaces=["basic", "access", "details", "stat"], ) } ) self.file_system.chown( self._path, self.file_system.default_uid, self.file_system.default_gid ) self.file_system.chmod(self._path, self.file_system.default_perms) logger.debug("Updating modified/access time") self.file_system.setinfo(self._path, {}) def __enter__(self): return self._file def __exit__(self, exc_type, exc_value, traceback): logger.debug("Exiting file at : {}".format(self._path)) self.close() class SubAbstractFS(SubFS[_F], typing.Generic[_F]): """ Creates a chroot jail sub file system. Each protocol can have an instance of this class. Use AbstractFS's create_jail method to access this. You won't be able to cd into an `up` directory. """ def __init__(self, parent_fs, path): self.parent_fs = parent_fs self._default_uid, self._default_gid = ( parent_fs.default_uid, parent_fs.default_gid, ) self._default_perms = parent_fs.default_perms self.utime = self.settimes super(SubAbstractFS, self).__init__(parent_fs, path) def getinfo(self, path: str, get_actual: bool = False, namespaces=None): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.getinfo(_path, get_actual=get_actual, namespaces=namespaces) # ------- Setters and getters for default users/grps/perms @property def default_perms(self): return self._default_perms @default_perms.setter def default_perms(self, perms): try: assert isinstance(perms, Permissions) self._default_perms = perms except AssertionError: raise FilesystemError( "Permissions provided must be of valid type (fs.permissions.Permission)" ) @property def default_uid(self): return self._default_uid @default_uid.setter def default_uid(self, _uid): if _uid in self.parent_fs._users.keys(): self._default_uid = _uid else: raise FilesystemError("User with id {} not registered with fs".format(_uid)) @property def default_gid(self): return self._default_gid @default_gid.setter def default_gid(self, _gid): if _gid in self.parent_fs._grps.keys(): self._default_gid = _gid else: raise FilesystemError( "Group with id {} not registered with fs".format(_gid) ) # ---- Other utilites @property def default_user(self): return self.parent_fs._users[self.default_uid]["user"] @property def default_group(self): return self.parent_fs._grps[self.default_gid]["group"] def getcwd(self): return self._sub_dir @property def root(self): return self.parent_fs.root + self.getcwd() def getmtime(self, path): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.getmtime(_path) def format_list(self, basedir, listing): _fs, _path = self.delegate_path(basedir) with unwrap_errors(basedir): return _fs.format_list(_path, listing) def check_access(self, path=None, user=None, perms=None): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.check_access(_path, user, perms) def chown( self, fs_path: str, uid: int, gid: int, recursive: Optional[bool] = False ): _fs, _path = self.delegate_path(fs_path) with unwrap_errors(fs_path): return _fs.chown(_path, uid, gid, recursive) def chmod(self, path: str, mode: oct, recursive: bool = False) -> None: _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.chmod(_path, mode, recursive) def access( self, path: str, name_or_id: Union[int, str] = None, required_perms: str = None ): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.access(_path, name_or_id, required_perms) def stat(self, path): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.stat(_path) def readlink(self, path): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.readlink(_path) def get_permissions(self, path): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.get_permissions(_path) def removedir(self, path, rf=False): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.removedir(_path) def remove(self, path): _fs, _path = self.delegate_path(path) with unwrap_errors(path): return _fs.remove(_path) def move(self, src_path, dst_path, overwrite=True): _fs, _src_path = self.delegate_path(src_path) _, _dst_path = self.delegate_path(dst_path) with unwrap_errors({_src_path: src_path, _dst_path: dst_path}): return _fs.move(_src_path, _dst_path, overwrite=overwrite) def __getattr__(self, item): if hasattr(self.parent_fs, item) and item in { "_cache", "create_group", "register_user", "take_snapshot", "norm_path", "users", "groups", "add_users_to_group", "check_access", }: return getattr(self.parent_fs, item) else: raise NotImplementedError( "Conpot's File System does not currently support method: {}".format( item ) )
8,783
Python
.py
235
28.804255
109
0.602517
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,510
log_worker.py
mushorg_conpot/conpot/core/log_worker.py
# Copyright (C) 2014 Lukas Rist <glaslos@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import json import logging import time from datetime import datetime import configparser from gevent.queue import Empty from conpot.core.loggers.sqlite_log import SQLiteLogger from conpot.core.loggers.hpfriends import HPFriendsLogger from conpot.core.loggers.syslog import SysLogger from conpot.core.loggers.taxii_log import TaxiiLogger from conpot.core.loggers.json_log import JsonLogger from .loggers.helpers import json_default logger = logging.getLogger(__name__) class LogWorker(object): def __init__(self, config, dom, session_manager, public_ip): self.config = config self.log_queue = session_manager.log_queue self.session_manager = session_manager self.sqlite_logger = None self.json_logger = None self.friends_feeder = None self.syslog_client = None self.public_ip = public_ip self.taxii_logger = None if config.getboolean("sqlite", "enabled"): self.sqlite_logger = SQLiteLogger() if config.getboolean("json", "enabled"): filename = config.get("json", "filename") sensorid = config.get("common", "sensorid") self.json_logger = JsonLogger(filename, sensorid, public_ip) if config.getboolean("hpfriends", "enabled"): host = config.get("hpfriends", "host") port = config.getint("hpfriends", "port") ident = config.get("hpfriends", "ident") secret = config.get("hpfriends", "secret") channels = eval(config.get("hpfriends", "channels")) try: self.friends_feeder = HPFriendsLogger( host, port, ident, secret, channels ) except Exception as e: logger.exception(e) self.friends_feeder = None if config.getboolean("syslog", "enabled"): host = config.get("syslog", "host") port = config.getint("syslog", "port") facility = config.get("syslog", "facility") logdevice = config.get("syslog", "device") logsocket = config.get("syslog", "socket") self.syslog_client = SysLogger(host, port, facility, logdevice, logsocket) if config.getboolean("taxii", "enabled"): # TODO: support for certificates self.taxii_logger = TaxiiLogger(config, dom) self.enabled = True def _process_sessions(self): sessions = self.session_manager._sessions try: session_timeout = self.config.get("session", "timeout") except (configparser.NoSectionError, configparser.NoOptionError): session_timeout = 5 for session in sessions: if len(session.data) > 0: sec_last_event = max(session.data) / 1000 else: sec_last_event = 0 sec_session_start = time.mktime(session.timestamp.timetuple()) sec_now = time.mktime(datetime.utcnow().timetuple()) if (sec_now - (sec_session_start + sec_last_event)) >= float( session_timeout ): # TODO: We need to close sockets in this case logger.info("Session timed out: %s", session.id) session.set_ended() sessions.remove(session) def start(self): self.enabled = True while self.enabled: try: event = self.log_queue.get(timeout=2) except Empty: self._process_sessions() else: if self.public_ip: event["public_ip"] = self.public_ip if self.friends_feeder: self.friends_feeder.log(json.dumps(event, default=json_default)) if self.sqlite_logger: self.sqlite_logger.log(event) if self.syslog_client: self.syslog_client.log(event) if self.taxii_logger: self.taxii_logger.log(event) if self.json_logger: self.json_logger.log(event) def stop(self): self.enabled = False
4,942
Python
.py
112
34.044643
86
0.620295
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,511
json_log.py
mushorg_conpot/conpot/core/loggers/json_log.py
# Copyright (C) 2015 Danilo Massa # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import json from .helpers import json_default class JsonLogger(object): def __init__(self, filename, sensorid, public_ip): self.fileHandle = open(filename, "a") self.sensorid = sensorid self.public_ip = public_ip def log(self, event): if self.public_ip is not None: dst_ip = self.public_ip else: dst_ip = None data = { "timestamp": event["timestamp"].isoformat(), "sensorid": self.sensorid, "id": event["id"], "src_ip": event["remote"][0], "src_port": event["remote"][1], "dst_ip": event["local"][0], "dst_port": event["local"][1], "public_ip": dst_ip, "data_type": event["data_type"], "request": event["data"].get("request"), "response": event["data"].get("response"), "event_type": event["data"].get("type"), } json.dump(data, self.fileHandle, default=json_default) self.fileHandle.write("\n") self.fileHandle.flush()
1,827
Python
.py
45
33.777778
67
0.635135
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,512
taxii_log.py
mushorg_conpot/conpot/core/loggers/taxii_log.py
# Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import libtaxii import libtaxii.messages from libtaxii.messages_11 import ContentBlock, InboxMessage, generate_message_id from libtaxii.clients import HttpClient from conpot.core.loggers.stix_transform import StixTransformer logger = logging.getLogger(__name__) class TaxiiLogger(object): def __init__(self, config, dom): self.host = config.get("taxii", "host") self.port = config.getint("taxii", "port") self.inbox_path = config.get("taxii", "inbox_path") self.use_https = config.getboolean("taxii", "use_https") self.client = HttpClient() self.client.setProxy("noproxy") self.stix_transformer = StixTransformer(config, dom) def log(self, event): # converts from conpot log format to STIX compatible xml stix_package = self.stix_transformer.transform(event) # wrapping the stix message in a TAXII envelope content_block = ContentBlock( libtaxii.CB_STIX_XML_11, stix_package.encode("utf-8") ) inbox_message = InboxMessage( message_id=generate_message_id(), content_blocks=[content_block] ) inbox_xml = inbox_message.to_xml() # the actual call to the TAXII web service response = self.client.callTaxiiService2( self.host, self.inbox_path, libtaxii.VID_TAXII_XML_11, inbox_xml, self.port ) response_message = libtaxii.get_message_from_http_response(response, "0") if response_message.status_type != libtaxii.messages.ST_SUCCESS: logger.error( "Error while transmitting message to TAXII server: %s", response_message.message, ) return False else: return True
2,546
Python
.py
56
39.053571
87
0.697862
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,513
hpfriends.py
mushorg_conpot/conpot/core/loggers/hpfriends.py
# Copyright (C) 2013 Lukas Rist <glaslos@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import socket import hpfeeds import gevent import logging logger = logging.getLogger(__name__) class HPFriendsLogger(object): def __init__(self, host, port, ident, secret, channels): self.host = host self.port = port self.ident = ident self.secret = secret self.channels = channels self.max_retires = 5 self._initial_connection_happend = False self.greenlet = gevent.spawn(self._start_connection, host, port, ident, secret) def _start_connection(self, host, port, ident, secret): # if no initial connection to hpfeeds this will hang forever, reconnect=True only comes into play # when lost connection after the initial connect happend. self.hpc = hpfeeds.new(host, port, ident, secret) self._initial_connection_happend = True def log(self, data): retries = 0 if self._initial_connection_happend: # hpfeed lib supports passing list of channels while True: if retries >= self.max_retires: break try: self.hpc.publish(self.channels, data) except socket.error: retries += 1 self.__init__( self.host, self.port, self.ident, self.secret, self.channels ) gevent.sleep(0.5) else: break error_msg = self.hpc.wait() return error_msg else: error_msg = ( "Not logging event because initial hpfeeds connect has not happend yet." ) logger.warning(error_msg) return error_msg
2,504
Python
.py
61
32.180328
105
0.632444
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,514
stix_transform.py
mushorg_conpot/conpot/core/loggers/stix_transform.py
# Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import json import ast import textwrap from mixbox import idgen from mixbox.namespaces import Namespace from stix.core import STIXHeader, STIXPackage from stix.common import InformationSource from stix.common.vocabs import VocabString from stix.incident import Incident from stix.incident.time import Time as StixTime from stix.indicator import Indicator from stix.ttp import TTP, VictimTargeting from stix.extensions.identity.ciq_identity_3_0 import CIQIdentity3_0Instance from cybox.core import Observable from cybox.objects.socket_address_object import SocketAddress from cybox.objects.address_object import Address from cybox.objects.port_object import Port from cybox.objects.network_connection_object import NetworkConnection from cybox.objects.artifact_object import Artifact, ZlibCompression, Base64Encoding from cybox.common import ToolInformationList, ToolInformation from cybox.common import Time as CyboxTime from datetime import datetime import conpot CONPOT_NAMESPACE = "mushmush-conpot" CONPOT_NAMESPACE_URL = "http://mushmush.org/conpot" class StixTransformer(object): def __init__(self, config, dom): self.protocol_to_port_mapping = dict( modbus=502, snmp=161, http=80, s7comm=102, ) port_path_list = [ "//conpot_template/protocols/" + x + "/@port" for x in list(self.protocol_to_port_mapping.keys()) ] for port_path in port_path_list: try: protocol_port = ast.literal_eval(dom.xpath(port_path)[0]) protocol_name = port_path.rsplit("/", 2)[1] self.protocol_to_port_mapping[protocol_name] = protocol_port except IndexError: continue conpot_namespace = Namespace(CONPOT_NAMESPACE_URL, CONPOT_NAMESPACE, "") idgen.set_id_namespace(conpot_namespace) def _add_header(self, stix_package, title, desc): stix_header = STIXHeader() stix_header.title = title stix_header.description = desc stix_header.information_source = InformationSource() stix_header.information_source.time = CyboxTime() stix_header.information_source.time.produced_time = datetime.now().isoformat() stix_package.stix_header = stix_header def transform(self, event): stix_package = STIXPackage() self._add_header( stix_package, "Unauthorized traffic to honeypot", "Describes one or more honeypot incidents", ) incident = Incident( id_="%s:%s-%s" % (CONPOT_NAMESPACE, "incident", event["session_id"]) ) initial_time = StixTime() initial_time.initial_compromise = event["timestamp"].isoformat() incident.time = initial_time incident.title = "Conpot Event" incident.short_description = "Traffic to Conpot ICS honeypot" incident.add_category(VocabString(value="Scans/Probes/Attempted Access")) tool_list = ToolInformationList() tool_list.append( ToolInformation.from_dict( { "name": "Conpot", "vendor": "Conpot Team", "version": conpot.__version__, "description": textwrap.dedent( "Conpot is a low interactive server side Industrial Control Systems " "honeypot designed to be easy to deploy, modify and extend." ), } ) ) incident.reporter = InformationSource(tools=tool_list) incident.add_discovery_method("Monitoring Service") incident.confidence = "High" # Victim Targeting by Sector ciq_identity = CIQIdentity3_0Instance() # identity_spec = STIXCIQIdentity3_0() # identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems") # ciq_identity.specification = identity_spec ttp = TTP( title="Victim Targeting: Electricity Sector and Industrial Control System Sector" ) ttp.victim_targeting = VictimTargeting() ttp.victim_targeting.identity = ciq_identity incident.leveraged_ttps.append(ttp) indicator = Indicator(title="Conpot Event") indicator.description = "Conpot network event" indicator.confidence = "High" source_port = Port.from_dict( {"port_value": event["remote"][1], "layer4_protocol": "tcp"} ) dest_port = Port.from_dict( { "port_value": self.protocol_to_port_mapping[event["data_type"]], "layer4_protocol": "tcp", } ) source_ip = Address.from_dict( {"address_value": event["remote"][0], "category": Address.CAT_IPV4} ) dest_ip = Address.from_dict( {"address_value": event["public_ip"], "category": Address.CAT_IPV4} ) source_address = SocketAddress.from_dict( {"ip_address": source_ip.to_dict(), "port": source_port.to_dict()} ) dest_address = SocketAddress.from_dict( {"ip_address": dest_ip.to_dict(), "port": dest_port.to_dict()} ) network_connection = NetworkConnection.from_dict( { "source_socket_address": source_address.to_dict(), "destination_socket_address": dest_address.to_dict(), "layer3_protocol": "IPv4", "layer4_protocol": "TCP", "layer7_protocol": event["data_type"], "source_tcp_state": "ESTABLISHED", "destination_tcp_state": "ESTABLISHED", } ) indicator.add_observable(Observable(network_connection)) artifact = Artifact() artifact.data = json.dumps(event["data"]) artifact.packaging.append(ZlibCompression()) artifact.packaging.append(Base64Encoding()) indicator.add_observable(Observable(artifact)) incident.related_indicators.append(indicator) stix_package.add_incident(incident) stix_package_xml = stix_package.to_xml() return stix_package_xml
7,022
Python
.py
159
35.289308
117
0.651761
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,515
helpers.py
mushorg_conpot/conpot/core/loggers/helpers.py
from datetime import datetime import uuid def json_default(obj): if isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, uuid.UUID): return str(obj) elif isinstance(obj, bytes): return str(obj) else: return None
280
Python
.py
11
19.909091
36
0.670412
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,516
syslog.py
mushorg_conpot/conpot/core/loggers/syslog.py
# Copyright (C) 2013 Daniel creo Haslinger <creo-conpot@blackmesa.at> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from logging.handlers import SysLogHandler import logging import socket class SysLogger(object): def __init__(self, host, port, facility, logdevice, logsocket): logger = logging.getLogger() if str(logsocket).lower() == "udp": logger.addHandler( SysLogHandler( address=(host, port), facility=getattr(SysLogHandler, "LOG_" + str(facility).upper()), socktype=socket.SOCK_DGRAM, ) ) elif str(logsocket).lower() == "dev": logger.addHandler(SysLogHandler(logdevice)) def log(self, data): # stub function since the additional handler has been added to the root loggers instance. pass
1,539
Python
.py
35
37.8
97
0.691127
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,517
sqlite_log.py
mushorg_conpot/conpot/core/loggers/sqlite_log.py
# Copyright (C) 2013 Lukas Rist <glaslos@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import sqlite3 import pwd import os import platform import grp class SQLiteLogger(object): def _chown_db(self, path, uid_name="nobody", gid_name="nogroup"): path = path.rpartition("/")[0] if not os.path.isdir(path): os.mkdir(path) # TODO: Have this in a central place wanted_uid = pwd.getpwnam(uid_name)[2] # special handling for os x. (getgrname has trouble with gid below 0) if platform.mac_ver()[0]: wanted_gid = -2 else: wanted_gid = grp.getgrnam(gid_name)[2] os.chown(path, wanted_uid, wanted_gid) def __init__(self, db_path="logs/conpot.db"): self._chown_db(db_path) self.conn = sqlite3.connect(db_path) self._create_db() def _create_db(self): cursor = self.conn.cursor() cursor.execute( """CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, session TEXT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, remote TEXT, protocol TEXT, request TEXT, response TEXT )""" ) def log(self, event): cursor = self.conn.cursor() cursor.execute( "INSERT INTO events(session, remote, protocol, request, response) VALUES (?, ?, ?, ?, ?)", ( str(event["id"]), str(event["remote"]), event["data_type"], str(event["data"].get("request")), str(event["data"].get("response")), ), ) self.conn.commit() return cursor.lastrowid
2,471
Python
.py
66
29.242424
102
0.609675
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,518
kamstrup_prober.py
mushorg_conpot/bin/kamstrup_prober.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import socket import json from datetime import datetime import calendar import time import argparse import crc16 import xml.dom.minidom from conpot.protocols.kamstrup_meter import kamstrup_constants logger = logging.getLogger(__name__) port_start_range = 1 port_end_range = 65535 default_comm_port = 63 class KamstrupRegisterCopier(object): def __init__(self, ip_address, port, comm_address): self._sock = None self.ip_address = ip_address self.port = port self.comm_address = comm_address self._connect() def _connect(self): logger.info("Connecting to {0}:{1}".format(self.ip_address, self.port)) if self._sock is not None: self._sock.close() time.sleep(1) self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.settimeout(2) try: self._sock.connect((self.ip_address, self.port)) except socket.error as socket_err: logger.exception("Error while connecting: {0}".format(str(socket_err))) self._connect() def get_register(self, register): message = [ kamstrup_constants.REQUEST_MAGIC, self.comm_address, 0x10, 0x01, register >> 8, register & 0xFF, ] crc = crc16.crc16xmodem("".join([chr(item) for item in message[1:]])) message.append(crc >> 8) message.append(crc & 0xFF) message_length = len(message) y = 1 while y < message_length: if message[y] in kamstrup_constants.NEED_ESCAPE: message[y] ^= 0xFF message.insert(y, kamstrup_constants.ESCAPE) y += 1 message_length += 1 y += 1 message.append(kamstrup_constants.EOT_MAGIC) received_data = None while received_data is None: try: self._sock.send(bytearray(message)) received_data = self._sock.recv(1024) received_data = bytearray(received_data) except socket.error as socket_err: logger.exception( "Error while communicating: {0}".format(str(socket_err)) ) self._connect() data_length = len(received_data) # remove escaped bytes p = 0 while p < data_length: if received_data[p] is kamstrup_constants.ESCAPE: del received_data[p] received_data[p] ^= 0xFF data_length -= 1 p += 1 return received_data def find_registers_in_candidates(args): if args.registerfile: candidate_registers_values = [] with open(args.registerfile, "r") as register_file: old_register_values = json.load(register_file) for value in old_register_values.iterkeys(): candidate_registers_values.append(int(value)) else: candidate_registers_values = range(port_start_range, port_end_range) found_registers = registers_from_candidates(candidate_registers_values, args) logger.info( "Scanned {0} registers, found {1}.".format( len(candidate_registers_values), len(found_registers) ) ) # with open('kamstrup_dump_{0}.json'.format(calendar.timegm(datetime.utcnow().utctimetuple())), 'w') as json_file: # json_file.write(json.dumps(found_registers, indent=4, default=json_default)) logger.info("""*** Sample Conpot configuration from this scrape:""") logger.info(generate_conpot_config(found_registers)) def registers_from_candidates(candidate_registers_values, args): kamstrupRegisterCopier = KamstrupRegisterCopier( args.host, args.port, int(args.communication_address) ) found_registers = {} not_found_counts = 0 scanned = 0 dumpfile = "kamstrup_dump_{0}.json".format( calendar.timegm(datetime.utcnow().utctimetuple()) ) for register_id in candidate_registers_values: result = kamstrupRegisterCopier.get_register(register_id) if len(result) > 12: units = result[5] length = result[6] unknown = result[7] register_value = 0 for p in range(length): register_value += result[8 + p] << (8 * ((length - p) - 1)) found_registers[register_id] = { "timestamp": datetime.utcnow(), "units": units, "value": register_value, "value_length": length, "unknown": unknown, } logger.info( "Found register value at {0}:{1}".format( hex(register_id), register_value ) ) with open(dumpfile, "w") as json_file: json_file.write( json.dumps(found_registers, indent=4, default=json_default) ) else: not_found_counts += 1 if not_found_counts % 10 == 0: logger.info( "Hang on, still scanning, so far scanned {0} and found {1} registers".format( scanned, len(found_registers) ) ) scanned += 1 return found_registers def generate_conpot_config(result_list): config_xml = """<conpot_template name="Kamstrup-Auto382" description="Register clone of an existing Kamstrup meter"> <core><databus><key_value_mappings>""" for key, value in result_list.items(): config_xml += ( """<key name="register_{0}"><value type="value">{1}</value></key>""".format( key, value["value"] ) ) config_xml += """</key_value_mappings></databus></core><protocols><kamstrup_meter enabled="True" host="0.0.0.0" port="1025"><registers>""" for key, value in result_list.items(): config_xml += """<register name="{0}" units="{1}" unknown="{2}" length="{3}"><value>register_{0}</value></register>""".format( key, value["units"], value["unknown"], value["value_length"] ) config_xml += "</registers></kamstrup_meter></protocols></conpot_template>" parsed_xml = xml.dom.minidom.parseString(config_xml) pretty_xml = parsed_xml.toprettyxml() return pretty_xml def json_default(obj): if isinstance(obj, datetime): return obj.isoformat() else: return None if __name__ == "__main__": parser = argparse.ArgumentParser( description="Probes kamstrup_meter meter registers." ) parser.add_argument("host", help="Hostname or IP or Kamstrup meter") parser.add_argument("port", type=int, help="TCP port") parser.add_argument( "--registerfile", dest="registerfile", help="Reads registers from previous dumps files instead of bruteforcing the meter.", ) parser.add_argument( "--comm-addr", dest="communication_address", default=default_comm_port ) find_registers_in_candidates(parser.parse_args())
7,896
Python
.py
194
31.701031
142
0.612588
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,519
start_protocol.py
mushorg_conpot/bin/start_protocol.py
# Copyright (C) 2020 srenfo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import sys import gevent from conpot.utils.greenlet import init_test_server_by_name, teardown_test_server def main(): """Start individual protocol instances (for debugging)""" name = sys.argv[1] ports = { "bacnet": 9999, "enip": 60002, "ftp": 10001, "guardian_ast": 10001, "http": 50001, "kamstrup_management": 50100, "kamstrup_meter": 1025, "ipmi": 10002, "s7comm": 9999, "tftp": 6090, } port = ports.get(name, 0) print(f"Starting '{name}'...") server, greenlet = init_test_server_by_name(name, port=port) try: gevent.wait() except KeyboardInterrupt: teardown_test_server(server=server, greenlet=greenlet) if __name__ == "__main__": main()
1,526
Python
.py
43
31.093023
80
0.68907
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,520
conf.py
mushorg_conpot/docs/source/conf.py
# -*- coding: utf-8 -*- # # Conpot documentation build configuration file, created by # sphinx-quickstart on Sat Apr 20 14:00:03 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import sphinx_rtd_theme sys.path.append(os.path.join(os.path.dirname(__file__))) sys.path.append(os.path.join(os.getcwd() + "/../../")) import conpot # print(conpot.__version__) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["sphinx.ext.autodoc"] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "Conpot" copyright = "2018, MushMush Foundation" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # The short X.Y version. version = conpot.__version__ # The full version, including alpha/beta/rc tags. release = conpot.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # t oday_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Conpotdoc" # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "Conpot.tex", "Conpot Documentation", "MushMush Foundation", "manual"), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "conpot", "Conpot Documentation", ["MushMush Foundation"], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "Conpot", "Conpot Documentation", "MushMush Foundation", "Conpot", "ICS/SCADA honeypot.", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False
8,370
Python
.py
189
42.444444
85
0.713828
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,521
test_attack_session.py
mushorg_conpot/conpot/tests/test_attack_session.py
from datetime import datetime, timedelta from freezegun import freeze_time from conpot.core.attack_session import AttackSession class LogQueueFake: def __init__(self): self.events = [] def put(self, event): self.events.append(event) def test_add_event_is_logged(): protocol = "testing" source_ip = "1.2.3.4" source_port = 11 destination_ip = "5.6.7.8" destination_port = 22 log_queue = LogQueueFake() session = AttackSession( protocol=protocol, source_ip=source_ip, source_port=source_port, destination_ip=destination_ip, destination_port=destination_port, log_queue=log_queue, ) event = {"foo": "bar"} session.add_event(event) logged = log_queue.events[0] assert logged["data"] == event assert logged["data_type"] == protocol assert logged["src_ip"] == source_ip assert logged["src_port"] == source_port assert logged["remote"] == (source_ip, source_port) assert logged["dst_ip"] == destination_ip assert logged["dst_port"] == destination_port assert logged["local"] == (destination_ip, destination_port) # TODO should this even include public_ip if it's always None? assert logged["public_ip"] is None def test_add_event_same_id(): log_queue = LogQueueFake() session = AttackSession( protocol=None, source_ip=None, source_port=None, destination_ip=None, destination_port=None, log_queue=log_queue, ) session.add_event({"foo": "bar"}) session.add_event({"bar": "baz"}) assert log_queue.events[0]["id"] == log_queue.events[1]["id"] def test_add_event_sessions_have_unique_ids(): log_queue = LogQueueFake() session_1 = AttackSession( protocol=None, source_ip=None, source_port=None, destination_ip=None, destination_port=None, log_queue=log_queue, ) session_2 = AttackSession( protocol=None, source_ip=None, source_port=None, destination_ip=None, destination_port=None, log_queue=log_queue, ) session_1.add_event({"foo": "bar"}) session_2.add_event({"bar": "baz"}) assert log_queue.events[0]["id"] != log_queue.events[1]["id"] def test_add_event_uses_session_timestamp(): log_queue = LogQueueFake() session_start = datetime(2000, 1, 1) with freeze_time(session_start) as frozen_time: session = AttackSession( protocol=None, source_ip=None, source_port=None, destination_ip=None, destination_port=None, log_queue=log_queue, ) frozen_time.tick(timedelta(days=1)) session.add_event({"foo": "bar"}) session.add_event({"bar": "baz"}) # timestamp is always the time the session started, # not the time the event occurred assert log_queue.events[0]["timestamp"] == session_start assert log_queue.events[1]["timestamp"] == session_start @freeze_time("2000-01-01", auto_tick_seconds=2) def test_dump_collects_events(): protocol = "testing" source_ip = "1.2.3.4" source_port = 11 destination_ip = "5.6.7.8" destination_port = 22 log_queue = LogQueueFake() session = AttackSession( protocol=protocol, source_ip=source_ip, source_port=source_port, destination_ip=destination_ip, destination_port=destination_port, log_queue=log_queue, ) event_1 = {"foo": "bar"} event_2 = {"bar": "baz"} session.add_event(event_1) session.add_event(event_2) session.add_event(event_1) dump = session.dump() assert dump["data_type"] == protocol assert list(dump["data"].keys()) == [2000, 4000, 6000] assert list(dump["data"].values()) == [event_1, event_2, event_1] assert dump["src_ip"] == source_ip assert dump["src_port"] == source_port assert dump["remote"] == (source_ip, source_port) assert dump["dst_ip"] == destination_ip assert dump["dst_port"] == destination_port assert dump["local"] == (destination_ip, destination_port) # TODO should this even include public_ip if it's always None? assert dump["public_ip"] is None
4,297
Python
.tac
122
28.491803
69
0.633946
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,522
attack_session.py
mushorg_conpot/conpot/core/attack_session.py
# Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging import uuid from datetime import datetime logger = logging.getLogger(__name__) # one instance per connection class AttackSession(object): def __init__( self, protocol, source_ip, source_port, destination_ip, destination_port, log_queue, ): self.log_queue = log_queue self.id = uuid.uuid4() logger.info("New %s session from %s (%s)", protocol, source_ip, self.id) self.protocol = protocol self.source_ip = source_ip self.source_port = source_port self.destination_ip = destination_ip self.destination_port = destination_port self.timestamp = datetime.utcnow() self.public_ip = None self.data = dict() self._ended = False def _dump_data(self, data): return { "id": self.id, "remote": (self.source_ip, self.source_port), "src_ip": self.source_ip, "src_port": self.source_port, "local": (self.destination_ip, self.destination_port), "dst_ip": self.destination_ip, "dst_port": self.destination_port, "data_type": self.protocol, "timestamp": self.timestamp, "public_ip": self.public_ip, "data": data, } def add_event(self, event_data): sec_elapsed = (datetime.utcnow() - self.timestamp).total_seconds() elapse_ms = int(sec_elapsed * 1000) while elapse_ms in self.data: elapse_ms += 1 self.data[elapse_ms] = event_data # TODO: We should only log the session when it is finished self.log_queue.put(self._dump_data(event_data)) def dump(self): return self._dump_data(self.data) def set_ended(self): self._ended = True
2,606
Python
.tac
69
30.811594
80
0.645289
mushorg/conpot
1,224
413
115
GPL-2.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,523
dnscan.py
rbsec_dnscan/dnscan.py
#!/usr/bin/env python3 # # dnscan copyright (C) 2013-2014 rbsec # Licensed under GPLv3, see LICENSE for details # from __future__ import print_function import packaging.version import os import platform import re import sys import threading import time try: # Ugly hack because Python3 decided to rename Queue to queue import Queue except ImportError: import queue as Queue try: # Python2 and Python3 have different IP address libraries from ipaddress import ip_address as ipaddr except ImportError: try: from netaddr import IPAddress as ipaddr except ImportError: if sys.version_info[0] == 2: print("FATAL: dnscan requires either the netaddr (python-netaddr) or ipaddress (python-ipaddress) modules.") else: print("FATAL: dnscan requires either the netaddr (python3-netaddr) or ipaddress (standard library) modules.") sys.exit(1) try: import argparse except: print("FATAL: Module argparse missing (python-argparse)") sys.exit(1) try: import dns.query import dns.resolver import dns.zone import dns.dnssec except: print("FATAL: Module dnspython missing (python-dnspython)") sys.exit(1) if (packaging.version.parse(dns.__version__) < packaging.version.Version("2.0.0")): print("dnscan requires dnspython 2.0.0 or greater.\nYou can install it with `pip install -r requirements.txt`") sys.exit(1) # Usage: dnscan.py -d <domain name> class scanner(threading.Thread): def __init__(self, queue): global wildcard threading.Thread.__init__(self) self.queue = queue def get_name(self, domain): global wildcard, addresses try: if sys.stdout.isatty(): # Don't spam output if redirected print(domain + '\033[K\r', end='') res = lookup(domain, recordtype) if args.tld and res: nameservers = sorted(list(res)) ns0 = str(nameservers[0])[:-1] # First nameserver print('\033[K\r', end='') print(domain + " - " + col.brown + ns0 + col.end) if outfile: print(ns0 + " - " + domain, file=outfile) if args.tld: if res: print('\033[K\r', end='') print(domain + " - " + res) return for rdata in res: address = rdata.address if wildcard: for wildcard_ip in wildcard: if address == wildcard_ip: return print('\033[K\r', end='') if args.no_ip: print(col.brown + domain + col.end) break elif args.domain_first: print(domain + " - " + col.brown + address + col.end) else: print(address + " - " + col.brown + domain + col.end) if outfile: if args.domain_first: print(domain + " - " + address, file=outfile) else: print(address + " - " + domain, file=outfile) try: addresses.add(ipaddr(unicode(address))) except NameError: addresses.add(ipaddr(str(address))) if ( domain != target and \ args.recurse and \ domain.count('.') - target.count('.') <= args.maxdepth ): # Check if subdomain is wildcard so can filter false positives in the recursive scan wildcard = get_wildcard(domain) for wildcard_ip in wildcard: try: addresses.add(ipaddr(unicode(wildcard_ip))) except NameError: addresses.add(ipaddr(str(wildcard_ip))) if args.recurse_wildcards or not wildcard: add_target(domain) # Recursively scan subdomains except: pass def run(self): while True: try: domain = self.queue.get(timeout=1) except: return self.get_name(domain) self.queue.task_done() class output: def status(self, message): print(col.blue + "[*] " + col.end + message) if outfile and not args.quick: print("[*] " + message, file=outfile) def good(self, message): print(col.green + "[+] " + col.end + message) if outfile and not args.quick: print("[+] " + message, file=outfile) def verbose(self, message): if args.verbose: print(col.brown + "[v] " + col.end + message) if outfile and not args.quick: print("[v] " + message, file=outfile) def warn(self, message): print(col.red + "[-] " + col.end + message) if outfile and not args.quick: print("[-] " + message, file=outfile) def fatal(self, message): print("\n" + col.red + "FATAL: " + message + col.end) if outfile and not args.quick: print("FATAL " + message, file=outfile) class col: if sys.stdout.isatty() and platform.system() != "Windows": green = '\033[32m' blue = '\033[94m' red = '\033[31m' brown = '\033[33m' end = '\033[0m' else: # Colours mess up redirected output, disable them green = "" blue = "" red = "" brown = "" end = "" def lookup(domain, recordtype): try: res = resolver.resolve(domain, recordtype) return res except: return def get_wildcard(target): # List of IP's for wildcard DNS wildcards = [] # Use current unix time as a test subdomain epochtime = str(int(time.time())) # Prepend a letter to work around incompetent companies like CableOne # and their stupid attempts at DNS hijacking res = lookup("a" + epochtime + "." + target, recordtype) if res: for res_data in res: address = res_data.address wildcards.append(address) out.warn("Wildcard domain found - " + col.brown + "*." + target + col.end + " (" + address + ")") else: out.verbose("No wildcard domain found") return wildcards def get_nameservers(target): try: ns = resolver.resolve(target, 'NS') return ns except: return def get_v6(target): out.verbose("Getting IPv6 (AAAA) records") try: res = lookup(target, "AAAA") if res: out.good("IPv6 (AAAA) records found. Try running dnscan with the "+ col.green + "-6 " + col.end + "option.") for v6 in res: print(str(v6) + "\n") if outfile: print(v6, file=outfile) except: return def get_txt(target): out.verbose("Getting TXT records") try: res = lookup(target, "TXT") if res: out.good("TXT records found") for txt in res: print(txt) if outfile: print(txt, file=outfile) print("") except: return def get_dmarc(target): out.verbose("Getting DMARC records") try: res = lookup("_dmarc." + target, "TXT") if res: out.good("DMARC records found") for dmarc in res: print(dmarc) if outfile: print(dmarc, file=outfile) print("") except: return def get_dnssec(target, nameserver): out.verbose("Checking DNSSEC") request = dns.message.make_query(target, dns.rdatatype.DNSKEY, want_dnssec=True) response = dns.query.udp(request, nameserver, timeout=1) if response.rcode() != 0: out.warn("DNSKEY lookup returned error code " + dns.rcode.to_text(response.rcode()) + "\n") else: answer = response.answer if len(answer) == 0: out.warn("DNSSEC not supported\n") elif len(answer) != 2: out.warn("Invalid DNSKEY record length\n") else: name = dns.name.from_text(target) try: dns.dnssec.validate(answer[0],answer[1],{name:answer[0]}) except dns.dnssec.ValidationFailure: out.warn("DNSSEC key validation failed\n") else: out.good("DNSSEC enabled and validated") dnssec_values = str(answer[0][0]).split(' ') algorithm_int = int(dnssec_values[2]) algorithm_str = dns.dnssec.algorithm_to_text(algorithm_int) print("Algorithm = " + algorithm_str + " (" + str(algorithm_int) + ")\n") def get_mx(target): out.verbose("Getting MX records") try: res = lookup(target, "MX") except: return # Return if we don't get any MX records back if not res: return out.good("MX records found, added to target list") for mx in res: print(mx.to_text()) if outfile: print(mx.to_text(), file=outfile) mxsub = re.search("([a-z0-9\.\-]+)\."+target, mx.to_text(), re.IGNORECASE) try: if mxsub.group(1) and mxsub.group(1) not in wordlist: queue.put(mxsub.group(1) + "." + target) except AttributeError: pass print("") def zone_transfer(domain, ns, nsip): out.verbose("Trying zone transfer against " + str(ns)) try: print(str(domain)) zone = dns.zone.from_xfr(dns.query.xfr(str(nsip), domain, relativize=False, timeout=3), relativize=False) out.good("Zone transfer sucessful using nameserver " + col.brown + str(ns) + col.end) names = list(zone.nodes.keys()) names.sort() for n in names: print(zone[n].to_text(n)) # Print raw zone if outfile: print(zone[n].to_text(n), file=outfile) sys.exit(0) except Exception: pass def add_target(domain): for word in wordlist: patterns = [word] if args.alt: probes = ["dev", "prod", "stg", "qa", "uat", "api", "alpha", "beta", "cms", "test", "internal", "staging", "origin", "stage"] for probe in probes: if probe not in word: # Reduce alterations that most likely don't exist (e.i. dev-dev.domain.com) patterns.append(probe + word) patterns.append(word + probe) patterns.append(probe + "-" + word) patterns.append(word + "-" + probe) if not word[-1].isdigit(): # If the subdomain has already had a number as the suffix for n in range(1, 6): patterns.append(word + str(n)) patterns.append(word + "0" + str(n)) for pattern in patterns: if '%%' in domain: queue.put(domain.replace(r'%%', pattern)) else: queue.put(pattern + "." + domain) def add_tlds(domain): for tld in wordlist: queue.put(domain + "." + tld) def get_args(): global args parser = argparse.ArgumentParser('dnscan.py', formatter_class=lambda prog:argparse.HelpFormatter(prog,max_help_position=40), epilog="Specify a custom insertion point with %% in the domain name, such as: dnscan.py -d dev-%%.example.org") target = parser.add_mutually_exclusive_group(required=True) # Allow a user to specify a list of target domains target.add_argument('-d', '--domain', help='Target domains (separated by commas)', dest='domain', required=False) target.add_argument('-l', '--list', help='File containing list of target domains', dest='domain_list', required=False) parser.add_argument('-w', '--wordlist', help='Wordlist', dest='wordlist', required=False) parser.add_argument('-t', '--threads', help='Number of threads', dest='threads', required=False, type=int, default=8) parser.add_argument('-6', '--ipv6', action="store_true", help='Scan for AAAA records', dest='ipv6') parser.add_argument('-z', '--zonetransfer', action="store_true", help='Only perform zone transfers', dest='zonetransfer') parser.add_argument('-r', '--recursive', action="store_true", help="Recursively scan subdomains", dest='recurse') parser.add_argument('--recurse-wildcards', action="store_true", help="Recursively scan wildcards (slow)", dest='recurse_wildcards') parser.add_argument('-m', '--maxdepth', help='Maximal recursion depth (for brute-forcing)', dest='maxdepth', required=False, type=int, default=5) parser.add_argument('-a', '--alterations', action="store_true", help='Scan for alterations of subdomains (slow)', dest='alt') parser.add_argument('-R', '--resolver', help="Use the specified resolvers (separated by commas)", dest='resolvers', required=False) parser.add_argument('-L', '--resolver-list', help="File containing list of resolvers", dest='resolver_list', required=False) parser.add_argument('-T', '--tld', action="store_true", help="Scan for TLDs", dest='tld') parser.add_argument('-o', '--output', help="Write output to a file", dest='output_filename', required=False) parser.add_argument('-i', '--output-ips', help="Write discovered IP addresses to a file", dest='output_ips', required=False) parser.add_argument('-D', '--domain-first', action="store_true", help='Output domain first, rather than IP address', dest='domain_first') parser.add_argument('-N', '--no-ip', action="store_true", help='Don\'t print IP addresses in the output', dest='no_ip') parser.add_argument('-v', '--verbose', action="store_true", help='Verbose mode', dest='verbose') parser.add_argument('-n', '--nocheck', action="store_true", help='Don\'t check nameservers before scanning', dest='nocheck') parser.add_argument('-q', '--quick', action="store_true", help='Only perform zone transfer and subdomains scan, with minimal output to file', dest='quick') args = parser.parse_args() def setup(): global targets, wordlist, queue, resolver, recordtype, outfile, outfile_ips if args.domain: targets = args.domain.split(",") if args.tld and not args.wordlist: args.wordlist = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tlds.txt") else: if not args.wordlist: # Try to use default wordlist if non specified args.wordlist = os.path.join(os.path.dirname(os.path.realpath(__file__)), "subdomains.txt") # Open file handle for output try: outfile = open(args.output_filename, "w") except TypeError: outfile = None except IOError: out.fatal("Could not open output file: " + args.output_filename) sys.exit(1) if args.output_ips: outfile_ips = open(args.output_ips, "w") else: outfile_ips = None try: wordlist = open(args.wordlist).read().splitlines() except: out.fatal("Could not open wordlist " + args.wordlist) sys.exit(1) # Number of threads should be between 1 and 32 if args.threads < 1: args.threads = 1 elif args.threads > 32: args.threads = 32 queue = Queue.Queue() resolver = dns.resolver.Resolver() resolver.timeout = 1 resolver.lifetime = 1 if args.resolver_list: try: resolver.nameservers = open(args.resolver_list, 'r').read().splitlines() except FileNotFoundError: out.fatal("Could not open file containing resolvers: " + args.resolver_list) sys.exit(1) elif args.resolvers: resolver.nameservers = args.resolvers.split(",") # Record type if args.ipv6: recordtype = 'AAAA' elif args.tld: recordtype = 'NS' else: recordtype = 'A' if __name__ == "__main__": global wildcard, addresses, outfile_ips addresses = set([]) out = output() get_args() setup() if args.nocheck == False: try: resolver.resolve('.', 'NS') except dns.resolver.NoAnswer: pass except dns.resolver.NoNameservers: out.warn("Failed to resolve '.' - server may be buggy. Continuing anyway....") pass except: out.fatal("No valid DNS resolver. This can occur when the server only resolves internal zones") out.fatal("Set a custom resolver with -R <resolver>") out.fatal("Ignore this warning with -n --nocheck\n") sys.exit(1) if args.domain_list: out.verbose("Domain list provided, will parse {} for domains.".format(args.domain_list)) if not os.path.isfile(args.domain_list): out.fatal("Domain list {} doesn't exist!".format(args.domain_list)) sys.exit(1) with open(args.domain_list, 'r') as domain_list: try: targets = list(filter(bool, domain_list.read().split('\n'))) except Exception as e: out.fatal("Couldn't read {}, {}".format(args.domain_list, e)) sys.exit(1) for subtarget in targets: global target target = subtarget out.status("Processing domain {}".format(target)) if args.resolver_list: out.status("Using resolvers from: {}".format(args.resolver_list)) elif args.resolvers: out.status("Using specified resolvers: {}".format(args.resolvers)) else: out.status("Using system resolvers: {}".format(",".join(resolver.nameservers))) if args.tld and not '%%' in target: if "." in target: out.warn("Warning: TLD scanning works best with just the domain root") out.good("TLD Scan") add_tlds(target) else: queue.put(target) # Add actual domain as well as subdomains # These checks will all fail if we have a custom injection point, so skip them if not '%%' in target: nameservers = get_nameservers(target) out.good("Getting nameservers") targetns = [] # NS servers for target nsip = None try: # Subdomains often don't have NS recoards.. for ns in nameservers: ns = str(ns)[:-1] # Removed trailing dot res = lookup(ns, "A") for rdata in res: targetns.append(rdata.address) nsip = rdata.address print(nsip + " - " + col.brown + ns + col.end) if not args.quick: if outfile: print(nsip + " - " + ns, file=outfile) zone_transfer(target, ns, nsip) except SystemExit: sys.exit(0) except: out.warn("Getting nameservers failed") out.warn("Zone transfer failed\n") if args.zonetransfer: sys.exit(0) if not args.quick: get_v6(target) get_txt(target) get_dmarc(target) # These checks need a proper nameserver, the systemd stub doesn't work if nsip: get_dnssec(target, nsip) else: get_dnssec(target, resolver.nameservers[0]) get_mx(target) wildcard = get_wildcard(target) for wildcard_ip in wildcard: try: addresses.add(ipaddr(unicode(wildcard_ip))) except NameError: addresses.add(ipaddr(str(wildcard_ip))) out.status("Scanning " + target + " for " + recordtype + " records") add_target(target) for i in range(args.threads): t = scanner(queue) t.daemon = True t.start() try: for i in range(args.threads): t.join(1024) # Timeout needed or threads ignore exceptions except KeyboardInterrupt: out.fatal("Caught KeyboardInterrupt, quitting...") if outfile: outfile.close() sys.exit(1) print(" ") if outfile_ips: for address in sorted(addresses): print(address, file=outfile_ips) if outfile: outfile.close() if outfile_ips: outfile_ips.close()
20,966
Python
.py
486
31.950617
159
0.56094
rbsec/dnscan
1,114
411
6
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,524
setup.py
florianfesti_boxes/setup.py
#!/usr/bin/env python3 import glob import os import subprocess import sys from pathlib import Path from subprocess import CalledProcessError, check_output from setuptools import find_packages, setup from setuptools.command.build_py import build_py class CustomBuildExtCommand(build_py): """Customized setuptools install command - prints a friendly greeting.""" script_path: Path = Path("scripts") def buildInkscapeExt(self) -> None: try: subprocess.run([sys.executable, str(self.script_path / "boxes2inkscape"), "inkex"], check=True, capture_output=True, text=True) except CalledProcessError as e: print("Could not build inkscape extension because of error: ", e) print("Output: ", e.stdout, e.stderr) def updatePOT(self) -> None: try: subprocess.run([sys.executable, str(self.script_path / "boxes2pot"), "po/boxes.py.pot"], check=True, capture_output=True, text=True) subprocess.run(["xgettext -L Python -j --from-code=utf-8 -o po/boxes.py.pot boxes/*.py scripts/boxesserver scripts/boxes"], shell=True, check=True, capture_output=True, text=True) except CalledProcessError as e: print("Could not process translation because of error: ", e) print("Output: ", e.stdout, e.stderr) def generate_mo_files(self): pos = glob.glob("po/*.po") for po in pos: lang = po.split(os.sep)[1][:-3].replace("-", "_") try: os.makedirs(os.path.join("locale", lang, "LC_MESSAGES")) except FileExistsError: pass os.system(f"msgfmt {po} -o locale/{lang}/LC_MESSAGES/boxes.py.mo") self.distribution.data_files.append( (os.path.join("share", "locale", lang, "LC_MESSAGES"), [os.path.join("locale", lang, "LC_MESSAGES", "boxes.py.mo")])) def run(self): if self.distribution.data_files is None: self.distribution.data_files = [] self.execute(self.updatePOT, ()) self.execute(self.generate_mo_files, ()) self.execute(self.buildInkscapeExt, ()) if 'CURRENTLY_PACKAGING' in os.environ: # we are most probably building a Debian package # let us define a simple path! path="/usr/share/inkscape/extensions" self.distribution.data_files.append((path, [i for i in glob.glob(os.path.join("inkex", "*.inx"))])) self.distribution.data_files.append((path, ['scripts/boxes'])) self.distribution.data_files.append((path, ['scripts/boxes_proxy.py'])) else: # we are surely not building a Debian package # then here is the default behavior: try: path = check_output(["inkscape", "--system-data-directory"]).decode().strip() path = os.path.join(path, "extensions") if not os.access(path, os.W_OK): # Can we install globally # Not tested on Windows and Mac path = os.path.expanduser("~/.config/inkscape/extensions") self.distribution.data_files.append((path, [i for i in glob.glob(os.path.join("inkex", "*.inx"))])) self.distribution.data_files.append((path, ['scripts/boxes'])) self.distribution.data_files.append((path, ['scripts/boxes_proxy.py'])) except (CalledProcessError, FileNotFoundError) as e: print("Could not find Inkscape. Skipping plugin files.\n", e) pass # Inkscape is not installed build_py.run(self) setup( packages=find_packages(), cmdclass={ 'build_py': CustomBuildExtCommand, }, )
3,732
Python
.py
72
41.486111
191
0.619792
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,525
boxes.py.mo
florianfesti_boxes/locale/de/LC_MESSAGES/boxes.py.mo
fiï-Ñ?Ï2ËCπÈCN£EÏÚEflFÛFG G7GB<G.G3ÆGD‚GX'HÄHÑHB°H‰HÌH1ˇH1I&DIkI |IÜI ôI¶IºI√I”I(ÔIJ.JICJBçJ–JÿJ"ÈJ K<K.MK|KúK1∏K'ÍKL(.L!WL'yL°L.∑L'ÊL-M <M]M6yM∞M–M ÷M·MÒM˙M¸MNNN,N/HN8xN8±N ÍNÙN OO*(OSOhO"jOçOûOµOÕO+ÏOP%2P*XPÉPùPªPœPÿPÍPÚP QQ $Q1Q4GQ/|Q!¨QŒQ◊QÈQÎQ˙QR&R(R0RARJR\ReRwRÄRíRõR≠R∂R »R“RÂRSSS])SáSèSóSüSßS&∏SflSÂSÙS&˝SE$TjTTÅTâTëTôT≤TªTÕT·TˆTUU1)U[U%vU%úU¬U›U ‚U7U(V*V=V0YVäV,åVπVªVΩV√V “V›VÒVÛV ˜VWW,W#GWkWÛpW dXÖX úX¶XVπX YY1YOYdY/fYñY©Y±Y ¬YÃY1flY1ZCZLZ^ZgZ yZÉZ)ñZ¿Z¬Z ≈Z“ZËZÌZ"ˇZ)"[ L[6V[ç[ †[´[ø[»[1⁄[0 \ =\K\R\b\d\ f\p\ É\ç\†\®\π\»\fi\˙\(]=]M] f]q]Ö]é] †] ´] ∂] ¡] Ã]◊]Efi]$^/4^ d^o^ É^ç^†^#¢^∆^Œ^Í^__=_X_j_!Ñ_ ¶_«_‚_˝_#`>`!D`f`n`-Ö` ≥`æ`,“` ˇ` a3a Ra:^a ôa∫a√a”aÏabb/bHbYb sbÅbòb¨b…bfib¸bc1cBc\cqcècóc®c ¿cÃc?·c !d.d*Ddodsdxd{dòêd)eFe*be çe õe®eæeH√e ff +f 6fBfWfpfyf(ãf¥fΩfœf—f ÷f‰fÙf gg0g=9gwg ygÉgñg©gΩg›gÊg¯g˚gii< i"Fiii+xi§iµi∏iºi’i€iÎi( j 4j @j Kj Wj bjmjrj tj Äj ãjïjûj£j ®jµj ≈j —j ›j%Îjkk5kRkTk Wk ck mk xkÇkäk°k ßk±k∆k Õk ÿkAÂk'l-l/l2l5l8l;lAl Pl[lalulÜlúl∫lœl·lˆl mmm/m-Cm,qmûm∏m(”m¸mn#'nAKnçn¶n≈nfln˚no1)o&[oÇo,†o(Õo ˆo p pp)p)2p/\påp ìp †p≠p±p≥pÕpÂp˛p q7 q Xq cq0Ñq-µq„q r rrr-r/r2r$9r^rcr irwr~rór(úr)≈rÔrır¯r˙r˝r$s (s4s Ds OsYs [s hs5ts™s±s«sÁs¸st6&t]tot%Çt®t&≈tÏt$ u/u%AuguÜuéuñuûu¶u≠u¿u »u”u-÷uvv v (v4v 9vFv Ov\vavsv1yv)´v’v◊v›v˜v+ w$5wZw,rwbüwx(x+Dxpxãxíx ´x µx¿x¬xƒx”x ’xflx ‰x3Óx"y5y<yVyuy}yÖyçyïyùy °y2´y fiyÎyÌy Úy ˇy zz?1z qz|z Éz êz öz§z¨z zÈzÚz¯z˝z{!{O={ ç{ò{ö{ ≠{ ∏{≈{ {Œ{’{$Ï{#|5|O|`|r|Ç|&í|π|*…| Ù|!}7}R}n} Ñ}•}∏}∫}¡}∆} }0›}~~ ~+~G~P~"j~ç~è~;ì~9œ~  )1:T Zf;kß ´∏«=÷+Ä@ÄHÄ bÄpÄsÄuÄwÄ~ÄÖÄ-ôīćÄÔÄÅ(!Å-JÅxÅ òÅπÅŒÅÓÅ ÛÅ ˇÅ Ç Ç Ç$Ç,Ç<Ç>ÇDÇKÇ RÇ\Ç lÇ∏wÇ10É1bÉîÉ £ÉÆÉ∂ÉæÉ∆ÉŒÉ÷ÉfiÉÊÉÓɈÉ4˛É3Ñ6Ñ=ÑCÑJÑQÑXÑ']Ñ ÖÑ êÑõÑ°ÑæÑ#ƒÑ.ËÑÖ8-ÖfÖ!nÖêÖôÖ&†Ö«ÖŒÖ÷ÖflÖ˙ÖÜÜ#Ü)Ü=ÜVÜ_ÜqÜ uÜÄÜÉÜÜÜàÜçÜìÜöÜ °Ü-´ÜCŸÜá 7á BáOá Sá ]ájá:sáÆá∑áªáœá?‰á$à*à0à6à<àBàDàLàeàgà làwà}à$Çàßà≠à√à€àÍàâIâbâ.wâ5¶â‹âÓâä-!äOäoä.Öä¥ä#«ä Îä¯ä ã(ã*ã,ã@.ãπoå?)éiéÅèóèµèÃèÊèFÎè72ê=jê'®êt–êEë*IëCtë ∏ëƒë›ëÛëí $í2í"Oírí+ãí∑í'∆í6Óí.%ìTìsì3èìA√ìîî!*îLî6Rî8âî6¬î˘îH ï:Uïêï(≠ï2÷ï+ ñ5ñ6Nñ/Öñ6µñ1Ïñ3óGRó(öó√ó  ó’óÙó˝óˇó'ò?òDòYòGrò@∫ò@˚ò<ô%Oôuô âô/™ô#⁄ô˛ô!ö"ö8öRönö.âö∏ö7Œö%õ,õ$Fõkõäõ ôõ∫õ¬õ ‹õËõ úú70ú2hú"õúæú"ŒúÒúÛú&ù.ùLùNù`ù|ùÖù°ù™ù∆ùœùÎùÙùûû 3û=û'ZûÇûàûúûC∂û˙ûü üüü,0ü ]ühüÅü.âüM∏ü†††%†-†5† O†Y†s†é†§†∏†Æ3Á†>°)Z°3Ѱ∏°’°€°LÔ°<¢!>¢`¢0{¢¨¢EÆ¢Ù¢ˆ¢¯¢£ £$£>£@£D£"Y£|£"å£/Ø£ fl£È£#•%•7•F•tc•ÿ•·•$ˆ•¶-¶4/¶d¶ Ŷé¶ ß¶≥¶EÕ¶CßWß`ßwßÄß óß°ß9πßÛßıß ¯ß®®&®(:®2c®ñ®0ß®ÿ®˜® © "©0©4L©-ũة ¬©–©Ï©Ó© ©˙© ™™4™<™ R™^™}™è™.¢™—™‚™Ù™" ´,´5´ L´ W´ b´ m´ x´É´Iä´‘´>È´(¨:¨Z¨ s¨î¨8ñ¨œ¨◊¨ı¨≠'2≠Z≠x≠ó≠0Æ≠'fl≠(Æ,0Æ#]Æ)ÅÆ´Æ≤ÆÕÆ’Æ:Æ+Ø:Ø:WØ íØûØU∏Ø∞E!∞g∞Ü∞è∞#•∞…∞·∞˝∞±3±M±k±}±ù±≥±Õ±‰±ˇ±≤2≤G≤`≤#Ä≤§≤¨≤¬≤ ⁄≤Ë≤F≥I≥ ]≥H~≥«≥À≥–≥E”≥¨¥∆¥!fi¥,µ#-µ Qµ_µsµKzµ ∆µ‘µ͵˘µ∂$∂C∂U∂8i∂ ¢∂≠∂∆∂»∂Õ∂‡∂˚∂∑∑;∑CD∑à∑ä∑†∑∏∑‘∑ Î∑ ∏∏.∏1∏FπHπKKπ óπ∏π1Õπˇπ∫∫∫6∫=∫W∫2r∫•∫∫∫Œ∫ „∫ Ò∫ˇ∫ªª ª $ª 0ª;ª MªXªgª xª Ѫ íª/ûªŒª‘ª=Ÿªººº -º 8º Dº Qº^ºxº º âº óº £º ƺGªº Ω ΩΩΩΩΩΩ!Ω 0Ω:Ω@ΩUΩiΩÑΩ §Ω∞Ω¡Ω ”ΩflΩ ÂΩÒΩæ1"æ0TæÖæ!¢æ0ƒæıæø!øL8øÖø!õøΩø‘øÔø¿<¿"R¿!u¿5ó¿/Õ¿˝¿¡¡ +¡ 9¡*D¡4o¡§¡ ¨¡ ∫¡»¡áŒ¡#Ë¡$ ¬1¬ O¬;\¬ ò¬+•¬4—¬5√-<√j√ }√ â√î√¨√Æ√±√&∏√fl√Â√Ì√¸√ƒ"ƒ!'ƒ#Iƒ mƒyƒ|ƒ~ƒŃ%რ≠ƒπƒ œƒ ⁄ƒʃ ˃ Ûƒ:ˇƒ:≈@≈'U≈}≈ï≈ Ø≈6ª≈Ú≈∆$∆=∆%T∆z∆$ï∆∫∆%Ã∆Ú∆«« «'«.«4«G« _«i«,l« ô«ß«∑« À«ÿ«fi« Ó« ˙«» »%»?+»=k»©»´»±»»»8Ÿ»….…9E…}…˝…$ 98 r å ì  Ø π ¡ √  ≈ —  ” ·  Á =Û 1ÀCÀJÀ!`ÀÇÀäÀíÀöÀ¢À™À ±À>ΩÀ¸À Ãà à à *Ã7ÃISà ùéà ∞à ºÃ «Ã‘ËÃ"¯Ã Õ)Õ/Õ4Õ;ÕQÕZiÕƒÕŸÕ€ÕÛÕ ŒŒŒŒŒ,2Œ$_ŒÑŒûŒ±Œ √Œ –Œ+€Œ œœ 2œ Sœ!tœñœÆœŒœÍœ–– –––.4–c– j–u–â– §–Æ–1…–˚–˝–K—9M—á—ù— £— Ø— º—…——Ì—¸—?“N“R“e“ u“IÉ“(Õ“ˆ“˝“ ”” ”"”$”+” 2”/@”p” Ü” ë”ù”+∞”1‹” ‘&/‘V‘m‘à‘ è‘õ‘§‘ ´‘ ∏‘∆‘ Œ‘Ÿ‘€‘ ‰‘ Ó‘ ¯‘’’…(’EÚ’C8÷|÷ é÷ô÷°÷©÷±÷π÷¡÷…÷—÷Ÿ÷·÷AÈ÷+◊.◊6◊<◊C◊J◊R◊%Z◊ Ä◊ ç◊õ◊0£◊‘◊3‹◊(ÿ9ÿ9Uÿ èÿ(ùÿ ∆ÿ‘ÿ=⁄ÿ Ÿ %Ÿ1Ÿ 9ŸZŸzŸÇŸâŸéŸ!≠Ÿ œŸ‹ŸÔŸ ÛŸ˛Ÿ⁄⁄⁄⁄⁄⁄!⁄$)⁄=N⁄å⁄ú⁄´⁄ ø⁄ …⁄◊⁄Í⁄M˙⁄H€P€U€l€eã€Ò€ˆ€˚€‹‹ ‹ ‹(‹>‹@‹ E‹Q‹X‹1^‹ê‹ó‹ ∞‹—‹ ‹›d!›Ü›1ó›7…›fifi*fi*Ffiqfiäfi-¢fi–fi ‚fi fl fl!fl;fl=fl?fl/ÛeóA∑π*Ù™∫«rzF=QÄfi K<ëy2UN˝¨ÿûÀ”‡FáØÙè ¨˝Í~íV>Mgkãü£`¶´öçÕ·‚#Z#—˜ѯÁh;åO/÷ÓÒ3l„HfPÖûµÚß?@vBIò∏flõÆÅdl,:,@Ÿ6Ë≠$™πDu…G •A≥ëΩî8Õè˜U(^˛9˘*±ï"l.-!Ç∆Aƒ,J$ú–‡4¢ˆ}=ÃD 46GÔ_µ}üùE-â y+XÌÇ>áo’«∞k˙5VÆdLæ⁄°äÿî¬∂≈aî ŒÏÚX|f±®}f?ˇ'≤("ƒÑ„¯2xÛI:‚ QS$˚• ô≈òȉ ˙ôUÉá5©Ïã˛‘»÷ÉcK˝+08| Ùo®fi°Í`¸')ø6ˇ°ºC‹&≥ı'sYJı9Idøñ•Ñj\m—›ÒÅ˘¸3k–Ë÷|ö⁄ªéÁ≈h^v´zF&ìã$+{Zin’›Íõõ-ñ\ÂÌÆÁôqΩó◊Rwºx1ïÛï+ù.flʪúR¨xíZüº‹È€oËeß2tNp¶µœ∞ ’¸∂Øπ …= Ü%aY1u<¶†jj{i;∞\æcÃ∫E* Q]Mfiˇq “å*··<zyT¿¢päO)É9nprt”?Ì¿a[¥Îr∆;C@] £ÎSKXà◊Äò_≤¡® :≤ç∑ à…Œù ë¡∑ƒÎ7Ãw.¥u‰n %©¡~H›À&≠æ%OêÓ–§0†”ÒÇ%q«EmÈØ!,>#˜‰éR´¥“~€P©Lÿ3ŒW ∫Óé¯fl∆SPVDâ√˚`êM≥ ⁄ÖÂ4Ÿóœ'B5Ô¬“‹¢0£cñÅ#Ê˘N/!§[J∏gTå„bg-7 Ö≠ßTè)€[w¬ø 8—Ü윟¿mb»Úˆª∂íY‘û◊"êˆ∏ìsÏ√t˛CG ÕHàú»ÜıÊse§_7™Ä( À)1†"Bh√LÂ(b] ä±i{!â˚ΩçW&‘v˙Ô‚Wö‡^ <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Cuttlery stand with carrying grip using flex for rounded corners Vitamins: DSP5005 (or similar) power supply, two banana sockets, two 4.8mm flat terminals with flat soldering tag To allow powering by laptop power supply: flip switch, Lenovo round socket (or adjust right hole for different socket) "outset" or "flush""spring", "stud" or "none""wave" or "bumps"# pieces of outer wall40DPA Type tray variant to be used up right with sloped walls in frontA clamp to hold down material to a knife tableA hook wit a rectangular mouth to mount at the wallA rack for storing disk-shaped objects vertically next to each otherA two piece box where top slips over the bottom half to form the enclosure. AT5Add external mounting pointsAdditional space kept between the disks and the outbox of the rackAllEdgesAllEdges SettingsAmount of circumference used for non convex partsAn error occurred!Angle between convex and concave partsAngle of the cutAngledBoxAngledBox SettingsAngledCutJigAngledCutJig SettingsArcadeArcade SettingsBackwards slant of the rackBalanced force Difference Planetary GearBar to hang pliers onBass Recorder EndpinBench power supply powered with Maktia 18V battery or laptop power supplyBeware of the rolling shutter effect! Use wax on sliding surfaces.BinTrayBinTray SettingsBook cover with flex for the spineBoxBox for drills with each compartment with a different heightBox for holding a stack of paper, coasters etcBox for storage of playingcardsBox in the form of an heartBox various options for different stypes and lidsBox with a rolling shutter made of flexBox with both ends corneredBox with different height in each cornerBox with lid and integraded hingeBox with lid attached by cabinet hingesBox with living hingeBox with living hinge and left corners roundedBox with living hinge and round cornersBox with living hinge and top corners roundedBox with regular polygon as baseBox with top and front openBox with various options for different styles and lidsBox with vertical edges roundedBoxesBoxes - %sBoxes with flexBoxes.pyCCardBoxCardBox SettingsCastleCastle SettingsCastle tower with two wallsClosed box with screw on top and mounting holesClosed box with screw on top for mounting in a 10" rack.Closed box with screw on top for mounting in a 19" rack.ClosedBoxClosedBox SettingsConcaveKnobConcaveKnob SettingsCreate boxes and more with a laser cutter!Cutup to mouth ratioDD-Flat in fraction of the diameterDefault SettingsDefaultParams SettingsDesktop Arcade MaschineDiameter of the bolt hole (mm)Diameter of the inner lid screw holes in mmDiameter of the knob (mm)Diameter of the lid screw holes in mmDiameter of the mounting screw holes in mmDiameter of the paintcansDiplay for flyers or leafletsDisc diameter in mmDiscRackDiscRack SettingsDisplayDisplay SettingsDisplayCaseDisplayCase SettingsDisplayShelfDisplayShelf SettingsDistance in halftones in the Normalmensur by T√∂pferDistance of the screw holes from the wall in mmDocumentation and API DescriptionDrillBoxDrillBox SettingsEElectronicsBoxElectronicsBox SettingsError generating %sFFlexBoxFlexBox SettingsFlexBox2FlexBox2 SettingsFlexBox3FlexBox3 SettingsFlexBox4FlexBox4 SettingsFlexBox5FlexBox5 SettingsFlexTestFlexTest SettingsFlexTest2FlexTest2 SettingsFoam soles for the OttO botFolderFolder SettingsFully closed boxFully closed box intended to be cut from transparent acrylics and to serve as a display case.GT2_2mmGT2_3mmGT2_5mmGearBoxGearBox SettingsGearbox with multiple identical stagesGearsGears SettingsGenerateGenerate a typetray from a layout fileGenerators are still untested or need manual adjustment to be useful.Get Source at GitHubHHTD_3mmHTD_5mmHTD_8mmHackaday.io Project PageHeartBoxHeartBox SettingsHeight of the cardsHeight of the handleHeight of the paintcansHingeBoxHingeBox SettingsHint of how much the flex part should be shortendHold a plane to a slatwallHold a set of wrenches at a slat wallHolds a single caliper to a slat wallHoney Comb Style Wine RackHookHook SettingsHook for pole like things to be clamped to another poleIIntegratedHingeBoxIntegratedHingeBox SettingsIntonation Number. 2 for max. efficiency, 3 max.JJig for making angled cuts in a laser cutterKLLBeamLBeam SettingsLaserClampLaserClamp SettingsMMXLMagazineFileMagazineFile SettingsMakitaPowerSupplyMakitaPowerSupply SettingsMinimum space between the paintcansMiscMost of the blue lines need to be engraved by cutting with high speed and low power. But there are three blue holes that actually need to be cut: The grip hole in the lid and two tiny rectangles on the top and bottom for the lid to grip into. Mounting braket for a Nema motorNema size of the motorNemaMountNemaMount SettingsNot yet parametrized box for drills from 1 to 12.5mm in 0.5mm steps, 3 holes each sizeNotesHolderNotesHolder SettingsNumber of rounded top cornersNumber of serrationsOOctave in International Pitch Notation (2 == C)Open magazine fileOpenBoxOpenBox SettingsOrganPipeOrganPipe SettingsOtto LC - a laser cut chassis for Otto DIY - bodyOtto LC - a laser cut chassis for Otto DIY - legsOttoBodyOttoBody SettingsOttoLegsOttoLegs SettingsOttoSolesOttoSoles SettingsOutset and angled plate to mount stuff toPPaPaintStoragePaintStorage SettingsPartParts and SamplesPiece for testing 2D flex settingsPiece for testing different flex settingsPlanetaryPlanetary Gear with possibly multiple identical stagesPlanetary SettingsPlanetary2Planetary2 SettingsPoleHookPoleHook SettingsPosition of the lower rack grids along the radiusPosition of the rear rack grids along the radiusProfile shiftPulleyPulley SettingsQRRack10BoxRack10Box SettingsRack19BoxRack19Box SettingsRackBoxRackBox SettingsRadius of combRadius of the cornersRadius of the corners in mmRadius of the latch in mmRectangular organ pipe based on pipecalcRectangularWallRectangularWall SettingsRegularBoxRegularBox SettingsRobotArmRobotArm SettingsRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotary Attachment for engraving cylindrical objects in a laser cutterRotary SettingsRound knob serrated outside for better grippingRoundedBoxRoundedBox SettingsRoyalGameRoyalGame SettingsSSegments of servo powered robot armServo9gSettings for Cabinet HingesSettings for Chest HingesSettings for Click-on LidsSettings for Dove Tail JointsSettings for Finger JointsSettings for FlexSettings for GrippingEdgeSettings for Hinges and HingePinsSettings for RoundedTriangleEdgeSettings for SlatWallEdgesSettings for Slide-on LidsSettings for Stackable EdgesSettings for rack (and pinion) edgeShelfShelf with forward slanted floorsShelvesShowing all edge typesShows the different edge types for slat wallsShutterBoxShutterBox SettingsSides of the triangles holding the lid in mmSilverwareSilverware SettingsSimple L-Beam: two pieces joined with a right angleSimple wallSlat wall tool holder for chisels, files and similar toolsSlat wall tool holder with slotsSlatWallSlatwallCaliperSlatwallCaliper SettingsSlatwallChiselHolderSlatwallChiselHolder SettingsSlatwallConsoleSlatwallConsole SettingsSlatwallDrillBoxSlatwallDrillBox SettingsSlatwallEdgesSlatwallEdges SettingsSlatwallPlaneHolderSlatwallPlaneHolder SettingsSlatwallPliersHolderSlatwallPliersHolder SettingsSlatwallSlottedHolderSlatwallSlottedHolder SettingsSlatwallTypeTraySlatwallTypeTray SettingsSlatwallWrenchHolderSlatwallWrenchHolder SettingsStachelStachel SettingsStackable paint storageStorageRackStorageRack SettingsStorageRack to store boxes and trays which have their own floorStorageShelfStorageShelf SettingsStorageShelf can be used to store TypetrayT10T2_5T5The Royal Game of UrThe traffic light was created to visualize the status of a Icinga monitored system. When turned by 90¬∞, it can be also used to create a bottle holder.Thickness of the discs in mmThis is a simple shelf box.Timing belt pulleys for different profilesTraffic lightTrafficLightTrafficLight SettingsTrayTray insert without floor and outer walls - allows only continuous wallsTrayInsertTrayInsert SettingsTrayLayoutTrayLayout2TrayLayout2 SettingsTrays and Drawer InsertsTwoPieceTwoPiece SettingsType tray - allows only continuous wallsTypeTrayTypeTray SettingsUUBoxUBox SettingsUnevenHeightBoxUnevenHeightBox SettingsUniversalBoxUniversalBox SettingsUnstableUse hexagonal arrangement for the holes instead of orthogonalVWaivyKnobWaivyKnob SettingsWidth of the cardsWidth of the handleWidth of the hex bolt head (mm)WineRackWineRack SettingsXLYou need a tension spring of the proper length to make the clamp work. Increace extraheight to get more space for the spring and to make the sliding mechanism less likely to bind. You may need to add some wax on the parts sliding on each other to reduce friction. aa#add a lid (works best with high corners opposing each other)additional height of the back walladditional lidadditional lid (for straight top_edge only)additional_depthaiallamount of hooks / bracesangleangle of floorsangle of the support underneethangle of the teeth touching (in degrees)angled holeangled lidangled lid2anklebolt1anklebolt2axlebback_heightbeamheightbeamwidthboltholeborebothbottom_depthbottom_diameterbottom_edgebottom_hookbottom_radiusbracing angle - less for more bracingbumpsburnburn correction in mm (bigger values for tighter fit)cc#candiametercanheightcardheightcardwidthchamferchamfer at the cornerschestclearanceclearance of the lidclosedconnectioncornerradiuscreate a ring gear with the belt being pushed against from withincutupdd#d1d2d3debugdefault (none)deltateethdepthdepth at the bottomdepth at the topdepth behind the lotsdepth of slots from the frontdepth of the groovesdepth of the rackdepth of the shadersdepth of the sidesdholediameterdiameter at the bottomdiameter at the topdiameter for hole for ankle bolts - foot sidediameter for hole for ankle bolts - leg sidediameter if the pin in mmdiameter of alignment pinsdiameter of lower part of the screw holediameter of the axlediameter of the axlesdiameter of the flutes bottom in mmdiameter of the hole for the tool (handle should not fit through)diameter of the pin holediameter of the pin hole in mmdiameter of the pin in mmdiameter of the screw in mmdiameter of the shaftdiameter of the shaft 1diameter of the shaft2 (zero for same as shaft 1)diameter of the strings of the O ringsdiameter of the thing to hookdiameter of the tool including space to grabdiameter of upper part of the screw holedimensiondisc_diameterdisc_outsetdisc_thicknessdistancedistance from finger holes to bottom edgedistance of flex cuts in multiples of thicknessdoubledpercentage1dpercentage2dxfeedge type for bottom edgeedge type for left edgeedge type for right edgeedge type for top edgeedge_widthenable secondary ring with given delta to the ring geareverythirdextend outward the straight edgeextend the triangle along the length of the edgeextra height to make operation smoother in mmextra space to allow movementextra_heightextraheighteyeeyes_per_hingeff#fingerfixed length of the grips on he lidsflatflushflutediameterformatformat of resulting filefourfraction of bin height covert with slopefrom one middle of a dove tail to anotherfrontfwgg#gcodegreater zero for top wider as bottomgrip_lengthgrip_percentagegripheightgripwidthhhandleheighthandlewidthhave lid overlap at the sides (similar to OutSetEdge)heightheight above the wallheight difference left to rightheight in rack unitsheight of front wallsheight of lid in mmheight of the (aluminium) profile connecting the partsheight of the boxheight of the feetheight of the front left corner in mmheight of the front of planeheight of the front right corner in mmheight of the grip hole in mmheight of the left back corner in mmheight of the lidheight of the right back corner in mmheight of the screw head in mmheight0height1height2height3heigthheigth of the bodyhexheadhexpatternhihigher values for deeper serrations (degrees)hinge_strengthhingeshingestrengthhold_lengthholeholediameterholedistholedistancehookhook_extra_heighthookshow far the dove tails stick out of/into the edgehow much should fingers widen (-80 to 80)iin Pain precent of the modulusinner depth in mminner depth in mm (unless outside selected)inner depth not including the shadesinner depth of the hookinner height in mm (unless outside selected)inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)inner height of the hookinner radius if the box (at the corners)inner width in mm (unless outside selected)inner width of the consoleinsideinside angle of the feetinsideoutintonationjkknifethicknessllatchsizeleftleft_edgelegth of the part hiolding the plane over the frontlegth of the planelengthlength of legs (34mm min)length of segment axle to axlelength1length2length3length4length5lidlidheightlimit the number of planets (0 for as much as fit)lower_factormmBarmax_strengthmax_widthmaxheightmaximal clamping height in mmmaximum space at the start and end in multiple of normal spacesmaxplanetsmensurmin_strengthmin_widthminheightminimalminimal clamping height in mmminimum space around the hingeminspacemmH2OmmHgmodulusmodulus of the gear (in mm)modulus of the theeth in mmmouth to circumference ratio (0.1 to 0.45). Determines the width to depth ratiomouthrationnema size of motornema_mountno_verticalsnonenumnumbernumber of compartmentsnumber of compartments back to frontnumber of compartments side by sidenumber of hinges per edgenumber of lightsnumber of shelvesnumber of sidesnumber of solesnumber of stages in the gear reductionnumber of teethnumber of teeth in the other size of gearsnumber of teeth on ingoing shaftnumber of teeth on outgoing shaftnumber of teeth on planetsnumber of teeth on sun gearnumber of tools/slotsnumber of walls at one side (1+)number of wrenchesooctaveoddsoneoptional argumentsouter diameter of the wheels (including O rings)outsetoutsideoutsidemountsoverall width for the toolsoverhangoverhang for joints in mmoverlap of top rim (zero for none)ppdfpercent of the D section of shaft 1 (0 for same as shaft 1)percent of the D section of shaft 1 (100 for round shaft)pieces per hingepinpin_heightpinsizepinwidthpipe is closed at the toppitchplanetteethplayplay between the two parts as multipleof the wall thicknesspltpolediameterpressure anglepressure_angleprint reference rectangle with given length (zero to disable)print surrounding boxes for some structuresprofileprofile of the teeth/beltprofile_shiftpsqrr_holeradiusradius at the slotsradius for strengthening walls with the hooksradius of bottom cornersradius of holeradius of the cornersradius of the corners in mmradius of the disc rotating in the hingeradius of the eye (in multiples of thickness)radius of the lids living hingeradius of the slots at the frontradius of top cornerradius used on all four cornersrailrear_factorreferencerightright_edgeround lidroundedrubberthicknesssscrewscrew1screw2screwheadscrewheadheightsecond_pinsections back to front in mm. Possible formats: overallwidth/numberof sections e.g. "250/5"; sectionwidth*numberofsections e.g. "50*5"; section widths separated by ":" e.g. "30:25.5:70sections bottom to top in mm. See --sy for formatsections left to right in mm. See --sy for formatserrationangleserrationsservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bset to lower value to get disks surrounding the pinsshshadesshaftshaft1shaft2singlesizesize of latch in multiples of thicknessslot_depthslot_widthslotsslots for grabbing the notesspacespace below holes of FingerHoleEdgespace between eyes (in multiples of thickness)space between fingersspace surrounding connectors (in multiples of thickness)spacingsplit the lid in y direction (mm)splitlidspringstack lights upright (or side by side)stagesstoppedstrengthstrength of largest wrenchstrength of smallest wrenchstretchstudstylestyle of hinge usedstyle of the top and lidsunteethsurroundingspacessvgsvg_Ponokosxsyttabsteethteeth1teeth2thicknessthickness of the arc holding the pin in placethickness of the knifes in mm. Use 0 for use with honey comb table.thickness of the materialtool_widthtooldiametertoptop_depthtop_diametertop_edgetreat sizes as outside measurements that include the wallstriangletwotype of arm segmenttype of servo to usetype of servo to use on second side (if different is supported)type1type2type3type4type5uuprightuses unit selected belowvwallwallpieceswallswavewhich of the honey comb walls to addwidthwidth of finger holeswidth of largest wrenchwidth of slotswidth of smallest wrenchwidth of sole stripewidth of tabs holding the parts in place in mm (not supported everywhere)width of teeth in mmwidth of th grip hole in mm (zero for no hole)width of the (aluminium) profile connecting the partswidth of the feetwidth of the fingerswidth of the gaps in the cutswidth of the hook (back plate is a bit wider)width of the hook from the sidewidth of the long endwidth of the pattern perpendicular to the cutswidth of the planewidth of the surrounding wall in mmwindpressurewindpressure_unitswith of the screw head in mmxyzProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: 2019-08-23 19:42+0200 Last-Translator: Florian Festi <florian@festi.info> Language-Team: Deutsch Language: de MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Besteckkorb mit Tragegriff und abgerundeten Ecken Vitamins: DSP5005 (oder √§hnliches) Netzteil, zwei Bananenstecker, zwei 4,8-mm-Flachanschl√ºsse mit flacher L√∂tfahne Um die Stromversorgung per Laptop-Netzteil zu erm√∂glichen: Kippschalter umlegen,Lenovo-Rundstecker (oder Passe rechtes Loch f√ºr verschiedene Anschl√ºsse an) "Anfang" or "B√ºndig""Feder", "Bolzen" or "nichts""Wellen" oder "Beulen"# Teil der √§u√üeren Wand40DPAufbewahrungsbox f√ºr loses Material mit vorne abgeschr√§gter √ñffnungEine Klemme um Material auf einem Messertisch zu haltenHaken mit abgeflachter Endung zur Montage an einer SeitenwandEine Ablage f√ºr scheibenartige ObjekteEine zweiteilige Schachtel, bei der die Oberseite √ºber die untere H√§lfte gleitet, um das Geh√§use zu bilden. AT5F√ºgt √§u√üere Montagem√∂glichkeiten hinzuZus√§tzlicher Abstand zwischen dem Regalraster und den Au√üenkantenalle KantenEinstellung aller KantenBreite der ZahnkonturEin Fehler ist aufgetreten!Tiefe der VerzahnungSchnittwinkelKiste mit abgekanteten EckenEinstellung f√ºr abgekantete KisteAbgekantete SchnittlehreEinstellungen f√ºr abgekantete SchnittlehreArcade-AutomatEinstellungen f√ºr den Arcade-Automatengreater zero for top wider as bottomNeigung der AblageAusgeglichenes Kraftdifferenz-PlanetengetriebeLeiste um Zangen aufzuh√§ngen Endknopf f√ºr Bass-RecorderLabornetzeil aus einem 18V-Makita- oder Laptop-AkkuBeachte den Rollladen-Effekt! Verwende Wachs an den Gleitfl√§chenSch√ºtteEinstellungen f√ºr Sch√ºtteBucheinband mit flexiblem R√ºckenKisteBox f√ºr Bohrer mit jedem Fach mit einer anderen H√∂heKiste, um Notizzettel und √§hnliches darin aufzubewahrenAufbewahrungsbeh√§lter f√ºr Spielkarten und √§hnlichesHerzf√∂rmige KisteKiste mit verschiedenen Optionen f√ºr unterschiedliche Arten von DeckelnKiste mit einem Rollladenverschluss aus flexiblem MaterialBeidseitig abgekantete KisteKiste mit unterschiedlichen Kantenh√∂henKiste mit Deckel und darin eingebundenem ScharnierKiste mit an Scharnieren befestigter DeckelKiste mit BiegescharnierKiste mit Biegescharnier und abgerundeten linken EckenKiste mit Biegescharnier und abgerundeten EckenKiste mit Biegescharnier und abgerundeten oberen EckenKiste mit einem gleichm√§√üigen Vieleck als BasisKiste, bei der die Ober- und Vorderseite offen sindKiste mit verschiedenen Optionen f√ºr verschiedene Varianten und DeckelKiste mit abgerundeten vertikalen KantenKistenBoxes - %sKisten mit abgerundeten KantenBoxes.pyCSpielkartenaufbewahrungEinstellung der SpielkartenaufbewahrungBurgEinstellung der BurgBurg mit zwei BurgmauernGeschlossenes Geh√§use mit Schrauben auf dem Deckel und Montagel√∂chernGeschlossene Box mit Schraubdeckel zum Einbau in einen 10"-Rack.Geschlossene Box mit Schraubdeckel zum Einbau in einen 19"-Rack.Geschlossene KisteEinstellungen der geschlossenen KisteGezahnter DrehknopfEinstellungen f√ºr den DrehknopfEntwirf Kisten und mehr mit einem Laser-Cutter!Zuschnitt des M√ºndungs-Verh√§ltnisDD-Flat am Anteil des DurchmessersStandardeinstellungenParametervoreinstellungenSchreibtisch-Arcade-AutomatDurchmesser der Achse (mm)Durchmesser der inneren Deckelschrauben, in mmKnopfdurchmesser (mm)Durchmesser der L√∂cher f√ºr die Deckelschrauben, in mmDurchmesser der Montagel√∂cher, in mmDurchmesser der FarbdosenAuslage f√ºr Flyer oder Flugbl√§tterDurchmesser der Scheiben in mmScheibenablageEinstellungen der ScheibenablageAuslageEinstellungen der AuslageSchaukastenEinstellungen des SchaukastensSchauregalEinstellungen f√ºr SchauregalAbstand der Halbt√∂ne in der Normalmensur durch T√∂pferAbstand der Montagel√∂chern zu den R√§ndern, in mmDokumentation und API-BeschreibungBohrerhalterungEinstellungen f√ºr BohrerhalterungEElektronik-Geh√§useEinstellungen f√ºr Elektronik-Geh√§useFehler beim Generieren von %sFAbgerundete KisteEinstellungen f√ºr FlexBox FlexBox2Einstellungen f√ºr FlexBox2FlexBox3Einstellungen f√ºr FlexBox3FlexBox4Einstellungen f√ºr FlexBox4FlexBox5Einstellungen f√ºr FlexBox5FlexTestEinstellung f√ºr FlexTestFlexTest2Einstellungen f√ºr FlexTest2Schaumstoffsohlen f√ºr den Otto DIY BotMappeEinstellungen MappeVoll abgeschlossene KisteGedacht als abgeschlossener Schaukasten aus transparenten AcrylglasGT2_2mmGT2_3mmGT2_5mmGetriebeEinstellung GetriebeGetriebe mit mehreren gleichen ZahnradpaarenZahnr√§derEinstellungen Zahnr√§derErzeugeErzeuge ein Setzkasten aus einer EntwurfsdateiGeneratoren sind noch ungetestet oder m√ºssen h√§ndisch nachgebessert werden.Get Source at GitHubHHTD_3mmHTD_5mmHTD_8mmHackaday.io Projekt-SeiteHerzkisteEinstellung der HerzkisteH√∂he der einzelnen KartenH√∂he des TragegriffsH√∂he der FarbdosenKiste mit ScharnierEinstellung ScharnierkisteMa√ü, um wie viel der Flexteil gek√ºrzt werden sollHalterung f√ºr Werkzeug oder √§hnliches an einer SperrholzwandHalterung f√ºr einen Satz Gabelschl√ºsselHalterung f√ºr einen Messschieber an einer Holzwandbienenwabenartiges WeinregalHakenEinstellungen HakenHaken f√ºr stangen√§hnliche Dinge, die an eine andere Stange geklemmt werdenIKiste mit eingebundenen ScharnierEinstellungen ScharnierboxTonfall Nummer. 2 f√ºr max. Wirkungsgrad, 3 max.JVorrichtung zum erstellen von Winkelschnitten in einem LaserschneiderKLL-WinkelEinstellungen L-WinkelLaserklemmeEinstellungen LaserklemmeMMXLZeitschriftensammlerEinstellungen ZeitschriftensammlerMakita-NetzteilEinstellungen Makita-LabornetzteilMinimalabstand zwischen den einzelnen FarbdosenSonstigesDie meisten blauen Linien m√ºssen mit hoher Geschwindigkeit und geringer Strahlkraft eingraviert werden. Allerdings gibt es drei L√∂cher, die herausgeschnitten werden m√ºssen: Das Griffloch am Deckel und die zwei kleinen Rechtecke oben und unten, in die der Deckel greifen kann. Halteklammern f√ºr einen NEMA-MotorNEMA Motorgr√∂√üeNEMA-HalterungEinstellungen NEMA-HalterungNoch nicht parametrisierte Kiste f√ºr Bohrer von 1 bis 12,5 mm in 0,5-mm-Abst√§nden, 3 L√∂cher pro BohrerdurchmesserNotizboxEinstellung NotizboxAnzahl der abgerundeten oberen EckenAnzahl der Z√§hneOOktave in internationaler Tonh√∂hennotation (2 == C)Offener ZeitschriftensammlerOffene KisteEinstellungen offene BoxOrgelpfeifeEinstellungen OrgelpfeifeOtto LC - ein lasergeschnittenes Geh√§use f√ºr den Otto DIY - K√∂rperOtto LC - ein lasergeschnittenes Geh√§use f√ºr die Otto DIY - BeineOttoBodyEinstellungen OttoBodyOttoLegsEinstellungen OttoLegsOttoSolesEinstellungen OttoSolesAbgewinkeltes Armaturenbrett, um darauf Zeug zu montierenPPaFarbenregalEinstellungen FarbenregalBauteilBauteile und MusterTeil, um 2D-Flex-Einstellungen zu testenTeil, um verschiedene Flex-Einstellungen zu testenPlanetengetriebePlanetengetriebe mit mehreren identischen StufenEinstellungen PlanetengetriebePlanetengetriebe2Einstellungen Planetary2StangenklemmeEinstellungen StangenklemmePosition des unteren Regalrasters entlang des RadiusPosition des Ablagegitters entlang des RadiusProfilverschiebungRiemenscheibeEinstellungen RiemenscheibeQRRack10BoxEinstellungen Rack10BoxRack19BoxEinstellungen Rack19BoxRackBoxEinstellungen RackBoxWabenradiusKantenradius des BesteckkorbesEckenradius in mmRiegelradius in mmRechteckige Orgelpfeife basierend auf pipecalcRechteckige WandWandeinstellungenGleichm√§√üige KisteEinstellungen Gleichm√§√üige KisteRobotArmEinstellungen RobotArmRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotationsaufsatz zum Gravieren zylindrischer Objekte in einem LasercutterEinstellungen RotaryRunder Drehknopf mit gezahnter Au√üenkontur f√ºr besseren HaltAbgerundete KisteEinstellungen abgerundete KisteK√∂nigliche Spiel von UrEinstellungen K√∂nigliches SpielSSegmente eines von Servomotoren betriebenen Roboterarms Servo9gEinstellungen KistenscharnierEinstellungen des KastengelenksEinstellung f√ºr KlickdeckelEinstellungen SchwalbenschanzverbindungEinstellung f√ºr FingerzinkenEinstellung f√ºr die Kr√ºmmungEinstellung GreifkanteEinstellungen der Scharniere und ScharnierbolzenEinstellungen f√ºr abgerundete DreieckeEinstellungen f√ºr die LeistenwandkantenEinstellungen f√ºr den aufschiebbaren DeckelEinstellungen f√ºr stapelbare EckenEinstellungen f√ºr Rack- und RitzelkantenAblageRegal mit geneigten B√∂denAblagenZeige alle KantenvariantenZeigt die verschiedenen Kantentypen f√ºr die Leistenw√§ndeRollladenkisteEinstellungen RollladenkisteSeitenl√§nge des Dreiecks, welches den Deckel h√§lt, in mmBesteckkorbEinstellungen BesteckkorbEinfacher L-Winkel: Zwei Seitenteile, die im rechten Winkel zueinander verbunden sindEine einfache WandSperrholz-Werkzeughalter f√ºr Mei√üel, Feilen und √§hnliche WerkzeugeWandhalterung mit Langl√∂chernSlatWallMessschieberhalterungEinstellungen MessschieberhalterungSperrholz-Mei√üelhalterEinstellungen Mei√üelhaltenSperrholz-ArmaturenbrettEinstellungen ArmaturenbrettSperrholz-BohrerhalterungEinstellungen BohrerhalterungLeistenwandkantenEinstellungen LeistenwandkantenSperrholz-PlatzhalterEinstellungen PlatzhalterSperrholz-ZangenhalterEinstellungen ZangenhalterSperrholz-LanglochhalterEinstellungen Langl√∂cherSperrholz-SetzkastenEinstellungen SetzkastenSperrholz-Gabelschl√ºsselhalterEinstellungen Gabelschl√ºsselhalterStachelEinstellungen StachelStapelbares FarbenregalAblagegestellEinstellung AblagegestellAblagegestell zur Lagerung von Kisten und √§hnlichem mit eigenem BodenAufbewahrungskistenEinstellungen AufbewahrungskisteAufbewahrungskisten k√∂nnen zum ablegen von Setzk√§sten verwendet werdenT10T2_5T5Das K√∂nigliche Spiel von Ur aus dem dritten Jahrtausend vor Christus‚ÄûDie Ampel wurde entworfen, um den Status eines von Icinga √ºberwachten ‚ÄûSystems‚Äú zu visualisieren. Um 90¬∞ gedreht, kann sie auch als Flaschenhalter benutzt werden.Dicke der Scheibe in mmDas ist eine einfache Regalkiste.Zahnriemenscheiben f√ºr verschiedene ProfileKleiner Nachbau einer VerkehrsampelVerkehrsampelEinstellungen AmpelSchaleEinsatz ohne Boden oder √§u√üere W√§nde - erlaubt nur gleichm√§√üige W√§ndeAblageeinsatzEinstellungen EinsatzEinsatz-LayoutAblageeinsatz2Einstellungen AblageeinsatzSchalen und SchubladeneinlagenZweiteilige KisteEinstellungen Kisteeinfacher Setzkasten - erlaubt nur gleichf√∂rmige W√§ndeSetzkastenEinstellungen SetzkastenUUBoxEinstellungen UBoxKiste mit ungleicher H√∂heEinstellungen KisteUniversalkisteEinstellungen UniversalkisteInstabilErzeuge eine abwechselnde Lochanordnung anstelle einer geradlinigenVGeriffelter-DrehknopfEinstellungen DrehknopfBreite der einzelnen KartenBreite des TragegriffsGr√∂√üe des Schraubenkopfes (mm)WeinregalEinstellungen WeinregalXLDamit die Klemme funktioniert, braucht man noch eine passende Feder. Vergr√∂√üere die Zusatzh√∂he um mehr Spiel f√ºr die Feder zu bekommen und um den Gleitmechanismus lockerer zu gestalten. Eventuell musst du etwas Wachs an die Gleitteile anbringen, um Reibung zu minimieren. aa#F√ºge Deckel hinzu (am besten mit einander gegen√ºberliegenden hohen Ecken)zus√§tzliche H√∂he der R√ºckwandzus√§tzlicher DeckelZus√§tzlicher Deckel (nur f√ºr gerade Oberkanten)zus√§tzliche TiefeaiAlleAnzahl der Haken / KlammernWinkelNeigungswinkel der B√∂denWinkel der unteren St√ºtzeWinkel der sich ber√ºhrenden Kopfflanken (in Grad)Abgekantete √ñffnungAbgekanteter DeckelAbgekanteter Deckel2Winkelbolzen1Winkelbolzen2Achsebh√∂he R√ºckseiteStrahlh√∂heStrahldickeAchsenlochBolzendurchmesserBeidseitigUnterteiltiefeBodendurchmesserBodenkantenunterer HakenBodenradiusSt√ºtzwinkel - weniger f√ºr mehr Unterst√ºtzungBeuleburnBrennpunktkorrektur in mm (h√∂herer Wert f√ºr engere Passung)cc#DosendurchmesserDosenh√∂heKartenh√∂heKartenbreiteAbschr√§gungAbschr√§gung an den EckenKastenSpielraumDeckelabstandGeschlossenVerbindungKantenradiusErstellt einen Zahnkranz, gegen den der Riemen von innen gedr√ºckt wirdZuschnittdd#d1d2d3debugdefault (none)DeltazahnTiefeTiefe des UnterteilsTiefe des OberteilsTiefe hinter den SchlitzenSchlitztiefe an der VorderseiteRillentiefeTiefe der AblageTiefe der BlendenSeitentiefedholeDurchmesserDurchmesser des BodensDurchmesser der OberseiteLochdurchmesser f√ºr den Winkelbolzen - Fu√üendeLochdurchmesser f√ºr den Winkelbolzen - BeinendeDurchmesser der Stange in mmDurchmesser der AusrichtungsstifeDurchmesser des unteren Teils des SchraubenlochsAchsdurchmessersAchsdurchmesserDurchmesser der unteren Nut in mmDurchmesser des Lochs f√ºr das Werkzeug (Der Griff sollte nicht durchpassen)BolzenlochdurchmesserDurchmesser des Bolzenlochs in mmStiftdurchmesser in mmSchreubendurchmesser in mmAchsendurchmesserAchsendurchmesser 1Achsendurchmesser 2 (0 f√ºr die gleiche Gr√∂√üe wie Achse 1)Durchmesser der F√§den der O-RingeDurchmesser des Dings zum KlemmenDurchmesser des Werkzeugs inklusive Abstand zum GriffDurchmesser des oberen Teils des SchraubenlochsMa√üeScheibendurchmesserAu√üenkantenabstandScheibendickeEntfernungAbstand zwischen Zapfenloch und UnterkanteAbstand der Flex-Einschnitte in Vielfachem der DickedoppeltdProzentsatz1dProzentsatz2dxfeKantenvariante f√ºr BodenVerbindungstyp f√ºr die linke KanteVerbindungstyp f√ºr die rechte KanteKantenvariante f√ºr OberseiteKantenbreiteFreigabe eines zweiten Rings mit gegebenem Delta zum Holradjeder dritteVerl√§ngerung der geraden Kante nach au√üenVerl√§ngert das Dreieck entlang der L√§nge der KanteZus√§tzliche H√∂he f√ºr mehr Bewegungsspielraum in mmZus√§tzlicher Abstand um Bewegung zu erlaubenzus√§tzliche H√∂heZusatzh√∂heGelenklochAnzahl Scharniergelenkeff#Zapfenfeste L√§nge der Griffe an den DeckelnflachB√ºndigNutdurchmesserFormatFormat der konvertierten DateivierAnteil der H√∂he der Abschr√§gungVon einer Zinkenmitte zur n√§chstenForderseitefwgg#gcodePositive Zahl f√ºr l√§ngere OberkanteGriffl√§ngeHandgriff-ProzentsatzGriffh√∂heGriffbreitehGriffh√∂heGriffbreiteDeckel√ºberlappung an den Seiten (√§hnlich mit OutSetEdge)H√∂heH√∂he √ºber der WandH√∂henunterschied von links nach rechtsH√∂he in Rack-EinheitenH√∂he der vorderen SeitenH√∂he in mmH√∂he des (Aluminium-)Profils, das die Teile verbindetH√∂he der KisteH√∂he der Standf√º√üeH√∂he der vorderen linken Ecke in mmFronth√∂he der Fl√§cheH√∂he der vorderen rechten Ecke in mmH√∂he des Grifflochs in mmH√∂he der hinteren linken Ecke in mmH√∂he des DeckelsH√∂he der hinteren rechten Ecke in mmH√∂he des Schraubenkopfes in mmH√∂he0H√∂he1H√∂he2H√∂he3H√∂heH√∂he des K√∂rpersSechskant-SchraubenkopfHexmusterhih√∂herer Wert f√ºr tiefere Verzahnung (Grad)Gelenkst√§rkeScharnieranzahlScharnierfestigkeitHalterl√§ngeOffenLochdurchmesserRandabstandLochabstandHakenzus√§tzliche Bolzenh√∂heHakenWie weit sollen die Schwalbenschanzzinken aus/in den Rand ragenwie weit sollten die Finger gespreizt werden (von -80 bis 80)iin Pain Prozent des BetragsInnentiefe in mmInnere Tiefe in mm (au√üer wenn Au√üenma√ü markiert ist)Innentiefe ohne die BlendenInnenbreite des HakensInnere H√∂he in mm (au√üer wenn Au√üenma√ü markiert ist)Innere H√∂he der Innenw√§nde in mm (au√üer wenn Au√üenma√ü markiert ist) (bleibt bei Null wenn Au√üenw√§nde gleich hoch sind)Innenh√∂he des HakensInnenradius der Kiste (an den Ecken)Innere Breite in mm (au√üer wenn Au√üenma√ü markiert ist)Innenbreite des Automatenau√üenInnenwinkel der Standf√º√üeauf linksTonfalljkMesserdickelRiegelgr√∂√üelinkslinke KanteL√§nge des Teils, das die Fl√§che √ºber der Vorderseite h√§ltPlatzhalterl√§ngeL√§ngeBeinl√§nge (34mm min)Lenge des Achse-zu-Achse SegmentsL√§nge1L√§nge2L√§nge3L√§nge4L√§nge5DeckelDeckelh√∂heBegrenzt die Anzahl der Planeten (0 f√ºr so viel wie m√∂glich)Unterer AbstandmmBarmax St√§rkemax BreiteMaximalh√∂heMaximale Klemmenh√∂he in mmMaximaler Abstand am Anfang und Ende als vielfaches der normalen Fl√§chenMaxPlanetenMensurmin St√§rkemin BreiteMinimalh√∂heminimalMinimale Klemmenh√∂he in mmMinimalster Abstand um die GelenkeMindesabstandmmH2OmmHgBetragZahnradbetrag (in mm)Betrag der Z√§hne in mmM√ºndungs-Umfangs-Verh√§ltnis (0,1 bis 0,45). Bestimmt das Verh√§ltnis von Breite zu TiefeM√ºndungsverh√§ltnisnNEMA Motorrahmengr√∂√üeNEMA-Halterungno_verticalsnoneNumNummerAnzahl der F√§cherAnzahl von Abteilungen von vorne nach hintenAnzahl von Abteilungen nebeneinanderScharnieranzahl pro KanteAnzahl der LichterAnzahl der B√∂denSeitenanzahlSohlenzahlAnzahl der Zahnradpaare in der √úbersetzungZ√§hnezahlZ√§hnezahl des zweiten ZahnradsZahnanzahl auf der EingangswelleZahnanzahl auf der AusgangswelleZ√§hnezahl an den Planetenr√§dernZ√§hnezahl am SonnenradAnzahl der Werkzeuge / SchlitzeWandanzahl einer Seite (+1)Anzahl der Gabelschl√ºsseloOktaveungleicheeinszus√§tzliche ArgumenteRadau√üendurchmesser (einschlie√ülich O-Ringe)AnfangAu√üenma√üMontagem√∂glichkeitGesamtbreite des Werkzeugs√úberhang√úberhang der Zinken in mm√úberlappung des oberen Randes (Null f√ºr keinen)ppdfTeilkreis D in Prozent der Achse 2 (0 f√ºr die gleiche Gr√∂√üe wie Achse 1)Teilkreis D in Prozent der Achse 1 (100 f√ºr runde Achse)Gelenke pro ScharnierStiftBolzenh√∂heStiftgr√∂√üeBolzenbreitePfeife ist oben geschlossenTonlagePlanetenz√§hneBewegungsfreiraumSpiel zwischen den beiden Teilen als Vielfaches der Wandst√§rkepltStangendurchmesserEingriffswinkelFlankenwinkelDrucke Refernezrechteck mit gegebener L√§nge (Wert Null zum deaktivieren)Drucke umgebende Box f√ºr etwas StrukturProfilProfil Z√§hne/G√ºrtelZahndickepsqrr_LochRadiusSchlitzradiusRadius zum Verst√§rken der W√§nde mit den HakenRadius der UnterkanteLochradiusEckenradiusKantenradius in mmRadius der rotierenden Scheibe in ScharnierRadius des Gelenklochs (als Mehrfaches der Dicke)Radius des BiegescharnierdeckelsRadien der Schlitze an der VorderseiteRadius der oberen EckeRadius an allen vier EckenLeisterear_factorReferenzrechtsrechte Kanterunder DeckelRundungGummidickesSchraubeSchraube1Schraube2SchraubenkopfSchraubenkopfh√∂hezweiter Bolzen'R√ºch- zu Vorderseite'-Abschnitt in mm. M√∂gliche Formate: overallwidth/numberofAuswahl z. B. "250/5"; sectionwidth*numberofsections z. B. "50*5"; Abschnittsbreite getrennt durch ":" z. B. "30:25.5:70'Boden zu Oberseiten'-Abschnitt in mm. F√ºr Format mit --sy nachsehen'Links nach Rechts'-Abschnitt in mm. F√ºr Format mit --sy nachsehenVerzahnungswinkelVerzahnungservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bkleinen Wert einstellen, um Bolzen-umgebende Scheiben zu erhaltenshBlendenAchseAchse1Achse2einfachGr√∂√üeRiegelausma√ü in Vielfachem der DickeSchlitztiefeSchlitzbreiteSchlitzSchlitz, um die Zettel besser greifen zu k√∂nnenAbstandFl√§che unterhalb der L√∂cher der FingerzinkenkanteGelenkabstand (als Mehrfaches der Dicke)Abstand zwischen den ZapfenAnschl√ºsse umgebender Abstand (als mehrfaches der Dicke)MindesabstandUnterteilt den Deckel in y-Richtung (mm)DeckelteilungFederWerden die Lampen aufeinander gestapelt (oder nebeneinander)?ZahnradpaaregeschlossenSt√§rkeSterke des gr√∂√üten Schl√ºsselsDicke des kleinsten Schl√ºsselsDehnungBolzenStilArt des verwendeten ScharniersArt der Oberseite und des DeckelsSonnenz√§hneumliegende Fl√§chesvgsvg_PonokosxsytLaschenZ√§hneZahn1Zahn2St√§rkeBogendicke die den Bolzen befestigenDicke der Messer in mm. 0 f√ºr die Verwendung mit Wabentisch.Materialst√§rkeWerkzeugbreiteWerkzeugdurchmesserOberseiteOberteiltiefeOberer DurchmesserOberseitenkanteBehandle Abmessungen als Au√üenma√üe, die die Materialst√§rke mit einbeziehenDreieckzweiTyp des ArmabschnittesArt des zu verwendenden ServosArt des zu verwendenden Servos an der zweiten Seite (fallsunterschiedliche Typen unterst√ºtzt werden)typ1Typ2Typ3Typ4Typ5uaufrechtVerwende die unten angegebenen EinheitenvWandWandst√ºckeW√§ndeWellewelche der Wabenw√§nde hinzugef√ºgt werden sollenBreiteBreite der Zapfenl√∂cherBreite des gr√∂√üten Schl√ºsselsBreite der SchlitzeBreite des kleinsten Schl√ºsselsBreite des SohlenstreifensBreite der Laschen, die die Teile an Ort und Stelle halten, in mm (wird nicht √ºberall unterst√ºtzt)Zahnbreite in mmBreite des Grifflochs in mm (Null f√ºr kein Loch)Breite des (Aluminium-)Profils, das die Teile verbindetBreite der Standf√º√üeBreite der ZapfenSpaltbreite der EinschnitteHakenbreite (R√ºckseite ist etwas breiter)Hakenbreite an der SeiteBreite des langen EndesBreite des Musters senkrecht zu den SchnittenPlatzhalterbreiteBreite der umgebenden Wand in mmWinddruckWinddruck-EinheitenSchreibenkopfbreite in mmxyz
57,153
Python
.py
115
495.452174
9,724
0.617217
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,526
boxes.py.mo
florianfesti_boxes/locale/zh_CN/LC_MESSAGES/boxes.py.mo
Ş•’¬Ç<9XL¹YLNNìbNOOcO~O�OB§OêOBïO.2P1aP3“PDÇPX QeQiQB†QÉQÒQ1äQR&)RPR aRkR ~R‹R¡R¨R¸R(ÔRıRS (S3SIGSB‘SÔSÜS"íS TT1T<5T.rT¡TÁT1İT'U7U(SU!|U'�UÆU.ÜU' V-3V aV‚V6�VÕVõVûV WW&W.W?WFWVW/rW8¢W8ÛW XX 1X=X*RX}X"’XµXÆXİXõXY+.YZY%tY*šYÅYßYıYZZ,Z4Z EZQZ fZsZ/‰Z ¹Z ÚZæZ!ûZ[&[8[G[ _[m[„[†[¥[­[¾[Ç[Ù[â[ô[ı[\\*\3\ E\O\b\~\…\•\]¦\] ]]]$]&5]\]b]q]&z]/¡]EÑ]^L,^y^{^ƒ^‹^“^2¬^ß^è^ú^_#_;_D_1V_ˆ_%£_%É_ï_ ` `7`U`h`0„`,µ`â`é`ù`ÿ` aa -a;aRa Vacaya‹a#¦aÊaóÏa Ãbäb÷b ccV+c ‚c�c£cÁc/Öcdd!d 2d<d1Od1�d³d¼dÎd×d édód)e0e 3e@eVe[e"me)�e ºe6Äeûe ff-f6f1Hf0zf «f¹fÀfĞf èfòf gg"g2gKgSgdgsg‰g¥g(¿gègøg hh0h9h Kh Vh ah lh wh‚hE‰hÏh,ßh/ i <iGi [ieixi Œi™i#¯iÓiÛi÷ij,jJjejwj!‘j ³jÔjïj k#'kKk!Qksk{k-’k ÀkËk,ßk ll3+l _l:kl ¦lÇlĞlàlùlm,m<mUmfm €m�m¥m¹mÖmëm nn>nOnin~n œn§n»nÃnÔnîn3o :oFo?[o ›o¨o*¾oéoíoòoõop˜%p¾p�Ûpis*…s °s ¾sËsásHæs /t:t Nt Ytetzt“t ¥t²tÈtÑt(ãt uu'u ,u:uJu cupu†u=�u Íu×u»êu¦v¹vÑvåvww w#w<,x,ix"–x¹x+ÈxôxWy]yayzy@€yÁyÑy(ñy z &z 1z =z HzSzXz Zz fz qz{z„z‰z�z •z¢z ²z ¾z Êz%Øzşz{ {{s{‰{‹{ �{ š{ ¤{ ¯{¹{Á{Ø{ Ş{,è{,|B| W| c| o|{| ‚| �| š|A¥|ç|í|ï|ò|õ|ø|û|} }}!}5}F}\}z}>�}Î}à}#õ}~,~0D~u~{~„~›~-¯~,İ~ $(?h”ª#ÈAì#.€!R€t€�€¬€Æ€â€ø€1�&B�i�,‡�(´� İ� ç� õ�‚‚)‚/C‚s‚‹‚ª‚ɂ߂ú‚ƒ)ƒ 0ƒ =ƒ?JƒŠƒŒƒœƒ¶ƒ΃"çƒ „ !„ ,„77„ o„ z„0›„@Ì„- …V;…+’…¾… Ü… é…õ…ù…† † ††$†>†C† I†W†^†w†(|†)¥†φÕ†؆Ú†݆ù†‡$8‡ ]‡i‡ y‡ „‡�‡$�‡ µ‡ ‡5·ˆ ˆ!ˆAˆVˆlˆ6€ˆ·ˆ-Ɉ÷ˆ% ‰0‰&M‰t‰$’‰·‰ɉ%ç‰ Š,Š CŠdŠlŠtŠ|ЄЋŠ�Š ¦Š±Š-´ŠâŠñŠ øŠ ‹‹‹&‹D‹S‹i‹ ‹Œ‹ •‹¢‹¨‹­‹ ¿‹Ê‹1Ğ‹Œ)ŒDŒ^Œ)pŒšŒ+¬Œ$ØŒıŒ,�bB�¥�(¾�+ç��.�5� N� X�c�r� ��‹� �� š�3¤�Ø�ë�ò� �+�3�;�C�K�S� W�2a� ”�¡�¦�)«� Õ� â� ì�ö�?� T�_� f� s� }�‡���­�Ì�Õ�Û�à�è�‘ ‘J/‘Oz‘ ʑՑ ב â‘ï‘ô‘ø‘+ÿ‘+’F’a’y’$�’#µ’Ù’ó’“/“K“`“r“‚“&’“¹“*É“ ô“!”7”R”n” „”¥”¸”½””É”ΔÒ”Ú”0픕%• -•;•W•`•"z•�•£•;À•9ü•6–G– K–V–^–g–�–7‡– ¿–Ë–;Ğ– ——(—=7—+u—¡—©— ×Ñ—Ó—Ú—á—-õ—#˜<˜K˜a˜(}˜-¦˜Ô˜!ô˜ ™7™L™l™ q™ }™ ‰™“™œ™¯™ µ™ À™ ˙ՙݙæ™ö™(ø™!š&š5š;šBš IšSš cš qš¸|š15›1g›™› ¨›³›»›Û˛ӛۛã›ë›ó›û›4œ8œ?œEœLœ Sœ ^œ"kœ�œ•œ'šœ œ ͜؜ éœ õœ��#�#)�M�.`���8¥�Ş�!æ���� �&'�N�U�Z�b�k�†�¢�ª�¯�µ�É�Ş�÷�ŸŸŸŸŸ!Ÿ&Ÿ,Ÿ3Ÿ :Ÿ-DŸCrŸ¶Ÿ9ĞŸ    "  &  0 =  F :T � ˜ 9œ Ö ê ?ÿ ?¡E¡K¡Q¡W¡]¡'e¡�¡¦¡ «¡¶¡¼¡$Á¡æ¡ì¡¢¢)¢B¢IW¢¡¢.¶¢5墣-£B£-`£�£®£Ä£.䣤&¤#9¤]¤r¤ ‡¤”¤§¤ĤƤȤCʤš¦6©§æà§Ǩ㨩 ©8'©`©Ee©!«©Í©-é©0ªCHªŒª�ª9¦ª àªíª!«"«2« N« [«h«{«�«§«·«Í«ã«ü« ¬ "¬,¬:<¬:w¬ ²¬¼¬̬ å¬ï¬ÿ¬*­'1­Y­ x­-‚­°­É­'ß­®&®B®![®!}®'Ÿ®Ç®æ®'¯-¯I¯P¯ c¯p¯ ƒ¯�¯�¯ ¤¯±¯*Á¯>ì¯A+°m°}° “° °'³° Û°å° ÿ° ±±5±M±#i±�±#¢±Ʊá±ñ±² ²)²9² @² M²W² j²t²&‡²®² ˲زë²ş² ³ ³³ ,³9³L³ N³ [³h³ {³‰³ �³«³ ¿³ͳ á³ï³ ´´ #´1´"E´ h´r´‚´W•´í´õ´ı´ µµ$µDµ KµXµ!_µ�µ:šµÕµ?îµ.¶0¶8¶@¶H¶2`¶ “¶ �¶ª¶ º¶Ƕ ×¶á¶$ñ¶·&·$E·j·z· �·E�·Ô·ä·2ú·6-¸d¸ w¸„¸ Œ¸ š¸¤¸´¸ĸÚ¸ ޸ë¸ ş¸ ¹¹=¹ÅD¹ º$º8º IºTºgeº ͺ׺çº úº(»0»C»S»i»y»7‰»4Á» ö»¼ ¼ ¼ +¼6¼G¼f¼i¼y¼�¼–¼¦¼'żí¼-ô¼ "½/½ 7½E½ L½Y½!u½ —½¤½ «½ ¸½ Žѽ ã½ğ½¾¾ &¾0¾ @¾ M¾Z¾u¾$�¾ µ¾¿¾ Ͼܾ ï¾ù¾ ¿ ¿ !¿ -¿ 9¿ E¿6O¿ †¿*“¿-¾¿ ì¿ö¿ ÀÀ&À>ÀTÀpÀ�À˜À¨À»ÀÑÀêÀ Á Á#Á?Á^ÁqÁ�Á'šÁÂÁÉÁâÁéÁ$ 'Â1Â,AÂn uÂ"‚ ¥Â0²ÂãÂö ı ÃÃ-ÃCÃSà iÃvà ‰Ã–Ã©Ã¼Ã ÕÃâÃõÃÄ!Ä4ÄMÄ]Ä sÄ}Ä �Ä —ĥľÄ$ÚÄ ÿÄ Å6Å PÅZÅ$jÅ�œŘśźÅnÍÅ<ÆPWƨÇÈÇ ŞÇ èÇòÇÈ: ÈDÈTÈjÈ zÈˆÈœÈ µÈ ÂÈÌÈ ÜÈæÈ$öÈ É(É;É CÉQÉdÉ }ÉŠÉ�É0¤ÉÕÉåɦûÉ¢Ê²Ê ÊÊ×ÊõÊ üÊ Ëí Ë'úË!"ÌDÌWÌ!gÌ ‰Ìa–ÌøÌÿÌÍ4Í OÍ\Í*rÍ�Í¤Í·Í ËÍ ÖÍáÍåÍçÍîÍ õÍ Î Î Î Î 'Î 4ÎAÎHÎ OÎYÎ uÎ ƒÎ‘Î ˜Î’¥Î8Ï:Ï =Ï GÏ TÏ aÏnÏuψÏ�Ï*–Ï*ÁÏ ìÏùÏĞ ĞĞĞ Ğ ,Ğ69ĞpĞwĞyĞ|ĞЂЅЌРœĞ¦Ğ ­ĞºĞÊĞ àĞíĞ3ıĞ1ÑAÑTÑsуѢÑÁÑÆÑ ÍÑ ÚÑ!çÑ! Ò+ÒCÒVÒiÒ yÒ ƒÒ�Ò©Ò'ÄÒ ìÒùÒ ÓÓ.ÓCÓ UÓ bÓ)pÓšÓ«Ó!¾ÓàÓóÓ úÓ Ô Ô!Ô(Ô*DÔoÔˆÔ§ÔÆÔÙÔòÔÕ Õ%Õ@Õ9[Õ•Õ—Õ�Õ´ÕÍÕæÕÖ Ö (Ö*5Ö`ÖpÖ$ƒÖ5¨Ö)ŞÖQ×*Z×…×¡× ±×¾×Â×Õ×××Ú×á×è×ØØ Ø"Ø)Ø?Ø!CØ$e؊ؙؑؔؖجؿØÒØ îØûØ Ù Ù%Ù)Ù HÙ UÙ-bÙ�ٗ٭ÙÃÙ ÖÙãÙ'şÙ&Ú6ÚRÚbÚ}Ú“Ú®ÚÉÚáÚñÚÛ+ÛCÛSÛiÛqÛyÛ�Û‰Û�Û  ÛªÛºÛ!¾Û àÛíÛ ôÛ ÜÜÜÜ 7Ü DÜ RÜ `ÜjÜqÜxÜ|Ü €Ü ŠÜ—Ü%�ÜÄÜ&àÜİ#İ*İFİ,[݈ݤİ,ºİbçİJŞ!`Ş‚Ş¡ŞºŞ ÁŞ ÎŞ ÛŞ åŞ òŞ ÿŞ ß ßß'$ßLß\ßcßzß“ß›ß£ß«ß³ß»ß Âß1Ïß à àà'à Bà Oà \àià9„à¾àÎà Õà âà ïàüàáá :áGáMáRáYáná†áL–á2ãá â â "â -â:â>âEâLâkâ‚â˜â ®â»âÎâäâ ã ã*ã Hã Uãbã iãvã �ãœã ¸ãÅãÕãèãää0ä @ä MäZä aäkäoä väƒä£ä ªä ·äÄä×äŞä$üä!å(å4Aå,vå£å³å ·å Áå ÎåÛåîå6õå ,æ6æ*=æ hæ ræ |æl†æBóæ6ç=ç MçZç \çfç mçzç ™ç ¦ç °ç½ç!Ûç'ıç%èAè Vè cèpè�è “è  è ªè ´è¾èÎè Õèßèæèíè ñè ûèé é )é 3é @éJéRé Zédété „éÀ�é6Oê6†ê ½êÇêÎê×êàêéêòêûêë ëëë3(ë\ëcëgëlëqëxëë ›ë¥ë-¬ëÚëáëèë øëì ìì,ì!3ìUì'hì�ì-¦ìÔìÛì ÷ìíííí5í<íAíHíOíeí{í‚í‰í�í ¦í³í Ìí Ùíæíííğíóí õíî îîî' î9Hî‚î5’î Èî Õîâî éî öîï ï*ï BïLï*Pï {ïˆï9¡ïÛïãïëïóïûï ğ ğ,ğHğLğSğWğ^ğwğ ~ğ‹ğ ¡ğ®ğÄğ=×ğñ(0ñ'Yñ �ñ�ñ�ñ·ñÖñ òñ"ÿñ"ò Aò Nò[ò vò „ò’ò ™ò¦ò¸òºò¼ò‚�23‰Cl°ÄÛW3wS©}tÀãr_f1¬fÜw/�›QUv‡ĞU^ ğZFBÖvŞÅ ìtri•kÏp‡Mª!MºÓ<;iƒÓ(oÎà8¥»²%´Êà‚\rêœŞ!µA´°%’JÈa”ì+D¸–<X/¢$c<¡yí×X Ä€m6šôè4PnM :�~½BåWåâ‚ [s¨Œæxş�#Ï)äşjãĞ„†Òó#æµ(>h.D'ı;}’écA±ËÆ0P„ PË|$…†¾�úKÖîlº¼¯�@TwŒ±Ü¯Û4´’öÈg8¦7S9“Ÿ'ş­L¯H«wÙœFƒm�^‡‹õ6z|•_¤*á¨QS£é�Jûhó:¹"eä’ö^ÿ�M˜ãø­o ò¦S4Õ×|§¶Áó¿¼]¤†-O!7 ½¾¿5�zDh.À-XuKÿª$üÁìÃÂd”ÙB`Ñ)�q�( ªë?ÎfExl|Úï/^On ÄŸ²;ûu~L28KÖ‚hÙÑ7Eí ʈ&¼q ¥b«j÷ÿk¬8ˆf#íŒÜ%ÂçL‰tŸ±6ŒËÍ™ù%À�£Z¥ Yx‘?tR�gg,Bnr¡yî¦,—Î39ßêpT *„»u‘K=eÉ l·HJ>òû$N[=ñ0Aİm_ �®D.¬IEkî»÷Ô}VÒ#Rdš[ôkôÆ‹Gš/›:~‰–{PQ½~ÕWä{1Ib—n·ÈZaZ ‹O„Xq¶©Y\C?ඨřxaŠ“N‰6+³³Ø™W¢ç¹§YI`iñ]cLz2 Ue�\øö ‘vÉ©zêuø‹]ğ*ĞÌı õŠ¡ëC°èÌCY)ƒqsÓœŞ{¿V>È0I"ÏdòGÒi,®•sñÕõp�-_á<=Ì«�çyüéFº� ú Evï…a²³:‡Ç5¤ÚNÇbVè­€+Ñ·GHÚ=×1Ô†—o3ŠİÛı¢æ5U£�ˆ›-2&&Jgâ.Ÿ\R5 øG–9y‘`"&!*åÊü,TØ�d m˜pHƹğØ€"�F§ß“@RA9â�Éù  ˜]�{s÷'e(Íb…jN[4?0Qú€�; ù)Ô7Š'ƒ�@á1O¾®ïß@İT+`ÇVÍ”>µ}…cjëoÁ <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Cuttlery stand with carrying grip using flex for rounded corners Vitamins: DSP5005 (or similar) power supply, two banana sockets, two 4.8mm flat terminals with flat soldering tag To allow powering by laptop power supply: flip switch, Lenovo round socket (or adjust right hole for different socket) "outset" or "flush""spring", "stud" or "none""wave" or "bumps"# pieces of outer wall3U Height case with adjustable width and height and included rails40DPA Type tray variant to be used up right with sloped walls in frontA clamp to hold down material to a knife tableA holdfast for honey comb tables of laser cuttersA hook wit a rectangular mouth to mount at the wallA rack for storing disk-shaped objects vertically next to each otherA two piece box where top slips over the bottom half to form the enclosure. AT5Add external mounting pointsAdditional space kept between the disks and the outbox of the rackAllEdgesAllEdges SettingsAmount of circumference used for non convex partsAn error occurred!Angle between convex and concave partsAngle of the cutAngledBoxAngledBox SettingsAngledCutJigAngledCutJig SettingsArcadeArcade SettingsBackwards slant of the rackBalanced force Difference Planetary GearBar to hang pliers onBass Recorder EndpinBayonetBoxBayonetBox SettingsBench power supply powered with Maktia 18V battery or laptop power supplyBeware of the rolling shutter effect! Use wax on sliding surfaces.BinTrayBinTray SettingsBook cover with flex for the spineBottleStackBottleStack SettingsBoxBox for drills with each compartment with a different heightBox for holding a stack of paper, coasters etcBox for storage of playingcardsBox in the form of an heartBox various options for different stypes and lidsBox with a rolling shutter made of flexBox with both ends corneredBox with different height in each cornerBox with lid and integraded hingeBox with lid attached by cabinet hingesBox with living hingeBox with living hinge and left corners roundedBox with living hinge and round cornersBox with living hinge and top corners roundedBox with regular polygon as baseBox with top and front openBox with various options for different styles and lidsBox with vertical edges roundedBoxesBoxes with flexBurnTestBurnTest SettingsCardBoxCardBox SettingsCastleCastle SettingsCastle tower with two wallsClosed box with screw on top and mounting holesClosed box with screw on top for mounting in a 10" rack.Closed box with screw on top for mounting in a 19" rack.ClosedBoxClosedBox SettingsConcaveKnobConcaveKnob SettingsCreate boxes and more with a laser cutter!Cutup to mouth ratioD-Flat in fraction of the diameterDefault SettingsDefaultParams SettingsDesktop Arcade MaschineDiameter of the bolt hole (mm)Diameter of the box in mmDiameter of the inner lid screw holes in mmDiameter of the knob (mm)Diameter of the lid screw holes in mmDiameter of the mounting screw holes in mmDiameter of the paintcansDiplay for flyers or leafletsDisc diameter in mmDiscRackDiscRack SettingsDisplayDisplay SettingsDisplayCaseDisplayCase SettingsDisplayShelfDisplayShelf SettingsDistance of the screw holes from the wall in mmDivider tray - rows and dividersDividerTrayDividerTray SettingsDocumentation and API DescriptionDrillBoxDrillBox SettingsElectronicsBoxElectronicsBox SettingsEuroRackSkiffEuroRackSkiff SettingsFF Finger Joint (opposing side)FlexBoxFlexBox SettingsFlexBox2FlexBox2 SettingsFlexBox3FlexBox3 SettingsFlexBox4FlexBox4 SettingsFlexBox5FlexBox5 SettingsFlexTestFlexTest SettingsFlexTest2FlexTest2 SettingsFoam soles for the OttO botFolderFolder SettingsFully closed boxFully closed box intended to be cut from transparent acrylics and to serve as a display case.GT2_2mmGT2_3mmGT2_5mmGearBoxGearBox SettingsGearbox with multiple identical stagesGearsGears SettingsGenerateGenerate a typetray from a layout fileGenerator for keypads with mechanical switches.Generators are still untested or need manual adjustment to be useful.Get Source at GitHubGlue together. All outside rings to the bottom, all inside rings to the top.HHTD_3mmHTD_5mmHTD_8mmHackaday.io Project PageHalf width 19inch rack unit for musical equipment.HeartBoxHeartBox SettingsHeight of the cardsHeight of the handleHeight of the paintcansHingeBoxHingeBox SettingsHint of how much the flex part should be shortendHold a plane to a slatwallHold a set of wrenches at a slat wallHolds a single caliper to a slat wallHoney Comb Style Wine RackHookHook SettingsHook for pole like things to be clamped to another poleIntegratedHingeBoxIntegratedHingeBox SettingsIntonation Number. 2 for max. efficiency, 3 max.Jig for making angled cuts in a laser cutterKeypadKeypad SettingsLBeamLBeam SettingsLaserClampLaserClamp SettingsLaserHoldfastLaserHoldfast SettingsMXLMagazineFileMagazineFile SettingsMakitaPowerSupplyMakitaPowerSupply SettingsMinimum space between the paintcansMiscMost of the blue lines need to be engraved by cutting with high speed and low power. But there are three blue holes that actually need to be cut: The grip hole in the lid and two tiny rectangles on the top and bottom for the lid to grip into. Mounting braket for a Nema motorNEMA size of motorNema size of the motorNemaMountNemaMount SettingsNot yet parametrized box for drills from 1 to 12.5mm in 0.5mm steps, 3 holes each sizeNotesHolderNotesHolder SettingsNumber of rounded top cornersNumber of serrationsOctave in International Pitch Notation (2 == C)Open magazine fileOpenBoxOpenBox SettingsOrganPipeOrganPipe SettingsOtto LC - a laser cut chassis for Otto DIY - bodyOtto LC - a laser cut chassis for Otto DIY - legsOttoBodyOttoBody SettingsOttoLegsOttoLegs SettingsOttoSolesOttoSoles SettingsOutset and angled plate to mount stuff toPaPaintStoragePaintStorage SettingsPartParts and SamplesPiece for testing 2D flex settingsPiece for testing different flex settingsPlanetaryPlanetary Gear with possibly multiple identical stagesPlanetary SettingsPlanetary2Planetary2 SettingsPoleHookPoleHook SettingsPosition of the lower rack grids along the radiusPosition of the rear rack grids along the radiusProfile shiftPulleyPulley SettingsRack for cans of spicesRack10BoxRack10Box SettingsRack19BoxRack19Box SettingsRack19HalfWidthRack19HalfWidth SettingsRackBoxRackBox SettingsRadius of combRadius of the cornersRadius of the corners in mmRadius of the latch in mmRectangular organ pipe based on pipecalcRectangularWallRectangularWall SettingsRegularBoxRegularBox SettingsRobotArmRobotArm SettingsRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotary Attachment for engraving cylindrical objects in a laser cutterRotary SettingsRound box made from layers with twist on topRound knob serrated outside for better grippingRoundedBoxRoundedBox SettingsRoyalGameRoyalGame SettingsSBC Clearance in mmSBCMicroRackSBCMicroRack SettingsSegments of servo powered robot armServo9gSettings for Cabinet HingesSettings for Chest HingesSettings for Click-on LidsSettings for Dove Tail JointsSettings for Finger JointsSettings for FlexSettings for GrippingEdgeSettings for Hinges and HingePinsSettings for RoundedTriangleEdgeSettings for SlatWallEdgesSettings for Slide-on LidsSettings for Stackable EdgesSettings for rack (and pinion) edgeShelfShelf with forward slanted floorsShelvesShowing all edge typesShows the different edge types for slat wallsShutterBoxShutterBox SettingsSides of the triangles holding the lid in mmSilverwareSilverware SettingsSimple L-Beam: two pieces joined with a right angleSimple wallSlat wall tool holder for chisels, files and similar toolsSlat wall tool holder with slotsSlatWallSlatwallCaliperSlatwallCaliper SettingsSlatwallChiselHolderSlatwallChiselHolder SettingsSlatwallConsoleSlatwallConsole SettingsSlatwallDrillBoxSlatwallDrillBox SettingsSlatwallEdgesSlatwallEdges SettingsSlatwallPlaneHolderSlatwallPlaneHolder SettingsSlatwallPliersHolderSlatwallPliersHolder SettingsSlatwallSlottedHolderSlatwallSlottedHolder SettingsSlatwallTypeTraySlatwallTypeTray SettingsSlatwallWrenchHolderSlatwallWrenchHolder SettingsSpicesRackSpicesRack SettingsStachelStachel SettingsStack bottles in a fridgeStackable paint storageStackable rackable racks for SBC Pi-Style ComputersStorageRackStorageRack SettingsStorageRack to store boxes and trays which have their own floorStorageShelfStorageShelf SettingsStorageShelf can be used to store TypetrayT10T2_5T5Test different burn valuesThe Royal Game of UrThe traffic light was created to visualize the status of a Icinga monitored system. When turned by 90°, it can be also used to create a bottle holder.Thickness of the discs in mmThis generator will make shapes that you can use to select optimal value for burn parameter for other generators. After burning try to attach sides with the same value and use best fitting one on real projects. In this generator set burn in the Default Settings to the lowest value to be tested. To get an idea cut a rectangle with known nominal size and measure the shrinkage due to the width of the laser cut. Now you can measure the burn value that you should use in other generators. It is half the difference of the overall size as shrinkage is occurring on both sides. You can use the reference rectangle as it is rendered without burn correction.This is a simple shelf box.Timing belt pulleys for different profilesTraffic lightTrafficLightTrafficLight SettingsTrayTray insert without floor and outer walls - allows only continuous wallsTrayInsertTrayInsert SettingsTrayLayoutTrayLayout2TrayLayout2 SettingsTrays and Drawer InsertsTriangle LED LampTriangleLampTriangleLamp SettingsTwoPieceTwoPiece SettingsType tray - allows only continuous wallsTypeTrayTypeTray SettingsUBoxUBox SettingsUnevenHeightBoxUnevenHeightBox SettingsUniversalBoxUniversalBox SettingsUnstableUse hexagonal arrangement for the holes instead of orthogonalWaivyKnobWaivyKnob SettingsWhen rendered with the "double" option the parts with the double slots get connected the shorter beams in the asymetrical slots.Without the "double" option the stand is a bit more narrow.Width of the cardsWidth of the case in HPWidth of the handleWidth of the hex bolt head (mm)WineRackWineRack SettingsXLYou need a tension spring of the proper length to make the clamp work. Increace extraheight to get more space for the spring and to make the sliding mechanism less likely to bind. You may need to add some wax on the parts sliding on each other to reduce friction. add a lid (works best with high corners opposing each other)add feet so the rack can stand on the groundadditional height of the back walladditional lidadditional lid (for straight top_edge only)additional_depthadds an additional vertical segment to hold the switch in place, works best w/ --stableallamount of hooks / bracesangleangle at which slots are generated, in degrees. 0° is vertical.angle of floorsangle of the support underneethangle of the teeth touching (in degrees)angled holeangled lidangled lid2anklebolt1anklebolt2axlebback_heightbeamheightbeamwidthboltholeborebothbottombottom_depthbottom_diameterbottom_edgebottom_hookbottom_radiusbracing angle - less for more bracingbtn_xbtn_ybumpsburnburn correction in mm (bigger values for tighter fit). Use BurnTest in "Parts and Samples" to find the right value.cc#candiametercanheightcardheightcardwidthchamferchamfer at the cornerschestclearanceclearance for the board in the box (x) in mmclearance for the board in the box (y) in mmclearance of the lidclearance_xclearance_yclearance_zclosedconnectioncornerradiuscornersizecreate a ring gear with the belt being pushed against from withincutupdd#d1d2d3debugdefault (none)deltateethdepthdepth at the bottomdepth at the topdepth behind the lotsdepth of slots from the frontdepth of the groovesdepth of the longer (screwed to another half sized thing) sidedepth of the rackdepth of the shadersdepth of the shorter (rackear) sidedepth of the sidesdepth of the slot in mmdepth of the stand along the base of the bottlesdholediameterdiameter at the bottomdiameter at the topdiameter for hole for ankle bolts - foot sidediameter for hole for ankle bolts - leg sidediameter if the pin in mmdiameter of alignment pinsdiameter of lower part of the screw holediameter of spice cansdiameter of the axlediameter of the axlesdiameter of the bottles in mmdiameter of the flutes bottom in mmdiameter of the hole for the tool (handle should not fit through)diameter of the holes in the screendiameter of the holes in the wooddiameter of the pin holediameter of the pin hole in mmdiameter of the pin in mmdiameter of the screw in mmdiameter of the shaftdiameter of the shaft 1diameter of the shaft2 (zero for same as shaft 1)diameter of the strings of the O ringsdiameter of the thing to hookdiameter of the tool including space to grabdiameter of upper part of the screw holedimensiondisc_diameterdisc_outsetdisc_thicknessdistancedistance from finger holes to bottom edgedistance of flex cuts in multiples of thicknessdivider's notch's depthdivider's notch's lower radiusdivider's notch's upper radiusdivider_bottom_margindivider_lower_notch_radiusdivider_notch_depthdivider_upper_notch_radiusdoubledpercentage1dpercentage2draw some holes to put a 1/4" dowel through at the base and topee Straight Edgeedge type for bottom edgeedge type for left edgeedge type for right edgeedge type for top and bottom edgesedge type for top edgeedge_styleedge_widthenable secondary ring with given delta to the ring geareverythirdextend outward the straight edgeextend the triangle along the length of the edgeextend walls for 45° corners. Requires grinding a 22.5° bevel.extra height to make operation smoother in mmextra slack (in addition to thickness and kerf) for slot width to help insert dividersextra space to allow finger move in and outextra space to allow movementextra_heightextraheighteyeeyes_per_hingeff#feetfingerfixed length of the grips on he lidsflatflushflutediameterformatformat of resulting filefourfraction of bin height covert with slopefrom one middle of a dove tail to anotherfrontfwgg#generate wall on the bottomgenerate wall on the left sidegenerate wall on the right sidegreater zero for top wider as bottomgrip_lengthgrip_percentagegripheightgripwidthhh Edge (parallel Finger Joint Holes)handleheighthandlewidthhave lid overlap at the sides (similar to OutSetEdge)heightheight above the wallheight difference left to rightheight in rack unitsheight of front wallsheight of lid in mmheight of the (aluminium) profile connecting the partsheight of the boxheight of the cans that needs to be supportedheight of the feetheight of the front left corner in mmheight of the front of planeheight of the front right corner in mmheight of the grip hole in mmheight of the left back corner in mmheight of the lidheight of the net/usb hole mmheight of the right back corner in mmheight of the screw head in mmheight of the top hookheight of wall atthe front edgesheight0height1height2height3heigthheigth of the bodyhexheadhexpatternhihigher values for deeper serrations (degrees)hinge_strengthhingeshingestrengthhold_lengthholehole diametershole distance from edge in mmhole_dist_edgehole_grid_dimension_xhole_grid_dimension_yholediameterholedistholedistanceholeshookhook_extra_heighthookheighthookshow far the dove tails stick out of/into the edgehow many slots for sbcshow much should fingers widen (-80 to 80)in precent of the modulusin_place_supportsincreases in burn value between the sidesinner depth in mminner depth in mm (unless outside selected)inner depth not including the shadesinner depth of the hookinner height in mm (unless outside selected)inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)inner height of the hookinner radius if the box (at the corners)inner width in mm (unless outside selected)inner width of the consoleinsideinside angle of the feetinsideoutintonationkeyboard_depthknifethicknesslatchsizeleftleft_edgeleft_walllegth of the part hiolding the plane over the frontlegth of the planelengthlength of legs (34mm min)length of segment axle to axlelength1length2length3length4length5lidlidheightlimit the number of planets (0 for as much as fit)lower_factorlugsmBarmargin between box's bottom and divider'smax_strengthmax_widthmaxheightmaximal clamping height in mmmaximum space at the start and end in multiple of normal spacesmaxplanetsmensurmin_strengthmin_widthminheightminimalminimal clamping height in mmminimum space around the hingeminspacemmH2OmmHgmodulusmodulus of the gear (in mm)modulus of the theeth in mmmonitor_heightmounting patterns: x=xlr, m=midi, p=9v-power, w=6.5mm-wire, space=next rowmouth to circumference ratio (0.1 to 0.45). Determines the width to depth ratiomouthrationnema_mountno_verticalsnonenumnumbernumber of bottles to hold in the bottom rownumber of buttons in x-rownumber of cans in a columnnumber of cans in a rownumber of compartmentsnumber of compartments back to frontnumber of compartments side by sidenumber of hinges per edgenumber of lightsnumber of locking lugsnumber of pairs (each testing four burn values)number of rack unitsnumber of shelvesnumber of sidesnumber of solesnumber of stages in the gear reductionnumber of teethnumber of teeth in the other size of gearsnumber of teeth on ingoing shaftnumber of teeth on outgoing shaftnumber of teeth on planetsnumber of teeth on sun gearnumber of tools/slotsnumber of walls at one side (1+)number of wrenchesnumxnumyoctaveoddsoneopeningoptional argumentsouter diameter of the wheels (including O rings)outsetoutsideoutsidemountsoverall width for the toolsoverhangoverhang for joints in mmoverlap of top rim (zero for none)pairspercent of front that's openpercent of the D section of shaft 1 (0 for same as shaft 1)percent of the D section of shaft 1 (100 for round shaft)pieces per hingepinpin_heightpinsizepinwidthpipe is closed at the toppitchplace supports pieces in holes (check for fit yourself)planetteethplayplay between the two parts as multipleof the wall thicknesspolediameterpressure anglepressure_angleprint reference rectangle with given length (zero to disable)print surrounding boxes for some structuresprofileprofile of the teeth/beltprofile_shiftrr_holeradiusradius at the slotsradius for strengthening walls with the hooksradius of bottom cornersradius of holeradius of the cornersradius of the corners in mmradius of the disc rotating in the hingeradius of the eye (in multiples of thickness)radius of the lids living hingeradius of the slot entrance in mmradius of the slots at the frontradius of top cornerradius used on all four cornersrailrear_factorrectangularreferenceretainerretainer_hole_edgerightright_edgeright_wallround lidroundedru_countrubberthicknessss Stackable (bottom, finger joint holes)sbcsscreenholesizescrewscrew1screw2screwheadscrewheadheightscrewholesizesecond_pinsections back to front in mm. Possible formats: overallwidth/numberof sections e.g. "250/5"; sectionwidth*numberofsections e.g. "50*5"; section widths separated by ":" e.g. "30:25.5:70sections bottom to top in mm. See --sy for formatsections left to right in mm. See --sy for formatserrationangleserrationsservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bset to lower value to get disks surrounding the pinsshadesshaftshaft1shaft2shaftwidthsharpcornersshort side of the corner trianglessinglesizesize of latch in multiples of thicknessslot_angleslot_depthslot_extra_slackslot_radiusslot_widthslotsslots for grabbing the notesspacespace below holes of FingerHoleEdgespace between cansspace between eyes (in multiples of thickness)space between fingersspace surrounding connectors (in multiples of thickness)spacingsplit the lid in y direction (mm)splitlidspringspringsstablestack lights upright (or side by side)stagesstepstoppedstrengthstrength of largest wrenchstrength of smallest wrenchstretchstudstylestyle of hinge usedstyle of the fingersstyle of the top and lidsunteethsurroundingspacesswitchsxsyttabsteethteeth1teeth2thicknessthickness of the arc holding the pin in placethickness of the knifes in mm. Use 0 for use with honey comb table.thickness of the materialthickness of the top layer, cherry needs 1.5mm or smallertool_widthtooldiametertoptop_depthtop_diametertop_edgetop_thicknesstreat sizes as outside measurements that include the wallstriangletwotwo pieces that can be combined to up to double the widthtype of arm segmenttype of servo to usetype of servo to use on second side (if different is supported)type1type2type3type4type5uprightuse finger hole edge for retainer wallsuses unit selected belowwallwallpieceswallswavewhich of the honey comb walls to addwidthwidth of finger holeswidth of largest wrenchwidth of slotswidth of smallest wrenchwidth of sole stripewidth of tabs holding the parts in place in mm (not supported everywhere)width of teeth in mmwidth of th grip hole in mm (zero for no hole)width of the (aluminium) profile connecting the partswidth of the feetwidth of the fingerswidth of the gaps in the cutswidth of the hook (back plate is a bit wider)width of the hook from the sidewidth of the long endwidth of the net/usb hole in mmwidth of the pattern perpendicular to the cutswidth of the planewidth of the shaftwidth of the surrounding wall in mmwidth of x hole areawidth of y hole areawindpressurewindpressure_unitswith of the screw head in mmxyzProject-Id-Version: Report-Msgid-Bugs-To: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PO-Revision-Date: 2020-03-30 15:20+0800 Last-Translator: cndk <2889188672@qq.com> Language-Team: Chinese (China) Language: zh_CN X-Generator: Poedit 2.3 Plural-Forms: nplurals=1; plural=0; <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a>是一个用<a href="https://www.python.org/">Python</a>编写的<a href="https://www.gnu.org/licenses/gpl-3.0.en.html">å¼€æº�</a>ç›’å­�生æˆ�器。 它具有完æˆ�çš„å�‚数化生æˆ�器以å�Šç”¨äº�编写自己的Python API。 它具有手指和(æ‰�平)燕尾榫æ�¥å¤´ï¼ŒæŸ”性切å�£ï¼Œè�ºé’‰ï¼Œé“°é“¾ï¼Œé½¿è½®ï¼Œæ»‘轮等孔和槽。 带æ�¡æŠŠçš„刀æ�¶ 对圆角使用柔性 维生素:DSP5005(或类似)电æº�,两个香蕉æ�’座,两个4.8毫米带æ‰�平焊æ�¥æ ‡ç­¾çš„æ‰�平端å­� å…�许通过笔记本电脑供电:翻转开关,è�”想圆形æ�’座(或调整å�³ä¾§å­”用äº�ä¸�å�Œæ�’座) “开始â€�或“冲洗â€�"弹簧", "è�ºæŸ±" , "没有"“波浪â€�或“颠簸â€�外墙片3U高度ä¿�护壳,宽度和高度å�¯è°ƒï¼Œé™„带导轨40DP一ç§�ç±»å�‹æ‰˜ç›˜å�˜ä½“,å�¯ç”¨äº�æ­£é�¢ï¼Œå‰�é�¢æœ‰å€¾æ–œçš„墙å£�把æ��料夹在刀å�°ä¸Šçš„夹å­�激光切割机的固定å�°å¸¦æœ‰çŸ©å½¢å�£çš„æŒ‚钩,å�¯å®‰è£…在墙上用äº�将盘形物体å�‚直相邻存放的æ�¶å­�一个两件套的盒å­�,上é�¢ä»�下å�Šéƒ¨åˆ†æ»‘è�½å½¢æˆ�外壳 AT5添加外部安装点ç£�盘和机æ�¶çš„å�‘件箱之间ä¿�留了é¢�外的空间所有边缘所有边缘设置用äº�é��凸起部分的周长é‡�å�‘生错误ï¼�凸凹部分之间的角度切割角度斜角盒å­�斜角盒å­�设置角度切割夹具角度切割夹具设置街机游æˆ�机街机游æˆ�机设置å�‘å��倾斜的机æ�¶å¹³è¡¡åŠ›å·®è¡Œæ˜Ÿé½¿è½®é…’å�§æŒ‚é’³å­�ä½�音录音机端针å�¡å�£ç›’å�¡å�£ç›’设置å�°å¼�电æº�采用Makita 18V电池或笔记本电æº�供电å°�心滚动快门效æ�œï¼� 在滑动表é�¢ä¸Šä½¿ç”¨èœ¡ã€‚托盘盒托盘盒设置书脊有弹性的书皮酒瓶å� é…’ç“¶å� è®¾ç½®ç›’å­�æ¯�个隔间具有ä¸�å�Œé«˜åº¦çš„钻头盒用æ�¥è£…一堆纸ã€�æ�¯å�«ç­‰çš„ç›’å­�用äº�存放扑克牌的盒å­�心形盒为ä¸�å�Œçš„ç±»å�‹å’Œç›–å­�æ��ä¾›å�„ç§�选项带柔性å�·å¸˜çš„ç›’å­�两端转弯的盒å­�在æ¯�个角è�½çš„ä¸�å�Œé«˜åº¦çš„ç›’å­�带盖和集æˆ�铰链的盒å­�箱盖由柜体铰链è¿�æ�¥å¸¦æ´»åŠ¨é“°é“¾çš„ç›’å­�带活动铰链和圆角的盒å­�带活动铰链和圆角的盒å­�带活动铰链和顶角圆形的盒å­�以正多边形为基础的框顶部和å‰�部打开的盒å­�å�¯é€‰æ‹©ä¸�å�Œæ¬¾å¼�和盖å­�的盒å­�å�‚直边缘圆形的盒å­�ç›’å­�带弹性的盒å­�激光补å�¿æ¿€å…‰è¡¥å�¿è®¾ç½®å�¡ç‰‡ç›’å�¡ç‰‡ç›’设置åŸ�å ¡åŸ�堡设置å�Œå£�åŸ�å ¡å¡”å°�闭的盒å­�顶部有è�ºé’‰å’Œå®‰è£…孔带顶部è�ºé’‰çš„å°�闭盒,用äº�安装在10“机æ�¶ä¸­ã€‚顶部带有è�ºä¸�çš„å°�闭盒,用äº�安装在19“机æ�¶ä¸­ã€‚å°�闭的盒å­�å°�闭的盒å­�设置凹é�¢æ—‹é’®å‡¹é�¢æ—‹é’®è®¾ç½®ç”¨æ¿€å…‰åˆ‡å‰²æœºåˆ¶ä½œç›’å­�等等ï¼�切å�£æ¯”直径分数为d的平é�¢é»˜è®¤è®¾ç½®é»˜è®¤å�‚数设置街机游æˆ�机桌é�¢è�ºæ “孔直径(mm)包装盒直径(毫米)内盖è�ºä¸�孔的直径,å�•ä½�mm旋钮直径(mm)盖å­�è�ºé’‰å­”的直径,å�•ä½�mm安装è�ºå­”直径(mm)油漆ç½�直径展示传å�•或传å�•圆盘直径,å�•ä½�mm圆盘æ�¶åœ†ç›˜æ�¶è®¾ç½®æ˜¾ç¤ºæ˜¾ç¤ºè®¾ç½®é™ˆåˆ—柜显示案例设置展示æ�¶æ˜¾ç¤ºè´§æ�¶è®¾ç½®è�ºå­”ä¸�墙å£�çš„è·�离,å�•ä½�为mm分隔托盘-行和分隔器分隔托盘分隔托盘设置文档和API说æ˜�钻箱钻箱设置电å­�盒电å­�盒设置欧å¼�å°�艇欧å¼�å°�艇设置F普通å�¡æ¦«æŸ”性盒å­�柔性盒å­�设置柔性盒å­�2柔性盒å­�2设置柔性盒å­�3柔性盒å­�3设置柔性盒å­�4柔性盒å­�4设置柔性盒å­�5柔性盒å­�5设置柔性测试柔性测试设置柔性测试2柔性测试2设置用äº�OttO机器人的泡沫é�‹åº•文件夹文件夹设置全å°�闭的盒å­�å…¨å°�闭的盒å­�,用äº�ä»�é€�æ˜�的丙烯酸树脂切割而æˆ�,用作展示柜。GT2_2mmGT2_3mmGT2_5mmå�˜é€Ÿç®±å�˜é€Ÿç®±è®¾ç½®å…·æœ‰å¤šä¸ªç›¸å�Œé˜¶æ®µçš„å�˜é€Ÿç®±é½¿è½®é½¿è½®è®¾ç½®ç”Ÿæˆ�ä»�布局文件生æˆ�ç±»å�‹æ‰˜ç›˜å�¯å®šåˆ¶çš„æœºæ¢°é”®ç›˜å�‘电机ä»�未ç»�过测试或需è¦�手动调整æ‰�有用.在GitHubè�·å�–æº�代ç �粘在一起。所有外ç�¯åˆ°åº•部,所有内ç�¯åˆ°é¡¶éƒ¨ã€‚HHTD_3mmHTD_5mmHTD_8mmHackaday.io项目页é�¢ç”¨äº�音ä¹�设备的å�Šå®½19英寸机æ�¶å�•元。心形盒心形设置å�¡ç‰‡çš„高度手柄高度油漆ç½�高度铰链盒铰链盒设置æ��示应缩短柔性部件的数é‡�æŒ�å¹³é�¢æ�¿å£�æŒ�有一套扳手在æ�¿æ�¡å£�å°†å�•个å�¡å°ºå›ºå®šåœ¨æ�¿æ�¡å£�上蜂çª�å¼�é…’æ�¶é’©å­�é’©å­�设置用钩å­�é’©ä½�æ�†å­�,就åƒ�把东西夹在å�¦ä¸€æ ¹æ�†å­�上一样综å�ˆé“°é“¾ç›’综å�ˆé“°é“¾ç›’设置音调数。最大效ç�‡ä¸º2,最大效ç�‡ä¸º3。用äº�在激光切割机中进行倾斜切割的夹具个性机械键盘键盘设置Lå�‹æ¢�Lå�‹æ¢�设置激光ç�¯æ¿€å…‰ç�¯è®¾ç½®æ¿€å…‰å®šå�‹å™¨æ¿€å…‰å®šå�‹å™¨è®¾ç½®MXLæ�‚志文件æ�‚志文件设置Makita电æº�Makita电æº�设置油漆ç½�之间的最å°�空间æ�‚项大多数è“�线需è¦�通过高速和ä½�功ç�‡åˆ‡å‰²è¿›è¡Œé›•刻。 但å®�际上需è¦�切割三个è“�æ´�:盖å­�上的抓æ�¡å­”和顶部和底部的两个å°�矩形,以便盖ä½�ç›–å­�。‪‪‪ Nema电机的安装支æ�¶NEMA尺寸的电机Nema电机大å°�Nema安装Nema安装设置尚未å�‚数化的盒å­�,适用äº�1至12.5毫米的钻头 以0.5毫米的步长,æ¯�个尺寸3个孔票æ�®å¤¹ç¥¨æ�®å¤¹è®¾ç½®åœ†è§’é¡¶è§’æ•°é‡�锯齿数é‡�国际音高符å�·ä¸­çš„八度(2==c)打开æ�‚志文件开放的盒å­�开放的盒å­�设置有机ç�»ç’ƒç®¡å™¨å®˜ç®¡è®¾ç½®Otto LC - 用äº�Otto DIY的激光切割底盘 - 本体Otto LC - 用äº�Otto DIY的激光切割底盘 - è…¿Otto本体Otto本体设置Otto的腿Otto腿设置Ottoé�‹åº•Ottoé�‹åº•设置开始和角度æ�¿å®‰è£…æ��æ–™Pa油漆存放处油漆存放处设置零件零件和样å“�用äº�测试二维柔性设置用äº�测试ä¸�å�ŒæŸ”性设置的工件行星å�¯èƒ½å…·æœ‰å¤šä¸ªç›¸å�Œé˜¶æ®µçš„行星齿轮行星设置行星2行星2设置æ�†é’©æ�†æ�„设置下齿æ�¡æ²¿å�Šå¾„çš„ä½�ç½®å��机æ�¶ç½‘格沿å�Šå¾„çš„ä½�置剖é�¢å��移滑轮滑轮设置调味ç½�æ�¶æœºæ�¶10盒机æ�¶10盒设置机æ�¶ 19盒机æ�¶19盒设置机æ�¶19å�Šå®½æœºæ�¶19å�Šå®½è®¾ç½®æœºæ�¶ç›’机æ�¶ç›’设置梳齿å�Šå¾„弯é�“å�Šå¾„è§’çš„å�Šå¾„以mm为å�•ä½�é—©é”�çš„å�Šå¾„,å�•ä½�mm基äº�管é�“计算的矩形器官管矩形墙矩形墙设置常规盒å­�常规盒å­�设置机械臂机械臂设置机械臂MM机械臂Mm机械臂Mu机械臂UU机械臂Uu旋转å¼�激光切割机上雕刻圆柱形物体的旋转附件旋转设置圆形盒由多层制æˆ�,顶部有扭曲圆形把手外有ä¸�状çª�起,便äº�抓æ�¡åœ†å½¢æ¡†åœ†å½¢æ¡†è®¾ç½®çš‡å®¶æ¸¸æˆ�皇家游æˆ�设置树è�“派间隙(mm)树è�“派堆å� æœºæ�¶æ ‘è�“派堆å� æœºæ�¶è®¾ç½®ä¼ºæœ�驱动机械臂的分段伺æœ�9g柜铰链设置箱å­�铰链设置点击盖å­�的设置燕尾榫æ�¥å¤´çš„设置å�¡æ¦«å…³èŠ‚çš„è®¾ç½®å¼¹æ€§è®¾ç½®æŠ“å�–边缘的设置铰链和铰链销的设置圆角三角形边缘的设置å£�æ�¿è¾¹ç¼˜è®¾ç½®æ»‘盖的设置å�¯å †å� è¾¹ç¼˜çš„设置机æ�¶ï¼ˆå’Œå°�齿轮)边缘的设置货æ�¶å¸¦å‰�斜地æ�¿çš„æ�¶å­�æ�¶å­�显示所有边缘类å�‹æ˜¾ç¤ºæ�¿æ�¡å¢™çš„ä¸�å�Œè¾¹ç¼˜ç±»å�‹ç™¾å�¶ç®±ç™¾å�¶ç®±è®¾ç½®å›ºå®šç›–å­�的三角形的边(å�•ä½�mm)银器银器设置简易Lå�‹æ¢�:两å�—ç›´è§’è¿�æ�¥ç®€å�•的墙凿å­�ã€�锉刀和类似工具的æ�¿æ�¡å£�刀æ�¶å¸¦æ§½æ�¿å£�刀æ�¶æ�¿å£�æ�¿å£�å�¡å°ºå£�æ�¿å�¡å°ºè®¾ç½®æ�¿å¢™å‡¿å­�æ�¶æ�¿å¢™å‡¿å­�æ�¶è®¾ç½®æ�¿å¢™æ�§åˆ¶å�°æ�¿å¢™æ�§åˆ¶å�°è®¾ç½®æ�¿å¢™é’»ç®±æ�¿å¢™é’»ç®±è®¾ç½®æ�¿å£�边缘å£�æ�¿è¾¹ç¼˜è®¾ç½®æ�¿å¢™å¹³é�¢æ”¯æ�¶æ�¿å¢™å¹³é�¢æ”¯æ�¶è®¾ç½®æ�¿å¢™å¢™æ�¿æ�¿å¢™å¢™æ�¿è®¾ç½®æ�¿å¢™å¼€æ§½æ”¯æ�¶æ�¿å¢™å¼€æ§½æ”¯æ�¶è®¾ç½®å¹³æ�¿å¢™å¼�托盘平æ�¿å¢™å¼�托盘设置æ�¿å¢™æ‰³æ‰‹åº§æ�¿å¢™æ‰³æ‰‹åº§è®¾ç½®è°ƒæ–™æ�¶è°ƒæ–™æ�¶è®¾ç½®ç‹¬è„šæ�¶Stachel设置将瓶å­�放在冰箱里å�¯å †å� çš„æ²¹æ¼†å­˜æ”¾å¤„适用äº�æ ‘è�“派的å�¯å †å� æœºæ�¶å­˜å‚¨æ�¶å‚¨å­˜æ�¶è®¾ç½®å­˜å‚¨æ�¶ç”¨äº�存放有自己楼层的盒å­�和托盘储物æ�¶å‚¨ç‰©æ�¶è®¾ç½®å­˜å‚¨æ�¶å�¯ç”¨äº�存放类å�‹æ‰˜ç›˜T10T2_5T5测试ä¸�å�Œçš„æ¿€å…‰è¡¥å�¿å€¼ä½ çš„皇家游æˆ�创建红绿ç�¯æ˜¯ä¸ºäº†å�¯è§†åŒ–ICINGA监æ�§ç³»ç»Ÿçš„状æ€�。 当旋转90°时,也å�¯ç”¨äº�制作瓶托。圆盘的å�šåº¦ï¼Œå�•ä½�mm将默认设置中的激光补å�¿è®¾ç½®ä¸ºè¦�测试的最ä½�值。为了得到一个想法,切割一个已知标称尺寸的矩形,并测é‡�激光切割宽度引起的收缩。激光补å�¿æ˜¯æ€»å°ºå¯¸çš„一å�Šï¼Œå› ä¸ºä¸¤è¾¹éƒ½åœ¨æ”¶ç¼©ã€‚å�¯ä»¥ä½¿ç”¨å¼•用矩形,因为它是在ä¸�进行激光补å�¿æ›´æ­£çš„æƒ…况下渲染的。这是一个简å�•的货æ�¶ç®±.ä¸�å�Œå¤–形的滑轮红绿ç�¯çº¢ç»¿ç�¯çº¢ç»¿ç�¯è®¾ç½®æ‰˜ç›˜ä¸�带地æ�¿å’Œå¤–墙的托盘æ�’入件-ä»…å…�许è¿�续墙托盘æ�’入件托盘æ�’入件设置å�˜å�‹å™¨å¸ƒå±€æ‰˜ç›˜å¸ƒå±€2托盘布局2设置纸盒和抽屉æ�’入件三角LEDç�¯ä¸‰è§’ç�¯ä¸‰è§’ç�¯è®¾ç½®ç‰™ç­¾ç›’牙签盒设置类å�‹æ‰˜ç›˜ - ä»…å…�许è¿�续墙å£�ç±»å�‹æ‰˜ç›˜ç±»å�‹æ‰˜ç›˜è®¾ç½®Uå�‹ç›’Uå�‹ç›’设置ä¸�å�‡åŒ€é«˜åº¦æ¡†ä¸�å�‡åŒ€é«˜åº¦æ¡†è®¾ç½®é€šç”¨ç›’å­�通用盒å­�设置æ�¾å¼›å­”采用六角形æ�’列,而ä¸�是正交æ�’列波浪形旋钮波浪形旋钮设置当使用“ doubleâ€�选项进行渲染时,具有å�Œæ§½çš„é›¶ä»¶å°†è¿�æ�¥åˆ°é��对称槽中的较短光æ�Ÿã€‚如æ�œæ²¡æœ‰â€œå�Œâ€�选项,则支æ�¶ä¼šæ›´ç‹­çª„。å�¡ç‰‡çš„宽度箱å­�的宽度(HP)手柄宽度六角è�ºæ “头宽度(mm)酒æ�¶é…’æ�¶è®¾ç½®XL您需è¦�一个适当长度的拉伸弹簧æ�¥ä½¿å¤¹é’³å·¥ä½œã€‚ å¢�加é¢�外的高度,以è�·å¾—更多的弹簧空间,并使滑动机æ�„ä¸�太å�¯èƒ½ç»‘定。 å�¯èƒ½éœ€è¦�在相互滑动的零件上添加一些蜡,以å‡�少摩擦。 添加盖å­�(最好ä¸�高角相对)加脚使机æ�¶å�¯ä»¥ç«™åœ¨åœ°ä¸Šå��墙附加高度é¢�外的盖å­�附加盖(仅用äº�直顶边)附加深度添加一个附加的å�‚直段以将开关ä¿�æŒ�在适当的ä½�置,在w/--稳固下工作最佳全部挂钩/支撑数é‡�角度生æˆ�槽的角度,以度为å�•ä½�。 å�‚ç›´0°。地æ�¿è§’度下方支撑的角度轮齿æ�¥è§¦çš„角度(以度为å�•ä½�)角孔有角度的盖å­�有角度的盖å­�2anklebolt1anklebolt2è½´bå��高æ¢�高波æ�Ÿå®½åº¦è�ºæ “å­”å�£å¾„å�Œæ—¶æ˜¾ç¤ºåº•部底部深度底部直径底边底钩底å�Šå¾„支撑角度 - 更少支撑x轴的个数y轴的个数颠簸激光补å�¿æ¿€å…‰è¡¥å�¿æ ¡æ­£ï¼Œå�•ä½�为mm(较大的值,适å�ˆæ›´ç´§å¯†ï¼‰ï¼Œä½¿ç”¨â€œé›¶ä»¶å’Œæ ·å“�â€�中的激光补å�¿æµ‹è¯•æ�¥æ‰¾åˆ°æ­£ç¡®çš„值。cc#盖直径凸轮高度å�¡ç‰‡é«˜åº¦å�¡ç‰‡å®½åº¦å€’è§’æ‹�角处的斜é�¢æŸœå­�间隙盒å­�中木æ�¿çš„间隙(x),å�•ä½�mmç›’å­�中木æ�¿çš„间隙(y),å�•ä½�mm盖的间隙间隙xé—´éš™yé—´éš™z关闭è¿�æ�¥è½¬è§’å�Šå¾„æ‹�角尺寸创建一个ç�¯å½¢é½¿è½®ï¼Œå°†ä¼ é€�带ä»�内部æ�¨å�‹åˆ‡å‰²dd#d1d2d3边框默认(无)三角齿深度底部深度顶部的深度地å�—背å��的深度å‰�槽深度凹槽的深度较长的深度(拧入å�¦ä¸€å�Šå°ºå¯¸çš„物体)机æ�¶çš„æ·±åº¦æ˜�暗器的深度较短(机æ�¶ï¼‰ä¾§çš„æ·±åº¦ä¸¤ä¾§çš„æ·±åº¦æ�’槽入å�£å�Šå¾„(毫米)沿瓶å­�底部的支æ�¶æ·±åº¦d孔直径底部直径顶部直径è¸�关节è�ºæ “孔直径 - 脚侧è¸�关节è�ºæ “孔直径 - 腿侧引脚直径,å�•ä½�mm定ä½�销的直径è�ºå­”下部直径调味ç½�直径轴直径车轴直径瓶å­�直径(毫米)凹槽底部直径(mm)工具孔的直径(手柄ä¸�适å�ˆï¼‰ç­›å­”直径木æ��孔的直径针孔直径销孔直径(mm)销的直径(mm)è�ºä¸�直径,mm轴的直径轴1的直径轴2的直径(ä¸�è½´1相å�Œï¼Œä¸ºé›¶ï¼‰o形圈的直径钩ä½�物的直径工具直径,包括抓å�–空间è�ºå­”上部直径尺寸圆盘直径光盘开始圆盘å�šåº¦è·�离ä»�å�¡æ¦«åˆ°åº•边的è·�离以å�šåº¦å€�数表示的弯曲切å�£è·�离分频器的凹å�£æ·±åº¦åˆ†é¢‘器的凹å�£çš„下å�Šå¾„分频器的缺å�£çš„上å�Šå¾„分隔线底边è·�分频器下凹å�£å�Šå¾„分隔槽深度分频器上凹å�£å�Šå¾„å�Œé‡�的轴1çš„D部分的百分比轴2çš„D部分的百分比在底部和顶部打几个孔,用1/4“的销钉穿过e直边底边的边缘类å�‹å·¦è¾¹ç¼˜çš„边缘类å�‹å�³è¾¹ç¼˜çš„边缘类å�‹ä¸Šã€�下边缘的边缘类å�‹é¡¶è¾¹çš„边缘类å�‹è¾¹ç¼˜æ ·å¼�边缘宽度使副ç�¯å…·æœ‰ç»™å®šå¢�é‡�到ç�¯å½¢é½¿è½®æ¯�三分之一å�‘外延伸直边沿ç�€è¾¹ç¼˜çš„长度延伸三角形将墙å£�延伸45°角。 需è¦�打磨22.5°斜角。é¢�外的高度使æ“�作更平滑(mm)æ�’槽宽度é¢�外的æ�¾å¼›ï¼ˆé™¤äº†å�šåº¦å’Œåˆ‡å�£ï¼‰ï¼Œä»¥å¸®åŠ©æ�’入分隔线调整å�¡æ¦«çš„间隙使他更容易活动å…�许移动的é¢�外空间é¢�外的高度é¢�外高度孔æ¯�个铰链的孔ff#撑脚å�¡æ¦«ä»–盖上固定长度的把手平é�¢å†²æ´—凹槽直径格å¼�生æˆ�的文件格å¼�四箱高度的分数ä¸�å�¡åº¦ç›¸å…³ä»�燕尾的一个中间到å�¦ä¸€ä¸ªå‰�端fwgg#在底部产生墙在左侧产生墙在å�³ä¾§äº§ç”Ÿå¢™é¡¶éƒ¨è¾ƒå®½çš„底部为零æ�¡æŠŠé•¿åº¦æ�¡æŠŠç™¾åˆ†æ¯”æ�¡æŠŠé«˜åº¦æ�¡æŠŠå®½åº¦é«˜æ�’å…¥å¼�å�¡æ¦«ï¼ˆæ— æ’‘角)手柄高度手柄宽度两侧有盖å­�é‡�å� ï¼ˆç±»ä¼¼äº�起始边)高度高äº�墙å£�的高度高度差ä»�左到å�³æœºæ�¶å�•ä½�高度å‰�å£�高度盖å­�高度以mm为å�•ä½�è¿�æ�¥é›¶ä»¶çš„(é“�)å�‹æ��的高度盒å­�的高度需è¦�支撑的ç½�的高度底部的高度左å‰�角的高度(mm)平é�¢å‰�部的高度å�³å‰�角的高度(mm)æ�¡æŠŠå­”的高度(mm)左å��角高度(mm)盖å­�的高度网å�£/usbå�£çš„高度(mm)å�³å��角的高度(mm)è�ºä¸�头高度(mm)å�Šé’©çš„高度å‰�边缘的墙高度高度0高度1高度2高度3高度身体的高度六角头六角形图案嗨较深锯齿的较高值(度)铰链强度铰链铰链强度ä¿�æŒ�长度æ´�孔径孔è·�边缘的è·�离(mm)孔è·�边缘孔格尺寸x孔格尺寸y孔直径æ´�å�£å­”è·�孔钩钩高度å�Šé’©é«˜åº¦é’©å­�燕尾巴伸出/伸入边缘的è·�离树è�“派有多少个æ�’槽凹槽应该加宽多少(-80到80)以模é‡�的百分比表示支撑å¢�加两侧的激光补å�¿å†…部深度(mm)内部深度(mm)(除é��选择外部)内部深度ä¸�包括阴影钩å­�的内部深度内部高度å�•ä½�mm(除é��选择外部)内墙的内部高度,å�•ä½�为mm(除é��选择外部)(ä¸�外部墙相å�Œï¼Œä¿�留为零)钩å­�的内部高度盒å­�的内å�Šå¾„(æ‹�角处)内宽(mm)(除é��外部选择)æ�§åˆ¶å�°çš„内部宽度里é�¢å†…侧角度ä»�内å�‘外å�‘音调键盘深度刀片å�šåº¦é—©é”�尺寸左侧左边缘左墙ä¿�æŒ�å¹³é�¢åœ¨å‰�é�¢çš„部分的长度平é�¢çš„长度长度腿长(最å°�34mm)分段轴到轴的长度长度1长度2长度3长度4长度5ç›–å­�ç›–å­�高度é™�制行星的数é‡�(0表示适å�ˆçš„æ•°é‡�)ä½�系数é”�止片mBarç›’å­�底部和分隔线之间的边è·�最大强度最大宽度最大高度最大夹紧高度(mm)在正常空间的多个起点和终点处的最大空间最大行星数测é‡�最å°�强度最å°�宽度最å°�高度最å°�最å°�夹紧高度(mm)铰链周围的最å°�空间最å°�空间mmH2OmmHg模数齿轮模数(mm)齿的模数,å�•ä½�mm显示器高度安装方å¼�:X=XLR,M=MIDI,P=9V电æº�,W=6.5m m-线,间è·�=下一æ�’å�£ä¸�周长比(0.1至0.45)。 确定宽深比å�£å�‹æ¯”nnema安装没有å�‚ç›´æ— æ•°é‡�æ•°é‡�最底行è¦�容纳的瓶å­�æ•°x行机械轴的个数ç½�头一列的数é‡�ç½�头一æ�’的数é‡�隔间数é‡�å‰�å��隔室数é‡�å¹¶æ�’的隔间数é‡�æ¯�个边缘的铰链数é‡�ç�¯çš„æ•°é‡�é”�止片数é‡�对数(æ¯�个测试四个激光补å�¿ï¼‰æœºæ�¶æ•°é‡�è´§æ�¶æ•°é‡�边数é�‹åº•æ•°é‡�齿轮å‡�速的阶段数轮齿数é‡�其他尺寸齿轮的齿数进轴齿数输出轴齿数行星上的齿数太阳齿轮上的齿数工具/æ�’槽数é‡�一侧墙å£�æ•°é‡�(1+)扳手的数é‡�一æ�’æ•°é‡�一列数é‡�八度å�¯èƒ½æ€§ä¸€å¼€å�£å�¯é€‰å�‚数车轮外径(包括Oå�‹åœˆï¼‰å¼€å§‹å¤–部尺寸外部支æ�¶å·¥å…·çš„æ€»å®½åº¦æ‚¬å�‚以mm为å�•ä½�的解å°�悬å�‚顶部边缘é‡�å� ï¼ˆé›¶è¡¨ç¤ºæ— ï¼‰å¯¹æ•°å‰�é�¢æ‰“开的百分比轴2çš„D部分的百分比(0表示ä¸�è½´1相å�Œï¼‰è½´1çš„D部分的百分比(圆轴为100)æ¯�个铰链件销销高度销的尺寸引脚宽度顶部管é�“关闭音调将支撑件æ�’入孔中(检查自己是å�¦é€‚å�ˆï¼‰è¡Œæ˜Ÿé½¿é—´éš™ä¸¤éƒ¨åˆ†ä¹‹é—´çš„间隙是å£�å�šçš„å€�æ•°æ�†ç›´å¾„å�‹åŠ›è§’å�‹åŠ›è§’é»˜è®¤ä¼šåœ¨å›¾çº¸åº•éƒ¨ç”Ÿæˆ�一个长度100mm的矩形框,方便确定图纸尺寸,输入0则ä¸�生æˆ�勾选å��,生æˆ�çš„æ¯�个零件外围都会出ç�°ä¸€ä¸ªçŸ©å½¢æ¡†è½®å»“齿带的轮廓轮廓调整rå­”å�Šå¾„å�Šå¾„槽的å�Šå¾„用钩å­�加固墙å£�çš„å�Šå¾„底角å�Šå¾„å­”å�Šå¾„æ‹�è§’å�Šå¾„è§’çš„å�Šå¾„,以mm为å�•ä½�在铰链中旋转的圆盘å�Šå¾„å­”å�Šå¾„(以å�šåº¦çš„å€�数表示)盖å­�活动铰链的å�Šå¾„æ§½å�£å�Šå¾„(mm)å‰�æ§½å�Šå¾„é¡¶è§’å�Šå¾„所有四个角都使用å�Šå¾„轨å��方因素长方形定ä½�框固定器固定孔边缘å�³ä¾§å�³è¾¹ç¼˜å�³å¢™åœ†ç›–圆机æ�¶æ•°æ©¡èƒ¶å�šåº¦sæ�’å…¥å¼�å�¡æ¦«ï¼ˆæœ‰æ’‘角)树è�“派筛孔尺寸è�ºä¸�é’‰è�ºä¸�1è�ºä¸�2è�ºä¸�头è�ºä¸�头高度è�ºä¸�孔尺寸第二针截é�¢ä»�å‰�å�‘å��以mm为å�•ä½�。 å�¯èƒ½çš„æ ¼å¼�:整体宽度/部分数,例如 "250/5";截é�¢å®½åº¦*截é�¢æ•°ä¾‹å¦‚ "50*5"ï¼› 截é�¢å®½åº¦ä¹‹é—´ç”¨â€œï¼šâ€�分隔,例如 “30:25.5:70ä»�下到上的部分以mm为å�•ä½�。è§�--sy的格å¼�ä»�左到å�³çš„部分以mm为å�•ä½�。è§�--sy的格å¼�锯齿角锯齿伺æœ�1a伺æœ�1b伺æœ�2a伺æœ�2b伺æœ�3a伺æœ�3b伺æœ�4a伺æœ�4b伺æœ�5a伺æœ�5b设置为较ä½�的值以è�·å�–引脚周围的ç£�盘色调轴轴1è½´2轴宽尖角角è�½é‡Œä¸‰è§’形的短边å�•一的大å°�é—©é”�的尺寸(以å�šåº¦çš„å€�数表示)槽角槽深槽é¢�外间隙槽å�Šå¾„槽宽æ�’槽用äº�抓å�–笔记的æ�’槽空间凹槽孔边缘孔下方的空间ç½�之间的空间孔之间的空间(å�šåº¦çš„å€�数)凹槽之间的空间è¿�æ�¥å™¨å‘¨å›´çš„空间(å�šåº¦çš„å€�数)间è·�沿Yæ–¹å�‘拆下盖(mm)开å�£ç›–弹簧弹性稳固堆å� ç�¯ç›´ç«‹ï¼ˆæˆ–å¹¶æ�’)阶段stepå�œæ­¢å¼ºåº¦æœ€å¤§æ‰³æ‰‹çš„强度最å°�扳手的强度伸展è�ºæŸ±æ ·å¼�使用的铰链样å¼�å�¡æ¦«æ ·å¼�顶部和盖å­�çš„é£�格太阳齿轮周边空间开关sxsyt切割ç¼�隙轮齿轮齿1轮齿2å�šåº¦å°†é”€é’‰ä¿�æŒ�在适当ä½�置的弧度刀的å�šåº¦ï¼ˆmm)。使用0ä¸�蜂çª�表一起使用。æ��料的å�šåº¦å¦‚æ�œæ˜¯æ¨±æ¡ƒè½´ï¼Œè½´æ�¿å�šåº¦éœ€è¦�1.5mm或更å°�刀具宽度刀具直径顶部顶部深度顶部直径顶边轴æ�¿å�šåº¦å°†å°ºå¯¸è§†ä¸ºåŒ…括墙å£�的外部测é‡�三角形二两件å�¯ä»¥ç»„å�ˆæˆ�最大宽度的两å€�臂段类å�‹è¦�使用的伺æœ�ç±»å�‹åœ¨ç¬¬äºŒé�¢ä½¿ç”¨çš„伺æœ�ç±»å�‹ï¼ˆå¦‚æ�œæ”¯æŒ�ä¸�å�Œï¼‰å�‹å�·1å�‹å�·2å�‹å�·3å�‹å�·4å�‹å�·5直立的使用å�¡æ¦«å­”边缘固定墙使用下é�¢é€‰æ‹©çš„å�•ä½�墙墙æ�¿å¢™æ³¢æµªè¦�添加哪个蜂巢墙宽度å�¡æ¦«å®½åº¦æœ€å¤§æ‰³æ‰‹çš„宽度槽的宽度最å°�扳手的宽度é�‹åº•æ�¡çº¹å®½åº¦ç”¨mm固定零件的切割ç¼�隙宽度(ä¸�支æŒ�所有地方)轮齿宽度以mm为å�•ä½�æ�¡æŠŠå­”的宽度(mm)(无孔为零)è¿�æ�¥é›¶ä»¶çš„(é“�)å�‹æ��的宽度底部宽度凹槽的宽度切å�£ä¸­çš„间隙宽度钩å­�宽度(背æ�¿ç¨�宽)ä»�ä¾§é�¢çœ‹é’©å­�的宽度长端宽度网å�£/usbå�£çš„宽度(毫米)å�‚ç›´äº�切å�£çš„图案宽度平é�¢å®½åº¦è½´çš„宽度周围å£�的宽度(mm)x孔区宽度y孔区宽度é£�å�‹é£�å�‹å�•ä½�è�ºä¸�头(mm)xyz
62,142
Python
.py
108
573.861111
11,443
0.511349
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,527
boxes.py.mo
florianfesti_boxes/locale/en/LC_MESSAGES/boxes.py.mo
fiï-Ñ?Ï2ËCπÈCN£EÏÚEflFÛFG G7GB<G.G3ÆGD‚GX'HÄHÑHB°H‰HÌH1ˇH1I&DIkI |IÜI ôI¶IºI√I”I(ÔIJ.JICJBçJ–JÿJ"ÈJ K<K.MK|KúK1∏K'ÍKL(.L!WL'yL°L.∑L'ÊL-M <M]M6yM∞M–M ÷M·MÒM˙M¸MNNN,N/HN8xN8±N ÍNÙN OO*(OSOhO"jOçOûOµOÕO+ÏOP%2P*XPÉPùPªPœPÿPÍPÚP QQ $Q1Q4GQ/|Q!¨QŒQ◊QÈQÎQ˙QR&R(R0RARJR\ReRwRÄRíRõR≠R∂R »R“RÂRSSS])SáSèSóSüSßS&∏SflSÂSÙS&˝SE$TjTTÅTâTëTôT≤TªTÕT·TˆTUU1)U[U%vU%úU¬U›U ‚U7U(V*V=V0YVäV,åVπVªVΩV√V “V›VÒVÛV ˜VWW,W#GWkWÛpW dXÖXòX ØXπXVÃX #Y/YDYbYwY/yY©YºYƒY ’YflY1ÚY1$ZVZ_ZqZzZ åZñZ)©Z”Z’Z ÿZÂZ˚Z["[)5[ _[6i[†[ ≥[æ[“[€[1Ì[0\ P\^\e\u\w\ y\É\ ñ\†\≥\ª\Ã\€\Ò\ ](']P]`] y]Ñ]ò]°] ≥] æ] …] ‘] fl]Í]EÒ]7^/G^ w^Ç^ ñ^†^≥^#µ^Ÿ^·^˝^_2_P_k_}_!ó_ π_⁄_ı_`#-`Q`!W`y`Å`-ò` ∆`—`,Â` aa31a ea:qa ¨aÕa÷aÊaˇab2bBb[blb Übîb´bøb‹bÒbc%cDcUcocÑc¢c™cªc ”cflc?Ùc 4dAd*WdÇdÜdãdédò£d<eYe*ue †e Æeªe—eH÷e f*f >f IfUfjfÉfåf(ûf«f–f‚f‰f Èf˜fg g-gCg=Lgäg ågñg©gºg–gg˘g hhii<i"Yi|i+ãi∑i»iÀiœiËiÓi˛i(j Gj Sj ^j jj ujÄjÖj áj ìj ûj®j±j∂j ªj»j ÿj ‰j j%˛j$k*k5/kekgk jk vk Äk ãkïkùk¥k ∫kƒkŸk ‡k ÎkA¯k:l@lBlElHlKlNlTl clnltlàlôlØlÕl‚lÙl mm"m+mBm-Vm,Ñm±mÀm(Êmn$n#:nA^n†nπnÿnÚno$o1<o&noïo,≥o(‡o p p !p-p<p)Ep/opüp ¶p ≥p¿pƒp∆p‡p¯pq (q73q kq vq0óq-»qˆq r !r-r1r@rBrEr$Lrqrvr |rärër™r(Ør)ÿrss s ss$s ;sGs Ws bsls ns {s5ásΩsƒs⁄s˙st%t69tptÇt%ïtªt&ÿtˇt$uBu%Tuzuôu°u©u±uπu¿u”u €uÊu-Èuv&v -v ;vGv LvYv bvovtvÜv1åv)ævËvÍvv w+w$Hwmw,Öwb≤wx(.x+WxÉxûx•x æx »x”x’x◊xÊx ËxÚx ˜x3y5yHyOyiyàyêyòy†y®y∞y ¥y2æy Òy˛yz z z z&z?Dz Ñzèz ñz £z ≠z∑zøz›z¸z{ {{{4{OP{ †{´{ ≠{ ∏{≈{ {Œ{’{$Ï{#|5|O|`|r|Ç|&í|π|*…| Ù|!}7}R}n} Ñ}•}∏}∫}¡}∆} }0›}~~ ~+~G~P~"j~ç~è~;ì~9œ~  )1:T Zf;kß ´∏«=÷+Ä@ÄHÄ bÄpÄsÄuÄwÄ~ÄÖÄ-ôīćÄÔÄÅ(!Å-JÅxÅ òÅπÅŒÅÓÅ ÛÅ ˇÅ Ç Ç Ç$Ç,Ç<Ç>ÇDÇKÇ RÇ\Ç lÇ∏wÇ10É1bÉîÉ £ÉÆÉ∂ÉæÉ∆ÉŒÉ÷ÉfiÉÊÉÓɈÉ4˛É3Ñ6Ñ=ÑCÑJÑQÑXÑ']Ñ ÖÑ êÑõÑ°ÑæÑ#ƒÑ.ËÑÖ8-ÖfÖ!nÖêÖôÖ&†Ö«ÖŒÖ÷ÖflÖ˙ÖÜÜ#Ü)Ü=ÜVÜ_ÜqÜ uÜÄÜÉÜÜÜàÜçÜìÜöÜ °Ü-´ÜCŸÜá 7á BáOá Sá ]ájá:sáÆá∑áªáœá?‰á$à*à0à6à<àBàDàLàeàgà làwà}à$Çàßà≠à√à€àÍàâIâbâ.wâ5¶â‹âÓâä-!äOäoä.Öä¥ä#«ä Îä¯ä ã(ã*ã,ã@.ãπoåN)éÏxéeèyèîè¶èΩèB¬è.ê34êDhêX≠êë ëB'ëjësë1Öë∑ë& ëÒë í í í,íBíIíYí(uíûí¥íI…íBìVì^ì"oìíì<ñì.”ìî"î1>î'pîòî(¥î!›î'ˇî'ï.=ï'lï-îï ¬ï„ï6ˇï6ñVñ \ñgñwñÄñÇñäñõñ¢ñ≤ñ/Œñ8˛ñ87ó pózó çóôó*ÆóŸóÓó"óò$ò;òSò+ròûò%∏ò*fiò ô#ôAôUô^ôpôxô âôïô ™ô∑ô4Õô/ö!2öTö]öoöqöÄöòö¨öÆö∂ö«ö–ö‚öÎö˝öõõ!õ3õ<õ NõXõkõáõéõûõ]Øõ úúú%ú-ú&>úeúkúzú&ÉúE™úúùùùùù8ùAùSùgù|ùîùùù1Øù·ù%¸ù%"ûHûcû hû7vûÆû∞û√û0flûü,ü?üAüCüIü Xücüwüyü }üäü†ü≤ü#ÕüÒüÛˆü ͆ °° 5°?°VR° ©°µ° °˰˝°/ˇ°/¢B¢J¢ [¢e¢1x¢1™¢‹¢¢˜¢£ ££)/£Y£[£ ^£k£Å£Ü£"ò£)ª£ £6Ô£&§ 9§D§X§a§1s§0•§ ÷§‰§Χ˚§˝§ ˇ§ • •&•9•A•R•a•w•ì•(≠•÷•Ê• ˇ• ¶¶'¶ 9¶ D¶ O¶ Z¶ e¶p¶Ew¶Ω¶/Õ¶ ˝¶ß ß&ß9ß#;ß_ßgßÉßùß∏ß÷ßÒß®!® ?®`®{®ñ®#≥®◊®!›®ˇ®©-© L©W©,k© ò©£©3∑© Ω:˜© 2™S™\™l™Ö™ö™∏™»™·™Ú™ ´´1´E´b´w´ï´´´ ´€´ı´ ¨(¨0¨A¨ Y¨e¨?z¨ ∫¨«¨*›¨≠ ≠≠≠ò)≠¬≠fl≠*˚≠ &Æ 4ÆAÆWÆH\Æ •Æ∞Æ ƒÆ œÆ€ÆÆ ØØ($ØMØVØhØjØ oØ}ØçØ ¶Ø≥Ø…Ø=“Ø∞ ∞∞/∞B∞V∞v∞∞ë∞î∞ù±ü±<¢±"fl±≤+≤=≤N≤Q≤U≤n≤t≤Ñ≤(§≤ Õ≤ Ÿ≤ ‰≤ ≤ ˚≤≥ ≥ ≥ ≥ $≥.≥7≥<≥ A≥N≥ ^≥ j≥ v≥%Ñ≥™≥∞≥5µ≥Î≥Ì≥ ≥ ¸≥ ¥ ¥¥#¥:¥ @¥J¥_¥ f¥ q¥A~¥¿¥∆¥»¥À¥Œ¥—¥‘¥⁄¥ È¥Ù¥˙¥µµ5µSµhµzµèµ¢µ®µ±µ»µ-‹µ, ∂7∂Q∂(l∂ï∂™∂#¿∂A‰∂&∑?∑^∑x∑î∑™∑1¬∑&Ù∑∏,9∏(f∏ è∏ ô∏ ß∏≥∏¬∏)À∏/ı∏%π ,π 9πFπJπLπfπ~πóπ Æπ7ππ Òπ ¸π0∫-N∫|∫ ö∫ ß∫≥∫∑∫∆∫»∫À∫$“∫˜∫¸∫ ªªª0ª(5ª)^ªàªéªëªìªñª$úª ¡ªÕª ›ª ˪Úª Ùª º5 ºCºJº`ºĺﺴº6øºˆºΩ%ΩAΩ&^ΩÖΩ$£Ω»Ω%⁄Ωææ'æ/æ7æ?æFæYæ aælæ-oæùæ¨æ ≥æ ¡æÕæ “æflæ Ëæıæ˙æ ø1ø)Dønøpøvøêø+¢ø$ŒøÛø, ¿b8¿õ¿(¥¿+›¿ ¡$¡+¡ D¡ N¡Y¡[¡]¡l¡ n¡x¡ }¡3ᡪ¡Œ¡’¡Ô¡¬¬¬&¬.¬6¬ :¬2D¬ w¬Ѭܬ 㬠ò¬ ¢¬¨¬? ¬ √√ √ )√ 3√=√E√c√Ç√ã√ë√ñ√û√∫√O÷√ &ƒ1ƒ 3ƒ >ƒKƒPƒTƒ[ƒ$rƒ#󃪃’ƒʃ¯ƒ≈&≈?≈*O≈ z≈!õ≈Ω≈ÿ≈Ù≈ ∆+∆>∆@∆G∆L∆P∆0c∆î∆õ∆ £∆±∆Õ∆÷∆"∆««;«9U«è«†« §«Ø«∑«¿«⁄« ‡«Ï«;Ò«-» 1»>»M»=\»+ö»∆»Œ» Ë»ˆ»˘»˚»˝»… …-…M…f…u…ã…(ß…-–…˛…  ? T t  y  Ö è  ï  † ™ ≤ ¬ ƒ   —  ÿ ‚  Ú ∏˝ 1∂À1ËÀà )Ã4Ã<ÃDÃLÃTÃ\ÃdÃlÃtÃ|Ã4ÑÃπúÃ√ÅÖÃ◊ÃfiÃ'„Ã Õ Õ!Õ'ÕDÕ#JÕ.nÕùÕ8≥ÕÏÕ!ÙÕŒŒ&&ŒMŒTŒ\ŒeŒÄŒúŒ§Œ©ŒØŒ√Œ‹ŒÂŒ˜Œ ˚Œœ œ œœœœ œ 'œ-1œC_œ£œ Ωœ »œ’œ Ÿœ „œœ:˘œ4–=–A–U–?j–™–∞–∂–º–¬–»– –“–ΖÌ– Ú–˝–—$—-—3—I—a—p—â—Iû—Ë—.˝—5,“b“t“â“-ß“’“ı“. ”:”#M” q”~”ë”Æ”∞”≤”0ÙfóB∑∫*ı™ª»rzG>RÅfi K=ëy2VO˛¨ŸüÀ”·GàµÙè ¨˝íW>Mgkãü£`¶´ö猂„$Z#“¯Ñ˘Ái<çP/◊ÔÚ4m‰IgQÖûµÚß@AvCJôπ‡õÆÇdl,;-A⁄7ÈÆ%™∫Eu H •B¥íæî8Œè˜V(_ˇ9˙+±ñ#l.."Ç«A≈,J$ù—·5¢˜~=ÕE 57G`∂}üùF.â y+XÓÉ?áo÷«∞l˚6VÆeMø€°äÿï√∂≈aî œÏÛY}f±®}f@'≥)#ƒÑ‰¯3xÙI:„ QT$¸• ö∆òÍ ˙ôUÉá6©Ìãˇ’…÷ÑcL˛+19| ıo©fl°Îa˝')¿6¢ΩD‹'≥ˆ(tYKıÄ:Jd¿ñ¶Öj]m“fiÒÅ˙˝3k–Ë◊|õ €ªèË∆h_v´{F&ìå%,|[jo’fi Îõú-ó]ÊÓØËôqæóÿSx ºy2ïÛï,û/‡ÊºúR≠xì[†Ω›È€pÈeß3tOqß∂–∞ ÷¸∑∞π …>Ü%aZ1v<¶°kj{i<±\ødêE+!R^ØNflˇq ”å*‚·=zzU¡£pãO*É:nprt‘?Ì¡b[¥Ïs∆;C@^ £ÏTLYà◊Äò_≤¬® ;≤ç∏ à œù ë¡∏≈Î7Õw/µu‰n!Ò%©¬~H›Ã&≠æ&PêÓ—§1†‘ÚÇ&r»FmÍØ!-?#¯ÂéS¨¥“~‹Q™MŸ4ŒX ∫Ôé˘fl«SPWD䃸ÕêN≥ ⁄ÜÂ4⁄òœ(C5Ô√”›¢0§cñÅ$Á˘N0"•\K∏hTå„bg-8ÀÖ≠®Uê)‹\w¬ø 9—áî–Ÿ¿nc»Û˜º∑íZ’ûÿ"ëˆπìsÌ√u˛DH  ÍIâú…܈Áse§`8´Ä(Ã*2†"BhƒLÊ)Òb]Àä≤i{!â˚ΩéX'‘w˚‚Wö‡^ <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Cuttlery stand with carrying grip using flex for rounded corners Vitamins: DSP5005 (or similar) power supply, two banana sockets, two 4.8mm flat terminals with flat soldering tag To allow powering by laptop power supply: flip switch, Lenovo round socket (or adjust right hole for different socket) "outset" or "flush""spring", "stud" or "none""wave" or "bumps"# pieces of outer wall40DPA Type tray variant to be used up right with sloped walls in frontA clamp to hold down material to a knife tableA hook wit a rectangular mouth to mount at the wallA rack for storing disk-shaped objects vertically next to each otherA two piece box where top slips over the bottom half to form the enclosure. AT5Add external mounting pointsAdditional space kept between the disks and the outbox of the rackAllEdgesAllEdges SettingsAmount of circumference used for non convex partsAn error occurred!Angle between convex and concave partsAngle of the cutAngledBoxAngledBox SettingsAngledCutJigAngledCutJig SettingsArcadeArcade SettingsBackwards slant of the rackBalanced force Difference Planetary GearBar to hang pliers onBass Recorder EndpinBench power supply powered with Maktia 18V battery or laptop power supplyBeware of the rolling shutter effect! Use wax on sliding surfaces.BinTrayBinTray SettingsBook cover with flex for the spineBoxBox for drills with each compartment with a different heightBox for holding a stack of paper, coasters etcBox for storage of playingcardsBox in the form of an heartBox various options for different stypes and lidsBox with a rolling shutter made of flexBox with both ends corneredBox with different height in each cornerBox with lid and integraded hingeBox with lid attached by cabinet hingesBox with living hingeBox with living hinge and left corners roundedBox with living hinge and round cornersBox with living hinge and top corners roundedBox with regular polygon as baseBox with top and front openBox with various options for different styles and lidsBox with vertical edges roundedBoxesBoxes - %sBoxes with flexBoxes.pyCCardBoxCardBox SettingsCastleCastle SettingsCastle tower with two wallsClosed box with screw on top and mounting holesClosed box with screw on top for mounting in a 10" rack.Closed box with screw on top for mounting in a 19" rack.ClosedBoxClosedBox SettingsConcaveKnobConcaveKnob SettingsCreate boxes and more with a laser cutter!Cutup to mouth ratioDD-Flat in fraction of the diameterDefault SettingsDefaultParams SettingsDesktop Arcade MaschineDiameter of the bolt hole (mm)Diameter of the inner lid screw holes in mmDiameter of the knob (mm)Diameter of the lid screw holes in mmDiameter of the mounting screw holes in mmDiameter of the paintcansDiplay for flyers or leafletsDisc diameter in mmDiscRackDiscRack SettingsDisplayDisplay SettingsDisplayCaseDisplayCase SettingsDisplayShelfDisplayShelf SettingsDistance in halftones in the Normalmensur by T√∂pferDistance of the screw holes from the wall in mmDocumentation and API DescriptionDrillBoxDrillBox SettingsEElectronicsBoxElectronicsBox SettingsError generating %sFFlexBoxFlexBox SettingsFlexBox2FlexBox2 SettingsFlexBox3FlexBox3 SettingsFlexBox4FlexBox4 SettingsFlexBox5FlexBox5 SettingsFlexTestFlexTest SettingsFlexTest2FlexTest2 SettingsFoam soles for the OttO botFolderFolder SettingsFully closed boxFully closed box intended to be cut from transparent acrylics and to serve as a display case.GT2_2mmGT2_3mmGT2_5mmGearBoxGearBox SettingsGearbox with multiple identical stagesGearsGears SettingsGenerateGenerate a typetray from a layout fileGenerators are still untested or need manual adjustment to be useful.Get Source at GitHubHHTD_3mmHTD_5mmHTD_8mmHackaday.io Project PageHeartBoxHeartBox SettingsHeight of the cardsHeight of the handleHeight of the paintcansHingeBoxHingeBox SettingsHint of how much the flex part should be shortendHold a plane to a slatwallHold a set of wrenches at a slat wallHolds a single caliper to a slat wallHoney Comb Style Wine RackHookHook SettingsHook for pole like things to be clamped to another poleIIntegratedHingeBoxIntegratedHingeBox SettingsIntonation Number. 2 for max. efficiency, 3 max.JJig for making angled cuts in a laser cutterKLLBeamLBeam SettingsLaserClampLaserClamp SettingsMMXLMagazineFileMagazineFile SettingsMakitaPowerSupplyMakitaPowerSupply SettingsMinimum space between the paintcansMiscMost of the blue lines need to be engraved by cutting with high speed and low power. But there are three blue holes that actually need to be cut: The grip hole in the lid and two tiny rectangles on the top and bottom for the lid to grip into. Mounting braket for a Nema motorNEMA size of motorNema size of the motorNemaMountNemaMount SettingsNot yet parametrized box for drills from 1 to 12.5mm in 0.5mm steps, 3 holes each sizeNotesHolderNotesHolder SettingsNumber of rounded top cornersNumber of serrationsOOctave in International Pitch Notation (2 == C)Open magazine fileOpenBoxOpenBox SettingsOrganPipeOrganPipe SettingsOtto LC - a laser cut chassis for Otto DIY - bodyOtto LC - a laser cut chassis for Otto DIY - legsOttoBodyOttoBody SettingsOttoLegsOttoLegs SettingsOttoSolesOttoSoles SettingsOutset and angled plate to mount stuff toPPaPaintStoragePaintStorage SettingsPartParts and SamplesPiece for testing 2D flex settingsPiece for testing different flex settingsPlanetaryPlanetary Gear with possibly multiple identical stagesPlanetary SettingsPlanetary2Planetary2 SettingsPoleHookPoleHook SettingsPosition of the lower rack grids along the radiusPosition of the rear rack grids along the radiusProfile shiftPulleyPulley SettingsQRRack10BoxRack10Box SettingsRack19BoxRack19Box SettingsRackBoxRackBox SettingsRadius of combRadius of the cornersRadius of the corners in mmRadius of the latch in mmRectangular organ pipe based on pipecalcRectangularWallRectangularWall SettingsRegularBoxRegularBox SettingsRobotArmRobotArm SettingsRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotary Attachment for engraving cylindrical objects in a laser cutterRotary SettingsRound knob serrated outside for better grippingRoundedBoxRoundedBox SettingsRoyalGameRoyalGame SettingsSSegments of servo powered robot armServo9gSettings for Cabinet HingesSettings for Chest HingesSettings for Click-on LidsSettings for Dove Tail JointsSettings for Finger JointsSettings for FlexSettings for GrippingEdgeSettings for Hinges and HingePinsSettings for RoundedTriangleEdgeSettings for SlatWallEdgesSettings for Slide-on LidsSettings for Stackable EdgesSettings for rack (and pinion) edgeShelfShelf with forward slanted floorsShelvesShowing all edge typesShows the different edge types for slat wallsShutterBoxShutterBox SettingsSides of the triangles holding the lid in mmSilverwareSilverware SettingsSimple L-Beam: two pieces joined with a right angleSimple wallSlat wall tool holder for chisels, files and similar toolsSlat wall tool holder with slotsSlatWallSlatwallCaliperSlatwallCaliper SettingsSlatwallChiselHolderSlatwallChiselHolder SettingsSlatwallConsoleSlatwallConsole SettingsSlatwallDrillBoxSlatwallDrillBox SettingsSlatwallEdgesSlatwallEdges SettingsSlatwallPlaneHolderSlatwallPlaneHolder SettingsSlatwallPliersHolderSlatwallPliersHolder SettingsSlatwallSlottedHolderSlatwallSlottedHolder SettingsSlatwallTypeTraySlatwallTypeTray SettingsSlatwallWrenchHolderSlatwallWrenchHolder SettingsStachelStachel SettingsStackable paint storageStorageRackStorageRack SettingsStorageRack to store boxes and trays which have their own floorStorageShelfStorageShelf SettingsStorageShelf can be used to store TypetrayT10T2_5T5The Royal Game of UrThe traffic light was created to visualize the status of a Icinga monitored system. When turned by 90¬∞, it can be also used to create a bottle holder.Thickness of the discs in mmThis is a simple shelf box.Timing belt pulleys for different profilesTraffic lightTrafficLightTrafficLight SettingsTrayTray insert without floor and outer walls - allows only continuous wallsTrayInsertTrayInsert SettingsTrayLayoutTrayLayout2TrayLayout2 SettingsTrays and Drawer InsertsTwoPieceTwoPiece SettingsType tray - allows only continuous wallsTypeTrayTypeTray SettingsUUBoxUBox SettingsUnevenHeightBoxUnevenHeightBox SettingsUniversalBoxUniversalBox SettingsUnstableUse hexagonal arrangement for the holes instead of orthogonalVWaivyKnobWaivyKnob SettingsWidth of the cardsWidth of the handleWidth of the hex bolt head (mm)WineRackWineRack SettingsXLYou need a tension spring of the proper length to make the clamp work. Increace extraheight to get more space for the spring and to make the sliding mechanism less likely to bind. You may need to add some wax on the parts sliding on each other to reduce friction. aa#add a lid (works best with high corners opposing each other)additional height of the back walladditional lidadditional lid (for straight top_edge only)additional_depthaiallamount of hooks / bracesangleangle of floorsangle of the support underneethangle of the teeth touching (in degrees)angled holeangled lidangled lid2anklebolt1anklebolt2axlebback_heightbeamheightbeamwidthboltholeborebothbottom_depthbottom_diameterbottom_edgebottom_hookbottom_radiusbracing angle - less for more bracingbumpsburnburn correction in mm (bigger values for tighter fit)cc#candiametercanheightcardheightcardwidthchamferchamfer at the cornerschestclearanceclearance of the lidclosedconnectioncornerradiuscreate a ring gear with the belt being pushed against from withincutupdd#d1d2d3debugdefault (none)deltateethdepthdepth at the bottomdepth at the topdepth behind the lotsdepth of slots from the frontdepth of the groovesdepth of the rackdepth of the shadersdepth of the sidesdholediameterdiameter at the bottomdiameter at the topdiameter for hole for ankle bolts - foot sidediameter for hole for ankle bolts - leg sidediameter if the pin in mmdiameter of alignment pinsdiameter of lower part of the screw holediameter of the axlediameter of the axlesdiameter of the flutes bottom in mmdiameter of the hole for the tool (handle should not fit through)diameter of the pin holediameter of the pin hole in mmdiameter of the pin in mmdiameter of the screw in mmdiameter of the shaftdiameter of the shaft 1diameter of the shaft2 (zero for same as shaft 1)diameter of the strings of the O ringsdiameter of the thing to hookdiameter of the tool including space to grabdiameter of upper part of the screw holedimensiondisc_diameterdisc_outsetdisc_thicknessdistancedistance from finger holes to bottom edgedistance of flex cuts in multiples of thicknessdoubledpercentage1dpercentage2dxfeedge type for bottom edgeedge type for left edgeedge type for right edgeedge type for top edgeedge_widthenable secondary ring with given delta to the ring geareverythirdextend outward the straight edgeextend the triangle along the length of the edgeextra height to make operation smoother in mmextra space to allow movementextra_heightextraheighteyeeyes_per_hingeff#fingerfixed length of the grips on he lidsflatflushflutediameterformatformat of resulting filefourfraction of bin height covert with slopefrom one middle of a dove tail to anotherfrontfwgg#gcodegreater zero for top wider as bottomgrip_lengthgrip_percentagegripheightgripwidthhhandleheighthandlewidthhave lid overlap at the sides (similar to OutSetEdge)heightheight above the wallheight difference left to rightheight in rack unitsheight of front wallsheight of lid in mmheight of the (aluminium) profile connecting the partsheight of the boxheight of the feetheight of the front left corner in mmheight of the front of planeheight of the front right corner in mmheight of the grip hole in mmheight of the left back corner in mmheight of the lidheight of the right back corner in mmheight of the screw head in mmheight0height1height2height3heigthheigth of the bodyhexheadhexpatternhihigher values for deeper serrations (degrees)hinge_strengthhingeshingestrengthhold_lengthholeholediameterholedistholedistancehookhook_extra_heighthookshow far the dove tails stick out of/into the edgehow much should fingers widen (-80 to 80)iin Pain precent of the modulusinner depth in mminner depth in mm (unless outside selected)inner depth not including the shadesinner depth of the hookinner height in mm (unless outside selected)inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)inner height of the hookinner radius if the box (at the corners)inner width in mm (unless outside selected)inner width of the consoleinsideinside angle of the feetinsideoutintonationjkknifethicknessllatchsizeleftleft_edgelegth of the part hiolding the plane over the frontlegth of the planelengthlength of legs (34mm min)length of segment axle to axlelength1length2length3length4length5lidlidheightlimit the number of planets (0 for as much as fit)lower_factormmBarmax_strengthmax_widthmaxheightmaximal clamping height in mmmaximum space at the start and end in multiple of normal spacesmaxplanetsmensurmin_strengthmin_widthminheightminimalminimal clamping height in mmminimum space around the hingeminspacemmH2OmmHgmodulusmodulus of the gear (in mm)modulus of the theeth in mmmouth to circumference ratio (0.1 to 0.45). Determines the width to depth ratiomouthrationnema_mountno_verticalsnonenumnumbernumber of compartmentsnumber of compartments back to frontnumber of compartments side by sidenumber of hinges per edgenumber of lightsnumber of shelvesnumber of sidesnumber of solesnumber of stages in the gear reductionnumber of teethnumber of teeth in the other size of gearsnumber of teeth on ingoing shaftnumber of teeth on outgoing shaftnumber of teeth on planetsnumber of teeth on sun gearnumber of tools/slotsnumber of walls at one side (1+)number of wrenchesooctaveoddsoneoptional argumentsouter diameter of the wheels (including O rings)outsetoutsideoutsidemountsoverall width for the toolsoverhangoverhang for joints in mmoverlap of top rim (zero for none)ppdfpercent of the D section of shaft 1 (0 for same as shaft 1)percent of the D section of shaft 1 (100 for round shaft)pieces per hingepinpin_heightpinsizepinwidthpipe is closed at the toppitchplanetteethplayplay between the two parts as multipleof the wall thicknesspltpolediameterpressure anglepressure_angleprint reference rectangle with given length (zero to disable)print surrounding boxes for some structuresprofileprofile of the teeth/beltprofile_shiftpsqrr_holeradiusradius at the slotsradius for strengthening walls with the hooksradius of bottom cornersradius of holeradius of the cornersradius of the corners in mmradius of the disc rotating in the hingeradius of the eye (in multiples of thickness)radius of the lids living hingeradius of the slots at the frontradius of top cornerradius used on all four cornersrailrear_factorreferencerightright_edgeround lidroundedrubberthicknesssscrewscrew1screw2screwheadscrewheadheightsecond_pinsections back to front in mm. Possible formats: overallwidth/numberof sections e.g. "250/5"; sectionwidth*numberofsections e.g. "50*5"; section widths separated by ":" e.g. "30:25.5:70sections bottom to top in mm. See --sy for formatsections left to right in mm. See --sy for formatserrationangleserrationsservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bset to lower value to get disks surrounding the pinsshshadesshaftshaft1shaft2singlesizesize of latch in multiples of thicknessslot_depthslot_widthslotsslots for grabbing the notesspacespace below holes of FingerHoleEdgespace between eyes (in multiples of thickness)space between fingersspace surrounding connectors (in multiples of thickness)spacingsplit the lid in y direction (mm)splitlidspringstack lights upright (or side by side)stagesstoppedstrengthstrength of largest wrenchstrength of smallest wrenchstretchstudstylestyle of hinge usedstyle of the top and lidsunteethsurroundingspacessvgsvg_Ponokosxsyttabsteethteeth1teeth2thicknessthickness of the arc holding the pin in placethickness of the knifes in mm. Use 0 for use with honey comb table.thickness of the materialtool_widthtooldiametertoptop_depthtop_diametertop_edgetreat sizes as outside measurements that include the wallstriangletwotype of arm segmenttype of servo to usetype of servo to use on second side (if different is supported)type1type2type3type4type5uuprightuses unit selected belowvwallwallpieceswallswavewhich of the honey comb walls to addwidthwidth of finger holeswidth of largest wrenchwidth of slotswidth of smallest wrenchwidth of sole stripewidth of tabs holding the parts in place in mm (not supported everywhere)width of teeth in mmwidth of th grip hole in mm (zero for no hole)width of the (aluminium) profile connecting the partswidth of the feetwidth of the fingerswidth of the gaps in the cutswidth of the hook (back plate is a bit wider)width of the hook from the sidewidth of the long endwidth of the pattern perpendicular to the cutswidth of the planewidth of the surrounding wall in mmwindpressurewindpressure_unitswith of the screw head in mmxyzProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: 2019-08-23 19:42+0200 Last-Translator: Florian Festi <florian@festi.info> Language-Team: English Language: en MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Cuttlery stand with carrying grip using flex for rounded corners Vitamins: DSP5005 (or similar) power supply, two banana sockets, two 4.8mm flat terminals with flat soldering tag To allow powering by laptop power supply: flip switch, Lenovo round socket (or adjust right hole for different socket) "outset" or "flush""spring", "stud" or "none""wave" or "bumps"# pieces of outer wall40DPA Type tray variant to be used up right with sloped walls in frontA clamp to hold down material to a knife tableA hook wit a rectangular mouth to mount at the wallA rack for storing disk-shaped objects vertically next to each otherA two piece box where top slips over the bottom half to form the enclosure. AT5Add external mounting pointsAdditional space kept between the disks and the outbox of the rackAllEdgesAllEdges SettingsAmount of circumference used for non convex partsAn error occurred!Angle between convex and concave partsAngle of the cutAngledBoxAngledBox SettingsAngledCutJigAngledCutJig SettingsArcadeArcade SettingsBackwards slant of the rackBalanced force Difference Planetary GearBar to hang pliers onBass Recorder EndpinBench power supply powered with Maktia 18V battery or laptop power supplyBeware of the rolling shutter effect! Use wax on sliding surfaces.BinTrayBinTray SettingsBook cover with flex for the spineBoxBox for drills with each compartment with a different heightBox for holding a stack of paper, coasters etcBox for storage of playingcardsBox in the form of an heartBox various options for different stypes and lidsBox with a rolling shutter made of flexBox with both ends corneredBox with different height in each cornerBox with lid and integraded hingeBox with lid attached by cabinet hingesBox with living hingeBox with living hinge and left corners roundedBox with living hinge and round cornersBox with living hinge and top corners roundedBox with regular polygon as baseBox with top and front openBox with various options for different styles and lidsBox with vertical edges roundedBoxesBoxes - %sBoxes with flexBoxes.pyCCardBoxCardBox SettingsCastleCastle SettingsCastle tower with two wallsClosed box with screw on top and mounting holesClosed box with screw on top for mounting in a 10" rack.Closed box with screw on top for mounting in a 19" rack.ClosedBoxClosedBox SettingsConcaveKnobConcaveKnob SettingsCreate boxes and more with a laser cutter!Cutup to mouth ratioDD-Flat in fraction of the diameterDefault SettingsDefaultParams SettingsDesktop Arcade MaschineDiameter of the bolt hole (mm)Diameter of the inner lid screw holes in mmDiameter of the knob (mm)Diameter of the lid screw holes in mmDiameter of the mounting screw holes in mmDiameter of the paintcansDiplay for flyers or leafletsDisc diameter in mmDiscRackDiscRack SettingsDisplayDisplay SettingsDisplayCaseDisplayCase SettingsDisplayShelfDisplayShelf SettingsDistance in halftones in the Normalmensur by T√∂pferDistance of the screw holes from the wall in mmDocumentation and API DescriptionDrillBoxDrillBox SettingsEElectronicsBoxElectronicsBox SettingsError generating %sFFlexBoxFlexBox SettingsFlexBox2FlexBox2 SettingsFlexBox3FlexBox3 SettingsFlexBox4FlexBox4 SettingsFlexBox5FlexBox5 SettingsFlexTestFlexTest SettingsFlexTest2FlexTest2 SettingsFoam soles for the OttO botFolderFolder SettingsFully closed boxFully closed box intended to be cut from transparent acrylics and to serve as a display case.GT2_2mmGT2_3mmGT2_5mmGearBoxGearBox SettingsGearbox with multiple identical stagesGearsGears SettingsGenerateGenerate a typetray from a layout fileGenerators are still untested or need manual adjustment to be useful.Get Source at GitHubHHTD_3mmHTD_5mmHTD_8mmHackaday.io Project PageHeartBoxHeartBox SettingsHeight of the cardsHeight of the handleHeight of the paintcansHingeBoxHingeBox SettingsHint of how much the flex part should be shortendHold a plane to a slatwallHold a set of wrenches at a slat wallHolds a single caliper to a slat wallHoney Comb Style Wine RackHookHook SettingsHook for pole like things to be clamped to another poleIIntegratedHingeBoxIntegratedHingeBox SettingsIntonation Number. 2 for max. efficiency, 3 max.JJig for making angled cuts in a laser cutterKLLBeamLBeam SettingsLaserClampLaserClamp SettingsMMXLMagazineFileMagazineFile SettingsMakitaPowerSupplyMakitaPowerSupply SettingsMinimum space between the paintcansMiscMost of the blue lines need to be engraved by cutting with high speed and low power. But there are three blue holes that actually need to be cut: The grip hole in the lid and two tiny rectangles on the top and bottom for the lid to grip into. Mounting braket for a Nema motorNEMA size of motorNema size of the motorNemaMountNemaMount SettingsNot yet parametrized box for drills from 1 to 12.5mm in 0.5mm steps, 3 holes each sizeNotesHolderNotesHolder SettingsNumber of rounded top cornersNumber of serrationsOOctave in International Pitch Notation (2 == C)Open magazine fileOpenBoxOpenBox SettingsOrganPipeOrganPipe SettingsOtto LC - a laser cut chassis for Otto DIY - bodyOtto LC - a laser cut chassis for Otto DIY - legsOttoBodyOttoBody SettingsOttoLegsOttoLegs SettingsOttoSolesOttoSoles SettingsOutset and angled plate to mount stuff toPPaPaintStoragePaintStorage SettingsPartParts and SamplesPiece for testing 2D flex settingsPiece for testing different flex settingsPlanetaryPlanetary Gear with possibly multiple identical stagesPlanetary SettingsPlanetary2Planetary2 SettingsPoleHookPoleHook SettingsPosition of the lower rack grids along the radiusPosition of the rear rack grids along the radiusProfile shiftPulleyPulley SettingsQRRack10BoxRack10Box SettingsRack19BoxRack19Box SettingsRackBoxRackBox SettingsRadius of combRadius of the cornersRadius of the corners in mmRadius of the latch in mmRectangular organ pipe based on pipecalcRectangularWallRectangularWall SettingsRegularBoxRegularBox SettingsRobotArmRobotArm SettingsRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotary Attachment for engraving cylindrical objects in a laser cutterRotary SettingsRound knob serrated outside for better grippingRoundedBoxRoundedBox SettingsRoyalGameRoyalGame SettingsSSegments of servo powered robot armServo9gSettings for Cabinet HingesSettings for Chest HingesSettings for Click-on LidsSettings for Dove Tail JointsSettings for Finger JointsSettings for FlexSettings for GrippingEdgeSettings for Hinges and HingePinsSettings for RoundedTriangleEdgeSettings for SlatWallEdgesSettings for Slide-on LidsSettings for Stackable EdgesSettings for rack (and pinion) edgeShelfShelf with forward slanted floorsShelvesShowing all edge typesShows the different edge types for slat wallsShutterBoxShutterBox SettingsSides of the triangles holding the lid in mmSilverwareSilverware SettingsSimple L-Beam: two pieces joined with a right angleSimple wallSlat wall tool holder for chisels, files and similar toolsSlat wall tool holder with slotsSlatWallSlatwallCaliperSlatwallCaliper SettingsSlatwallChiselHolderSlatwallChiselHolder SettingsSlatwallConsoleSlatwallConsole SettingsSlatwallDrillBoxSlatwallDrillBox SettingsSlatwallEdgesSlatwallEdges SettingsSlatwallPlaneHolderSlatwallPlaneHolder SettingsSlatwallPliersHolderSlatwallPliersHolder SettingsSlatwallSlottedHolderSlatwallSlottedHolder SettingsSlatwallTypeTraySlatwallTypeTray SettingsSlatwallWrenchHolderSlatwallWrenchHolder SettingsStachelStachel SettingsStackable paint storageStorageRackStorageRack SettingsStorageRack to store boxes and trays which have their own floorStorageShelfStorageShelf SettingsStorageShelf can be used to store TypetrayT10T2_5T5The Royal Game of UrThe traffic light was created to visualize the status of a Icinga monitored system. When turned by 90¬∞, it can be also used to create a bottle holder.Thickness of the discs in mmThis is a simple shelf box.Timing belt pulleys for different profilesTraffic lightTrafficLightTrafficLight SettingsTrayTray insert without floor and outer walls - allows only continuous wallsTrayInsertTrayInsert SettingsTrayLayoutTrayLayout2TrayLayout2 SettingsTrays and Drawer InsertsTwoPieceTwoPiece SettingsType tray - allows only continuous wallsTypeTrayTypeTray SettingsUUBoxUBox SettingsUnevenHeightBoxUnevenHeightBox SettingsUniversalBoxUniversalBox SettingsUnstableUse hexagonal arrangement for the holes instead of orthogonalVWaivyKnobWaivyKnob SettingsWidth of the cardsWidth of the handleWidth of the hex bolt head (mm)WineRackWineRack SettingsXLYou need a tension spring of the proper length to make the clamp work. Increace extraheight to get more space for the spring and to make the sliding mechanism less likely to bind. You may need to add some wax on the parts sliding on each other to reduce friction. aa#add a lid (works best with high corners opposing each other)additional height of the back walladditional lidadditional lid (for straight top_edge only)additional_depthaiallamount of hooks / bracesangleangle of floorsangle of the support underneethangle of the teeth touching (in degrees)angled holeangled lidangled lid2anklebolt1anklebolt2axlebback_heightbeamheightbeamwidthboltholeborebothbottom_depthbottom_diameterbottom_edgebottom_hookbottom_radiusbracing angle - less for more bracingbumpsburnburn correction in mm (bigger values for tighter fit)cc#candiametercanheightcardheightcardwidthchamferchamfer at the cornerschestclearanceclearance of the lidclosedconnectioncornerradiuscreate a ring gear with the belt being pushed against from withincutupdd#d1d2d3debugdefault (none)deltateethdepthdepth at the bottomdepth at the topdepth behind the lotsdepth of slots from the frontdepth of the groovesdepth of the rackdepth of the shadersdepth of the sidesdholediameterdiameter at the bottomdiameter at the topdiameter for hole for ankle bolts - foot sidediameter for hole for ankle bolts - leg sidediameter if the pin in mmdiameter of alignment pinsdiameter of lower part of the screw holediameter of the axlediameter of the axlesdiameter of the flutes bottom in mmdiameter of the hole for the tool (handle should not fit through)diameter of the pin holediameter of the pin hole in mmdiameter of the pin in mmdiameter of the screw in mmdiameter of the shaftdiameter of the shaft 1diameter of the shaft2 (zero for same as shaft 1)diameter of the strings of the O ringsdiameter of the thing to hookdiameter of the tool including space to grabdiameter of upper part of the screw holedimensiondisc_diameterdisc_outsetdisc_thicknessdistancedistance from finger holes to bottom edgedistance of flex cuts in multiples of thicknessdoubledpercentage1dpercentage2dxfeedge type for bottom edgeedge type for left edgeedge type for right edgeedge type for top edgeedge_widthenable secondary ring with given delta to the ring geareverythirdextend outward the straight edgeextend the triangle along the length of the edgeextra height to make operation smoother in mmextra space to allow movementextra_heightextraheighteyeeyes_per_hingeff#fingerfixed length of the grips on he lidsflatflushflutediameterformatformat of resulting filefourfraction of bin height covert with slopefrom one middle of a dove tail to anotherfrontfwgg#gcodegreater zero for top wider as bottomgrip_lengthgrip_percentagegripheightgripwidthhhandleheighthandlewidthhave lid overlap at the sides (similar to OutSetEdge)heightheight above the wallheight difference left to rightheight in rack unitsheight of front wallsheight of lid in mmheight of the (aluminium) profile connecting the partsheight of the boxheight of the feetheight of the front left corner in mmheight of the front of planeheight of the front right corner in mmheight of the grip hole in mmheight of the left back corner in mmheight of the lidheight of the right back corner in mmheight of the screw head in mmheight0height1height2height3heigthheigth of the bodyhexheadhexpatternhihigher values for deeper serrations (degrees)hinge_strengthhingeshingestrengthhold_lengthholeholediameterholedistholedistancehookhook_extra_heighthookshow far the dove tails stick out of/into the edgehow much should fingers widen (-80 to 80)iin Pain precent of the modulusinner depth in mminner depth in mm (unless outside selected)inner depth not including the shadesinner depth of the hookinner height in mm (unless outside selected)inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)inner height of the hookinner radius if the box (at the corners)inner width in mm (unless outside selected)inner width of the consoleinsideinside angle of the feetinsideoutintonationjkknifethicknessllatchsizeleftleft_edgelegth of the part hiolding the plane over the frontlegth of the planelengthlength of legs (34mm min)length of segment axle to axlelength1length2length3length4length5lidlidheightlimit the number of planets (0 for as much as fit)lower_factormmBarmax_strengthmax_widthmaxheightmaximal clamping height in mmmaximum space at the start and end in multiple of normal spacesmaxplanetsmensurmin_strengthmin_widthminheightminimalminimal clamping height in mmminimum space around the hingeminspacemmH2OmmHgmodulusmodulus of the gear (in mm)modulus of the theeth in mmmouth to circumference ratio (0.1 to 0.45). Determines the width to depth ratiomouthrationnema_mountno_verticalsnonenumnumbernumber of compartmentsnumber of compartments back to frontnumber of compartments side by sidenumber of hinges per edgenumber of lightsnumber of shelvesnumber of sidesnumber of solesnumber of stages in the gear reductionnumber of teethnumber of teeth in the other size of gearsnumber of teeth on ingoing shaftnumber of teeth on outgoing shaftnumber of teeth on planetsnumber of teeth on sun gearnumber of tools/slotsnumber of walls at one side (1+)number of wrenchesooctaveoddsoneoptional argumentsouter diameter of the wheels (including O rings)outsetoutsideoutsidemountsoverall width for the toolsoverhangoverhang for joints in mmoverlap of top rim (zero for none)ppdfpercent of the D section of shaft 1 (0 for same as shaft 1)percent of the D section of shaft 1 (100 for round shaft)pieces per hingepinpin_heightpinsizepinwidthpipe is closed at the toppitchplanetteethplayplay between the two parts as multipleof the wall thicknesspltpolediameterpressure anglepressure_angleprint reference rectangle with given length (zero to disable)print surrounding boxes for some structuresprofileprofile of the teeth/beltprofile_shiftpsqrr_holeradiusradius at the slotsradius for strengthening walls with the hooksradius of bottom cornersradius of holeradius of the cornersradius of the corners in mmradius of the disc rotating in the hingeradius of the eye (in multiples of thickness)radius of the lids living hingeradius of the slots at the frontradius of top cornerradius used on all four cornersrailrear_factorreferencerightright_edgeround lidroundedrubberthicknesssscrewscrew1screw2screwheadscrewheadheightsecond_pinsections back to front in mm. Possible formats: overallwidth/numberof sections e.g. "250/5"; sectionwidth*numberofsections e.g. "50*5"; section widths separated by ":" e.g. "30:25.5:70sections bottom to top in mm. See --sy for formatsections left to right in mm. See --sy for formatserrationangleserrationsservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bset to lower value to get disks surrounding the pinsshshadesshaftshaft1shaft2singlesizesize of latch in multiples of thicknessslot_depthslot_widthslotsslots for grabbing the notesspacespace below holes of FingerHoleEdgespace between eyes (in multiples of thickness)space between fingersspace surrounding connectors (in multiples of thickness)spacingsplit the lid in y direction (mm)splitlidspringstack lights upright (or side by side)stagesstoppedstrengthstrength of largest wrenchstrength of smallest wrenchstretchstudstylestyle of hinge usedstyle of the top and lidsunteethsurroundingspacessvgsvg_Ponokosxsyttabsteethteeth1teeth2thicknessthickness of the arc holding the pin in placethickness of the knifes in mm. Use 0 for use with honey comb table.thickness of the materialtool_widthtooldiametertoptop_depthtop_diametertop_edgetreat sizes as outside measurements that include the wallstriangletwotype of arm segmenttype of servo to usetype of servo to use on second side (if different is supported)type1type2type3type4type5uuprightuses unit selected belowvwallwallpieceswallswavewhich of the honey comb walls to addwidthwidth of finger holeswidth of largest wrenchwidth of slotswidth of smallest wrenchwidth of sole stripewidth of tabs holding the parts in place in mm (not supported everywhere)width of teeth in mmwidth of th grip hole in mm (zero for no hole)width of the (aluminium) profile connecting the partswidth of the feetwidth of the fingerswidth of the gaps in the cutswidth of the hook (back plate is a bit wider)width of the hook from the sidewidth of the long endwidth of the pattern perpendicular to the cutswidth of the planewidth of the surrounding wall in mmwindpressurewindpressure_unitswith of the screw head in mmxyz
54,196
Python
.py
130
415.369231
8,763
0.602445
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,528
boxes.py.mo
florianfesti_boxes/locale/fr/LC_MESSAGES/boxes.py.mo
fiï-Ñ?Ï2ËCπÈCN£EÏÚEflFÛFG G7GB<G.G3ÆGD‚GX'HÄHÑHB°H‰HÌH1ˇH1I&DIkI |IÜI ôI¶IºI√I”I(ÔIJ.JICJBçJ–JÿJ"ÈJ K<K.MK|KúK1∏K'ÍKL(.L!WL'yL°L.∑L'ÊL-M <M]M6yM∞M–M ÷M·MÒM˙M¸MNNN,N/HN8xN8±N ÍNÙN OO*(OSOhO"jOçOûOµOÕO+ÏOP%2P*XPÉPùPªPœPÿPÍPÚP QQ $Q1Q4GQ/|Q!¨QŒQ◊QÈQÎQ˙QR&R(R0RARJR\ReRwRÄRíRõR≠R∂R »R“RÂRSSS])SáSèSóSüSßS&∏SflSÂSÙS&˝SE$TjTTÅTâTëTôT≤TªTÕT·TˆTUU1)U[U%vU%úU¬U›U ‚U7U(V*V=V0YVäV,åVπVªVΩV√V “V›VÒVÛV ˜VWW,W#GWkWÛpW dXÖXòX ØXπXVÃX #Y/YDYbYwY/yY©YºYƒY ’YflY1ÚY1$ZVZ_ZqZzZ åZñZ)©Z”Z’Z ÿZÂZ˚Z["[)5[ _[6i[†[ ≥[æ[“[€[1Ì[0\ P\^\e\u\w\ y\É\ ñ\†\≥\ª\Ã\€\Ò\ ](']P]`] y]Ñ]ò]°] ≥] æ] …] ‘] fl]Í]EÒ]7^/G^ w^Ç^ ñ^†^≥^#µ^Ÿ^·^˝^_2_P_k_}_!ó_ π_⁄_ı_`#-`Q`!W`y`Å`-ò` ∆`—`,Â` aa31a ea:qa ¨aÕa÷aÊaˇab2bBb[blb Übîb´bøb‹bÒbc%cDcUcocÑc¢c™cªc ”cflc?Ùc 4dAd*WdÇdÜdãdédò£d<eYe*ue †e Æeªe—eH÷e f*f >f IfUfjfÉfåf(ûf«f–f‚f‰f Èf˜fg g-gCg=Lgäg ågñg©gºg–gg˘g hhii<i"Yi|i+ãi∑i»iÀiœiËiÓi˛i(j Gj Sj ^j jj ujÄjÖj áj ìj ûj®j±j∂j ªj»j ÿj ‰j j%˛j$k*k5/kekgk jk vk Äk ãkïkùk¥k ∫kƒkŸk ‡k ÎkA¯k:l@lBlElHlKlNlTl clnltlàlôlØlÕl‚lÙl mm"m+mBm-Vm,Ñm±mÀm(Êmn$n#:nA^n†nπnÿnÚno$o1<o&noïo,≥o(‡o p p !p-p<p)Ep/opüp ¶p ≥p¿pƒp∆p‡p¯pq (q73q kq vq0óq-»qˆq r !r-r1r@rBrEr$Lrqrvr |rärër™r(Ør)ÿrss s ss$s ;sGs Ws bsls ns {s5ásΩsƒs⁄s˙st%t69tptÇt%ïtªt&ÿtˇt$uBu%Tuzuôu°u©u±uπu¿u”u €uÊu-Èuv&v -v ;vGv LvYv bvovtvÜv1åv)ævËvÍvv w+w$Hwmw,Öwb≤wx(.x+WxÉxûx•x æx »x”x’x◊xÊx ËxÚx ˜x3y5yHyOyiyàyêyòy†y®y∞y ¥y2æy Òy˛yz z z z&z?Dz Ñzèz ñz £z ≠z∑zøz›z¸z{ {{{4{OP{ †{´{ ≠{ ∏{≈{ {Œ{’{$Ï{#|5|O|`|r|Ç|&í|π|*…| Ù|!}7}R}n} Ñ}•}∏}∫}¡}∆} }0›}~~ ~+~G~P~"j~ç~è~;ì~9œ~  )1:T Zf;kß ´∏«=÷+Ä@ÄHÄ bÄpÄsÄuÄwÄ~ÄÖÄ-ôīćÄÔÄÅ(!Å-JÅxÅ òÅπÅŒÅÓÅ ÛÅ ˇÅ Ç Ç Ç$Ç,Ç<Ç>ÇDÇKÇ RÇ\Ç lÇ∏wÇ10É1bÉîÉ £ÉÆÉ∂ÉæÉ∆ÉŒÉ÷ÉfiÉÊÉÓɈÉ4˛É3Ñ6Ñ=ÑCÑJÑQÑXÑ']Ñ ÖÑ êÑõÑ°ÑæÑ#ƒÑ.ËÑÖ8-ÖfÖ!nÖêÖôÖ&†Ö«ÖŒÖ÷ÖflÖ˙ÖÜÜ#Ü)Ü=ÜVÜ_ÜqÜ uÜÄÜÉÜÜÜàÜçÜìÜöÜ °Ü-´ÜCŸÜá 7á BáOá Sá ]ájá:sáÆá∑áªáœá?‰á$à*à0à6à<àBàDàLàeàgà làwà}à$Çàßà≠à√à€àÍàâIâbâ.wâ5¶â‹âÓâä-!äOäoä.Öä¥ä#«ä Îä¯ä ã(ã*ã,ãD.ãsåUèéÂé˜è ê'ê)9êcêChêE¨ê9ÚêT,ëUÅë◊ë'€ëJíNí]íFyí¿í,›í ìì!1ìSìcìÄìáì%ùì:√ì#˛ì"îm>îZ¨îïï'2ïZï@^ï3üï%”ï˘ï8ñ'Kñ)sñ0ùñ1Œñ1ó#2óAVó'òóA¿ó'ò *òAKò+çòπò ¡òŒòÎòÙòˆòôô!ô7ô:MôJàôJ”ôö-öIöXö?tö¥ö–ö “öÛö% õ/õ Jõ8kõ§õ-Ωõ0Îõ#ú)@újúÑú!ôú ªú«ú‡ú#Ùúù)3ù5]ù/ìù%√ùÈù˙ùûû$/û!Tûvûxûàûôû!´ûÕû!flûü ü4ü!Fühüyüóü$™ü+œü ˚ü††f;†¢†™†≤†∫†%Œ†7Ù† ,°7° P°9Z°Yî° Ó°¢¢¢!¢)¢ H¢U¢r¢,Ö¢!≤¢‘¢%Í¢?£%P£@v£2∑£(Í£§§J0§{§!}§1ü§?—§•9•M•O•Q•!f•à•õ•ª•Ω•¡•–•Ï•"¶#¶=¶%D¶%jßêß¶ß ΩßÀßpÊßW®%k®ë®±®∆®+»®Ù®©© >©L©=g©>•©‰©"¯©™,™J™Z™3x™¨™Æ™±™√™‚™Á™5´:9´ t´GÄ´»´ ·´Ô´ ¨$!¨+F¨2r¨ •¨≥¨∫¨Œ¨–¨ “¨0Û¨ $≠0E≠v≠#ä≠Æ≠≈≠’≠Î≠.Æ2Æ#FÆjÆ"}Æ †ÆÆÆ …Æ ‘Æ flÆ ÍÆ ıÆØPØXØ2lØüØØØ œØŸØÒØ0ÛØ$∞,∞'H∞*p∞õ∞&π∞‡∞˜∞)± ;±5\±%í±"∏±#€±ˇ±2≤ 8≤C≤=c≤°≤"¥≤3◊≤ ≥≥50≥f≥;w≥3≥≥Á≥!˘≥.¥J¥]¥}¥.ú¥(À¥6Ù¥+µ*Hµsµѵ¢µ ∂µ◊µ ε ∂$$∂I∂Z∂x∂Ä∂ï∂±∂$«∂YÏ∂F∑#[∑)∑©∑≠∑≤∑µ∑Æ»∑w∏#í∏8∂∏Ô∏π!π9π_>πûπ$∂π€π Ûπˇπ∫,∫'D∫Xl∫≈∫◊∫ˆ∫¯∫ ª*ª)Dªnª"Ū§ªH≠ªˆª¯ªº%º8º-Oº}º&ﺺºMøº æ æ\æ,wæ§æ=ææ¸æøøø5ø;øOø%gøçøùø±ø«øŸøÎøÔøÚø¿¿(¿7¿<¿E¿T¿ e¿ q¿ }¿8㿃¿ ¿T”¿(¡ *¡ 4¡ B¡N¡_¡ p¡z¡ì¡ ö¡§¡Ω¡ ƒ¡œ¡Ifl¡)¬/¬ 3¬>¬A¬D¬G¬M¬ a¬ l¬w¬â¬"ú¬(ø¬ˬ˝¬√-√D√ L√V√k√A√E¡√ƒ$#ƒ+Hƒtƒäƒ"†ƒ=√ƒ≈≈=≈Z≈t≈â≈:†≈/€≈" ∆1.∆+`∆ å∆ñ∆ß∆∂∆»∆/—∆/«1« 8« B«L«P« R«s«ä«!°«√«V”« *» 7»0X»>â»2»» ˚» ………*… ,…6…-?…m…r…x…â…ê…≠…2¥…)Á…     * :0  k w á ò © ´ ø G” À#À*9ÀdÀÀúÀ3∑ÀÎÀÃ#Ã6Ã"QÃtÃ%ìÃπÃ$ŒÃ Ûà Õ Õ (Õ 2Õ<ÕDÕ UÕ_ÕcÕAfÕ®ÕπÕ ¿ÕŒÕ›Õ‚ÕÙÕŒŒ"Œ8Œ1AŒ7sŒ´Œ≠Œ≥ŒÃŒEÈŒ1/œ!aœBÉœò∆œ_–.~–B≠–!–—— 4— B—M—O—Q—b— d—Ö— å—5ò—Œ—‡—&È—“ .“ 9“ D“ O“ Z“ e“o“:Ñ“ ø“À“Õ“ ““ ‹“ Ë“!Ù“F” ]”k” r” |” à” î”!û”¿” fl”͔Ҕ˜”˛”‘a1‘ì‘£‘ •‘∞‘¬‘»‘Ñ”‘.Α&’A’[’j’y’ã’2û’—’-·’(÷(8÷!a÷&É÷™÷!≈÷Á÷˜÷˘÷◊◊ ◊; ◊\◊ c◊n◊Ä◊ õ◊®◊-∆◊Ù◊ˆ◊F˙◊<Aÿ~ÿèÿñÿßÿºÿ≈ÿ·ÿÈÿ¯ÿF¸ÿCŸGŸ^ŸmŸUŸ5’Ÿ ⁄⁄2⁄G⁄J⁄L⁄N⁄U⁄[⁄1n⁄†⁄ª⁄ ⁄⁄⁄:⁄-+€,Y€ Ü€߀º€ ‹€Á€ ¯€‹ ‹‹%‹-‹C‹E‹I‹O‹ U‹ b‹ p‹È{‹Ce›H©›Ú› fi fififi(fi1fi:fiCfiLfiUfi^fiJgfi≤fi µfiøfi≈fiÕfi’fi‹fi0„fifl'fl7fl#@fldfl4kfl.†flœfl<Ífl'‡)/‡Y‡l‡s‡í‡ö‡°‡߇ƒ‡·‡ȇÓ‡Ù‡· (·5·D· H·S·V·Y·[·b·h·p· x·,É·H∞·˘· ‚‚/‚6‚F‚ X‚Pe‚∂‚ø‚ƒ‚ ·‚\„_„f„m„t„{„DŽф*ì„æ„¿„∆„ÿ„fl„.‰„‰‰!;‰]‰!r‰î‰V≥‰ Â5"Â3XÂåÂûÂ&¥Â>€ÂÊ:Ê.UÊÑÊ%ïʪÊÃÊ flÊÁÁÁ0ÙfóB∑∫*ı™ª»rzG>RÅfi K=ëy2VO˛¨ŸüÀ”·GàµÙè ¨˝íW>Mgkãü£`¶´ö猂„$Z#“¯Ñ˘Ái<çP/◊ÔÚ4m‰IgQÖûµÚß@AvCJôπ‡õÆÇdl,;-A⁄7ÈÆ%™∫Eu H •B¥íæî8Œè˜V(_ˇ9˙+±ñ#l.."Ç«A≈,J$ù—·5¢˜~=ÕE 57G`∂}üùF.â y+XÓÉ?áo÷«∞l˚6VÆeMø€°äÿï√∂≈aî œÏÛY}f±®}f@'≥)#ƒÑ‰¯3xÙI:„ QT$¸• ö∆òÍ ˙ôUÉá6©Ìãˇ’…÷ÑcL˛+19| ıo©fl°Îa˝')¿6¢ΩD‹'≥ˆ(tYKıÄ:Jd¿ñ¶Öj]m“fiÒÅ˙˝3k–Ë◊|õ €ªèË∆h_v´{F&ìå%,|[jo’fi Îõú-ó]ÊÓØËôqæóÿSx ºy2ïÛï,û/‡ÊºúR≠xì[†Ω›È€pÈeß3tOqß∂–∞ ÷¸∑∞π …>Ü%aZ1v<¶°kj{i<±\ødêE+!R^ØNflˇq ”å*‚·=zzU¡£pãO*É:nprt‘?Ì¡b[¥Ïs∆;C@^ £ÏTLYà◊Äò_≤¬® ;≤ç∏ à œù ë¡∏≈Î7Õw/µu‰n!Ò%©¬~H›Ã&≠æ&PêÓ—§1†‘ÚÇ&r»FmÍØ!-?#¯ÂéS¨¥“~‹Q™MŸ4ŒX ∫Ôé˘fl«SPWD䃸ÕêN≥ ⁄ÜÂ4⁄òœ(C5Ô√”›¢0§cñÅ$Á˘N0"•\K∏hTå„bg-8ÀÖ≠®Uê)‹\w¬ø 9—áî–Ÿ¿nc»Û˜º∑íZ’ûÿ"ëˆπìsÌ√u˛DH  ÍIâú…܈Áse§`8´Ä(Ã*2†"BhƒLÊ)Òb]Àä≤i{!â˚ΩéX'‘w˚‚Wö‡^ <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> is an <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> box generator written in <a href="https://www.python.org/">Python</a>. It features both finished parametrized generators as well as a Python API for writing your own. It features finger and (flat) dovetail joints, flex cuts, holes and slots for screws, hinges, gears, pulleys and much more. Cuttlery stand with carrying grip using flex for rounded corners Vitamins: DSP5005 (or similar) power supply, two banana sockets, two 4.8mm flat terminals with flat soldering tag To allow powering by laptop power supply: flip switch, Lenovo round socket (or adjust right hole for different socket) "outset" or "flush""spring", "stud" or "none""wave" or "bumps"# pieces of outer wall40DPA Type tray variant to be used up right with sloped walls in frontA clamp to hold down material to a knife tableA hook wit a rectangular mouth to mount at the wallA rack for storing disk-shaped objects vertically next to each otherA two piece box where top slips over the bottom half to form the enclosure. AT5Add external mounting pointsAdditional space kept between the disks and the outbox of the rackAllEdgesAllEdges SettingsAmount of circumference used for non convex partsAn error occurred!Angle between convex and concave partsAngle of the cutAngledBoxAngledBox SettingsAngledCutJigAngledCutJig SettingsArcadeArcade SettingsBackwards slant of the rackBalanced force Difference Planetary GearBar to hang pliers onBass Recorder EndpinBench power supply powered with Maktia 18V battery or laptop power supplyBeware of the rolling shutter effect! Use wax on sliding surfaces.BinTrayBinTray SettingsBook cover with flex for the spineBoxBox for drills with each compartment with a different heightBox for holding a stack of paper, coasters etcBox for storage of playingcardsBox in the form of an heartBox various options for different stypes and lidsBox with a rolling shutter made of flexBox with both ends corneredBox with different height in each cornerBox with lid and integraded hingeBox with lid attached by cabinet hingesBox with living hingeBox with living hinge and left corners roundedBox with living hinge and round cornersBox with living hinge and top corners roundedBox with regular polygon as baseBox with top and front openBox with various options for different styles and lidsBox with vertical edges roundedBoxesBoxes - %sBoxes with flexBoxes.pyCCardBoxCardBox SettingsCastleCastle SettingsCastle tower with two wallsClosed box with screw on top and mounting holesClosed box with screw on top for mounting in a 10" rack.Closed box with screw on top for mounting in a 19" rack.ClosedBoxClosedBox SettingsConcaveKnobConcaveKnob SettingsCreate boxes and more with a laser cutter!Cutup to mouth ratioDD-Flat in fraction of the diameterDefault SettingsDefaultParams SettingsDesktop Arcade MaschineDiameter of the bolt hole (mm)Diameter of the inner lid screw holes in mmDiameter of the knob (mm)Diameter of the lid screw holes in mmDiameter of the mounting screw holes in mmDiameter of the paintcansDiplay for flyers or leafletsDisc diameter in mmDiscRackDiscRack SettingsDisplayDisplay SettingsDisplayCaseDisplayCase SettingsDisplayShelfDisplayShelf SettingsDistance in halftones in the Normalmensur by T√∂pferDistance of the screw holes from the wall in mmDocumentation and API DescriptionDrillBoxDrillBox SettingsEElectronicsBoxElectronicsBox SettingsError generating %sFFlexBoxFlexBox SettingsFlexBox2FlexBox2 SettingsFlexBox3FlexBox3 SettingsFlexBox4FlexBox4 SettingsFlexBox5FlexBox5 SettingsFlexTestFlexTest SettingsFlexTest2FlexTest2 SettingsFoam soles for the OttO botFolderFolder SettingsFully closed boxFully closed box intended to be cut from transparent acrylics and to serve as a display case.GT2_2mmGT2_3mmGT2_5mmGearBoxGearBox SettingsGearbox with multiple identical stagesGearsGears SettingsGenerateGenerate a typetray from a layout fileGenerators are still untested or need manual adjustment to be useful.Get Source at GitHubHHTD_3mmHTD_5mmHTD_8mmHackaday.io Project PageHeartBoxHeartBox SettingsHeight of the cardsHeight of the handleHeight of the paintcansHingeBoxHingeBox SettingsHint of how much the flex part should be shortendHold a plane to a slatwallHold a set of wrenches at a slat wallHolds a single caliper to a slat wallHoney Comb Style Wine RackHookHook SettingsHook for pole like things to be clamped to another poleIIntegratedHingeBoxIntegratedHingeBox SettingsIntonation Number. 2 for max. efficiency, 3 max.JJig for making angled cuts in a laser cutterKLLBeamLBeam SettingsLaserClampLaserClamp SettingsMMXLMagazineFileMagazineFile SettingsMakitaPowerSupplyMakitaPowerSupply SettingsMinimum space between the paintcansMiscMost of the blue lines need to be engraved by cutting with high speed and low power. But there are three blue holes that actually need to be cut: The grip hole in the lid and two tiny rectangles on the top and bottom for the lid to grip into. Mounting braket for a Nema motorNEMA size of motorNema size of the motorNemaMountNemaMount SettingsNot yet parametrized box for drills from 1 to 12.5mm in 0.5mm steps, 3 holes each sizeNotesHolderNotesHolder SettingsNumber of rounded top cornersNumber of serrationsOOctave in International Pitch Notation (2 == C)Open magazine fileOpenBoxOpenBox SettingsOrganPipeOrganPipe SettingsOtto LC - a laser cut chassis for Otto DIY - bodyOtto LC - a laser cut chassis for Otto DIY - legsOttoBodyOttoBody SettingsOttoLegsOttoLegs SettingsOttoSolesOttoSoles SettingsOutset and angled plate to mount stuff toPPaPaintStoragePaintStorage SettingsPartParts and SamplesPiece for testing 2D flex settingsPiece for testing different flex settingsPlanetaryPlanetary Gear with possibly multiple identical stagesPlanetary SettingsPlanetary2Planetary2 SettingsPoleHookPoleHook SettingsPosition of the lower rack grids along the radiusPosition of the rear rack grids along the radiusProfile shiftPulleyPulley SettingsQRRack10BoxRack10Box SettingsRack19BoxRack19Box SettingsRackBoxRackBox SettingsRadius of combRadius of the cornersRadius of the corners in mmRadius of the latch in mmRectangular organ pipe based on pipecalcRectangularWallRectangularWall SettingsRegularBoxRegularBox SettingsRobotArmRobotArm SettingsRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryRotary Attachment for engraving cylindrical objects in a laser cutterRotary SettingsRound knob serrated outside for better grippingRoundedBoxRoundedBox SettingsRoyalGameRoyalGame SettingsSSegments of servo powered robot armServo9gSettings for Cabinet HingesSettings for Chest HingesSettings for Click-on LidsSettings for Dove Tail JointsSettings for Finger JointsSettings for FlexSettings for GrippingEdgeSettings for Hinges and HingePinsSettings for RoundedTriangleEdgeSettings for SlatWallEdgesSettings for Slide-on LidsSettings for Stackable EdgesSettings for rack (and pinion) edgeShelfShelf with forward slanted floorsShelvesShowing all edge typesShows the different edge types for slat wallsShutterBoxShutterBox SettingsSides of the triangles holding the lid in mmSilverwareSilverware SettingsSimple L-Beam: two pieces joined with a right angleSimple wallSlat wall tool holder for chisels, files and similar toolsSlat wall tool holder with slotsSlatWallSlatwallCaliperSlatwallCaliper SettingsSlatwallChiselHolderSlatwallChiselHolder SettingsSlatwallConsoleSlatwallConsole SettingsSlatwallDrillBoxSlatwallDrillBox SettingsSlatwallEdgesSlatwallEdges SettingsSlatwallPlaneHolderSlatwallPlaneHolder SettingsSlatwallPliersHolderSlatwallPliersHolder SettingsSlatwallSlottedHolderSlatwallSlottedHolder SettingsSlatwallTypeTraySlatwallTypeTray SettingsSlatwallWrenchHolderSlatwallWrenchHolder SettingsStachelStachel SettingsStackable paint storageStorageRackStorageRack SettingsStorageRack to store boxes and trays which have their own floorStorageShelfStorageShelf SettingsStorageShelf can be used to store TypetrayT10T2_5T5The Royal Game of UrThe traffic light was created to visualize the status of a Icinga monitored system. When turned by 90¬∞, it can be also used to create a bottle holder.Thickness of the discs in mmThis is a simple shelf box.Timing belt pulleys for different profilesTraffic lightTrafficLightTrafficLight SettingsTrayTray insert without floor and outer walls - allows only continuous wallsTrayInsertTrayInsert SettingsTrayLayoutTrayLayout2TrayLayout2 SettingsTrays and Drawer InsertsTwoPieceTwoPiece SettingsType tray - allows only continuous wallsTypeTrayTypeTray SettingsUUBoxUBox SettingsUnevenHeightBoxUnevenHeightBox SettingsUniversalBoxUniversalBox SettingsUnstableUse hexagonal arrangement for the holes instead of orthogonalVWaivyKnobWaivyKnob SettingsWidth of the cardsWidth of the handleWidth of the hex bolt head (mm)WineRackWineRack SettingsXLYou need a tension spring of the proper length to make the clamp work. Increace extraheight to get more space for the spring and to make the sliding mechanism less likely to bind. You may need to add some wax on the parts sliding on each other to reduce friction. aa#add a lid (works best with high corners opposing each other)additional height of the back walladditional lidadditional lid (for straight top_edge only)additional_depthaiallamount of hooks / bracesangleangle of floorsangle of the support underneethangle of the teeth touching (in degrees)angled holeangled lidangled lid2anklebolt1anklebolt2axlebback_heightbeamheightbeamwidthboltholeborebothbottom_depthbottom_diameterbottom_edgebottom_hookbottom_radiusbracing angle - less for more bracingbumpsburnburn correction in mm (bigger values for tighter fit)cc#candiametercanheightcardheightcardwidthchamferchamfer at the cornerschestclearanceclearance of the lidclosedconnectioncornerradiuscreate a ring gear with the belt being pushed against from withincutupdd#d1d2d3debugdefault (none)deltateethdepthdepth at the bottomdepth at the topdepth behind the lotsdepth of slots from the frontdepth of the groovesdepth of the rackdepth of the shadersdepth of the sidesdholediameterdiameter at the bottomdiameter at the topdiameter for hole for ankle bolts - foot sidediameter for hole for ankle bolts - leg sidediameter if the pin in mmdiameter of alignment pinsdiameter of lower part of the screw holediameter of the axlediameter of the axlesdiameter of the flutes bottom in mmdiameter of the hole for the tool (handle should not fit through)diameter of the pin holediameter of the pin hole in mmdiameter of the pin in mmdiameter of the screw in mmdiameter of the shaftdiameter of the shaft 1diameter of the shaft2 (zero for same as shaft 1)diameter of the strings of the O ringsdiameter of the thing to hookdiameter of the tool including space to grabdiameter of upper part of the screw holedimensiondisc_diameterdisc_outsetdisc_thicknessdistancedistance from finger holes to bottom edgedistance of flex cuts in multiples of thicknessdoubledpercentage1dpercentage2dxfeedge type for bottom edgeedge type for left edgeedge type for right edgeedge type for top edgeedge_widthenable secondary ring with given delta to the ring geareverythirdextend outward the straight edgeextend the triangle along the length of the edgeextra height to make operation smoother in mmextra space to allow movementextra_heightextraheighteyeeyes_per_hingeff#fingerfixed length of the grips on he lidsflatflushflutediameterformatformat of resulting filefourfraction of bin height covert with slopefrom one middle of a dove tail to anotherfrontfwgg#gcodegreater zero for top wider as bottomgrip_lengthgrip_percentagegripheightgripwidthhhandleheighthandlewidthhave lid overlap at the sides (similar to OutSetEdge)heightheight above the wallheight difference left to rightheight in rack unitsheight of front wallsheight of lid in mmheight of the (aluminium) profile connecting the partsheight of the boxheight of the feetheight of the front left corner in mmheight of the front of planeheight of the front right corner in mmheight of the grip hole in mmheight of the left back corner in mmheight of the lidheight of the right back corner in mmheight of the screw head in mmheight0height1height2height3heigthheigth of the bodyhexheadhexpatternhihigher values for deeper serrations (degrees)hinge_strengthhingeshingestrengthhold_lengthholeholediameterholedistholedistancehookhook_extra_heighthookshow far the dove tails stick out of/into the edgehow much should fingers widen (-80 to 80)iin Pain precent of the modulusinner depth in mminner depth in mm (unless outside selected)inner depth not including the shadesinner depth of the hookinner height in mm (unless outside selected)inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)inner height of the hookinner radius if the box (at the corners)inner width in mm (unless outside selected)inner width of the consoleinsideinside angle of the feetinsideoutintonationjkknifethicknessllatchsizeleftleft_edgelegth of the part hiolding the plane over the frontlegth of the planelengthlength of legs (34mm min)length of segment axle to axlelength1length2length3length4length5lidlidheightlimit the number of planets (0 for as much as fit)lower_factormmBarmax_strengthmax_widthmaxheightmaximal clamping height in mmmaximum space at the start and end in multiple of normal spacesmaxplanetsmensurmin_strengthmin_widthminheightminimalminimal clamping height in mmminimum space around the hingeminspacemmH2OmmHgmodulusmodulus of the gear (in mm)modulus of the theeth in mmmouth to circumference ratio (0.1 to 0.45). Determines the width to depth ratiomouthrationnema_mountno_verticalsnonenumnumbernumber of compartmentsnumber of compartments back to frontnumber of compartments side by sidenumber of hinges per edgenumber of lightsnumber of shelvesnumber of sidesnumber of solesnumber of stages in the gear reductionnumber of teethnumber of teeth in the other size of gearsnumber of teeth on ingoing shaftnumber of teeth on outgoing shaftnumber of teeth on planetsnumber of teeth on sun gearnumber of tools/slotsnumber of walls at one side (1+)number of wrenchesooctaveoddsoneoptional argumentsouter diameter of the wheels (including O rings)outsetoutsideoutsidemountsoverall width for the toolsoverhangoverhang for joints in mmoverlap of top rim (zero for none)ppdfpercent of the D section of shaft 1 (0 for same as shaft 1)percent of the D section of shaft 1 (100 for round shaft)pieces per hingepinpin_heightpinsizepinwidthpipe is closed at the toppitchplanetteethplayplay between the two parts as multipleof the wall thicknesspltpolediameterpressure anglepressure_angleprint reference rectangle with given length (zero to disable)print surrounding boxes for some structuresprofileprofile of the teeth/beltprofile_shiftpsqrr_holeradiusradius at the slotsradius for strengthening walls with the hooksradius of bottom cornersradius of holeradius of the cornersradius of the corners in mmradius of the disc rotating in the hingeradius of the eye (in multiples of thickness)radius of the lids living hingeradius of the slots at the frontradius of top cornerradius used on all four cornersrailrear_factorreferencerightright_edgeround lidroundedrubberthicknesssscrewscrew1screw2screwheadscrewheadheightsecond_pinsections back to front in mm. Possible formats: overallwidth/numberof sections e.g. "250/5"; sectionwidth*numberofsections e.g. "50*5"; section widths separated by ":" e.g. "30:25.5:70sections bottom to top in mm. See --sy for formatsections left to right in mm. See --sy for formatserrationangleserrationsservo1aservo1bservo2aservo2bservo3aservo3bservo4aservo4bservo5aservo5bset to lower value to get disks surrounding the pinsshshadesshaftshaft1shaft2singlesizesize of latch in multiples of thicknessslot_depthslot_widthslotsslots for grabbing the notesspacespace below holes of FingerHoleEdgespace between eyes (in multiples of thickness)space between fingersspace surrounding connectors (in multiples of thickness)spacingsplit the lid in y direction (mm)splitlidspringstack lights upright (or side by side)stagesstoppedstrengthstrength of largest wrenchstrength of smallest wrenchstretchstudstylestyle of hinge usedstyle of the top and lidsunteethsurroundingspacessvgsvg_Ponokosxsyttabsteethteeth1teeth2thicknessthickness of the arc holding the pin in placethickness of the knifes in mm. Use 0 for use with honey comb table.thickness of the materialtool_widthtooldiametertoptop_depthtop_diametertop_edgetreat sizes as outside measurements that include the wallstriangletwotype of arm segmenttype of servo to usetype of servo to use on second side (if different is supported)type1type2type3type4type5uuprightuses unit selected belowvwallwallpieceswallswavewhich of the honey comb walls to addwidthwidth of finger holeswidth of largest wrenchwidth of slotswidth of smallest wrenchwidth of sole stripewidth of tabs holding the parts in place in mm (not supported everywhere)width of teeth in mmwidth of th grip hole in mm (zero for no hole)width of the (aluminium) profile connecting the partswidth of the feetwidth of the fingerswidth of the gaps in the cutswidth of the hook (back plate is a bit wider)width of the hook from the sidewidth of the long endwidth of the pattern perpendicular to the cutswidth of the planewidth of the surrounding wall in mmwindpressurewindpressure_unitswith of the screw head in mmxyzProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: 2019-10-27 22:58+0100 Last-Translator: Georges Khaznadar <georgesk@debian.org> Language-Team: French Language: fr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); <a href="https://hackaday.io/project/10649-boxespy">Boxes.py</a> est un g√©n√©rateur de bo√Ætes <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">Open Source</a> √©crit en <a href="https://www.python.org/">Python</a>. Il propose des g√©n√©rateurs param√©trables de produits finis et aussi une API en Python pour cr√©er les v√¥tres. Il propose des assemblages √† enture dentel√©e et des queues d'aronde (droites), des d√©coupes de zones flexibles, des trous et des encoches pour vis, des charni√®res, des poulies et bien plus. Support √† couteaux avec une poign√©e de portage utilisant des coins arrondi en flex Vitamines¬†: alimentation DSP5005 (ou similaire), deux fiches bananes, deux bornes plates 4,8 mm avec une zone √† souder Pour une alimentation par un adaptateur d'ordinateur portable¬†: un interrupteur, une borne coaxiale Lenovo (ou adapt√©e, pour une prise diff√©rente) "outset" ou "flush""ressort", "clou" or "rien""wave" or "bumps"nombre de pi√®ces de la paroi ext√©rieure40DPUn type de casier √† poser debout avec des parois inclin√©es devantUn valet pour serrer le mat√©riau √† la table de la d√©coupeuse laserUn crochet avec une bouche rectangulaire √† monter au murUn rangement pour des objets en forme de disque plac√©s verticalement c√¥te √† c√¥teUne bo√Æte en deux morceaux o√π le dessus glisse sur le dessous pour former la bo√ÆteAT5Ajouter des points de montages externesEspace suppl√©mentaire conserv√© entre les disques et le contour du casierTous les bordsR√©glages de Tous les bordspourcentage de la circonf√©rence utilis√© par les parties non convexesUne erreur s'est produite¬†!Angle entre les parties convexes et concavesAngle de la d√©coupeBo√Æte polygonaleR√©glages de la Bo√Æte PolygonaleCoupes en angleR√©glages de Coupes en angleArcadeR√©glages pour ArcadeInclinaison vers l'arri√®re du casierDiff√©rentiel √† forces √©gales √† engrenages plan√©tairesUne barre pour accorcher des pincesAccessoire pour flute basseAlimentation de laboratoire bas√©e sur une batterie Makita 18 V ou sur une alimentation d'ordinateur portableAttention √† l'effet du fermoir coulissant¬†! paraffinez les surfaces qui doivent glisser.Casier √† vracR√©glages du casier √† vracCouverure de livre avec un dos flexibleBoxBo√Æte √† forets avec des compartiments de hauteurs diff√©rentesBo√Æte pour une pirle de papiers, de post-its, etc.Bo√Æte pour ranger des jeux de cartesBo√Æte en forme de c≈ìurBo√Æte avec plusieurs options de styles et de couverclesBo√Æte fermant par un coulisse flexibleBo√Æte avec deux extr√©mit√©s polygonalesBo√Æte avec des hauteurs vari√©es √† chaque coinBo√Æte avec un couvercle et charni√®re int√©gr√©eBo√Æte avec un couvercle tenu par des charni√®resBo√Æte avec une charni√®re flexibleBo√Æte avec une charni√®re flexible et les coins gauches arrondisBox with living hinge and round cornersBo√Æte avec une charni√®re flexible et les coins du haut arrondisBo√Æte bas√©e sur un polygone r√©gulierBo√Æte ouverte en haut et devantBo√Æte avec diverses options pour varier le style et le couvercleBo√Æte avec les parois verticales arrondiesBo√ÆtesBo√Ætes - %sBo√Ætes avec un pli flexibleBoxes.pyCBo√Æte √† cartesCardBox SettingsCh√¢teauR√©glages de Ch√¢teauDonjon avec deux mursBo√Æte ferm√©e avec des vis dessus et des trous de montageBo√Æte ferm√©e avec des vis dessus pour montage dans un rack de 10 pouces.Bo√Æte ferm√©e avec des vis dessus pour montage dans un rack de 19 pouces.Bo√Æte ferm√©eR√©glages de Bo√Æte Ferm√©eBouton concaveR√©glages du Bouton concaveCr√©ez des bo√Ætes et plus √† l'aide d'une d√©coupeuse laser¬†!Ratio du cutup √† la boucheDm√©plat en fraction du diam√®treR√©glages par d√©fautR√©glages des param√®tres par d√©fautMachine d'Arcade de bureauDiam√®tre du trou du boulon (mm)Diam√®tre des trous de vis du couvercle int√©rieur en mmDiam√®tre du bouton (mm)Diam√®tre des trous de vis du couvercle en mmDiam√®tre des trous de vis pour le montage en mmDiam√®tre des pots ou des cannettesPr√©sentoir pour des flyers ou des tractsDiam√®tre du disque en mmRangement √† disquesR√©glages du Rangement √† disquesPr√©sentoirR√©glades de Pr√©sentoirBo√Æte d'expositionR√©glages de la Bo√Æte d'exposition√âtag√®re de pr√©sentationR√©glages de l'√âtag√®re de pr√©sentationDistance en demi-tons dans la Normalmensur de T√∂pferDistance des trous de vis depuis la paroi en mmDocumentation et description de l'APIBo√Æte √† foretsR√©glages de Bo√Æte √† foretsEBo√Æte √âlectroniqueR√©glages de la Bo√Æte √âlectroniqueErreur dans la g√©n√©ration de %sFBo√Æte flexibleFlexBox SettingsBo√Æte flexible 2R√©glages de la Bo√Æte flexible 2Bo√Æte flexible 3R√©glages de la Bo√Æte flexible 3Bo√Æte flexible 4R√©glages de la Boite flexible 4Bo√Æte flexible 5R√©glages de la Bo√Æte flexible 5Test de flexibleR√©glages du Test de flexibleTest de flexible 2R√©glages pour le Test de flexible 2Semelles de mousse pour Otto le petit robotCouvertureR√©glages de CouvertureBo√Æte compl√®tement ferm√©eBo√Æte enti√®rement ferm√©e √† d√©couper dans de l'acrylique transparente servant pour une exposition.GT2_2mmGT2_3mmGT2_5mmBo√Æte d'engrenagesR√©glages pour la Bo√Æte d'engrenagesBo√Æte d'engrenanges avec plusieurs niveaux indentiquesEngrenagesR√©glages des EngrenagesG√©n√©rerG√©n√®re un s√©parateur √† partir d'un fichier de croquisG√©n√©rateurs encore peu test√©s ou qui n√©cessitent des ajustements manuels avant usage.R√©cup√©rer la Source sur GitHubHHTD_3mmHTD_5mmHTD_8mmPage du Projet sur Hackaday.ioBo√Æte C≈ìurR√©glages de la Bo√Æte C≈ìurHauteur des cartesHauteur de la poign√©e<KHeight of the handleHauteur des pots ou des cannettesBo√Æte √† charni√®resR√©glages de la Bo√Æte √† charni√®resIndication de combien il faudrait raccourcir la partie flexibleFixe un rabot √† un pr√©sentoir muralSupport pour une s√©rie de cl√©s plates sur un pr√©sentoir muralFixe un pied √† coulisse sur une pr√©sentoir mural√âtag√®re √† bouteilles en nid d'abeilleCrochetR√©glages de CrochetTrucs pour des objets longs comme des perches √† fixer √† une autre percheIBo√Æte √† charni√®res int√©gr√©esR√©glages de la Bo√Æte √† charni√®res int√©gr√©esNombre d'intonation. 2 pour efficacit√© maximale, 3 au maximum.JPour faire des coupes en angle avec une d√©coupeuse laserKLDi√®dre en ¬´¬†L¬†¬ªR√©glages du Di√®dre en ¬´¬†L¬†¬ªSerrage pour laserR√©glages de Serrage pour laserMMXLPorte-magazineR√©glages de Porte-magazineAlimentation MakitaR√©glages pour Alimentation MakitaEspace minimal entre potsDiversLa plupart des lignes bleues doivent re grav√©es par une d√©coupe √† grande vitesse et faible puissance. Mais il y a des trous bleus qui doivent vraiment √™tre d√©coup√©s¬†: le trou de prise en main du couvercle et les deux petits rectangles en haut et en bas du couvercle pour saisir dedans. Flanc de montage pour un moteur N√©mataille NEMA du moteurTaille du moteur N√©maMontage N√©maR√©glages du Montage N√©maBo√Æte non param√©trable pour des forets de 1 √† 12,5 mm par √©tape de 0,5 mm, trois trous pour chaque diam√®treBo√Æte √† Bloc-noteR√©glages pour la Bo√Æte √† Bloc-noteNombre de coins arrondis dessusNombre de canneluresOOctave en notation internationale (2 == do)Support de magazines ouvertBo√Æte ouverteR√©glages de la Bo√Æte ouverteTuyau d'orgueR√©glages de Tuyau d'orgueOtto LC - un chassis d√©coup√© au laser pour OTTO DIY - corpsOtto LC - un chassis d√©coup√© au laser pour OTTO DIY - jambesOtto le petit robotR√©glages pour Otto le petit robotJambes pour OttoR√©glages de Jambes pour OttoSemelles d'OttoR√©glages des Semelles d'OttoConsole et plateau inclin√© o√π placer du mat√©rielPPaRangement de potsR√©glages du Rangement de potsPartComposants et √âchantillons√âchantillon pour tester les r√©glages du flexible 2D√âchantillon pour tester diff√©rents r√©glages de flexiblePlan√©taireEngrenage plan√©taire avec √©ventuellement plusieurs niveaux identiquesR√©glages du Plan√©tairePlan√©taire 2R√©glages du Plan√©taire 2Trucs avec des perchesR√©glages des Trucs avec des perchesPosition du bas de la case le long du rayonPosition de l'arri√®re de la case le long du rayonProfile shiftPoulieR√©glages de PoulieQRBo√Æte pour un rack de 10 poucesR√©glages de la Bo√Æte pour un rack de 10 poucesBo√Æte pour un rack de 19 poucesR√©glages de la Bo√Æte pour un rack de 19 poucesBo√Æte pour un rackR√©glages de la Bo√Æte pour un rackRayon du nid d'abeilleRayon des coinsRayon des coins en mmRayon du flexible en mmTuyau d'orgue rectangulaire bas√© sur pipecalcParoi rectangulaireR√©glages de la Paroi rectangulaireBo√Æte R√©guli√®reR√©glages de la Bo√Æte R√©guli√®reBras de robotR√©glages du Bras de robotRobotArmMMRobotArmMmRobotArmMuRobotArmUURobotArmUuRotaryFixation rotative pour graver des objets cylindriques dans une d√©coupeuse laserR√©glages de RotaryBouton rond dent√© pour une meilleur prise en mainBo√Æte ArrondieR√©glages de la Bo√Æte ArrondieJeu RoyalR√©glages du Jeau RoyalSSegments de bras de robot pour des servo-moteursServo9gSettings for Cabinet HingesR√©glages pour la charni√®re int√©gr√©eR√©glages pour les couvercles encliquablesSettings for Dove Tail JointsR√©glages pour les entures cr√©nel√©esR√©glages pour le FlexSettings for GrippingEdgeR√©glages pour les gonds et axes de gondsSettings for RoundedTriangleEdgeR√©glages g√©n√©raux des Bords pour pr√©sentoir muralR√©glages pour couvercles coulissantsR√©glages pour des bords gerbablesSettings for rack (and pinion) edgeShelf√âtag√®re avec des planchers pench√©s vers l'avant√âtag√®resMontrer tous les types de bordsMontre les divers types de bords pour les pr√©sentoirs murauxBo√Æte √† coulisseR√©glages de la Bo√Æte √† coulisseC√¥t√©s des triangles supportant le couvercle en mmArgenterieR√©glages de l'ArgenterieDi√®dre simple¬†: deux pi√®ces jointes √† angle droitSimple rectanglePorte-outils mural pour ciseaux, lime, et outils similairesSupport d'outils √† encoches pour pr√©sentoir muralPr√©sentoir muralPr√©sentoir pour pied √† coulisseR√©glages du Pr√©sentoir pour pied √† coulissePorte Ciseau MuralR√©glages du Porte Ciseau MuralConsole pour pr√©sentoir muralR√©glages de la Console pour pr√©sentoir muralBo√Ætes pour forets de pr√©sentoir muralR√©glages des Bo√Ætes pour forets de pr√©sentoir muralBords pour pr√©sentoir muralR√©glages des Bords pour pr√©sentoir muralSupport de rabotR√©glages du Support de rabotSupport pour pincesR√©glages du Support pour pincesSupport √† encochesR√©glages du Support √† encochesTiroir √† compartimentsR√©glages du Tiroir √† compartimentsSupport de cl√©sR√©glages du Support de cl√©sStachelR√©glages de StachelRangement de pots empilable√âtag√®re de stockageR√©glages de l'√âtag√®re de stockage√âtag√®re de stockage pour entreposer des bo√Ætes et des tiroirs qui ont leur propre fond√âtag√®re √† tiroirsR√©glages de l'√âtag√®re √† tiroirs√âtag√®re qui peut entreposer des tiroirsT10T2_5T5Le jeu royal d'OurLes feux de circulation ont √©t√© cr√©√©s pour visualiser le status d'un syst√®me Icinga. Quand on les tourne de 90¬∞, on peut aussi les utiliser pour porter des bouteilles.√âpaisseur du disque en mmC'est une simple bo√Æte √† √©tages.Poulies pour courroies dent√©es avec diff√©rents profilsFeux de circulationFeux de circulationR√©glages des Feux de circulationTrayS√©parateur pour tiroir sans dessous ni parois lat√©rales - n'autorise que les parois continuesS√©parateur pour tiroirR√©glages du S√©parateur pour tiroirS√©parateur par croquisTrayLayout2TrayLayout2 SettingsTiroirs et s√©parateursBo√Æte en deux morceauxR√©glages de la Bo√Æte en deux morceauxTiroir √† compartiments pour pr√©sentoir mural - autorise seulement des parois continuesTiroir cloisonn√©R√©glages du Tiroir cloisonn√©UBo√Æte ¬´¬†U¬†¬ªR√©glages de la Bo√Æte ¬´¬†U¬†¬ªBo√Æte de hauteur vari√©eR√©glages de la Bo√Æte de hauteur vari√©eBo√Æte universelleR√©glages de la Bo√Æte universelleInstableUtiliser un arragement hexagonal pour les pots plut√¥t qu'√† angle droitVBouton cannel√©R√©glages du Bouton cannel√©Largeur des cartesLargeur de la poign√©eLargeur de la t√™te hexagonale du boulon (mm)√âtag√®re √† bouteillesR√©glages de l'√âtag√®re √† bouteillesXLIl faut un ressort de longueur appropri√©e pour que le valet fonctionne. Augmenter la hauteur suppl√©mentaire pour donner plus de place au ressort et pour que le m√©canisme glissant soit moins facilement bloqu√©. Il faut peut-√™tre ajouter un peu de paraffine sur les parties glissant l'une sur l'autre afin de r√©duire la friction. lala di√®seajouter un couvercle (marche mieux avec des coins de m√™me hauteur de deux c√¥t√©s oppos√©s)hauteur suppl√©mentaire de la paroi arri√®recouvercle suppl√©mentairecouvercle suppl√©mentaire (pour un bord haut droit seulement)profondeur en plusaitousnombre de crochets par flancsangleangle des planchersangle du support en basangle de contact des dents (en deg√©)creux polygonalcouvercle polygonalcouvercle polygonal 2boulon cheville 1boulon cheville 2axesihauteur derri√®rehauteur de poutrelargeur de poutretrou du boulonboreles deuxprofondeur basdiam√®tre du basbord du bascrochet basbottom_radiusangle de contrevent - moins pour un contrevent plus hautbumpsbr√ªlageCorrection du br√ªlage en mm (augmenter la valeur pour un embo√Ætement plus ajust√©)cdo di√®sediam√®tre pothauteur pothauteur de cartelargeur de cartechanfreinchanfrein dans les coinscoffreclearanced√©gagement du couvercleferm√©connectionrayon des coinscr√©e un engrenage en anneau o√π la courroie est press√©e de l'int√©rieurcutupr√©r√© di√®sed1d2d3debugaucun (par d√©faut)dent deltaprofondeurprofondeur en basprofondeur en hautprofondeur derri√®re les enconchesprofondeur des encoches depuis le devantdepth of the grooveslargeur de l'√©tag√®reprofondeur des visi√®resprofondeur des c√¥t√©sm√©platdiam√®trediam√®tre du dessousdiam√®tre du dessusdiam√®tre du trou pour les boulons de la cheville - cot√© du pieddiam√®tre du trou pour les boulons de la cheville - cot√© de la jambediam√®tre de la brche en mmdiam√®tre des chevilles d'alignementdiam√®tre de la partie basse du trou de visdiam√®tre de l'essieudiam√®tre des essieusDiam√®tre du bas des fl√ªtes en mmDiam√®tre du trou pour l'outil (le manche ne doit pas passer)diam√®tre du trou pour l'axediameter of the pin hole in mmdiam√®tre de la broche en mmdiam√®tre de la vis en mmdiam√®tre de l'arbrediam√®tre de l'arbre 1diam√®tre de l'arbre 2 (z√©ro pour le m√™me que l'arbre 1)diam√®tre des ¬´¬†pneux¬†¬ª des joints toriquesdiam√®tre de la chose √† accrocherdiam√®tre de l'outil incluant l'espace pour tenirdiam√®tre de la partie haute du trou de visdimensiondiam√®tre disqued√©bord disque√©paisseur disquedistancedistance des trous des cr√©neaux au bord du basdistance of flex cuts in multiples of thicknessdoublem√©plat 1m√©plat 2dxfetype de bord pour le bord du bastype de bord √† gauchetype de bord √† droitetype de bord pour le bord du hautlargeur de bordactiver un anneau secondaire avec le delta donn√© par rapport √† l'anneau d'engrenagesun sur troisextend outward the straight edgeextend the triangle along the length of the edgehauteur suppl√©mentaire pour faciliter le fonctionnement en mmespace suppl√©mentaire pour autoriser un mouvementhauteur extrahauteur extraeyeeyes_per_hingeffa di√®secr√©neaulongueur fixe des attaches sur les couverclesplatflushdiam√®tre fl√ªteformatformat du fichier r√©sultantquatreFraction de la case couverte par la paroi pench√©efrom one middle of a dove tail to anotherdevantfwsolsol di√®segcodeplus que z√©ro pour que le haut soit plus large que le basgrip_lengthgrip_percentagehauteur poign√©elargeur poign√©ehHauteur de poign√©elargeur de poign√©efaire un d√©bord du couvercle sur les c√¥t√©s (similaire √† OutSetEdge)hauteurheight above the walldiff√©rence de hauteur de gauche √† droitehauteur en unit√©s du rackhauteur des parois de devanthauteur du couvercle en mmhauteur du profil√© (aluminium) reliant les partieshauteur de la bo√Ætehauteur des piedshauteur du coin devant gauche en mmhauteur du devant du rabothauteur du coin devant droit en mmHauteur du trou-poign√©e en mmhauteur de coin arri√®re gauche en mmhauteur du couverclehauteur du coin droit arri√®re en mmhauteur de la t√™te de vis en mmhauteur 0hauteur 1hauteur 2hauteur 3hauteurhauteur du corpst√™te hexhexhiUne valeur plus grande donne une cannelure plus profonde (degr√©)largeur de bridehingeshingestrengthlongueur gardetroudiam√®tre du troudistance des trousdistance des trouscrochetcrochet hauteur extracrochetshow far the dove tails stick out of/into the edgeDe combien les cr√©neaux doivent s'√©largir (-80 √† 80)ien Paen pourcentage du moduleprofondeur int√©rieure en mmprofondeur interieure en mm (si on ne choisit pas ¬´¬†ext√©rieur¬†¬ª)Profondeur int√©rieure sans inclure les visi√®resprofondeur int√©rieure du crochethauteur interieure en mm (si on ne choisit pas ¬´¬†ext√©rieur¬†¬ª)hauteur des cloisons internes interieure en mm (si on ne choisit pas ¬´¬†ext√©rieur¬†¬ª) (laisser √† z√©ro pour des cloisons aussi hautes que les bords)hauteur int√©rieure du crochetrayon int√©rieur de la bo√Æte (dans les coins)largeur interieure en mm (si on ne choisit pas ¬´¬†ext√©rieur¬†¬ª)largeur int√©rieure de la consoleinsideangle int√©rieur des piedsdedans dehorsintonationjklargeur couteauxltaille des d√©coupes du flexiblegauchebord gauchelongueur de la pi√®ce gardant le haut du rabot devantlongueur du rabotlongueurlongueur des jambes (34 mm au minimum)longueur du segment (entraxe)longueur 1longueur 2longueur 3longueur 4longueur 5couverclehauteur de couvercleLinite du nombre de plan√®tes (0 pour autant que possible)facteur basmmBarforce maxlargeur maxhauteur maxhauteur de serrage maximale en mmespace maximum au d√©but et √† la fin des multiples d'un espace normalplan√®tes maxmensurforce minlargeur minhauteur minminimaleshauteur de serrage minimale en mmminimum space around the hingeespace minmm H2Omm Hgmodulemodulus of the gear (in mm)module des dents en mmratio de la bouche √† la circonf√©rence (0,1 √† 0,45). D√©termine le ratio largeur sur profondeurratio de bouchennema_mountpas de verticalesaucunnumnombrenombre de compartimentsnombre de compartiments de devant √† derri√®renombre de compartiments c√¥te √† c√¥tenumber of hinges per edgenombre de feuxNombre d'atgesnombre de c√¥t√©snombre de semellesnombre de niveaux dans le r√©ducteur √† engrenagesnombre de dentsnombre de dents de l'autre taille d'engrenagenombre de dents de l'engrenage d'entr√©enombre de dents de l'engrenage de sortienombre de dents sur les plan√®tesnombre de dents sur l'engranage soleilnombre d'outils/d'encochesnombre de parois d'un c√¥t√© (+1)nombre de cl√©sooctaveimpairsunarguments optionnelsdiam√®tre externe des roues (y compris les joints toriques)outsetext√©rieurmontages externeslargeur moyenne des outilsd√©bordementd√©bordement des joints en mmD√©bord de la jante (z√©ro pour rien du tout)ppdfpourcentage du m√©plat de l'arbre 2 (z√©ro pur le m√™me que l'arbre 1)pourcentage du m√©plat de l'arbre 1 (100 pour un arbre rond)pieces per hingebrochehauteur du tenontaille des chevillespinwidthLe tuyau est ferm√© en hauthauteurdents plan√®tejeujeu entre les deux parties, comme multiple de l'√©paisseur de la paroipltDiam√®tre de la brochepressure angleangle de pressionimprime un rectangle de r√©f√©rence avec la longueur donn√©e (z√©ro pour d√©sactiver)imprime les rectangles contenant certaines structuresprofilprofil des dents/de la courroieglissement de profilpsqrr_holerayonRayon aux encochesrayon pour renforcer les parois avec les crochetsrayon des coins du dessousradius of holerayon des coinsrayon des coins en mmrayon du tenon en forme de disque articulant la charni√®reradius of the eye (in multiples of thickness)rayon de la charni√®re flexible du couverclerayon des encoches sur le devantradius of top cornerradius used on all four cornersglissi√®refacteur arri√®rer√©f√©rencedroitebord droitcouvercle rondarrondi√©paisseur caoutchoucsvisvis 1vis 2t√™te de vishauteur t√™tesecond_pinlargeur des sections du devant vers derri√®re en mm. Formats possibles¬†: largeur totale/nombre de sections p.ex. "250/5"¬†; largeur_de_section*nombre_de_section p.ex. "50*5"; largeurs de sections s√©par√©es par ":" p.ex. "30:25.5:70largeur des sections de bas en haut en mm. Voir --sy pour le formatlargeur des sections de gauche √† droite en mm. Voir --sy pour le formatangle cannelagecanneluresservo 1aservo 1bservo 2aservo 2bservo 3aservo 3bservo 4aservo 4bservo 5aservo 5bR√©gler √† la valeur inf√©rieure pour avoir des disques entourant les axesshvisi√®resarbrearbre 1arbre 2uniquetailletaille des d√©coupes en mutiples de l'√©paisseurprofondeur encochelargeur encocheencochesEncoches pour acc√®der au bloc-noteespaceespace sous les trous du bord de l'enture cr√©nel√©espace between eyes (in multiples of thickness)espace entre les cr√©neauxespace autour des connecteurs (en multiples de l'√©paisseur)spacings√©parer le couvercle en direction y (mm)couvercle s√©par√©springplacer les feux c√¥te √† c√¥teniveauxferm√©forceforce de la plus grande cl√©force de la plus petite cl√©stretchcloustylestyle of hinge usedstyle du dessus et du couvercledents soleilespaces autoursvgsvg_Ponokosxsytbridesdentsdents 1dents 2√©paisseur√©paisseur de l'arc qui tient en place l'axelargeur des couteaux en mm. Utiliser 0 pour les tables en nid d'abeille.√©paisseur du mat√©riaulargeur outildiam√®tre_outildessusprofondeur hautdiam√®tre du hautbord du hauttraiter les dimensions comme des dimensions ext√©rieures qui incluent les paroistriangledeuxtype du segment pour le brastype de servo-moteur √† utilisertype de servo-moteur √† utiliser sur le deuxi√®me c√¥t√© (si une diff√©rence est support√©e)type 1type 2type 3type 4type 5uc√¥te √† c√¥teutilise l'unit√© s√©lectionn√©e ci-dessousvparoinombre de pi√®cesparoiswavequelle parois du nid d'abeille doit-on ajouterlargeurlargeur des trous des cr√©neauxlargeur de la cl√© la plus grandelargeur des encocheslargeur de la cl√© la plus petiteLargeur de la bande de semellelargeur des brides qui tiennent les composants en place, en mm (non support√© partout)largeur des dents en mmlargeur du trou-pign√©e en mm (z√©ro pour aucun trou)largeur du profil√© (aluminium) reliant les partieslargeur des piedslargeur des cr√©neauxlargeur des espaces dans les d√©coupeslargeur du crochet (le plateau arri√®re est un peu plus large)largeur du crochet vu de c√¥t√©Largeur dela partie longuelargeur du motif perpendiculaire aux d√©coupeslargeur du rabotlargeur de la paroi ext√©rieure en mmpression du ventunit√© de pressionlargeur de la t√™te de vis en mmxyz
59,142
Python
.py
119
495.621849
10,490
0.599593
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,529
formats.py
florianfesti_boxes/boxes/formats.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import shutil import subprocess import tempfile from boxes.drawing import Context, LBRN2Surface, PSSurface, SVGSurface class Formats: pstoedit_candidates = ["/usr/bin/pstoedit", "pstoedit", "pstoedit.exe"] ps2pdf_candidates = ["/usr/bin/ps2pdf", "ps2pdf", "ps2pdf.exe"] _BASE_FORMATS = ['svg', 'svg_Ponoko', 'ps', 'lbrn2'] formats = { "svg": None, "svg_Ponoko": None, "ps": None, "lbrn2": None, "dxf": "{pstoedit} -flat 0.1 -f dxf:-mm {input} {output}", "gcode": "{pstoedit} -f gcode {input} {output}", "plt": "{pstoedit} -f hpgl {input} {output}", # "ai": "{pstoedit} -f ps2ai", "pdf": "{ps2pdf} -dEPSCrop {input} {output}", } http_headers = { "svg": [('Content-type', 'image/svg+xml; charset=utf-8')], "svg_Ponoko": [('Content-type', 'image/svg+xml; charset=utf-8')], "ps": [('Content-type', 'application/postscript')], "lbrn2": [('Content-type', 'application/lbrn2')], "dxf": [('Content-type', 'image/vnd.dxf')], "plt": [('Content-type', ' application/vnd.hp-hpgl')], "gcode": [('Content-type', 'text/plain; charset=utf-8')], # "" : [('Content-type', '')], } def __init__(self) -> None: for cmd in self.pstoedit_candidates: self.pstoedit = shutil.which(cmd) if self.pstoedit: break for cmd in self.ps2pdf_candidates: self.ps2pdf = shutil.which(cmd) if self.ps2pdf: break def getFormats(self): if self.pstoedit: return sorted(self.formats.keys()) return self._BASE_FORMATS def getSurface(self, fmt): if fmt in ("svg", "svg_Ponoko"): surface = SVGSurface() elif fmt == "lbrn2": surface = LBRN2Surface() else: surface = PSSurface() ctx = Context(surface) return surface, ctx def convert(self, data, fmt): if fmt not in self._BASE_FORMATS: fd, tmpfile = tempfile.mkstemp() os.write(fd, data.getvalue()) os.close(fd) fd2, outfile = tempfile.mkstemp() cmd = self.formats[fmt].format( pstoedit=self.pstoedit, ps2pdf=self.ps2pdf, input=tmpfile, output=outfile).split() result = subprocess.run(cmd) os.unlink(tmpfile) if result.returncode: # XXX show stderr output raise ValueError("Conversion failed. pstoedit returned %i\n\n %s" % (result.returncode, result.stderr)) data = open(outfile, 'rb') os.unlink(outfile) os.close(fd2) return data
3,484
Python
.py
86
32.034884
119
0.591003
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,530
Color.py
florianfesti_boxes/boxes/Color.py
class Color: BLACK = [ 0.0, 0.0, 0.0 ] BLUE = [ 0.0, 0.0, 1.0 ] GREEN = [ 0.0, 1.0, 0.0 ] RED = [ 1.0, 0.0, 0.0 ] CYAN = [ 0.0, 1.0, 1.0 ] YELLOW = [ 1.0, 1.0, 0.0 ] MAGENTA = [ 1.0, 0.0, 1.0 ] WHITE = [ 1.0, 1.0, 1.0 ] # TODO: Make this configurable OUTER_CUT = BLACK INNER_CUT = BLUE ANNOTATIONS = RED ETCHING = GREEN ETCHING_DEEP = CYAN
414
Python
.py
15
22.8
34
0.469849
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,531
walledges.py
florianfesti_boxes/boxes/walledges.py
from __future__ import annotations import math from typing import Any from boxes import Boxes, edges from .edges import BaseEdge, Settings class _WallMountedBox(Boxes): ui_group = "WallMounted" def __init__(self) -> None: super().__init__() self.addWallSettingsArgs() def addWallSettingsArgs(self): self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(WallSettings) self.addSettingsArgs(SlatWallSettings) self.addSettingsArgs(DinRailSettings) self.addSettingsArgs(FrenchCleatSettings) self.argparser.add_argument( "--walltype", action="store", type=str, default="plain", choices=["plain", "plain reinforced", "slatwall", "dinrail", "french cleat"], help="Type of wall system to attach to") def generateWallEdges(self): if self.walltype.startswith("plain"): s = WallSettings( self.thickness, True, **self.edgesettings.get("Wall", {})) elif self.walltype == "slatwall": s = SlatWallSettings( self.thickness, True, **self.edgesettings.get("SlatWall", {})) elif self.walltype == "dinrail": s = DinRailSettings( self.thickness, True, **self.edgesettings.get("DinRail", {})) elif self.walltype == "french cleat": s = FrenchCleatSettings( self.thickness, True, **self.edgesettings.get("FrenchCleat", {})) s.edgeObjects(self) self.wallHolesAt = self.edges["|"] if self.walltype.endswith("reinforced"): self.edges["c"] = self.edges["d"] self.edges["C"] = self.edges["D"] ############################################################################# #### Straight Edge / Base class ############################################################################# class WallEdge(BaseEdge): _reversed = False def lengths(self, length): return [length] def _joint(self, length): self.edge(length) def _section(self, nr, length): self.edge(length) def __call__(self, length, **kw): lengths = list(enumerate(self.lengths(length))) if self._reversed: lengths = list(reversed(lengths)) for nr, l in lengths: if l == 0.0: continue if nr % 2: self._section(nr // 2, l) else: self._joint(l) class WallJoinedEdge(WallEdge): char = "b" def _joint(self, length): t = self.settings.thickness self.step(-t) self.edges["f"](length) self.step(t) def startwidth(self) -> float: return self.settings.thickness class WallBackEdge(WallEdge): def _section(self, nr, length): self.edge(length) def _joint(self, length): t = self.settings.thickness self.step(t) self.edges["F"](length) self.step(-t) def margin(self) -> float: return self.settings.thickness class WallHoles(WallEdge): def _section(self, nr, length): self.rectangularHole(length/2, 0, length, self.settings.thickness) self.moveTo(length, 0) def _joint(self, length): self.fingerHolesAt(0, 0, length, 0) self.moveTo(length, 0) def __call__(self, x, y, length, angle, **kw): """ Draw holes for a matching WallJoinedEdge :param x: x position :param y: y position :param length: length of matching edge :param angle: (Default value = 90) """ with self.boxes.saved_context(): self.boxes.moveTo(x, y, angle) b = self.boxes.burn t = self.settings.thickness if self.boxes.debug: # XXX width = self.settings.thickness self.ctx.rectangle(b, -width / 2 + b, length - 2 * b, width - 2 * b) self.boxes.moveTo(length, 0, 180) super().__call__(length) class WallHoleEdge(WallHoles): """Edge with holes for a parallel finger joint""" description = "Edge (parallel slot wall Holes)" def __init__(self, boxes, wallHoles, **kw) -> None: super().__init__(boxes, wallHoles.settings, **kw) self.wallHoles = wallHoles def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): dist = self.wallHoles.settings.edge_width + self.settings.thickness / 2 with self.saved_context(): px, angle = (0, 0) if self._reversed else (length, 180) self.wallHoles( px, dist, length, angle) self.edge(length, tabs=2) def startwidth(self) -> float: """ """ return self.wallHoles.settings.edge_width + self.settings.thickness def margin(self) -> float: return 0.0 class WallSettings(Settings): """Settings for plain WallEdges Values: * relative (in multiples of thickness) * edge_width : 1.0 : space below holes of FingerHoleEdge (multiples of thickness) """ absolute_params: dict[str, Any] = { } relative_params = { "edge_width": 1.0, } base_class = WallEdge def edgeObjects(self, boxes, chars="aAbBcCdD|", add=True): bc = self.base_class bn = bc.__name__ wallholes = type(bn+"Hole", (WallHoles, bc), {})(boxes, self) edges = [bc(boxes, self), type(bn+"Reversed", (bc,), {'_reversed' : True})(boxes, self), type(bn+"Joined", (WallJoinedEdge, bc), {})(boxes, self), type(bn+"JoinedReversed", (WallJoinedEdge, bc), {'_reversed' : True})(boxes, self), type(bn+"Back", (WallBackEdge, bc), {})(boxes, self), type(bn+"BackReversed", (WallBackEdge, bc), {'_reversed' : True})(boxes, self), type(bn+"Hole", (WallHoleEdge, bc), {})(boxes, wallholes), type(bn+"HoleReversed", (WallHoleEdge, bc), {'_reversed' : True})(boxes, wallholes), wallholes, ] return self._edgeObjects(edges, boxes, chars, add) ############################################################################# #### Slat wall ############################################################################# class SlatWallEdge(WallEdge): def lengths(self, length): pitch = self.settings.pitch h = self.settings.hook_height he = self.settings.hook_extra_height lengths = [] if length < h + he: return [length] lengths = [0, h + he] length -= h + he if length > pitch: lengths.extend([(length // pitch) * pitch - h - 2 - 2*he, h + 2 + 2*he, length % pitch]) else: lengths.append(length) return lengths def _section(self, nr, length): w = self.settings.hook_height # vertical width of hook hd = self.settings.hook_depth hdist = self.settings.hook_distance hh = self.settings.hook_overall_height ro = w # outer radius ri = min(w/2, hd/2) # inner radius rt = min(1, hd/2) # top radius slot = self.settings.hook_height + 2 # XXX if nr == 0: poly = [0, -90, hdist-ri, (-90, ri), hh-ri-w-rt, (90, rt), hd-2*rt, (90, rt), hh-ro-rt, (90, ro), hdist+hd-ro, -90, length-6] elif nr == 1: if self.settings.bottom_hook == "spring": r_plug = slot*.4 slotslot = slot - r_plug * 2**0.5 poly = [self.settings.hook_extra_height, -90, 5.0, -45, 0, (135, r_plug), 0, 90, 10, -90, slotslot, -90, 10, 90, 0, (135, r_plug), 0, -45, 5, -90, self.settings.hook_extra_height] elif self.settings.bottom_hook == "hook": d = 2 poly = [self.settings.hook_extra_height + d - 1, -90, 4.5+hd, (90,1), slot-2, (90, 1), hd-1, 90, d, -90, 5.5, -90, self.settings.hook_extra_height + 1] elif self.settings.bottom_hook == "stud": poly = [self.settings.hook_extra_height, -90, 6, (90, 1) , slot-2, (90, 1), 6, -90, self.settings.hook_extra_height] else: poly = [2*self.settings.hook_extra_height + slot] if self._reversed: poly = reversed(poly) self.polyline(*poly) def margin(self) -> float: return self.settings.hook_depth + self.settings.hook_distance class SlatWallSettings(WallSettings): """Settings for SlatWallEdges Values: * absolute_params * bottom_hook : "hook" : "spring", "stud" or "none" * pitch : 101.6 : vertical spacing of slots middle to middle (in mm) * hook_depth : 4.0 : horizontal width of the hook * hook_distance : 5.5 : horizontal space to the hook * hook_height : 6.0 : height of the horizontal bar of the hook * hook_overall_height : 12.0 : height of the hook top to bottom * relative (in multiples of thickness) * hook_extra_height : 2.0 : space surrounding connectors (multiples of thickness) * edge_width : 1.0 : space below holes of FingerHoleEdge (multiples of thickness) """ absolute_params = { "bottom_hook" : ("hook", "spring", "stud", "none"), "pitch" : 101.6, "hook_depth" : 4.0, "hook_distance" : 5.5, "hook_height" : 6.0, "hook_overall_height" : 12.0, } relative_params = { "hook_extra_height" : 2.0, "edge_width": 1.0, } base_class = SlatWallEdge ############################################################################# #### DIN rail ############################################################################# class DinRailEdge(WallEdge): def lengths(self, length): if length < 20: return [length] if length > 50 and self.settings.bottom == "stud": return [0, 20, length - 40, 20] return [0, 20, length - 20] def _section(self, nr, length): d = self.settings.depth if nr == 0: r = 1. poly = [0, -90, d-0.5-r, (90, r), 15+3-2*r, (90, r), d-4-r, 45, 4*2**.5, -45, .5, -90, 6] elif nr == 1: slot = 20 if self.settings.bottom == "stud": r = 1. poly = [0, -90, 7.5-r, (90, r), slot - 2*r, (90, r), 7.5-r, -90, 0] else: poly = [slot] if self._reversed: poly = reversed(poly) self.polyline(*poly) def margin(self) -> float: return self.settings.depth class DinRailSettings(WallSettings): """Settings for DinRailEdges Values: * absolute_params * bottom : "stud" : "stud" or "none" * depth : 4.0 : horizontal width of the hook * relative (in multiples of thickness) * edge_width : 1.0 : space below holes of FingerHoleEdge (multiples of thickness) """ absolute_params = { "bottom" : ("stud", "none"), "depth" : 8.0, } relative_params = { "edge_width": 1.0, } base_class = DinRailEdge ############################################################################# #### French Cleats ############################################################################# class FrenchCleatEdge(WallEdge): def lengths(self, length): d = self.settings.depth t = self.settings.thickness s = self.settings.spacing h = d * math.tan(math.radians(self.settings.angle)) # make small enough to not have finger holes top = 0.5*t bottom = 0.5 * t if length < top + bottom + 1.5*d + h: return [length] if length > top + bottom + 2*t + 1.5*d + h and \ self.settings.bottom == "stud": return [top, 1.5*d + h, length - top - bottom - 2.5*d - h, d, bottom] if length > top + bottom + 2.5*d + s and \ self.settings.bottom == "hook": dist = ((length - top - t - 1.5*d - h) // s ) * s - 1.5*d - h return [top, 1.5*d + h, dist, 1.5*d + h, length-dist-top-3*d-2*h] return [top, 2.5*d, length-top-2.5*d] def _section(self, nr, length): d = self.settings.depth t = self.settings.thickness r = min(0.5*t, 0.1*d) a = self.settings.angle h = d * math.tan(math.radians(a)) l = d / math.cos(math.radians(a)) if nr == 0 or self.settings.bottom == "hook": poly = [0, -90, 0, (90, d), .5*d+h, 90+a, l, -90-a, length-1.5*d] elif nr == 1: if self.settings.bottom == "stud": r = min(t, length/4, d) poly = [0, -90, d-r, (90, r), length - 2*r, (90, r), d-r, -90, 0] else: poly = [length] if self._reversed: poly = reversed(poly) self.polyline(*poly) def margin(self) -> float: return self.settings.depth class FrenchCleatSettings(WallSettings): """Settings for FrenchCleatEdges Values: * absolute_params * bottom : "stud" : "stud" to brace against the wall, "hook" for attaching to a second cleat or "none" for just straight * depth : 18.0 : horizontal width of the hook in mm * angle : 45.0 : angle of the cut (0 for horizontal) * spacing : 200.0 : distance of the cleats in mm (for bottom hook) * relative (in multiples of thickness) * edge_width : 1.0 : space below holes of FingerHoleEdge (multiples of thickness) """ absolute_params = { "bottom" : ("stud", "hook", "none"), "depth" : 18.0, "spacing" : 200.0, "angle" : 45.0, } relative_params = { "edge_width": 1.0, } base_class = FrenchCleatEdge
14,169
Python
.py
354
30.460452
121
0.523757
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,532
vectors.py
florianfesti_boxes/boxes/vectors.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math def normalize(v): """set length of vector to one""" l = (v[0] ** 2 + v[1] ** 2) ** 0.5 if l == 0.0: return (0.0, 0.0) return (v[0] / l, v[1] / l) def vlength(v): return (v[0] ** 2 + v[1] ** 2) ** 0.5 def vclip(v, length): l = vlength(v) if l > length: return vscalmul(v, length / l) return v def vdiff(p1, p2): """vector from point1 to point2""" return (p2[0] - p1[0], p2[1] - p1[1]) def vadd(v1, v2): """Sum of two vectors""" return (v1[0] + v2[0], v1[1] + v2[1]) def vorthogonal(v): """Orthogonal vector""" return (-v[1], v[0]) def vscalmul(v, a): """scale vector by a""" return (a * v[0], a * v[1]) def dotproduct(v1, v2): """Dot product""" return v1[0] * v2[0] + v1[1] * v2[1] def circlepoint(r, a): return (r * math.cos(a), r * math.sin(a)) def tangent(x, y, r): """angle and length of a tangent to a circle at x,y with radius r""" l1 = vlength((x, y)) a1 = math.atan2(y, x) a2 = math.asin(r / l1) l2 = math.cos(a2) * l1 return (a1+a2, l2) def rotm(angle): """Rotation matrix""" return [[math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0]] def vtransl(v, m): m0, m1 = m return [m0[0] * v[0] + m0[1] * v[1] + m0[2], m1[0] * v[0] + m1[1] * v[1] + m1[2]] def mmul(m0, m1): result = [[0, ] * len(m0[0]) for i in range(len(m0))] for i in range(len(m0[0])): for j in range(len(m0)): for k in range(len(m0)): result[j][i] += m0[k][i] * m1[j][k] return result def kerf(points, k, closed=True): """Outset points by k Assumes a closed loop of points """ result = [] lp = len(points) for i in range(len(points)): # get normalized orthogonals of both segments v1 = vorthogonal(normalize(vdiff(points[i - 1], points[i]))) v2 = vorthogonal(normalize(vdiff(points[i], points[(i + 1) % lp]))) if not closed: if i == 0: v1 = v2 if i == lp-1: v2 = v1 # direction the point has to move d = normalize(vadd(v1, v2)) # cos of the half the angle between the segments cos_alpha = dotproduct(v1, d) result.append(vadd(points[i], vscalmul(d, -k / cos_alpha))) return result
3,076
Python
.py
88
29.534091
75
0.584319
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,533
drawing.py
florianfesti_boxes/boxes/drawing.py
from __future__ import annotations import codecs import io import math from typing import Any from xml.etree import ElementTree as ET from affine import Affine from boxes.extents import Extents EPS = 1e-4 PADDING = 10 RANDOMIZE_COLORS = False # enable to ease check for continuity of paths def reorder_attributes(root) -> None: """ Source: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove """ for el in root.iter(): attrib = el.attrib if len(attrib) > 1: # adjust attribute order, e.g. by sorting attribs = sorted(attrib.items()) attrib.clear() attrib.update(attribs) def points_equal(x1, y1, x2, y2): return abs(x1 - x2) < EPS and abs(y1 - y2) < EPS def pdiff(p1, p2): x1, y1 = p1 x2, y2 = p2 return (x1 - x2, y1 - y2) class Surface: scale = 1.0 invert_y = False def __init__(self) -> None: self.parts: list[Any] = [] self._p = self.new_part("default") self.count = 0 def set_metadata(self, metadata): self.metadata = metadata def flush(self): pass def finish(self): pass def _adjust_coordinates(self): extents = self.extents() extents.xmin -= PADDING extents.ymin -= PADDING extents.xmax += PADDING extents.ymax += PADDING m = Affine.translation(-extents.xmin, -extents.ymin) if self.invert_y: m = Affine.scale(self.scale, -self.scale) * m m = Affine.translation(0, self.scale*extents.height) * m else: m = Affine.scale(self.scale, self.scale) * m self.transform(self.scale, m, self.invert_y) return Extents(0, 0, extents.width * self.scale, extents.height * self.scale) def render(self, renderer): renderer.init(**self.args) for p in self.parts: p.render(renderer) renderer.finish() def transform(self, f, m, invert_y=False): for p in self.parts: p.transform(f, m, invert_y) def new_part(self, name="part"): if self.parts and len(self.parts[-1].pathes) == 0: return self._p p = Part(name) self.parts.append(p) self._p = p return p def append(self, *path): self.count += 1 if self.count > 100000: raise ValueError("Too many lines") self._p.append(*path) def stroke(self, **params): return self._p.stroke(**params) def move_to(self, *xy): self._p.move_to(*xy) def extents(self): if not self.parts: return Extents() return sum([p.extents() for p in self.parts]) class Part: def __init__(self, name) -> None: self.pathes: list[Any] = [] self.path: list[Any] = [] def extents(self): if not self.pathes: return Extents() return sum([p.extents() for p in self.pathes]) def transform(self, f, m, invert_y=False): assert(not self.path) for p in self.pathes: p.transform(f, m, invert_y) def append(self, *path): self.path.append(list(path)) def stroke(self, **params): if len(self.path) == 0: return # search for path ending at new start coordinates to append this path to xy0 = self.path[0][1:3] if (not points_equal(*xy0, *self.path[-1][1:3]) and not self.path[0][0] == "T"): for p in reversed(self.pathes): xy1 = p.path[-1][1:3] if points_equal(*xy0, *xy1) and p.params == params: p.path.extend(self.path[1:]) self.path = [] return p p = Path(self.path, params) self.pathes.append(p) self.path = [] return p def move_to(self, *xy): if len(self.path) == 0: self.path.append(["M", *xy]) elif self.path[-1][0] == "M": self.path[-1] = ["M", *xy] else: xy0 = self.path[-1][1:3] if not points_equal(*xy0, *xy): self.path.append(["M", *xy]) class Path: def __init__(self, path, params) -> None: self.path = path self.params = params def __repr__(self) -> str: l = len(self.path) # x1,y1 = self.path[0][1:3] if l>0: x2, y2 = self.path[-1][1:3] return f"Path[{l}] to ({x2:.2f},{y2:.2f})" return f"empty Path" def extents(self): e = Extents() for p in self.path: e.add(*p[1:3]) if p[0] == 'T': m, text, params = p[3:] h = params['fs'] l = len(text) * h * 0.7 align = params.get('align', 'left') start, end = { 'left' : (0, 1), 'middle' : (-0.5, 0.5), 'end' : (-1, 0), }[align] for x in (start*l, end*l): for y in (0, h): x_, y_ = m * (x, y) e.add(x_, y_) return e def transform(self, f, m, invert_y=False): self.params["lw"] *= f for c in self.path: C = c[0] c[1], c[2] = m * (c[1], c[2]) if C == 'C': c[3], c[4] = m * (c[3], c[4]) c[5], c[6] = m * (c[5], c[6]) if C == "T": c[3] = m * c[3] if invert_y: c[3] *= Affine.scale(1, -1) def faster_edges(self, inner_corners): if inner_corners == "backarc": return for (i, p) in enumerate(self.path): if p[0] == "C" and i > 1 and i < len(self.path) - 1: if self.path[i - 1][0] == "L" and self.path[i + 1][0] == "L": p11 = self.path[i - 2][1:3] p12 = self.path[i - 1][1:3] p21 = p[1:3] p22 = self.path[i + 1][1:3] if (((p12[0]-p21[0])**2 + (p12[1]-p21[1])**2) > self.params["lw"]**2): continue lines_intersect, x, y = line_intersection((p11, p12), (p21, p22)) if lines_intersect: self.path[i - 1] = ("L", x, y) if inner_corners == "loop": self.path[i] = ("C", x, y, *p12, *p21) else: self.path[i] = ("L", x, y) # filter duplicates if len(self.path) > 1: # no need to find duplicates if only one element in path self.path = [p for n, p in enumerate(self.path) if p != self.path[n-1]] class Context: def __init__(self, surface, *al, **ad) -> None: self._renderer = self._dwg = surface self._bounds = Extents() self._padding = PADDING self._stack: list[Any] = [] self._m = Affine.translation(0, 0) self._xy = (0, 0) self._mxy = self._m * self._xy self._lw = 0 self._rgb = (0, 0, 0) self._ff = "sans-serif" self._fs = 10 self._last_path = None def _update_bounds_(self, mx, my): self._bounds.update(mx, my) def save(self): self._stack.append( (self._m, self._xy, self._lw, self._rgb, self._mxy, self._last_path) ) self._xy = (0, 0) def restore(self): ( self._m, self._xy, self._lw, self._rgb, self._mxy, self._last_path, ) = self._stack.pop() ## transformations def translate(self, x, y): self._m *= Affine.translation(x, y) self._xy = (0, 0) def scale(self, sx, sy): self._m *= Affine.scale(sx, sy) def rotate(self, r): self._m *= Affine.rotation(180 * r / math.pi) def set_line_width(self, lw): self._lw = lw def set_source_rgb(self, r, g, b): self._rgb = (r, g, b) ## path methods def _line_to(self, x, y): self._add_move() x1, y1 = self._mxy self._xy = x, y x2, y2 = self._mxy = self._m * self._xy if not points_equal(x1, y1, x2, y2): self._dwg.append("L", x2, y2) def _add_move(self): self._dwg.move_to(*self._mxy) def move_to(self, x, y): self._xy = (x, y) self._mxy = self._m * self._xy def line_to(self, x, y): self._line_to(x, y) def _arc(self, xc, yc, radius, angle1, angle2, direction): if abs(angle1 - angle2) < EPS or radius < EPS: return x1, y1 = radius * math.cos(angle1) + xc, radius * math.sin(angle1) + yc x4, y4 = radius * math.cos(angle2) + xc, radius * math.sin(angle2) + yc # XXX direction seems not needed for small arcs ax = x1 - xc ay = y1 - yc bx = x4 - xc by = y4 - yc q1 = ax * ax + ay * ay q2 = q1 + ax * bx + ay * by k2 = 4/3 * ((2 * q1 * q2)**0.5 - q2) / (ax * by - ay * bx) x2 = xc + ax - k2 * ay y2 = yc + ay + k2 * ax x3 = xc + bx + k2 * by y3 = yc + by - k2 * bx mx1, my1 = self._m * (x1, y1) mx2, my2 = self._m * (x2, y2) mx3, my3 = self._m * (x3, y3) mx4, my4 = self._m * (x4, y4) mxc, myc = self._m * (xc, yc) self._add_move() self._dwg.append("C", mx4, my4, mx2, my2, mx3, my3) self._xy = (x4, y4) self._mxy = (mx4, my4) def arc(self, xc, yc, radius, angle1, angle2): self._arc(xc, yc, radius, angle1, angle2, 1) def arc_negative(self, xc, yc, radius, angle1, angle2): self._arc(xc, yc, radius, angle1, angle2, -1) def curve_to(self, x1, y1, x2, y2, x3, y3): # mx0,my0 = self._m*self._xy mx1, my1 = self._m * (x1, y1) mx2, my2 = self._m * (x2, y2) mx3, my3 = self._m * (x3, y3) self._add_move() self._dwg.append("C", mx3, my3, mx1, my1, mx2, my2) # destination first! self._xy = (x3, y3) self._mxy = (mx3, my3) def stroke(self): # print('stroke stack-level=',len(self._stack),'lastpath=',self._last_path,) self._last_path = self._dwg.stroke(rgb=self._rgb, lw=self._lw) self._xy = (0, 0) def fill(self): self._xy = (0, 0) raise NotImplementedError() def set_font(self, style, bold=False, italic=False): if style not in ("serif", "sans-serif", "monospaced"): raise ValueError("Unknown font style") self._ff = (style, bold, italic) def set_font_size(self, fs): self._fs = fs def show_text(self, text, **args): params = {"ff": self._ff, "fs": self._fs, "lw": self._lw, "rgb": self._rgb} params.update(args) mx0, my0 = self._m * self._xy m = self._m self._dwg.append("T", mx0, my0, m, text, params) def text_extents(self, text): fs = self._fs # XXX ugly hack! Fix Boxes.text() ! return (0, 0, 0.6 * fs * len(text), 0.65 * fs, fs * 0.1, 0) def rectangle(self, x, y, width, height): # todo: better check for empty path? self.stroke() self.move_to(x, y) self.line_to(x + width, y) self.line_to(x + width, y + height) self.line_to(x, y + height) self.line_to(x, y) self.stroke() def get_current_point(self): return self._xy def flush(self): pass # todo: check, if needed # self.stroke() ## additional methods def new_part(self): self._dwg.new_part() class SVGSurface(Surface): invert_y = True fonts = { 'serif' : 'TimesNewRoman, "Times New Roman", Times, Baskerville, Georgia, serif', 'sans-serif' : '"Helvetica Neue", Helvetica, Arial, sans-serif', 'monospaced' : '"Courier New", Courier, "Lucida Sans Typewriter"' } def _addTag(self, parent, tag, text, first=False): if first: t = ET.Element(tag) else: t = ET.SubElement(parent, tag) t.text = text t.tail = '\n' if first: parent.insert(0, t) return t def _add_metadata(self, root) -> None: md = self.metadata title = "{group} - {name}".format(**md) creation_date: str = md["creation_date"].strftime("%Y-%m-%d %H:%M:%S") # Add Inkscape style rdf meta data root.set("xmlns:dc", "http://purl.org/dc/elements/1.1/") root.set("xmlns:cc", "http://creativecommons.org/ns#") root.set("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") m = self._addTag(root, "metadata", '\n', True) r = ET.SubElement(m, 'rdf:RDF') w = ET.SubElement(r, 'cc:Work') w.text = '\n' self._addTag(w, 'dc:title', title) if not md["reproducible"]: self._addTag(w, 'dc:date', creation_date) if "url" in md and md["url"]: self._addTag(w, 'dc:source', md["url"]) self._addTag(w, 'dc:source', md["url_short"]) else: self._addTag(w, 'dc:source', md["cli"]) desc = md["short_description"] or "" if "description" in md and md["description"]: desc += "\n\n" + md["description"] desc += "\n\nCreated with Boxes.py (https://boxes.hackerspace-bamberg.de/)\n" desc += "Command line: %s\n" % md["cli"] desc += "Command line short: %s\n" % md["cli_short"] if md["url"]: desc += "Url: %s\n" % md["url"] desc += "Url short: %s\n" % md["url_short"] desc += "SettingsUrl: %s\n" % md["url"].replace("&render=1", "") desc += "SettingsUrl short: %s\n" % md["url_short"].replace("&render=1", "") self._addTag(w, 'dc:description', desc) # title self._addTag(root, "title", md["name"], True) # Add XML comment txt = """\n{name} - {short_description}\n""".format(**md) if md["description"]: txt += """\n\n{description}\n\n""".format(**md) txt += """\nCreated with Boxes.py (https://boxes.hackerspace-bamberg.de/)\n""" if not md["reproducible"]: txt += f"""Creation date: {creation_date}\n""" txt += "Command line (remove spaces between dashes): %s\n" % md["cli_short"] if md["url"]: txt += "Url: %s\n" % md["url"] txt += "Url short: %s\n" % md["url_short"] txt += "SettingsUrl: %s\n" % md["url"].replace("&render=1", "") txt += "SettingsUrl short: %s\n" % md["url_short"].replace("&render=1", "") m = ET.Comment(txt.replace("--", "- -").replace("--", "- -")) # ---- m.tail = '\n' root.insert(0, m) def finish(self, inner_corners="loop"): extents = self._adjust_coordinates() w = extents.width * self.scale h = extents.height * self.scale nsmap = { "dc": "http://purl.org/dc/elements/1.1/", "cc": "http://creativecommons.org/ns#", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "svg": "http://www.w3.org/2000/svg", "xlink": "http://www.w3.org/1999/xlink", "inkscape": "http://www.inkscape.org/namespaces/inkscape", } ET.register_namespace("", "http://www.w3.org/2000/svg") ET.register_namespace("xlink", "http://www.w3.org/1999/xlink") svg = ET.Element('svg', width=f"{w:.2f}mm", height=f"{h:.2f}mm", viewBox=f"0.0 0.0 {w:.2f} {h:.2f}", xmlns="http://www.w3.org/2000/svg") for name, value in nsmap.items(): svg.set(f"xmlns:{name}", value) svg.text = "\n" tree = ET.ElementTree(svg) self._add_metadata(svg) for i, part in enumerate(self.parts): if not part.pathes: continue g = ET.SubElement(svg, "g", id=f"p-{i}", style="fill:none;stroke-linecap:round;stroke-linejoin:round;") g.text = "\n " g.tail = "\n" for j, path in enumerate(part.pathes): p = [] x, y = 0, 0 start = None last = None path.faster_edges(inner_corners) for c in path.path: x0, y0 = x, y C, x, y = c[0:3] if C == "M": if start and points_equal(start[1], start[2], last[1], last[2]): p.append("Z") start = c p.append(f"M {x:.3f} {y:.3f}") elif C == "L": if abs(x - x0) < EPS: p.append(f"V {y:.3f}") elif abs(y - y0) < EPS: p.append(f"H {x:.3f}") else: p.append(f"L {x:.3f} {y:.3f}") elif C == "C": x1, y1, x2, y2 = c[3:] p.append( f"C {x1:.3f} {y1:.3f} {x2:.3f} {y2:.3f} {x:.3f} {y:.3f}" ) elif C == "T": m, text, params = c[3:] m = m * Affine.translation(0, -params['fs']) tm = " ".join(f"{m[i]:.3f}" for i in (0, 3, 1, 4, 2, 5)) font, bold, italic = params['ff'] fontweight = ("normal", "bold")[bool(bold)] fontstyle = ("normal", "italic")[bool(italic)] style = f"font-family: {font} ; font-weight: {fontweight}; font-style: {fontstyle}; fill: {rgb_to_svg_color(*params['rgb'])}" t = ET.SubElement(g, "text", #x=f"{x:.3f}", y=f"{y:.3f}", transform=f"matrix( {tm} )", style=style) t.text = text t.set("font-size", f"{params['fs']}px") t.set("text-anchor", params.get('align', 'left')) t.set("dominant-baseline", 'hanging') else: print("Unknown", c) last = c if start and start is not last and \ points_equal(start[1], start[2], last[1], last[2]): p.append("Z") color = ( random_svg_color() if RANDOMIZE_COLORS else rgb_to_svg_color(*path.params["rgb"]) ) if p and p[-1][0] == "M": p.pop() if p: # might be empty if only contains text t = ET.SubElement(g, "path", d=" ".join(p), stroke=color) t.set("stroke-width", f'{path.params["lw"]:.2f}') t.tail = "\n " t.tail = "\n" reorder_attributes(tree) f = io.BytesIO() tree.write(f, encoding="utf-8", xml_declaration=True, method="xml") f.seek(0) return f class PSSurface(Surface): scale = 72 / 25.4 # 72 dpi fonts = { ('serif', False, False) : 'Times-Roman', ('serif', False, True) : 'Times-Italic', ('serif', True, False) : 'Times-Bold', ('serif', True, True) : 'Times-BoldItalic', ('sans-serif', False, False) : 'Helvetica', ('sans-serif', False, True) : 'Helvetica-Oblique', ('sans-serif', True, False) : 'Helvetica-Bold', ('sans-serif', True, True) : 'Helvetica-BoldOblique', ('monospaced', False, False) : 'Courier', ('monospaced', False, True) : 'Courier-Oblique', ('monospaced', True, False) : 'Courier-Bold', ('monospaced', True, True) : 'Courier-BoldOblique', } def _metadata(self) -> str: md = self.metadata desc = "" desc += "%%Title: Boxes.py - {group} - {name}\n".format(**md) if not md["reproducible"]: desc += f'%%CreationDate: {md["creation_date"].strftime("%Y-%m-%d %H:%M:%S")}\n' desc += f'%%Keywords: boxes.py, laser, laser cutter\n' desc += f'%%Creator: {md.get("url") or md["cli"]}\n' desc += "%%CreatedBy: Boxes.py (https://boxes.hackerspace-bamberg.de/)\n" for line in (md["short_description"] or "").split("\n"): desc += "%% %s\n" % line desc += "%\n" if "description" in md and md["description"]: desc += "%\n" for line in md["description"].split("\n"): desc += "%% %s\n" % line desc += "%\n" desc += "%% Command line: %s\n" % md["cli"] desc += "%% Command line short: %s\n" % md["cli_short"] if md["url"]: desc += f'%%Url: {md["url"]}\n' desc += f'%%Url short: {md["url_short"]}\n' desc += f'%%SettingsUrl: {md["url"].replace("&render=1", "")}\n' desc += f'%%SettingsUrl short: {md["url_short"].replace("&render=1", "")}\n' return desc def finish(self, inner_corners="loop"): extents = self._adjust_coordinates() w = extents.width h = extents.height data = io.BytesIO() f = codecs.getwriter('utf-8')(data) f.write(f"""%!PS-Adobe-2.0 EPSF-2.0 %%BoundingBox: 0 0 {w:.0f} {h:.0f} {self._metadata()} %%EndComments 1 setlinecap 1 setlinejoin 0.0 0.0 0.0 setrgbcolor """) f.write(""" /ReEncode { % inFont outFont encoding | - /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def """) for font in self.fonts.values(): f.write(f"/{font} /{font}-Latin1 ISOLatin1Encoding ReEncode\n") # f.write(f"%%DocumentMedia: \d+x\d+mm ((\d+) (\d+)) 0 \(" # dwg['width']=f'{w:.2f}mm' # dwg['height']=f'{h:.2f}mm' for i, part in enumerate(self.parts): if not part.pathes: continue for j, path in enumerate(part.pathes): p = [] x, y = 0, 0 path.faster_edges(inner_corners) for c in path.path: x0, y0 = x, y C, x, y = c[0:3] if C == "M": p.append(f"{x:.3f} {y:.3f} moveto") elif C == "L": p.append(f"{x:.3f} {y:.3f} lineto") elif C == "C": x1, y1, x2, y2 = c[3:] p.append( f"{x1:.3f} {y1:.3f} {x2:.3f} {y2:.3f} {x:.3f} {y:.3f} curveto" ) elif C == "T": m, text, params = c[3:] tm = " ".join(f"{m[i]:.3f}" for i in (0, 3, 1, 4, 2, 5)) text = text.replace("(", r"\(").replace(")", r"\)") color = " ".join(f"{c:.2f}" for c in params["rgb"]) align = params.get('align', 'left') f.write(f"/{self.fonts[params['ff']]}-Latin1 findfont\n") f.write(f"{params['fs']} scalefont\n") f.write("setfont\n") #f.write(f"currentfont /Encoding ISOLatin1Encoding put\n") f.write(f"{color} setrgbcolor\n") f.write("matrix currentmatrix") # save current matrix f.write(f"[ {tm} ] concat\n") if align == "left": f.write(f"0.0\n") else: f.write(f"({text}) stringwidth pop ") if align == "middle": f.write(f"-0.5 mul\n") else: # end f.write(f"neg\n") # offset y by descender f.write("currentfont dup /FontBBox get 1 get \n") f.write("exch /FontMatrix get 3 get mul neg moveto \n") f.write(f"({text}) show\n") # text created by dup above f.write("setmatrix\n\n") # restore matrix else: print("Unknown", c) color = ( random_svg_color() if RANDOMIZE_COLORS else rgb_to_svg_color(*path.params["rgb"]) ) if p: # todo: might be empty since text is not implemented yet color = " ".join(f"{c:.2f}" for c in path.params["rgb"]) f.write("newpath\n") f.write("\n".join(p)) f.write("\n") f.write(f"{path.params['lw']} setlinewidth\n") f.write(f"{color} setrgbcolor\n") f.write("stroke\n\n") f.write( """ showpage %%Trailer %%EOF """ ) data.seek(0) return data class LBRN2Surface(Surface): invert_y = False dbg = False fonts = { 'serif' : 'Times New Roman', 'sans-serif' : 'Arial', 'monospaced' : 'Courier New' } lbrn2_colors=[ 0, # Colors.OUTER_CUT (BLACK) --> Lightburn C00 (black) 1, # Colors.INNER_CUT (BLUE) --> Lightburn C01 (blue) 3, # Colors.ETCHING (GREEN) --> Lightburn C02 (green) 6, # Colors.ETCHING_DEEP (CYAN) --> Lightburn C06 (cyan) 30, # Colors.ANNOTATIONS (RED) --> Lightburn T1 7, # Colors.OUTER_CUT (MAGENTA) --> Lightburn C07 (magenta) 4, # Colors.OUTER_CUT (YELLOW) --> Lightburn C04 (yellow) 8, # Colors.OUTER_CUT (WHITE) --> Lightburn C08 (grey) ] def finish(self, inner_corners="loop"): if self.dbg: print("LBRN2 save") extents = self._adjust_coordinates() w = extents.width * self.scale h = extents.height * self.scale svg = ET.Element('LightBurnProject', AppVersion="1.0.06", FormatVersion="1", MaterialHeight="0", MirrorX="False", MirrorY="False") svg.text = "\n" num = 0 txtOffset = {} tree = ET.ElementTree(svg) if self.dbg: print ("8", num) cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="3") # green layer (ETCHING) name = ET.SubElement(cs, "name", Value="Etch") priority = ET.SubElement(cs, "priority", Value="0") # is cut first cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="6") # cyan layer (ETCHING_DEEP) name = ET.SubElement(cs, "name", Value="Deep Etch") priority = ET.SubElement(cs, "priority", Value="1") # is cut second cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="7") # magenta layer (MAGENTA) name = ET.SubElement(cs, "name", Value="C07") priority = ET.SubElement(cs, "priority", Value="2") # is cut third cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="4") # yellow layer (YELLOW) name = ET.SubElement(cs, "name", Value="C04") priority = ET.SubElement(cs, "priority", Value="3") # is cut third cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="8") # grey layer (WHITE) name = ET.SubElement(cs, "name", Value="C08") priority = ET.SubElement(cs, "priority", Value="4") # is cut fourth cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="1") # blue layer (INNER_CUT) name = ET.SubElement(cs, "name", Value="Inner Cut") priority = ET.SubElement(cs, "priority", Value="5") # is cut fifth cs = ET.SubElement(svg, "CutSetting", Type="Cut") index = ET.SubElement(cs, "index", Value="0") # black layer (OUTER_CUT) name = ET.SubElement(cs, "name", Value="Outer Cut") priority = ET.SubElement(cs, "priority", Value="6") # is cut sixth cs = ET.SubElement(svg, "CutSetting", Type="Tool") index = ET.SubElement(cs, "index", Value="30") # T1 layer (ANNOTATIONS) name = ET.SubElement(cs, "name", Value="T1") # tool layer do not support names priority = ET.SubElement(cs, "priority", Value="7") # is not cut at all for i, part in enumerate(self.parts): if self.dbg: print ("7", num) if not part.pathes: continue gp = ET.SubElement(svg, "Shape", Type="Group") gp.text = "\n " gp.tail = "\n" children = ET.SubElement(gp, "Children") children.text = "\n " children.tail = "\n" for j, path in enumerate(part.pathes): myColor = self.lbrn2_colors[4*int(path.params["rgb"][0])+2*int(path.params["rgb"][1])+int(path.params["rgb"][2])] p = [] x, y = 0, 0 C = "" start = None last = None path.faster_edges(inner_corners) num = 0 cnt = 1 end = len(path.path) - 1 if self.dbg: for c in path.path: print ("6",num, c) num += 1 num = 0 c = path.path[num] C, x, y = c[0:3] if self.dbg: print("end:", end) while num < end or (C == "T" and num <= end): # len(path.path): if self.dbg: print("0", num) c = path.path[num] if self.dbg: print("first: ", num, c) C, x, y = c[0:3] if C == "M": if self.dbg: print ("1", num) sh = ET.SubElement(children, "Shape", Type="Path", CutIndex=str(myColor)) sh.text = "\n " sh.tail = "\n" vl = ET.SubElement(sh, "VertList") vl.text = f"V{x:.3f} {y:.3f}c0x1c1x1" vl.tail = "\n" pl = ET.SubElement(sh, "PrimList") pl.text = ""#f"L{cnt} {cnt+1}" pl.tail = "\n" start = c x0, y0 = x, y # do something with M done = False bspline = False while done == False and num < end: # len(path.path): num += 1 c = path.path[num] if self.dbg: print ("next: ",num, c) C, x, y = c[0:3] if C == "M": if start and points_equal(start[1], start[2], x0, y0): pl.text = "LineClosed" start = c cnt = 1 if self.dbg: print ("next, because M") done = True elif C == "T": if self.dbg: print ("next, because T") done = True else: if C == "L": vl.text+=(f"V{x:.3f} {y:.3f}c0x1c1x1") pl.text += f"L{cnt-1} {cnt}" cnt +=1 elif C == "C": x1, y1, x2, y2 = c[3:] if self.dbg: print ("C: ",x0, y0, x1, y1, x, y, x2, y2) vl.text+=(f"V{x0:.3f} {y0:.3f}c0x{(x1):.3f}c0y{(y1):.3f}c1x1V{x:.3f} {y:.3f}c0x1c1x{(x2):.3f}c1y{(y2):.3f}") pl.text += f"L{cnt-1} {cnt}B{cnt} {cnt+1}" cnt +=2 bspline = True else: print("unknown", c) if done == False: x0, y0 = x, y if start and points_equal(start[1], start[2], x0, y0): if bspline == False: pl.text = "LineClosed" start = c if self.dbg: print ("2", num) elif C == "T": cnt = 1 #C = "" if self.dbg: print ("3", num) m, text, params = c[3:] m = m * Affine.translation(0, params['fs']) if self.dbg: print ("T: ",x, y, c) num += 1 font, bold, italic = params['ff'] if params.get('font', 'Arial')=='Arial': f = self.fonts[font] else: f = params.get('font', 'Arial') fontColor = self.lbrn2_colors[4*int(params["rgb"][0])+2*int(params["rgb"][1])+int(params["rgb"][2])] #alignment can be left|middle|end if params.get('align', 'left')=='middle': hor = '1' else: if params.get('align', 'left')=='end': hor = '2' else: hor = '0' ver = 1 # vertical is always bottom, text is shifted in box class pos = text.find('%') offs = 0 if pos >- 1: if self.dbg: print ("p: ", pos, text[pos+1:pos+3]) texttype = '2' if self.dbg: print("l ", len(text[pos+1:pos+3])) if text[pos+1:pos+2].isnumeric(): if self.dbg: print ("t0", text[pos+1:pos+3]) if text[pos+1:pos+3].isnumeric() and len(text[pos+1:pos+3]) == 2: if self.dbg: print ("t1") if text[pos:pos+3] in txtOffset: if self.dbg: print ("t2") offs = txtOffset[text[pos:pos+3]] + 1 else: if self.dbg: print ("t3") offs = 0 txtOffset[text[pos:pos+3]] = offs else: if self.dbg: print ("t4") if text[pos:pos+2] in txtOffset: if self.dbg: print ("t5") offs = txtOffset[text[pos:pos+2]] + 1 else: offs = 0 if self.dbg: print ("t6") txtOffset[text[pos:pos+2]] = offs else: if self.dbg: print ("t7") texttype = '0' else: texttype = '0' if self.dbg: print ("t8") if self.dbg: print ("o: ", text, txtOffset, offs) if not text: if self.dbg: print ("T: text with empty string - ",x, y, c) else: sh = ET.SubElement(children, "Shape", Type="Text", CutIndex=str(fontColor), Font=f"{f}", H=f"{(params['fs']*1.75*0.6086434):.3f}", Str=f"{text}", Bold=f"{'1' if bold else '0'}", Italic=f"{'1' if italic else '0'}", Ah=f"{str(hor)}", Av=f"{str(ver)}", Eval=f"{texttype}", VariableOffset=f"{str(offs)}") # 1mm = 1.75 Lightburn H units sh.text = "\n " sh.tail = "\n" xf = ET.SubElement(sh, "XForm") xf.text = " ".join(f"{m[i]:.3f}" for i in (0, 3, 1, 4, 2, 5)) xf.tail = "\n" else: if self.dbg: print ("4", num) print ("next, because not M") num += 1 url = self.metadata["url"].replace("&render=1", "") # remove render argument to get web form again pl = ET.SubElement(svg, "Notes", ShowOnLoad="1", Notes="File created by Boxes.py script, programmed by Florian Festi.\nLightburn output by Klaus Steinhammer.\n\nURL with settings:\n" + str(url)) pl.text = "" pl.tail = "\n" if self.dbg: print ("5", num) f = io.BytesIO() tree.write(f, encoding="utf-8", xml_declaration=True, method="xml") f.seek(0) return f from random import random def random_svg_color(): r, g, b = random(), random(), random() return f"rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})" def rgb_to_svg_color(r, g, b): return f"rgb({r*255:.0f},{g*255:.0f},{b*255:.0f})" def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: # todo: deal with parallel line intersection / overlay return False, None, None d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div on_segments = ( (x + EPS >= min(line1[0][0], line1[1][0])), (x + EPS >= min(line2[0][0], line2[1][0])), (x - EPS <= max(line1[0][0], line1[1][0])), (x - EPS <= max(line2[0][0], line2[1][0])), (y + EPS >= min(line1[0][1], line1[1][1])), (y + EPS >= min(line2[0][1], line2[1][1])), (y - EPS <= max(line1[0][1], line1[1][1])), (y - EPS <= max(line2[0][1], line2[1][1])), ) return min(on_segments), x, y
39,290
Python
.py
885
29.868927
360
0.444816
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,534
parts.py
florianfesti_boxes/boxes/parts.py
from __future__ import annotations from math import * from typing import Any, Callable from boxes import vectors def arcOnCircle(spanning_angle: float, outgoing_angle: float, r: float = 1.0) -> tuple[float, float]: angle = spanning_angle + 2 * outgoing_angle radius = r * sin(radians(0.5 * spanning_angle)) / sin(radians(180 - outgoing_angle - 0.5 * spanning_angle)) return angle, abs(radius) class Parts: def __init__(self, boxes) -> None: self.boxes = boxes """ def roundKnob(self, diameter: float, n: int = 20, callback: Callable | None = None, move: str = ""): size = diameter+diameter/n if self.move(size, size, move, before=True): return self.moveTo(size/2, size/2) self.cc(callback, None, 0, 0) self.move(size, size, move) """ def __getattr__(self, name: str) -> Any: return getattr(self.boxes, name) def disc(self, diameter: float, hole: float = 0, dwidth: float = 1.0, callback: Callable | None = None, move: str = "", label: str = "") -> None: """Simple disc :param diameter: diameter of the disc :param hole: (Default value = 0) :param callback: (Default value = None) called in the center :param dwidth: (Default value = 1) flatten on right side to given ratio :param move: (Default value = "") :param label: (Default value = "") """ size = diameter r = diameter / 2.0 if self.move(size*dwidth, size, move, before=True, label=label): return self.moveTo(size / 2, size / 2) if hole: self.hole(0, 0, hole / 2) self.cc(callback, None, 0, 0) if dwidth == 1.0: self.moveTo(r + self.burn, 0, 90) self.corner(360, r, tabs=6) else: w = (2.0 * dwidth - 1) * r a = degrees(acos(w / r)) self.moveTo(0, 0, -a) self.moveTo(r, 0, -90) self.corner(-360+2*a, r) self.corner(-a) self.edge(2*r*sin(radians(a))) self.move(size*dwidth, size, move, label=label) def wavyKnob(self, diameter: float, n: int = 20, angle: float = 45, hole: float = 0, callback: Callable | None = None, move: str = "") -> None: """Disc with a wavy edge to be easier to be gripped :param diameter: diameter of the knob :param n: (Default value = 20) number of waves :param angle: (Default value = 45) maximum angle of the wave :param hole: (Default value = 0) :param callback: (Default value = None) called in the center :param move: (Default value = "") """ if n < 2: return size = diameter + pi * diameter / n if self.move(size, size, move, before=True): return self.moveTo(size / 2, size / 2) self.cc(callback, None, 0, 0) if hole: self.hole(0, 0, hole / 2) self.moveTo(diameter / 2, 0, 90-angle) a, r = arcOnCircle(360. / n / 2, angle, diameter / 2) a2, r2 = arcOnCircle(360. / n / 2, -angle, diameter / 2) for i in range(n): self.boxes.corner(a, r, tabs=(i % max(1, (n+1) // 6) == 0)) self.boxes.corner(a2, r2) self.move(size, size, move) def concaveKnob(self, diameter: float, n: int = 3, rounded: float = 0.2, angle: float = 70, hole: float = 0, callback: Callable | None = None, move: str = "") -> None: """Knob with dents to be easier to be gripped :param diameter: diameter of the knob :param n: (Default value = 3) number of dents :param rounded: (Default value = 0.2) proportion of circumference remaining :param angle: (Default value = 70) angle the dents meet the circumference :param hole: (Default value = 0) :param callback: (Default value = None) called in the center :param move: (Default value = "") """ size = diameter if n < 2: return if self.move(size, size, move, before=True): return self.moveTo(size / 2, size / 2) if hole: self.hole(0, 0, hole / 2) self.cc(callback, None, 0, 0) self.moveTo(diameter / 2, 0, 90 + angle) a, r = arcOnCircle(360. / n * (1 - rounded), -angle, diameter / 2) if abs(a) < 0.01: # avoid trying to make a straight line as an arc a, r = arcOnCircle(360. / n * (1 - rounded), -angle - 0.01, diameter / 2) for i in range(n): self.boxes.corner(a, r) self.corner(angle) self.corner(360. / n * rounded, diameter / 2, tabs=(i % max(1, (n+1) // 6) == 0)) self.corner(angle) self.move(size, size, move) def ringSegment(self, r_outside: float, r_inside: float, angle: float, n: int = 1, move: str = "") -> None: """Ring Segment :param r_outside: outer radius :param r_inside: inner radius :param angle: angle the segment is spanning :param n: (Default value = 1) number of segments :param move: (Default value = "") """ space = 360 * self.spacing / r_inside / 2 / pi nc = int(min(n, 360 / (angle+space))) while n > 0: if self.move(2*r_outside, 2*r_outside, move, True): return self.moveTo(0, r_outside, -90) for i in range(nc): self.polyline( 0, (angle, r_outside), 0, 90, (r_outside-r_inside, 2), 90, 0, (-angle, r_inside), 0, 90, (r_outside-r_inside, 2), 90) x, y = vectors.circlepoint(r_outside, radians(angle+space)) self.moveTo(y, r_outside-x, angle+space) n -=1 if n == 0: break self.move(2*r_outside, 2*r_outside, move)
5,952
Python
.py
131
35.167939
149
0.549542
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,535
qrcode_factory.py
florianfesti_boxes/boxes/qrcode_factory.py
from decimal import Decimal import qrcode.image.base import qrcode.image.svg class BoxesQrCodeFactory(qrcode.image.base.BaseImage): """ SVG image builder Creates a QR-code image as a SVG document fragment. """ _SVG_namespace = "http://www.w3.org/2000/svg" kind = "SVG" allowed_kinds = ("SVG",) def __init__(self, *args, ctx=None, x=0, y=0, **kwargs): super().__init__(*args, **kwargs) self.ctx = ctx self.x, self.y = x, y # Save the unit size, for example the default box_size of 10 is '1mm'. self.unit_size = self.units(self.box_size) def drawrect(self, row, col): self.ctx.rectangle(*self._rect(row, col)) self._img.append(self._rect(row, col)) def units(self, pixels, text=True): """ A box_size of 10 (default) equals 1mm. """ units = Decimal(pixels) / 10 if not text: return units return '%smm' % units def save(self, stream, kind=None): self.check_kind(kind=kind) self._write(stream) def to_string(self): return f"".join(self._img) def new_image(self, **kwargs): self._img = [] return self._img def _rect(self, row, col): size = self.box_size / 10 x = self.x + (row + self.border) * size y = self.y + (col + self.border) * size return x, y, size, size def _write(self, stream): stream.write("".join(self._img)) if __name__=="__main__": import qrcode import qrcode.image q = qrcode.QRCode(image_factory=BoxesQrCodeFactory, box_size=10) q.add_data('hello') ctx = "a context" img = q.make_image(ctx="a context") print(img.to_string())
1,733
Python
.py
51
27.176471
78
0.592216
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,536
extents.py
florianfesti_boxes/boxes/extents.py
class Extents: __slots__ = "xmin ymin xmax ymax".split() def __init__(self, xmin: float = float('inf'), ymin: float = float('inf'), xmax: float = float('-inf'), ymax: float = float('-inf')) -> None: self.xmin = xmin self.ymin = ymin self.xmax = xmax self.ymax = ymax def add(self, x: float, y: float) -> None: self.xmin = min(self.xmin, x) self.xmax = max(self.xmax, x) self.ymin = min(self.ymin, y) self.ymax = max(self.ymax, y) def extend(self, l) -> None: for x, y in l: self.add(x, y) def __add__(self, extent): # todo: why can this happen? if extent == 0: return Extents(self.xmin, self.ymin, self.xmax, self.ymax) return Extents( min(self.xmin, extent.xmin), min(self.ymin, extent.ymin), max(self.xmax, extent.xmax), max(self.ymax, extent.ymax) ) def __radd__(self, extent): if extent == 0: return Extents(self.xmin, self.ymin, self.xmax, self.ymax) return self.__add__(extent) @property def width(self) -> float: return self.xmax - self.xmin @property def height(self) -> float: return self.ymax - self.ymin def __repr__(self) -> str: return f'Extents ({self.xmin},{self.ymin})-({self.xmax},{self.ymax})'
1,368
Python
.py
35
30.771429
145
0.56
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,537
gears.py
florianfesti_boxes/boxes/gears.py
# Copyright (C) 2007 Aaron Spike (aaron @ ekips.org) # Copyright (C) 2007 Tavmjong Bah (tavmjong @ free.fr) # Copyright (C) https://cnc-club.ru/forum/viewtopic.php?f=33&t=434&p=2594#p2500 # Copyright (C) 2014 Jürgen Weigert (juewei@fabmail.org) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # 2014-03-20 jw@suse.de 0.2 Option --accuracy=0 for automatic added. # 2014-03-21 sent upstream: https://bugs.launchpad.net/inkscape/+bug/1295641 # 2014-03-21 jw@suse.de 0.3 Fixed center of rotation for gears with odd number of teeth. # 2014-04-04 juewei 0.7 Revamped calc_unit_factor(). # 2014-04-05 juewei 0.7a Correctly positioned rack gear. # The geometry above the meshing line is wrong. # 2014-04-06 juewei 0.7b Undercut detection added. Reference: # https://web.archive.org/web/20140801105942/https://nptel.ac.in/courses/IIT-MADRAS/Machine_Design_II/pdf/2_2.pdf # Manually merged https://github.com/jnweiger/inkscape-gears-dev/pull/15 # 2014-04-07 juewei 0.7c Manually merged https://github.com/jnweiger/inkscape-gears-dev/pull/17 # 2014-04-09 juewei 0.8 Fixed https://github.com/jnweiger/inkscape-gears-dev/issues/19 # Ring gears are ready for production now. Thanks neon22 for driving this. # Profile shift implemented (Advanced Tab), fixing # https://github.com/jnweiger/inkscape-gears-dev/issues/9 # 2015-05-29 juewei 0.9 ported to inkscape 0.91 # AttributeError: 'module' object inkex has no attribute 'uutounit # Fixed https://github.com/jnweiger/inkscape-gears-dev from math import acos, asin, ceil, cos, degrees, pi, radians, sin, sqrt, tan from os import devnull # for debugging two_pi = 2 * pi import argparse from boxes.vectors import vdiff, vlength __version__ = '0.9' def linspace(a,b,n): """ return list of linear interp of a to b in n steps - if a and b are ints - you'll get an int result. - n must be an integer """ return [a+x*(b-a)/(n-1) for x in range(0,n)] def involute_intersect_angle(Rb, R): Rb, R = float(Rb), float(R) return (sqrt(R**2 - Rb**2) / (Rb)) - (acos(Rb / R)) def point_on_circle(radius, angle): """ return xy coord of the point at distance radius from origin at angle """ x = radius * cos(angle) y = radius * sin(angle) return (x, y) ### Undercut support functions def undercut_min_teeth(pitch_angle, k=1.0): """ computes the minimum tooth count for a spur gear so that no undercut with the given pitch_angle (in deg) and an addendum = k * metric_module, where 0 < k < 1 Note: The return value should be rounded upwards for perfect safety. E.g. min_teeth = int(math.ceil(undercut_min_teeth(20.0))) # 18, not 17 """ x = max(sin(radians(pitch_angle)), 0.01) return 2*k /(x*x) def undercut_max_k(teeth, pitch_angle=20.0): """ computes the maximum k value for a given teeth count and pitch_angle so that no undercut occurs. """ x = max(sin(radians(pitch_angle)), 0.01) return 0.5 * teeth * x * x def undercut_min_angle(teeth, k=1.0): """ computes the minimum pitch angle, to that the given teeth count (and profile shift) cause no undercut. """ return degrees(asin(min(0.856, sqrt(2.0*k/teeth)))) # max 59.9 deg def have_undercut(teeth, pitch_angle=20.0, k=1.0): """ returns true if the specified number of teeth would cause an undercut. """ return (teeth < undercut_min_teeth(pitch_angle, k)) ## gather all basic gear calculations in one place def gear_calculations(num_teeth, circular_pitch, pressure_angle, clearance=0, ring_gear=False, profile_shift=0.): """ Put base calcs for spur/ring gears in one place. - negative profile shifting helps against undercut. """ diametral_pitch = pi / circular_pitch pitch_diameter = num_teeth / diametral_pitch pitch_radius = pitch_diameter / 2.0 addendum = 1 / diametral_pitch dedendum = addendum dedendum *= 1+profile_shift addendum *= 1-profile_shift if ring_gear: addendum = addendum + clearance # our method else: dedendum = dedendum + clearance # our method base_radius = pitch_diameter * cos(radians(pressure_angle)) / 2.0 outer_radius = pitch_radius + addendum root_radius = pitch_radius - dedendum # Tooth thickness: Tooth width along pitch circle. tooth_thickness = ( pi * pitch_diameter ) / ( 2.0 * num_teeth ) return (pitch_radius, base_radius, addendum, dedendum, outer_radius, root_radius, tooth_thickness ) def generate_rack_points(tooth_count, pitch, addendum, pressure_angle, base_height, tab_length, clearance=0, draw_guides=False): """ Return path (suitable for svg) of the Rack gear. - rack gear uses straight sides - involute on a circle of infinite radius is a simple linear ramp - the meshing circle touches at y = 0, - the highest elevation of the teeth is at y = +addendum - the lowest elevation of the teeth is at y = -addendum-clearance - the base_height extends downwards from the lowest elevation. - we generate this middle tooth exactly centered on the y=0 line. (one extra tooth on the right hand side, if number of teeth is even) """ spacing = 0.5 * pitch # rolling one pitch distance on the spur gear pitch_diameter. # roughly center rack in drawing, exact position is so that it meshes # nicely with the spur gear. # -0.5*spacing has a gap in the center. # +0.5*spacing has a tooth in the center. if tab_length <= 0.0: tab_length = 1E-8 tas = tan(radians(pressure_angle)) * addendum tasc = tan(radians(pressure_angle)) * (addendum+clearance) base_top = addendum+clearance base_bot = addendum+clearance+base_height x_lhs = -pitch * 0.5*tooth_count - tab_length # Start with base tab on LHS points = [] # make list of points points.append((x_lhs, base_bot)) points.append((x_lhs, base_top)) x = x_lhs + tab_length+tasc # An involute on a circle of infinite radius is a simple linear ramp. # We need to add curve at bottom and use clearance. for i in range(tooth_count): # move along path, generating the next 'tooth' # pitch line is at y=0. the left edge hits the pitch line at x points.append((x-tasc, base_top)) points.append((x+tas, -addendum)) points.append((x+spacing-tas, -addendum)) points.append((x+spacing+tasc, base_top)) x += pitch # add base on RHS x_rhs = x - tasc + tab_length points.append((x_rhs, base_top)) points.append((x_rhs, base_bot)) # We don't close the path here. Caller does it. # points.append((x_lhs, base_bot)) # Draw line representing the pitch circle of infinite diameter guide_path = None p = [] if draw_guides: p.append( (x_lhs + 0.5 * tab_length, 0) ) p.append( (x_rhs - 0.5 * tab_length, 0) ) return (points, p) def generate_spur_points(teeth, base_radius, pitch_radius, outer_radius, root_radius, accuracy_involute, accuracy_circular): """ given a set of core gear params - generate the svg path for the gear """ half_thick_angle = two_pi / (4.0 * teeth ) #?? = pi / (2.0 * teeth) pitch_to_base_angle = involute_intersect_angle( base_radius, pitch_radius ) pitch_to_outer_angle = involute_intersect_angle( base_radius, outer_radius ) - pitch_to_base_angle start_involute_radius = max(base_radius, root_radius) radii = linspace(start_involute_radius, outer_radius, accuracy_involute) angles = [involute_intersect_angle(base_radius, r) for r in radii] centers = [(x * two_pi / float( teeth) ) for x in range( teeth ) ] points = [] for c in centers: # Angles pitch1 = c - half_thick_angle base1 = pitch1 - pitch_to_base_angle offsetangles1 = [ base1 + x for x in angles] points1 = [ point_on_circle( radii[i], offsetangles1[i]) for i in range(0,len(radii)) ] pitch2 = c + half_thick_angle base2 = pitch2 + pitch_to_base_angle offsetangles2 = [ base2 - x for x in angles] points2 = [ point_on_circle( radii[i], offsetangles2[i]) for i in range(0,len(radii)) ] points_on_outer_radius = [ point_on_circle(outer_radius, x) for x in linspace(offsetangles1[-1], offsetangles2[-1], accuracy_circular) ] if root_radius > base_radius: pitch_to_root_angle = pitch_to_base_angle - involute_intersect_angle(base_radius, root_radius ) root1 = pitch1 - pitch_to_root_angle root2 = pitch2 + pitch_to_root_angle points_on_root = [point_on_circle (root_radius, x) for x in linspace(root2, root1+(two_pi/float(teeth)), accuracy_circular) ] p_tmp = points1 + points_on_outer_radius[1:-1] + points2[::-1] + points_on_root[1:-1] # [::-1] reverses list; [1:-1] removes first and last element else: points_on_root = [point_on_circle (root_radius, x) for x in linspace(base2, base1+(two_pi/float(teeth)), accuracy_circular) ] p_tmp = points1 + points_on_outer_radius[1:-1] + points2[::-1] + points_on_root # [::-1] reverses list points.extend( p_tmp ) return (points) def inkbool(val): return val not in ("False", False, "0", 0, "None", None) class OptionParser(argparse.ArgumentParser): types = { "int" : int, "float" : float, "string" : str, "inkbool" : inkbool, } def add_option(self, short, long_, **kw): kw["type"] = self.types[kw["type"]] names = [] if short: names.append("-" + short.replace("-", "_")[1:]) if long_: names.append("--" + long_.replace("-", "_")[2:]) self.add_argument(*names, **kw) class Gears(): def __init__(self, boxes, **kw) -> None: # an alternate way to get debug info: # could use inkex.debug(string) instead... #try: # self.tty = open("/dev/tty", 'w') #except: # self.tty = open(devnull, 'w') # '/dev/null' for POSIX, 'nul' for Windows. # # print >>self.tty, "gears-dev " + __version__ self.boxes = boxes self.OptionParser = OptionParser() self.OptionParser.add_option("-t", "--teeth", action="store", type="int", dest="teeth", default=24, help="Number of teeth") self.OptionParser.add_option("-s", "--system", action="store", type="string", dest="system", default='MM', help="Select system: 'CP' (Cyclic Pitch (default)), 'DP' (Diametral Pitch), 'MM' (Metric Module)") self.OptionParser.add_option("-d", "--dimension", action="store", type="float", dest="dimension", default=1.0, help="Tooth size, depending on system (which defaults to CP)") self.OptionParser.add_option("-a", "--angle", action="store", type="float", dest="angle", default=20.0, help="Pressure Angle (common values: 14.5, 20, 25 degrees)") self.OptionParser.add_option("-p", "--profile-shift", action="store", type="float", dest="profile_shift", default=20.0, help="Profile shift [in percent of the module]. Negative values help against undercut") self.OptionParser.add_option("-u", "--units", action="store", type="string", dest="units", default='mm', help="Units this dialog is using") self.OptionParser.add_option("-A", "--accuracy", action="store", type="int", dest="accuracy", default=0, help="Accuracy of involute: automatic: 5..20 (default), best: 20(default), medium 10, low: 5; good accuracy is important with a low tooth count") # Clearance: Radial distance between top of tooth on one gear to bottom of gap on another. self.OptionParser.add_option("", "--clearance", action="store", type="float", dest="clearance", default=0.0, help="Clearance between bottom of gap of this gear and top of tooth of another") self.OptionParser.add_option("", "--annotation", action="store", type="inkbool", dest="annotation", default=False, help="Draw annotation text") self.OptionParser.add_option("-i", "--internal-ring", action="store", type="inkbool", dest="internal_ring", default=False, help="Ring (or Internal) gear style (default: normal spur gear)") self.OptionParser.add_option("", "--mount-hole", action="store", type="float", dest="mount_hole", default=0., help="Mount hole diameter") self.OptionParser.add_option("", "--mount-diameter", action="store", type="float", dest="mount_diameter", default=15, help="Mount support diameter") self.OptionParser.add_option("", "--spoke-count", action="store", type="int", dest="spoke_count", default=3, help="Spokes count") self.OptionParser.add_option("", "--spoke-width", action="store", type="float", dest="spoke_width", default=5, help="Spoke width") self.OptionParser.add_option("", "--holes-rounding", action="store", type="float", dest="holes_rounding", default=5, help="Holes rounding") self.OptionParser.add_option("", "--active-tab", action="store", type="string", dest="active_tab", default='', help="Active tab. Not used now.") self.OptionParser.add_option("-x", "--centercross", action="store", type="inkbool", dest="centercross", default=False, help="Draw cross in center") self.OptionParser.add_option("-c", "--pitchcircle", action="store", type="inkbool", dest="pitchcircle", default=False, help="Draw pitch circle (for mating)") self.OptionParser.add_option("-r", "--draw-rack", action="store", type="inkbool", dest="drawrack", default=False, help="Draw rack gear instead of spur gear") self.OptionParser.add_option("", "--rack-teeth-length", action="store", type="int", dest="teeth_length", default=12, help="Length (in teeth) of rack") self.OptionParser.add_option("", "--rack-base-height", action="store", type="float", dest="base_height", default=8, help="Height of base of rack") self.OptionParser.add_option("", "--rack-base-tab", action="store", type="float", dest="base_tab", default=14, help="Length of tabs on ends of rack") self.OptionParser.add_option("", "--undercut-alert", action="store", type="inkbool", dest="undercut_alert", default=False, help="Let the user confirm a warning dialog if undercut occurs. This dialog also shows helpful hints against undercut") def calc_circular_pitch(self): """We use math based on circular pitch.""" dimension = self.options.dimension if self.options.system == 'CP': # circular pitch circular_pitch = dimension * 25.4 elif self.options.system == 'DP': # diametral pitch circular_pitch = pi * 25.4 / dimension elif self.options.system == 'MM': # module (metric) circular_pitch = pi * dimension else: raise ValueError("unknown system '%s', try CP, DP, MM" % self.options.system) # circular_pitch defines the size in mm return circular_pitch def generate_spokes(self, root_radius, spoke_width, spokes, mount_radius, mount_hole, unit_factor, unit_label): """ given a set of constraints - generate the svg path for the gear spokes - lies between mount_radius (inner hole) and root_radius (bottom of the teeth) - spoke width also defines the spacing at the root_radius - mount_radius is adjusted so that spokes fit if there is room - if no room (collision) then spokes not drawn """ if not spokes: return [] # Spokes collision = False # assume we draw spokes messages = [] # messages to send back about changes. spoke_holes = [] r_outer = root_radius - spoke_width try: spoke_count = spokes spokes = [i*2*pi/spokes for i in range(spoke_count)] except TypeError: spoke_count = len(spokes) spokes = [radians(a) for a in spokes] spokes.append(spokes[0]+two_pi) # checks for collision with spokes # check for mount hole collision with inner spokes if mount_radius <= mount_hole/2: adj_factor = (r_outer - mount_hole/2) / 5 if adj_factor < 0.1: # not enough reasonable room collision = True else: mount_radius = mount_hole/2 + adj_factor # small fix messages.append(f"Mount support too small. Auto increased to {mount_radius/unit_factor*2:2.2f}{unit_label}.") # then check to see if cross-over on spoke width for i in range(spoke_count): angle = spokes[i]-spokes[i-1] if spoke_width >= angle * mount_radius: adj_factor = 1.2 # wrong value. it's probably one of the points distances calculated below mount_radius += adj_factor messages.append(f"Too many spokes. Increased Mount support by {adj_factor/unit_factor:2.3f}{unit_label}") # check for collision with outer rim if r_outer <= mount_radius: # not enough room to draw spokes so cancel collision = True if collision: # don't draw spokes if no room. messages.append("Not enough room for Spokes. Decrease Spoke width.") else: # draw spokes for i in range(spoke_count): self.boxes.ctx.save() start_a, end_a = spokes[i], spokes[i+1] # inner circle around mount asin_factor = spoke_width/mount_radius/2 # check if need to clamp radius asin_factor = max(-1.0, min(1.0, asin_factor)) # no longer needed - resized above a = asin(asin_factor) # is inner circle too small asin_factor = spoke_width/r_outer/2 # check if need to clamp radius asin_factor = max(-1.0, min(1.0, asin_factor)) # no longer needed - resized above a2 = asin(asin_factor) l = vlength(vdiff(point_on_circle(mount_radius, start_a + a), point_on_circle(r_outer, start_a + a2))) self.boxes.moveTo(*point_on_circle(mount_radius, start_a + a), degrees=degrees(start_a)) self.boxes.polyline( l, +90+degrees(a2), 0, (degrees(end_a-start_a-2*a2), r_outer), 0, +90+degrees(a2), l, 90-degrees(a), 0, (-degrees(end_a-start_a-2*a), mount_radius), 0, 90+degrees(a2), 0 ) self.boxes.ctx.restore() return messages def sizes(self, **kw): self.options = self.OptionParser.parse_args([f"--{name}={value}" for name, value in kw.items()]) # Pitch (circular pitch): Length of the arc from one tooth to the next) # Pitch diameter: Diameter of pitch circle. pitch = self.calc_circular_pitch() if self.options.drawrack: base_height = self.options.base_height * unit_factor tab_width = self.options.base_tab * unit_factor tooth_count = self.options.teeth_length width = tooth_count * pitch + 2*tab_width height = base_height+ 2* addendum return 0, width, height teeth = self.options.teeth # Angle of tangent to tooth at circular pitch wrt radial line. angle = self.options.angle # Clearance: Radial distance between top of tooth on one gear to # bottom of gap on another. clearance = self.options.clearance # * unit_factor # Replace section below with this call to get the combined gear_calculations() above (pitch_radius, base_radius, addendum, dedendum, outer_radius, root_radius, tooth) = gear_calculations(teeth, pitch, angle, clearance, self.options.internal_ring, self.options.profile_shift*0.01) if self.options.internal_ring: outer_radius += self.options.spoke_width return pitch_radius, 2*outer_radius, 2*outer_radius def gearCarrier(self, r, spoke_width, positions, mount_radius, mount_hole, circle=True, callback=None, move=None): width = 2*r+spoke_width if self.boxes.move(width, width, move, before=True): return try: positions = [i*360/positions for i in range(positions)] except TypeError: pass self.boxes.ctx.save() self.boxes.moveTo(width/2.0, width/2.0) if callback: self.boxes.cc(callback, None) self.generate_spokes(r+0.5*spoke_width, spoke_width, positions, mount_radius, mount_hole, 1, "") self.boxes.hole(0, 0, mount_hole) for angle in positions: self.boxes.ctx.save() self.boxes.moveTo(0, 0, angle) self.boxes.hole(r, 0, mount_hole) self.boxes.ctx.restore() self.boxes.moveTo(r+0.5*spoke_width+self.boxes.burn, 0, 90) self.boxes.corner(360, r+0.5*spoke_width) self.boxes.ctx.restore() self.boxes.move(width, width, move) def __call__(self, teeth_only=False, move="", callback=None, **kw): """ Calculate Gear factors from inputs. - Make list of radii, angles, and centers for each tooth and iterate through them - Turn on other visual features e.g. cross, rack, annotations, etc """ self.options = self.OptionParser.parse_args([f"--{name}={value}" for name, value in kw.items()]) warnings = [] # list of extra messages to be shown in annotations # calculate unit factor for units defined in dialog. unit_factor = 1 # User defined options teeth = self.options.teeth # Angle of tangent to tooth at circular pitch wrt radial line. angle = self.options.angle # Clearance: Radial distance between top of tooth on one gear to # bottom of gap on another. clearance = self.options.clearance * unit_factor mount_hole = self.options.mount_hole * unit_factor # for spokes mount_radius = self.options.mount_diameter * 0.5 * unit_factor spoke_count = self.options.spoke_count spoke_width = self.options.spoke_width * unit_factor holes_rounding = self.options.holes_rounding * unit_factor # unused # visible guide lines centercross = self.options.centercross # draw center or not (boolean) pitchcircle = self.options.pitchcircle # draw pitch circle or not (boolean) # Accuracy of teeth curves accuracy_involute = 20 # Number of points of the involute curve accuracy_circular = 9 # Number of points on circular parts if self.options.accuracy is not None: if self.options.accuracy == 0: # automatic if teeth < 10: accuracy_involute = 20 elif teeth < 30: accuracy_involute = 12 else: accuracy_involute = 6 else: accuracy_involute = self.options.accuracy accuracy_circular = max(3, int(accuracy_involute/2) - 1) # never less than three # print >>self.tty, "accuracy_circular=%s accuracy_involute=%s" % (accuracy_circular, accuracy_involute) # Pitch (circular pitch): Length of the arc from one tooth to the next) # Pitch diameter: Diameter of pitch circle. pitch = self.calc_circular_pitch() # Replace section below with this call to get the combined gear_calculations() above (pitch_radius, base_radius, addendum, dedendum, outer_radius, root_radius, tooth) = gear_calculations(teeth, pitch, angle, clearance, self.options.internal_ring, self.options.profile_shift*0.01) b = self.boxes.burn # Add Rack (instead) if self.options.drawrack: base_height = self.options.base_height * unit_factor tab_width = self.options.base_tab * unit_factor tooth_count = self.options.teeth_length (points, guide_points) = generate_rack_points(tooth_count, pitch, addendum, angle, base_height, tab_width, clearance, pitchcircle) width = tooth_count * pitch + 2 * tab_width height = base_height + 2 * addendum if self.boxes.move(width, height, move, before=True): return self.boxes.cc(callback, None) self.boxes.moveTo(width/2.0, base_height+addendum, -180) if base_height < 0: points = points[1:-1] self.boxes.drawPoints(points, close=base_height >= 0) self.boxes.drawPoints(guide_points, kerfdir=0) self.boxes.move(width, height, move) return # Move only width = height = 2 * outer_radius if self.options.internal_ring: width = height = width + 2 * self.options.spoke_width if not teeth_only and self.boxes.move(width, height, move, before=True): return # Detect Undercut of teeth ## undercut = int(ceil(undercut_min_teeth( angle ))) ## needs_undercut = teeth < undercut #? no longer needed ? if have_undercut(teeth, angle, 1.0): min_teeth = int(ceil(undercut_min_teeth(angle, 1.0))) min_angle = undercut_min_angle(teeth, 1.0) + .1 max_k = undercut_max_k(teeth, angle) msg = "Undercut Warning: This gear (%d teeth) will not work well.\nTry tooth count of %d or more,\nor a pressure angle of %.1f [deg] or more,\nor try a profile shift of %d %%.\nOr other decent combinations." % (teeth, min_teeth, min_angle, int(100.*max_k)-100.) # alas annotation cannot handle the degree symbol. Also it ignore newlines. # so split and make a list warnings.extend(msg.split("\n")) # All base calcs done. Start building gear points = generate_spur_points(teeth, base_radius, pitch_radius, outer_radius, root_radius, accuracy_involute, accuracy_circular) if not teeth_only: self.boxes.moveTo(width/2, height/2) self.boxes.cc(callback, None, 0, 0) self.boxes.drawPoints(points) # Spokes if not teeth_only and not self.options.internal_ring: # only draw internals if spur gear msg = self.generate_spokes(root_radius, spoke_width, spoke_count, mount_radius, mount_hole, unit_factor, self.options.units) warnings.extend(msg) # Draw mount hole # A : rx,ry x-axis-rotation, large-arch-flag, sweepflag x,y r = mount_hole / 2 self.boxes.hole(0, 0, r) elif not teeth_only: # it's a ring gear # which only has an outer ring where width = spoke width r = outer_radius + spoke_width + self.boxes.burn self.boxes.ctx.save() self.boxes.moveTo(r, 0) self.boxes.ctx.arc(-r, 0, r, 0, 2*pi) self.boxes.ctx.restore() # Add center if centercross: cs = pitch / 3.0 # centercross length self.boxes.ctx.save() self.boxes.ctx.move_to(-cs, 0) self.boxes.ctx.line_to(+cs, 0) self.boxes.ctx.move_to(0, -cs) self.boxes.ctx.line_to(0, +cs) self.boxes.ctx.restore() # Add pitch circle (for mating) if pitchcircle: self.boxes.hole(0, 0, pitch_radius) # Add Annotations (above) if self.options.annotation: outer_dia = outer_radius * 2 if self.options.internal_ring: outer_dia += 2 * spoke_width notes = [] notes.extend(warnings) #notes.append('Document (%s) scale conversion = %2.4f' % (self.document.getroot().find(inkex.addNS('namedview', 'sodipodi')).get(inkex.addNS('document-units', 'inkscape')), unit_factor)) notes.extend(['Teeth: %d CP: %2.4f(%s) ' % (teeth, pitch / unit_factor, self.options.units), f'DP: {25.4 * pi / pitch:2.3f} Module: {pitch:2.4f}(mm)', 'Pressure Angle: %2.2f degrees' % (angle), f'Pitch diameter: {pitch_radius * 2 / unit_factor:2.3f} {self.options.units}', f'Outer diameter: {outer_dia / unit_factor:2.3f} {self.options.units}', f'Base diameter: {base_radius * 2 / unit_factor:2.3f} {self.options.units}'#, #'Addendum: %2.4f %s' % (addendum / unit_factor, self.options.units), #'Dedendum: %2.4f %s' % (dedendum / unit_factor, self.options.units) ]) # text height relative to gear size. # ranges from 10 to 22 over outer radius size 60 to 360 text_height = max(10, min(10+(outer_dia-60)/24, 22)) # position above y = - outer_radius - (len(notes)+1) * text_height * 1.2 for note in notes: self.boxes.text(note, -outer_radius, y) y += text_height * 1.2 if not teeth_only: self.boxes.move(width, height, move)
32,755
Python
.py
594
42.159933
273
0.575329
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,538
__init__.py
florianfesti_boxes/boxes/__init__.py
#!/usr/bin/env python3 # Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import annotations import argparse import copy import datetime import gettext import math import random import re import sys from argparse import ArgumentParser from contextlib import contextmanager from functools import wraps from shlex import quote from typing import Any from xml.sax.saxutils import quoteattr import qrcode from shapely.geometry import * from shapely.ops import split from boxes import edges, formats, gears, parts, pulley from boxes.Color import * from boxes.qrcode_factory import BoxesQrCodeFactory from boxes.vectors import kerf ### Helpers def dist(dx, dy): """ Return distance :param dx: delta x :param dy: delay y """ return (dx * dx + dy * dy) ** 0.5 def restore(func): """ Wrapper: Restore coordinates after function :param func: function to wrap """ @wraps(func) def f(self, *args, **kw): with self.saved_context(): pt = self.ctx.get_current_point() func(self, *args, **kw) self.ctx.move_to(*pt) return f def holeCol(func): """ Wrapper: color holes differently :param func: function to wrap """ @wraps(func) def f(self, *args, **kw): if "color" in kw: color = kw.pop("color") else: color = Color.INNER_CUT self.ctx.stroke() with self.saved_context(): self.set_source_color(color) func(self, *args, **kw) self.ctx.stroke() return f ############################################################################# ### Building blocks ############################################################################# HexSizes = { # (nut width, nut height, shaft width) "M1.6" : (3.2, 1.3, 1.6), "M2" : (4, 1.6, 2), "M2.5" : (5, 2.0, 2.5), "M3" : (5.5, 2.4, 3), "M4" : (7, 3.2, 4), "M5" : (8, 4.7, 5), "M6" : (10, 5.2, 6), "M8" : (13.7, 6.8, 8), "M10" : (16, 8.4, 10), "M12" : (18, 10.8, 12), "M14" : (21, 12.8, 14), "M16" : (24, 14.8, 16), "M20" : (30, 18.0, 20), "M24" : (36, 21.5, 24), "M30" : (46, 25.6, 30), "M36" : (55, 31, 36), "M42" : (65, 34, 42), "M48" : (75, 38, 48), "M56" : (85, 45, 56), "M64" : (95, 51, 64), "#0" : (0.156*25.4, 0.050*25.4, 0.060*25.4), "#1" : (0.156*25.4, 0.050*25.4, 0.073*25.4), "#2" : (0.188*25.4, 0.066*25.4, 0.086*25.4), "#3" : (0.188*25.4, 0.066*25.4, 0.099*25.4), "#4" : (0.250*25.4, 0.098*25.4, 0.112*25.4), "#5" : (0.312*25.4, 0.114*25.4, 0.125*25.4), "#6" : (0.312*25.4, 0.114*25.4, 0.138*25.4), "#8" : (0.344*25.4, 0.130*25.4, 0.164*25.4), "#10" : (0.375*25.4, 0.130*25.4, 0.190*25.4), "#12" : (0.438*25.4, 0.161*25.4, 0.216*25.4), "1/4" : (0.438*25.4, 0.226*25.4, 0.250*25.4), "5/16" : (0.562*25.4, 0.273*25.4, (5/16 )*25.4), "3/8" : (0.625*25.4, 0.337*25.4, (3/8 )*25.4), "7/16" : (0.688*25.4, 0.385*25.4, (7/16 )*25.4), "1/2" : (0.750*25.4, 0.448*25.4, (1/2 )*25.4), "9/16" : (0.875*25.4, 0.496*25.4, (9/16 )*25.4), "5/8" : (0.938*25.4, 0.559*25.4, (5/8 )*25.4), "3/4" : (1.125*25.4, 0.665*25.4, (3/4 )*25.4), "7/8" : (1.312*25.4, 0.776*25.4, (7/8 )*25.4), "1" : (1.500*25.4, 0.887*25.4, (1 )*25.4), "1-1/8": (1.688*25.4, 0.999*25.4, (1+1/8)*25.4), "1-1/4": (1.875*25.4, 1.094*25.4, (1+1/4)*25.4), "1-3/8": (2.062*25.4, 1.206*25.4, (1+3/8)*25.4), "1-1/2": (2.250*25.4, 1.317*25.4, (1+1/2)*25.4), "1-5/8": (2.438*25.4, 1.429*25.4, (1+5/8)*25.4), "1-3/4": (2.625*25.4, 1.540*25.4, (1+3/4)*25.4), "1-7/8": (2.813*25.4, 1.651*25.4, (1+7/8)*25.4), "2" : (3.000*25.4, 1.763*25.4, (2 )*25.4), "2-1/4": (3.375*25.4, 1.986*25.4, (2+1/4)*25.4), "2-1/2": (3.750*25.4, 2.209*25.4, (2+1/2)*25.4), } class NutHole: """Draw a hex nut""" def __init__(self, boxes, settings) -> None: self.boxes = boxes self.ctx = boxes.ctx self.settings = settings def __getattr__(self, name): return getattr(self.boxes, name) @restore @holeCol def __call__(self, size, x=0, y=0, angle=0): size = HexSizes.get(size, (size,))[0] side = size / 3 ** 0.5 self.boxes.moveTo(x, y, angle) self.boxes.moveTo(-0.5 * side, 0.5 * size, angle) for i in range(6): self.boxes.edge(side) self.boxes.corner(-60) ############################################################################## ### Argument types ############################################################################## def argparseSections(s): """ Parse sections parameter :param s: string to parse """ result = [] s = re.split(r"\s|:", s) try: for part in s: m = re.match(r"^(\d+(\.\d+)?)/(\d+)$", part) if m: n = int(m.group(3)) result.extend([float(m.group(1)) / n] * n) continue m = re.match(r"^(\d+(\.\d+)?)\*(\d+)$", part) if m: n = int(m.group(3)) result.extend([float(m.group(1))] * n) continue result.append(float(part)) except ValueError: raise argparse.ArgumentTypeError("Don't understand sections string") if not result: result.append(0.0) return result class ArgparseEdgeType: """argparse type to select from a set of edge types""" names = edges.getDescriptions() edges: list[str] = [] def __init__(self, edges: str | None = None) -> None: if edges: self.edges = list(edges) def __call__(self, pattern): if len(pattern) != 1: raise ValueError("Edge type can only have one letter.") if pattern not in self.edges: raise ValueError("Use one of the following values: " + ", ".join(edges)) return pattern def html(self, name, default, translate): options = "\n".join( """<option value="%s"%s>%s</option>""" % (e, ' selected="selected"' if e == default else "", translate("{} {}".format(e, self.names.get(e, "")))) for e in self.edges) return """<select name="{}" id="{}" aria-labeledby="{} {}" size="1">\n{}</select>\n""".format(name, name, name+"_id", name+"_description", options) def inx(self, name, viewname, arg): return (' <param name="%s" type="optiongroup" appearance="combo" gui-text="%s" gui-description=%s>\n' % (name, viewname, quoteattr(arg.help or "")) + ''.join(' <option value="{}">{} {}</option>\n'.format( e, e, self.names.get(e, "")) for e in self.edges) + ' </param>\n') class BoolArg: def __call__(self, arg): if not arg or arg.lower() in ("none", "0", "off", "false"): return False return True def html(self, name, default, _): if isinstance(default, (str)): default = self(default) return """<input name="%s" type="hidden" value="0"> <input name="%s" id="%s" aria-labeledby="%s %s" type="checkbox" value="1"%s>""" % \ (name, name, name, name+"_id", name+"_description",' checked="checked"' if default else "") boolarg = BoolArg() class HexHolesSettings(edges.Settings): """Settings for hexagonal hole patterns Values: * absolute * diameter : 5.0 : diameter of the holes * distance : 3.0 : distance between the holes * style : "circle" : currently only supported style """ absolute_params = { 'diameter' : 10.0, 'distance' : 3.0, 'style' : ('circle', ), } relative_params: dict[str, Any] = {} class fillHolesSettings(edges.Settings): """Settings for Hole filling Values: * absolute * fill_pattern : "no fill" : style of hole pattern * hole_style : "round" : style of holes (does not apply to fill patterns 'vbar' and 'hbar') * max_random : 1000 : maximum number of random holes * bar_length : 50 : maximum length of bars * hole_max_radius : 12.0 : maximum radius of generated holes (in mm) * hole_min_radius : 4.0 : minimum radius of generated holes (in mm) * space_between_holes : 4.0 : hole to hole spacing (in mm) * space_to_border : 4.0 : hole to border spacing (in mm) """ absolute_params = { "fill_pattern": ("no fill", "hex", "square", "random", "hbar", "vbar"), "hole_style": ("round", "triangle", "square", "hexagon", "octagon"), "max_random": 1000, "bar_length": 50, "hole_max_radius": 3.0, "hole_min_radius": 0.5, "space_between_holes": 4.0, "space_to_border": 4.0, } ############################################################################## ### Main class ############################################################################## class Boxes: """Main class -- Generator should subclass this """ webinterface = True ui_group = "Misc" UI = "" description: str = "" # Markdown syntax is supported def __init__(self) -> None: self.formats = formats.Formats() self.ctx = None description: str = self.__doc__ or "" if self.description: description += "\n\n" + self.description self.argparser = ArgumentParser(description=description) self.edgesettings: dict[Any, Any] = {} self.non_default_args: dict[Any, Any] = {} self.translations = gettext.NullTranslations() self.metadata = { "name": self.__class__.__name__, "short_description": self.__doc__, "description": self.description, "group": self.ui_group, "url": "", "url_short": "", "cli": "", "cli_short": "", "creation_date": datetime.datetime.now(), "reproducible": False, # If True output does not contain variable content like creation date. } # Dummy attribute for static analytic tools. Will be overwritten by `argparser` at runtime. self.thickness: float = 0.0 self.argparser._action_groups[1].title = self.__class__.__name__ + " Settings" defaultgroup = self.argparser.add_argument_group( "Default Settings") defaultgroup.add_argument( "--thickness", action="store", type=float, default=3.0, help="thickness of the material (in mm) [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#thickness)") defaultgroup.add_argument( "--output", action="store", type=str, default="box.svg", help="name of resulting file") defaultgroup.add_argument( "--format", action="store", type=str, default="svg", choices=self.formats.getFormats(), help="format of resulting file [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#format)") defaultgroup.add_argument( "--tabs", action="store", type=float, default=0.0, help="width of tabs holding the parts in place (in mm)(not supported everywhere) [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#tabs)") defaultgroup.add_argument( "--qr_code", action="store", type=boolarg, default=False, help="Add a QR Code with link or command line to the generated output") defaultgroup.add_argument( "--debug", action="store", type=boolarg, default=False, help="print surrounding boxes for some structures [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#debug)") defaultgroup.add_argument( "--labels", action="store", type=boolarg, default=True, help="label the parts (where available)") defaultgroup.add_argument( "--reference", action="store", type=float, default=100.0, help="print reference rectangle with given length (in mm)(zero to disable) [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#reference)") defaultgroup.add_argument( "--inner_corners", action="store", type=str, default="loop", choices=["loop", "corner", "backarc"], help="style for inner corners [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#inner-corners)") defaultgroup.add_argument( "--burn", action="store", type=float, default=0.1, help='burn correction (in mm)(bigger values for tighter fit) [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#burn)') @contextmanager def saved_context(self): """ Generator: for saving and restoring contexts. """ cr = self.ctx cr.save() try: yield cr finally: cr.restore() def set_source_color(self, color): """ Sets the color of the pen. """ self.ctx.set_source_rgb(*color) def set_font(self, style, bold=False, italic=False): """ Set font style used :param style: "serif", "sans-serif" or "monospaced" :param bold: Use bold font :param italic: Use italic font """ self.ctx.set_font(style, bold, italic) def open(self): """ Prepare for rendering Create canvas and edge and other objects Call this before .render() """ if self.ctx is not None: return self.bedBoltSettings = (3, 5.5, 2, 20, 15) # d, d_nut, h_nut, l, l1 self.surface, self.ctx = self.formats.getSurface(self.format) if self.format == 'svg_Ponoko': self.ctx.set_line_width(0.01) self.set_source_color(Color.BLUE) else: self.ctx.set_line_width(max(2 * self.burn, 0.05)) self.set_source_color(Color.BLACK) self.spacing = 2 * self.burn + 0.5 * self.thickness self.set_font("sans-serif") self._buildObjects() if self.reference and self.format != 'svg_Ponoko': self.move(self.reference, 10, "up", before=True) self.ctx.rectangle(0, 0, self.reference, 10) if self.reference < 80: self.text(f"{self.reference:.1f}mm, burn:{self.burn:.2f}mm", self.reference + 5, 5, fontsize=6, align="middle left", color=Color.ANNOTATIONS) else: self.text(f"{self.reference:.1f}mm, burn:{self.burn:.2f}mm", self.reference / 2.0, 5, fontsize=6, align="middle center", color=Color.ANNOTATIONS) self.move(self.reference, 10, "up") if self.qr_code: self.renderQrCode() self.ctx.stroke() def renderQrCode(self): content = self.metadata['url_short'] or self.metadata["cli_short"] size = 1.5 if content: with self.saved_context(): self.qrcode(content, box_size=size, move="right") self.text(text=content, y=6, color=Color.ANNOTATIONS, fontsize=6) self.qrcode(content, box_size=size, move="up only") def buildArgParser(self, *l, **kw): """ Add commonly used arguments :param l: parameter names :param kw: parameters with new default values Supported parameters are * floats: x, y, h, hi * argparseSections: sx, sy, sh * ArgparseEdgeType: bottom_edge, top_edge * boolarg: outside * str (selection): nema_mount """ for arg in l: kw[arg] = None for arg, default in kw.items(): if arg == "x": if default is None: default = 100.0 help = "inner width in mm" if "outside" in kw: help += " (unless outside selected)" self.argparser.add_argument( "--x", action="store", type=float, default=default, help=help) elif arg == "y": if default is None: default = 100.0 help = "inner depth in mm" if "outside" in kw: help += " (unless outside selected)" self.argparser.add_argument( "--y", action="store", type=float, default=default, help=help) elif arg == "sx": if default is None: default = "50*3" self.argparser.add_argument( "--sx", action="store", type=argparseSections, default=str(default), help="""sections left to right in mm [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#section-parameters)""") elif arg == "sy": if default is None: default = "50*3" self.argparser.add_argument( "--sy", action="store", type=argparseSections, default=str(default), help="""sections back to front in mm [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#section-parameters)""") elif arg == "sh": if default is None: default = "50*3" self.argparser.add_argument( "--sh", action="store", type=argparseSections, default=str(default), help="""sections bottom to top in mm [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#section-parameters)""") elif arg == "h": if default is None: default = 100.0 help = "inner height in mm" if "outside" in kw: help += " (unless outside selected)" self.argparser.add_argument( "--h", action="store", type=float, default=default, help=help) elif arg == "hi": if default is None: default = 0.0 self.argparser.add_argument( "--hi", action="store", type=float, default=default, help="inner height of inner walls in mm (unless outside selected)(leave to zero for same as outer walls)") elif arg == "hole_dD": if default is None: default = "3.5:6.5" self.argparser.add_argument( "--hole_dD", action="store", type=argparseSections, default=default, help="mounting hole diameter (shaft:head) in mm [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#mounting-holes)") elif arg == "bottom_edge": if default is None: default = "h" self.argparser.add_argument( "--bottom_edge", action="store", type=ArgparseEdgeType("Fhse"), choices=list("Fhse"), default=default, help="edge type for bottom edge") elif arg == "top_edge": if default is None: default = "e" self.argparser.add_argument( "--top_edge", action="store", type=ArgparseEdgeType("efFhcESŠikvLtGyY"), choices=list("efFhcESŠikvfLtGyY"), default=default, help="edge type for top edge") elif arg == "outside": if default is None: default = True self.argparser.add_argument( "--outside", action="store", type=boolarg, default=default, help="treat sizes as outside measurements [\U0001F6C8](https://florianfesti.github.io/boxes/html/usermanual.html#outside)") elif arg == "nema_mount": if default is None: default = 23 self.argparser.add_argument( "--nema_mount", action="store", type=int, choices=list(sorted(self.nema_sizes.keys())), default=default, help="NEMA size of motor") else: raise ValueError("No default for argument", arg) def addSettingsArgs(self, settings, prefix=None, **defaults): prefix = prefix or settings.__name__[:-len("Settings")] settings.parserArguments(self.argparser, prefix, **defaults) self.edgesettings[prefix] = {} def parseArgs(self, args=None): """ Parse command line parameters :param args: (Default value = None) parameters, None for using sys.argv """ if args is None: args = sys.argv[1:] def cliQuote(s: str) -> str: s = s.replace('\r', '') s = s.replace('\n', "\\n") return quote(s) self.metadata["cli"] = "boxes " + self.__class__.__name__ + " " + " ".join(cliQuote(arg) for arg in args) self.metadata["cli"] = self.metadata["cli"].strip() for key, value in vars(self.argparser.parse_args(args=args)).items(): default = self.argparser.get_default(key) # treat edge settings separately for setting in self.edgesettings: if key.startswith(setting + '_'): self.edgesettings[setting][key[len(setting)+1:]] = value continue setattr(self, key, value) if value != default: self.non_default_args[key] = value # Change file ending to format if not given explicitly fileFormat = getattr(self, "format", "svg") if getattr(self, 'output', None) == 'box.svg': self.output = 'box.' + fileFormat.split("_")[0] self.metadata["cli_short"] = "boxes " + self.__class__.__name__ + " " + " ".join(cliQuote(arg) for arg in args if (arg.split("=")[0][2:] in self.non_default_args)) self.metadata["cli_short"] = self.metadata["cli_short"].strip() def addPart(self, part, name=None): """ Add Edge or other part instance to this one and add it as attribute :param part: Callable :param name: (Default value = None) attribute name (__name__ as default) """ if name is None: name = part.__class__.__name__ name = name[0].lower() + name[1:] # if not hasattr(self, name): if isinstance(part, edges.BaseEdge): self.edges[part.char] = part else: setattr(self, name, part) def addParts(self, parts): for part in parts: self.addPart(part) fingerHolesAt : Any def _buildObjects(self): """Add default edges and parts""" self.edges = {} self.addPart(edges.Edge(self, None)) self.addPart(edges.OutSetEdge(self, None)) edges.GripSettings(self.thickness).edgeObjects(self) # Finger joints # Share settings object s = edges.FingerJointSettings(self.thickness, True, **self.edgesettings.get("FingerJoint", {})) s.edgeObjects(self) self.addPart(edges.FingerHoles(self, s), name="fingerHolesAt") # Stackable edges.StackableSettings(self.thickness, True, **self.edgesettings.get("Stackable", {})).edgeObjects(self) # Dove tail joints edges.DoveTailSettings(self.thickness, True, **self.edgesettings.get("DoveTail", {})).edgeObjects(self) # Flex s = edges.FlexSettings(self.thickness, True, **self.edgesettings.get("Flex", {})) self.addPart(edges.FlexEdge(self, s)) # Clickable edges.ClickSettings(self.thickness, True, **self.edgesettings.get("Click", {})).edgeObjects(self) # Hinges edges.HingeSettings(self.thickness, True, **self.edgesettings.get("Hinge", {})).edgeObjects(self) edges.ChestHingeSettings(self.thickness, True, **self.edgesettings.get("ChestHinge", {})).edgeObjects(self) edges.CabinetHingeSettings(self.thickness, True, **self.edgesettings.get("CabinetHinge", {})).edgeObjects(self) # Sliding Lid edges.SlideOnLidSettings(self.thickness, True, **self.edgesettings.get("SlideOnLid", {})).edgeObjects(self) # Rounded Triangle Edge edges.RoundedTriangleEdgeSettings(self.thickness, True, **self.edgesettings.get("RoundedTriangleEdge", {})).edgeObjects(self) # Grooved Edge edges.GroovedSettings(self.thickness, True, **self.edgesettings.get("Grooved", {})).edgeObjects(self) # Mounting Edge edges.MountingSettings(self.thickness, True, **self.edgesettings.get("Mounting", {})).edgeObjects(self) # Handle Edge edges.HandleEdgeSettings(self.thickness, True, **self.edgesettings.get("HandleEdge", {})).edgeObjects(self) # HexHoles self.hexHolesSettings = HexHolesSettings(self.thickness, True, **self.edgesettings.get("HexHoles", {})) # Lids from . import lids self.lidSettings = lids.LidSettings(self.thickness, True, **self.edgesettings.get("Lid", {})) self.lid = lids.Lid(self, self.lidSettings) # Nuts self.addPart(NutHole(self, None)) # Gears self.addPart(gears.Gears(self)) s = edges.GearSettings(self.thickness, True, **self.edgesettings.get("Gear", {})) self.addPart(edges.RackEdge(self, s)) self.addPart(pulley.Pulley(self)) self.addPart(parts.Parts(self)) def adjustSize(self, l, e1=True, e2=True): # Char to edge object e1 = self.edges.get(e1, e1) e2 = self.edges.get(e2, e2) try: total = sum(l) walls = (len(l) - 1) * self.thickness except TypeError: total = l walls = 0 if isinstance(e1, edges.BaseEdge): walls += e1.startwidth() + e1.margin() elif e1: walls += self.thickness if isinstance(e2, edges.BaseEdge): walls += e2.startwidth() + e2.margin() elif e2: walls += self.thickness try: if total > 0.0: factor = (total - walls) / total else: factor = 1.0 return [s * factor for s in l] except TypeError: return l - walls def render(self): """Implement this method in your subclass. You will typically need to call .parseArgs() before calling this one """ # Change settings and create new Edges and part classes here raise NotImplementedError def cc(self, callback, number, x=0.0, y=None, a=0.0): """Call callback from edge of a part :param callback: callback (callable or list of callables) :param number: number of the callback :param x: (Default value = 0.0) x position to be call on :param y: (Default value = None) y position to be called on (default does burn correction) """ if y is None: y = self.burn if hasattr(callback, '__getitem__'): try: callback = callback[number] number = None except (KeyError, IndexError): pass if callback and callable(callback): with self.saved_context(): self.moveTo(x, y, a) if number is None: callback() else: callback(number) self.ctx.move_to(0, 0) def getEntry(self, param, idx): """ Get entry from list or items itself :param param: list or item :param idx: index in list """ if isinstance(param, list): if len(param) > idx: return param[idx] else: return None else: return param def close(self): """Finish rendering Flush canvas to disk and convert output to requested format if needed. Call after .render()""" if self.ctx is None: return self.ctx.stroke() self.ctx = None self.surface.set_metadata(self.metadata) self.surface.flush() data = self.surface.finish(self.inner_corners) data = self.formats.convert(data, self.format) return data ############################################################ ### Turtle graphics commands ############################################################ def corner(self, degrees, radius=0, tabs=0): """ Draw a corner This is what does the burn corrections :param degrees: angle :param radius: (Default value = 0) """ try: degrees, radius = degrees except: pass rad = degrees * math.pi / 180 if tabs and self.tabs: if degrees > 0: r_ = radius + self.burn tabrad = self.tabs / max(r_, 0.01) else: r_ = radius - self.burn tabrad = -self.tabs / max(r_, 0.01) length = abs(r_ * rad) tabs = min(tabs, int(length // (tabs*3*self.tabs))) if tabs and self.tabs: l = (length - tabs * self.tabs) / tabs lang = math.degrees(l / r_) if degrees < 0: lang = -lang #print(degrees, radius, l, lang, tabs, math.degrees(tabrad)) self.corner(lang/2., radius) for i in range(tabs-1): self.moveArc(math.degrees(tabrad), r_) self.corner(lang, radius) if tabs: self.moveArc(math.degrees(tabrad), r_) self.corner(lang/2., radius) return if ((radius > 0.5* self.burn and abs(degrees) > 36) or (abs(degrees) > 100)): steps = int(abs(degrees)/ 36.) + 1 for i in range(steps): self.corner(float(degrees)/steps, radius) return if degrees > 0: self.ctx.arc(0, radius + self.burn, radius + self.burn, -0.5 * math.pi, rad - 0.5 * math.pi) elif radius > self.burn: self.ctx.arc_negative(0, -(radius - self.burn), radius - self.burn, 0.5 * math.pi, rad + 0.5 * math.pi) else: # not rounded inner corner self.ctx.arc_negative(0, self.burn - radius, self.burn - radius, -0.5 * math.pi, -0.5 * math.pi + rad) self._continueDirection(rad) def edge(self, length, tabs=0): """ Simple line :param length: length in mm """ self.ctx.move_to(0, 0) if tabs and self.tabs: if self.tabs > length: self.ctx.move_to(length, 0) else: tabs = min(tabs, max(1, int(length // (tabs*3*self.tabs)))) l = (length - tabs * self.tabs) / tabs self.ctx.line_to(0.5*l, 0) for i in range(tabs-1): self.ctx.move_to((i+0.5)*l+self.tabs, 0) self.ctx.line_to((i+0.5)*l+self.tabs+l, 0) if tabs == 1: self.ctx.move_to((tabs-0.5)*l+self.tabs, 0) else: self.ctx.move_to((tabs-0.5)*l+2*self.tabs, 0) self.ctx.line_to(length, 0) else: self.ctx.line_to(length, 0) self.ctx.translate(*self.ctx.get_current_point()) def step(self, out): """ Create a parallel step perpendicular to the current direction Positive values move to the outside of the part """ if out > 1E-5: self.corner(-90) self.edge(out) self.corner(90) elif out < -1E-5: self.corner(90) self.edge(-out) self.corner(-90) def curveTo(self, x1, y1, x2, y2, x3, y3): """control point 1, control point 2, end point :param x1: :param y1: :param x2: :param y2: :param x3: :param y3: """ self.ctx.curve_to(x1, y1, x2, y2, x3, y3) dx = x3 - x2 dy = y3 - y2 rad = math.atan2(dy, dx) self._continueDirection(rad) def polyline(self, *args): """ Draw multiple connected lines :param args: Alternating length in mm and angle in degrees. lengths may be a tuple (length, #tabs) angles may be tuple (angle, radius) """ for i, arg in enumerate(args): if i % 2: if isinstance(arg, tuple): self.corner(*arg) else: self.corner(arg) else: if isinstance(arg, tuple): self.edge(*arg) else: self.edge(arg) def bedBoltHole(self, length, bedBoltSettings=None, tabs=0): """ Draw an edge with slot for a bed bolt :param length: length of the edge in mm :param bedBoltSettings: (Default value = None) Dimensions of the slot """ d, d_nut, h_nut, l, l1 = bedBoltSettings or self.bedBoltSettings self.edge((length - d) / 2.0, tabs=tabs//2) self.corner(90) self.edge(l1) self.corner(90) self.edge((d_nut - d) / 2.0) self.corner(-90) self.edge(h_nut) self.corner(-90) self.edge((d_nut - d) / 2.0) self.corner(90) self.edge(l - l1 - h_nut) self.corner(-90) self.edge(d) self.corner(-90) self.edge(l - l1 - h_nut) self.corner(90) self.edge((d_nut - d) / 2.0) self.corner(-90) self.edge(h_nut) self.corner(-90) self.edge((d_nut - d) / 2.0) self.corner(90) self.edge(l1) self.corner(90) self.edge((length - d) / 2.0, tabs=tabs-(tabs//2)) def edgeCorner(self, edge1, edge2, angle=90): """Make a corner between two Edges. Take width of edges into account""" edge1 = self.edges.get(edge1, edge1) edge2 = self.edges.get(edge2, edge2) self.edge(edge2.startwidth() * math.tan(math.radians(angle/2.))) self.corner(angle) self.edge(edge1.endwidth() * math.tan(math.radians(angle/2.))) def regularPolygon(self, corners=3, radius=None, h=None, side=None): """Give measures of a regular polygon :param corners: number of corners of the polygon :param radius: distance center to one of the corners :param h: distance center to one of the sides (height of sector) :param side: length of one side :return: (radius, h, side) """ if radius: side = 2 * math.sin(math.radians(180.0/corners)) * radius h = radius * math.cos(math.radians(180.0/corners)) elif h: side = 2 * math.tan(math.radians(180.0/corners)) * h radius = ((side/2.)**2+h**2)**0.5 elif side: h = 0.5 * side * math.tan(math.radians(90-180./corners)) radius = ((side/2.)**2+h**2)**0.5 return radius, h, side @restore def regularPolygonAt(self, x, y, corners, angle=0, r=None, h=None, side=None): """Draw regular polygon""" self.moveTo(x, y, angle) r, h, side = self.regularPolygon(corners, r, h, side) self.moveTo(-side/2.0, -h-self.burn) for i in range(corners): self.edge(side) self.corner(360./corners) def regularPolygonWall(self, corners=3, r=None, h=None, side=None, edges='e', hole=None, callback=None, move=None): """Create regular polygon as a wall :param corners: number of corners of the polygon :param r: radius distance center to one of the corners :param h: distance center to one of the sides (height of sector) :param side: length of one side :param edges: (Default value = "e", may be string/list of length corners) :param hole: diameter of central hole (Default value = 0) :param callback: (Default value = None, middle=0, then sides=1..) :param move: (Default value = None) """ r, h, side = self.regularPolygon(corners, r, h, side) t = self.thickness if not hasattr(edges, "__getitem__") or len(edges) == 1: edges = [edges] * corners edges = [self.edges.get(e, e) for e in edges] edges += edges # append for wrapping around if corners % 2: th = r + h + edges[0].spacing() + ( max(edges[corners//2].spacing(), edges[corners//2+1].spacing()) / math.sin(math.radians(90-180/corners))) else: th = 2*h + edges[0].spacing() + edges[corners//2].spacing() tw = 0 for i in range(corners): ang = (180+360*i)/corners tw = max(tw, 2*abs(math.sin(math.radians(ang))* (r + max(edges[i].spacing(), edges[i+1].spacing())/ math.sin(math.radians(90-180/corners))))) if self.move(tw, th, move, before=True): return self.moveTo(0.5*tw-0.5*side, edges[0].margin()) if hole: self.hole(side/2., h+edges[0].startwidth() + self.burn, hole/2.) self.cc(callback, 0, side/2., h+edges[0].startwidth() + self.burn) for i in range(corners): self.cc(callback, i+1, 0, edges[i].startwidth() + self.burn) edges[i](side) self.edgeCorner(edges[i], edges[i+1], 360.0/corners) self.move(tw, th, move) def grip(self, length, depth): """Corrugated edge useful as a gipping area :param length: length :param depth: depth of the grooves """ grooves = max(int(length // (depth * 2.0)) + 1, 1) depth = length / grooves / 4.0 for groove in range(grooves): self.corner(90, depth) self.corner(-180, depth) self.corner(90, depth) def _latchHole(self, length): """ :param length: """ self.edge(1.1 * self.thickness) self.corner(-90) self.edge(length / 2.0 + 0.2 * self.thickness) self.corner(-90) self.edge(1.1 * self.thickness) def _latchGrip(self, length, extra_length=0.0): """ :param length: """ self.corner(90, self.thickness / 4.0) self.grip(length / 2.0 - self.thickness / 2.0 - 0.2 * self.thickness + extra_length, self.thickness / 2.0) self.corner(90, self.thickness / 4.0) def latch(self, length, positive=True, reverse=False, extra_length=0.0): """Latch to fix a flex box door to the box :param length: length in mm :param positive: (Default value = True) False: Door side; True: Box side :param reverse: (Default value = False) True when running away from the latch """ t = self.thickness if positive: poly = [0, -90, t, 90, length / 2.0, 90, t, -90, length / 2.] if reverse: poly = list(reversed(poly)) self.polyline(*poly) else: if reverse: self._latchGrip(length, extra_length) else: self.corner(90) self._latchHole(length) if not reverse: self._latchGrip(length, extra_length) else: self.corner(90) def handle(self, x, h, hl, r=30): """Creates an Edge with a handle :param x: width in mm :param h: height in mm :param hl: height if the grip hole :param r: (Default value = 30) radius of the corners """ d = (x - hl - 2 * r) / 2.0 # Hole with self.saved_context(): self.moveTo(d + 2 * r, 0) self.edge(hl - 2 * r) self.corner(-90, r) self.edge(h - 3 * r) self.corner(-90, r) self.edge(hl - 2 * r) self.corner(-90, r) self.edge(h - 3 * r) self.corner(-90, r) self.moveTo(0, 0) self.curveTo(d, 0, d, 0, d, -h + r) self.curveTo(r, 0, r, 0, r, r) self.edge(hl) self.curveTo(r, 0, r, 0, r, r) self.curveTo(h - r, 0, h - r, 0, h - r, -d) ### Navigation def moveTo(self, x, y=0.0, degrees=0): """ Move coordinate system to given point :param x: :param y: (Default value = 0.0) :param degrees: (Default value = 0) """ self.ctx.move_to(0, 0) self.ctx.translate(x, y) self.ctx.rotate(degrees * math.pi / 180.0) self.ctx.move_to(0, 0) def moveArc(self, angle, r=0.0): """ :param angle: :param r: (Default value = 0.0) """ if r < 0: r = -r angle = -angle rad = math.radians(angle) if angle > 0: self.moveTo(r*math.sin(rad), r*(1-math.cos(rad)), angle) else: self.moveTo(r*math.sin(-rad), -r*(1-math.cos(rad)), angle) def _continueDirection(self, angle=0): """ Set coordinate system to current position (end point) :param angle: (Default value = 0) heading """ self.ctx.translate(*self.ctx.get_current_point()) self.ctx.rotate(angle) def move(self, x, y, where, before=False, label=""): """Intended to be used by parts where can be combinations of "up" or "down", "left" or "right", "only", "mirror" and "rotated" when "only" is included the move is only done when before is True "mirror" will flip the part along the y-axis "rotated" draws the parts rotated 90 counter clockwise The function returns whether actual drawing of the part should be omitted. :param x: width of part :param y: height of part :param where: which direction to move :param before: (Default value = False) called before or after part being drawn """ if not where: where = "" terms = where.split() dontdraw = before and "only" in terms x += self.spacing y += self.spacing if "rotated" in terms: x, y = y, x moves = { "up": (0, y, False), "down": (0, -y, True), "left": (-x, 0, True), "right": (x, 0, False), "only": (0, 0, None), "mirror": (0, 0, None), "rotated": (0, 0, None), } if not before: # restore position self.ctx.restore() if self.labels and label: self.text(label, x/2, y/2, align="middle center", color=Color.ANNOTATIONS, fontsize=4) self.ctx.stroke() for term in terms: if not term in moves: raise ValueError("Unknown direction: '%s'" % term) mx, my, movebeforeprint = moves[term] if movebeforeprint and before: self.moveTo(mx, my) elif (not movebeforeprint and not before) or dontdraw: self.moveTo(mx, my) if not dontdraw: if before: # paint debug rectangle if self.debug: with self.saved_context(): self.set_source_color(Color.ANNOTATIONS) self.ctx.rectangle(0, 0, x, y) # save position self.ctx.save() if "rotated" in terms: self.moveTo(x, 0, 90) x, y = y, x # change back for "mirror" if "mirror" in terms: self.moveTo(x, 0) self.ctx.scale(-1, 1) self.moveTo(self.spacing / 2.0, self.spacing / 2.0) self.ctx.new_part() return dontdraw @restore def circle(self, x, y, r): """ Draw a round disc :param x: x position :param y: y position :param r: radius """ r += self.burn self.moveTo(x + r, y) a = 0 n = 10 da = 2 * math.pi / n for i in range(n): self.ctx.arc(-r, 0, r, a, a+da) a += da self.ctx.stroke() @restore @holeCol def regularPolygonHole(self, x, y, r=0.0, d=0.0, n=6, a=0.0, tabs=0, corner_radius=0.0): """ Draw a hole in shape of an n-edged regular polygon :param x: x position :param y: y position :param r: radius :param n: number of edges :param a: rotation angle """ if not r: r = d / 2.0 if n == 0: self.hole(x, y, r=r, tabs=tabs) return if r < self.burn: r = self.burn + 1E-9 r_ = r - self.burn if corner_radius < self.burn: corner_radius = self.burn cr_ = corner_radius - self.burn side_length = 2 * r_ * math.sin(math.pi / n) apothem = r_ * math.cos(math.pi / n) # the corner chord: s = math.sqrt(2 * math.pow(cr_, 2) * (1 - math.cos(2 * math.pi / n))) # the missing portion of the rounded corner: b = math.sin(math.pi / n) / math.sin(2 * math.pi / n) * s # the flat portion of the side: flat_side_length = side_length - 2 * b self.moveTo(x, y, a) self.moveTo(r_, 0, 90+180/n) self.moveTo(b, 0, 0) for _ in range(n): self.edge(flat_side_length) self.corner(360/n, cr_) @restore @holeCol def hole(self, x, y, r=0.0, d=0.0, tabs=0): """ Draw a round hole :param x: x position :param y: y position :param r: radius """ if not r: r = d / 2.0 if r < self.burn: r = self.burn + 1E-9 r_ = r - self.burn self.moveTo(x + r_, y, -90) self.corner(-360, r, tabs) @restore @holeCol def rectangularHole(self, x, y, dx, dy, r=0, center_x=True, center_y=True): """ Draw a rectangular hole :param x: x position :param y: y position :param dx: width :param dy: height :param r: (Default value = 0) radius of the corners :param center_x: (Default value = True) if True, x position is the center, else the start :param center_y: (Default value = True) if True, y position is the center, else the start """ r = min(r, dx/2., dy/2.) x_start = x if center_x else x + dx / 2.0 y_start = y - dy / 2.0 if center_y else y self.moveTo(x_start, y_start + self.burn, 180) self.edge(dx / 2.0 - r) # start with an edge to allow easier change of inner corners for d in (dy, dx, dy, dx / 2.0 + r): self.corner(-90, r) self.edge(d - 2 * r) @restore @holeCol def dHole(self, x, y, r=None, d=None, w=None, rel_w=0.75, angle=0): """ Draw a hole for a shaft with flat edge - D shaped hole :param x: center x position :param y: center y position :param r: radius (overrides d) :param d: diameter :param w: width measured against flat side in mm :param rel_w: width in percent :param angle: orientation (rotation) of the flat side """ if r is None: r = d / 2.0 if w is None: w = 2.0 * r * rel_w w -= r if r <= 0.0: return if abs(w) > r: return self.hole(x, y, r) a = math.degrees(math.acos(w / r)) self.moveTo(x, y, angle-a) self.moveTo(r-self.burn, 0, -90) self.corner(-360+2*a, r) self.corner(-a) self.edge(2*r*math.sin(math.radians(a))) @restore @holeCol def flatHole(self, x, y, r=None, d=None, w=None, rel_w=0.75, angle=0): """ Draw a hole for a shaft with two opposed flat edges - ( ) shaped hole :param x: center x position :param y: center y position :param r: radius (overrides d) :param d: diameter :param w: width measured against flat side in mm :param rel_w: width in percent :param angle: orientation (rotation) of the flat sides """ if r is None: r = d / 2.0 if w is None: w = r * rel_w else: w = w / 2.0 if r < 0.0: return if abs(w) > r: return self.hole(x, y, r) a = math.degrees(math.acos(w / r)) self.moveTo(x, y, angle-a) self.moveTo(r-self.burn, 0, -90) for i in range(2): self.corner(-180+2*a, r) self.corner(-a) self.edge(2*r*math.sin(math.radians(a))) self.corner(-a) @restore @holeCol def mountingHole(self, x, y, d_shaft, d_head=0.0, angle=0, tabs=0): """ Draw a pear shaped mounting hole for sliding over a screw head. Total height = 1.5* d_shaft + d_head :param x: x position :param y: y position :param d_shaft: diameter of the screw shaft :param d_head: diameter of the screw head :param angle: rotation angle of the hole """ if d_shaft < (2 * self.burn): return # no hole if diameter is smaller then the capabilities of the machine if not d_head or d_head < (2 * self.burn): # if no head diameter is given self.hole(x, y ,d=d_shaft, tabs=tabs) # only a round hole is generated return rs = d_shaft / 2 rh = d_head / 2 self.moveTo(x, y, angle) self.moveTo(0, rs - self.burn, 0) self.corner(-180, rs, tabs) self.edge(2 * rs,tabs) a = math.degrees(math.asin(rs / rh)) self.corner(90 - a, 0, tabs) self.corner(-360 + 2 * a, rh, tabs) self.corner(90 - a, 0, tabs) self.edge(2 * rs, tabs) @restore def text(self, text, x=0, y=0, angle=0, align="", fontsize=10, color=[0.0, 0.0, 0.0], font="Arial"): """ Draw text :param text: text to render :param x: (Default value = 0) :param y: (Default value = 0) :param angle: (Default value = 0) :param align: (Default value = "") string with combinations of (top|middle|bottom) and (left|center|right) separated by a space """ self.moveTo(x, y, angle) text = text.split("\n") lines = len(text) height = lines * fontsize + (lines - 1) * 0.4 * fontsize align = align.split() halign = "left" moves = { "top": -height, "middle": -0.5 * height, "bottom": 0, "left": "left", "center": "middle", "right": "end", } for a in align: if a in moves: if isinstance(moves[a], str): halign = moves[a] else: self.moveTo(0, moves[a]) else: raise ValueError("Unknown alignment: %s" % align) for line in reversed(text): self.ctx.show_text(line, fs=fontsize, align=halign, rgb=color, font=font) self.moveTo(0, 1.4 * fontsize) tx_sizes = { 1 : 0.61, 2 : 0.70, 3 : 0.82, 4 : 0.96, 5 : 1.06, 6 : 1.27, 7 : 1.49, 8 : 1.75, 9 : 1.87, 10 : 2.05, 15 : 2.40, 20 : 2.85, 25 : 3.25, 30 : 4.05, 40 : 4.85, 45 : 5.64, 50 : 6.45, 55 : 8.05, 60 : 9.60, 70 : 11.20, 80 : 12.80, 90 : 14.40, 100 : 16.00, } @restore @holeCol def TX(self, size, x=0, y=0, angle=0): """Draw a star pattern :param size: 1 to 100 :param x: (Default value = 0) :param y: (Default value = 0) :param angle: (Default value = 0) """ self.moveTo(x, y, angle) size = self.tx_sizes.get(size, 0) ri = 0.5 * size * math.tan(math.radians(30)) ro = ri * (2**0.5-1) self.moveTo(size * 0.5 - self.burn, 0, -90) for i in range(6): self.corner(45, ri) self.corner(-150, ro) self.corner(45, ri) nema_sizes = { # motor,flange, holes, screws 8: (20.3, 16, 15.4, 3), 11: (28.2, 22, 23, 4), 14: (35.2, 22, 26, 4), 16: (39.2, 22, 31, 4), 17: (42.2, 22, 31, 4), 23: (56.4, 38.1, 47.1, 5.2), 24: (60, 36, 49.8, 5.1), 34: (86.3, 73, 69.8, 6.6), 42: (110, 55.5, 89, 8.5), } @restore def NEMA(self, size, x=0, y=0, angle=0, screwholes=None): """Draw holes for mounting a NEMA stepper motor :param size: Nominal size in tenths of inches :param x: (Default value = 0) :param y: (Default value = 0) :param angle: (Default value = 0) :param screwholes: """ width, flange, holedistance, diameter = self.nema_sizes[size] if screwholes: diameter = screwholes self.moveTo(x, y, angle) if self.debug: self.rectangularHole(0, 0, width, width) self.hole(0, 0, 0.5 * flange) for x in (-1, 1): for y in (-1, 1): self.hole(x * 0.5 * holedistance, y * 0.5 * holedistance, 0.5 * diameter) def drawPoints(self, lines, kerfdir=1, close=True): if not lines: return if kerfdir != 0: lines = kerf(lines, self.burn*kerfdir, closed=close) self.ctx.save() self.ctx.move_to(*lines[0]) for x, y in lines[1:]: self.ctx.line_to(x, y) if close: self.ctx.line_to(*lines[0]) self.ctx.restore() def qrcode(self, content, box_size=1.0, color=Color.ETCHING, move=None): q = qrcode.QRCode(image_factory=BoxesQrCodeFactory, box_size=box_size*10) q.add_data(content) m = q.get_matrix() tw, th = len(m) * box_size, len(m[0]) * box_size if self.move(tw, th, move, True): return self.set_source_color(color) q.make_image(ctx=self.ctx) self.move(tw, th, move) @restore def showBorderPoly(self,border,color=Color.ANNOTATIONS): """ draw border polygon (for debugging only) :param border: array with coordinate [(x0,y0), (x1,y1),...] of the border polygon :param color: """ self.set_source_color(color) self.ctx.save() self.ctx.move_to(*border[0]) for x, y in border[1:]: self.ctx.line_to(x, y) self.ctx.line_to(*border[0]) self.ctx.restore() i = 0 for x, y in border: i += 1 self.hole(x, y, 0.5, color=color) self.text(str(i), x, y, fontsize=2, color=color) @restore @holeCol def fillHoles(self, pattern, border, max_radius, hspace=3, bspace=0, min_radius=0.5, style="round", bar_length=50, max_random=1000): """ fill a polygon defined by its outline with holes :param pattern: defines the hole pattern - currently "random", "hex", "square" "hbar" or "vbar" are supported :param border: array with coordinate [(x0,y0), (x1,y1),...] of the border polygon :param max_radius: maximum hole radius :param hspace: space between holes :param bspace: space to border :param min_radius: minimum hole radius :param style: defines hole style - currently one of "round", "triangle", "square", "hexagon" or "octagon" :param bar_length: maximum bar length :param max_random: maximum number of random holes """ if pattern not in ["random", "hex", "square", "hbar", "vbar"]: return a = 0 if style == "round": n = 0 elif style == "triangle": n = 3 a = 60 elif style == "square": n = 4 elif style == "hexagon": n = 6 a = 30 elif style == "octagon": n = 8 a = 22.5 else: raise ValueError("fillHoles - unknown hole style: %s)" % style) # note to myself: ^y x> if self.debug: self.showBorderPoly(border) borderPoly = Polygon(border) min_x, min_y, max_x, max_y = borderPoly.bounds if pattern == "vbar": border = [(max_y - y + min_y, x) for x, y in border] borderPoly = Polygon(border) min_x, min_y, max_x, max_y = borderPoly.bounds self.moveTo(0, max_x + min_x, -90) pattern = "hbar" if self.debug: self.showBorderPoly(border, color=Color.MAGENTA) row = 0 i = 0 # calc the next smaller radius to fit an 'optimum' number of circles # for x direction nx = math.ceil((max_x - min_x - 2 * bspace + hspace) / (2 * max_radius + hspace)) max_radius_x = (max_x - min_x - 2 * bspace - (nx - 1) * hspace) / nx / 2 # for y direction if pattern == "hex": ny = math.ceil((max_y - min_y - 2 * bspace - 2 * max_radius) / (math.sqrt(3) / 2 * (2 * max_radius + hspace))) max_radius_y = (max_y - min_y - 2 * bspace - math.sqrt(3) / 2 * ny * hspace) / (math.sqrt(3) * ny + 2 ) else: ny = math.ceil((max_y - min_y - 2 * bspace + hspace) / (2 * max_radius + hspace)) max_radius_y = (max_y - min_y - 2 * bspace - (ny - 1) * hspace) / ny / 2 if pattern == "random": grid = {} misses = 0 # in a row while i < max_random and misses < 20: i += 1 misses += 1 # random new point x = random.randrange(math.floor(min_x + bspace), math.ceil(max_x - bspace)) # randomness takes longer to compute y = random.randrange(math.floor(min_y + bspace), math.ceil(max_y - bspace)) # but generates a new pattern for each run pt = Point(x, y).buffer(min_radius + bspace) # check if point is within border if borderPoly.contains(pt): pt1 = Point(x, y) grid_x = int(x//(2*max_radius+hspace)) grid_y = int(y//(2*max_radius+hspace)) # compute distance between hole and border bdist = borderPoly.exterior.distance(pt1) - bspace # compute minimum distance to all other holes hdist = max_radius try: # learned from https://medium.com/techtofreedom/5-ways-to-break-out-of-nested-loops-in-python-4c505d34ace7 for gx in (-1, 0, 1): for gy in (-1, 0, 1): for pt2 in grid.get((grid_x+gx, grid_y+gy), []): pt3 = Point(pt2.x, pt2.y) hdist = min(hdist, pt1.distance(pt3) - pt2.z - hspace) if hdist < min_radius: hdist = 0 raise StopIteration except StopIteration: pass # find maximum radius depending on distances r = min(bdist, hdist) # if too small, dismiss cycle if r < min_radius: continue # if too large, limit to max size if r > max_radius: r = max_radius # store in grid with radius as z value grid.setdefault((grid_x, grid_y), []).append( Point(x, y, r)) misses = 0 # and finally paint the hole self.regularPolygonHole(x, y, r=r, n=n, a=a) # rinse and repeat elif pattern in ("square", "hex"): # use 'optimum' hole size max_radius = min(max_radius_x, max_radius_y) # check if at least one line fits (we do horizontal filling) if (max_y - min_y) < (2 * max_radius + 2 * bspace): return # make cutPolys a little wider to avoid # overlapping with lines to be cut outerCutPoly = borderPoly.buffer(-1 * (bspace - 0.000001), join_style=2) outerTestPoly = borderPoly.buffer(-1 * (bspace - 0.01), join_style=2) # shrink original polygon to get place for full size polygons innerCutPoly = borderPoly.buffer(-1 * (bspace + max_radius - 0.0001), join_style=2) innerTestPoly = borderPoly.buffer(-1 * (bspace + max_radius - 0.001), join_style=2) # get left and right boundaries of cut polygon x_cpl, y_cpl, x_cpr, y_cpr = outerCutPoly.bounds if self.debug: self.showBorderPoly(list(outerCutPoly.exterior.coords)) self.showBorderPoly(list(innerCutPoly.exterior.coords)) # set startpoint y = min_y + bspace + max_radius_y while y < (max_y - bspace - max_radius_y): if pattern == "square" or row % 2 == 0: xs = min_x + bspace + max_radius_x else: xs = min_x + max_radius_x * 2 + hspace / 2 + bspace # create line segments cut by the polygons line_complete = LineString([(x_cpl, y), (max_x + 1, y)]) # cut accurate outer_line_split = split(line_complete, outerCutPoly) line_complete = LineString([(x_cpl, y), (max_x + 1, y)]) inner_line_split = split(line_complete, innerCutPoly) inner_line_index = 0 if self.debug and False: for line in inner_line_split.geoms: self.hole(line.bounds[0], line.bounds[1], 1.1) self.hole(line.bounds[2], line.bounds[3], .9) # process each line for line_this in outer_line_split.geoms: if self.debug and False: # enable to debug missing lines x_start, y_start, x_end, y_end = line_this.bounds with self.saved_context(): self.moveTo(x_start, y_start ,0) self.hole(0, 0, 0.5) self.edge(x_end - x_start) with self.saved_context(): self.moveTo(x_start, y_start ,0) self.text(str(outerTestPoly.contains(line_this)), 0, 0, fontsize=2, color=Color.ANNOTATIONS) with self.saved_context(): self.moveTo(x_end, y_end ,0) self.hole(0, 0, 0.5) if not outerTestPoly.contains(line_this): continue x_start, y_start , x_end, y_end = line_this.bounds #initialize walking x coordinate xw = (math.ceil((x_start - xs) / (2 * max_radius_x + hspace)) * (2 * max_radius_x + hspace)) + xs # look up matching inner line while (inner_line_index < len(inner_line_split.geoms) and (inner_line_split.geoms[inner_line_index].bounds[2] < xw or not innerTestPoly.contains(inner_line_split.geoms[inner_line_index]))): inner_line_index += 1 # and process line while not xw > x_end: # are we in inner polygon already? if (len(inner_line_split.geoms) > inner_line_index and xw > inner_line_split.geoms[inner_line_index].bounds[0]): # place inner, full size polygons while xw < inner_line_split.geoms[inner_line_index].bounds[2]: self.regularPolygonHole(xw, y, r=max_radius, n=n, a=a) xw += (2 * max_radius_x + hspace) # forward to next inner line while (inner_line_index < len(inner_line_split.geoms) and (inner_line_split.geoms[inner_line_index].bounds[0] < xw or not innerTestPoly.contains(inner_line_split.geoms[inner_line_index]))): inner_line_index += 1 if xw > x_end: break # Check distance to border to size the polygon pt = Point(xw, y) r = min(borderPoly.exterior.distance(pt) - bspace, max_radius) # if too small, dismiss if r >= min_radius: self.regularPolygonHole(xw, y, r=r, n=n, a=a) xw += (2 * max_radius_x + hspace) row += 1 if pattern == "square": y += 2 * max_radius_y + hspace - 0.0001 else: y += (math.sqrt(3) / 2 * (2 * max_radius_y + hspace)) - 0.0001 elif pattern == "hbar": # 'optimum' hole size to be used max_radius = max_radius_y # check if at least one bar fits if (max_y - min_y) < (2 * max_radius + 2 * bspace): return #shrink original polygon shrinkPoly = borderPoly.buffer(-1 * (bspace + max_radius - 0.01), join_style=2) cutPoly = borderPoly.buffer(-1 * (bspace + max_radius - 0.000001), join_style=2) if self.debug: self.showBorderPoly(list(shrinkPoly.exterior.coords)) segment_length = [bar_length / 2, bar_length] segment_max = 1 segment_toggle = False # set startpoint y = min_y + bspace + max_radius # and calc step width step_y = 2 * max_radius_y + hspace - 0.0001 while y < (max_y - bspace - max_radius): # toggle segment length each new line if segment_toggle: segment_max = 0 segment_toggle ^= 1 # create line from left to right and cut according to shrunk polygon line_complete = LineString([(min_x - 1, y), (max_x + 1, y)]) line_split = split(line_complete, cutPoly) # process each line for line_this in line_split.geoms: if self.debug and False: # enable to debug missing lines x_start, y_start , x_end, y_end = line_this.bounds with self.saved_context(): self.moveTo(x_start, y_start ,0) self.hole(0, 0, 0.5) self.edge(x_end - x_start) with self.saved_context(): self.moveTo(x_start, y_start ,0) self.text(str(shrinkPoly.contains(line_this)), 0, 0, fontsize=2, color=Color.ANNOTATIONS) with self.saved_context(): self.moveTo(x_end, y_end ,0) self.hole(0, 0, 0.5) if shrinkPoly.contains(line_this): # long segment are cut down further if line_this.length > segment_length[segment_max]: line_working = line_this length = line_working.length while length > 0: x_start, y_start , xw_end, yw_end = line_working.bounds # calculate point with required distance from start point p = line_working.interpolate(segment_length[segment_max]) # and use its coordinates as endpoint for this segment x_end = p.x y_end = p.y # draw segment self.set_source_color(Color.INNER_CUT) with self.saved_context(): self.moveTo(x_start, y_start + max_radius,0) self.edge(x_end - x_start) self.corner(-180, max_radius) self.edge(x_end - x_start) self.corner(-180, max_radius) if self.debug and False: # enable to debug cutting lines self.set_source_color(Color.ANNOTATIONS) with self.saved_context(): self.moveTo(x_start, y_start, 0) self.edge(x_end - x_start) s = "long - y: " + str(round(y, 1)) + " xs: " + str(round(x_start, 1)) + " xe: " + str(round(x_end, 1)) + " l: " + str(round(length, 1)) + " max: " + str(round(segment_length[segment_max], 1)) with self.saved_context(): self.text(s, x_start, y_start, fontsize=2, color=Color.ANNOTATIONS) # subtract length of segmant from total segment length length -= (x_end - x_start + hspace + 2 * max_radius) # create remaining line to work with line_working = LineString([(x_end + hspace + 2 * max_radius, y_end), (xw_end, yw_end)]) # next segment shall be long segment_max = 1 else: # short segment can be drawn instantly x_start, y_start , x_end, y_end = line_this.bounds self.set_source_color(Color.INNER_CUT) with self.saved_context(): self.moveTo(x_start, y_start + max_radius, 0) self.edge(x_end - x_start) self.corner(-180, max_radius) self.edge(x_end - x_start) self.corner(-180, max_radius) if self.debug and False: # enable to debug short lines self.set_source_color(Color.ANNOTATIONS) with self.saved_context(): self.moveTo(x_start, y_start, 0) self.edge(x_end - x_start) s = "short - y: " + str(round(y, 1)) + " xs: " + str(round(x_start, 1)) + " xe: " + str(round(x_end, 1)) + " l: " + str(round(line_this.length, 1)) + " max: " + str(round(segment_length[segment_max], 1)) with self.saved_context(): self.text(s, x_start, y_start, fontsize=2, color=Color.ANNOTATIONS) segment_max = 1 # short segment shall be skipped if a short segment shall start the line if segment_toggle: segment_max = 0 y += step_y else: raise ValueError("fillHoles - unknown hole pattern: %s)" % pattern) def hexHolesRectangle(self, x, y, settings=None, skip=None): """Fills a rectangle with holes in a hex pattern. Settings have: r : radius of holes b : space between holes style : what types of holes (not yet implemented) :param x: width :param y: height :param settings: (Default value = None) :param skip: (Default value = None) function to check if hole should be present gets x, y, r, b, posx, posy """ if settings is None: settings = self.hexHolesSettings r, b, style = settings.diameter/2, settings.distance, settings.style w = r + b / 2.0 dist = w * math.cos(math.pi / 6.0) # how many half circles do fit cx = int((x - 2 * r) // (w)) + 2 cy = int((y - 2 * r) // (dist)) + 2 # what's left on the sides lx = (x - (2 * r + (cx - 2) * w)) / 2.0 ly = (y - (2 * r + ((cy // 2) * 2) * dist - 2 * dist)) / 2.0 for i in range(cy // 2): for j in range((cx - (i % 2)) // 2): px = 2 * j * w + r + lx py = i * 2 * dist + r + ly if i % 2: px += w if skip and skip(x, y, r, b, px, py): continue self.hole(px, py, r=r) def __skipcircle(self, x, y, r, b, posx, posy): cx, cy = x / 2.0, y / 2.0 return (dist(posx - cx, posy - cy) > (cx - r)) def hexHolesCircle(self, d, settings=None): """ Fill circle with holes in a hex pattern :param d: diameter of the circle :param settings: (Default value = None) """ d2 = d / 2.0 self.hexHolesRectangle(d, d, settings=settings, skip=self.__skipcircle) def hexHolesPlate(self, x, y, rc, settings=None): """ Fill a plate with holes in a hex pattern :param x: width :param y: height :param rc: radius of the corners :param settings: (Default value = None) """ def skip(x, y, r, b, posx, posy): """ :param x: :param y: :param r: :param b: :param posx: :param posy: """ posx = abs(posx - (x / 2.0)) posy = abs(posy - (y / 2.0)) wx = 0.5 * x - rc - r wy = 0.5 * y - rc - r if (posx <= wx) or (posy <= wx): return 0 return dist(posx - wx, posy - wy) > rc self.hexHolesRectangle(x, y, settings, skip=skip) def hexHolesHex(self, h, settings=None, grow=None): """ Fill a hexagon with holes in a hex pattern :param h: height :param settings: (Default value = None) :param grow: (Default value = None) """ if settings is None: settings = self.hexHolesSettings r, b, style = settings.diameter/2, settings.distance, settings.style self.ctx.rectangle(0, 0, h, h) w = r + b / 2.0 dist = w * math.cos(math.pi / 6.0) cy = 2 * int((h - 4 * dist) // (4 * w)) + 1 leftover = h - 2 * r - (cy - 1) * 2 * r if grow == 'space ': b += leftover / (cy - 1) / 2 # recalculate with adjusted values w = r + b / 2.0 dist = w * math.cos(math.pi / 6.0) self.moveTo(h / 2.0 - (cy // 2) * 2 * w, h / 2.0) for j in range(cy): self.hole(2 * j * w, 0, r) for i in range(1, cy / 2 + 1): for j in range(cy - i): self.hole(j * 2 * w + i * w, i * 2 * dist, r) self.hole(j * 2 * w + i * w, -i * 2 * dist, r) def flex2D(self, x, y, width=1): """ Fill a rectangle with a pattern allowing bending in both axis :param x: width :param y: height :param width: width between the lines of the pattern in multiples of thickness """ width *= self.thickness cx = int(x // (5 * width)) cy = int(y // (5 * width)) if cx == 0 or cy == 0: return wx = x / 5. / cx wy = y / 5. / cy armx = (4 * wx, 90, 4 * wy, 90, 2 * wx, 90, 2 * wy) army = (4 * wy, 90, 4 * wx, 90, 2 * wy, 90, 2 * wx) for i in range(cx): for j in range(cy): if (i + j) % 2: with self.saved_context(): self.moveTo((5 * i) * wx, (5 * j) * wy) self.polyline(*armx) with self.saved_context(): self.moveTo((5 * i + 5) * wx, (5 * j + 5) * wy, -180) self.polyline(*armx) else: with self.saved_context(): self.moveTo((5 * i + 5) * wx, (5 * j) * wy, 90) self.polyline(*army) with self.saved_context(): self.moveTo((5 * i) * wx, (5 * j + 5) * wy, -90) self.polyline(*army) self.ctx.stroke() @restore def fingerHoleRectangle(self, dx, dy, x=0., y=0., angle=0., outside=False): """ Place finger holes for four walls - attaching a box on this plane :param dx: size in x direction :param dy: size in y direction :param x: x position of the center :param y: y position of the center :param angle: angle in which the rectangle is placed :param outside: measure size from the outside of the walls - not the inside """ self.moveTo(x, y, angle) d = 0.5*self.thickness if outside: d = -d self.fingerHolesAt(dx/2+d, -dy/2, dy, 90) self.fingerHolesAt(-dx/2-d, -dy/2, dy, 90) self.fingerHolesAt(-dx/2, -dy/2-d, dx, 0) self.fingerHolesAt(-dx/2, dy/2+d, dx, 0) ################################################## ### parts ################################################## def _splitWall(self, pieces, side): """helper for roundedPlate and surroundingWall figures out what sides to split """ return [ (False, False, False, False, True), (True, False, False, False, True), (True, False, True, False, True), (True, True, True, False, True), (True, True, True, True, True), ][pieces][side] def roundedPlate( self, x, y, r, edge="f", callback=None, holesMargin=None, holesSettings=None, bedBolts=None, bedBoltSettings=None, wallpieces=1, extend_corners=True, move=None, label=None, ): """Plate with rounded corner fitting to .surroundingWall() For the callbacks the sides are counted depending on wallpieces :param x: width :param y: height :param r: radius of the corners :param edge: :param callback: (Default value = None) :param holesMargin: (Default value = None) set to get hex holes :param holesSettings: (Default value = None) :param bedBolts: (Default value = None) :param bedBoltSettings: (Default value = None) :param wallpieces: (Default value = 1) # of separate surrounding walls :param extend_corners: (Default value = True) have corners outset with the edges :param move: (Default value = None) :param label: (Default value = None) """ corner_holes = True t = self.thickness edge = self.edges.get(edge, edge) overallwidth = x + 2 * edge.spacing() overallheight = y + 2 * edge.spacing() if self.move(overallwidth, overallheight, move, before=True): return lx = x - 2*r ly = y - 2*r self.moveTo(edge.spacing(), edge.margin()) self.moveTo(r, 0) if wallpieces > 4: wallpieces = 4 wallcount = 0 for nr, l in enumerate((lx, ly, lx, ly)): if self._splitWall(wallpieces, nr): for i in range(2): self.cc(callback, wallcount, y=edge.startwidth()+self.burn) edge(l / 2.0 , bedBolts=self.getEntry(bedBolts, wallcount), bedBoltSettings=self.getEntry(bedBoltSettings, wallcount)) wallcount += 1 else: self.cc(callback, wallcount, y=edge.startwidth()+self.burn) edge(l, bedBolts=self.getEntry(bedBolts, wallcount), bedBoltSettings=self.getEntry(bedBoltSettings, wallcount)) wallcount += 1 if extend_corners: if corner_holes: with self.saved_context(): self.moveTo(0, edge.startwidth()) self.polyline(0, (90, r), 0, -90, t, -90, 0, (-90, r+t), 0, -90, t, -90, 0,) self.ctx.stroke() self.corner(90, r + edge.startwidth()) else: self.step(-edge.endwidth()) self.corner(90, r) self.step(edge.startwidth()) self.ctx.restore() self.ctx.save() self.moveTo(edge.margin(), edge.margin()) if holesMargin is not None: self.moveTo(holesMargin, holesMargin) if r > holesMargin: r -= holesMargin else: r = 0 self.hexHolesPlate(x - 2 * holesMargin, y - 2 * holesMargin, r, settings=holesSettings) self.move(overallwidth, overallheight, move, label=label) def surroundingWallPiece(self, cbnr, x, y, r, pieces=1): """ Return the geometry of a pices of surroundingWall with the given callback number. :param cbnr: number of the callback corresponding to this part of the wall :param x: width of matching roundedPlate :param y: height of matching roundedPlate :param r: corner radius of matching roundedPlate :param pieces: (Default value = 1) number of separate pieces :return: (left, length, right) left and right are Booleans that are True if the start or end of the wall is on that side. """ if pieces<=2 and (y - 2 * r) < 1E-3: # remove zero length y sides sides = (x/2-r, x - 2*r, x - 2*r) if pieces > 0: # hack to get the right splits pieces += 1 else: sides = (x/2-r, y - 2*r, x - 2*r, y - 2*r, x - 2*r) wallcount = 0 for nr, l in enumerate(sides): if self._splitWall(pieces, nr) and nr > 0: if wallcount == cbnr: return (False, l/2, True) wallcount += 1 if wallcount == cbnr: return (True, l/2, False) wallcount += 1 else: if wallcount == cbnr: return (False, l, False) wallcount += 1 return (False, 0.0, False) def surroundingWall(self, x, y, r, h, bottom='e', top='e', left="D", right="d", pieces=1, extend_corners=True, callback=None, move=None): """ Wall(s) with flex filing around a roundedPlate() For the callbacks the sides are counted depending on pieces :param x: width of matching roundedPlate :param y: height of matching roundedPlate :param r: corner radius of matching roundedPlate :param h: inner height of the wall (without edges) :param bottom: (Default value = 'e') Edge type :param top: (Default value = 'e') Edge type :param left: (Default value = 'D') left edge(s) :param right: (Default value = 'd') right edge(s) :param pieces: (Default value = 1) number of separate pieces :param callback: (Default value = None) :param move: (Default value = None) """ t = self.thickness c4 = (r + self.burn) * math.pi * 0.5 # circumference of quarter circle c4 = c4 / self.edges["X"].settings.stretch top = self.edges.get(top, top) bottom = self.edges.get(bottom, bottom) left = self.edges.get(left, left) right = self.edges.get(right, right) # XXX assumes startwidth == endwidth if extend_corners: topwidth = t bottomwidth = t else: topwidth = top.startwidth() bottomwidth = bottom.startwidth() overallwidth = 2*x + 2*y - 8*r + 4*c4 + (self.edges["d"].spacing() + self.edges["D"].spacing() + self.spacing) * pieces overallheight = h + max(t, top.spacing()) + max(t, bottom.spacing()) if self.move(overallwidth, overallheight, move, before=True): return self.moveTo(left.spacing(), bottom.margin()) wallcount = 0 tops = [] # edges needed on the top for this wall segment if pieces<=2 and (y - 2 * r) < 1E-3: # remove zero length y sides c4 *= 2 sides = (x/2-r, x - 2*r, x - 2*r) if pieces > 0: # hack to get the right splits pieces += 1 else: sides = (x/2-r, y - 2*r, x - 2*r, y - 2*r, x - 2*r) for nr, l in enumerate(sides): if self._splitWall(pieces, nr) and nr > 0: self.cc(callback, wallcount, y=bottomwidth + self.burn) wallcount += 1 bottom(l / 2.) tops.append(l / 2.) # complete wall segment with self.saved_context(): self.edgeCorner(bottom, right, 90) right(h) self.edgeCorner(right, top, 90) for n, d in enumerate(reversed(tops)): if n % 2: # flex self.step(topwidth-top.endwidth()) self.edge(d) self.step(top.startwidth()-topwidth) else: top(d) self.edgeCorner(top, left, 90) left(h) self.edgeCorner(left, bottom, 90) if nr == len(sides) - 1: break # start new wall segment tops = [] self.moveTo(right.margin() + left.margin() + self.spacing) self.cc(callback, wallcount, y=bottomwidth + self.burn) wallcount += 1 bottom(l / 2.) tops.append(l / 2.) else: self.cc(callback, wallcount, y=bottomwidth + self.burn) wallcount += 1 bottom(l) tops.append(l) self.step(bottomwidth-bottom.endwidth()) self.edges["X"](c4, h + topwidth + bottomwidth) self.step(bottom.startwidth()-bottomwidth) tops.append(c4) self.move(overallwidth, overallheight, move) def rectangularWall(self, x, y, edges="eeee", ignore_widths=[], holesMargin=None, holesSettings=None, bedBolts=None, bedBoltSettings=None, callback=None, move=None, label=""): """ Rectangular wall for all kind of box like objects :param x: width :param y: height :param edges: (Default value = "eeee") bottom, right, top, left :param ignore_widths: list of edge_widths added to adjacent edge :param holesMargin: (Default value = None) :param holesSettings: (Default value = None) :param bedBolts: (Default value = None) :param bedBoltSettings: (Default value = None) :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") """ if len(edges) != 4: raise ValueError("four edges required") edges = [self.edges.get(e, e) for e in edges] edges += edges # append for wrapping around overallwidth = x + edges[-1].spacing() + edges[1].spacing() overallheight = y + edges[0].spacing() + edges[2].spacing() if self.move(overallwidth, overallheight, move, before=True): return if 7 not in ignore_widths: self.moveTo(edges[-1].spacing()) self.moveTo(0, edges[0].margin()) for i, l in enumerate((x, y, x, y)): self.cc(callback, i, y=edges[i].startwidth() + self.burn) e1, e2 = edges[i], edges[i + 1] if (2*i-1 in ignore_widths or 2*i-1+8 in ignore_widths): l += edges[i-1].endwidth() if 2*i in ignore_widths: l += edges[i+1].startwidth() e2 = self.edges["e"] if 2*i+1 in ignore_widths: e1 = self.edges["e"] edges[i](l, bedBolts=self.getEntry(bedBolts, i), bedBoltSettings=self.getEntry(bedBoltSettings, i)) self.edgeCorner(e1, e2, 90) if holesMargin is not None: self.moveTo(holesMargin, holesMargin + edges[0].startwidth()) self.hexHolesRectangle(x - 2 * holesMargin, y - 2 * holesMargin, settings=holesSettings) self.move(overallwidth, overallheight, move, label=label) def flangedWall(self, x, y, edges="FFFF", flanges=None, r=0.0, callback=None, move=None, label=""): """Rectangular wall with flanges extending the regular size This is similar to the rectangularWall but it may extend to either side. Sides with flanges may only have e, E, or F edges - the later being replaced with fingerHoles. :param x: width :param y: height :param edges: (Default value = "FFFF") bottom, right, top, left :param flanges: (Default value = None) list of width of the flanges :param r: radius of the corners of the flange :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") """ t = self.thickness if not flanges: flanges = [0.0] * 4 while len(flanges) < 4: flanges.append(0.0) edges = [self.edges.get(e, e) for e in edges] # double to allow looping around edges = edges + edges flanges = flanges + flanges tw = x + edges[1].spacing() + flanges[1] + edges[3].spacing() + flanges[3] th = y + edges[0].spacing() + flanges[0] + edges[2].spacing() + flanges[2] if self.move(tw, th, move, True): return rl = min(r, max(flanges[-1], flanges[0])) self.moveTo(rl + edges[-1].margin(), edges[0].margin()) for i in range(4): l = y if i % 2 else x rl = min(r, max(flanges[i-1], flanges[i])) rr = min(r, max(flanges[i], flanges[i+1])) self.cc(callback, i, x=-rl) if flanges[i]: if edges[i] is self.edges["F"] or edges[i] is self.edges["h"]: self.fingerHolesAt(flanges[i-1]+edges[i-1].endwidth()-rl, 0.5*t+flanges[i], l, angle=0) self.edge(l+flanges[i-1]+flanges[i+1]+edges[i-1].endwidth()+edges[i+1].startwidth()-rl-rr) else: self.edge(flanges[i-1]+edges[i-1].endwidth()-rl) edges[i](l) self.edge(flanges[i+1]+edges[i+1].startwidth()-rr) self.corner(90, rr) self.move(tw, th, move, label=label) def rectangularTriangle(self, x, y, edges="eee", r=0.0, num=1, bedBolts=None, bedBoltSettings=None, callback=None, move=None, label=""): """ Rectangular triangular wall :param x: width :param y: height :param edges: (Default value = "eee") bottom, right[, diagonal] :param r: radius towards the hypotenuse :param num: (Default value = 1) number of triangles :param bedBolts: (Default value = None) :param bedBoltSettings: (Default value = None) :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") """ edges = [self.edges.get(e, e) for e in edges] if len(edges) == 2: edges.append(self.edges["e"]) if len(edges) != 3: raise ValueError("two or three edges required") r = min(r, x, y) a = math.atan2(y-r, float(x-r)) alpha = math.degrees(a) if a > 0: width = x + (edges[-1].spacing()+self.spacing)/math.sin(a) + edges[1].spacing() + self.spacing else: width = x + (edges[-1].spacing()+self.spacing) + edges[1].spacing() + self.spacing height = y + edges[0].spacing() + edges[2].spacing() * math.cos(a) + 2* self.spacing + self.spacing if num > 1: width = 2*width - x + r - self.spacing dx = width - x - edges[1].spacing() - self.spacing / 2 dy = edges[0].margin() + self.spacing / 2 overallwidth = width * (num // 2 + num % 2) - self.spacing overallheight = height - self.spacing if self.move(overallwidth, overallheight, move, before=True): return if self.debug: self.rectangularHole(width/2., height/2., width, height) self.moveTo(dx - self.spacing / 2, dy - self.spacing / 2) for n in range(num): for i, l in enumerate((x, y)): self.cc(callback, i, y=edges[i].startwidth() + self.burn) edges[i](l, bedBolts=self.getEntry(bedBolts, i), bedBoltSettings=self.getEntry(bedBoltSettings, i)) if i==0: self.edgeCorner(edges[i], edges[i + 1], 90) self.edgeCorner(edges[i], "e", 90) self.corner(alpha, r) self.cc(callback, 2) self.step(edges[2].startwidth()) edges[2](((x-r)**2+(y-r)**2)**0.5) self.step(-edges[2].endwidth()) self.corner(90-alpha, r) self.edge(edges[0].startwidth()) self.corner(90) self.ctx.stroke() self.moveTo(width-2*dx, height - 2*dy, 180) if n % 2: self.moveTo(width) self.move(overallwidth, overallheight, move, label=label) def trapezoidWall(self, w, h0, h1, edges="eeee", callback=None, move=None, label=""): """ Rectangular trapezoidal wall :param w: width :param h0: left height :param h1: right height :param edges: (Default value = "eee") bottom, right, left :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") """ edges = [self.edges.get(e, e) for e in edges] overallwidth = w + edges[-1].spacing() + edges[1].spacing() overallheight = max(h0, h1) + edges[0].spacing() if self.move(overallwidth, overallheight, move, before=True): return a = math.degrees(math.atan((h1-h0)/w)) l = ((h0-h1)**2+w**2)**0.5 self.moveTo(edges[-1].spacing(), edges[0].margin()) self.cc(callback, 0, y=edges[0].startwidth()) edges[0](w) self.edgeCorner(edges[0], edges[1], 90) self.cc(callback, 1, y=edges[1].startwidth()) edges[1](h1) self.edgeCorner(edges[1], self.edges["e"], 90) self.corner(a) self.cc(callback, 2) edges[2](l) self.corner(-a) self.edgeCorner(self.edges["e"], edges[-1], 90) self.cc(callback, 3, y=edges[-1].startwidth()) edges[3](h0) self.edgeCorner(edges[-1], edges[0], 90) self.move(overallwidth, overallheight, move, label=label) def trapezoidSideWall(self, w, h0, h1, edges="eeee", radius=0.0, callback=None, move=None, label=""): """ Rectangular trapezoidal wall :param w: width :param h0: left height :param h1: right height :param edges: (Default value = "eeee") bottom, right, left :param radius: (Default value = 0.0) radius of upper corners :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") """ edges = [self.edges.get(e, e) for e in edges] overallwidth = w + edges[-1].spacing() + edges[1].spacing() overallheight = max(h0, h1) + edges[0].spacing() if self.move(overallwidth, overallheight, move, before=True): return r = min(radius, abs(h0-h1)) ws = w-r if h0 > h1: ws += edges[1].endwidth() else: ws += edges[3].startwidth() hs = abs(h1-h0) - r a = math.degrees(math.atan(hs/ws)) l = (ws**2+hs**2)**0.5 self.moveTo(edges[-1].spacing(), edges[0].margin()) self.cc(callback, 0, y=edges[0].startwidth()) edges[0](w) self.edgeCorner(edges[0], edges[1], 90) self.cc(callback, 1, y=edges[1].startwidth()) edges[1](h1) if h0 > h1: self.polyline(0, (90-a, r)) self.cc(callback, 2) edges[2](l) self.polyline(0, (a, r), edges[3].startwidth(), 90) else: self.polyline(0, 90, edges[1].endwidth(), (a, r)) self.cc(callback, 2) edges[2](l) self.polyline(0, (90-a, r)) self.cc(callback, 3, y=edges[-1].startwidth()) edges[3](h0) self.edgeCorner(edges[-1], edges[0], 90) self.move(overallwidth, overallheight, move, label=label) ### polygonWall and friends def _polygonWallExtend(self, borders, edges, close=False): posx, posy = 0, 0 ext = [ 0.0 ] * 4 angle = 0 def checkpoint(ext, x, y): ext[0] = min(ext[0], x) ext[1] = min(ext[1], y) ext[2] = max(ext[2], x) ext[3] = max(ext[3], y) # trace edge margins nborders = [] for i, val in enumerate(borders): if i % 2: nborders.append(val) else: edge = edges[(i//2)%len(edges)] margin = edge.margin() try: l = val[0] except TypeError: l = val if margin: nborders.extend([0.0, -90, margin, 90, l, 90, margin, -90, 0.0]) else: nborders.append(val) borders = nborders for i in range(len(borders)): if i % 2: try: a, r = borders[i] except TypeError: angle = (angle + borders[i]) % 360 continue if a > 0: centerx = posx + r * math.cos(math.radians(angle+90)) centery = posy + r * math.sin(math.radians(angle+90)) else: centerx = posx + r * math.cos(math.radians(angle-90)) centery = posy + r * math.sin(math.radians(angle-90)) for direction in (0, 90, 180, 270): if (a > 0 and angle <= direction and (angle + a) % 360 >= direction): direction -= 90 elif (a < 0 and angle >= direction and (angle + a) % 360 <= direction): direction -= 90 else: continue checkpoint(ext, centerx + r * math.cos(math.radians(direction)), centery + r * math.sin(math.radians(direction))) #print("%4s %4s %4s %f %f" % (angle, direction+90, angle+a, centerx + r * math.cos(math.radians(direction)), centery + r * math.sin(math.radians(direction)))) angle = (angle + a) % 360 if a > 0: posx = centerx + r * math.cos(math.radians(angle-90)) posy = centery + r * math.sin(math.radians(angle-90)) else: posx = centerx + r * math.cos(math.radians(angle+90)) posy = centery + r * math.sin(math.radians(angle+90)) else: posx += borders[i] * math.cos(math.radians(angle)) posy += borders[i] * math.sin(math.radians(angle)) checkpoint(ext, posx, posy) return ext def _closePolygon(self, borders): posx, posy = 0, 0 angle = 0.0 if borders and borders[-1] is not None: return borders borders = borders[:-1] for i in range(len(borders)): if i % 2: try: a, r = borders[i] except TypeError: angle = (angle + borders[i]) % 360 continue if a > 0: centerx = posx + r * math.cos(math.radians(angle+90)) centery = posy + r * math.sin(math.radians(angle+90)) else: centerx = posx + r * math.cos(math.radians(angle-90)) centery = posy + r * math.sin(math.radians(angle-90)) angle = (angle + a) % 360 if a > 0: posx = centerx + r * math.cos(math.radians(angle-90)) posy = centery + r * math.sin(math.radians(angle-90)) else: posx = centerx + r * math.cos(math.radians(angle+90)) posy = centery + r * math.sin(math.radians(angle+90)) else: posx += borders[i] * math.cos(math.radians(angle)) posy += borders[i] * math.sin(math.radians(angle)) if len(borders) % 2 == 0: borders.append(0.0) a = math.degrees(math.atan2(-posy, -posx)) #print(a, angle, a - angle) borders.append((a - angle + 360) % 360) borders.append((posx**2 + posy**2)**.5) borders.append(-a) #print(borders) return borders def polygonWall(self, borders, edge="f", turtle=False, correct_corners=True, callback=None, move=None, label=""): """ Polygon wall for all kind of multi-edged objects :param borders: array of distance and angles to draw :param edge: (Default value = "f") Edges to apply. If the array of borders contains more segments that edges, the edge will wrap. Only edge types without start and end width supported for now. :param turtle: (Default value = False) :param correct_corners: (Default value = True) :param callback: (Default value = None) :param move: (Default value = None) :param label: rendered to identify parts, it is not meant to be cut or etched (Default value = "") borders is alternating between length of the edge and angle of the corner. For now neither tabs nor radii are supported. None at the end closes the polygon. """ try: edges = [self.edges.get(e, e) for e in edge] except TypeError: edges = [self.edges.get(edge, edge)] t = self.thickness # XXX edge.margin() borders = self._closePolygon(borders) minx, miny, maxx, maxy = self._polygonWallExtend(borders, edges) tw, th = maxx - minx, maxy - miny if not turtle: if self.move(tw, th, move, True): return self.moveTo(-minx, -miny) length_correction = 0. for i in range(0, len(borders), 2): self.cc(callback, i // 2) self.edge(length_correction) l = borders[i] - length_correction next_angle = borders[i+1] if (correct_corners and isinstance(next_angle, (int, float)) and next_angle < 0): length_correction = t * math.tan(math.radians(-next_angle / 2)) else: length_correction = 0.0 l -= length_correction edge = edges[(i//2)%len(edges)] edge(l) self.edge(length_correction) self.corner(next_angle, tabs=1) if not turtle: self.move(tw, th, move, label=label) @restore def polygonWalls(self, borders, h, bottom="F", top="F", symmetrical=True): if not borders: return borders = self._closePolygon(borders) bottom = self.edges.get(bottom, bottom) top = self.edges.get(top, top) t = self.thickness # XXX edge.margin() leftsettings = copy.deepcopy(self.edges["f"].settings) lf, lF, lh = leftsettings.edgeObjects(self, add=False) rightsettings = copy.deepcopy(self.edges["f"].settings) rf, rF, rh = rightsettings.edgeObjects(self, add=False) length_correction = 0. angle = borders[-1] i = 0 part_cnt = 0 self.moveTo(0, bottom.margin()) while i < len(borders): if symmetrical: if part_cnt % 2: left, right = lf, rf else: # last part of an uneven lot if (part_cnt == (len(borders)//2)-1): left, right = lF, rf else: left, right = lF, rF else: left, right = lf, rF top_lengths = [] top_edges = [] if angle == 0: left = self.edges["d"] leftsettings.setValues(self.thickness, angle=angle) self.moveTo(left.spacing() + self.spacing, 0) l = borders[i] - length_correction angle = borders[i+1] while isinstance(angle, (tuple, list)): bottom(l) angle, radius = angle lr = abs(math.radians(angle) * radius) self.edges["X"](lr, h + 2*t) # XXX top_lengths.append(l) top_lengths.append(lr) top_edges.append(top) top_edges.append("E") i += 2 l = borders[i] angle = borders[i+1] rightsettings.setValues(self.thickness, angle=angle) if angle < 0: length_correction = t * math.tan(math.radians(-angle / 2)) else: length_correction = 0.0 if angle == 0: right = self.edges["D"] l -= length_correction bottom(l) top_lengths.append(l) top_edges.append(top) with self.saved_context(): self.edgeCorner(bottom, right, 90) right(h) self.edgeCorner(right, top, 90) top_edges.reverse() top_lengths.reverse() edges.CompoundEdge(self, top_edges, top_lengths)(sum(top_lengths)) self.edgeCorner(top, left, 90) left(h) self.edgeCorner(left, bottom, 90) self.ctx.stroke() self.moveTo(right.spacing() + self.spacing) part_cnt += 1 i += 2 ################################################## ### Place Parts ################################################## def partsMatrix(self, n, width, move, part, *l, **kw): """place many of the same part :param n: number of parts :param width: number of parts in a row (0 for same as n) :param move: (Default value = "") :param part: callable that draws a part and knows move param :param l: params for part :param kw: keyword params for part """ if n <= 0: return if not width: width = n rows = n//width + (1 if n % width else 0) if not move: move = "" move = move.split() #move down / left before for m in move: if m == "left": kw["move"] = "left only" for i in range(width): part(*l, **kw) if m == "down": kw["move"] = "down only" for i in range(rows): part(*l, **kw) # draw matrix for i in range(rows): with self.saved_context(): for j in range(width): if "only" in move: break if width*i+j >= n: break kw["move"] = "right" part(*l, **kw) kw["move"] = "up only" part(*l, **kw) # Move back down if "up" not in move: kw["move"] = "down only" for i in range(rows): part(*l, **kw) # Move right if "right" in move: kw["move"] = "right only" for i in range(width): part(*l, **kw) def mirrorX(self, f, offset=0.0): """Wrap a function to draw mirrored at the y axis :param f: function to wrap :param offset: (default value = 0.0) axis to mirror at """ def r(): self.moveTo(offset, 0) with self.saved_context(): self.ctx.scale(-1, 1) f() return r def mirrorY(self, f, offset=0.0): """Wrap a function to draw mirrored at the x axis :param f: function to wrap :param offset: (default value = 0.0) axis to mirror at """ def r(): self.moveTo(0, offset) with self.saved_context(): self.ctx.scale(1, -1) f() return r
112,686
Python
.py
2,605
30.735893
236
0.509385
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,539
lids.py
florianfesti_boxes/boxes/lids.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import annotations import math from typing import Any, Callable import boxes from boxes import Boxes, edges class LidSettings(edges.Settings): """Settings for the Lid Values: * absolute * style : "none" : type of lid to create * handle : "none" : type of handle * relative (in multiples of thickness) * height : 4.0 : height of the brim (if any) * play : 0.1 : play when sliding the lid on (if applicable) * handle_height : 8.0 : height of the handle (if applicable) """ absolute_params = { "style": ("none", "flat", "chest", "overthetop", "ontop"), "handle": ("none", "long_rounded", "long_trapezoid", "long_doublerounded", "knob"), } relative_params = { "height": 4.0, "play": 0.1, "handle_height": 8.0, } class Lid: def __init__(self, boxes, settings: LidSettings) -> None: self.boxes = boxes self.settings = settings def __getattr__(self, name: str) -> Any: """Hack for using unaltered code form Boxes class""" if hasattr(self.settings, name): return getattr(self.settings, name) return getattr(self.boxes, name) def __call__(self, x: float, y: float, edge=None) -> bool: t = self.thickness style = self.settings.style height = self.height if style == "flat": self.rectangularWall(x, y, "eeee", callback=[self.handleCB(x, y)], move="up", label="lid bottom") self.rectangularWall(x, y, "EEEE", callback=[self.handleCB(x, y)], move="up", label="lid top") elif style == "chest": self.chestSide(x, move="right", label="lid right") self.chestSide(x, move="up", label="lid left") self.chestSide(x, move="left only", label="invisible") self.chestTop(x, y, callback=[None, self.handleCB(x, 3*t)], move="up", label="lid top") elif style in ("overthetop", "ontop"): x2 = x y2 = y b = { "Š": "š", "S": "š", }.get(edge, "e") if style == "overthetop": x2 += 2*t + self.play y2 += 2*t + self.play self.rectangularWall(x2, y2, "ffff", callback=[self.handleCB(x2, y2)], move="up") self.rectangularWall(x2, self.height, b +"FFF", ignore_widths=[1, 2, 5, 6], move="up") self.rectangularWall(x2, self.height, b + "FFF", ignore_widths=[1, 2, 5, 6], move="up") self.rectangularWall(y2, self.height, b + "fFf", ignore_widths=[1, 2, 5, 6], move="up") self.rectangularWall(y2, self.height, b + "fFf", ignore_widths=[1, 2, 5, 6], move="up") if style == "ontop": for _ in range(4): self.polygonWall( (2*t, (90, t), t+self.height, 90, 4*t, 90, t+self.height, (90, t)), "e", move="up") else: return False self.handleParts(x, y) return True ###################################################################### ### Handles ###################################################################### def handleCB(self, x: float, y: float) -> Callable: t = self.thickness def cb() -> None: if self.handle.startswith("long"): self.rectangularHole(x/2, y/2, x/2, t) elif self.handle.startswith("knob"): h = v = 3 * t # adjust for different styles self.moveTo((x - t) / 2 + self.burn, (y - t) / 2 + self.burn, 180) self.ctx.stroke() with self.saved_context(): self.set_source_color(boxes.Color.INNER_CUT) for l in (h, v, h, v): self.polyline(l, -90, t, -90, l, 90) self.ctx.stroke() return cb def longHandle(self, x:float, y: float, style="long_rounded", move=None) -> None: t = self.settings.thickness hh = self.handle_height tw, th = x/2 + 2*t, self.handle_height + 2*t if self.move(tw, th, move, True): return self.moveTo(0.5*t) poly = [(90, t/2), t/2, 90, t, -90] if style == "long_rounded": r = min(hh/2, x/4) poly += [t + hh - r, (90, r)] l = x/2 - 2*r elif style == "long_trapezoid": poly += [t, (45, t), (hh - t) * 2**.5, (45, t)] l = x/2 - 2 * hh elif style == "long_doublerounded": poly += [t, 90, 0, (-90, hh /2), 0, (90, hh/2)] l = x/2 - 2*hh poly = [x/2+t] + poly + [l] + list(reversed(poly)) self.polyline(*poly) self.move(tw, th, move) def knobHandle(self, x: float, y: float, style, move=None) -> None: t = self.settings.thickness hh = self.handle_height tw, th = 2 * 7 * t + self.spacing, self.handle_height + 2*t if self.move(tw, th, move, True): return poly = [(90, t/2), t/2, 90, t/2, -90] poly += [hh - 2*t, (90, 3*t)] for bottom, top in (([3*t, 90, 2*t + hh/2, -90, t, -90, hh/2 + 2*t, 90, 3*t], [t]), ([7*t], [0, 90, hh/2, -90, t, -90, hh/2, 90, 0])) : self.moveTo(0.5*t) p = bottom + poly + top + list(reversed(poly)) self.polyline(*p) self.moveTo(tw/2 + self.spacing) self.move(tw, th, move) def handleParts(self, x: float, y: float) -> None: if self.handle.startswith("long"): self.longHandle(x, y, self.handle, move="up") elif self.handle.startswith("knob"): self.knobHandle(x, y, self.handle, move="up") ###################################################################### ### Chest Lid ###################################################################### def getChestR(self, x: float, angle: float = 0) -> float: t = self.thickness d = x - 2*math.sin(math.radians(angle)) * (3*t) r = d / 2.0 / math.cos(math.radians(angle)) return r def chestSide(self, x: float, angle: float = 0, move="", label: str = "") -> None: if "a" not in self.edges: s = edges.FingerJointSettings(self.thickness, True, finger=1.0, space=1.0) s.edgeObjects(self, "aA.") t = self.thickness r = self.getChestR(x, angle) if self.move(x+2*t, 0.5*x+3*t, move, True, label=label): return self.moveTo(t, 0) self.edge(x) self.corner(90+angle) self.edges["a"](3*t) self.corner(180-2*angle, r) self.edges["a"](3*t) self.corner(90+angle) self.move(x+2*t, 0.5*x+3*t, move, False, label=label) def chestTop(self, x: float, y: float, angle: float = 0, callback=None, move=None, label: str = "") -> None: if "a" not in self.edges: s = edges.FingerJointSettings(self.thickness, True, finger=1.0, space=1.0) s.edgeObjects(self, "aA.") t = self.thickness l = math.radians(180-2*angle) * self.getChestR(x, angle) tw = l + 6*t th = y+2*t if self.move(tw, th, move, True, label=label): return self.cc(callback, 0, self.edges["A"].startwidth()+self.burn) self.edges["A"](3*t) self.edges["X"](l, y+2*t) self.edges["A"](3*t) self.corner(90) self.cc(callback, 1) self.edge(y+2*t) self.corner(90) self.cc(callback, 2, self.edges["A"].startwidth()+self.burn) self.edges["A"](3*t) self.edge(l) self.edges["A"](3*t) self.corner(90) self.cc(callback, 3) self.edge(y+2*t) self.corner(90) self.move(tw, th, move, label=label) class _TopEdge(Boxes): def addTopEdgeSettings(self, fingerjoint={}, stackable={}, hinge={}, cabinethinge={}, slideonlid={}, click={}, roundedtriangle={}, mounting={}, handle={}): self.addSettingsArgs(edges.FingerJointSettings, **fingerjoint) self.addSettingsArgs(edges.StackableSettings, **stackable) self.addSettingsArgs(edges.HingeSettings, **hinge) self.addSettingsArgs(edges.CabinetHingeSettings, **cabinethinge) self.addSettingsArgs(edges.SlideOnLidSettings, **slideonlid) self.addSettingsArgs(edges.ClickSettings, **click) self.addSettingsArgs(edges.RoundedTriangleEdgeSettings, **roundedtriangle) self.addSettingsArgs(edges.MountingSettings, **mounting) self.addSettingsArgs(edges.HandleEdgeSettings, **handle) def topEdges(self, top_edge): """Return top edges belonging to given main edge type as a list containing edge for left, back, right, front. """ tl = tb = tr = tf = self.edges.get(top_edge, self.edges["e"]) if tl.char == "i": tb = tf = "e" tl = "j" elif tl.char == "k": tl = tr = "e" elif tl.char == "L": tl = "M" tf = "e" tr = "N" elif tl.char == "v": tl = tr = tf = "e" elif tl.char == "t": tf = tb = "e" elif tl.char == "G": tl = tb = tr = tf = "e" if self.edges["G"].settings.side == edges.MountingSettings.PARAM_LEFT: tl = "G" elif self.edges["G"].settings.side == edges.MountingSettings.PARAM_RIGHT: tr = "G" elif self.edges["G"].settings.side == edges.MountingSettings.PARAM_FRONT: tf = "G" else: #PARAM_BACK tb = "G" elif tl.char == "y": tl = tb = tr = tf = "e" if self.edges["y"].settings.on_sides == True: tl = tr = "y" else: tb = tf = "y" elif tl.char == "Y": tl = tb = tr = tf = "h" if self.edges["Y"].settings.on_sides == True: tl = tr = "Y" else: tb = tf = "Y" return [tl, tb, tr, tf] def drawLid(self, x: float, y: float, top_edge, bedBolts=[None, None]) -> bool: d2, d3 = bedBolts if top_edge == "c": self.rectangularWall(x, y, "CCCC", bedBolts=[d2, d3, d2, d3], move="up", label="top") elif top_edge == "f": self.rectangularWall(x, y, "FFFF", move="up", label="top") elif top_edge in "FhŠY": self.rectangularWall(x, y, "ffff", move="up", label="top") elif top_edge == "L": self.rectangularWall(x, y, "Enlm", move="up", label="lid top") elif top_edge == "i": self.rectangularWall(x, y, "EJeI", move="up", label="lid top") elif top_edge == "k": outset = self.edges["k"].settings.outset self.edges["k"].settings.setValues(self.thickness, outset=True) lx = x/2.0-0.1*self.thickness self.edges['k'].settings.setValues(self.thickness, grip_length=5) self.rectangularWall(lx, y, "IeJe", move="right", label="lid top left") self.rectangularWall(lx, y, "IeJe", move="mirror up", label="lid top right") self.rectangularWall(lx, y, "IeJe", move="left only", label="invisible") self.edges["k"].settings.setValues(self.thickness, outset=outset) elif top_edge == "v": self.rectangularWall(x, y, "VEEE", move="up", label="lid top") self.edges["v"].parts(move="up") else: return False return True
12,747
Python
.py
288
33.017361
112
0.510237
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,540
servos.py
florianfesti_boxes/boxes/servos.py
from __future__ import annotations import math import boxes.vectors class EyeEdge(boxes.edges.FingerHoleEdge): char = "m" def __init__(self, boxes, servo, fingerHoles=None, driven: bool = False, outset: bool = False, **kw) -> None: self.servo = servo self.outset = outset self.driven = driven super().__init__(boxes, fingerHoles, **kw) def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): t = self.fingerHoles.settings.thickness dist = self.fingerHoles.settings.edge_width pos_axle = self.servo.hinge_depth() self.ctx.save() self.hole(length / 2.0, -pos_axle, self.servo.axle / 2.0 if self.driven else self.servo.servo_axle / 2.0) if self.outset: self.fingerHoles(t, self.thickness / 2, length - 2 * t, 0) else: self.fingerHoles(0, self.thickness / 2, length, 0) self.ctx.restore() r = self.servo.servo_axle * 2 a, l = boxes.vectors.tangent(length / 2, pos_axle, r) angle = math.degrees(a) self.polyline(0, -angle, l, (2 * angle, r), l, -angle, 0) def startwidth(self) -> float: return self.fingerHoles.settings.thickness def margin(self) -> float: return self.servo.hinge_depth() + self.fingerHoles.settings.thickness + self.servo.servo_axle * 2 def buildEdges(boxes, servo, chars: str = "mMnN"): result = {} for n, char in enumerate(chars): e = EyeEdge(boxes, servo, outset=(n < 2), driven=((n % 2) == 1)) e.char = char result[char] = e return result class ServoArg: def __init__(self, includeNone: bool = False) -> None: self.servos = ["Servo9g"] if includeNone: self.servos[0:0] = ["none"] def __call__(self, arg) -> str: return str(arg) def choices(self) -> list[str]: return [name for name in self.servos] def html(self, name: str, default: str, translate) -> str: options = "\n".join("""<option value="{}"{}>{}</option>""".format(name, ' selected="selected"' if name == default else "", name) for name in self.servos) return f"""<select name="{name}" size="1">\n{options}</select>\n""" class Servo: def __init__(self, boxes, axle: float = 3) -> None: self.boxes = boxes self.axle = axle self._edges = buildEdges(boxes, self) def edges(self, edges): return [self._edges.get(e, e) for e in edges] class Servo9g(Servo): height: float = 22.5 length: float = 28.0 # one tab in the wall width: float = 12.0 axle_pos: float = 6.0 servo_axle: float = 4.6 # 6.9 for servo arm def top(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.hole(6, 0, 6) self.boxes.hole(12, 0, 3) def bottom(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.hole(6, 0, self.axle / 2.0) def front(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.rectangularHole(5.4, 0, 2.4, 12) self.boxes.rectangularHole(17, 0, 4, 16) def hinge_width(self) -> float: return self.height + self.boxes.thickness + 4.5 def hinge_depth(self) -> float: return self.height # XXX class Servo9gt(Servo9g): height = 35 def top(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.hole(6, 0, 6) self.boxes.hole(12, 0, 5) def bottom(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.hole(6, 0, self.axle) def front(self, x: float = 0.0, y: float = 0.0, angle: float = 90.0) -> None: self.boxes.moveTo(x, y, angle) self.boxes.rectangularHole(5.4, 0, 2.4, 12)
4,023
Python
.py
90
37.044444
161
0.591748
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,541
robot.py
florianfesti_boxes/boxes/robot.py
__all__ = [ "RobotArg", "RobotArmMM", "RobotArmMm", "RobotArmUU", "RobotArmUu", "RobotArmMu", ] class RobotArg: def __init__(self, includenone=False) -> None: self.robotarms = [ (name, globals()[name].__doc__[23:]) for name in __all__ if name.startswith("RobotArm")] if includenone: self.robotarms[0:0] = [("none", "")] def __call__(self, arg): return str(arg) def choices(self): return [name for name, descr in self.robotarms] def html(self, name, default, translate): options = "\n".join( ("""<option value="%s"%s>%s %s</option>""" % (name, ' selected="selected"' if name == default else "", name, descr) for name, descr in self.robotarms)) return f"""<select name="{name}" size="1">\n{options}</select>\n""" class _RobotArm: def __init__(self, boxes, servo, servo2=None) -> None: self.boxes = boxes self.servo = servo self.servo2 = servo2 or servo def __getattr__(self, name): """Hack for easy access of Boxes methods""" return getattr(self.boxes, name) class RobotArmMM(_RobotArm): """Robot arm segment with two parallel servos""" def __call__(self, length, move=None): t = self.thickness w = self.servo.height l = max(self.servo.length * 2, length + 2*self.servo.axle_pos) th = max(2 * t + l, 2*w + 4*t + self.spacing) tw = 5 * (w + 2*self.thickness + self.spacing) if self.move(tw, th, move, True): return self.rectangularWall(w, l, "FfFf", callback=[ lambda:self.servo.top(w/2), None, lambda:self.servo.top(w/2)], move="right") self.rectangularWall(w, l, "FfFf", callback=[ lambda:self.servo.bottom(w/2), None, lambda:self.servo.bottom(w/2)], move="right") self.rectangularWall(w, l, "FFFF", move="right") self.rectangularWall(w, l, "FFFF", move="right") self.rectangularWall(w, w, "ffff", callback=[ lambda:self.servo.front(w/2)], move="up") self.rectangularWall(w, w, "ffff", callback=[ lambda:self.servo.front(w/2)], move="") self.move(tw, th, move) class RobotArmMm(_RobotArm): """Robot arm segment with two orthogonal servos""" def __call__(self, length, move=None): t = self.thickness w = self.servo.height w2 = self.servo2.height l = max(self.servo.length * 2, length + 2*self.servo.axle_pos) th = max(2 * self.thickness + l, w + w2 + 4*t + self.spacing) tw = 5 * (max(w, w2) + 2*self.thickness + self.spacing) if self.move(tw, th, move, True): return self.rectangularWall(w2, l, "FfFf", callback=[ lambda:self.servo.top(w2/2)], move="right") self.rectangularWall(w2, l, "FfFf", callback=[ lambda:self.servo.bottom(w2/2)], move="right") self.rectangularWall(w, l, "FFFF", callback=[ None, None, lambda:self.servo2.top(w/2)], move="right") self.rectangularWall(w, l, "FFFF", callback=[ None, None, lambda:self.servo2.bottom(w/2)], move="right") self.rectangularWall(w2, w, "ffff", callback=[ lambda:self.servo.front(w2/2)], move="up") self.rectangularWall(w, w2, "ffff", callback=[ lambda:self.servo2.front(w/2)], move="") self.move(tw, th, move) class RobotArmUU(_RobotArm): """Robot arm segment with two parallel sets of hinge knuckles""" def __call__(self, length, move=None): t = self.thickness w = self.servo.hinge_width() l = max(4*self.thickness, length - 2*t - 2*self.servo.height) th = max(2 * self.servo._edges["m"].spacing() + l, 2*w + 4*t + self.spacing) tw = 5 * (w + 2*self.thickness + self.spacing) if self.move(tw, th, move, True): return iw = (0, 3, 4, 7) e = self.servo.edges self.rectangularWall(w, l, e("mFmF"), ignore_widths=iw, move="right") self.rectangularWall(w, l, e("MFMF"), ignore_widths=iw, move="right") self.rectangularWall(w, l, "FfFf", move="right") self.rectangularWall(w, l, "FfFf", move="right") self.rectangularWall(w, w, "ffff", callback=[ lambda: self.hole(w/2, w/2, 6)], move="up") self.rectangularWall(w, w, "ffff", callback=[ lambda: self.hole(w/2, w/2, 6)], move="") self.move(tw, th, move) class RobotArmUu(_RobotArm): """Robot arm segment with two orthogonal sets of hinge knuckles""" def __call__(self, length, move=None): t = self.thickness w = self.servo.hinge_width() w2 = self.servo2.hinge_width() l = max(4*self.thickness, length - 2*t - 2*self.servo.height) th = max(self.thickness + self.servo._edges["m"].spacing() + l, 2*w + self.thickness + 4 * self.edges["f"].spacing()) tw = 5 * (w + 2*self.thickness + self.spacing) if self.move(tw, th, move, True): return iw = (3, 4) e = self.servo.edges self.rectangularWall(w2, l, e("nfFf"), move="right") self.rectangularWall(w2, l, e("NfFf"), move="right") self.rectangularWall(w, l, e("FFmF"), ignore_widths=iw, move="right") self.rectangularWall(w, l, e("FFMF"), ignore_widths=iw, move="right") self.rectangularWall(w2, w, "ffff", callback=[ lambda: self.hole(w2/2, w/2, 6)], move="up") self.rectangularWall(w2, w, "ffff", callback=[ lambda: self.hole(w2/2, w/2, 6)], move="") self.move(tw, th, move) class RobotArmMu(_RobotArm): """Robot arm segment with a servo and an orthogonal sets of hinge knuckles""" def __call__(self, length, move=None): t = self.thickness w = self.servo.height w2 = self.servo2.hinge_width() l = max(self.servo.length, length + self.servo.axle_pos - self.servo.height - t) th = max(t + l + self.servo2._edges["m"].spacing(), w + w2 + self.thickness + 4 * self.edges["f"].spacing()) tw = 5 * (w + 2*self.thickness + self.spacing) if self.move(tw, th, move, True): return e = self.servo2.edges iw = (3, 4) self.rectangularWall(w2, l, "FfFf", callback=[ lambda:self.servo.top(w2/2)], move="right") self.rectangularWall(w2, l, "FfFf", callback=[ lambda:self.servo.bottom(w2/2)], move="right") self.rectangularWall(w, l, e("FFmF"), ignore_widths=iw, move="right") self.rectangularWall(w, l, e("FFMF"), ignore_widths=iw, move="right") self.rectangularWall(w2, w, "ffff", callback=[ lambda:self.servo.front(w2/2)], move="up") self.rectangularWall(w2, w, "ffff", callback=[ lambda: self.hole(w2/2, w/2, 6)], move="") self.move(tw, th, move) # class RobotArmMU(_RobotArm):
7,056
Python
.py
151
37.437086
88
0.572406
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,542
pulley.py
florianfesti_boxes/boxes/pulley.py
""" // Parametric Pulley with multiple belt profiles // by droftarts January 2012 // Based on pulleys by: // https://www.thingiverse.com/thing:11256 by me! // https://github.com/prusajr/PrusaMendel by Josef Prusa // https://www.thingiverse.com/thing:3104 by GilesBathgate // https://www.thingiverse.com/thing:2079 by nophead // dxf tooth data from http://oem.cadregister.com/asp/PPOW_Entry.asp?company=915217&elementID=07807803/METRIC/URETH/WV0025/F // pulley diameter checked and modelled from data at https://www.sdp-si.com/D265/HTML/D265T016.html """ from math import * from boxes.vectors import * def tooth_spaceing_curvefit(teeth, b, c, d): return ((c * teeth ** d) / (b + teeth ** d)) * teeth def tooth_spacing(teeth, tooth_pitch, pitch_line_offset): return (2 * ((teeth * tooth_pitch) / (3.14159265 * 2) - pitch_line_offset)) def mirrorx(points): return [[-x, y] for x, y in points] class Pulley: spacing = { "MXL": (False, 2.032, 0.254), "40DP": (False, 2.07264, 0.1778), "XL": (False, 5.08, 0.254), "H": (False, 9.525, 0.381), "T2_5": (True, 0.7467, 0.796, 1.026), "T5": (True, 0.6523, 1.591, 1.064), "T10": (False, 10, 0.93), "AT5": (True, 0.6523, 1.591, 1.064), "HTD_3mm": (False, 3, 0.381), "HTD_5mm": (False, 5, 0.5715), "HTD_8mm": (False, 8, 0.6858), "GT2_2mm": (False, 2, 0.254), "GT2_3mm": (False, 3, 0.381), "GT2_5mm": (False, 5, 0.5715), } profile_data = { "MXL": (0.508, 1.321), "40DP": (0.457, 1.226), "XL": (1.27, 3.051), "H": (1.905, 5.359), "T2_5": (0.7, 1.678), "T5": (1.19, 3.264), "T10": (2.5, 6.13), "AT5": (1.19, 4.268), "HTD_3mm": (1.289, 2.27), "HTD_5mm": (2.199, 3.781), "HTD_8mm": (3.607, 6.603), "GT2_2mm": (0.764, 1.494), "GT2_3mm": (1.169, 2.31), "GT2_5mm": (1.969, 3.952), } teeth = { "MXL" : [[-0.660421,-0.5],[-0.660421,0],[-0.621898,0.006033],[-0.587714,0.023037],[-0.560056,0.049424],[-0.541182,0.083609],[-0.417357,0.424392],[-0.398413,0.458752],[-0.370649,0.48514],[-0.336324,0.502074],[-0.297744,0.508035],[0.297744,0.508035],[0.336268,0.502074],[0.370452,0.48514],[0.39811,0.458752],[0.416983,0.424392],[0.540808,0.083609],[0.559752,0.049424],[0.587516,0.023037],[0.621841,0.006033],[0.660421,0],[0.660421,-0.5]], "40DP" : [[-0.612775,-0.5],[-0.612775,0],[-0.574719,0.010187],[-0.546453,0.0381],[-0.355953,0.3683],[-0.327604,0.405408],[-0.291086,0.433388],[-0.248548,0.451049],[-0.202142,0.4572],[0.202494,0.4572],[0.248653,0.451049],[0.291042,0.433388],[0.327609,0.405408],[0.356306,0.3683],[0.546806,0.0381],[0.574499,0.010187],[0.612775,0],[0.612775,-0.5]], "XL" : [[-1.525411,-1],[-1.525411,0],[-1.41777,0.015495],[-1.320712,0.059664],[-1.239661,0.129034],[-1.180042,0.220133],[-0.793044,1.050219],[-0.733574,1.141021],[-0.652507,1.210425],[-0.555366,1.254759],[-0.447675,1.270353],[0.447675,1.270353],[0.555366,1.254759],[0.652507,1.210425],[0.733574,1.141021],[0.793044,1.050219],[1.180042,0.220133],[1.239711,0.129034],[1.320844,0.059664],[1.417919,0.015495],[1.525411,0],[1.525411,-1]], "H" : [[-2.6797,-1],[-2.6797,0],[-2.600907,0.006138],[-2.525342,0.024024],[-2.45412,0.052881],[-2.388351,0.091909],[-2.329145,0.140328],[-2.277614,0.197358],[-2.234875,0.262205],[-2.202032,0.334091],[-1.75224,1.57093],[-1.719538,1.642815],[-1.676883,1.707663],[-1.62542,1.764693],[-1.566256,1.813112],[-1.500512,1.85214],[-1.4293,1.880997],[-1.353742,1.898883],[-1.274949,1.905021],[1.275281,1.905021],[1.354056,1.898883],[1.429576,1.880997],[1.500731,1.85214],[1.566411,1.813112],[1.625508,1.764693],[1.676919,1.707663],[1.719531,1.642815],[1.752233,1.57093],[2.20273,0.334091],[2.235433,0.262205],[2.278045,0.197358],[2.329455,0.140328],[2.388553,0.091909],[2.454233,0.052881],[2.525384,0.024024],[2.600904,0.006138],[2.6797,0],[2.6797,-1]], "T2_5" : [[-0.839258,-0.5],[-0.839258,0],[-0.770246,0.021652],[-0.726369,0.079022],[-0.529167,0.620889],[-0.485025,0.67826],[-0.416278,0.699911],[0.416278,0.699911],[0.484849,0.67826],[0.528814,0.620889],[0.726369,0.079022],[0.770114,0.021652],[0.839258,0],[0.839258,-0.5]], "T5" : [[-1.632126,-0.5],[-1.632126,0],[-1.568549,0.004939],[-1.507539,0.019367],[-1.450023,0.042686],[-1.396912,0.074224],[-1.349125,0.113379],[-1.307581,0.159508],[-1.273186,0.211991],[-1.246868,0.270192],[-1.009802,0.920362],[-0.983414,0.978433],[-0.949018,1.030788],[-0.907524,1.076798],[-0.859829,1.115847],[-0.80682,1.147314],[-0.749402,1.170562],[-0.688471,1.184956],[-0.624921,1.189895],[0.624971,1.189895],[0.688622,1.184956],[0.749607,1.170562],[0.807043,1.147314],[0.860055,1.115847],[0.907754,1.076798],[0.949269,1.030788],[0.9837,0.978433],[1.010193,0.920362],[1.246907,0.270192],[1.273295,0.211991],[1.307726,0.159508],[1.349276,0.113379],[1.397039,0.074224],[1.450111,0.042686],[1.507589,0.019367],[1.568563,0.004939],[1.632126,0],[1.632126,-0.5]], "T10" : [[-3.06511,-1],[-3.06511,0],[-2.971998,0.007239],[-2.882718,0.028344],[-2.79859,0.062396],[-2.720931,0.108479],[-2.651061,0.165675],[-2.590298,0.233065],[-2.539962,0.309732],[-2.501371,0.394759],[-1.879071,2.105025],[-1.840363,2.190052],[-1.789939,2.266719],[-1.729114,2.334109],[-1.659202,2.391304],[-1.581518,2.437387],[-1.497376,2.47144],[-1.408092,2.492545],[-1.314979,2.499784],[1.314979,2.499784],[1.408091,2.492545],[1.497371,2.47144],[1.581499,2.437387],[1.659158,2.391304],[1.729028,2.334109],[1.789791,2.266719],[1.840127,2.190052],[1.878718,2.105025],[2.501018,0.394759],[2.539726,0.309732],[2.59015,0.233065],[2.650975,0.165675],[2.720887,0.108479],[2.798571,0.062396],[2.882713,0.028344],[2.971997,0.007239],[3.06511,0],[3.06511,-1]], "AT5" : [[-2.134129,-0.75],[-2.134129,0],[-2.058023,0.005488],[-1.984595,0.021547],[-1.914806,0.047569],[-1.849614,0.082947],[-1.789978,0.127073],[-1.736857,0.179338],[-1.691211,0.239136],[-1.653999,0.305859],[-1.349199,0.959203],[-1.286933,1.054635],[-1.201914,1.127346],[-1.099961,1.173664],[-0.986896,1.18992],[0.986543,1.18992],[1.099614,1.173664],[1.201605,1.127346],[1.286729,1.054635],[1.349199,0.959203],[1.653646,0.305859],[1.690859,0.239136],[1.73651,0.179338],[1.789644,0.127073],[1.849305,0.082947],[1.914539,0.047569],[1.984392,0.021547],[2.057906,0.005488],[2.134129,0],[2.134129,-0.75]], "HTD_3mm" : [[-1.135062,-0.5],[-1.135062,0],[-1.048323,0.015484],[-0.974284,0.058517],[-0.919162,0.123974],[-0.889176,0.206728],[-0.81721,0.579614],[-0.800806,0.653232],[-0.778384,0.72416],[-0.750244,0.792137],[-0.716685,0.856903],[-0.678005,0.918199],[-0.634505,0.975764],[-0.586483,1.029338],[-0.534238,1.078662],[-0.47807,1.123476],[-0.418278,1.16352],[-0.355162,1.198533],[-0.289019,1.228257],[-0.22015,1.25243],[-0.148854,1.270793],[-0.07543,1.283087],[-0.000176,1.28905],[0.075081,1.283145],[0.148515,1.270895],[0.219827,1.252561],[0.288716,1.228406],[0.354879,1.19869],[0.418018,1.163675],[0.477831,1.123623],[0.534017,1.078795],[0.586276,1.029452],[0.634307,0.975857],[0.677809,0.91827],[0.716481,0.856953],[0.750022,0.792167],[0.778133,0.724174],[0.800511,0.653236],[0.816857,0.579614],[0.888471,0.206728],[0.919014,0.123974],[0.974328,0.058517],[1.048362,0.015484],[1.135062,0],[1.135062,-0.5]], "HTD_5mm" : [[-1.89036,-0.75],[-1.89036,0],[-1.741168,0.02669],[-1.61387,0.100806],[-1.518984,0.21342],[-1.467026,0.3556],[-1.427162,0.960967],[-1.398568,1.089602],[-1.359437,1.213531],[-1.310296,1.332296],[-1.251672,1.445441],[-1.184092,1.552509],[-1.108081,1.653042],[-1.024167,1.746585],[-0.932877,1.832681],[-0.834736,1.910872],[-0.730271,1.980701],[-0.62001,2.041713],[-0.504478,2.09345],[-0.384202,2.135455],[-0.259708,2.167271],[-0.131524,2.188443],[-0.000176,2.198511],[0.131296,2.188504],[0.259588,2.167387],[0.384174,2.135616],[0.504527,2.093648],[0.620123,2.04194],[0.730433,1.980949],[0.834934,1.911132],[0.933097,1.832945],[1.024398,1.746846],[1.108311,1.653291],[1.184308,1.552736],[1.251865,1.445639],[1.310455,1.332457],[1.359552,1.213647],[1.39863,1.089664],[1.427162,0.960967],[1.467026,0.3556],[1.518984,0.21342],[1.61387,0.100806],[1.741168,0.02669],[1.89036,0],[1.89036,-0.75]], "HTD_8mm" : [[-3.301471,-1],[-3.301471,0],[-3.16611,0.012093],[-3.038062,0.047068],[-2.919646,0.10297],[-2.813182,0.177844],[-2.720989,0.269734],[-2.645387,0.376684],[-2.588694,0.496739],[-2.553229,0.627944],[-2.460801,1.470025],[-2.411413,1.691917],[-2.343887,1.905691],[-2.259126,2.110563],[-2.158035,2.30575],[-2.041518,2.490467],[-1.910478,2.66393],[-1.76582,2.825356],[-1.608446,2.973961],[-1.439261,3.10896],[-1.259169,3.22957],[-1.069074,3.335006],[-0.869878,3.424485],[-0.662487,3.497224],[-0.447804,3.552437],[-0.226732,3.589341],[-0.000176,3.607153],[0.226511,3.589461],[0.447712,3.552654],[0.66252,3.497516],[0.870027,3.424833],[1.069329,3.33539],[1.259517,3.229973],[1.439687,3.109367],[1.608931,2.974358],[1.766344,2.825731],[1.911018,2.664271],[2.042047,2.490765],[2.158526,2.305998],[2.259547,2.110755],[2.344204,1.905821],[2.411591,1.691983],[2.460801,1.470025],[2.553229,0.627944],[2.588592,0.496739],[2.645238,0.376684],[2.720834,0.269734],[2.81305,0.177844],[2.919553,0.10297],[3.038012,0.047068],[3.166095,0.012093],[3.301471,0],[3.301471,-1]], "GT2_2mm" : mirrorx([[0.747183,-0.5],[0.747183,0],[0.647876,0.037218],[0.598311,0.130528],[0.578556,0.238423],[0.547158,0.343077],[0.504649,0.443762],[0.451556,0.53975],[0.358229,0.636924],[0.2484,0.707276],[0.127259,0.750044],[0,0.76447],[-0.127259,0.750044],[-0.2484,0.707276],[-0.358229,0.636924],[-0.451556,0.53975],[-0.504797,0.443762],[-0.547291,0.343077],[-0.578605,0.238423],[-0.598311,0.130528],[-0.648009,0.037218],[-0.747183,0],[-0.747183,-0.5]]), "GT2_3mm" : [[-1.155171,-0.5],[-1.155171,0],[-1.065317,0.016448],[-0.989057,0.062001],[-0.93297,0.130969],[-0.90364,0.217664],[-0.863705,0.408181],[-0.800056,0.591388],[-0.713587,0.765004],[-0.60519,0.926747],[-0.469751,1.032548],[-0.320719,1.108119],[-0.162625,1.153462],[0,1.168577],[0.162625,1.153462],[0.320719,1.108119],[0.469751,1.032548],[0.60519,0.926747],[0.713587,0.765004],[0.800056,0.591388],[0.863705,0.408181],[0.90364,0.217664],[0.932921,0.130969],[0.988924,0.062001],[1.065168,0.016448],[1.155171,0],[1.155171,-0.5]], "GT2_5mm" : [[-1.975908,-0.75],[-1.975908,0],[-1.797959,0.03212],[-1.646634,0.121224],[-1.534534,0.256431],[-1.474258,0.426861],[-1.446911,0.570808],[-1.411774,0.712722],[-1.368964,0.852287],[-1.318597,0.989189],[-1.260788,1.123115],[-1.195654,1.25375],[-1.12331,1.380781],[-1.043869,1.503892],[-0.935264,1.612278],[-0.817959,1.706414],[-0.693181,1.786237],[-0.562151,1.851687],[-0.426095,1.9027],[-0.286235,1.939214],[-0.143795,1.961168],[0,1.9685],[0.143796,1.961168],[0.286235,1.939214],[0.426095,1.9027],[0.562151,1.851687],[0.693181,1.786237],[0.817959,1.706414],[0.935263,1.612278],[1.043869,1.503892],[1.123207,1.380781],[1.195509,1.25375],[1.26065,1.123115],[1.318507,0.989189],[1.368956,0.852287],[1.411872,0.712722],[1.447132,0.570808],[1.474611,0.426861],[1.534583,0.256431],[1.646678,0.121223],[1.798064,0.03212],[1.975908,0],[1.975908,-0.75]], } def __init__(self, boxes) -> None: self.boxes = boxes @classmethod def getProfiles(cls): return list(sorted(cls.teeth.keys())) def diameter(self, teeth, profile): if self.spacing[profile][0]: return tooth_spaceing_curvefit(teeth, *self.spacing[profile][1:]) return tooth_spacing(teeth, *self.spacing[profile][1:]) def __call__(self, teeth, profile, insideout=False, r_axle=None, callback=None, move=""): # ******************************** # ** Scaling tooth for good fit ** # ******************************** # To improve fit of belt to pulley, set the following constant. Decrease or increase by 0.1mm at a time. We are modelling the *BELT* tooth here, not the tooth on the pulley. Increasing the number will *decrease* the pulley tooth size. Increasing the tooth width will also scale proportionately the tooth depth, to maintain the shape of the tooth, and increase how far into the pulley the tooth is indented. Can be negative additional_tooth_width = 0.2 # mm # If you need more tooth depth than this provides, adjust the following constant. However, this will cause the shape of the tooth to change. additional_tooth_depth = 0 # mm pulley_OD = self.diameter(teeth, profile) tooth_depth, tooth_width = self.profile_data[profile] tooth_distance_from_centre = ((pulley_OD / 2) ** 2 - ((tooth_width + additional_tooth_width) / 2) ** 2) ** 0.5 tooth_width_scale = (tooth_width + additional_tooth_width) / tooth_width tooth_depth_scale = ((tooth_depth + additional_tooth_depth) / tooth_depth) if insideout: pulley_OD += 2*tooth_depth * tooth_depth_scale tooth_depth_scale *= -1 total_width = max(pulley_OD, 2*(r_axle or 0.0)) if self.boxes.move(total_width, total_width, move, before=True): return self.boxes.moveTo(total_width / 2, total_width / 2) self.boxes.cc(callback, None, 0.0, 0.0) if r_axle: if insideout: self.boxes.circle(0, 0, r_axle) else: self.boxes.hole(0, 0, r_axle) points = [] for i in range(teeth): m = [[tooth_width_scale, 0, 0], [0, tooth_depth_scale, -tooth_distance_from_centre]] m = mmul(m, rotm(i * 2 * pi / teeth)) points.extend(vtransl(pt, m) for pt in self.teeth[profile][1:-1]) self.boxes.drawPoints(points, kerfdir=-1 if insideout else 1) self.boxes.move(total_width, total_width, move)
13,898
Python
.py
111
116.333333
1,078
0.628262
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,543
edges.py
florianfesti_boxes/boxes/edges.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import annotations import argparse import inspect import math import re from abc import ABC, abstractmethod from typing import Any from boxes import gears def argparseSections(s: str) -> list[float]: """ Parse sections parameter :param s: string to parse """ result: list[float] = [] parse = re.split(r"\s|:", s) try: for part in parse: m = re.match(r"^(\d+(\.\d+)?)/(\d+)$", part) if m: n = int(m.group(3)) result.extend([float(m.group(1)) / n] * n) continue m = re.match(r"^(\d+(\.\d+)?)\*(\d+)$", part) if m: n = int(m.group(3)) result.extend([float(m.group(1))] * n) continue result.append(float(part)) except ValueError: raise argparse.ArgumentTypeError("Don't understand sections string") if not result: result.append(0.0) return result def getDescriptions() -> dict: d = {edge.char: edge.description for edge in globals().values() if inspect.isclass(edge) and issubclass(edge, BaseEdge) and edge.char} d['j'] = d['i'] + " (other end)" d['J'] = d['I'] + " (other end)" d['k'] = d['i'] + " (both ends)" d['K'] = d['I'] + " (both ends)" d['O'] = d['o'] + ' (other end)' d['P'] = d['p'] + ' (other end)' d['U'] = d['u'] + ' top side' d['v'] = d['u'] + ' for 90° lid' d['V'] = d['u'] + ' 90° lid' return d class BoltPolicy(ABC): """Abstract class Distributes (bed) bolts on a number of segments (fingers of a finger joint) """ def drawbolt(self, pos) -> bool: """Add a bolt to this segment? :param pos: number of the finger """ return False def numFingers(self, numFingers: int) -> int: """Return next smaller, possible number of fingers :param numFingers: number of fingers to aim for """ return numFingers def _even(self, numFingers: int) -> int: """ Return same or next smaller even number :param numFingers: """ return (numFingers // 2) * 2 def _odd(self, numFingers: int) -> int: """ Return same or next smaller odd number :param numFingers: """ if numFingers % 2: return numFingers return numFingers - 1 class Bolts(BoltPolicy): """Distribute a fixed number of bolts evenly""" def __init__(self, bolts: int = 1) -> None: self.bolts = bolts def numFingers(self, numFingers: int) -> int: if self.bolts % 2: self.fingers = self._even(numFingers) else: self.fingers = numFingers return self.fingers def drawBolt(self, pos): """ Return if this finger needs a bolt :param pos: number of this finger """ if pos > self.fingers // 2: pos = self.fingers - pos if pos == 0: return False if pos == self.fingers // 2 and not (self.bolts % 2): return False return (math.floor((float(pos) * (self.bolts + 1) / self.fingers) - 0.01) != math.floor((float(pos + 1) * (self.bolts + 1) / self.fingers) - 0.01)) ############################################################################# ### Settings ############################################################################# class Settings: """Generic Settings class Used by different other classes to store measurements and details. Supports absolute values and settings that grow with the thickness of the material used. Overload the absolute_params and relative_params class attributes with the supported keys and default values. The values are available via attribute access. Store values that are not supposed to be changed by the users in class or instance properties. This way API users can set them as needed while still be shared between all (Edge) instances using this settings object. """ absolute_params: dict[str, Any] = {} # TODO find better typing. relative_params: dict[str, Any] = {} # TODO find better typing. @classmethod def parserArguments(cls, parser, prefix=None, **defaults): prefix = prefix or cls.__name__[:-len("Settings")] lines = cls.__doc__.split("\n") # Parse doc string descriptions = {} r = re.compile(r"^ +\* +(\S+) +: .* : +(.*)") for l in lines: m = r.search(l) if m: descriptions[m.group(1)] = m.group(2) group = parser.add_argument_group(lines[0] or lines[1]) group.prefix = prefix for name, default in (sorted(cls.absolute_params.items()) + sorted(cls.relative_params.items())): # Handle choices choices = None if isinstance(default, tuple): choices = default t = type(default[0]) for val in default: if (type(val) is not t or type(val) not in (bool, int, float, str)): raise ValueError("Type not supported: %r", val) default = default[0] # Overwrite default if name in defaults: default = type(default)(defaults[name]) if type(default) not in (bool, int, float, str): raise ValueError("Type not supported: %r", default) if type(default) is bool: from boxes import BoolArg t = BoolArg() else: t = type(default) group.add_argument(f"--{prefix}_{name}", type=t, action="store", default=default, choices=choices, help=descriptions.get(name)) def __init__(self, thickness, relative: bool = True, **kw) -> None: self.values = {} for name, value in self.absolute_params.items(): if isinstance(value, tuple): value = value[0] if type(value) not in (bool, int, float, str): raise ValueError("Type not supported: %r", value) self.values[name] = value self.thickness = thickness factor = 1.0 if relative: factor = thickness for name, value in self.relative_params.items(): self.values[name] = value * factor self.setValues(thickness, relative, **kw) def edgeObjects(self, boxes, chars: str = "", add: bool = True): """ Generate Edge objects using this kind of settings :param boxes: Boxes object :param chars: sequence of chars to be used by Edge objects :param add: add the resulting Edge objects to the Boxes object's edges """ edges: list[Any] = [] return self._edgeObjects(edges, boxes, chars, add) def _edgeObjects(self, edges, boxes, chars: str, add: bool): for i, edge in enumerate(edges): try: char = chars[i] edge.char = char except IndexError: pass except TypeError: pass if add: boxes.addParts(edges) return edges def setValues(self, thickness, relative: bool = True, **kw): """ Set values :param thickness: thickness of the material used :param relative: Do scale by thickness (Default value = True) :param kw: parameters to set """ factor = 1.0 if relative: factor = thickness for name, value in kw.items(): if name in self.absolute_params: self.values[name] = value elif name in self.relative_params: self.values[name] = value * factor elif hasattr(self, name): setattr(self, name, value) else: raise ValueError(f"Unknown parameter for {self.__class__.__name__}: {name}") self.checkValues() def checkValues(self) -> None: """ Check if all values are in the right range. Raise ValueError if needed. """ pass def __getattr__(self, name): if "values" in self.__dict__ and name in self.values: return self.values[name] raise AttributeError ############################################################################# ### Edges ############################################################################# class BaseEdge(ABC): """Abstract base class for all Edges""" char: str | None = None description: str = "Abstract Edge Class" def __init__(self, boxes, settings) -> None: self.boxes = boxes self.ctx = boxes.ctx self.settings = settings def __getattr__(self, name): """Hack for using unalter code form Boxes class""" return getattr(self.boxes, name) @abstractmethod def __call__(self, length, **kw): pass def startwidth(self) -> float: """Amount of space the beginning of the edge is set below the inner space of the part """ return 0.0 def endwidth(self) -> float: return self.startwidth() def margin(self) -> float: """Space needed right of the starting point""" return 0.0 def spacing(self) -> float: """Space the edge needs outside of the inner space of the part""" return self.startwidth() + self.margin() def startAngle(self) -> float: """Not yet supported""" return 0.0 def endAngle(self) -> float: """Not yet supported""" return 0.0 class Edge(BaseEdge): """Straight edge""" char = 'e' description = "Straight Edge" positive = False def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): """Draw edge of length mm""" if bedBolts: # distribute the bolts equidistantly interval_length = length / bedBolts.bolts if self.positive: d = (bedBoltSettings or self.bedBoltSettings)[0] for i in range(bedBolts.bolts): self.hole(0.5 * interval_length, 0.5 * self.thickness, 0.5 * d) self.edge(interval_length, tabs= (i == 0 or i == bedBolts.bolts - 1)) else: for i in range(bedBolts.bolts): self.bedBoltHole(interval_length, bedBoltSettings, tabs= (i == 0 or i == bedBolts.bolts - 1)) else: self.edge(length, tabs=2) class OutSetEdge(Edge): """Straight edge out set by one thickness""" char = 'E' description = "Straight Edge (outset by thickness)" positive = True def startwidth(self) -> float: return self.settings if self.settings is not None else self.boxes.thickness class NoopEdge(BaseEdge): """ Edge which does nothing, not even turn or move. """ def __init__(self, boxes, margin=0) -> None: super().__init__(boxes, None) self._margin = margin def __call__(self, _, **kw): # cancel turn self.corner(-90) def margin(self) -> float: return self._margin ############################################################################# #### MountingEdge ############################################################################# class MountingSettings(Settings): """Settings for Mounting Edge Values: * absolute_params * style : "straight edge, within" : edge style * side : "back" : side of box (not all valid configurations make sense...) * num : 2 : number of mounting holes (integer) * margin : 0.125 : minimum space left and right without holes (fraction of the edge length) * d_shaft : 3.0 : shaft diameter of mounting screw (in mm) * d_head : 6.5 : head diameter of mounting screw (in mm) """ PARAM_IN = "straight edge, within" PARAM_EXT = "straight edge, extended" PARAM_TAB = "mounting tab" PARAM_LEFT = "left" PARAM_BACK = "back" PARAM_RIGHT = "right" PARAM_FRONT = "front" absolute_params = { "style": (PARAM_IN, PARAM_EXT, PARAM_TAB), "side": (PARAM_BACK, PARAM_LEFT, PARAM_RIGHT, PARAM_FRONT), "num": 2, "margin": 0.125, "d_shaft": 3.0, "d_head": 6.5 } def edgeObjects(self, boxes, chars: str = "G", add: bool = True): edges = [MountingEdge(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class MountingEdge(BaseEdge): description = """Edge with pear shaped mounting holes""" # for slide-on mounting using flat-head screws""" char = 'G' def margin(self) -> float: if self.settings.style == MountingSettings.PARAM_TAB: return 2.75 * self.boxes.thickness + self.settings.d_head return 0.0 def startwidth(self) -> float: if self.settings.style == MountingSettings.PARAM_EXT: return 2.5 * self.boxes.thickness + self.settings.d_head return 0.0 def __call__(self, length, **kw): if length == 0.0: return def check_bounds(val, mn, mx, name): if not mn <= val <= mx: raise ValueError(f"MountingEdge: {name} needs to be in [{mn}, {mx}] but is {val}") style = self.settings.style margin = self.settings.margin num = self.settings.num ds = self.settings.d_shaft dh = self.settings.d_head if dh > 0: width = 3 * self.thickness + dh else: width = ds if num != int(num): raise ValueError(f"MountingEdge: num needs to be an integer number") check_bounds(margin, 0, 0.5, "margin") if not dh == 0: if not dh > ds: raise ValueError(f"MountingEdge: d_shaft needs to be in 0 or > {ds}, but is {dh}") # Check how many holes fit count = max(1, int(num)) if count > 1: margin_ = length * margin gap = (length - 2 * margin_ - width * count) / (count - 1) if gap < width: count = int(((length - 2 * margin + width) / (2 * width)) - 0.5) if count < 1: self.edge(length) return if count < 2: margin_ = (length - width) / 2 gap = 0 else: gap = (length - 2 * margin_ - width * count) / (count - 1) else: margin_ = (length - width) / 2 gap = 0 if style == MountingSettings.PARAM_TAB: # The edge until the first groove self.edge(margin_, tabs=1) for i in range(count): if i > 0: self.edge(gap) self.corner(-90, self.thickness / 2) self.edge(dh + 1.5 * ds - self.thickness / 4 - dh / 2) self.corner(90, self.thickness + dh / 2) self.corner(-90) self.corner(90) self.mountingHole(0, self.thickness * 1.25 + ds / 2, ds, dh, -90) self.corner(90, self.thickness + dh / 2) self.edge(dh + 1.5 * ds - self.thickness / 4 - dh / 2) self.corner(-90, self.thickness / 2) # The edge until the end self.edge(margin_, tabs=1) else: x = margin_ for i in range(count): x += width / 2 self.mountingHole(x, ds / 2 + self.thickness * 1.5, ds, dh, -90) x += width / 2 x += gap self.edge(length) ############################################################################# #### GroovedEdge ############################################################################# class GroovedSettings(Settings): """Settings for Grooved Edge Values: * absolute_params * style : "arc" : the style of grooves * tri_angle : 30 : the angle of triangular cuts * arc_angle : 120 : the angle of arc cuts * width : 0.2 : the width of each groove (fraction of the edge length) * gap : 0.1 : the gap between grooves (fraction of the edge length) * margin : 0.3 : minimum space left and right without grooves (fraction of the edge length) * inverse : False : invert the groove directions * interleave : False : alternate the direction of grooves """ PARAM_ARC = "arc" PARAM_FLAT = "flat" PARAM_SOFTARC = "softarc" PARAM_TRIANGLE = "triangle" absolute_params = { "style": (PARAM_ARC, PARAM_FLAT, PARAM_TRIANGLE, PARAM_SOFTARC), "tri_angle": 30, "arc_angle": 120, "width": 0.2, "gap": 0.1, "margin": 0.3, "inverse": False, "interleave": False, } def edgeObjects(self, boxes, chars: str = "zZ", add: bool = True): edges = [GroovedEdge(boxes, self), GroovedEdgeCounterPart(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class GroovedEdgeBase(BaseEdge): def is_inverse(self) -> bool: return self.settings.inverse != self.inverse def groove_arc(self, width, angle: float = 90.0, inv: float = -1.0) -> None: side_length = width / math.sin(math.radians(angle)) / 2 self.corner(inv * -angle) self.corner(inv * angle, side_length) self.corner(inv * angle, side_length) self.corner(inv * -angle) def groove_soft_arc(self, width, angle: float = 60.0, inv: float = -1.0) -> None: side_length = width / math.sin(math.radians(angle)) / 4 self.corner(inv * -angle, side_length) self.corner(inv * angle, side_length) self.corner(inv * angle, side_length) self.corner(inv * -angle, side_length) def groove_triangle(self, width, angle: float = 45.0, inv: float = -1.0) -> None: side_length = width / math.cos(math.radians(angle)) / 2 self.corner(inv * -angle) self.edge(side_length) self.corner(inv * 2 * angle) self.edge(side_length) self.corner(inv * -angle) def __call__(self, length, **kw): if length == 0.0: return def check_bounds(val, mn, mx, name): if not mn <= val <= mx: raise ValueError(f"{name} needs to be in [{mn}, {mx}] but is {val}") style = self.settings.style width = self.settings.width margin = self.settings.margin gap = self.settings.gap interleave = self.settings.interleave check_bounds(width, 0, 1, "width") check_bounds(margin, 0, 0.5, "margin") check_bounds(gap, 0, 1, "gap") # Check how many grooves fit count = max(0, int((1 - 2 * margin + gap) / (width + gap))) inside_width = max(0, count * (width + gap) - gap) margin = (1 - inside_width) / 2 # Convert to actual length margin = length * margin gap = length * gap width = length * width # Determine the initial inversion inv = 1 if self.is_inverse() else -1 if interleave and self.inverse and count % 2 == 0: inv = -inv # The edge until the first groove self.edge(margin, tabs=1) # Grooves for i in range(count): if i > 0: self.edge(gap) if interleave: inv = -inv if style == GroovedSettings.PARAM_FLAT: self.edge(width) elif style == GroovedSettings.PARAM_ARC: angle = self.settings.arc_angle / 2 self.groove_arc(width, angle, inv) elif style == GroovedSettings.PARAM_SOFTARC: angle = self.settings.arc_angle / 2 self.groove_soft_arc(width, angle, inv) elif style == GroovedSettings.PARAM_TRIANGLE: angle = self.settings.tri_angle self.groove_triangle(width, angle, inv) else: raise ValueError("Unknown GroovedEdge style: %s)" % style) # The final edge self.edge(margin, tabs=1) class GroovedEdge(GroovedEdgeBase): description = """Edge with grooves""" char = 'z' inverse = False class GroovedEdgeCounterPart(GroovedEdgeBase): description = """Edge with grooves (opposing side)""" char = 'Z' inverse = True ############################################################################# #### Gripping Edge ############################################################################# class GripSettings(Settings): """Settings for GrippingEdge Values: * absolute_params * style : "wave" : "wave" or "bumps" * outset : True : extend outward the straight edge * relative (in multiples of thickness) * depth : 0.3 : depth of the grooves """ absolute_params = { "style": ("wave", "bumps"), "outset": True, } relative_params = { "depth": 0.3, } def edgeObjects(self, boxes, chars: str = "g", add: bool = True): edges = [GrippingEdge(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class GrippingEdge(BaseEdge): description = """Corrugated edge useful as an gipping area""" char = 'g' def wave(self, length) -> None: depth = self.settings.depth grooves = int(length // (depth * 2.0)) + 1 depth = length / grooves / 4.0 o = 1 if self.settings.outset else -1 for groove in range(grooves): self.corner(o * -90, depth) self.corner(o * 180, depth) self.corner(o * -90, depth) def bumps(self, length) -> None: depth = self.settings.depth grooves = int(length // (depth * 2.0)) + 1 depth = length / grooves / 2.0 o = 1 if self.settings.outset else -1 if self.settings.outset: self.corner(-90) else: self.corner(90) self.edge(depth) self.corner(-180) for groove in range(grooves): self.corner(180, depth) self.corner(-180, 0) if self.settings.outset: self.corner(90) else: self.edge(depth) self.corner(90) def margin(self) -> float: if self.settings.outset: return self.settings.depth return 0.0 def __call__(self, length, **kw): if length == 0.0: return getattr(self, self.settings.style)(length) class CompoundEdge(BaseEdge): """Edge composed of multiple different Edges""" description = "Compound Edge" def __init__(self, boxes, types, lengths) -> None: super().__init__(boxes, None) self.types = [self.edges.get(edge, edge) for edge in types] self.lengths = lengths self.length = sum(lengths) def startwidth(self) -> float: return self.types[0].startwidth() def endwidth(self) -> float: return self.types[-1].endwidth() def margin(self) -> float: return max(e.margin() + e.startwidth() for e in self.types) - self.types[0].startwidth() def __call__(self, length, **kw): if length and abs(length - self.length) > 1E-5: raise ValueError("Wrong length for CompoundEdge") lastwidth = self.types[0].startwidth() for e, l in zip(self.types, self.lengths): self.step(e.startwidth() - lastwidth) e(l) lastwidth = e.endwidth() ############################################################################# #### Slots ############################################################################# class Slot(BaseEdge): """Edge with a slot to slide another piece through """ description = "Slot" def __init__(self, boxes, depth) -> None: super().__init__(boxes, None) self.depth = depth def __call__(self, length, **kw): if self.depth: self.boxes.corner(90) self.boxes.edge(self.depth) self.boxes.corner(-90) self.boxes.edge(length) self.boxes.corner(-90) self.boxes.edge(self.depth) self.boxes.corner(90) else: self.boxes.edge(self.length) class SlottedEdge(BaseEdge): """Edge with multiple slots""" description = "Straight Edge with slots" def __init__(self, boxes, sections, edge: str = "e", slots: int = 0) -> None: super().__init__(boxes, Settings(boxes.thickness)) self.edge = self.edges.get(edge, edge) self.sections = sections self.slots = slots def startwidth(self) -> float: return self.edge.startwidth() def endwidth(self) -> float: return self.edge.endwidth() def margin(self) -> float: return self.edge.margin() def __call__(self, length, **kw): for l in self.sections[:-1]: self.edge(l) if self.slots: Slot(self.boxes, self.slots)(self.settings.thickness) else: self.boxes.edge(self.settings.thickness) self.edge(self.sections[-1]) ############################################################################# #### Finger Joints ############################################################################# class FingerJointSettings(Settings): """Settings for Finger Joints Values: * absolute * style : "rectangular" : style of the fingers * surroundingspaces : 2.0 : space at the start and end in multiple of normal spaces * relative (in multiples of thickness) * space : 2.0 : space between fingers (multiples of thickness) * finger : 2.0 : width of the fingers (multiples of thickness) * width : 1.0 : width of finger holes (multiples of thickness) * edge_width : 1.0 : space below holes of FingerHoleEdge (multiples of thickness) * play : 0.0 : extra space to allow finger move in and out (multiples of thickness) * extra_length : 0.0 : extra material to grind away burn marks (multiples of thickness) * bottom_lip : 0.0 : height of the bottom lips sticking out (multiples of thickness) FingerHoleEdge only! """ absolute_params = { "style": ("rectangular", "springs", "barbs", "snap"), "surroundingspaces": 2.0, } relative_params = { "space": 2.0, "finger": 2.0, "width": 1.0, "edge_width": 1.0, "play": 0.0, "extra_length": 0.0, "bottom_lip": 0.0, } angle = 90 # Angle of the walls meeting def checkValues(self) -> None: if abs(self.space + self.finger) < 0.1: raise ValueError("FingerJointSettings: space + finger must not be close to zero") def edgeObjects(self, boxes, chars: str = "fFh", add: bool = True): edges = [FingerJointEdge(boxes, self), FingerJointEdgeCounterPart(boxes, self), FingerHoleEdge(boxes, self), ] return self._edgeObjects(edges, boxes, chars, add) class FingerJointBase(ABC): """Abstract base class for finger joint.""" def calcFingers(self, length: float, bedBolts) -> tuple[int, float]: space, finger = self.settings.space, self.settings.finger # type: ignore fingers = int((length - (self.settings.surroundingspaces - 1) * space) // (space + finger)) # type: ignore # shrink surrounding space up to half a thickness each side if fingers == 0 and length > finger + 1.0 * self.settings.thickness: # type: ignore fingers = 1 if not finger: fingers = 0 if bedBolts: fingers = bedBolts.numFingers(fingers) leftover = length - fingers * (space + finger) + space if fingers <= 0: fingers = 0 leftover = length return fingers, leftover def fingerLength(self, angle: float) -> tuple[float, float]: # sharp corners if angle >= 90 or angle <= -90: return self.settings.thickness + self.settings.extra_length, 0.0 # type: ignore # inner blunt corners if angle < 0: return (math.sin(math.radians(-angle)) * self.settings.thickness + self.settings.extra_length), 0 # type: ignore # 0 to 90 (blunt corners) a = 90 - (180 - angle) / 2.0 fingerlength = self.settings.thickness * math.tan(math.radians(a)) # type: ignore b = 90 - 2 * a spacerecess = -math.sin(math.radians(b)) * fingerlength return fingerlength + self.settings.extra_length, spacerecess # type: ignore class FingerJointEdge(BaseEdge, FingerJointBase): """Finger joint edge """ char = 'f' description = "Finger Joint" positive = True def draw_finger(self, f, h, style, positive: bool = True, firsthalf: bool = True) -> None: t = self.settings.thickness if positive: if style == "springs": self.polyline( 0, -90, 0.8 * h, (90, 0.2 * h), 0.1 * h, 90, 0.9 * h, -180, 0.9 * h, 90, f - 0.6 * h, 90, 0.9 * h, -180, 0.9 * h, 90, 0.1 * h, (90, 0.2 * h), 0.8 * h, -90) elif style == "barbs": n = int((h - 0.1 * t) // (0.3 * t)) a = math.degrees(math.atan(0.5)) l = 5 ** 0.5 poly = [h - n * 0.3 * t] + \ ([-45, 0.1 * 2 ** 0.5 * t, 45 + a, l * 0.1 * t, -a, 0] * n) self.polyline( 0, -90, *poly, 90, f, 90, *reversed(poly), -90 ) elif style == "snap" and f > 1.9 * t: a12 = math.degrees(math.atan(0.5)) l12 = t / math.cos(math.radians(a12)) d = 4 * t d2 = d + 1 * t a = math.degrees(math.atan((0.5 * t) / (h + d2))) l = (h + d2) / math.cos(math.radians(a)) poly = [0, 90, d, -180, d + h, -90, 0.5 * t, 90 + a12, l12, 90 - a12, 0.5 * t, 90 - a, l, +a, 0, (-180, 0.1 * t), h + d2, 90, f - 1.7 * t, 90 - a12, l12, a12, h, -90, 0] if firsthalf: poly = list(reversed(poly)) self.polyline(*poly) else: self.polyline(0, -90, h, 90, f, 90, h, -90) else: self.polyline(0, 90, h, -90, f, -90, h, 90) def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): positive = self.positive t = self.settings.thickness s, f = self.settings.space, self.settings.finger thickness = self.settings.thickness style = self.settings.style play = self.settings.play fingers, leftover = self.calcFingers(length, bedBolts) # not enough space for normal fingers - use small rectangular one if (fingers == 0 and f and leftover > 0.75 * thickness and leftover > 4 * play): fingers = 1 f = leftover = leftover / 2.0 bedBolts = None style = "rectangular" if not positive: f += play s -= play leftover -= play self.edge(leftover / 2.0, tabs=1) l1, l2 = self.fingerLength(self.settings.angle) h = l1 - l2 d = (bedBoltSettings or self.bedBoltSettings)[0] for i in range(fingers): if i != 0: if not positive and bedBolts and bedBolts.drawBolt(i): self.hole(0.5 * s, 0.5 * self.settings.thickness, 0.5 * d) if positive and bedBolts and bedBolts.drawBolt(i): self.bedBoltHole(s, bedBoltSettings) else: self.edge(s) self.draw_finger(f, h, style, positive, i < fingers // 2) self.edge(leftover / 2.0, tabs=1) def margin(self) -> float: """ """ widths = self.fingerLength(self.settings.angle) if self.positive: if self.settings.style == "snap": return widths[0] - widths[1] + self.settings.thickness return widths[0] - widths[1] return 0.0 def startwidth(self) -> float: widths = self.fingerLength(self.settings.angle) return widths[self.positive] class FingerJointEdgeCounterPart(FingerJointEdge): """Finger joint edge - other side""" char = 'F' description = "Finger Joint (opposing side)" positive = False class FingerHoles(FingerJointBase): """Hole matching a finger joint edge""" def __init__(self, boxes, settings) -> None: self.boxes = boxes self.ctx = boxes.ctx self.settings = settings def __call__(self, x, y, length, angle=90, bedBolts=None, bedBoltSettings=None): """ Draw holes for a matching finger joint edge :param x: x position :param y: y position :param length: length of matching edge :param angle: (Default value = 90) :param bedBolts: (Default value = None) :param bedBoltSettings: (Default value = None) """ with self.boxes.saved_context(): self.boxes.moveTo(x, y, angle) s, f = self.settings.space, self.settings.finger p = self.settings.play b = self.boxes.burn fingers, leftover = self.calcFingers(length, bedBolts) # not enough space for normal fingers - use small rectangular one if (fingers == 0 and f and leftover > 0.75 * self.settings.thickness and leftover > 4 * p): fingers = 1 f = leftover = leftover / 2.0 bedBolts = None if self.boxes.debug: self.ctx.rectangle(b, -self.settings.width / 2 + b, length - 2 * b, self.settings.width - 2 * b) for i in range(fingers): pos = leftover / 2.0 + i * (s + f) if bedBolts and bedBolts.drawBolt(i): d = (bedBoltSettings or self.boxes.bedBoltSettings)[0] self.boxes.hole(pos - 0.5 * s, 0, d * 0.5) self.boxes.rectangularHole(pos + 0.5 * f, 0, f + p, self.settings.width + p) class FingerHoleEdge(BaseEdge): """Edge with holes for a parallel finger joint""" char = 'h' description = "Edge (parallel Finger Joint Holes)" def __init__(self, boxes, fingerHoles=None, **kw) -> None: settings = None if isinstance(fingerHoles, Settings): settings = fingerHoles fingerHoles = FingerHoles(boxes, settings) super().__init__(boxes, settings, **kw) self.fingerHoles = fingerHoles or boxes.fingerHolesAt def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): dist = self.fingerHoles.settings.edge_width with self.saved_context(): self.fingerHoles( 0, self.burn + dist + self.settings.thickness / 2, length, 0, bedBolts=bedBolts, bedBoltSettings=bedBoltSettings) if self.settings.bottom_lip: h = self.settings.bottom_lip + \ self.fingerHoles.settings.edge_width sp = self.boxes.spacing self.moveTo(-sp / 2, -h - sp) self.rectangularWall(length - 1.05 * self.boxes.thickness, h) self.edge(length, tabs=2) def startwidth(self) -> float: """ """ return self.fingerHoles.settings.edge_width + self.settings.thickness def margin(self) -> float: if self.settings.bottom_lip: return self.settings.bottom_lip + self.fingerHoles.settings.edge_width + self.boxes.spacing return 0.0 class CrossingFingerHoleEdge(Edge): """Edge with holes for finger joints 90° above""" description = "Edge (orthogonal Finger Joint Holes)" char = '|' def __init__(self, boxes, height, fingerHoles=None, outset: float = 0.0, **kw) -> None: super().__init__(boxes, None, **kw) self.fingerHoles = fingerHoles or boxes.fingerHolesAt self.height = height self.outset = outset def __call__(self, length, **kw): self.fingerHoles(length / 2.0, self.outset + self.burn, self.height) super().__call__(length) def startwidth(self) -> float: return self.outset ############################################################################# #### Stackable Joints ############################################################################# class StackableSettings(Settings): """Settings for Stackable Edges Values: * absolute_params * angle : 60 : inside angle of the feet * relative (in multiples of thickness) * height : 2.0 : height of the feet (multiples of thickness) * width : 4.0 : width of the feet (multiples of thickness) * holedistance : 1.0 : distance from finger holes to bottom edge (multiples of thickness) * bottom_stabilizers : 0.0 : height of strips to be glued to the inside of bottom edges (multiples of thickness) """ absolute_params = { "angle": 60, } relative_params = { "height": 2.0, "width": 4.0, "holedistance": 1.0, "bottom_stabilizers": 0.0, } def checkValues(self) -> None: if self.angle < 20: raise ValueError("StackableSettings: 'angle' is too small. Use value >= 20") if self.angle > 260: raise ValueError("StackableSettings: 'angle' is too big. Use value < 260") def edgeObjects(self, boxes, chars: str = "sSšŠ", add: bool = True, fingersettings=None): fingersettings = fingersettings or boxes.edges["f"].settings edges = [StackableEdge(boxes, self, fingersettings), StackableEdgeTop(boxes, self, fingersettings), StackableFeet(boxes, self, fingersettings), StackableHoleEdgeTop(boxes, self, fingersettings), ] return self._edgeObjects(edges, boxes, chars, add) class StackableBaseEdge(BaseEdge): """Edge for having stackable Boxes. The Edge creates feet on the bottom and has matching recesses on the top corners.""" char = "s" description = "Abstract Stackable class" bottom = True def __init__(self, boxes, settings, fingerjointsettings) -> None: super().__init__(boxes, settings) self.fingerjointsettings = fingerjointsettings def __call__(self, length, **kw): s = self.settings r = s.height / 2.0 / (1 - math.cos(math.radians(s.angle))) l = r * math.sin(math.radians(s.angle)) p = 1 if self.bottom else -1 if self.bottom and s.bottom_stabilizers: with self.saved_context(): sp = self.boxes.spacing self.moveTo(-sp / 2) self.rectangularWall(length - 1.05 * self.boxes.thickness, s.bottom_stabilizers, move="down") self.boxes.edge(s.width, tabs=1) self.boxes.corner(p * s.angle, r) self.boxes.corner(-p * s.angle, r) self.boxes.edge(length - 2 * s.width - 4 * l) self.boxes.corner(-p * s.angle, r) self.boxes.corner(p * s.angle, r) self.boxes.edge(s.width, tabs=1) def _height(self): return self.settings.height + self.settings.holedistance + self.settings.thickness def startwidth(self) -> float: return self._height() if self.bottom else 0 def margin(self) -> float: if self.bottom: if self.settings.bottom_stabilizers: return self.settings.bottom_stabilizers + self.boxes.spacing else: return 0 else: return self.settings.height class StackableEdge(StackableBaseEdge): """Edge for having stackable Boxes. The Edge creates feet on the bottom and has matching recesses on the top corners.""" char = "s" description = "Stackable (bottom, finger joint holes)" def __call__(self, length, **kw): s = self.settings self.boxes.fingerHolesAt( 0, s.height + s.holedistance + 0.5 * self.boxes.thickness, length, 0) super().__call__(length, **kw) class StackableEdgeTop(StackableBaseEdge): char = "S" description = "Stackable (top)" bottom = False class StackableFeet(StackableBaseEdge): char = "š" description = "Stackable feet (bottom)" def _height(self): return self.settings.height class StackableHoleEdgeTop(StackableBaseEdge): char = "Š" description = "Stackable edge with finger holes (top)" bottom = False def startwidth(self) -> float: return self.settings.thickness + self.settings.holedistance def __call__(self, length, **kw): s = self.settings self.boxes.fingerHolesAt( 0, s.holedistance + 0.5 * self.boxes.thickness, length, 0) super().__call__(length, **kw) ############################################################################# #### Hinges ############################################################################# class HingeSettings(Settings): """Settings for Hinges and HingePins Values: * absolute_params * style : "outset" : "outset" or "flush" * outset : False : have lid overlap at the sides (similar to OutSetEdge) * pinwidth : 1.0 : set to lower value to get disks surrounding the pins * grip_percentage" : 0 : percentage of the lid that should get grips * relative (in multiples of thickness) * hingestrength : 1 : thickness of the arc holding the pin in place (multiples of thickness) * axle : 2 : diameter of the pin hole (multiples of thickness) * grip_length : 0 : fixed length of the grips on he lids (multiples of thickness) """ absolute_params = { "style": ("outset", "flush"), "outset": False, "pinwidth": 0.5, "grip_percentage": 0, } relative_params = { "hingestrength": 1, # 1.5-0.5*2**0.5, "axle": 2.0, "grip_length": 0, } def checkValues(self) -> None: if self.axle / self.thickness < 0.1: raise ValueError("HingeSettings: 'axle' need to be at least 0.1 strong") def edgeObjects(self, boxes, chars: str = "iIjJkK", add: bool = True): edges = [ Hinge(boxes, self, 1), HingePin(boxes, self, 1), Hinge(boxes, self, 2), HingePin(boxes, self, 2), Hinge(boxes, self, 3), HingePin(boxes, self, 3), ] return self._edgeObjects(edges, boxes, chars, add) class Hinge(BaseEdge): char = 'i' description = "Straight edge with hinge eye" def __init__(self, boxes, settings=None, layout: int = 1) -> None: super().__init__(boxes, settings) if not (0 < layout <= 3): raise ValueError("layout must be 1, 2 or 3 (got %i)" % layout) self.layout = layout self.char = "eijk"[layout] self.description = self.description + ('', ' (start)', ' (end)', ' (both ends)')[layout] def margin(self) -> float: t: float = self.settings.thickness if self.settings.style == "outset": r = 0.5 * self.settings.axle alpha = math.degrees(math.asin(0.5 * t / r)) pos = math.cos(math.radians(alpha)) * r return 1.5 * t + pos else: # flush return 0.5 * t + 0.5 * self.settings.axle + self.settings.hingestrength def outset(self, _reversed: bool = False) -> None: t: float = self.settings.thickness r = 0.5 * self.settings.axle alpha = math.degrees(math.asin(0.5 * t / r)) pinl = (self.settings.axle ** 2 - self.settings.thickness ** 2) ** 0.5 * self.settings.pinwidth pos = math.cos(math.radians(alpha)) * r hinge = ( 0., 90. - alpha, 0., (-360., r), 0., 90. + alpha, t, 90., 0.5 * t, (180., t + pos), 0., (-90., 0.5 * t), 0. ) if _reversed: hinge = reversed(hinge) # type: ignore self.polyline(*hinge) self.boxes.rectangularHole(-pos, -0.5 * t, pinl, self.settings.thickness) else: self.boxes.rectangularHole(pos, -0.5 * t, pinl, self.settings.thickness) self.polyline(*hinge) def outsetlen(self) -> float: t = self.settings.thickness r = 0.5 * self.settings.axle alpha = math.degrees(math.asin(0.5 * t / r)) pos = math.cos(math.radians(alpha)) * r return 2.0 * pos + 1.5 * t def flush(self, _reversed: bool = False) -> None: t = self.settings.thickness hinge = ( 0., -90., 0.5 * t, (180., 0.5 * self.settings.axle + self.settings.hingestrength), 0., (-90., 0.5 * t), 0. ) pos = 0.5 * self.settings.axle + self.settings.hingestrength pinl = (self.settings.axle ** 2 - self.settings.thickness ** 2) ** 0.5 * self.settings.pinwidth if _reversed: hinge = reversed(hinge) # type: ignore self.hole(0.5 * t + pos, -0.5 * t, 0.5 * self.settings.axle) self.boxes.rectangularHole(0.5 * t + pos, -0.5 * t, pinl, self.settings.thickness) else: self.hole(pos, -0.5 * t, 0.5 * self.settings.axle) self.boxes.rectangularHole(pos, -0.5 * t, pinl, self.settings.thickness) self.polyline(*hinge) def flushlen(self) -> float: return self.settings.axle + 2.0 * self.settings.hingestrength + 0.5 * self.settings.thickness def __call__(self, l, **kw): hlen = getattr(self, self.settings.style + 'len', self.outsetlen)() if self.layout & 1: getattr(self, self.settings.style, self.outset)() self.edge(l - (self.layout & 1) * hlen - bool(self.layout & 2) * hlen, tabs=2) if self.layout & 2: getattr(self, self.settings.style, self.outset)(True) class HingePin(BaseEdge): char = 'I' description = "Edge with hinge pin" def __init__(self, boxes, settings=None, layout: int = 1) -> None: super().__init__(boxes, settings) if not (0 < layout <= 3): raise ValueError("layout must be 1, 2 or 3 (got %i)" % layout) self.layout = layout self.char = "EIJK"[layout] self.description = self.description + ('', ' (start)', ' (end)', ' (both ends)')[layout] def startwidth(self) -> float: if self.layout & 1: return 0.0 return self.settings.outset * self.boxes.thickness def endwidth(self) -> float: if self.layout & 2: return 0.0 return self.settings.outset * self.boxes.thickness def margin(self) -> float: return self.settings.thickness def outset(self, _reversed: bool = False) -> None: t: float = self.settings.thickness r = 0.5 * self.settings.axle alpha = math.degrees(math.asin(0.5 * t / r)) pos = math.cos(math.radians(alpha)) * r pinl = (self.settings.axle ** 2 - self.settings.thickness ** 2) ** 0.5 * self.settings.pinwidth pin = (pos - 0.5 * pinl, -90., t, 90., pinl, 90., t, -90.) if self.settings.outset: pin += ( # type: ignore pos - 0.5 * pinl + 1.5 * t, -90., t, 90., 0., ) else: pin += (pos - 0.5 * pinl,) # type: ignore if _reversed: pin = reversed(pin) # type: ignore self.polyline(*pin) def outsetlen(self): t = self.settings.thickness r = 0.5 * self.settings.axle alpha = math.degrees(math.asin(0.5 * t / r)) pos = math.cos(math.radians(alpha)) * r if self.settings.outset: return 2 * pos + 1.5 * self.settings.thickness return 2 * pos def flush(self, _reversed: bool = False) -> None: t: float = self.settings.thickness pinl = (self.settings.axle ** 2 - t ** 2) ** 0.5 * self.settings.pinwidth d = (self.settings.axle - pinl) / 2.0 pin = (self.settings.hingestrength + d, -90., t, 90., pinl, 90., t, -90., d) if self.settings.outset: pin += ( # type: ignore 0., self.settings.hingestrength + 0.5 * t, -90., t, 90., 0., ) if _reversed: pin = reversed(pin) # type: ignore self.polyline(*pin) def flushlen(self): l = self.settings.hingestrength + self.settings.axle if self.settings.outset: l += self.settings.hingestrength + 0.5 * self.settings.thickness return l def __call__(self, l, **kw): plen = getattr(self, self.settings.style + 'len', self.outsetlen)() glen = l * self.settings.grip_percentage / 100 + \ self.settings.grip_length if not self.settings.outset: glen = 0.0 glen = min(glen, l - plen) if self.layout & 1 and self.layout & 2: getattr(self, self.settings.style, self.outset)() self.edge(l - 2 * plen, tabs=2) getattr(self, self.settings.style, self.outset)(True) elif self.layout & 1: getattr(self, self.settings.style, self.outset)() self.edge(l - plen - glen, tabs=2) self.edges['g'](glen) else: self.edges['g'](glen) self.edge(l - plen - glen, tabs=2) getattr(self, self.settings.style, self.outset)(True) ############################################################################# #### Chest Hinge ############################################################################# class ChestHingeSettings(Settings): """Settings for Chest Hinges Values: * relative (in multiples of thickness) * pin_height : 2.0 : radius of the disc rotating in the hinge (multiples of thickness) * hinge_strength : 1.0 : thickness of the arc holding the pin in place (multiples of thickness) * absolute * finger_joints_on_box : False : whether to include finger joints on the edge with the box * finger_joints_on_lid : False : whether to include finger joints on the edge with the lid """ relative_params = { "pin_height": 2.0, "hinge_strength": 1.0, "play": 0.1, } absolute_params = { "finger_joints_on_box": False, "finger_joints_on_lid": False, } def checkValues(self) -> None: if self.pin_height / self.thickness < 1.2: raise ValueError("ChestHingeSettings: 'pin_height' must be >= 1.2") def pinheight(self): return ((0.9 * self.pin_height) ** 2 - self.thickness ** 2) ** 0.5 def edgeObjects(self, boxes, chars: str = "oOpPqQ", add: bool = True): edges = [ ChestHinge(boxes, self), ChestHinge(boxes, self, True), ChestHingeTop(boxes, self), ChestHingeTop(boxes, self, True), ChestHingePin(boxes, self), ChestHingeFront(boxes, self), ] return self._edgeObjects(edges, boxes, chars, add) class ChestHinge(BaseEdge): description = "Edge with chest hinge" char = "o" def __init__(self, boxes, settings=None, reversed: bool = False) -> None: super().__init__(boxes, settings) self.reversed = reversed self.char = "oO"[reversed] self.description = self.description + (' (start)', ' (end)')[reversed] def __call__(self, l, **kw): t = self.settings.thickness p = self.settings.pin_height s = self.settings.hinge_strength pinh = self.settings.pinheight() if self.reversed: self.hole(l + t, 0, p, tabs=4) self.rectangularHole(l + 0.5 * t, -0.5 * pinh, t, pinh) else: self.hole(-t, -s - p, p, tabs=4) self.rectangularHole(-0.5 * t, -s - p - 0.5 * pinh, t, pinh) if self.settings.finger_joints_on_box: final_segment = t - s draw_rest_of_edge = lambda: self.edges["F"](l - p) else: final_segment = l + t - p - s draw_rest_of_edge = lambda: None poly = (0, -180, t, (270, p + s), 0, -90, final_segment) if self.reversed: draw_rest_of_edge() self.polyline(*reversed(poly)) else: self.polyline(*poly) draw_rest_of_edge() def margin(self) -> float: if self.reversed: return 0.0 return 1 * (self.settings.pin_height + self.settings.hinge_strength) def startwidth(self) -> float: if self.reversed: return self.settings.pin_height + self.settings.hinge_strength return 0.0 def endwidth(self) -> float: if self.reversed: return 0.0 return self.settings.pin_height + self.settings.hinge_strength class ChestHingeTop(ChestHinge): """Edge above a chest hinge""" char = "p" def __init__(self, boxes, settings=None, reversed: bool = False) -> None: super().__init__(boxes, settings) self.reversed = reversed self.char = "oO"[reversed] self.description = self.description + (' (start)', ' (end)')[reversed] def __call__(self, l, **kw): t = self.settings.thickness p = self.settings.pin_height s = self.settings.hinge_strength play = self.settings.play if self.settings.finger_joints_on_lid: final_segment = t - s - play draw_rest_of_edge = lambda: self.edges["F"](l - p) else: final_segment = l + t - p - s - play draw_rest_of_edge = lambda: None poly = (0, -180, t, -180, 0, (-90, p + s + play), 0, 90, final_segment) if self.reversed: draw_rest_of_edge() self.polyline(*reversed(poly)) else: self.polyline(*poly) draw_rest_of_edge() def startwidth(self) -> float: if self.reversed: return self.settings.play + self.settings.pin_height + self.settings.hinge_strength return 0.0 def endwidth(self) -> float: if self.reversed: return 0.0 return self.settings.play + self.settings.pin_height + self.settings.hinge_strength def margin(self) -> float: if self.reversed: return 0.0 return 1 * (self.settings.play + self.settings.pin_height + self.settings.hinge_strength) class ChestHingePin(BaseEdge): description = "Edge with pins for an chest hinge" char = "q" def __call__(self, l, **kw): t = self.settings.thickness p = self.settings.pin_height s = self.settings.hinge_strength pinh = self.settings.pinheight() if self.settings.finger_joints_on_lid: middle_segment = [0] draw_rest_of_edge = lambda: (self.edge(t), self.edges["F"](l), self.edge(t)) else: middle_segment = [l + 2 * t, ] draw_rest_of_edge = lambda: None poly = [0, -90, s + p - pinh, -90, t, 90, pinh, 90, ] self.polyline(*poly) draw_rest_of_edge() self.polyline(*(middle_segment + list(reversed(poly)))) def margin(self) -> float: return (self.settings.pin_height + self.settings.hinge_strength) class ChestHingeFront(Edge): description = "Edge opposing a chest hinge" char = "Q" def startwidth(self) -> float: return self.settings.pin_height + self.settings.hinge_strength ############################################################################# #### Cabinet Hinge ############################################################################# class CabinetHingeSettings(Settings): """Settings for Cabinet Hinges Values: * absolute_params * bore : 3.2 : diameter of the pin hole in mm * eyes_per_hinge : 5 : pieces per hinge * hinges : 2 : number of hinges per edge * style : inside : style of hinge used * relative (in multiples of thickness) * eye : 1.5 : radius of the eye (multiples of thickness) * play : 0.05 : space between eyes (multiples of thickness) * spacing : 2.0 : minimum space around the hinge (multiples of thickness) """ absolute_params = { "bore": 3.2, "eyes_per_hinge": 5, "hinges": 2, "style": ("inside", "outside"), } relative_params = { "eye": 1.5, "play": 0.05, "spacing": 2.0, } def edgeObjects(self, boxes, chars: str = "uUvV", add: bool = True): edges = [CabinetHingeEdge(boxes, self), CabinetHingeEdge(boxes, self, top=True), CabinetHingeEdge(boxes, self, angled=True), CabinetHingeEdge(boxes, self, top=True, angled=True), ] for e, c in zip(edges, chars): e.char = c return self._edgeObjects(edges, boxes, chars, add) class CabinetHingeEdge(BaseEdge): """Edge with cabinet hinges""" char = "u" description = "Edge with cabinet hinges" def __init__(self, boxes, settings=None, top: bool = False, angled: bool = False) -> None: super().__init__(boxes, settings) self.top = top self.angled = angled self.char = "uUvV"[bool(top) + 2 * bool(angled)] def startwidth(self) -> float: return self.settings.thickness if self.top and self.angled else 0.0 def __poly(self): n = self.settings.eyes_per_hinge p = self.settings.play e = self.settings.eye t = self.settings.thickness spacing = self.settings.spacing if self.settings.style == "outside" and self.angled: e = t elif self.angled and not self.top: # move hinge up to leave space for lid e -= t if self.top: # start with space poly = [spacing, 90, e + p] else: # start with hinge eye poly = [spacing + p, 90, e + p, 0] for i in range(n): if (i % 2) ^ self.top: # space if i == 0: poly += [-90, t + 2 * p, 90] else: poly += [90, t + 2 * p, 90] else: # hinge eye poly += [t - p, -90, t, -90, t - p] if (n % 2) ^ self.top: # stopped with hinge eye poly += [0, e + p, 90, p + spacing] else: # stopped with space poly[-1:] = [-90, e + p, 90, 0 + spacing] width = (t + p) * n + p + 2 * spacing return poly, width def __call__(self, l, **kw): n = self.settings.eyes_per_hinge p = self.settings.play e = self.settings.eye t = self.settings.thickness hn = self.settings.hinges poly, width = self.__poly() if self.settings.style == "outside" and self.angled: e = t elif self.angled and not self.top: # move hinge up to leave space for lid e -= t hn = min(hn, int(l // width)) if hn == 1: self.edge((l - width) / 2, tabs=2) for j in range(hn): for i in range(n): if not (i % 2) ^ self.top: self.rectangularHole(self.settings.spacing + 0.5 * t + p + i * (t + p), e + 2.5 * t, t, t) self.polyline(*poly) if j < (hn - 1): self.edge((l - hn * width) / (hn - 1), tabs=2) if hn == 1: self.edge((l - width) / 2, tabs=2) def parts(self, move=None) -> None: e, b = self.settings.eye, self.settings.bore t = self.settings.thickness n = self.settings.eyes_per_hinge * self.settings.hinges pairs = n // 2 + 2 * (n % 2) if self.settings.style == "outside": th = 2 * e + 4 * t tw = n * (max(3 * t, 2 * e) + self.boxes.spacing) else: th = 4 * e + 3 * t + self.boxes.spacing tw = max(e, 2 * t) * pairs if self.move(tw, th, move, True, label="hinges"): return if self.settings.style == "outside": ax = max(t / 2, e - t) self.moveTo(t + ax) for i in range(n): if self.angled: if i > n // 2: l = 4 * t + ax else: l = 5 * t + ax else: l = 3 * t + e self.hole(0, e, b / 2.0) da = math.asin((t - ax) / e) dad = math.degrees(da) dy = e * (1 - math.cos(da)) self.polyline(0, (180 - dad, e), 0, (-90 + dad), dy + l - e, (90, t)) self.polyline(0, 90, t, -90, t, 90, t, 90, t, -90, t, -90, t, 90, t, 90, (ax + t) - e, -90, l - 3 * t, (90, e)) self.moveTo(2 * max(e, 1.5 * t) + self.boxes.spacing) self.move(tw, th, move, label="hinges") return if e <= 2 * t: if self.angled: corner = [2 * e - t, (90, 2 * t - e), 0, -90, t, (90, e)] else: corner = [2 * e, (90, 2 * t)] else: a = math.asin(2 * t / e) ang = math.degrees(a) corner = [e * (1 - math.cos(a)) + 2 * t, -90 + ang, 0, (180 - ang, e)] self.moveTo(max(e, 2 * t)) for i in range(n): self.hole(0, e, b / 2.0) self.polyline(*[0, (180, e), 0, -90, t, 90, t, -90, t, -90, t, 90, t, 90, t, (90, t)] + corner) self.moveTo(self.boxes.spacing, 4 * e + 3 * t + self.boxes.spacing, 180) if i % 2: self.moveTo(2 * max(e, 2 * t) + 2 * self.boxes.spacing) self.move(th, tw, move, label="hinges") ############################################################################# #### Slide-on lid ############################################################################# class SlideOnLidSettings(FingerJointSettings): """Settings for Slide-on Lids Note that edge_width below also determines how much the sides extend above the lid. Values: * absolute_params * second_pin : True : additional pin for better positioning * spring : "both" : position(s) of the extra locking springs in the lid * hole_width : 0 : width of the "finger hole" in mm """ __doc__ += FingerJointSettings.__doc__ or "" absolute_params = FingerJointSettings.absolute_params.copy() relative_params = FingerJointSettings.relative_params.copy() relative_params.update({ "play": 0.05, "finger": 3.0, "space": 2.0, }) absolute_params.update({ "second_pin": True, "spring": ("both", "none", "left", "right"), "hole_width": 0 }) def edgeObjects(self, boxes, chars=None, add: bool = True): edges = [LidEdge(boxes, self), LidHoleEdge(boxes, self), LidRight(boxes, self), LidLeft(boxes, self), LidSideRight(boxes, self), LidSideLeft(boxes, self), ] return self._edgeObjects(edges, boxes, chars, add) class LidEdge(FingerJointEdge): char = "l" description = "Edge for slide on lid (back)" def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw): hole_width = self.settings.hole_width if hole_width > 0: super().__call__((length - hole_width) / 2) GroovedEdgeBase.groove_arc(self, hole_width) super().__call__((length - hole_width) / 2) else: super().__call__(length) class LidHoleEdge(FingerHoleEdge): char = "L" description = "Edge for slide on lid (box back)" def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw) -> None: hole_width = self.settings.hole_width if hole_width > 0: super().__call__((length - hole_width) / 2) self.edge(hole_width) super().__call__((length - hole_width) / 2) else: super().__call__(length) class LidRight(BaseEdge): char = "n" description = "Edge for slide on lid (right)" rightside = True def __call__(self, length, **kw): t = self.boxes.thickness if self.rightside: spring = self.settings.spring in ("right", "both") else: spring = self.settings.spring in ("left", "both") if spring: l = min(6 * t, length - 2 * t) a = 30 sqt = 0.4 * t / math.cos(math.radians(a)) sw = 0.5 * t p = [0, 90, 1.5 * t + sw, -90, l, (-180, 0.25 * t), l - 0.2 * t, 90, sw, 90 - a, sqt, 2 * a, sqt, -a, length - t] else: p = [t, 90, t, -90, length - t] pin = self.settings.second_pin if pin: pinl = 2 * t p[-1:] = [length - 2 * t - pinl, -90, t, 90, pinl, 90, t, -90, t] if not self.rightside: p = list(reversed(p)) self.polyline(*p) def startwidth(self) -> float: if self.rightside: # or self.settings.second_pin: return self.boxes.thickness return 0.0 def endwidth(self) -> float: if not self.rightside: # or self.settings.second_pin: return self.boxes.thickness return 0.0 def margin(self) -> float: if not self.rightside: # and not self.settings.second_pin: return self.boxes.thickness return 0.0 class LidLeft(LidRight): char = "m" description = "Edge for slide on lid (left)" rightside = False class LidSideRight(BaseEdge): char = "N" description = "Edge for slide on lid (box right)" rightside = True def __call__(self, length, **kw): t = self.boxes.thickness s = self.settings.play pin = self.settings.second_pin edge_width = self.settings.edge_width r = edge_width / 3 if self.rightside: spring = self.settings.spring in ("right", "both") else: spring = self.settings.spring in ("left", "both") if spring: p = [s, -90, t + s, -90, t + s, 90, edge_width - s / 2, 90, length + t] else: p = [t + s, -90, t + s, -90, 2 * t + s, 90, edge_width - s / 2, 90, length + t] if pin: pinl = 2 * t p[-1:] = [p[-1] - 1.5 * t - 2 * pinl - r, (90, r), edge_width + t + s / 2 - r, -90, 2 * pinl + s + 0.5 * t, -90, t + s, -90, pinl - r, (90, r), edge_width - s / 2 - 2 * r, (90, r), pinl + t - s - r] holex = 0.6 * t holey = -0.5 * t + self.burn - s / 2 if self.rightside: p = list(reversed(p)) holex = length - holex holey = edge_width + 0.5 * t + self.burn if spring: self.rectangularHole(holex, holey, 0.4 * t, t + 2 * s) self.polyline(*p) def startwidth(self) -> float: return self.boxes.thickness + self.settings.edge_width if self.rightside else -self.settings.play / 2 def endwidth(self) -> float: return self.boxes.thickness + self.settings.edge_width if not self.rightside else -self.settings.play / 2 def margin(self) -> float: return self.boxes.thickness + self.settings.edge_width + self.settings.play / 2 if not self.rightside else 0.0 class LidSideLeft(LidSideRight): char = "M" description = "Edge for slide on lid (box left)" rightside = False ############################################################################# #### Click Joints ############################################################################# class ClickSettings(Settings): """Settings for Click-on Lids Values: * absolute_params * angle : 5.0 : angle of the hooks bending outward * relative (in multiples of thickness) * depth : 3.0 : length of the hooks (multiples of thickness) * bottom_radius : 0.1 : radius at the bottom (multiples of thickness) """ absolute_params = { "angle": 5.0, } relative_params = { "depth": 3.0, "bottom_radius": 0.1, } def edgeObjects(self, boxes, chars: str = "cC", add: bool = True): edges = [ClickConnector(boxes, self), ClickEdge(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class ClickConnector(BaseEdge): char = "c" description = "Click on (bottom side)" def hook(self, reverse: bool = False) -> None: t = self.settings.thickness a = self.settings.angle d = self.settings.depth r = self.settings.bottom_radius c = math.cos(math.radians(a)) s = math.sin(math.radians(a)) p1 = (0, 90 - a, c * d) p2 = ( d + t, -90, t * 0.5, 135, t * 2 ** 0.5, 135, d + 2 * t + s * 0.5 * t) p3 = (c * d - s * c * 0.2 * t, -a, 0) if not reverse: self.polyline(*p1) self.corner(-180, r) self.polyline(*p2) self.corner(-180 + 2 * a, r) self.polyline(*p3) else: self.polyline(*reversed(p3)) self.corner(-180 + 2 * a, r) self.polyline(*reversed(p2)) self.corner(-180, r) self.polyline(*reversed(p1)) def hookWidth(self): t = self.settings.thickness a = self.settings.angle d = self.settings.depth r = self.settings.bottom_radius c = math.cos(math.radians(a)) s = math.sin(math.radians(a)) return 2 * s * d * c + 0.5 * c * t + c * 4 * r def hookOffset(self): a = self.settings.angle d = self.settings.depth r = self.settings.bottom_radius c = math.cos(math.radians(a)) s = math.sin(math.radians(a)) return s * d * c + 2 * r def finger(self, length) -> None: t = self.settings.thickness self.polyline( 2 * t, 90, length, 90, 2 * t, ) def __call__(self, length, **kw): t = self.settings.thickness self.edge(4 * t) self.hook() self.finger(2 * t) self.hook(reverse=True) self.edge(length - 2 * (6 * t + 2 * self.hookWidth()), tabs=2) self.hook() self.finger(2 * t) self.hook(reverse=True) self.edge(4 * t) def margin(self) -> float: return 2 * self.settings.thickness class ClickEdge(ClickConnector): char = "C" description = "Click on (top)" def startwidth(self) -> float: return self.boxes.thickness def margin(self) -> float: return 0.0 def __call__(self, length, **kw): t = self.settings.thickness o = self.hookOffset() w = self.hookWidth() p1 = ( 4 * t + o, 90, t, -90, 2 * (t + w - o), -90, t, 90, 0) self.polyline(*p1) self.edge(length - 2 * (6 * t + 2 * w) + 2 * o, tabs=2) self.polyline(*reversed(p1)) ############################################################################# #### Dove Tail Joints ############################################################################# class DoveTailSettings(Settings): """Settings for Dove Tail Joints Values: * absolute * angle : 50 : how much should fingers widen (-80 to 80) * relative (in multiples of thickness) * size : 3 : from one middle of a dove tail to another (multiples of thickness) * depth : 1.5 : how far the dove tails stick out of/into the edge (multiples of thickness) * radius : 0.2 : radius used on all four corners (multiples of thickness) """ absolute_params = { "angle": 50, } relative_params = { "size": 3, "depth": 1.5, "radius": 0.2, } def edgeObjects(self, boxes, chars: str = "dD", add: bool = True): edges = [DoveTailJoint(boxes, self), DoveTailJointCounterPart(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class DoveTailJoint(BaseEdge): """Edge with dove tail joints """ char = 'd' description = "Dove Tail Joint" positive = True def __call__(self, length, **kw): s = self.settings radius = max(s.radius, self.boxes.burn) # no smaller than burn positive = self.positive a = s.angle + 90 alpha = 0.5 * math.pi - math.pi * s.angle / 180.0 l1 = radius / math.tan(alpha / 2.0) diffx = 0.5 * s.depth / math.tan(alpha) l2 = 0.5 * s.depth / math.sin(alpha) sections = int((length) // (s.size * 2)) leftover = length - sections * s.size * 2 if sections == 0: self.edge(length) return p = 1 if positive else -1 self.edge((s.size + leftover) / 2.0 + diffx - l1, tabs=1) for i in range(sections): self.corner(-1 * p * a, radius) self.edge(2 * (l2 - l1)) self.corner(p * a, radius) self.edge(2 * (diffx - l1) + s.size) self.corner(p * a, radius) self.edge(2 * (l2 - l1)) self.corner(-1 * p * a, radius) if i < sections - 1: # all but the last self.edge(2 * (diffx - l1) + s.size) self.edge((s.size + leftover) / 2.0 + diffx - l1, tabs=1) def margin(self) -> float: """ """ return self.settings.depth class DoveTailJointCounterPart(DoveTailJoint): """Edge for other side of dove joints """ char = 'D' description = "Dove Tail Joint (opposing side)" positive = False def margin(self) -> float: return 0.0 class FlexSettings(Settings): """Settings for Flex Values: * absolute * stretch : 1.05 : Hint of how much the flex part should be shortened * relative (in multiples of thickness) * distance : 0.5 : width of the pattern perpendicular to the cuts (multiples of thickness) * connection : 1.0 : width of the gaps in the cuts (multiples of thickness) * width : 5.0 : width of the pattern in direction of the cuts (multiples of thickness) """ relative_params = { "distance": 0.5, "connection": 1.0, "width": 5.0, } absolute_params = { "stretch": 1.05, } def checkValues(self) -> None: if self.distance < 0.01: raise ValueError("Flex Settings: distance parameter must be > 0.01mm") if self.width < 0.1: raise ValueError("Flex Settings: width parameter must be > 0.1mm") class FlexEdge(BaseEdge): """Edge with flex cuts - use straight edge for the opposing side""" char = 'X' description = "Flex cut" def __call__(self, x, h, **kw): dist = self.settings.distance connection = self.settings.connection width = self.settings.width burn = self.boxes.burn h += 2 * burn lines = int(x // dist) leftover = x - lines * dist sections = max(int((h - connection) // width), 1) sheight = ((h - connection) / sections) - connection self.ctx.stroke() for i in range(1, lines): pos = i * dist + leftover / 2 if i % 2: self.ctx.move_to(pos, 0) self.ctx.line_to(pos, connection + sheight) for j in range((sections - 1) // 2): self.ctx.move_to(pos, (2 * j + 1) * sheight + (2 * j + 2) * connection) self.ctx.line_to(pos, (2 * j + 3) * (sheight + connection)) if not sections % 2: self.ctx.move_to(pos, h - sheight - connection) self.ctx.line_to(pos, h) else: if sections % 2: self.ctx.move_to(pos, h) self.ctx.line_to(pos, h - connection - sheight) for j in range((sections - 1) // 2): self.ctx.move_to( pos, h - ((2 * j + 1) * sheight + (2 * j + 2) * connection)) self.ctx.line_to( pos, h - (2 * j + 3) * (sheight + connection)) else: for j in range(sections // 2): self.ctx.move_to(pos, h - connection - 2 * j * (sheight + connection)) self.ctx.line_to(pos, h - 2 * (j + 1) * (sheight + connection)) self.ctx.stroke() self.ctx.move_to(0, 0) self.ctx.line_to(x, 0) self.ctx.translate(*self.ctx.get_current_point()) class GearSettings(Settings): """Settings for rack (and pinion) edge Values: * absolute_params * dimension : 3.0 : modulus of the gear (in mm) * angle : 20.0 : pressure angle * profile_shift : 20.0 : Profile shift * clearance : 0.0 : clearance """ absolute_params = { "dimension": 3.0, "angle": 20.0, "profile_shift": 20.0, "clearance": 0.0, } relative_params: dict[str, Any] = {} class RackEdge(BaseEdge): char = "R" description = "Rack (and pinion) Edge" def __init__(self, boxes, settings) -> None: super().__init__(boxes, settings) self.gear = gears.Gears(boxes) def __call__(self, length, **kw): params = self.settings.values.copy() params["draw_rack"] = True params["rack_base_height"] = -1E-36 params["rack_teeth_length"] = int(length // (params["dimension"] * math.pi)) params["rack_base_tab"] = (length - (params["rack_teeth_length"]) * params["dimension"] * math.pi) / 2.0 s_tmp = self.boxes.spacing self.boxes.spacing = 0 self.moveTo(length, 0, 180) self.gear(move="", **params) self.moveTo(0, 0, 180) self.boxes.spacing = s_tmp def margin(self) -> float: return self.settings.dimension * 1.1 class RoundedTriangleEdgeSettings(Settings): """Settings for RoundedTriangleEdge Values: * absolute_params * height : 150. : height above the wall * radius : 30. : radius of top corner * r_hole : 0. : radius of hole * relative (in multiples of thickness) * outset : 0 : extend the triangle along the length of the edge (multiples of thickness) """ absolute_params = { "height": 50., "radius": 30., "r_hole": 2., } relative_params = { "outset": 0., } def edgeObjects(self, boxes, chars: str = "t", add: bool = True): edges = [RoundedTriangleEdge(boxes, self), RoundedTriangleFingerHolesEdge(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) class RoundedTriangleEdge(Edge): """Makes an 'edge' with a rounded triangular bumpout and optional hole""" description = "Triangle for handle" char = "t" def __call__(self, length, **kw): length += 2 * self.settings.outset r = self.settings.radius if r > length / 2: r = length / 2 if length - 2 * r < self.settings.height: # avoid division by zero angle = 90 - math.degrees(math.atan( (length - 2 * r) / (2 * self.settings.height))) l = self.settings.height / math.cos(math.radians(90 - angle)) else: angle = math.degrees(math.atan( 2 * self.settings.height / (length - 2 * r))) l = 0.5 * (length - 2 * r) / math.cos(math.radians(angle)) if self.settings.outset: self.polyline(0, -180, self.settings.outset, 90) else: self.corner(-90) if self.settings.r_hole: self.hole(self.settings.height, length / 2., self.settings.r_hole) self.corner(90 - angle, r, tabs=1) self.edge(l, tabs=1) self.corner(2 * angle, r, tabs=1) self.edge(l, tabs=1) self.corner(90 - angle, r, tabs=1) if self.settings.outset: self.polyline(0, 90, self.settings.outset, -180) else: self.corner(-90) def margin(self) -> float: return self.settings.height + self.settings.radius class RoundedTriangleFingerHolesEdge(RoundedTriangleEdge): char = "T" def startwidth(self) -> float: return self.settings.thickness def __call__(self, length, **kw): self.fingerHolesAt(0, 0.5 * self.settings.thickness, length, 0) super().__call__(length, **kw) class HandleEdgeSettings(Settings): """Settings for HandleEdge Values: * absolute_params * height : 20. : height above the wall in mm * radius : 10. : radius of corners in mm * hole_width : "40:40" : width of hole(s) in percentage of maximum hole width (width of edge - (n+1) * material thickness) * hole_height : 75. : height of hole(s) in percentage of maximum hole height (handle height - 2 * material thickness) * on_sides : True, : added to side panels if checked, to front and back otherwise (only used with top_edge parameter) * relative * outset : 1. : extend the handle along the length of the edge (multiples of thickness) """ absolute_params = { "height": 20., "radius": 10., "hole_width": "40:40", "hole_height": 75., "on_sides": True, } relative_params = { "outset": 1., } def edgeObjects(self, boxes, chars: str = "yY", add: bool = True): edges = [HandleEdge(boxes, self), HandleHoleEdge(boxes, self)] return self._edgeObjects(edges, boxes, chars, add) # inspiration came from https://www.thingiverse.com/thing:327393 class HandleEdge(Edge): """Extends an 'edge' by adding a rounded bumpout with optional holes""" description = "Handle for e.g. a drawer" char = "y" extra_height = 0.0 def __call__(self, length, **kw): length += 2 * self.settings.outset extra_height = self.extra_height * self.settings.thickness r = self.settings.radius if r > length / 2: r = length / 2 if r > self.settings.height: r = self.settings.height widths = argparseSections(self.settings.hole_width) if self.settings.outset: self.polyline(0, -180, self.settings.outset, 90) else: self.corner(-90) if self.settings.hole_height and sum(widths) > 0: if sum(widths) < 100: slot_offset = ((1 - sum(widths) / 100) * (length - (len(widths) + 1) * self.thickness)) / (len(widths) * 2) else: slot_offset = 0 slot_height = (self.settings.height - 2 * self.thickness) * self.settings.hole_height / 100 slot_x = self.thickness + slot_offset for w in widths: if sum(widths) > 100: slotwidth = w / sum(widths) * (length - (len(widths) + 1) * self.thickness) else: slotwidth = w / 100 * (length - (len(widths) + 1) * self.thickness) slot_x += slotwidth / 2 with self.saved_context(): self.moveTo((self.settings.height / 2) + extra_height, slot_x, 0) self.rectangularHole(0, 0, slot_height, slotwidth, slot_height / 2, True, True) slot_x += slotwidth / 2 + slot_offset + self.thickness + slot_offset self.edge(self.settings.height - r + extra_height, tabs=1) self.corner(90, r, tabs=1) self.edge(length - 2 * r, tabs=1) self.corner(90, r, tabs=1) self.edge(self.settings.height - r + extra_height, tabs=1) if self.settings.outset: self.polyline(0, 90, self.settings.outset, -180) else: self.corner(-90) def margin(self) -> float: return self.settings.height class HandleHoleEdge(HandleEdge): """Extends an 'edge' by adding a rounded bumpout with optional holes and holes for parallel finger joint""" description = "Handle with holes for parallel finger joint" char = "Y" extra_height = 1.0 def __call__(self, length, **kw): self.fingerHolesAt(0, -0.5 * self.settings.thickness, length, 0) super().__call__(length, **kw) def margin(self) -> float: return self.settings.height + self.extra_height * self.settings.thickness
86,102
Python
.py
2,098
31.535272
136
0.544858
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,544
closedbox.py
florianfesti_boxes/boxes/generators/closedbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class ClosedBox(Boxes): """Fully closed box""" ui_group = "Box" description = """This box is more of a building block than a finished item. Use a vector graphics program (like Inkscape) to add holes or adjust the base plate. See BasedBox for variant with a base.""" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser("x", "y", "h", "outside") def render(self): x, y, h = self.x, self.y, self.h if self.outside: x = self.adjustSize(x) y = self.adjustSize(y) h = self.adjustSize(h) t = self.thickness d2 = edges.Bolts(2) d3 = edges.Bolts(3) d2 = d3 = None self.rectangularWall(x, h, "FFFF", bedBolts=[d2] * 4, move="right", label="Wall 1") self.rectangularWall(y, h, "FfFf", bedBolts=[d3, d2, d3, d2], move="up", label="Wall 2") self.rectangularWall(y, h, "FfFf", bedBolts=[d3, d2, d3, d2], label="Wall 4") self.rectangularWall(x, h, "FFFF", bedBolts=[d2] *4, move="left up", label="Wall 3") self.rectangularWall(x, y, "ffff", bedBolts=[d2, d3, d2, d3], move="right", label="Top") self.rectangularWall(x, y, "ffff", bedBolts=[d2, d3, d2, d3], label="Bottom")
2,030
Python
.py
42
42.785714
96
0.656868
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,545
concaveknob.py
florianfesti_boxes/boxes/generators/concaveknob.py
# Copyright (C) 2013-2017 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class ConcaveKnob(Boxes): """Round knob serrated outside for better gripping""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) # Add non default cli params if needed (see argparse std lib) self.argparser.add_argument( "--diameter", action="store", type=float, default=50., help="Diameter of the knob (mm)") self.argparser.add_argument( "--serrations", action="store", type=int, default=3, help="Number of serrations") self.argparser.add_argument( "--rounded", action="store", type=float, default=.2, help="Amount of circumference used for non convex parts") self.argparser.add_argument( "--angle", action="store", type=float, default=70., help="Angle between convex and concave parts") self.argparser.add_argument( "--bolthole", action="store", type=float, default=6., help="Diameter of the bolt hole (mm)") self.argparser.add_argument( "--dhole", action="store", type=float, default=1., help="D-Flat in fraction of the diameter") self.argparser.add_argument( "--hexhead", action="store", type=float, default=10., help="Width of the hex bolt head (mm)") def render(self): t = self.thickness self.parts.concaveKnob(self.diameter, self.serrations, self.rounded, self.angle, callback=lambda:self.dHole(0, 0, d=self.bolthole, rel_w=self.dhole), move="right") self.parts.concaveKnob(self.diameter, self.serrations, self.rounded, self.angle, callback=lambda: self.nutHole(self.hexhead), move="right") self.parts.concaveKnob(self.diameter, self.serrations, self.rounded, self.angle)
2,847
Python
.py
56
38.625
76
0.588362
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,546
sevensegment.py
florianfesti_boxes/boxes/generators/sevensegment.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class SevenSegmentPattern(Boxes): """Holepatterns and walls for a seven segment digit""" description = """This pattern is indented to be used with a LED stripe that is wound through all segments in an S pattern while the stripe being upright on its side. It can also be used with small pieces of LED stripes connected with short wires for large enough sizes. """ ui_group = "Holes" def __init__(self): Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--digit", action="store", type=float, default=100.0, help="height of the digit (without walls) in mm") self.argparser.add_argument( "--h", action="store", type=float, default=20.0, help="height separation walls in mm") @restore @holeCol def segment(self, l, w): w2 = w * 2**0.5 self.moveTo(0, 0, 45) self.polyline(w2, -45, l-2*w, -45, w2, -90, w2, -45, l-2*w, -45, w2, -90) @restore def seven_segments(self, x): t = self.thickness l = 0.4 * x w = 0.05 * x d = 0.05 * x width = l + 2*w + d # 0.55 * x #self.rectangularHole(width/2, x/2, width, x) for px in [w/2 + d/2 , w/2 + l + 1.5*d]: for py in [w + d/2, w + l + 1.5*d]: with self.saved_context(): self.moveTo(px, py, 90) self.segment(l, w) for i in range(3): with self.saved_context(): self.moveTo(w/2 + d, w + i*(l+d)) self.segment(l, w) def seven_segment_holes(self, x): t = self.thickness l = 0.4 * x w = 0.05 * x d = 0.05 * x width = l + 2*w + d for i in range(2): self.fingerHolesAt(t/4*2**.5, x/2+w-t/4*2**.5, 2**0.5*(width-t) - t/2, -45) self.fingerHolesAt(t, t, 2**0.5* (.55*x/2 - t) - t/2, 45) self.fingerHolesAt(width/2 + t/2**.5/2, width/2 + t/2**.5/2, 2**0.5*(l/2+d/2) - 1.5*t, 45) self.fingerHolesAt(-t/2, x/2 + 0.25*t, x/2 - 0.25*t, 90) self.fingerHolesAt(-t/2, 0, x/2 - 0.25*t, 90) self.fingerHolesAt(-t, -t/2, l + 2*w + d + 2*t, 0) self.moveTo(width, x, 180) def seven_segment_separators(self, x, h, n=1): t = self.thickness l = 0.4 * x w = 0.05 * x d = 0.05 * x width = l + 2*w + d # 0.55 * x for length in ( 2**0.5*(width-t) - t/2, 2**0.5* x/4 - t, 2**0.5*(l/2+d/2) - 1.5*t, x/2 - 0.25*t, x/2 - 0.25*t, l + 2*w + d + 2*t,): self.partsMatrix(2*n, 1, "right", self.rectangularWall, length, h, "feee") def render(self): digit, h = self.digit, self.h t = self.thickness self.seven_segments(digit) self.moveTo(0.55*digit+self.spacing+t, t) #self.seven_segments(digit) self.seven_segment_holes(digit) self.moveTo(0.55*digit+self.spacing+t, -t) self.seven_segment_separators(digit, h)
4,007
Python
.py
94
32.702128
273
0.539507
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,547
_swtemplate.py
florianfesti_boxes/boxes/generators/_swtemplate.py
# Copyright (C) 2013-2019 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # mypy: ignore-errors from boxes import * class SlatwallXXX(Boxes): # Change class name! """DESCRIPTION""" ui_group = "SlatWall" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.SlatWallSettings) # remove cli params you do not need self.buildArgParser(x=100, sx="3*50", y=100, sy="3*50", h=100, hi=0) # Add non default cli params if needed (see argparse std lib) self.argparser.add_argument( "--XX", action="store", type=float, default=0.5, help="DESCRIPTION") def render(self): # Add slat wall edges s = edges.SlatWallSettings(self.thickness, True, **self.edgesettings.get("SlatWall", {})) s.edgeObjects(self) self.slatWallHolesAt = edges.SlatWallHoles(self, s) # render your parts here
1,641
Python
.py
36
39.555556
76
0.676489
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,548
wavyknob.py
florianfesti_boxes/boxes/generators/wavyknob.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class WavyKnob(Boxes): """Round knob serrated outside for better gripping""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) # Add non default cli params if needed (see argparse std lib) self.argparser.add_argument( "--diameter", action="store", type=float, default=50., help="Diameter of the knob (mm)") self.argparser.add_argument( "--serrations", action="store", type=int, default=20, help="Number of serrations") self.argparser.add_argument( "--serrationangle", action="store", type=float, default=45., help="higher values for deeper serrations (degrees)") self.argparser.add_argument( "--bolthole", action="store", type=float, default=6., help="Diameter of the bolt hole (mm)") self.argparser.add_argument( "--dhole", action="store", type=float, default=1., help="D-Flat in fraction of the diameter") self.argparser.add_argument( "--hexhead", action="store", type=float, default=10., help="Width of the hex bolt head (mm)") def render(self): t = self.thickness angle = self.serrationangle self.parts.wavyKnob(self.diameter, self.serrations, angle, callback=lambda:self.dHole(0, 0, d=self.bolthole, rel_w=self.dhole), move="right") self.parts.wavyKnob(self.diameter, self.serrations, angle, callback=lambda: self.nutHole(self.hexhead), move="right") self.parts.wavyKnob(self.diameter, self.serrations, angle)
2,497
Python
.py
50
40.08
78
0.620492
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,549
sidedoorhousing.py
florianfesti_boxes/boxes/generators/sidedoorhousing.py
# Copyright (C) 2013-2020 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes.generators.console2 import Console2 class SideDoorHousing(Console2): """Box with service hatches on either one or both of the sides that are locked with latches""" ui_group = "Box" description = """ This box is designed as a housing for electronic projects but could be used for other purposes. It has hatches that can be re-opened with simple tools. If built from thin enough material, it intentionally cannot be opened with bare hands. The hatches are on the x sides. #### Assembly instructions The main body is easy to assemble: 1. Starting with the floor and then add the four walls (for any removable sides, the wall will just be a small part on the base ) 2. Add the top piece For the removable walls: 1. Add the lips to the removable walls 2. Sit the latches in place (it is importand to make sure the springs on the latches point inwards and the angled ends point to the side walls. See image below) 3. Glue the U-shaped clamps in place (it is important **not** to glue the latches) ![Wall details](static/samples/SideDoorHousing.jpg) #### Re-Opening The latches lock in place when closed. To open them they need to be pressed in and can then be moved aside. ![Closed Box](static/samples/SideDoorHousing-2.jpg) """ def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=.5) self.addSettingsArgs(edges.StackableSettings) self.buildArgParser(x=100, y=100, h=100, bottom_edge="s") self.argparser.add_argument( "--double_door", action="store", type=boolarg, default=True, help="allow removing the backwall, too") def render(self): x, y, h = self.x, self.y, self.h t = self.thickness bottom = self.edges.get(self.bottom_edge) self.latchpos = latchpos = 3*t self.rectangularWall(x, y, "ffff", move="right") # floor if self.double_door: # top self.rectangularWall(x, y, "EFEF", move="right") else: self.rectangularWall(x, y, "EFFF", move="right") for move in ("right", "mirror right"): re = edges.CompoundEdge(self, ("f", "e"), (bottom.endwidth()+t, h-t)) if self.double_door: le = edges.CompoundEdge(self, ("e", "f"), (h-t, bottom.endwidth()+t)) else: le = "f" self.rectangularWall( # side y, h, (bottom, re, "f", le), ignore_widths=[1, 6], callback=[ None, None, lambda: (self.rectangularHole(1.55*t, latchpos, 1.1*t, 1.1*t), self.double_door and self.rectangularHole(y-1.55*t, latchpos, 1.1*t, 1.1*t))], move=move) for i in range(2 if self.double_door else 1): self.rectangularWall(x, t, (bottom, "F", "e", "F"), ignore_widths=[1, 6], move="up") self.rectangularWall( # back wall x, h-1.1*t, "eEeE", callback=[ lambda: self.fingerHolesAt(.5*t, 0, h-4.05*t-latchpos), lambda:self.latch_hole(h-1.2*t-latchpos), lambda: self.fingerHolesAt(.5*t, 3.05*t+latchpos, h-4.05*t-latchpos), lambda:self.latch_hole(latchpos)], move="right") self.rectangularWall(x, t, (bottom, "F", "e", "F"), ignore_widths=[1, 6], move="down only") if not self.double_door: self.rectangularWall(x, h, (bottom, "F", "f", "F"), ignore_widths=[1, 6], move="right") # hardware for back wall if self.double_door: latches = 4 else: latches = 2 self.partsMatrix(latches, 0, "right", self.rectangularWall, 2*t, h-4.05*t-latchpos, "EeEf") self.partsMatrix(latches, 2, "up", self.latch) self.partsMatrix(2*latches, 2, "up", self.latch_clamp)
4,868
Python
.py
94
41.5
238
0.609016
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,550
compartmentbox.py
florianfesti_boxes/boxes/generators/compartmentbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes.generators.typetray import TypeTray class CompartmentBox(TypeTray): """Type tray variation with sliding lid""" description = """Sliding lid rests on inner walls, so will not work if no inner walls are present. Suggested to place walls close to both sides for maximum stability. Margin helps to prevent the lid from getting stuck. Vertical margin increases the overall height. The lip holding the lid in place can be generated as two separate pieces or as a single piece that continues at the back. ![Closed](static/samples/CompartmentBox-closed.jpg) ![Half open](static/samples/CompartmentBox-lid.jpg) """ ui_group = "Tray" def __init__(self) -> None: Boxes.__init__(self) # avoid TypeTray.__init__ self.addSettingsArgs(edges.StackableSettings) self.buildArgParser("sx", "sy", "h", "outside", "bottom_edge") self.argparser.add_argument( "--handle", action="store", type=str, default="lip", choices={"none","lip","hole"}, help="how to grab the lid to remove") self.argparser.add_argument( "--radius", action="store", type=float, default=10, dest="radius", help="radius of the grip hole in mm") self.argparser.add_argument( "--holes", action="store", type=str, default="70", help="width of hole(s) in percentage of maximum hole width") self.argparser.add_argument( "--margin_t", action="store", type=float, default=0.1, dest="margin_vertical", help="vertical margin for sliding lid (multiples of thickness)") self.argparser.add_argument( "--margin_s", action="store", type=float, default=0.05, dest="margin_side", help="margin to add at both sides of sliding lid (multiples of thickness)") self.argparser.add_argument( "--split_lip", action="store", type=boolarg, default=True, help="create two strips to reduce waste material") def render(self): t = self.thickness k = self.burn b = self.bottom_edge stackable = b == "s" tside, tback = ["Å ","S"] if stackable else ["F","E"] # top edges margin_side = self.margin_side margin_vertical = self.margin_vertical * t if (margin_vertical < 0): raise ValueError("vertical margin can not be negative") if (margin_side < 0): raise ValueError("side margin can not be negative") split_lip = self.split_lip if not split_lip: tback = tside if self.outside: self.sx = self.adjustSize(self.sx) self.sy = self.adjustSize(self.sy) self.h = self.adjustSize(self.h, b, tside) - 1 * t - margin_vertical self.hi = self.h x = sum(self.sx) + self.thickness * (len(self.sx) - 1) y = sum(self.sy) + self.thickness * (len(self.sy) - 1) h = self.h # x walls self.ctx.save() # outer walls - front/back hb = h + t + margin_vertical if stackable: hb += self.edges["S"].settings.holedistance + (t if split_lip else -t) self.rectangularWall(x, hb, [b, "F", tback, "F"], callback=[self.xHoles], ignore_widths=[1,2,5,6], move="up", label="back") self.rectangularWall(x, h, [b, "F", "e", "F"], callback=[self.mirrorX(self.xHoles, x)], ignore_widths=[1,6], move="up", label="front") # floor if b != "e": self.rectangularWall(x, y, "ffff", callback=[self.xSlots, self.ySlots], move="up", label="bottom") # Inner x walls be = "f" if b != "e" else "e" for i in range(len(self.sy) - 1): e = [edges.SlottedEdge(self, self.sx, be), "f", edges.SlottedEdge(self, self.sx[::-1], "e", slots=0.5 * h), "f"] self.rectangularWall(x, h, e, move="up", label=f"inner x {i+1}") # top / lid handle = self.handle x_compensated = x - 2*margin_side*t # margin at both sides (left, right) if handle == "lip": #compensate for the lid being a bit lower due to the margin, goal is to keep top at same height lip_height = (0 if stackable else t) + margin_vertical/2 if (stackable): #compensate for the stackable edge extra height lip_height += self.edges["S"].settings.holedistance #get this value from the settings # correct the stackable edge for the length lost at the ends s = copy.deepcopy(self.edges["S"].settings) # get value from settings and make change s.setValues(self.thickness, width = self.edges["S"].settings.width/self.thickness - margin_side) s.edgeObjects(self, chars="aA") # this seems to be correct self.rectangularWall(x_compensated, y, "feee", move="up", label="lid") self.rectangularWall(x_compensated, lip_height, "Fe" + ("A" if stackable else "e") + "e", move="up", label="lid lip") if handle == "hole": self.rectangularWall(x_compensated, y + t, move="up", label="lid", callback=[self.gripHole]) if handle == "none": self.rectangularWall(x_compensated, y + t, move="up", label="lid") self.ctx.restore() self.rectangularWall(x, h, "ffff", move="right only") # y walls # outer walls - left/right f = edges.CompoundEdge(self, "fE", [h+self.edges[b].startwidth(), t+margin_vertical]) self.rectangularWall(y, h+t+margin_vertical, [b, f, tside, "f"], callback=[self.yHoles, ], ignore_widths=[1,5,6], move="up", label="left side") self.rectangularWall(y, h+t+margin_vertical, [b, f, tside, "f"], callback=[self.yHoles, ], ignore_widths=[1,5,6], move="mirror up", label="right side") # inner y walls for i in range(len(self.sx) - 1): e = [edges.SlottedEdge(self, self.sy, be, slots=0.5 * h), "f", "e", "f"] self.rectangularWall(y, h, e, move="up", label=f"inner y {i+1}") # lip that holds the lid in place lip_front_edge = "e" if self.handle == "lip" else "E" if split_lip: self.rectangularWall(y, t, "eef" + lip_front_edge, move="up", label="Lip Left") self.rectangularWall(y, t, "eef" + lip_front_edge, move="mirror up", label="Lip Right") else: tx = y + self.edges.get('f').spacing() + self.edges.get(lip_front_edge).spacing() ty = x + 2 * self.edges.get('f').spacing() r=k # as sharp as possible without removing additional material from the part self.move(tx, ty, "up", before=True) self.moveTo(self.edges.get("f").margin(), self.edges.get("f").margin()) self.edges.get("f")(y) self.edgeCorner("f", lip_front_edge) self.edges.get(lip_front_edge)(t) self.edgeCorner(lip_front_edge, "e") self.edge(y-t-r) self.corner(-90, radius=r) self.edge(x-(t+r)*2) self.corner(-90, radius=r) self.edge(y-t-r) self.edgeCorner("e", lip_front_edge) self.edges.get(lip_front_edge)(t) self.edgeCorner(lip_front_edge, "f") self.edges.get('f')(y) self.corner(90) self.edges.get('f')(x) self.corner(90) self.move(tx, ty, "up", label="Lip") def gripHole(self): if not self.radius: return radius = self.radius t = self.thickness widths = argparseSections(self.holes) x = sum(self.sx) + self.thickness * (len(self.sx) - 1) if sum(widths) > 0: if sum(widths) < 100: slot_offset = ((1 - sum(widths) / 100) * (x - (len(widths) + 1) * self.thickness)) / (len(widths) * 2) else: slot_offset = 0 slot_height = 2* radius slot_x = self.thickness + slot_offset for w in widths: if sum(widths) > 100: slotwidth = w / sum(widths) * (x - (len(widths) + 1) * self.thickness) else: slotwidth = w / 100 * (x - (len(widths) + 1) * self.thickness) slot_x += slotwidth / 2 with self.saved_context(): self.rectangularHole(slot_x,radius+t,slotwidth,slot_height,radius,True,True) slot_x += slotwidth / 2 + slot_offset + self.thickness + slot_offset
9,575
Python
.py
186
40.075269
129
0.572146
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,551
frontpanel.py
florianfesti_boxes/boxes/generators/frontpanel.py
# Copyright (C) 2013-2017 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import io import shlex from boxes import * def str_to_bool(s: str) -> bool: return s.lower() in ('true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh') class FrontPanel(Boxes): """Mounting Holes and cutouts for all your holy needs.""" description = f""" <script type="module" src="https://md-block.verou.me/md-block.js"></script> <md-block> This will help you create font (and side and top) panels for your boxes that are pre-configured for all the bits and bobs you'd like to install The layout can create several types of holes including rectangles, circles and mounting holes. The default shows an example layout with all currently supported objects. #### `rect x y w h [cr=0] [cx=True] [cy=True]` x: x position y: y position w: width h: height cr: optional, Corner radius, default=0 cx: optional, Center x. the x position denotes the center of the rectangle. accepts t, T, 1, or other true-like values. cy: optional, Center y. the y position denotes the center of the rectangle. #### outline `rect w h` w: width h: height `outline` has a special meaning: You can create multiple panel outlines with one command. This has the effect of making it easy to manage all the holes on all the sides of your boxes. #### circle `circle x y r` x: x position y: y position r: radius #### mountinghole mountinghole x y d_shaft [d_head=0] [angle=0] x: x position y: y position d_shaft: diameter of the shaft part of the mounting hole d_head: optional. diameter of the head angle: optional. angle of the mounting hole #### text `text x y size "some text" [angle=0] [align=bottom|left]` x: x position y: y position size: size, in mm text: text to render. This *must* be in quotation marks angle: angle (in degrees) align: string with combinations of (top|middle|bottom) and (left|center|right), separated by '|'. Default is 'bottom|left' #### nema `nema x y size [screwhole_size=0]` x: x position (center of shaft) y: y position (center of shaft) size: nema size. One of [{', '.join([f'{x}' for x in Boxes.nema_sizes])}] screw: screw size, in mm. Optional. Default=0, which means the default size </md-block> """ ui_group = "Holes" def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--layout", action="store", type=str, default=""" outline 100 100 rect 50 60 80 30 3 True False text 50 91 7 "Super Front Panel With Buttons!" 0 bottom|center circle 10 45 3.5 circle 30 45 3.5 circle 50 45 3.5 circle 70 45 3.5 circle 90 45 3.5 text 10 40 3 "BTN_1" 0 top|center text 35 45 3 "BTN_2" 90 top|center text 50 50 3 "BTN_3" 180 top|center text 65 45 3 "BTN_4" 270 top|center text 90 45 3 "5" 0 middle|center mountinghole 5 85 3 6 90 mountinghole 95 85 3 6 90 # Start another panel, 30x50 outline 30 50 rect 15 25 15 15 1 True True text 15 25 3 "__Fun!" 0 bottom|left text 15 25 3 "__Fun!" 45 bottom|left text 15 25 3 "__Fun!" 90 bottom|left text 15 25 3 "__Fun!" 135 bottom|left text 15 25 3 "__Fun!" 180 bottom|left text 15 25 3 "__Fun!" 225 bottom|left text 15 25 3 "__Fun!" 270 bottom|left text 3 10 2 "Another panel, for fun" 0 top|left # Let's create another panel with a nema motor on it outline 40 40 nema 20 20 17 """) def applyOffset(self, x, y): return (x+self.offset[0], y+self.offset[1]) def drawRect(self, x, y, w, h, r=0, center_x="True", center_y="True") -> None: x, y, w, h, r = (float(i) for i in [x, y, w, h, r]) x, y = self.applyOffset(x, y) center_x = str_to_bool(center_x) center_y = str_to_bool(center_y) self.rectangularHole(x, y, w, h, r, center_x, center_y) def drawCircle(self, x, y, r) -> None: x, y, r = (float(i) for i in [x, y, r]) x, y = self.applyOffset(x, y) self.hole(x, y, r) def drawMountingHole(self, x, y, d_shaft, d_head=0.0, angle=0) -> None: x, y, d_shaft, d_head, angle = (float(i) for i in [x, y, d_shaft, d_head, angle]) x, y = self.applyOffset(x, y) self.mountingHole(x, y, d_shaft, d_head, angle) def drawOutline(self, w, h): w, h = (float(i) for i in [w, h]) if self.outline is not None: self.offset = self.applyOffset(self.outline[0]+10, 0) self.outline = (w, h) # store away for next time x = 0 y = 0 x, y = self.applyOffset(x, y) border = [(x, y), (x+w, y), (x+w, y+h), (x, y+h), (x, y)] self.showBorderPoly( border ) def drawText(self, x, y, size, text, angle=0, align='bottom|left'): x, y, size, angle = (float(i) for i in [x, y, size, angle]) x, y = self.applyOffset(x, y) align = align.replace("|", " ") self.text(text=text, x=x, y=y, fontsize=size, angle=angle, align=align) def drawNema(self, x, y, size, screwhole_size=0): x, y, size, screwhole_size = (float(i) for i in [x, y, size, screwhole_size]) if size in self.nema_sizes: x, y = self.applyOffset(x, y) self.NEMA(size, x, y, screwholes=screwhole_size) def parse_layout(self, layout): f = io.StringIO(layout) line = 0 objects = { 'outline': self.drawOutline, 'rect': self.drawRect, 'circle': self.drawCircle, 'mountinghole': self.drawMountingHole, 'text': self.drawText, 'nema': self.drawNema, } for l in f.readlines(): line += 1 l = re.sub('#.*$', '', l) # remove comments l = l.strip() la = shlex.split(l, comments=True, posix=True) if len(la) > 0 and la[0].lower() in objects: objects[la[0]](*la[1:]) def render(self): self.offset = (0.0, 0.0) self.outline = None # No outline yet self.parse_layout(self.layout)
6,731
Python
.py
170
34.041176
92
0.628988
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,552
rack19halfwidth.py
florianfesti_boxes/boxes/generators/rack19halfwidth.py
"""Half 19inch rack unit for musical equipment.""" from boxes import Boxes class Rack19HalfWidth(Boxes): """Half width 19inch rack unit for musical equipment.""" ui_group = "Box" def __init__(self) -> None: super().__init__() self.argparser.add_argument( '--ru_count', action='store', type=float, default=1, help='number of rack units') self.argparser.add_argument( '--holes', action='store', type=str, default="xxmpwx", help='mounting patterns: x=xlr, m=midi, p=9v-power, w=6.5mm-wire, space=next row') self.argparser.add_argument( '--z', action='store', type=float, default=20, help='depth of the shorter (rackear) side') self.argparser.add_argument( '--deepz', action="store", type=float, default=124, help='depth of the longer (screwed to another half sized thing) side') def render(self): """Render box.""" # pylint: disable=invalid-name t = self.thickness z = self.z self.x = x = 223 - (2 * t) self.y = y = (self.ru_count * 44.45) - 4.45 - (2 * t) deepz = self.deepz # front self.flangedWall(x, y, "FFFF", callback=[self.util_holes, self.rack_holes], r=t, flanges=[0, 17, 0, 0], move="up") # top&bottom self.trapezoidWall(x, deepz, z, "fFeF", move="up") self.trapezoidWall(x, deepz, z, "fFeF", move="up") # side self.rectangularWall(deepz, y, "fffe", move="right") self.rectangularWall(z, y, "fffe", move="up") def rack_holes(self): """Rackmount holes.""" t = self.thickness # pylint: disable=invalid-name self.rectangularHole(6 + t, 10, 10, 6.5, r=3.25) self.rectangularHole(self.y - 6 + t, 10, 10, 6.5, r=3.25) def util_holes(self): """Add holes.""" self.moveTo(10, (44.45 - 4.45)/2) for line in self.holes.split(): with self.saved_context(): for hole in line: self.hole_map.get(hole, lambda _: None)(self) self.moveTo(0, 44.45) def hole_xlr(self): """Hole for a xlr port.""" self.moveTo(16) self.hole(-9.5, 12, 1) self.hole(0, 0, 11.8) self.hole(9.5, -12, 1) self.moveTo(16) def hole_midi(self): """Hole for a midi port.""" self.moveTo(17) self.hole(-11.1, 0, 1) self.hole(0, 0, 7.5) self.hole(11.1, 0, 1) self.moveTo(17) def hole_power(self): """Hole for a 9v power port.""" self.moveTo(11) self.rectangularHole(0, 0, 9, 11) self.moveTo(11) def hole_wire(self): """Hole for a wire.""" self.moveTo(3) self.hole(0, 0, 3.25) self.moveTo(3) hole_map = { 'm': hole_midi, 'p': hole_power, 'w': hole_wire, 'x': hole_xlr, }
2,979
Python
.py
79
28.443038
94
0.539875
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,553
nemapattern.py
florianfesti_boxes/boxes/generators/nemapattern.py
# Copyright (C) 2013-2017 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class NemaPattern(Boxes): """Mounting holes for a Nema motor""" ui_group = "Holes" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--size", action="store", type=int, default=8, choices=list(sorted(self.nema_sizes.keys())), help="Nema size of the motor") self.argparser.add_argument( "--screwholes", action="store", type=float, default=0.0, help="Size of the screw holes in mm - 0 for default size") def render(self): motor, flange, holes, screws = self.nema_sizes.get( self.size, self.nema_sizes[8]) self.NEMA(self.size, motor/2, motor/2, screwholes=self.screwholes)
1,505
Python
.py
32
41.5625
74
0.68281
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,554
pizzashovel.py
florianfesti_boxes/boxes/generators/pizzashovel.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class PizzaShovel(Boxes): """Pizza shovel with conveyor belt action""" description = """ You need (permanent) baking paper to create the conveyor. With that you can pick up and put down the pizza by moving the handle attached to the belt. """ ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.HandleEdgeSettings, outset=0.0, height=40, hole_width="30:30:30") self.buildArgParser(x=382, y=400) self.argparser.add_argument( "--grip_length", action="store", type=float, default=250.0, help="Length of the grip. Zero for holes for a screw-in handle") self.argparser.add_argument( "--grip_height", action="store", type=float, default=30.0, help="Height of the grip. Distance between the cross beams.") self.argparser.add_argument( "--top_holes", action="store", type=float, default=3.0, help="Diameter of the screw holes in the bottom of the pusher - where the screws pass through") self.argparser.add_argument( "--bottom_holes", action="store", type=float, default=2.0, help="Diameter of the screw holes in the bottom of the pusher - where the screws hold") self.argparser.add_argument( "--grip_holes", action="store", type=float, default=3.0, help="Diameter of the screw holes for zero griplength") def holesCB(self, d): def cb(): for i in range(5): self.hole((self.x-3)/5 * (i+0.5), 20, d=d) return cb def gripCB(self, top): def cb(): t = self.thickness if self.grip_length: for d in (-t, +t): self.fingerHolesAt(self.x/2 + d, 0, 40, 90) else: for y in ((10, 30) if top else (15, 35, 60)): self.hole(self.x/2, y, d=self.grip_holes) return cb def render(self): x, y, h = self.x, self.y, self.grip_height grip = self.grip_length t = self.thickness ce = edges.CompoundEdge(self, "fe", [y/2, y/2]) ec = edges.CompoundEdge(self, "ef", [y/2, y/2]) self.rectangularWall(x, y, ["e", ce, "e", ec], move="up") self.rectangularWall(x, 40, "efef", callback=[self.gripCB(top=True)], move="up") self.rectangularWall(x, 80, "efef", callback=[self.gripCB(top=False)], move="up") for i in range(2): a = math.atan((h+2*t) / (y/2 - 30)) l = (y/2 - 30) / math.cos(a) a = math.degrees(a) self.polygonWall((y/2+40, (90, t), h+2*t, (90, t), 70, a, l, -a, 0, (180, t)), "e", callback=[lambda: (self.fingerHolesAt(0, 1.5*t, y/2, 0), self.fingerHolesAt(y/2+t, 1.5*t, 40, 0)), None, lambda: self.fingerHolesAt(-t, 1.5*t, 80, 0)], move="up") self.rectangularWall(x-3, 40, "eeee", callback=[self.holesCB(self.bottom_holes)], move="up") self.rectangularWall(x-3, 40, "yeee", callback=[self.holesCB(self.top_holes)], move="up") if grip: ce1 = edges.CompoundEdge(self, "fe", (40, grip-h/2)) ce2 = edges.CompoundEdge(self, "ef", (grip-h/2, 40)) self.flangedWall(40+grip-h/2, h, [ce1, "e", ce2, "e"], flanges=[0, h/2], r=h/2, move="up") self.flangedWall(40+grip-h/2, h, "eeee", flanges=[0, h/2], r=h/2, move="up") self.flangedWall(40+grip-h/2, h, [ce1, "e", ce2, "e"], flanges=[0, h/2], r=h/2, move="up") self.flangedWall(30+grip-h/2, h-2*t, "eeee", flanges=[0, h/2-t], r=h/2-t, move="up") self.flangedWall(30+grip-h/2, h-2*t, "eeee", flanges=[0, h/2-t], r=h/2-t, move="up")
4,673
Python
.py
85
44.341176
149
0.576864
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,555
nemamount.py
florianfesti_boxes/boxes/generators/nemamount.py
# Copyright (C) 2013-2017 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class NemaMount(Boxes): """Mounting bracket for a Nema motor""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--size", action="store", type=int, default=8, choices=list(sorted(self.nema_sizes.keys())), help="Nema size of the motor") def render(self): motor, flange, holes, screws = self.nema_sizes.get( self.size, self.nema_sizes[8]) t = self.thickness x = y = h = motor + 2*t self.rectangularWall(x, y, "ffef", callback=[ lambda: self.NEMA(self.size, x/2, y/2)], move="right") self.rectangularTriangle(x, h, "fFe", num=2, move="right") self.rectangularWall(x, h, "FFeF", callback=[ lambda:self.rectangularHole((x-holes)/2, y/2, screws, holes, screws/2), None, lambda:self.rectangularHole((x-holes)/2, y/2, screws, holes, screws/2)], move="right") self.moveTo(t, 0) self.fingerHolesAt(0.5*t, t, x, 90) self.fingerHolesAt(1.5*t+x, t, x, 90) self.fingerHolesAt(t, 0.5*t, x, 0)
2,025
Python
.py
44
37.409091
73
0.613902
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,556
openbox.py
florianfesti_boxes/boxes/generators/openbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class OpenBox(Boxes): """Box with top and front open""" ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.buildArgParser("x", "y", "h", "outside") self.argparser.add_argument( "--edgetype", action="store", type=ArgparseEdgeType("Fh"), choices=list("Fh"), default="F", help="edge type") self.addSettingsArgs(edges.FingerJointSettings) def render(self): x, y, h = self.x, self.y, self.h t = self.thickness if self.outside: x = self.adjustSize(x) y = self.adjustSize(y, False) h = self.adjustSize(h, False) e = self.edgetype self.rectangularWall(x, h, [e, e, "e", e], move="right") self.rectangularWall(y, h, [e, "e", "e", "f"], move="up") self.rectangularWall(y, h, [e, "e", "e", "f"]) self.rectangularWall(x, y, "efff", move="left")
1,673
Python
.py
39
36.666667
73
0.632841
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,557
phoneholder.py
florianfesti_boxes/boxes/generators/phoneholder.py
# Copyright (C) 2021 Guillaume Collic # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from functools import partial from boxes import Boxes, edges class PhoneHolder(Boxes): """ Smartphone desk holder """ ui_group = "Misc" description = """ This phone stand holds your phone between two tabs, with access to its bottom, in order to connect a charger, headphones, and also not to obstruct the mic. Default values are currently based on Galaxy S7. """ def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--phone_height", type=float, default=142, help="Height of the phone.", ) self.argparser.add_argument( "--phone_width", type=float, default=73, help="Width of the phone.", ) self.argparser.add_argument( "--phone_depth", type=float, default=11, help=( "Depth of the phone. Used by the bottom support holding the " "phone, and the side tabs depth as well. Should be at least " "your material thickness for assembly reasons." ), ) self.argparser.add_argument( "--angle", type=float, default=25, help="angle at which the phone stands, in degrees. 0° is vertical.", ) self.argparser.add_argument( "--bottom_margin", type=float, default=30, help="Height of the support below the phone", ) self.argparser.add_argument( "--tab_size", type=float, default=76, help="Length of the tabs holding the phone", ) self.argparser.add_argument( "--bottom_support_spacing", type=float, default=16, help=( "Spacing between the two bottom support. Choose a value big " "enough for the charging cable, without getting in the way of " "other ports." ), ) self.addSettingsArgs(edges.FingerJointSettings) def render(self): self.h = self.phone_height + self.bottom_margin tab_start = self.bottom_margin tab_length = self.tab_size tab_depth = self.phone_depth support_depth = self.phone_depth support_spacing = self.bottom_support_spacing rad = math.radians(self.angle) self.stand_depth = self.h * math.sin(rad) self.stand_height = self.h * math.cos(rad) self.render_front_plate(tab_start, tab_length, support_spacing, move="right") self.render_back_plate(move="right") self.render_side_plate(tab_start, tab_length, tab_depth, move="right") for move in ["right mirror", "right"]: self.render_bottom_support(tab_start, support_depth, tab_length, move=move) def render_front_plate( self, tab_start, tab_length, support_spacing, support_fingers_length=None, move="right", ): if not support_fingers_length: support_fingers_length = tab_length be = BottomEdge(self, tab_start, support_spacing) se1 = SideEdge(self, tab_start, tab_length) se2 = SideEdge(self, tab_start, tab_length, reverse=True) self.rectangularWall( self.phone_width, self.h, [be, se1, "e", se2], move=move, callback=[ partial( lambda: self.front_plate_holes( tab_start, support_fingers_length, support_spacing ) ) ], ) def render_back_plate( self, move="right", ): be = BottomEdge(self, 0, 0) self.rectangularWall( self.phone_width, self.stand_height, [be, "F", "e", "F"], move=move, ) def front_plate_holes( self, support_start_height, support_fingers_length, support_spacing ): margin = (self.phone_width - support_spacing - self.thickness) / 2 self.fingerHolesAt( margin, support_start_height, support_fingers_length, ) self.fingerHolesAt( self.phone_width - margin, support_start_height, support_fingers_length, ) def render_side_plate(self, tab_start, tab_length, tab_depth, move): te = TabbedEdge(self, tab_start, tab_length, tab_depth, reverse=True) self.rectangularTriangle( self.stand_depth, self.stand_height, ["e", "f", te], move=move, num=2, ) def render_bottom_support( self, support_start_height, support_depth, support_fingers_length, move="right" ): full_height = support_start_height + support_fingers_length rad = math.radians(self.angle) floor_length = full_height * math.sin(rad) angled_height = full_height * math.cos(rad) bottom_radius = min(support_start_height, 3 * self.thickness + support_depth) smaller_radius = 0.5 support_hook_height = 5 full_width = floor_length + (support_depth + 3 * self.thickness) * math.cos(rad) if self.move(full_width, angled_height, move, True): return self.polyline( floor_length, self.angle, 3 * self.thickness + support_depth - bottom_radius, (90, bottom_radius), support_hook_height + support_start_height - bottom_radius, (180, self.thickness), support_hook_height - smaller_radius, (-90, smaller_radius), self.thickness + support_depth - smaller_radius, -90, ) self.edges["f"](support_fingers_length) self.polyline( 0, 180 - self.angle, angled_height, 90, ) # Move for next piece self.move(full_width, angled_height, move) class BottomEdge(edges.BaseEdge): def __init__(self, boxes, support_start_height, support_spacing) -> None: super().__init__(boxes, None) self.support_start_height = support_start_height self.support_spacing = support_spacing def __call__(self, length, **kw): cable_hole_radius = 2.5 self.support_spacing = max(self.support_spacing, 2 * cable_hole_radius) side = (length - self.support_spacing - 2 * self.thickness) / 2 half = [ side, 90, self.support_start_height, -90, self.thickness, -90, self.support_start_height, 90, self.support_spacing / 2 - cable_hole_radius, 90, 2 * cable_hole_radius, ] path = half + [(-180, cable_hole_radius)] + list(reversed(half)) self.polyline(*path) class SideEdge(edges.BaseEdge): def __init__(self, boxes, tab_start, tab_length, reverse=False) -> None: super().__init__(boxes, None) self.tab_start = tab_start self.tab_length = tab_length self.reverse = reverse def __call__(self, length, **kw): tab_start = self.tab_start tab_end = length - self.tab_start - self.tab_length if self.reverse: tab_start, tab_end = tab_end, tab_start self.edges["F"](tab_start) self.polyline( 0, 90, self.thickness, -90, ) self.edges["f"](self.tab_length) self.polyline(0, -90, self.thickness, 90) self.edges["F"](tab_end) def startwidth(self) -> float: return self.boxes.thickness class TabbedEdge(edges.BaseEdge): def __init__(self, boxes, tab_start, tab_length, tab_depth, reverse=False) -> None: super().__init__(boxes, None) self.tab_start = tab_start self.tab_length = tab_length self.tab_depth = tab_depth self.reverse = reverse def __call__(self, length, **kw): tab_start = self.tab_start tab_end = length - self.tab_start - self.tab_length if self.reverse: tab_start, tab_end = tab_end, tab_start self.edges["f"](tab_start) self.ctx.save() self.fingerHolesAt(0, -self.thickness / 2, self.tab_length, 0) self.ctx.restore() self.polyline( 0, -90, self.thickness, (90, self.tab_depth), self.tab_length - 2 * self.tab_depth, (90, self.tab_depth), self.thickness, -90, ) self.edges["f"](tab_end) def margin(self) -> float: return self.tab_depth + self.thickness
9,607
Python
.py
266
26.255639
88
0.56957
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,558
angledbox.py
florianfesti_boxes/boxes/generators/angledbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class AngledBox(Boxes): """Box with both ends cornered""" ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser("x", "y", "h", "outside", "bottom_edge") self.argparser.add_argument( "--n", action="store", type=int, default=5, help="number of walls at one side (1+)") self.argparser.add_argument( "--top", action="store", type=str, default="none", choices=["none", "angled hole", "angled lid", "angled lid2"], help="style of the top and lid") def floor(self, x, y, n, edge='e', hole=None, move=None, callback=None, label=""): r, h, side = self.regularPolygon(2*n+2, h=y/2.0) t = self.thickness if n % 2: lx = x - 2 * h + side else: lx = x - 2 * r + side edge = self.edges.get(edge, edge) tx = x + 2 * edge.spacing() ty = y + 2 * edge.spacing() if self.move(tx, ty, move, before=True): return self.moveTo((tx-lx)/2., edge.margin()) if hole: with self.saved_context(): hr, hh, hside = self.regularPolygon(2*n+2, h=y/2.0-t) dx = side - hside hlx = lx - dx self.moveTo(dx/2.0, t+edge.spacing()) for i, l in enumerate(([hlx] + ([hside] * n))* 2): self.edge(l) self.corner(360.0/(2*n + 2)) for i, l in enumerate(([lx] + ([side] * n))* 2): self.cc(callback, i, 0, edge.startwidth() + self.burn) edge(l) self.edgeCorner(edge, edge, 360.0/(2*n + 2)) self.move(tx, ty, move, label=label) def render(self): x, y, h, n = self.x, self.y, self.h, self.n b = self.bottom_edge if n < 1: n = self.n = 1 if x < y: x, y = y, x if self.outside: x = self.adjustSize(x) y = self.adjustSize(y) if self.top == "none": h = self.adjustSize(h, False) elif "lid" in self.top and self.top != "angled lid": h = self.adjustSize(h) - self.thickness else: h = self.adjustSize(h) t = self.thickness r, hp, side = self.regularPolygon(2*n+2, h=y/2.0) if n % 2: lx = x - 2 * hp + side else: lx = x - 2 * r + side fingerJointSettings = copy.deepcopy(self.edges["f"].settings) fingerJointSettings.setValues(self.thickness, angle=360./(2 * (n+1))) fingerJointSettings.edgeObjects(self, chars="gGH") with self.saved_context(): if b != "e": self.floor(x, y , n, edge='f', move="right", label="Bottom") if self.top == "angled lid": self.floor(x, y, n, edge='e', move="right", label="Lower Lid") self.floor(x, y, n, edge='E', move="right", label="Upper Lid") elif self.top in ("angled hole", "angled lid2"): self.floor(x, y, n, edge='F', move="right", hole=True, label="Top Rim and Lid") if self.top == "angled lid2": self.floor(x, y, n, edge='E', move="right", label="Upper Lid") self.floor(x, y , n, edge='F', move="up only") fingers = self.top in ("angled lid2", "angled hole") cnt = 0 for j in range(2): cnt += 1 if j == 0 or n % 2: self.rectangularWall(lx, h, move="right", edges=b+"GfG" if fingers else b+"GeG", label=f"wall {cnt}") else: self.rectangularWall(lx, h, move="right", edges=b+"gfg" if fingers else b+"geg", label=f"wall {cnt}") for i in range(n): cnt += 1 if (i+j*((n+1)%2)) % 2: # reverse for second half if even n self.rectangularWall(side, h, move="right", edges=b+"GfG" if fingers else b+"GeG", label=f"wall {cnt}") else: self.rectangularWall(side, h, move="right", edges=b+"gfg" if fingers else b+"geg", label=f"wall {cnt}")
5,244
Python
.py
114
33.254386
95
0.507153
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,559
fanhole.py
florianfesti_boxes/boxes/generators/fanhole.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class FanHole(Boxes): """Hole pattern for mounting a fan""" ui_group = "Holes" def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--diameter", action="store", type=float, default=80, help="diameter of the fan hole") self.argparser.add_argument( "--mounting_holes", action="store", type=float, default=3, help="diameter of the fan mounting holes") self.argparser.add_argument( "--mounting_holes_inset", action="store", type=float, default=5, help="distance of the fan mounting holes from the outside") self.argparser.add_argument( "--arms", action="store", type=int, default=10, help="number of arms") self.argparser.add_argument( "--inner_disc", action="store", type=float, default=.2, help="relative size of the inner disc") self.argparser.add_argument( "--style", action="store", type=str, default="CW Swirl", choices=["CW Swirl", "CCW Swirl", "Hole"], help="Style of the fan hole") def arc(self, d, a): r = abs(1/math.cos(math.radians(90-a/2))*d/2) self.corner(-a/2) self.corner(a, r) self.corner(-a/2) def swirl(self, r, ri_rel=.1, n=20): d = 2*r #r = d/2 ri = ri_rel * r ai = 90 ao = 360/n * 0.8 # angle going in a1 = math.degrees(math.atan( ri*math.sin(math.radians(ai)) / (r - ri*math.cos(math.radians(ai))))) d1= (ri*math.sin(math.radians(ai))**2 + (r - ri*math.cos(math.radians(ai)))**2)**.5 d2= (ri*math.sin(math.radians(ai-ao))**2 + (r - ri*math.cos(math.radians(ai-ao)))**2)**.5 # angle coming out a_i2 = math.degrees(math.atan( (r*math.sin(math.radians(ao)) - ri*math.sin(math.radians(ai))) / (r*math.cos(math.radians(ao)) - ri*math.cos(math.radians(ai))))) a3 = a1 + a_i2 a2 = 90 + a_i2 - ao self.moveTo(0, -r, 180) for i in range(n): with self.saved_context(): self.corner(-ao, r) self.corner(-a2) self.arc(d2, -90) self.corner(-180+a3) self.arc(d1, 85) self.corner(-90-a1) self.moveArc(-360./n, r) def render(self): r_h = self.mounting_holes / 2 d = self.diameter inset = self.mounting_holes_inset for px in (inset, d-inset): for py in (inset, d-inset): self.hole(px, py, r_h) self.moveTo(d/2, d/2) if self.style == "CW Swirl": self.ctx.scale(-1, 1) self.swirl(d/2, self.inner_disc, self.arms) elif self.style == "CCW Swirl": self.swirl(d/2, self.inner_disc, self.arms) else: #Hole self.hole(0, 0, d=d)
3,709
Python
.py
89
32.359551
77
0.566907
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,560
filamentspool.py
florianfesti_boxes/boxes/generators/filamentspool.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes.generators.bayonetbox import BayonetBox class FilamentSpool(BayonetBox): """A two part spool for 3D printing filament""" description = """ Use small nails to properly align the pieces of the bayonet latch. Glue the parts of the bayonet latch before assembling the "axle". The inner parts go at the side and the outer parts at the inside of the axle. ![opened spool](static/samples/FilamentSpool-2.jpg)""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser(h=48) self.argparser.add_argument( "--outer_diameter", action="store", type=float, default=200.0, help="diameter of the flanges") self.argparser.add_argument( "--inner_diameter", action="store", type=float, default=100.0, help="diameter of the center part") self.argparser.add_argument( "--axle_diameter", action="store", type=float, default=50.0, help="diameter of the axle hole") self.argparser.add_argument( "--sides", action="store", type=int, default=8, help="number of pieces for the center part") self.argparser.add_argument( "--alignment_pins", action="store", type=float, default=1.0, help="diameter of the alignment pins") def leftsideCB(self): self.hole(0, 0, d=self.axle_diameter) r, h, side = self.regularPolygon(self.sides, radius=self.inner_diameter/2) for i in range(self.sides): self.fingerHolesAt(-side/2, h+0.5*self.thickness, side, 0) self.moveTo(0, 0, 360/self.sides) self.outerHolesCB() def outerHolesCB(self): t = self.thickness for i in range(6): for j in range(2): self.rectangularHole( 0, self.outer_diameter / 2 - 7.0, self.outer_diameter * math.pi / 360 * 8, 5, r=2.5) self.moveTo(0, 0, 10) self.moveTo(0, 0, 360 / 6 - 20) self.rectangularHole( (self.outer_diameter + self.inner_diameter) / 4, 0, (self.outer_diameter - self.inner_diameter) / 2 - 4*t, t, r=t/2) def render(self): t = self.thickness self.inner_diameter -= 2 * t r, h, side = self.regularPolygon(self.sides, radius=self.inner_diameter/2) self.diameter = 2*h self.lugs = self.sides self.parts.disc( self.outer_diameter, callback=self.leftsideCB, move="right") self.parts.disc( self.outer_diameter, hole=self.axle_diameter, callback=lambda:(self.alignmentHoles(True), self.outerHolesCB()), move="right") self.regularPolygonWall( self.sides, r=self.inner_diameter/2, edges="f", callback=[self.upperCB], move="right") self.parts.disc(self.diameter, callback=self.lowerCB, move="right") for i in range(self.sides): self.rectangularWall( side, self.h - t, "feFe", callback=[lambda:self.hole(side/2, self.h-2*t, r=t)], move="right")
3,960
Python
.py
82
39.134146
210
0.627395
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,561
trayinsert.py
florianfesti_boxes/boxes/generators/trayinsert.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class TrayInsert(Boxes): """Tray insert without floor and outer walls - allows only continuous walls""" ui_group = "Tray" def __init__(self) -> None: Boxes.__init__(self) self.buildArgParser("sx", "sy", "h", "outside") def render(self): if self.outside: self.sx = self.adjustSize(self.sx, False, False) self.sy = self.adjustSize(self.sy, False, False) x = sum(self.sx) + self.thickness * (len(self.sx) - 1) y = sum(self.sy) + self.thickness * (len(self.sy) - 1) h = self.h t = self.thickness # Inner walls for i in range(len(self.sx) - 1): e = [edges.SlottedEdge(self, self.sy, slots=0.5 * h), "e", "e", "e"] self.rectangularWall(y, h, e, move="up") for i in range(len(self.sy) - 1): e = ["e", "e", edges.SlottedEdge(self, self.sx[::-1], "e", slots=0.5 * h), "e"] self.rectangularWall(x, h, e, move="up")
1,700
Python
.py
36
41.25
91
0.635209
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,562
lbeam.py
florianfesti_boxes/boxes/generators/lbeam.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class LBeam(Boxes): """Simple L-Beam: two pieces joined with a right angle""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) self.buildArgParser("x", "y", "h", "outside") self.addSettingsArgs(edges.FingerJointSettings) def render(self): x, y, h = self.x, self.y, self.h t = self.thickness if self.outside: x = self.adjustSize(x, False) y = self.adjustSize(y, False) self.rectangularWall(x, h, "eFee", move="right") self.rectangularWall(y, h, "eeef")
1,300
Python
.py
30
38.533333
73
0.679365
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,563
wallrack.py
florianfesti_boxes/boxes/generators/wallrack.py
# Copyright (C) 2013-2023 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from functools import partial from boxes import * class WallRack(Boxes): """Wall mountable rack for spices or other items""" ui_group = "WallMounted" def __init__(self): Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=1.0) self.addSettingsArgs(edges.MountingSettings) self.addSettingsArgs(edges.HandleEdgeSettings) self.buildArgParser(x=200, y=50, sh="100*3", outside=False) self.argparser.add_argument( "--top_edge", action="store", type=ArgparseEdgeType("eEGy"), choices=list("eEGy"), default="G", help="edge type for top edge") self.argparser.add_argument("--full_height_top", type=boolarg, default=True, help="Add full height of topmost rack to the back panel") self.argparser.add_argument( "--wall_height", action="store", type=float, default=20.0, help="height of walls") self.argparser.add_argument( "--back_height", action="store", type=float, default=1.5, help="height of the back as fraction of the front height") self.argparser.add_argument( "--side_edges", action="store", type=ArgparseEdgeType("Fh"), choices=list("Fh"), default="h", help="edge type holding the shelves together") self.argparser.add_argument( "--flat_bottom", type=boolarg, default=False, help="Make bottom Flat, so that the rack can also stand") def generate_shelves(self, x, y, front_height, back_height): se = self.side_edges for i in range(len(self.sh)): self.rectangularWall(x, y, "ffff", move="up", label=f"shelf {i+1}") self.rectangularWall(x, front_height, se + "fef", move="up", label=f"front lip {i+1}") self.trapezoidWall(y, front_height, back_height, se + "fe" + se, move="right", label=f"right lip {i+1}") self.trapezoidWall(y, front_height, back_height, se + "fe" + se, move="up", label=f"left lip {i+1}") self.move(y + self.thickness*2, back_height, "left", before=True) #Generate finger holes for back part def generate_finger_holes(self, x, back_height): t = self.thickness pos_y = 0 for h in self.sh: self.fingerHolesAt(t*0.5, pos_y + 0.5*t, x, 0) self.fingerHolesAt(0, pos_y + t, back_height, 90) self.fingerHolesAt(x+t, pos_y + t, back_height, 90) pos_y += h def render(self): x, y, front_height = self.x, self.y, self.wall_height back_height = front_height * self.back_height t = self.thickness if self.outside: x = self.adjustSize(x, "h", "f") y = self.adjustSize(y) front_height = self.adjustSize(front_height) back_height = self.adjustSize(back_height) if self.full_height_top: total_height = sum(self.sh) else: total_height = sum(self.sh[:-1]) + back_height be = "e" if self.flat_bottom and self.side_edges == "F" else "E" if be == "E" and self.full_height_top: total_height -= t self.rectangularWall(x+self.thickness, total_height, be + "E" + self.top_edge + "E", callback=[partial(self.generate_finger_holes, x, back_height)], label="back wall", move="right") self.generate_shelves(x, y, front_height, back_height)
4,162
Python
.py
78
44.628205
142
0.63317
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,564
matrix.py
florianfesti_boxes/boxes/generators/matrix.py
# Copyright (C) 2024 fidoriel # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Matrix(Boxes): """WS2812b matrix enclosure""" description = """## Simple WS2812b matrix enclosure WS2812b matrix enclosure for cheap chinease prebuild led matrixes. This design assumes that the distance between the leds is equal in both directions. There are several parts to this design: - The inner frame to hold the pcb in place - The front frame to hold a sandwich of plexiglass, spacer and the pcb - The plexiglass to protect and diffuse the leds. You may add car tint foil to the plexiglass to achieve a black look - The spacer to keep the plexiglass from touching the leds - The back box with an optional mounting hole. Please add a hole for the power supply to the side panels and the power and data cables through the led mount frame with your favorite svg editor. - The side panels with finger joints to hold everything together Assembly: 1. Cut the parts 2. Assemble the frame (side panels and inner frame) 3. Insert the pcb, the spacers and the plexiglass 4. Close the front frame 5. Insert electronics in the back box (for example a USB C port on the side panel, a esp32 with wled firmware) 6. Close the back box The inner frame and spacer should keep everything in place without the need for glue. If you are using multiple modules, you can add the layout parameters, so that the inner frame adjusts accordingly. Please Note: if you are creating a large matrix build of multiple individual modules, you need to enter absolute values across all modules for all parameters. Please cut the plane labeled "Plexiglass" out of plexiglass :) You can use a different thickness for the plexiglass, but make sure to adjust the settings accordingly. """ ui_group = "Misc" led_width: int led_height: int pysical_led_y: int pysical_led_x: int distance_between_leds: float plexiglass_thicknes: float h: int matrix_back_frame_border: int = 20 matrix_front_frame_border_offset: int = 10 height_pcb: float bottom_edge: str = "F" mounting_holes: bool mounting_hole_diameter: float matrix_count_x: int matrix_count_y: int def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--led_width", action="store", type=int, default=16, help="Width of the LED matrix in pixels", ) self.argparser.add_argument( "--led_height", action="store", type=int, default=16, help="Height of the LED matrix in pixels", ) self.argparser.add_argument( "--pysical_led_y", action="store", type=int, default=160, help="Width of the LED matrix pcb in mm", ) self.argparser.add_argument( "--pysical_led_x", action="store", type=int, default=160, help="Height of the LED matrix pcb in mm", ) self.argparser.add_argument( "--matrix_back_frame_border", action="store", type=int, default=20, help="Border of the back frame bo keep the pcb in blace but allow for air flow and cable management", ) self.argparser.add_argument( "--matrix_front_frame_border_offset", action="store", type=int, default=10, help="Offset of the front frame to allow for the plexiglass to be attached", ) self.argparser.add_argument( "--distance_between_leds", action="store", type=float, default=1, help="Distance of the color dividers. Make sure your machine is able to cut thin structures.", ) self.argparser.add_argument( "--h", action="store", type=int, default=30, help="Height of the matrix", ) self.argparser.add_argument( "--height_pcb", action="store", type=float, default=0.2, help="Height of the pcb including the highest non led components in mm", ) self.argparser.add_argument( "--plexiglass_thicknes", action="store", type=float, default=3, help="Thickness of the plexiglass in mm", ) self.argparser.add_argument( "--mounting_holes", action="store", type=boolarg, default=False, help="Add mounting holes for the enclosure", ) self.argparser.add_argument( "--mounting_hole_diameter", action="store", type=float, default=5, help="Diameter of the mounting holes in mm", ) self.argparser.add_argument( "--matrix_count_x", action="store", type=int, default=1, help="Number of modules in x direction", ) self.argparser.add_argument( "--matrix_count_y", action="store", type=int, default=1, help="Number of modules in y direction", ) self.buildArgParser() def draw_frame(self, sizex: int, sizey: int, posx: int, posy: int): self.rectangularHole( x=posx, y=posy, dx=sizex, dy=sizey, r=0, center_x=False, center_y=False, ) def matrix_back_sideholes(self, length: int): sandwich_height = ( 2 * self.thickness + self.plexiglass_thicknes + self.height_pcb ) h = -0.5 * self.thickness + self.h - sandwich_height self.fingerHolesAt(0, h, length, angle=0) def draw_led_grid(self): space_per_led_x = self.pysical_led_x / self.led_width space_per_led_y = self.pysical_led_y / self.led_height for x in range(self.led_width): for y in range(self.led_height): self.rectangularHole( x=self.matrix_front_frame_border_offset + (x * space_per_led_x) + self.distance_between_leds / 2, y=self.matrix_front_frame_border_offset + (y * space_per_led_y) + self.distance_between_leds / 2, dx=space_per_led_x - self.distance_between_leds, dy=space_per_led_y - self.distance_between_leds, r=0, center_x=False, center_y=False, ) def create_mounting_holes(self): if self.mounting_holes: pos_x = (self.pysical_led_x + 2 * self.matrix_front_frame_border_offset) / 2 pos_y = ( (self.pysical_led_y + 2 * self.matrix_front_frame_border_offset) * 3 / 4 ) self.rectangularHole( x=pos_x, y=pos_y, dx=self.mounting_hole_diameter, dy=self.mounting_hole_diameter, r=self.mounting_hole_diameter, ) self.rectangularHole( x=pos_x, y=pos_y + self.mounting_hole_diameter / 2, dx=self.mounting_hole_diameter / 2, dy=self.mounting_hole_diameter / 2, r=self.mounting_hole_diameter, ) def render(self): x, y, h = ( self.pysical_led_x + 2 * self.matrix_front_frame_border_offset, self.pysical_led_y + 2 * self.matrix_front_frame_border_offset, self.h, ) d2 = edges.Bolts(2) d3 = edges.Bolts(3) d2 = d3 = None self.rectangularWall( x, h, "FFFF", bedBolts=[d2] * 4, move="up", label="Wall 1", callback=[ lambda: self.matrix_back_sideholes( self.pysical_led_x + 2 * self.matrix_front_frame_border_offset ) ], ) self.rectangularWall( y, h, "FfFf", bedBolts=[d3, d2, d3, d2], move="up", label="Wall 2", callback=[ lambda: self.matrix_back_sideholes( self.pysical_led_x + 2 * self.matrix_front_frame_border_offset ) ], ) self.rectangularWall( y, h, "FfFf", move="up", bedBolts=[d3, d2, d3, d2], label="Wall 4", callback=[ lambda: self.matrix_back_sideholes( self.pysical_led_y + 2 * self.matrix_front_frame_border_offset ) ], ) self.rectangularWall( x, h, "FFFF", bedBolts=[d2] * 4, move="up", label="Wall 3", callback=[ lambda: self.matrix_back_sideholes( self.pysical_led_y + 2 * self.matrix_front_frame_border_offset ) ], ) self.rectangularWall( x, y, "ffff", bedBolts=[d2, d3, d2, d3], move="right", label="Top", callback=[ lambda: self.draw_frame( sizex=self.pysical_led_x, sizey=self.pysical_led_y, posx=self.matrix_front_frame_border_offset, posy=self.matrix_front_frame_border_offset, ) ], ) self.rectangularWall( x, y, "ffff", bedBolts=[d2, d3, d2, d3], move="right", label="Bottom", callback=[self.create_mounting_holes], ) self.rectangularWall( x, y, "ffff", bedBolts=[d2, d3, d2, d3], move="right", label="matrix mount frame, please add cable holes as needed", ) self.rectangularWall( x, y, label="led_grid", move="right", callback=[lambda: self.draw_led_grid()], ) self.rectangularWall( x, y, label="led_grid", move="right", callback=[lambda: self.draw_led_grid()], ) self.rectangularWall(x, y, label="Plexiglass")
11,564
Python
.py
327
24.088685
113
0.539802
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,565
hingebox.py
florianfesti_boxes/boxes/generators/hingebox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class HingeBox(Boxes): """Box with lid attached by cabinet hinges""" description = """Needs (metal) pins as hinge axles. Pieces of nails will do fine. They need to be cut to length as they are captured as soon as the hinges are assembled. Assemble the box and the lid separately. Then insert the axle into the hinges. Then attach the hinges on the inside of the box and then connect them to lid. """ ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.CabinetHingeSettings) self.buildArgParser("x", "y", "h", "outside") self.argparser.add_argument( "--lidheight", action="store", type=float, default=20.0, help="height of lid in mm") self.argparser.add_argument( "--splitlid", action="store", type=float, default=0.0, help="split the lid in y direction (mm)") def render(self): x, y, h, hl = self.x, self.y, self.h, self.lidheight s = self.splitlid if self.outside: x = self.adjustSize(x) y = self.adjustSize(y) h = self.adjustSize(h) s = self.adjustSize(s, None) # reduce by half of the walls if s > x or s < 0.0: s = 0.0 t = self.thickness # bottom walls if s: self.rectangularWall(x, h, "FFuF", move="right") else: self.rectangularWall(x, h, "FFeF", move="right") self.rectangularWall(y, h, "Ffef", move="up") self.rectangularWall(y, h, "Ffef") self.rectangularWall(x, h, "FFuF", move="left up") # lid self.rectangularWall(x, hl, "UFFF", move="right") if s: self.rectangularWall(s, hl, "eeFf", move="right") self.rectangularWall(y-s, hl, "efFe", move="up") self.rectangularWall(y-s, hl, "eeFf") self.rectangularWall(s, hl, "efFe", move="left") self.rectangularWall(x, hl, "UFFF", move="left up") else: self.rectangularWall(y, hl, "efFf", move="up") self.rectangularWall(y, hl, "efFf") self.rectangularWall(x, hl, "eFFF", move="left up") self.rectangularWall(x, y, "ffff", move="right only") self.rectangularWall(x, y, "ffff") if s: self.rectangularWall(x, s, "ffef", move="left up") self.rectangularWall(x, y-s, "efff", move="up") else: self.rectangularWall(x, y, "ffff", move="left up") self.edges['u'].parts(move="up") if s: self.edges['u'].parts(move="up")
3,383
Python
.py
75
37.266667
78
0.620941
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,566
coinbanksafe.py
florianfesti_boxes/boxes/generators/coinbanksafe.py
# Copyright (C) 2024 Oliver Jensen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class CoinBankSafe(Boxes): """A piggy-bank designed to look like a safe.""" description =''' Make sure not to discard the circle cutouts from the lid, base, and door. They are all needed. ![Closed](static/samples/CoinBankSafe-closed.jpg) ![Open](static/samples/CoinBankSafe-open.jpg) Assemble the locking pins like this: wiggle-disc, number-disc, doorhole-disc, spacer-disc, D-disc. Glue the first three in place, but do not glue the last two. Leaving them unglued will allow you change the code, and to remove the pin from the door. ![Pins](static/samples/CoinBankSafe-pins.jpg) ''' ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser("x", "y", "h") self.argparser.add_argument( "--slotlength", action="store", type=float, default=30, help="Length of the coin slot in mm") self.argparser.add_argument( "--slotwidth", action="store", type=float, default=4, help="Width of the coin slot in mm") self.argparser.add_argument( "--handlelength", action="store", type=float, default=8, help="Length of handle in multiples of thickness") self.argparser.add_argument( "--handleclearance", action="store", type=float, default=1.5, help="Clearance of handle in multiples of thickness") def drawNumbers(self, radius, cover): fontsize = 0.8 * (radius - cover) for num in range(8): angle = num*45 x = (cover + fontsize *0.4) * math.sin(math.radians(angle)) y = (cover + fontsize *0.4) * math.cos(math.radians(angle)) self.text(str(num+1), align="center middle", fontsize=fontsize, angle=-angle, color=[1,0,0], y=y, x=x) def lockPin(self, layers, move=None): t = self.thickness cutout_width = t/3 barb_length = t base_length = layers * t base_width = t total_length = base_length + barb_length total_width = base_width + cutout_width * 0.5 cutout_angle = math.degrees(math.atan(cutout_width / base_length)) cutout_length = math.sqrt(cutout_width**2 + base_length**2) #self.rectangularWall(5*t, t) if self.move(total_length, total_width, move, True): return self.edge(total_length) self.corner(90) self.edge(base_width * 1/3) self.corner(90) self.edge(base_length) self.corner(180+cutout_angle, 0) self.edge(cutout_length) self.corner(90-cutout_angle) self.edge(cutout_width * 1.5) self.corner(90) self.edge(barb_length) self.corner(90) self.corner(-90, cutout_width * 0.5) self.edge(base_length - cutout_width * 0.5) self.corner(90) self.edge(t) self.corner(90) self.move(total_length, total_width, move) def render(self): x, y, h = self.x, self.y, self.h t = self.thickness slot_length = self.slotlength slot_width = self.slotwidth handle_length = self.handlelength * t handle_clearance = self.handleclearance * t # lock parameters big_radius = 2.25 * t small_radius = 1.4 * t doorhole_radius = 1.25 * t spacing = 1 # side walls with self.saved_context(): self.rectangularWall(x, h, "seFf", move="mirror right") self.rectangularWall(y, h, "sFFF", move="right") # wall with holes for the locking bar self.rectangularWall( x, h, "sfFe", ignore_widths=[3,4,7,8], callback=[lambda: self.fingerHolesAt(2.75*t, 0, h, 90)], move="mirror right") # locking bar self.moveTo(0, self.edges['s'].spacing() + t) self.rectangularWall(1.33*t, h, "eeef", move="right") # door door_clearance = .1 * t # amount to shave off of the door width so it can open before_hinge = 1.25 * t - door_clearance after_hinge = y - 2.25 * t - door_clearance self.moveTo(self.spacing/2, -t) self.polyline( after_hinge, -90, t, 90, t, 90, t, -90, before_hinge, 90, h, 90, before_hinge, -90, t, 90, t, 90, t, -90, after_hinge, 90, h, 90) num_dials = 3 space_under_dials = 6*big_radius space_not_under_dials = h - space_under_dials dial_spacing = space_not_under_dials / (num_dials + 1) if dial_spacing < 1 : min_height = 6*big_radius + 4 raise ValueError(f"With thickness {t}, h must be at least {min_height} to fit the dials.") for pos_y in (h/2, h/2 - (2*big_radius + dial_spacing), h/2 + (2*big_radius + dial_spacing)): self.hole(3*t - door_clearance, pos_y, doorhole_radius) self.rectangularHole(3*t - door_clearance, pos_y, t, t) self.rectangularHole(y/2 - door_clearance, h/2, t, handle_length / 2) self.rectangularWall(x, h, "seff", move="up only") # top self.rectangularWall( y, x, "efff", callback=[ lambda: self.rectangularHole(y/2, x/2, slot_length, slot_width), lambda: (self.hole(1.75*t, 1.75*t, 1.15*t), self.rectangularHole(1.75*t, 1.75*t, t, t))], label="top", move="right") # bottom self.rectangularWall( y, x, "efff", callback=[ lambda: (self.hole(1.75*t, 1.75*t, 1.15*t), self.rectangularHole(1.75*t, 1.75*t, t, t))], label="bottom", move="right") def holeCB(): self.rectangularHole(0, 0, t, t) self.moveTo(0, 0, 45) self.rectangularHole(0, 0, t, t) # locks with self.saved_context(): self.partsMatrix(3, 1, "right", self.parts.disc, 2*big_radius, callback=lambda: (self.drawNumbers(big_radius, small_radius), self.rectangularHole(0, 0, t, t))) self.partsMatrix(3, 1, "right", self.parts.disc, 2*big_radius, dwidth=0.8,callback=holeCB) self.partsMatrix( 3, 1, "right", self.parts.disc, 2*small_radius, callback=lambda:self.rectangularHole(0, 0, t, t)) self.partsMatrix( 3, 1, "right", self.parts.wavyKnob, 2*small_radius, callback=lambda:self.rectangularHole(0, 0, t, t)) self.partsMatrix(3, 1, "up only", self.parts.disc, 2*big_radius) # lock pins with self.saved_context(): self.lockPin(5, move="up") self.lockPin(5, move="up") self.lockPin(5, move="up") self.lockPin(5, move="right only") # handle self.moveTo(0) handle_curve_radius = 0.2 * t self.moveTo(t * 2.5) self.polyline( 0, (90, handle_curve_radius), handle_length - 2 * handle_curve_radius, (90, handle_curve_radius), handle_clearance - handle_curve_radius, 90, handle_length / 4, -90, t, 90, handle_length / 2, 90, t, -90, handle_length / 4, 90, handle_clearance - handle_curve_radius, )
8,373
Python
.py
189
33.460317
125
0.569202
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,567
walledges.py
florianfesti_boxes/boxes/generators/walledges.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes.walledges import _WallMountedBox class WallEdges(_WallMountedBox): """Shows the different edge types for wall systems""" def __init__(self) -> None: super().__init__() self.buildArgParser(h=120) def render(self): self.generateWallEdges() h = self.h self.moveTo(0, 25) self.rectangularWall( 40, h, "eAea", move="right", callback=[lambda : (self.text("a", 0, -20), self.text("A", 30, -20))]) self.rectangularWall( 40, h, "eBeb", move="right", callback=[lambda : (self.text("b", 0, -20), self.text("B", 30, -20))]) self.rectangularWall(40, h, "eCec", callback=[lambda : (self.text("c", 0, -20), self.text("C", 30, -20), self.text("wallHolesAt", -5, -30), self.wallHolesAt(20, 0, h, 90))], move="right") self.moveTo(10) self.rectangularWall( 40, h, "eDed", move="right", callback=[lambda : (self.text("d", 0, -20), self.text("D", 30, -20))])
1,920
Python
.py
42
35.785714
79
0.572956
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,568
stackablebin.py
florianfesti_boxes/boxes/generators/stackablebin.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class StackableBinEdge(edges.BaseEdge): char = "B" def __call__(self, length, **kw): f = self.settings.front a1 = math.degrees(math.atan(f/(1-f))) a2 = 45 + a1 self.corner(-a1) self.edges["e"](self.settings.h* (f**2+(1-f)**2)**0.5) self.corner(a2) self.edges["f"](self.settings.h*f*2**0.5) self.corner(-45) def margin(self) -> float: return self.settings.h * self.settings.front class StackableBinSideEdge(StackableBinEdge): char = 'b' class StackableBin(Boxes): """Stackable bin base on bintray""" ui_group = "Shelf" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.StackableSettings, bottom_stabilizers=2.4) self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=0.5) self.buildArgParser("outside") self.buildArgParser(x=70, h=50) self.argparser.add_argument( "--d", action="store", type=float, default=100, help="bin (d)epth") self.argparser.add_argument( "--front", action="store", type=float, default=0.4, help="fraction of bin height covered with slope") def render(self): self.front = min(self.front, 0.999) self.addPart(StackableBinEdge(self, self)) self.addPart(StackableBinSideEdge(self, self)) angledsettings = copy.deepcopy(self.edges["f"].settings) angledsettings.setValues(self.thickness, True, angle=45) angledsettings.edgeObjects(self, chars="gGH") if self.outside: self.x = self.adjustSize(self.x) self.h = self.adjustSize(self.h, "s", "S") self.d = self.adjustSize(self.d, "h", "b") with self.saved_context(): self.rectangularWall(self.x, self.d, "ffGf", label="bottom", move="up") self.rectangularWall(self.x, self.h, "hfef", label="back", move="up ") self.rectangularWall(self.x, self.h*self.front*2**0.5, "gFeF", label="retainer", move="up") self.rectangularWall(self.x, 3, "EEEE", label="for label (optional)") self.rectangularWall(self.x, 3, "EEEE", label="movement", move="right only") self.rectangularWall(self.d, self.h, "shSb", label="left", move="up") self.rectangularWall(self.d, self.h, "shSb", label="right", move="mirror up")
3,112
Python
.py
64
41.375
103
0.650925
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,569
jointpanel.py
florianfesti_boxes/boxes/generators/jointpanel.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class JointPanel(Boxes): """Create pieces larger than your laser cutter by joining them with Dove Tails""" description = """This can be used to just create a big panel in a smaller laser cutter. But the actual use is to split large parts into multiple smaller pieces. Copy the outline onto the sheet and then use the pieces to cut it into multiple parts that each can fit your laser cutter. Note that each piece must be cut with the sheet surrounding it to ensure the burn correction (aka kerf) is correct. Depending on your vector graphics software you may need to duplicate your part multiple times and then generate the intersection between one copy and each rectangular part. The Boxes.py drawings assume that the laser is cutting in the center of the line and the width of the line represents the material that is cut away. Make sure your changes work the same way and you do not cutting away the kerf. Small dove tails make it easier to fit parts in without problems. Lookout for pieces cut loose where the dove tails meet the edge of the parts. Move your part if necessary to avoid dove tails or details of your part colliding in a weird way. For plywood this method works well with a very stiff press fit. Aim for needing a hammer to join the pieces together. This way they will feel like they have been welder together. """ ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs( edges.DoveTailSettings, size=1, depth=.5, radius=.1) self.buildArgParser(sx="400/2", sy="400/3") self.argparser.add_argument( "--separate", action="store", type=boolarg, default=False, help="draw pieces apart so they can be cut to form a large sheet") def render(self): sx, sy = self.sx, self.sy t = self.thickness for ny, y in enumerate(sy): t0 = "e" if ny == 0 else "d" t2 = "e" if ny == len(sy) - 1 else "D" with self.saved_context(): for nx, x in enumerate(sx): t1 = "e" if nx == len(sx) - 1 else "d" t3 = "e" if nx == 0 else "D" self.rectangularWall(x, y, [t0, t1, t2, t3]) if self.separate: self.rectangularWall(x, y, [t0, t1, t2, t3], move="right only") else: self.moveTo(x) if self.separate: self.rectangularWall(x, y, [t0, t1, t2, t3], move="up only") else: self.moveTo(0, y - self.edges["d"].spacing() if ny == 0 else y)
3,432
Python
.py
52
56.115385
576
0.651322
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,570
slantedtray.py
florianfesti_boxes/boxes/generators/slantedtray.py
# Copyright (C) 2013-2023 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from functools import partial from boxes import * class SlantedTray(Boxes): """One row tray with high back wall and low front wall""" ui_group = "Tray" description = """Can be used as a display or for cards or gaming tokens. Lay on the side to get piles to draw from. ![Example Use](static/samples/SlantedTray-2.jpg)""" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) # self.addSettingsArgs(edges.StackableSettings) self.buildArgParser(sx="40*3", y=40.0, h=40.0, outside=False) self.argparser.add_argument( "--front_height", action="store", type=float, default=0.3, help="height of the front as fraction of the total height") def finger_holes_CB(self, sx, h): t = self.thickness pos = -0.5 * t for x in sx[:-1]: pos += x + t self.fingerHolesAt(pos, 0, h) def render(self): # adjust to the variables you want in the local scope sx, y, h = self.sx, self.y, self.h t = self.thickness if self.outside: self.sx = sx = self.adjustSize(sx) self.y = y = self.adjustSize(y) self.h = h = self.adjustSize(h, False) front_height = h * self.front_height x = sum(sx) + t * (len(sx) - 1) self.rectangularWall( x, h, "eFfF", move="up", callback=[partial(self.finger_holes_CB, sx, h)], ) self.rectangularWall( x, y, "FFfF", move="up", callback=[partial(self.finger_holes_CB, sx, y)], ) self.rectangularWall( x, front_height, "FFeF", move="up", callback=[ partial(self.finger_holes_CB, sx, front_height) ], ) for _ in range(len(sx) + 1): self.trapezoidWall(y, h, front_height, "ffef", move="right")
2,744
Python
.py
70
30.814286
119
0.597667
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,571
coffeecapsulesholder.py
florianfesti_boxes/boxes/generators/coffeecapsulesholder.py
# Copyright (C) 2021 Guillaume Collic # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from boxes import Boxes, boolarg class CoffeeCapsuleHolder(Boxes): """ Coffee capsule holder """ ui_group = "Misc" description = """ You can store your coffee capsule near your espresso machine with this. It works both vertically, or upside down under a shelf. """ def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--columns", type=int, default=4, help="Number of columns of capsules.", ) self.argparser.add_argument( "--rows", type=int, default=5, help="Number of capsules by columns.", ) self.argparser.add_argument( "--backplate", type=boolarg, default=True, help="True if a backplate should be generated.", ) def render(self): self.lid_size = 37 self.lid_size_with_margin = 39 self.body_size = 30 self.column_spacing = 5 self.corner_radius = 3 self.screw_margin = 6 self.outer_margin = 7 # Add space for the opening. A full row is not necessary for it. self.rows = self.rows + 0.6 self.render_plate(screw_hole=7, hole_renderer=self.render_front_hole) self.render_plate(hole_renderer=self.render_middle_hole) if self.backplate: self.render_plate() def render_plate(self, screw_hole=3.5, hole_renderer=None, move="right"): width = ( self.columns * (self.lid_size_with_margin + self.column_spacing) - self.column_spacing + 2 * self.outer_margin ) height = self.rows * self.lid_size + 2 * self.outer_margin if self.move(width, height, move, True): return with self.saved_context(): self.moveTo(self.corner_radius) self.polyline( width - 2 * self.corner_radius, (90, self.corner_radius), height - 2 * self.corner_radius, (90, self.corner_radius), width - 2 * self.corner_radius, (90, self.corner_radius), height - 2 * self.corner_radius, (90, self.corner_radius), ) if hole_renderer: for col in range(self.columns): with self.saved_context(): self.moveTo( self.outer_margin + col * (self.lid_size_with_margin + self.column_spacing) - self.burn, self.outer_margin + (self.rows - 0.5) * self.lid_size + self.burn, -90, ) hole_renderer() if screw_hole: for x in [self.screw_margin, width - self.screw_margin]: for y in [self.screw_margin, height - self.screw_margin]: self.hole(x, y + self.burn, d=screw_hole) self.move(width, height, move) def render_front_hole(self): radians = math.acos(self.body_size / self.lid_size_with_margin) height_difference = (self.lid_size / 2) * math.sin(radians) degrees = math.degrees(radians) half = [ 0, (degrees, self.lid_size_with_margin / 2), 0, -degrees, (self.rows - 1) * self.lid_size - height_difference, ] path = ( half + [(180, self.body_size / 2)] + list(reversed(half)) + [(180, self.lid_size_with_margin / 2)] ) self.polyline(*path) def render_middle_hole(self): half = [(self.rows - 1) * self.lid_size, (180, self.lid_size_with_margin / 2)] path = half * 2 self.polyline(*path)
4,505
Python
.py
115
29.052174
131
0.568488
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,572
heart.py
florianfesti_boxes/boxes/generators/heart.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class HeartBox(Boxes): """Box in the form of a heart""" ui_group = "FlexBox" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, finger=1.0,space=1.0) self.addSettingsArgs(edges.FlexSettings) self.buildArgParser(x=150, h=50) self.argparser.add_argument( "--top", action="store", type=str, default="closed", choices=["closed", "hole", "lid",], help="style of the top and lid") def CB(self): x = self.x t = self.thickness l = 2/3. * x - t r = l/2. - t d = 2 *t if self.top == "closed": return for i in range(2): self.moveTo(t, t) self.polyline((l, 2), (180, r), (d, 1), -90, (d, 1), (180, r), (l, 2), 90) l -= t r -= t d += t if self.top == "hole": return def render(self): x, h = self.x, self.h t = self.thickness l = 2/3. * x r = l/2. - 0.5*t borders = [l, (180, r), t, -90, t, (180, r), l, 90] self.polygonWalls(borders, h) self.rectangularWall(0, h, "FFFF", move="up only") self.polygonWall(borders, callback=[self.CB], move="right") self.polygonWall(borders, move="mirror right") if self.top == "lid": self.polygonWall([l+t, (180, r+t), 0, -90, 0, (180, r+t), l+t, 90], 'e')
2,223
Python
.py
56
31.857143
84
0.573352
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,573
smallpartstray2.py
florianfesti_boxes/boxes/generators/smallpartstray2.py
# Copyright (C) 2013-2023 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes.lids import LidSettings, _TopEdge class TopEdge(edges.BaseEdge): def __init__(self, boxes, lengths, h): super().__init__(boxes, None) self.lengths = lengths self.h = h def __call__(self, length, **kw): h = self.h t = self.boxes.thickness t2 = t * 2**.5 slot = h/2**.5 + t/2 self.polyline( 0, 90, t2, -45, slot-t, -90, t, -90, slot, 135, self.lengths[0] - t2/2) for l in self.lengths[1:]: self.polyline( 0, 45, t, 45, h/2-t2/2, -90, t, -90, h/2-t2, 135, slot-t, -90, t, -90, slot, 135, l - t2/2 ) self.polyline(t2/2) class SmallPartsTray2(_TopEdge): """A Type Tray variant with slopes toward the front""" description = """Assemble inside out. If there are inner front to back walls start with attaching the floor boards to them. Then add the vertical inner left to right walls. After sliding in the slopes attach the outer wall to fix everything in place. If there are no inner front to back walls just add everything to one side wall and then add the other one after that. Possibly saving the front and back as last step.""" ui_group = "Tray" def __init__(self) -> None: Boxes.__init__(self) self.addTopEdgeSettings(fingerjoint={"surroundingspaces": 1.0}, roundedtriangle={"outset" : 1}) self.addSettingsArgs(LidSettings) self.buildArgParser("sx", "sy", "hi", "outside", h=30) # "bottom_edge", "top_edge") self.argparser.add_argument( "--back_height", action="store", type=float, default=0.0, help="additional height of the back wall - e top edge only") self.argparser.add_argument( "--radius", action="store", type=float, default=0.0, help="radius for strengthening side walls with back_height") self.argparser.add_argument( "--handle", type=boolarg, default=False, help="add handle to the bottom (changes bottom edge in the front)", ) def fingerHolesCB(self, sections, height): def CB(): posx = -0.5 * self.thickness for x in sections[:-1]: posx += x + self.thickness self.fingerHolesAt(posx, 0, height) return CB def fingerHoleLineCB(self, posx, posy, sections): def CB(): self.moveTo(posx, posy, 90) for l in sections: self.fingerHolesAt(0, 0, l, 0) self.moveTo(l+self.thickness) return CB def xHoles(self): posx = -0.5 * self.thickness for x in self.sx[:-1]: posx += x + self.thickness self.fingerHolesAt(posx, 0, self.hi) def yHoles(self): t = self.thickness posy = -0.5 * self.thickness for y in self.sy[:-1]: posy += y + self.thickness self.fingerHolesAt(posy, 0, self.hi-t*2**.5) with self.saved_context(): self.moveTo(posy-0.5*t, self.hi, 135) self.fingerHolesAt(-0.5*t, 0, self.hi*2**.5+t/2) self.moveTo(posy+self.sy[-1]+0.5*t, self.hi, 135) self.fingerHolesAt(-0.5*t, 0, self.hi*2**.5+t/2) def render(self): # tmp settings self.top_edge = "e" self.bottom_edge = "F" if self.outside: self.sx = self.adjustSize(self.sx) self.sy = self.adjustSize(self.sy) self.h = self.adjustSize(self.h, e2=False) if self.hi: self.hi = self.adjustSize(self.hi, e2=False) x = sum(self.sx) + self.thickness * (len(self.sx) - 1) y = sum(self.sy) + self.thickness * (len(self.sy) - 1) h = self.h sameh = not self.hi hi = self.hi = self.hi or h t = self.thickness # outer walls b = self.bottom_edge tl, tb, tr, tf = self.topEdges(self.top_edge) self.closedtop = self.top_edge in "fFhŠ" bh = self.back_height if self.top_edge == "e" else 0.0 # x sides self.ctx.save() # outer walls - front/back if bh: self.rectangularWall(x, h+bh, [b, "f", tb, "f"], callback=[self.xHoles], #ignore_widths=[], move="up", label="back") self.rectangularWall(x, h, ["f" if self.handle else b, "f", "e", "f"], callback=[self.fingerHolesCB(self.sx[::-1], h),], move="up", label="front") else: self.rectangularWall(x, h, [b, "F", tb, "F"], callback=[self.xHoles], #ignore_widths=[1, 6], move="up", label="back") self.rectangularWall(x, hi-t*2**.5, ["f" if self.handle else b, "F", "e", "F"], callback=[self.fingerHolesCB(self.sx[::-1], hi-t*2**.5),], #ignore_widths=[] if self.handle else [1, 6], move="up", label="front") # floor boards t2 = t * 2**.5 dy = hi + t2/2 slot = t + t2/2 # 1.5*t floors = [self.sy[0]- hi - slot + t2, slot] self.rectangularWall( x, floors[0], "ffef", callback=[self.fingerHolesCB(self.sx, self.sy[0]-dy)], move="up", label="floor back side") for y_ in self.sy[1:]: self.rectangularWall( x, y_ - slot + t, "efef", callback=[self.fingerHolesCB(self.sx, y_ - slot + t), self.fingerHoleLineCB(hi-t2+t/2, 0, self.sx[::-1])], move="up", label="floor") floors.extend([y_ - slot + t, slot]) self.rectangularWall( x, hi-t2, "efYf" if self.handle else "efff", callback=[self.fingerHolesCB(self.sx, hi-t2)], move="up", label="floor front side") floors.append(hi-t2) # Inner walls be = "f" if b != "e" else "e" for i in range(len(self.sy) - 1): e = [edges.SlottedEdge(self, self.sx, be, slots=0.5 * hi), "f", edges.SlottedEdge(self, self.sx[::-1], "e"), "f"] self.rectangularWall(x, hi-t2, e, move="up", label=f"inner x {i+1}") # slopes for i in self.sy: self.rectangularWall( x, hi*2**.5 + t/2, [edges.SlottedEdge(self, self.sx, "e", slots=hi/2**.5), "f", edges.SlottedEdge(self, self.sx[::-1], "e"), "f"], move="up", label="slope") # top / lid self.drawLid(x, y, self.top_edge) # XXX deal with front self.lid(x, y, self.top_edge) self.ctx.restore() self.rectangularWall(x, hi, "ffff", move="right only") # y walls # outer walls - left/right for move in ("up", "up mirror"): if bh: self.trapezoidSideWall( y, h+bh, hi-t*2**.5, [edges.CompoundEdge(self, ("FE"*len(self.sy))+"F", floors), "h", "e", "h"], radius=self.radius, callback=[self.yHoles, ], move=move, label="side") else: self.rectangularWall( y, h, [edges.CompoundEdge(self, ("FE"*len(self.sy))+"F", floors), edges.CompoundEdge(self, "fE", (hi-t*2**.5, h-hi+t*2**.5)), tl, "f"], callback=[self.yHoles, ], #ignore_widths=[6] if self.handle else [1, 6], move=move, label="side") # inner walls for i in range(len(self.sx) - 1): e = [edges.CompoundEdge(self, ("fE"*len(self.sy))+"f", floors), edges.CompoundEdge(self, "fe", (hi-t*2**.5, t*2**.5)), TopEdge(self, self.sy[::-1], hi), "f"] self.rectangularWall(y, hi, e, move="up", label=f"inner y {i+1}")
8,922
Python
.py
193
33.829016
254
0.52227
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,574
skadis.py
florianfesti_boxes/boxes/generators/skadis.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class SkadisBoard(Boxes): """Customizable Ikea like pegboard""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--columns", action="store", type=int, default=17, help="Number of holes left to right counting both even and odd rows") self.argparser.add_argument( "--rows", action="store", type=int, default=27, help="Number of rows of holes top to bottom") def CB(self): for r in range(self.rows): for c in range(self.columns): if (r+c) % 2 == 0: continue self.rectangularHole((c+1)*20 - 8, (r+1)*20, 5, 15, r=2.5) def render(self): self.roundedPlate((self.columns+1) * 20, (self.rows+1)*20, edge="e", r=8, extend_corners=False, callback=[self.CB])
1,621
Python
.py
35
39.4
81
0.641091
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,575
trafficlight.py
florianfesti_boxes/boxes/generators/trafficlight.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class ShadyEdge(edges.BaseEdge): char = "s" def __call__(self, length, **kw): s = self.shades h = self.h a = math.atan(s/h) angle = math.degrees(a) for i in range(self.n): self.polyline(0, -angle, h / math.cos(a), angle+90) self.edges["f"](s) self.corner(-90) if i < self.n-1: self.edge(self.thickness) def margin(self) -> float: return self.shades class TrafficLight(Boxes): # change class name here and below """Traffic light""" description = """The traffic light was created to visualize the status of a Icinga monitored system. When turned by 90°, it can be also used to create a bottle holder. """ def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) # remove cli params you do not need self.buildArgParser("h", "hole_dD") # Add non default cli params if needed (see argparse std lib) self.argparser.add_argument( "--depth", action="store", type=float, default=100, help="inner depth not including the shades") self.argparser.add_argument( "--shades", action="store", type=float, default=50, help="depth of the shaders") self.argparser.add_argument( "--n", action="store", type=int, default=3, help="number of lights") self.argparser.add_argument( "--upright", action="store", type=boolarg, default=True, help="stack lights upright (or side by side)") def backCB(self): t = self.thickness for i in range(1, self.n): self.fingerHolesAt(i*(self.h+t)-0.5*t, 0, self.h) def sideCB(self): t = self.thickness for i in range(1, self.n): self.fingerHolesAt(i*(self.h+t)-0.5*t, 0, self.depth) for i in range(self.n): self.fingerHolesAt(i*(self.h+t), self.depth-2*t, self.h, 0) def topCB(self): t = self.thickness for i in range(1, self.n): self.fingerHolesAt(i*(self.h+t)-0.5*t, 0, self.depth + self.shades) for i in range(self.n): self.fingerHolesAt(i*(self.h+t), self.depth-2*t, self.h, 0) def frontCB(self): self.hole(self.h/2, self.h/2, self.h/2-self.thickness) def wall(self, h1, h2, w, edges="ffef", callback=None, move="", label=""): edges = [self.edges.get(e, e) for e in edges] edges += edges # append for wrapping around overallwidth = w + edges[-1].spacing() + edges[1].spacing() overallheight = max(h1, h2) + edges[0].spacing() + edges[2].spacing() if self.move(overallwidth, overallheight, move, before=True, label=label): return a = math.atan((h2-h1)/float(w)) angle = math.degrees(a) self.moveTo(edges[-1].spacing(), edges[0].margin()) for i, l in [(0, w), (1, h2)]: self.cc(callback, i, y=edges[i].startwidth() + self.burn) edges[i](l) self.edgeCorner(edges[i], edges[i + 1], 90) self.corner(angle) self.cc(callback, i, y=edges[2].startwidth() + self.burn) edges[2](w / math.cos(a)) self.corner(-angle) self.edgeCorner(edges[2], edges[2 + 1], 90) self.cc(callback, i, y=edges[3].startwidth() + self.burn) edges[3](h1) self.edgeCorner(edges[3], edges[3 + 1], 90) self.move(overallwidth, overallheight, move, label=label) def addMountH(self, width, height): ds = self.hole_dD[0] if len(self.hole_dD) < 2: # if no head diameter is given dh = 0 # only a round hole is generated y = height - max (self.thickness * 1.25, self.thickness * 1.0 + ds) # and we assume that a typical screw head diameter is twice the shaft diameter else: dh = self.hole_dD[1] # use given head diameter y = height - max (self.thickness * 1.25, self.thickness * 1.0 + dh / 2) # and offset the hole to have enough space for the head dx = width x1 = dx * 0.125 x2 = dx * 0.875 self.mountingHole(x1, y, ds, dh, 90) self.mountingHole(x2, y, ds, dh, 90) def addMountV(self, width, height): if self.hole_dD[0] < 2 * self.burn: return # no hole if no diameter is given ds = self.hole_dD[0] if len(self.hole_dD) < 2: # if no head diameter is given dh = 0 # only a round hole is generated x = max (self.thickness * 2.75, self.thickness * 2.25 + ds) # and we assume that a typical screw head diameter is twice the shaft diameter else: dh = self.hole_dD[1] # use given head diameter x = max (self.thickness * 2.75, self.thickness * 2.25 + dh / 2) # and offset the hole to have enough space for the head dy = height y1 = self.thickness * 0.75 + dy * 0.125 y2 = self.thickness * 0.75 + dy * 0.875 self.mountingHole(x, y1, ds, dh, 180) self.mountingHole(x, y2, ds, dh, 180) def render(self): # adjust to the variables you want in the local scope d, h, n = self.depth, self.h, self.n s = self.shades t = self.thickness th = n * (h + t) - t self.addPart(ShadyEdge(self, None)) # back if self.upright: self.rectangularWall(th, h, "FFFF", callback=[self.backCB, self.addMountV(th, h)], move="up", label="back") else: self.rectangularWall(th, h, "FFFF", callback=[self.backCB, self.addMountH(th, h)], move="up", label="back") if self.upright: # sides self.rectangularWall(th, d, "fFsF", callback=[self.sideCB], move="up", label="left") self.rectangularWall(th, d, "fFsF", callback=[self.sideCB], move="up", label="right") # horizontal Walls / blinds tops e = edges.CompoundEdge(self, "fF", (d, s)) e2 = edges.CompoundEdge(self, "Ff", (s, d)) for i in range(n): self.rectangularWall(h, d+s, ['f', e, 'e', e2], move="right" if i<n-1 else "right up", label="horizontal Wall " + str(i+1)) else: # bottom self.rectangularWall(th, d, "fFeF", callback=[self.sideCB], move="up", label="bottom") # top self.rectangularWall(th, d+s, "fFeF", callback=[self.topCB], move="up", label="top") # vertical walls for i in range(n): self.wall(d, d+s, h, move="right" if i<n-1 else "right up", label="vertical wall " + str(i+1)) # fronts for i in range(n): self.rectangularWall(h, h, "efef", callback=[self.frontCB], move="left" if i<n-1 else "left up", label="front " + str(i+1)) if self.upright: # bottom wall self.rectangularWall(h, d, "ffef", move="up", label="bottom wall") else: # vertical wall self.wall(d, d+s, h, move="up", label="vertical wall") # Colored windows for i in range(n): self.parts.disc(h-2*t, move="right", label="colored windows")
8,065
Python
.py
167
38.305389
158
0.579356
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,576
jigsaw.py
florianfesti_boxes/boxes/generators/jigsaw.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class JigsawPuzzle(Boxes): # change class name here and below """Fractal jigsaw puzzle. Still alpha.""" webinterface = False # Change to make visible in web interface def __init__(self) -> None: Boxes.__init__(self) self.count = 0 self.argparser.add_argument( "--size", action="store", type=float, default=100, help="size of the puzzle in mm") self.argparser.add_argument( "--depth", action="store", type=int, default=5, help="depth of the recursion/level of detail") def peano(self, level): if level == 0: self.edge(self.size / self.depth) return self.peano(self, level - 1) self.corner() def edge(self, l): self.count += 1 Boxes.edge(self, l) # if (self.count % 2**5) == 0: #level == 3 and parity>0: # self.corner(-360, 0.25*self.size/2**self.depth) def hilbert(self, level, parity=1): if level == 0: return # rotate and draw first subcurve with opposite parity to big curve self.corner(parity * 90) self.hilbert(level - 1, -parity) # interface to and draw second subcurve with same parity as big curve self.edge(self.size / 2 ** self.depth) self.corner(parity * -90) self.hilbert(level - 1, parity) # third subcurve self.edge(self.size / 2 ** self.depth) self.hilbert(level - 1, parity) # if level == 3: self.corner(-360, 0.4*self.size/2**self.depth) # fourth subcurve self.corner(parity * -90) self.edge(self.size / 2 ** self.depth) self.hilbert(level - 1, -parity) # a final turn is needed to make the turtle # end up facing outward from the large square self.corner(parity * 90) # if level == 3 and parity>0: # and random.random() < 100*0.5**(self.depth-2): # self.corner(-360, 0.4*self.size/2**self.depth) # with self.savedcontext(): # self.corner(parity*-90) # self.edge(self.size/2**self.depth) def render(self): size = self.size t = self.thickness self.burn = 0.0 self.moveTo(10, 10) self.hilbert(self.depth)
2,994
Python
.py
70
35.414286
86
0.622123
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,577
bintray.py
florianfesti_boxes/boxes/generators/bintray.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class BinFrontEdge(edges.BaseEdge): char = "B" def __call__(self, length, **kw): f = self.settings.front a1 = math.degrees(math.atan(f/(1-f))) a2 = 45 + a1 self.corner(-a1) for i, l in enumerate(self.settings.sy): self.edges["e"](l* (f**2+(1-f)**2)**0.5) self.corner(a2) self.edges["f"](l*f*2**0.5) if i < len(self.settings.sy)-1: if self.char == "B": self.polyline(0, 45, 0.5*self.settings.hi, -90, self.thickness, -90, 0.5*self.settings.hi, 90-a1) else: self.polyline(0, -45, self.thickness, -a1) else: self.corner(-45) def margin(self) -> float: return max(self.settings.sy) * self.settings.front class BinFrontSideEdge(BinFrontEdge): char = 'b' class BinTray(Boxes): """A Type tray variant to be used up right with sloped walls in front""" ui_group = "Shelf" def __init__(self) -> None: Boxes.__init__(self) self.buildArgParser("sx", "sy", "h", "outside", "hole_dD") self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=0.5) self.argparser.add_argument( "--front", action="store", type=float, default=0.4, help="fraction of bin height covered with slope") def xSlots(self): posx = -0.5 * self.thickness for x in self.sx[:-1]: posx += x + self.thickness posy = 0 for y in self.sy: self.fingerHolesAt(posx, posy, y) posy += y + self.thickness def ySlots(self): posy = -0.5 * self.thickness for y in self.sy[:-1]: posy += y + self.thickness posx = 0 for x in self.sx: self.fingerHolesAt(posy, posx, x) posx += x + self.thickness def addMount(self): ds = self.hole_dD[0] if len(self.hole_dD) < 2: # if no head diameter is given dh = 0 # only a round hole is generated y = max (self.thickness * 1.25, self.thickness * 1.0 + ds) # and we assume that a typical screw head diameter is twice the shaft diameter else: dh = self.hole_dD[1] # use given head diameter y = max (self.thickness * 1.25, self.thickness * 1.0 + dh / 2) # and offset the hole to have enough space for the head dx = sum(self.sx) + self.thickness * (len(self.sx) - 1) x1 = dx * 0.125 x2 = dx * 0.875 self.mountingHole(x1, y, ds, dh, -90) self.mountingHole(x2, y, ds, dh, -90) def xHoles(self): posx = -0.5 * self.thickness for x in self.sx[:-1]: posx += x + self.thickness self.fingerHolesAt(posx, 0, self.hi) def frontHoles(self, i): def CB(): posx = -0.5 * self.thickness for x in self.sx[:-1]: posx += x + self.thickness self.fingerHolesAt(posx, 0, self.sy[i]*self.front*2**0.5) return CB def yHoles(self): posy = -0.5 * self.thickness for y in reversed(self.sy[1:]): posy += y + self.thickness self.fingerHolesAt(posy, 0, self.hi) def render(self): if self.outside: self.sx = self.adjustSize(self.sx) self.sy = self.adjustSize(self.sy) self.h = self.adjustSize(self.h, e2=False) x = sum(self.sx) + self.thickness * (len(self.sx) - 1) y = sum(self.sy) + self.thickness * (len(self.sy) - 1) h = self.h hi = self.hi = h t = self.thickness self.front = min(self.front, 0.999) self.addPart(BinFrontEdge(self, self)) self.addPart(BinFrontSideEdge(self, self)) angledsettings = copy.deepcopy(self.edges["f"].settings) angledsettings.setValues(self.thickness, True, angle=45) angledsettings.edgeObjects(self, chars="gGH") # outer walls e = ["F", "f", edges.SlottedEdge(self, self.sx[::-1], "G"), "f"] self.rectangularWall(x, h, e, callback=[self.xHoles], move="right", label="bottom") self.rectangularWall(y, h, "FFbF", callback=[self.yHoles, ], move="up", label="left") self.rectangularWall(y, h, "FFbF", callback=[self.yHoles, ], label="right") self.rectangularWall(x, h, "Ffef", callback=[self.xHoles, ], move="left", label="top") self.rectangularWall(y, h, "FFBF", move="up only") # floor self.rectangularWall(x, y, "ffff", callback=[self.xSlots, self.ySlots, self.addMount], move="right", label="back") # Inner walls for i in range(len(self.sx) - 1): e = [edges.SlottedEdge(self, self.sy, "f"), "f", "B", "f"] self.rectangularWall(y, hi, e, move="up", label="inner vertical " + str(i+1)) for i in range(len(self.sy) - 1): e = [edges.SlottedEdge(self, self.sx, "f", slots=0.5 * hi), "f", edges.SlottedEdge(self, self.sx[::-1], "G"), "f"] self.rectangularWall(x, hi, e, move="up", label="inner horizontal " + str(i+1)) # Front walls for i in range(len(self.sy)): e = [edges.SlottedEdge(self, self.sx, "g"), "F", "e", "F"] self.rectangularWall(x, self.sy[i]*self.front*2**0.5, e, callback=[self.frontHoles(i)], move="up", label="retainer " + str(i+1))
6,180
Python
.py
131
37.519084
149
0.575556
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,578
eurorackskiff.py
florianfesti_boxes/boxes/generators/eurorackskiff.py
# Copyright (C) 2013-2017 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class EuroRackSkiff(Boxes): """3U Height case with adjustable width and height and included rails""" ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser("h") self.argparser.add_argument( "--hp", action="store", type=int, default=84, help="Width of the case in HP") def wallxCB(self, x): t = self.thickness def wallyCB(self, y): t = self.thickness self.fingerHolesAt(0, self.h-1.5*t, y, 0) def railHoles(self): for i in range(0, self.hp): self.hole(i*5.08 + 2.54, 3, d=3.0) def render(self): t = self.thickness h = self.h y = self.hp * 5.08 x = 128.5 self.rectangularWall(y, 6, "feee", callback=[self.railHoles] , move="up") self.rectangularWall(y, 6, "feee", callback=[self.railHoles] , move="up") self.rectangularWall(x, h, "fFeF", callback=[lambda: self.wallxCB(x)], move="right") self.rectangularWall(y, h, "ffef", callback=[lambda: self.wallyCB(y)], move="up") self.rectangularWall(y, h, "ffef", callback=[lambda: self.wallyCB(y)]) self.rectangularWall(x, h, "fFeF", callback=[lambda: self.wallxCB(x)], move="left up") self.rectangularWall(x, y, "FFFF", callback=[], move="right")
2,170
Python
.py
47
39.06383
89
0.638389
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,579
gearbox.py
florianfesti_boxes/boxes/generators/gearbox.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class GearBox(Boxes): """Gearbox with multiple identical stages""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--teeth1", action="store", type=int, default=8, help="number of teeth on ingoing shaft") self.argparser.add_argument( "--teeth2", action="store", type=int, default=20, help="number of teeth on outgoing shaft") self.argparser.add_argument( "--modulus", action="store", type=float, default=3, help="modulus of the teeth in mm") self.argparser.add_argument( "--shaft", action="store", type=float, default=6., help="diameter of the shaft") self.argparser.add_argument( "--stages", action="store", type=int, default=4, help="number of stages in the gear reduction") def render(self): if self.teeth2 < self.teeth1: self.teeth2, self.teeth1 = self.teeth1, self.teeth2 pitch1, size1, xxx = self.gears.sizes(teeth=self.teeth1, dimension=self.modulus) pitch2, size2, xxx = self.gears.sizes(teeth=self.teeth2, dimension=self.modulus) t = self.thickness x = 1.1 * t * self.stages if self.stages == 1: y = size1 + size2 y1 = y / 2 - (pitch1 + pitch2) + pitch1 y2 = y / 2 + (pitch1 + pitch2) - pitch2 else: y = 2 * size2 y1 = y / 2 - (pitch1 + pitch2) / 2 y2 = y / 2 + (pitch1 + pitch2) / 2 h = max(size1, size2) + t b = "F" t = "e" # prepare for close box mh = self.shaft def sideCB(): self.hole(y1, h / 2, mh / 2) self.hole(y2, h / 2, mh / 2) self.moveTo(self.thickness, self.thickness) self.rectangularWall(y, h, [b, "f", t, "f"], callback=[sideCB], move="right") self.rectangularWall(x, h, [b, "F", t, "F"], move="up") self.rectangularWall(x, h, [b, "F", t, "F"]) self.rectangularWall(y, h, [b, "f", t, "f"], callback=[sideCB], move="left") self.rectangularWall(x, h, [b, "F", t, "F"], move="up only") self.rectangularWall(x, y, "ffff", move="up") profile_shift = 20 pressure_angle = 20 for i in range(self.stages - 1): self.gears(teeth=self.teeth2, dimension=self.modulus, angle=pressure_angle, mount_hole=mh, profile_shift=profile_shift, move="up") self.gears(teeth=self.teeth2, dimension=self.modulus, angle=pressure_angle, mount_hole=mh, profile_shift=profile_shift, move="right") for i in range(self.stages): self.gears(teeth=self.teeth1, dimension=self.modulus, angle=pressure_angle, mount_hole=mh, profile_shift=profile_shift, move="down")
3,666
Python
.py
75
39.88
88
0.605543
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,580
can_storage.py
florianfesti_boxes/boxes/generators/can_storage.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class FrontEdge(edges.BaseEdge): char = "a" def __call__(self, length, **kw): x = math.ceil( ((self.canDiameter * 0.5 + 2 * self.thickness) * math.sin(math.radians(self.chuteAngle))) / self.thickness) if self.top_edge != "e": self.corner(90, self.thickness) self.edge(0.5 * self.canDiameter) self.corner(-90, 0.25 * self.canDiameter) else: self.moveTo(-self.burn, self.canDiameter + self.thickness, -90) self.corner(90, 0.25 * self.canDiameter) self.edge(self.thickness) self.edge(0.5 * self.canDiameter - self.thickness) self.corner(-90, 0.25 * self.canDiameter) self.edge(0.5 * self.canDiameter) self.corner(90, self.thickness) self.edge(x * self.thickness ) self.corner(90, self.thickness) self.edge(0.5 * self.canDiameter) self.corner(-90, 0.25 * self.canDiameter) self.edge(0.5 * self.canDiameter - (1 + x) * self.thickness + self.top_chute_height + self.bottom_chute_height - self.barrier_height) self.corner(-90, 0.25 * self.canDiameter) self.edge(0.5 * self.canDiameter) self.corner(90, self.thickness) self.edge(self.barrier_height) self.edge(self.thickness) class TopChuteEdge(edges.BaseEdge): char = "b" def __call__(self, length, **kw): self.edge(0.2 * length - self.thickness) self.corner(90, self.thickness) self.edge(1.5*self.canDiameter - 2 * self.thickness) self.corner(-90, self.thickness) self.edge(0.6 * length - 2 * self.thickness) self.corner(-90, self.thickness) self.edge(1.5*self.canDiameter - 2 * self.thickness) self.corner(90, self.thickness) self.edge(0.2 * length - self.thickness) class BarrierEdge(edges.BaseEdge): char = "A" def __call__(self, length, **kw): self.edge(0.2*length) self.corner(90,self.thickness/2) self.corner(-90,self.thickness/2) self.edge(0.6*length-2*self.thickness) self.corner(-90,self.thickness/2) self.corner(90,self.thickness/2) self.edge(0.2*length) def startwidth(self) -> float: return self.boxes.thickness class CanStorage(Boxes): """Storage box for round containers""" description = """ for AA batteries: ![CanStorage for AA batteries](static/samples/CanStorageAA.jpg) for canned tomatoes: """ ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, finger=2.0, space=2.0, surroundingspaces=0.0) self.addSettingsArgs(edges.StackableSettings) self.addSettingsArgs(fillHolesSettings) self.argparser.add_argument( "--top_edge", action="store", type=ArgparseEdgeType("efhŠ"), choices=list("efhŠ"), default="Š", help="edge type for top edge") self.argparser.add_argument( "--bottom_edge", action="store", type=ArgparseEdgeType("eEš"), choices=list("eEš"), default="š", help="edge type for bottom edge") # Add non default cli params if needed (see argparse std lib) self.argparser.add_argument( "--canDiameter", action="store", type=float, default=75, help="outer diameter of the cans to be stored (in mm)") self.argparser.add_argument( "--canHeight", action="store", type=float, default=110, help="height of the cans to be stored (in mm)") self.argparser.add_argument( "--canNum", action="store", type=int, default=12, help="number of cans to be stored") self.argparser.add_argument( "--chuteAngle", action="store", type=float, default=5.0, help="slope angle of the chutes") def DrawPusher(self, dbg = False): with self.saved_context(): if dbg == False: self.moveTo(0,self.thickness) self.edge(0.25*self.pusherA) self.corner(-90) self.edge(self.thickness) self.corner(90) self.edge(0.5*self.pusherA) self.corner(90) self.edge(self.thickness) self.corner(-90) self.edge(0.25*self.pusherA) self.corner(90-self.chuteAngle) self.edge(0.25*self.pusherB) self.corner(-90) self.edge(self.thickness) self.corner(90) self.edge(0.5*self.pusherB) self.corner(90) self.edge(self.thickness) self.corner(-90) self.edge(0.25*self.pusherB) self.corner(90+self.pusherAngle+self.chuteAngle) self.edge(self.pusherC) def cb_top_chute(self, nr): if nr == 0: # fill with holes border = [ (0, 0), (self.top_chute_depth, 0), (self.top_chute_depth, 0.2 * self.width - self.thickness), (self.top_chute_depth - self.thickness, 0.2 * self.width), (self.top_chute_depth - 1.5*self.canDiameter, 0.2 * self.width), (self.top_chute_depth - 1.5*self.canDiameter, 0.8 * self.width), (self.top_chute_depth - self.thickness, 0.8 * self.width), (self.top_chute_depth, 0.8 * self.width + self.thickness), (self.top_chute_depth, self.width), (0, self.width), ] if self.fillHoles_fill_pattern != "no fill": self.fillHoles( pattern="hbar", border=border, max_radius = min(2*self.thickness, self.fillHoles_hole_max_radius) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/30), hspace=min(2*self.thickness, self.fillHoles_space_between_holes) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/20), bspace=min(2*self.thickness, self.fillHoles_space_to_border) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/20), bar_length=self.fillHoles_bar_length, max_random=self.fillHoles_max_random, ) def cb_top(self, nr): if nr == 0: # fill with holes border = [ (0, 0), (self.depth, 0), (self.depth, self.width), (0, self.width), ] if self.fillHoles_fill_pattern != "no fill": self.fillHoles( pattern="hbar", border=border, max_radius = min(2*self.thickness, self.fillHoles_hole_max_radius) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/30), hspace=min(2*self.thickness, self.fillHoles_space_between_holes) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/20), bspace=min(2*self.thickness, self.fillHoles_space_to_border) if self.fillHoles_fill_pattern in ["hbar", "vbar"] else min(2*self.thickness, self.width/20), bar_length=self.fillHoles_bar_length, max_random=self.fillHoles_max_random, ) def cb_bottom_chute(self, nr): if nr == 1: # holes for pusher self.rectangularHole(self.width*0.85-0.5*self.thickness, 0.25*self.pusherA, self.thickness, 0.5*self.pusherA, center_x=False, center_y=False) self.rectangularHole(self.width*0.5 -0.5*self.thickness, 0.25*self.pusherA, self.thickness, 0.5*self.pusherA, center_x=False, center_y=False) self.rectangularHole(self.width*0.15-0.5*self.thickness, 0.25*self.pusherA, self.thickness, 0.5*self.pusherA, center_x=False, center_y=False) def cb_back(self, nr): if nr == 1: # holes for pusher self.rectangularHole(self.width*0.85-0.5*self.thickness, self.thickness + self.depth * math.tan(math.radians(self.chuteAngle)) + 0.25*self.pusherB, self.thickness, 0.5*self.pusherB + self.thickness, center_x=False, center_y=False) self.rectangularHole(self.width*0.5 -0.5*self.thickness, self.thickness + self.depth * math.tan(math.radians(self.chuteAngle)) + 0.25*self.pusherB, self.thickness, 0.5*self.pusherB + self.thickness, center_x=False, center_y=False) self.rectangularHole(self.width*0.15-0.5*self.thickness, self.thickness + self.depth * math.tan(math.radians(self.chuteAngle)) + 0.25*self.pusherB, self.thickness, 0.5*self.pusherB + self.thickness, center_x=False, center_y=False) def cb_sides(self, nr): if nr == 0: # for debugging only if self.debug: # draw orientation points self.hole(0, 0, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness + self.canDiameter, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness + self.canDiameter + self.bottom_chute_height, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + self.thickness, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + self.thickness + self.canDiameter, 1, color=Color.ANNOTATIONS) self.hole(0, self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + self.thickness + self.canDiameter + 1.0 * self.thickness, 1, color=Color.ANNOTATIONS) with self.saved_context(): # draw cans, bottom row self.moveTo(0, self.thickness, self.chuteAngle) self.rectangularHole(2*self.thickness, 0, math.ceil(self.canNum / 2) * self.canDiameter, self.canDiameter, center_x=False, center_y=False, color=Color.ANNOTATIONS) for i in range(math.ceil(self.canNum / 2)-1): self.hole(2*self.thickness+(0.5 + i) * self.canDiameter, self.canDiameter / 2, self.canDiameter / 2, color=Color.ANNOTATIONS) i+=1 self.hole(2*self.thickness+(0.5 + i) * self.canDiameter, self.canDiameter*0.8 , self.canDiameter / 2, color=Color.ANNOTATIONS) with self.saved_context(): # draw pusher self.moveTo(self.depth-self.pusherA, self.thickness + (self.depth-self.pusherA) * math.tan(math.radians(self.chuteAngle))) self.moveTo(0,0,self.chuteAngle) self.DrawPusher(True) with self.saved_context(): # draw cans, top row self.moveTo(0, self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + 0.5 * self.thickness, -self.chuteAngle) self.rectangularHole(0, 0.5 * self.thickness, math.ceil(self.canNum / 2) * self.canDiameter, self.canDiameter, center_x=False, center_y=False, color=Color.ANNOTATIONS) for i in range(math.ceil(self.canNum / 2)): self.hole((0.5 + i) * self.canDiameter, self.canDiameter / 2 + 0.5 * self.thickness, self.canDiameter / 2, color=Color.ANNOTATIONS) with self.saved_context(): # draw barrier self.moveTo(1.5 * self.thickness, 1.1 * self.thickness + self.burn + math.sin(math.radians(self.chuteAngle)) * 2 * self.thickness, 90) self.rectangularHole(0, 0, self.barrier_height, self.thickness, center_x=False, center_y=True, color=Color.ANNOTATIONS) # bottom chute with self.saved_context(): self.moveTo(0, 0.5 * self.thickness, self.chuteAngle) self.fingerHolesAt(0, 0, self.depth / math.cos(math.radians(self.chuteAngle)), 0) # top chute with self.saved_context(): self.moveTo(0, self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + 0.5 * self.thickness, -self.chuteAngle) self.fingerHolesAt(0, 0, self.top_chute_depth, 0) # front barrier with self.saved_context(): self.moveTo(1.5 * self.thickness, 1.1 * self.thickness + self.burn + math.sin(math.radians(self.chuteAngle)) * 2 * self.thickness, 90) self.fingerHolesAt(0, 0, self.barrier_height, 0) # fill with holes border = [ (2*self.thickness, 0.5*self.thickness + 2*self.thickness * math.tan(math.radians(self.chuteAngle)) + 0.5*self.thickness/math.cos(math.radians(self.chuteAngle))), (self.depth, self.thickness + self.depth * math.tan(math.radians(self.chuteAngle))), (self.depth, self.height), (self.thickness + 0.75 * self.canDiameter, self.height), (self.thickness + 0.75 * self.canDiameter, 0.5*self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + self.thickness - (self.thickness + 0.75 * self.canDiameter) * math.tan(math.radians(self.chuteAngle)) + 0.5*self.thickness/math.cos(math.radians(self.chuteAngle))), (self.top_chute_depth * math.cos(math.radians(self.chuteAngle)), self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + self.thickness - (self.top_chute_depth) * math.sin(math.radians(self.chuteAngle))), (self.top_chute_depth * math.cos(math.radians(self.chuteAngle)), self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height - (self.top_chute_depth) * math.sin(math.radians(self.chuteAngle))), (self.thickness + 0.75 * self.canDiameter, 1.5*self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height - (self.thickness + 0.75 * self.canDiameter) * math.tan(math.radians(self.chuteAngle)) - 0.5*self.thickness/math.cos(math.radians(self.chuteAngle))), (self.thickness + 0.75 * self.canDiameter, 2*self.thickness + self.barrier_height ), (2*self.thickness, 2*self.thickness + self.barrier_height), ] self.fillHoles( pattern=self.fillHoles_fill_pattern, border=border, max_radius=self.fillHoles_hole_max_radius, hspace=self.fillHoles_space_between_holes, bspace=self.fillHoles_space_to_border, min_radius=self.fillHoles_hole_min_radius, style=self.fillHoles_hole_style, bar_length=self.fillHoles_bar_length, max_random=self.fillHoles_max_random, ) def render(self): self.chuteAngle = self.chuteAngle self.pusherAngle = 30 # angle of pusher self.pusherA = 0.75 * self.canDiameter # length of pusher self.pusherB = self.pusherA / math.sin(math.radians(180 - (90+self.chuteAngle) - self.pusherAngle)) * math.sin(math.radians(self.pusherAngle)) self.pusherC = self.pusherA / math.sin(math.radians(180 - (90+self.chuteAngle) - self.pusherAngle)) * math.sin(math.radians(90+self.chuteAngle)) self.addPart(FrontEdge(self, self)) self.addPart(TopChuteEdge(self, self)) self.addPart(BarrierEdge(self, self)) if self.canDiameter < 8 * self.thickness: self.edges["f"].settings.setValues(self.thickness, True, finger=1.0) self.edges["f"].settings.setValues(self.thickness, True, space=1.0) self.edges["f"].settings.setValues(self.thickness, True, surroundingspaces=0.0) if self.canDiameter < 4 * self.thickness: raise ValueError("Can diameter has to be at least 4 times the material thickness!") if self.canNum < 4: raise ValueError("4 cans is the minimum!") self.depth = self.canDiameter * (math.ceil(self.canNum / 2) + 0.1) + self.thickness self.top_chute_height = max(self.depth * math.sin(math.radians(self.chuteAngle)), 0.1 * self.canDiameter) self.top_chute_depth = (self.depth - 1.1 * self.canDiameter) / math.cos(math.radians(self.chuteAngle)) self.bottom_chute_height = max((self.depth - 1.1 * self.canDiameter) * math.sin(math.radians(self.chuteAngle)), 0.1 * self.canDiameter) self.bottom_chute_depth = self.depth / math.cos(math.radians(self.chuteAngle)) self.barrier_height = min( 0.25 * self.canDiameter, self.bottom_chute_height + self.top_chute_height - self.thickness) if (self.top_chute_depth + self.bottom_chute_height - self.thickness) < (self.barrier_height + self.canDiameter * 0.1): self.bottom_chute_height = self.barrier_height + self.canDiameter * 0.1 + self.thickness - self.top_chute_depth self.height = self.thickness + self.canDiameter + self.bottom_chute_height + self.top_chute_height + 0.5 * self.thickness + self.canDiameter + 1.5 * self.thickness # measurements from bottom to top self.width = 0.01 * self.canHeight + self.canHeight + 0.01 * self.canHeight edgs = self.bottom_edge + "h" + self.top_edge + "a" # render your parts here self.rectangularWall(self.depth, self.height, edges=edgs, callback=self.cb_sides, move="up", label="right") self.rectangularWall(self.depth, self.height, edges=edgs, callback=self.cb_sides, move="up mirror", label="left") self.rectangularWall(self.bottom_chute_depth, self.width, "fefe", callback=self.cb_bottom_chute, move="up", label="bottom chute") self.rectangularWall(self.top_chute_depth, self.width, "fbfe", callback=self.cb_top_chute, move="up", label="top chute") self.rectangularWall(self.barrier_height, self.width, "fAfe", move="right", label="barrier") self.rectangularWall(self.height, self.width, "fefe", callback=self.cb_back, move="up", label="back") self.rectangularWall(self.barrier_height, self.width, "fefe", move="left only", label="invisible") if self.top_edge != "e": self.rectangularWall(self.depth, self.width, "fefe", callback=self.cb_top, move="up", label="top") pusherH = self.pusherB * math.cos(math.radians(self.chuteAngle)) + self.thickness pusherV = self.pusherC * math.cos(math.radians(self.chuteAngle)) + self.thickness self.move(pusherV, pusherH, where ="right", before=True, label="Pusher") self.DrawPusher() self.move(pusherV, pusherH, where ="right", before=False, label="Pusher") self.move(pusherV, pusherH, where ="right", before=True, label="Pusher") self.DrawPusher() self.move(pusherV, pusherH, where ="right", before=False, label="Pusher") self.move(pusherV, pusherH, where ="up", before=True, label="Pusher") self.DrawPusher() self.text("Glue the Pusher pieces into slots on bottom\nand back plates to prevent stuck cans.", pusherV+3,0, fontsize=4, color=Color.ANNOTATIONS) self.move(pusherV, pusherH, where ="up", before=False, label="Pusher") self.move(pusherV, pusherH, where ="left only", before=True, label="Pusher") self.move(pusherV, pusherH, where ="left only", before=True, label="Pusher") if self.bottom_edge == "š": self.rectangularWall(self.edges["š"].settings.width+3*self.thickness, self.edges["š"].settings.height-4*self.burn, "eeee", move="right", label="Stabilizer 1") self.rectangularWall(self.edges["š"].settings.width+3*self.thickness, self.edges["š"].settings.height-4*self.burn, "eeee", move="right", label="Stabilizer 2") self.rectangularWall(self.edges["š"].settings.width+5*self.thickness, self.edges["š"].settings.height-4*self.burn, "eeee", move="right", label="Stabilizer 3") self.rectangularWall(self.edges["š"].settings.width+5*self.thickness, self.edges["š"].settings.height-4*self.burn, "eeee", move="right", label="Stabilizer 4") self.text("Glue a stabilizer on the inside of each bottom\nside stacking foot for lateral stabilization.",3 ,0 , fontsize=4, color=Color.ANNOTATIONS)
21,148
Python
.py
311
55.70418
331
0.629815
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,581
keyboard.py
florianfesti_boxes/boxes/generators/keyboard.py
# Copyright (C) 2021 Guillaume Collic # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import argparse import re from boxes import boolarg class Keyboard: """ Code to manage Cherry MX compatible switches and Kailh hotswap socket. Reference : * https://www.cherrymx.de/en/dev.html * https://cdn.sparkfun.com/datasheets/Components/Switches/MX%20Series.pdf * https://www.kailhswitch.com/uploads/201815927/PG151101S11.pdf """ STANDARD_KEY_SPACING = 19.05 SWITCH_CASE_SIZE = 15.6 FRAME_CUTOUT = 14 def __init__(self) -> None: pass def add_common_keyboard_parameters( self, add_hotswap_parameter=True, add_pcb_mount_parameter=True, add_led_parameter=True, add_diode_parameter=True, add_cutout_type_parameter=True, default_columns_definition=None, ): if add_hotswap_parameter: self.argparser.add_argument( "--hotswap_enable", action="store", type=boolarg, default=True, help=("enlarge switches holes for hotswap pcb sockets"), ) if add_pcb_mount_parameter: self.argparser.add_argument( "--pcb_mount_enable", action="store", type=boolarg, default=True, help=("adds holes for pcb mount switches"), ) if add_led_parameter: self.argparser.add_argument( "--led_enable", action="store", type=boolarg, default=False, help=("adds pin holes under switches for leds"), ) if add_diode_parameter: self.argparser.add_argument( "--diode_enable", action="store", type=boolarg, default=False, help=("adds pin holes under switches for diodes"), ) if add_cutout_type_parameter: self.argparser.add_argument( "--cutout_type", action="store", type=str, default="castle", help=( "Shape of the plate cutout: 'castle' allows for modding, and 'simple' is a tighter and simpler square" ), ) if default_columns_definition: self.argparser.add_argument( "--columns_definition", type=self.argparseColumnsDefinition, default=default_columns_definition, help=( "Each column is separated by '/', and is in the form 'nb_rows @ offset x repeat_count'. " "Nb_rows is the number of rows for this column. " "The offset is in mm and optional. " "Repeat_count is optional and repeats this column multiple times. " "Spaces are not important." "For example '3x2 / 4@11' means we want 3 columns, the two first with " "3 rows without offset, and the last with 4 rows starting at 11mm high." ), ) def argparseColumnsDefinition(self, s): """ Parse columns definition parameter :param s: string to parse Each column is separated by '/', and is in the form 'nb_rows @ offset x repeat_count'. Nb_rows is the number of rows for this column. The offset is in mm and optional. Repeat_count is optional and repeats this column multiple times. Spaces are not important. For example '3x2 / 4@11' means we want 3 columns, the two first with 3 rows without offset, and the last with 4 rows starting at 11mm high """ result = [] try: for column_string in s.split("/"): m = re.match(r"^\s*(\d+)\s*@?\s*(\d*\.?\d*)(?:\s*x\s*(\d+))?\s*$", column_string) keys_count = int(m.group(1)) offset = float(m.group(2)) if m.group(2) else 0 n = int(m.group(3)) if m.group(3) else 1 result.extend([(offset, keys_count)]*n) except: raise argparse.ArgumentTypeError("Don't understand columns definition string") return result def pcb_holes( self, with_hotswap=True, with_pcb_mount=True, with_led=False, with_diode=False ): grid_unit = 1.27 main_hole_size = 4 pcb_mount_size = 1.7 led_hole_size = 1 if with_hotswap: pin_hole_size = 2.9 else: pin_hole_size = 1.5 def grid_hole(x, y, d): self.hole(grid_unit * x, grid_unit * y, d=d) # main hole grid_hole(0, 0, main_hole_size) # switch pins grid_hole(-3, 2, pin_hole_size) grid_hole(2, 4, pin_hole_size) if with_pcb_mount: grid_hole(-4, 0, pcb_mount_size) grid_hole(4, 0, pcb_mount_size) if with_led: grid_hole(-1, -4, led_hole_size) grid_hole(1, -4, led_hole_size) if with_diode: grid_hole(-3, -4, led_hole_size) grid_hole(3, -4, led_hole_size) def apply_callback_on_columns(self, cb, columns_definition, spacing=None, reverse=False): if spacing is None: spacing = self.STANDARD_KEY_SPACING if reverse: columns_definition = list(reversed(columns_definition)) for offset, nb_keys in columns_definition: self.moveTo(0, offset) for _ in range(nb_keys): cb() self.moveTo(0, spacing) self.moveTo(spacing, -nb_keys * spacing) self.moveTo(0, -offset) total_width = len(columns_definition) * spacing self.moveTo(-1 * total_width) def outer_hole(self, radius=2, centered=True): """ Draws a rounded square big enough to go around a whole switch (15.6mm) """ half_size = Keyboard.SWITCH_CASE_SIZE / 2 if centered: self.moveTo(-half_size, -half_size) # draw clock wise to work with burn correction straight_edge = Keyboard.SWITCH_CASE_SIZE - 2 * radius polyline = [straight_edge, (-90, radius)] * 4 self.moveTo(self.burn, radius, 90) self.polyline(*polyline) self.moveTo(0, 0, 270) self.moveTo(0, -radius) self.moveTo(-self.burn) if centered: self.moveTo(half_size, half_size) def castle_shaped_plate_cutout(self, centered=True): """ This cutout shaped like a castle enables switch modding and rotation. More information (type 4) on https://geekhack.org/index.php?topic=59837.0 """ half_size = Keyboard.SWITCH_CASE_SIZE / 2 if centered: self.moveTo(-half_size, -half_size) # draw clock wise to work with burn correction btn_half_side = [0.98, 90, 0.81, -90, 3.5, -90, 0.81, 90, 2.505] btn_full_side = [*btn_half_side, 0, *btn_half_side[::-1]] btn = [*btn_full_side, -90] * 4 self.moveTo(self.burn+0.81, 0.81, 90) self.polyline(*btn) self.moveTo(0, 0, 270) self.moveTo(-self.burn-0.81, -0.81) if centered: self.moveTo(half_size, half_size) def configured_plate_cutout(self, support=False): """ Choose which cutout to use based on configured type. support: if true, not the main cutout, but one to glue against the first 1.5mm cutout to strengthen it, without the clipping part. """ if self.cutout_type.lower() == "castle": if support: self.outer_hole() else: self.castle_shaped_plate_cutout() else: self.simple_plate_cutout(with_notch=support) def simple_plate_cutout(self, radius=0.2, with_notch=False): """ A simple plate cutout, a 14mm rectangle, as specified in this reference sheet https://cdn.sparkfun.com/datasheets/Components/Switches/MX%20Series.pdf With_notch should be used for a secondary lower plate, strengthening the first one. A notch is added to let the hooks grasp the main upper plate. Current position should be switch center. Radius should be lower or equal to 0.3 mm """ size = Keyboard.FRAME_CUTOUT half_size = size / 2 if with_notch: notch_length = 5 notch_depth = 1 straight_part = 0.5 * (size - 2 * radius - 2 * notch_depth - notch_length) self.moveTo(-half_size + self.burn, 0, 90) polyline_quarter = [ half_size - radius, (-90, radius), straight_part, (90, notch_depth / 2), 0, (-90, notch_depth / 2), notch_length / 2, ] polyline = ( polyline_quarter + [0] + list(reversed(polyline_quarter)) + [0] + polyline_quarter + [0] + list(reversed(polyline_quarter)) ) self.polyline(*polyline) self.moveTo(0, 0, -90) self.moveTo(half_size - self.burn) else: self.rectangularHole(0, 0, size, size, r=radius)
10,089
Python
.py
247
29.720648
122
0.564814
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,582
cardbox.py
florianfesti_boxes/boxes/generators/cardbox.py
# Copyright (C) 2013-2014 Florian Festi # Copyright (C) 2018 jens persson <jens@persson.cx> # Copyright (C) 2023 Manuel Lohoff # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import BoolArg, Boxes, edges class InsetEdgeSettings(edges.Settings): """Settings for InsetEdge""" absolute_params = { "thickness": 0, } class InsetEdge(edges.BaseEdge): """An edge with space to slide in a lid""" def __call__(self, length, **kw): t = self.settings.thickness self.corner(90) self.edge(t, tabs=2) self.corner(-90) self.edge(length, tabs=2) self.corner(-90) self.edge(t, tabs=2) self.corner(90) class FingerHoleEdgeSettings(edges.Settings): """Settings for FingerHoleEdge""" absolute_params = { "wallheight": 0, "fingerholedepth": 0, } class FingerHoleEdge(edges.BaseEdge): """An edge with room to get your fingers around cards""" def __call__(self, length, **kw): depth = self.settings.fingerholedepth-10 self.edge(length/2-10, tabs=2) self.corner(90) self.edge(depth, tabs=2) self.corner(-180, 10) self.edge(depth, tabs=2) self.corner(90) self.edge(length/2-10, tabs=2) class CardBox(Boxes): """Box for storage of playing cards, with versatile options""" ui_group = "Box" description = """ ### Description Versatile Box for Storage of playing cards. Multiple different styles of storage are supported, e.g. a flat storage or a trading card deck box style storage. See images for ideas. #### Building instructions Place inner walls on floor first (if any). Then add the outer walls. Glue the two walls without finger joins to the inside of the side walls. Make sure there is no squeeze out on top, as this is going to form the rail for the lid. Add the top of the rails to the sides (front open) or to the back and front (right side open) and the grip rail to the lid. Details of the lid and rails ![Details](static/samples/CardBox-detail.jpg) Whole box (early version still missing grip rail on the lid): """ def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser(y=68, h=92, outside=False, sx="65*4") self.argparser.add_argument( "--openingdirection", action="store", type=str, default="front", choices=['front', 'right'], help="Direction in which the lid slides open. Lid length > Lid width recommended.") self.argparser.add_argument( "--fingerhole", action="store", type=str, default="regular", choices=['regular', 'deep', 'custom'], help="Depth of cutout to grab the cards") self.argparser.add_argument( "--fingerhole_depth", action="store", type=float, default=20, help="Depth of cutout if fingerhole is set to 'custom'. Disabled otherwise.") self.argparser.add_argument( "--add_lidtopper", action="store", type=BoolArg(), default=False, help="Add an additional lid topper for optical reasons and customisation" ) @property def fingerholedepth(self): if self.fingerhole == 'custom': return self.fingerhole_depth elif self.fingerhole == 'regular': a = self.h/4 if a < 35: return a else: return 35 elif self.fingerhole == 'deep': return self.h-self.thickness-10 #inner dimensions of surrounding box (disregarding inlays) @property def boxhight(self): if self.outside: return self.h - 3 * self.thickness return self.h @property def boxwidth(self): return (len(self.sx) + 1) * self.thickness + sum(self.sx) @property def boxdepth(self): if self.outside: return self.y - 2 * self.thickness if self.openingdirection == 'right': return self.y + 2 * self.thickness return self.y def divider_bottom(self): t = self.thickness sx = self.sx y = self.boxdepth pos = 0.5 * t for i in sx[:-1]: pos += i + t self.fingerHolesAt(pos, 0, y, 90) def divider_back_and_front(self): t = self.thickness sx = self.sx y = self.boxhight pos = 0.5 * t for i in sx[:-1]: pos += i + t self.fingerHolesAt(pos, 0, y, 90) def render(self): t = self.thickness h = self.boxhight x = self.boxwidth y = self.boxdepth sx = self.sx s = InsetEdgeSettings(thickness=t) p = InsetEdge(self, s) p.char = "a" self.addPart(p) s = FingerHoleEdgeSettings(thickness=t, wallheight=h, fingerholedepth=self.fingerholedepth) p = FingerHoleEdge(self, s) p.char = "A" self.addPart(p) if self.openingdirection == 'right': with self.saved_context(): self.rectangularWall(x, y-t*.2, "eFee", move="right", label="Lid") self.rectangularWall(x, y, "ffff", callback=[self.divider_bottom], move="right", label="Bottom") self.rectangularWall(x, y, "eEEE", move="up only") self.rectangularWall(x, t, "feee", move="up", label="Lip Front") self.rectangularWall(x, t, "eefe", move="up", label="Lip Back") with self.saved_context(): self.rectangularWall(x, h+t, "FfFf", callback=[self.divider_back_and_front], move="right", label="Back") self.rectangularWall(x, h+t, "FfFf", callback=[self.divider_back_and_front], move="right", label="Front") self.rectangularWall(x, h+t, "EEEE", move="up only") with self.saved_context(): self.rectangularWall(y, h+t, "FFEF", move="right", label="Outer Side Left") self.rectangularWall(y, h+t, "FFaF", move="right", label="Outer Side Right") self.rectangularWall(y, h+t, "fFfF", move="up only") with self.saved_context(): self.rectangularWall(y, h, "Aeee", move="right", label="Inner Side Left") self.rectangularWall(y, h, "Aeee", move="right", label="Inner Side Right") self.rectangularWall(y, h, "eAee", move="up only") with self.saved_context(): self.rectangularWall(y-t*.2, t, "fEeE", move="right", label="Lid Lip") self.rectangularWall(y, t*2, "efee", move="up only") for i in range(len(sx) - 1): self.rectangularWall(h, y, "fAff", move="right", label="Divider") for c in sx: self.rectangularWall(c, h, "eeee", move="right", label="Front inlay") self.rectangularWall(c, h, "eeee", move="right", label="Back inlay") if self.add_lidtopper: self.rectangularWall(x, y - 2*t, "eeee", move="right", label="Lid topper") elif self.openingdirection == 'front': with self.saved_context(): self.rectangularWall(x - t * .2, y, "eeFe", move="right", label="Lid") self.rectangularWall(x, y, "ffff", callback=[self.divider_bottom], move="right", label="Bottom") self.rectangularWall(x, y, "eEEE", move="up only") self.rectangularWall(x - t * .2, t, "fEeE", move="up", label="Lid Lip") with self.saved_context(): self.rectangularWall(x, h + t, "FFEF", callback=[self.divider_back_and_front], move="right", label="Back") self.rectangularWall(x, h + t, "FFaF", callback=[self.divider_back_and_front], move="right", label="Front") self.rectangularWall(x, h + t, "EEEE", move="up only") with self.saved_context(): self.rectangularWall(y, h + t, "FfFf", move="right", label="Outer Side Left") self.rectangularWall(y, h + t, "FfFf", move="right", label="Outer Side Right") self.rectangularWall(y, h + t, "fFfF", move="up only") with self.saved_context(): self.rectangularWall(y, h, "Aeee", move="right", label="Inner Side Left") self.rectangularWall(y, h, "Aeee", move="right", label="Inner Side Right") self.rectangularWall(y, h, "eAee", move="up only") with self.saved_context(): self.rectangularWall(y, t, "eefe", move="right", label="Lip Left") self.rectangularWall(y, t, "feee", move="right", label="Lip Right") self.rectangularWall(y, t * 2, "efee", move="up only") for i in range(len(sx) - 1): self.rectangularWall(h, y, "fAff", move="right", label="Divider") if self.add_lidtopper: self.rectangularWall(x, y - 2 * t, "eeee", move="right", label="Lid topper (optional)")
10,063
Python
.py
209
36.818182
230
0.577295
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,583
planetary.py
florianfesti_boxes/boxes/generators/planetary.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Planetary(Boxes): """Planetary Gear with possibly multiple identical stages""" ui_group = "Part" def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--sunteeth", action="store", type=int, default=8, help="number of teeth on sun gear") self.argparser.add_argument( "--planetteeth", action="store", type=int, default=20, help="number of teeth on planets") self.argparser.add_argument( "--maxplanets", action="store", type=int, default=0, help="limit the number of planets (0 for as much as fit)") self.argparser.add_argument( "--deltateeth", action="store", type=int, default=0, help="enable secondary ring with given delta to the ring gear") self.argparser.add_argument( "--modulus", action="store", type=float, default=3, help="modulus of the theeth in mm") self.argparser.add_argument( "--shaft", action="store", type=float, default=6., help="diameter of the shaft") # self.argparser.add_argument( # "--stages", action="store", type=int, default=4, # help="number of stages in the gear reduction") def render(self): ringteeth = self.sunteeth + 2 * self.planetteeth spoke_width = 3 * self.shaft pitch1, size1, xxx = self.gears.sizes(teeth=self.sunteeth, dimension=self.modulus) pitch2, size2, xxx = self.gears.sizes(teeth=self.planetteeth, dimension=self.modulus) pitch3, size3, xxx = self.gears.sizes( teeth=ringteeth, internal_ring=True, spoke_width=spoke_width, dimension=self.modulus) t = self.thickness planets = int(math.pi / (math.asin(float(self.planetteeth + 2) / (self.planetteeth + self.sunteeth)))) if self.maxplanets: planets = min(self.maxplanets, planets) # Make sure the teeth mash ta = self.sunteeth + ringteeth # There are sunteeth+ringteeth mashing positions for the planets if ta % planets: planetpositions = [round(i * ta / planets) * 360 / ta for i in range(planets)] else: planetpositions = planets # XXX make configurable? profile_shift = 20 pressure_angle = 20 self.parts.disc(size3, callback=lambda: self.hole(0, 0, self.shaft / 2), move="up") self.gears(teeth=ringteeth, dimension=self.modulus, angle=pressure_angle, internal_ring=True, spoke_width=spoke_width, mount_hole=self.shaft, profile_shift=profile_shift, move="up") self.gears.gearCarrier(pitch1 + pitch2, spoke_width, planetpositions, 2 * spoke_width, self.shaft / 2, move="up") self.gears(teeth=self.sunteeth, dimension=self.modulus, angle=pressure_angle, mount_hole=self.shaft, profile_shift=profile_shift, move="up") numplanets = planets if self.deltateeth: numplanets += planets deltamodulus = self.modulus * ringteeth / (ringteeth - self.deltateeth) self.gears(teeth=ringteeth - self.deltateeth, dimension=deltamodulus, angle=pressure_angle, internal_ring=True, spoke_width=spoke_width, mount_hole=self.shaft, profile_shift=profile_shift, move="up") for i in range(numplanets): self.gears(teeth=self.planetteeth, dimension=self.modulus, angle=pressure_angle, mount_hole=self.shaft, profile_shift=profile_shift, move="up")
4,549
Python
.py
87
41.183908
110
0.617356
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,584
microrack.py
florianfesti_boxes/boxes/generators/microrack.py
# Copyright (C) 2019 Gabriel Morell # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import Boxes, boolarg, edges class SBCMicroRack(Boxes): """Stackable rackable racks for SBC Pi-Style Computers""" webinterface = True ui_group = "Shelf" # see ./__init__.py for names def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.StackableSettings) self.buildArgParser(x=56, y=85) # count self.argparser.add_argument( "--sbcs", action="store", type=int, default=5, help="how many slots for sbcs", ) # spaces self.argparser.add_argument( "--clearance_x", action="store", type=int, default=3, help="clearance for the board in the box (x) in mm" ) self.argparser.add_argument( "--clearance_y", action="store", type=int, default=3, help="clearance for the board in the box (y) in mm" ) self.argparser.add_argument( "--clearance_z", action="store", type=int, default=28, help="SBC Clearance in mm", ) # mounting holes self.argparser.add_argument( "--hole_dist_edge", action="store", type=float, default=3.5, help="hole distance from edge in mm" ) self.argparser.add_argument( "--hole_grid_dimension_x", action="store", type=int, default=58, help="width of x hole area" ) self.argparser.add_argument( "--hole_grid_dimension_y", action="store", type=int, default=49, help="width of y hole area" ) self.argparser.add_argument( "--hole_diameter", action="store", type=float, default=2.75, help="hole diameters" ) # i/o holes self.argparser.add_argument( "--netusb_z", action="store", type=int, default=18, help="height of the net/usb hole mm" ) self.argparser.add_argument( "--netusb_x", action="store", type=int, default=53, help="width of the net/usb hole in mm" ) # features self.argparser.add_argument( "--stable", action='store', type=boolarg, default=False, help="draw some holes to put a 1/4\" dowel through at the base and top" ) self.argparser.add_argument( "--switch", action='store', type=boolarg, default=False, help="adds an additional vertical segment to hold the switch in place, works best w/ --stable" ) # TODO flesh this idea out better #self.argparser.add_argument( # "--fan", action='store', type=int, default=0, required=False, # help="ensure that the x width is at least this much and as well, draw a snug holder for a fan someplace" # ) def paint_mounting_holes(self): cy = self.clearance_y cx = self.clearance_x h2r = self.hole_diameter hde = self.hole_dist_edge hgdx = self.hole_grid_dimension_x hgdy = self.hole_grid_dimension_y self.hole( h2r + cx + hde / 2, h2r + cy + hde / 2, h2r / 2 ) self.hole( h2r + cx + hgdx + hde / 2, h2r + cy + hde / 2, h2r / 2 ) self.hole( h2r + cx + hde / 2, h2r + cy + hgdy + hde / 2, h2r / 2 ) self.hole( h2r + cx + hgdx + hde / 2, h2r + cy + hgdy + hde / 2, h2r / 2 ) def paint_stable_features(self): if self.stable: self.hole( 10, 10, d=6.5 ) def paint_netusb_holes(self): t = self.thickness x = self.x w = x + self.hole_dist_edge * 2 height_per = self.clearance_z + t usb_height = self.netusb_z usb_width = self.netusb_x for i in range(self.sbcs): self.rectangularHole(w/2, (height_per)*i+15 , usb_width, usb_height, r=1) def paint_finger_holes(self): t = self.thickness height_per = self.clearance_z + t for i in range(self.sbcs): self.fingerHolesAt((height_per) * i + +height_per/2 + 1.5, self.hole_dist_edge, self.x, 90) def render(self): # adjust to the variables you want in the local scope x, y = self.x, self.y t = self.thickness height_per = self.clearance_z + t height_total = self.sbcs * height_per # render your parts here with self.saved_context(): self.rectangularWall(height_total + height_per/2, x + self.hole_dist_edge * 2, "eseS", callback=[self.paint_finger_holes, self.paint_netusb_holes], move="up") self.rectangularWall(height_total + height_per/2, x + self.hole_dist_edge * 2, "eseS", callback=[self.paint_finger_holes, self.paint_stable_features], move="up") if self.switch: self.rectangularWall(height_total + height_per / 2, x + self.hole_dist_edge * 2, "eseS", callback=[self.paint_stable_features], move="up") self.rectangularWall(height_total + height_per/2, x + self.hole_dist_edge * 2, "eseS", move="right only") self.rectangularWall(y + self.hole_dist_edge * 2, x + self.hole_dist_edge * 2, "efef", move="up") for i in range(self.sbcs): self.rectangularWall(y + self.hole_dist_edge * 2, x + self.hole_dist_edge * 2, "efef", callback=[self.paint_mounting_holes], move="up")
7,058
Python
.py
168
29.017857
117
0.521796
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,585
roundedbox.py
florianfesti_boxes/boxes/generators/roundedbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import boxes class RoundedBox(boxes.Boxes): """Box with vertical edges rounded""" description = """ Default: edge_style = f Finger Joint: ![Finger Joint](static/samples/RoundedBox-2.jpg) Alternative: edge_style = h Edge (parallel Finger Joint Holes): ![Finger Joint Holes](static/samples/RoundedBox-3.jpg) With lid: """ ui_group = "FlexBox" def __init__(self) -> None: boxes.Boxes.__init__(self) self.addSettingsArgs(boxes.edges.FingerJointSettings) self.addSettingsArgs(boxes.edges.DoveTailSettings) self.addSettingsArgs(boxes.edges.FlexSettings) self.buildArgParser("x", "y", "outside", sh="100.0") self.argparser.add_argument( "--radius", action="store", type=float, default=15, help="Radius of the corners in mm") self.argparser.add_argument( "--wallpieces", action="store", type=int, default=1, choices=[1, 2, 3, 4], help="number of pieces for outer wall") self.argparser.add_argument( "--edge_style", action="store", type=boxes.ArgparseEdgeType("fFh"), choices=list("fFh"), default="f", help="edge type for top and bottom edges") self.argparser.add_argument( "--top", action="store", type=str, default="none", choices=["closed", "hole", "lid",], help="style of the top and lid") def hole(self): t = self.thickness x, y, r = self.x, self.y, self.radius dr = 2*t if self.edge_style == "h": dr = t if r > dr: r -= dr else: self.moveTo(dr-r, 0) r = 0 lx = x - 2*r - 2*dr ly = y - 2*r - 2*dr self.moveTo(0, dr) for l in (lx, ly, lx, ly): self.edge(l) self.corner(90, r) def cb(self, nr): h = 0.5 * self.thickness left, l, right = self.surroundingWallPiece(nr, self.x, self.y, self.radius, self.wallpieces) for dh in self.sh[:-1]: h += dh self.fingerHolesAt(0, h, l, 0) def render(self): x, y, sh, r = self.x, self.y, self.sh, self.radius if self.outside: self.x = x = self.adjustSize(x) self.y = y = self.adjustSize(y) self.sh = sh = self.adjustSize(sh) r = self.radius = min(r, y / 2.0) t = self.thickness h = sum(sh) + t * (len(sh) - 1) es = self.edge_style corner_holes = True if self.edge_style == "f": pe = "F" ec = False elif self.edge_style == "F": pe = "f" ec = False else: # "h" pe = "f" corner_holes = True ec = True with self.saved_context(): self.roundedPlate(x, y, r, es, wallpieces=self.wallpieces, extend_corners=ec, move="right") for dh in self.sh[:-1]: self.roundedPlate(x, y, r, "f", wallpieces=self.wallpieces, extend_corners=False, move="right") self.roundedPlate(x, y, r, es, wallpieces=self.wallpieces, extend_corners=ec, move="right", callback=[self.hole] if self.top != "closed" else None) if self.top == "lid": r_extra = self.edges[self.edge_style].spacing() self.roundedPlate(x+2*r_extra, y+2*r_extra, r+r_extra, "e", wallpieces=self.wallpieces, extend_corners=False, move="right") self.roundedPlate(x, y, r, es, wallpieces=self.wallpieces, move="up only") self.surroundingWall(x, y, r, h, pe, pe, pieces=self.wallpieces, callback=self.cb)
4,630
Python
.py
109
31.697248
100
0.55516
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,586
folder.py
florianfesti_boxes/boxes/generators/folder.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Folder(Boxes): """Book cover with flex for the spine""" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FlexSettings) self.buildArgParser("x", "y", "h") self.argparser.add_argument( "--r", action="store", type=float, default=10.0, help="radius of the corners") self.argparser.set_defaults(h=20) def render(self): x, y, r, h = self.x, self.y, self.r, self.h c2 = math.pi * h self.moveTo(r + self.thickness, self.thickness) self.edge(x - r) self.edges["X"](c2, y) self.edge(x - r) self.corner(90, r) self.edge(y - 2 * r) self.corner(90, r) self.edge(2 * x - 2 * r + c2) self.corner(90, r) self.edge(y - 2 * r) self.corner(90, r)
1,562
Python
.py
39
34.307692
73
0.637681
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,587
integratedhingebox.py
florianfesti_boxes/boxes/generators/integratedhingebox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class IntegratedHingeBox(Boxes): """Box with lid and integraded hinge""" ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.ChestHingeSettings) self.buildArgParser("x", "y", "h", "outside") self.argparser.add_argument( "--lidheight", action="store", type=float, default=20.0, help="height of lid in mm") def render(self): x, y, h, hl = self.x, self.y, self.h, self.lidheight if self.outside: x = self.adjustSize(x) y = self.adjustSize(y) h = self.adjustSize(h) t = self.thickness hy = self.edges["O"].startwidth() hy2 = self.edges["P"].startwidth() e1 = edges.CompoundEdge(self, "Fe", (h-hy, hy)) e2 = edges.CompoundEdge(self, "eF", (hy, h-hy)) e_back = ("F", e1, "e", e2) self.rectangularWall(y, h-hy, "FfOf", ignore_widths=[2], move="up") self.rectangularWall(y, hl-hy2, "pfFf", ignore_widths=[1], move="up") self.rectangularWall(y, h-hy, "Ffof", ignore_widths=[5], move="up") self.rectangularWall(y, hl-hy2, "PfFf", ignore_widths=[6], move="up") self.rectangularWall(x, h, "FFeF", move="up") self.rectangularWall(x, h, e_back, move="up") self.rectangularWall(x, hl, "FFeF", move="up") self.rectangularWall(x, hl-hy2, "FFqF", move="up") self.rectangularWall(y, x, "ffff", move="up") self.rectangularWall(y, x, "ffff")
2,301
Python
.py
48
41.229167
77
0.639125
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,588
rotary.py
florianfesti_boxes/boxes/generators/rotary.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class MotorEdge(edges.BaseEdge): # def margin(self) -> float: # return 30.0 def __call__(self, l, **kw): self.polyline( l - 165, 45, 25 * 2 ** 0.5, -45, 60, -45, 25 * 2 ** 0.5, 45, 55) class OutsetEdge(edges.OutSetEdge): def startwidth(self) -> float: return 20.0 class HangerEdge(edges.BaseEdge): char = "H" def margin(self) -> float: return 40.0 def __call__(self, l, **kw): self.fingerHolesAt(0, -0.5 * self.thickness, l, angle=0) w = self.settings self.polyline(0, -90, 22 + w, 90, 70, 135, 2 ** 0.5 * 12, 45, 35, -45, 2 ** 0.5 * 0.5 * w, -90, 2 ** 0.5 * 0.5 * w, -45, l - 28, 45, 2 ** 0.5 * 5, 45, 5, -90) class RollerEdge(edges.BaseEdge): def margin(self) -> float: return 20.0 def __call__(self, l, **kw): m = 40 + 100 self.polyline((l - m) / 2.0, -45, 2 ** 0.5 * 20, 45, 100, 45, 2 ** 0.5 * 20, -45, (l - m) / 2.0) class RollerEdge2(edges.BaseEdge): def margin(self) -> float: return self.thickness def __call__(self, l, **kw): a = 30 f = 1 / math.cos(math.radians(a)) self.edges["f"](70) self.polyline(0, a, f * 25, -a, l - 190, -a, f * 25, a, 0) self.edges["f"](70) class Rotary(Boxes): """Rotary Attachment for engraving cylindrical objects in a laser cutter""" ui_group = "Unstable" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--diameter", action="store", type=float, default=72., help="outer diameter of the wheels (including O rings)") self.argparser.add_argument( "--rubberthickness", action="store", type=float, default=5., help="diameter of the strings of the O rings") self.argparser.add_argument( "--axle", action="store", type=float, default=6., help="diameter of the axles") self.argparser.add_argument( "--knifethickness", action="store", type=float, default=8., help="thickness of the knives in mm. Use 0 for use with honey comb table.") self.argparser.add_argument( "--beamwidth", action="store", type=float, default=32., help="width of the (aluminium) profile connecting the parts") self.argparser.add_argument( "--beamheight", action="store", type=float, default=7.1, help="height of the (aluminium) profile connecting the parts") def mainPlate(self): # Motor block outer side t = self.thickness d = self.diameter a = self.axle bw, bh = self.beamwidth, self.beamheight hh = 0.5 * d + bh + 2 # hole height self.hole(1.0 * d, hh, a/2.) #self.hole(1.0 * d, hh, d/2.) self.hole(2.0 * d + 5, hh, a/2.) #self.hole(2.0 * d + 5, hh, d/2.) # Main beam self.rectangularHole(1.5*d+2.5, 0.5*bh, bw, bh) def frontPlate(self): # Motor block inner side with motor mount t = self.thickness d = self.diameter a = self.axle bw, bh = self.beamwidth, self.beamheight hh = 0.5 * d + bh + 2 # hole height self.hole(1.0 * d, hh, a/2.) #self.hole(1.0 * d, hh, d/2.) self.hole(2.0 * d + 5, hh, a/2.) #self.hole(2.0 * d + 5, hh, d/2.) # Main beam self.rectangularHole(1.5 * d+2.5, 0.5 * bh, bw, bh) # Motor mx = 2.7 * d + 20 self.rectangularHole(mx, hh, 36 + 20, 36, r=36 / 2.0) for x in (-1, 1): for y in (-1,1): self.rectangularHole(mx+x * 25, hh + y * 25, 20, 4, r=2) def link(self, x, y, a, middleHole=False, move=None): t = self.thickness overallwidth = x + y overallheight = y ra = a / 2.0 if self.move(overallwidth, overallheight, move, before=True): return self.moveTo(y / 2.0, 0) self.hole(0, y / 2., ra) self.hole(x, y / 2., ra) if middleHole: self.hole(x / 2., y / 2., ra) self.edge(10) self.edges["F"](60) self.polyline(x - 70, (180, y / 2.), x, (180, y / 2.)) self.move(overallwidth, overallheight, move) def holderBaseCB(self): bw, bh = self.beamwidth, self.beamheight self.hole(20, self.hh - 10, self.a / 2) self.rectangularHole(self.hl - 70, self.hh - 10, 110, self.a, r=self.a / 2) self.rectangularHole(self.hl / 2, 0.5 * bh, bw, bh) def holderTopCB(self): self.fingerHolesAt(0, 30 - 0.5 * self.thickness, self.hl, 0) d = self.diameter / 2.0 + 1 # XXX y = -0.5 * self.diameter + self.th + self.hh - self.beamheight - 2. self.hole(self.hl / 2 + d, y, self.axle / 2.0) self.hole(self.hl / 2 - d, y, self.axle / 2.0) self.hole(self.hl / 2 + d, y, self.diameter / 2.0) self.hole(self.hl / 2 - d, y, self.diameter / 2.0) def render(self): # adjust to the variables you want in the local scope t = self.thickness d = self.diameter a = self.a = self.axle bw, bh = self.beamwidth, self.beamheight # self.spacing = 0.1 * t # Change settings of default edges if needed. E.g.: self.edges["f"].settings.setValues(self.thickness, space=2, finger=2, surroundingspaces=1) if self.knifethickness: self.addPart(HangerEdge(self, self.knifethickness)) else: self.edges["H"] = self.edges["F"] # Holder hw = self.hw = 70. hh = self.hh = 35. + bh hl = self.hl = 240 # Base self.rectangularWall(hl, hh, edges="hfef", callback=[self.holderBaseCB, None, lambda: self.rectangularHole(hl / 2 + 50, hh - t / 2 - 1, 60, t + 2)], move="up") self.rectangularWall(hl, hh, edges="hfef", callback=[self.holderBaseCB], move="up") self.rectangularWall(hl, hw, edges="ffff", callback=[lambda: self.hole(hl / 2 - 16 - 20, 25, 5)], move="up") with self.saved_context(): self.rectangularWall(hw, hh, edges="hFeF", callback=[ lambda: self.hole(hw / 2, hh - 20, 4)],move="right") self.rectangularWall(hw, hh, edges="hFeF", move="right") # Top th = self.th = 30 # sides self.rectangularWall(hw + 20, th, edges="fFeF", move="right", callback=[lambda: self.fingerHolesAt(20 - 0.5 * t, 0, th)]) self.rectangularWall(hw + 20, th, edges="fFeF", move="right", callback=[lambda: self.fingerHolesAt(20 - 0.5 * t, 0, th)]) self.rectangularWall(hw, hh, edges="hFeF", move="up only") outset = OutsetEdge(self, None) roller2 = RollerEdge2(self, None) self.rectangularWall(hl, th, edges=[roller2, "f", "e", "f"], callback=[ lambda: self.hole(20, 15, a / 2), None, lambda: self.rectangularHole(50, th - 15, 70, a, r=a / 2)], move="up") self.rectangularWall(hl, th, edges=[roller2, "f", "e", "f"], callback=[ lambda: self.hole(20, 15, a / 2), None, lambda: self.rectangularHole(50, th - 15 - t, 70, a, r=a / 2)], move="up") self.rectangularWall(hl, th, edges=[roller2, "f", RollerEdge(self, None), "f"], callback=[ self.holderTopCB], move="up") self.rectangularWall(hl, 20 - t, edges="feee", move="up") tl = 70 self.rectangularWall(tl, hw + 20, edges="FeFF", move="right", callback=[None, lambda: self.fingerHolesAt(20 - 0.5 * t, 0, tl)]) self.rectangularWall(tl, hw + 20, edges="FeFF", move="", callback=[None, lambda: self.fingerHolesAt(20 - 0.5 * t, 0, tl)]) self.rectangularWall(tl, hw + 20, edges="FeFF", move="left up only", callback=[None, lambda: self.fingerHolesAt(20 - 0.5 * t, 0, tl)]) # Links self.link(hl - 40, 25, a, True, move="up") self.link(hl - 40, 25, a, True, move="up") self.link(hl - 40, 25, a, True, move="up") self.link(hl - 40, 25, a, True, move="up") with self.saved_context(): self.rectangularWall(hw - 2 * t - 2, 60, edges="efef", move="right") self.rectangularWall(hw - 4 * t - 4, 60, edges="efef", move="right") # Spindle auxiliaries self.parts.wavyKnob(50, callback=lambda: self.nutHole("M8"), move="right") self.parts.wavyKnob(50, callback=lambda: self.nutHole("M8"), move="right") self.rectangularWall(hw - 2 * t - 4, 60, edges="efef", move="up only") with self.saved_context(): slot = edges.SlottedEdge(self, [(30 - t) / 2, (30 - t) / 2], slots=15) self.rectangularWall(30, 30, edges=["e", "e", slot, "e"], callback=[lambda: self.hole(7, 23, self.axle / 2)], move="right") self.rectangularWall(30, 30, edges=["e", "e", slot, "e"], callback=[lambda: self.hole(7, 23, self.axle / 2)], move="right") leftover = (hw - 6 * t - 6 - 20) / 2.0 slot = edges.SlottedEdge(self, [leftover, 20, leftover], slots=15) self.rectangularWall(hw - 4 * t - 6, 30, edges=[slot, "e", "e", "e"], callback=[lambda: self.hole((hw - 4 * t - 6) / 2., 15, 4)], move="right") for i in range(3): self.rectangularWall(20, 30, callback=[lambda: self.nutHole("M8", 10, 15)], move="right") self.rectangularWall(20, 30, callback=[lambda: self.hole(10, 15, 4)], move="right") self.rectangularWall(30, 30, move="up only") self.h = h = bh + 2 + 1.0 * d # height of outer pieces # Other side if self.knifethickness: ow = 10 self.rectangularWall(3.6 * d, h, edges="hfFf", callback=[ lambda:self.rectangularHole(1.8 * d, 0.5 * bh, bw, bh)], move="up") self.rectangularWall(3.6 * d, h, edges="hfFf", callback=[ lambda:self.rectangularHole(1.8 * d, 0.5 * bh, bw, bh)], move="up") self.rectangularWall(3.6 * d, ow, edges="ffff", move="up") self.rectangularWall(3.6 * d, ow, edges="ffff", move="up") with self.saved_context(): self.rectangularWall(ow, h, edges="hFFH", move="right") self.rectangularWall(ow, h, edges="hFFH", move="right") self.rectangularWall(ow, h, edges="hFFH", move="up only") # Motor block mw = 40 self.rectangularWall(3.6 * d, h, edges=["h", "f", MotorEdge(self, None),"f"], callback=[self.mainPlate], move="up") self.rectangularWall(3.6 * d, h, edges=["h", "f", MotorEdge(self, None),"f"], callback=[self.frontPlate], move="up") self.rectangularWall(3.6 * d, mw, edges="ffff", move="up") with self.saved_context(): self.rectangularWall(mw, h, edges="hFeH", move="right") self.rectangularWall(mw, h, edges="hFeH", move="right") self.pulley(88, "GT2_2mm", r_axle=a / 2.0, move="right") self.pulley(88, "GT2_2mm", r_axle=a / 2.0, move="right") self.rectangularWall(mw, h, edges="hFeH", move="up only") self.axle = 19 for i in range(3): self.parts.disc(self.diameter - 2 * self.rubberthickness, hole=self.axle, move="right") self.parts.disc(self.diameter - 2 * self.rubberthickness, hole=self.axle, move="up right") for i in range(3): self.parts.disc(self.diameter - 2 * self.rubberthickness, hole=self.axle, move="left") self.parts.disc(self.diameter - 2 * self.rubberthickness, hole=self.axle, move="left up") for i in range(3): self.parts.disc(self.diameter - 2 * self.rubberthickness + 4, hole=self.axle, move="right") self.parts.disc(self.diameter - 2 * self.rubberthickness + 4, hole=self.axle, move="right up")
13,596
Python
.py
274
37.649635
124
0.531193
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,589
alledges.py
florianfesti_boxes/boxes/generators/alledges.py
# Copyright (C) 2013-2018 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class AllEdges(Boxes): """Showing all edge types""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.StackableSettings) self.addSettingsArgs(edges.HingeSettings) self.addSettingsArgs(edges.SlideOnLidSettings) self.addSettingsArgs(edges.ClickSettings) self.addSettingsArgs(edges.FlexSettings) self.addSettingsArgs(edges.HandleEdgeSettings) self.buildArgParser(x=100) def render(self): x = self.x t = self.thickness chars = list(self.edges.keys()) chars.sort(key=lambda c: c.lower() + (c if c.isupper() else '')) chars.reverse() self.moveTo(0, 10*t) for c in chars: with self.saved_context(): self.move(0, 0, "", True) self.moveTo(x, 0, 90) self.edge(t+self.edges[c].startwidth()) self.corner(90) self.edges[c](x, h=4*t) self.corner(90) self.edge(t+self.edges[c].endwidth()) self.move(0, 0, "") self.moveTo(0, 3*t + self.edges[c].spacing()) self.text(f"{c} - {self.edges[c].description}") self.moveTo(0, 12*t)
2,049
Python
.py
48
34.770833
73
0.636501
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,590
regularstarbox.py
florianfesti_boxes/boxes/generators/regularstarbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class SlotEdge(edges.Edge): def __call__(self, length, **kw): t, n = self.settings.thickness, self.settings.n r, h = self.settings.radius, self.settings.h sh = self.settings.sh # distance side to center li = 2 * sh * math.tan(math.radians(90/n)) # side inner 2x polygon ls2 = t / math.tan(math.radians(180/n)) ls1 = t / math.cos(math.radians(90-(180/n))) lo = (length-li-2*ls1)/2 li = li - 2*ls2 # correct for overlap of wall d = h/2 if li > 0: poly = [lo-1, (90, 1), d+t-1, -90, ls1+ls2, -90, d-t, (90, t)] self.polyline(*(poly + [li-2*t] + list(reversed(poly)))) else: raise ValueError("Box is too small and has too many corners to work properly") def startwidth(self) -> float: return self.settings.thickness class RegularStarBox(Boxes): """Regular polygon boxes that form a star when closed""" ui_group = "Box" description = """![Open box](static/samples/RegularStarBox-2.jpg)""" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.buildArgParser("h", "outside") self.argparser.add_argument( "--radius", action="store", type=float, default=50.0, help="inner radius if the box (center to corners)") self.argparser.add_argument( "--n", action="store", type=int, default=5, choices=(3, 4, 5), help="number of sides") def render(self): r, h, n = self.radius, self.h, self.n if self.outside: self.r = r = r - self.thickness / math.cos(math.radians(360/(2*n))) self.h = h = self.adjustSize(h) t = self.thickness fingerJointSettings = copy.deepcopy(self.edges["f"].settings) fingerJointSettings.setValues(self.thickness, angle=360./n) fingerJointSettings.edgeObjects(self, chars="gGH") self.edges["e"] = SlotEdge(self, self) r, sh, side = self.regularPolygon(n, radius=r) self.sh = sh with self.saved_context(): self.regularPolygonWall(corners=n, r=r, edges='F', move="right") self.regularPolygonWall(corners=n, r=r, edges='F', move="right") self.regularPolygonWall(corners=n, r=r, edges='F', move="up only") for s in range(2): with self.saved_context(): if n % 2: for i in range(n): self.rectangularWall(side, h, move="right", edges="fgeG") else: for i in range(n//2): self.rectangularWall(side, h, move="right", edges="fGeG") self.rectangularWall(side, h, move="right", edges="fgeg") self.rectangularWall(side, h, move="up only", edges="fgeG")
3,783
Python
.py
78
37.615385
90
0.581022
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,591
console.py
florianfesti_boxes/boxes/generators/console.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Console(Boxes): """Console with slanted panel""" ui_group = "Box" description = """ Console Arcade Stick ![Front](static/samples/ConsoleArcadeStickFront.jpg) ![Back](static/samples/ConsoleArcadeStickBack.jpg) ![Inside](static/samples/ConsoleArcadeStickInside.jpg) Keyboard enclosure: """ def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=.5) self.addSettingsArgs(edges.StackableSettings) self.buildArgParser(x=100, y=100, h=100, outside=False) self.argparser.add_argument( "--front_height", action="store", type=float, default=30, help="height of the front below the panel (in mm)") self.argparser.add_argument( "--angle", action="store", type=float, default=50, help="angle of the front panel (90°=upright)") def render(self): x, y, h, hf = self.x, self.y, self.h, self.front_height t = self.thickness if self.outside: self.x = x = self.adjustSize(x) self.y = y = self.adjustSize(y) self.h = h = self.adjustSize(h) panel = min((h-hf)/math.cos(math.radians(90-self.angle)), y/math.cos(math.radians(self.angle))) top = y - panel * math.cos(math.radians(self.angle)) h = hf + panel * math.sin(math.radians(self.angle)) if top>0.1*t: borders = [y, 90, hf, 90-self.angle, panel, self.angle, top, 90, h, 90] else: borders = [y, 90, hf, 90-self.angle, panel, self.angle+90, h, 90] if hf < 0.01*t: borders[1:4] = [180-self.angle] self.polygonWall(borders, move="right") self.polygonWall(borders, move="right") self.polygonWalls(borders, x)
2,567
Python
.py
57
38
77
0.647814
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,592
flexbox4.py
florianfesti_boxes/boxes/generators/flexbox4.py
# Copyright (C) 2013-2018 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class FlexBox4(Boxes): """Box with living hinge and left corners rounded""" ui_group = "FlexBox" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.FlexSettings) self.buildArgParser("x", "y", "h", "outside") self.argparser.add_argument( "--radius", action="store", type=float, default=15, help="Radius of the corners in mm") self.argparser.add_argument( "--latchsize", action="store", type=float, default=8, help="size of latch in multiples of thickness") def flexBoxSide(self, x, y, r, callback=None, move=None): t = self.thickness if self.move(x+2*t, y+t, move, True): return self.moveTo(t, t) self.cc(callback, 0) self.edges["f"](x) self.corner(90, 0) self.cc(callback, 1) self.edges["f"](y - r) self.corner(90, r) self.cc(callback, 2) self.edge(x - 2 * r) self.corner(90, r) self.cc(callback, 3) self.edges["e"](y - r - self.latchsize) self.cc(callback, 4) self.latch(self.latchsize) self.corner(90) self.move(x+2*t, y+t, move) def surroundingWall(self, move=None): x, y, h, r = self.x, self.y, self.h, self.radius c4 = self.c4 t = self.thickness tw, th = 2*c4 + 2*y + x - 4*r + 2*t, h + 2.5*t if self.move(tw, th, move, True): return self.moveTo(t, 0.25*t) self.edges["F"](y - r, False) if (x - 2 * r < self.thickness): self.edges["X"](2 * c4 + x - 2 * r, h + 2 * self.thickness) else: self.edges["X"](c4, h + 2 * self.thickness) self.edge(x - 2 * r) self.edges["X"](c4, h + 2 * self.thickness) self.edge(y - r - self.latchsize) self.latch(self.latchsize, False, extra_length=t) self.edge(h + 2 * self.thickness) self.latch(self.latchsize, False, True, extra_length=t) self.edge(y - r - self.latchsize) self.edge(c4) self.edge(x - 2 * r) self.edge(c4) self.edges["F"](y - r) self.corner(90) self.edge(self.thickness) self.edges["f"](h) self.edge(self.thickness) self.corner(90) self.move(tw, th, move) def render(self): if self.outside: self.x = self.adjustSize(self.x) self.y = self.adjustSize(self.y) self.h = self.adjustSize(self.h) self.latchsize *= self.thickness self.radius = self.radius or min(self.x / 2.0, self.y - self.latchsize) self.radius = min(self.radius, self.x / 2.0) self.radius = min(self.radius, max(0, self.y - self.latchsize)) self.c4 = c4 = math.pi * self.radius * 0.5 self.surroundingWall(move="up") self.flexBoxSide(self.x, self.y, self.radius, move="right") self.flexBoxSide(self.x, self.y, self.radius, move="mirror right") self.rectangularWall(self.x, self.h, edges="FeFF")
3,863
Python
.py
93
33.376344
79
0.596585
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,593
stachel.py
florianfesti_boxes/boxes/generators/stachel.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Stachel(Boxes): """Bass Recorder Endpin""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.argparser.add_argument( "--flutediameter", action="store", type=float, default=115.0, help="diameter of the flutes bottom in mm") self.argparser.add_argument( "--polediameter", action="store", type=float, default=25., help="diameter if the pin in mm") self.argparser.add_argument( "--wall", action="store", type=float, default=7., help="width of the surrounding wall in mm") def layer(self, ri, ro, rp, holes=False, move=""): r = 2.5 # radius l = 25 # depth of clamp w = 20 # width of clamp wp = rp+8 # width pole tw = 2*ro + 2*rp th = 2*ro + l if self.move(tw, th, move, True): return self.moveTo(ro, r, 90) a1 = math.degrees(math.asin(w / ro)) a2 = math.degrees(math.asin(wp / ro)) l1 = ro*(1-math.cos(math.radians(a1))) a3 = math.degrees(math.asin(1./rp)) self.polyline(ro-ri+l-r, 90, 0, (-355, ri), 0, 90, ro-ri+l-r, # inside (90, r), w-2*r, (90, r)) if holes: # right side main clamp poly1 = [(l+l1-2)/2-r, 90, w-2, -90, 2, -90, w-2, 90, (l+l1-2)/2] self.polyline(*poly1) else: self.polyline(l+l1-r) self.polyline(0, -90+a1, 0 , (90-a1-a2, ro), 0, -90+a2) if holes: poly2 = [2*rp+15, 90, wp-2, -90, 2, -90, wp-2, 90, 10-2-r] self.polyline(*poly2) else: self.polyline(25+2*rp-r) self.polyline(0, (90, r), wp-1-r, 90, 20, 90-a3, 0, (-360+2*a3, rp), 0, 90-a3, 20, 90, wp-1-r, (90, r)) if holes: self.polyline(*list(reversed(poly2))) else: self.polyline(25+2*rp-r) self.polyline(0, -90+a2, 0, (270-a2-a1-5, ro), 0, (-90+a1)) if holes: # left sidemain clamp self.polyline(*list(reversed(poly1))) else: self.polyline(l+l1-r) self.polyline(0, (90, r), w-2*r, (90, r)) self.move(tw, th, move) def render(self): ri = self.flutediameter / 2.0 ro = ri + self.wall rp = self.polediameter / 2.0 w = self.wall self.layer(ri-20, ro, rp, move="up") self.layer(ri, ro, rp, True, move="up") self.layer(ri, ro, rp, move="up")
3,238
Python
.py
77
33.441558
111
0.563156
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,594
ottolegs.py
florianfesti_boxes/boxes/generators/ottolegs.py
# Copyright (C) 2013-2016 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes import edges class LegEdge(edges.BaseEdge): def __call__(self, l, **kw): d0 = (l - 12.0) /2 self.hole(l/2, 6, 3.0) self.polyline(d0, 90, 0, (-180, 6), 0, 90, d0) class OttoLegs(Boxes): """Otto LC - a laser cut chassis for Otto DIY - legs""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, finger=1.0, space=1.0, surroundingspaces=1.0) self.argparser.add_argument( "--anklebolt1", action="store", type=float, default=3.0, help="diameter for hole for ankle bolts - foot side") self.argparser.add_argument( "--anklebolt2", action="store", type=float, default=2.6, help="diameter for hole for ankle bolts - leg side") self.argparser.add_argument( "--length", action="store", type=float, default=34.0, help="length of legs (34mm min)") def foot(self, x, y, ly, l, r=5., move=None): if self.move(x, y, move, True): return t = self.thickness w = ly + 5.5 + 2 * t self.fingerHolesAt(x/2 - w/2, 0, l, 90) self.fingerHolesAt(x/2 + w/2, 0, l, 90) self.moveTo(r, 0) for l in (x, y, x, y): self.polyline((l - 2*r, 2), 45, r*2**0.5, 45) self.move(x, y, move) def ankles(self, x, h, edge="f", callback=None, move=None): f = 0.5 tw = x th = 2 * h + self.thickness if self.move(tw, th, move, True): return self.moveTo(0, self.thickness) for i in range(2): self.cc(callback, 0) self.edges[edge](x) self.polyline(0, 90) self.cc(callback, 1) self.polyline((h, 2), 90, (f*x, 1), 45, ((2**0.5)*(1-f)*x, 1), 45, (h-(1-f)*x, 1), 90) self.moveTo(tw, th, 180) self.ctx.stroke() self.move(tw, th, move) def ankle1(self): # from vertical edge self.hole(15, 10, 3.45) # 3.45 for servo arm, 2.3 for knob def servoring(self, move=""): if self.move(20, 20, move, True): return self.moveTo(10, 10, 90) self.moveTo(3.45, 0, -90) self.polyline(0, (-264, 3.45), 0, 36, 6.55, 108, 0, (330, 9.0, 4), 0, 108, 6.55) self.move(20, 20, move) def ankle2(self): # from vertical edge self.hole(15, 10, self.anklebolt1/2) def servoHole(self): self.hole(6, 6, 11.6/2) self.hole(6, 12, 5.5/2) def render(self): # adjust to the variables you want in the local scope t = self.thickness ws = 25 lx, ly, lh = 12.4, 23.5, max(self.length, ws+6+t) self.ctx.save() # Legs c1 = edges.CompoundEdge(self, "FE", (ly-7.0, 7.0)) c2 = edges.CompoundEdge(self, "EF", (7.0, lh-7.0)) e = [c1, c2, "F", "F"] for i in range(2): # front self.rectangularWall(lx, lh-7., [LegEdge(self, None), "f", "F", "f"], callback=[None, lambda:self.fingerHolesAt(ws-7., 0, lx)], move="right") # back self.rectangularWall(lx, lh, "FfFf", callback=[ lambda:self.hole(lx/2, 7, self.anklebolt2/2)], move="right") # sides self.rectangularWall(ly, lh, e, callback=[None, lambda:self.fingerHolesAt(ws, 7.0, ly-7.0-3.0)], move="right") self.rectangularWall(ly, lh, e, callback=[ lambda:self.rectangularHole(ly/2, ws+3+0.5*t, 12, 6, 3), lambda:self.fingerHolesAt(ws, 7.0, ly-7.0-3.0)], move="right") # top self.partsMatrix(2, 1, "right", self.rectangularWall, ly, lx, "ffff", callback=[None, lambda: self.hole(lx/2, ly/2, 2.3)]) self.partsMatrix(2, 1, "right", self.rectangularWall, lx, ly, "eeee", callback=[lambda: self.hole(lx/2, ly/2, 1.5)]) # hold servo at the front self.partsMatrix(2, 1, "right", self.rectangularWall, 4.6, lx, "efee") # bottom self.partsMatrix(2, 1, "right", self.rectangularWall, lx, ly-7.0, "efff") # hold servo inside self.partsMatrix(2, 1, "right", self.rectangularWall, lx, ly-7.0-3.0, "efef") self.ctx.restore() self.rectangularWall(lx, lh, "ffff", move="up only") # feet self.foot(60, 40, ly, 30, move="right") self.foot(60, 40, ly, 30, move="right") self.ankles(30, 25, callback=[None, self.ankle1], move="right") self.ankles(30, 25, callback=[None, self.ankle2], move="right") self.partsMatrix(2, 2, "right", self.servoring)
5,451
Python
.py
121
35.900826
153
0.567817
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,595
dicetower.py
florianfesti_boxes/boxes/generators/dicetower.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class DiceTower(Boxes): """Tool for fairly rolling dice""" ui_group = "Misc" description = """Feel free to add a shallow ABox as a container for catching the dice so they don't scatter across the table. You can also configure the DiceTower and change the number and angle of the ramps. """ def __init__(self): Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.argparser.add_argument( "--width", action="store", type=float, default=80.0, help="width of the tower (side where the dice fall out)") self.argparser.add_argument( "--depth", action="store", type=float, default=80.0, help="depth of the tower") self.argparser.add_argument( "--height", action="store", type=float, default=170.0, help="height of the tower") self.buildArgParser("outside") self.argparser.add_argument( "--bottom", action="store", type=boolarg, default=True, help="include bottom piece") self.argparser.add_argument( "--ramps", action="store", type=int, default=3, help="number of ramps in the tower") self.argparser.add_argument( "--angle", action="store", type=float, default=30.0, help="angle of the ramps in the tower") def side(self): a = math.radians(self.angle) # Bottom ramp (full length) pos_x = self.left_ramp_cutoff pos_y = (self.depth - self.left_ramp_cutoff) * math.tan(a) self.fingerHolesAt(pos_x, pos_y, self.ramp_len, -self.angle) # Other ramps top_gap = 4 * self.thickness section_height = (self.height - pos_y - top_gap) / (self.ramps - 1) for i in range(self.ramps -1): pos_y_i = pos_y + (section_height * (i+1)) self.ramp(pos_x, pos_y_i, i % 2 == 0) def ramp(self, pos_x, pos_y, mirror): # Fingerholes for a single ramp if mirror: # Starts on left side (front) self.fingerHolesAt(self.depth - pos_x, pos_y, 0.5*self.ramp_len, 180+self.angle) else: # Starts on right side (back) self.fingerHolesAt(pos_x, pos_y, 0.5*self.ramp_len, -self.angle) def render(self): if self.outside: self.width = self.adjustSize(self.width) self.depth = self.adjustSize(self.depth) self.height = self.adjustSize(self.height) # Calculate length of the bottom ramp a = math.radians(self.angle) # Start ramps a bit to the side, so we don't have overlap self.left_ramp_cutoff = (0.5*self.thickness)*math.sin(a) # Bottom ramp also needs to end a bit earlier self.right_ramp_cutoff = (0.5*self.thickness) / math.tan(a) * math.cos(a) self.ramp_len = (self.depth - self.left_ramp_cutoff - self.right_ramp_cutoff) / math.cos(a) # Leave room for dice to fall through on the bottom front_gap = self.depth * math.tan(a) front_edge = edges.CompoundEdge(self, "Ef", (front_gap, self.height - front_gap)) # Outer walls bottom_edge = "F" if self.bottom else "e" self.rectangularWall(self.depth, self.height, (bottom_edge, front_edge, "e", "f"), callback=[self.side], move="mirror right", label="side") self.rectangularWall(self.width, self.height, (bottom_edge, "F", "e", "F"), move="right", label="back") self.rectangularWall(self.depth, self.height, (bottom_edge, front_edge, "e", "f"), callback=[self.side], move="right", label="side") self.rectangularWall(self.width, self.height - front_gap, ("e", "F", "e", "F"), move="right", label="front") # Bottom if self.bottom: self.rectangularWall(self.width, self.depth, "Efff", move="right", label="bottom") # ramps self.rectangularWall(self.width, self.ramp_len, "efef", move="up", label="ramp") for _ in range(self.ramps - 1): self.rectangularWall(self.width, 0.5*self.ramp_len, "efef", move="up", label="ramp")
4,759
Python
.py
85
47.976471
147
0.640954
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,596
gridfinitydrillbox.py
florianfesti_boxes/boxes/generators/gridfinitydrillbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import ArgparseEdgeType, Boxes, edges from boxes.generators.gridfinitytraylayout import GridfinityTrayLayout from boxes.lids import LidSettings, _TopEdge class GridfinityDrillBox(_TopEdge, GridfinityTrayLayout): """A Gridfinity box for drills or similar tools""" description = """You need to add a hole pattern to all horizontal layers except the very bottom""" ui_group = "Tray" def __init__(self) -> None: Boxes.__init__(self) self.pitch = 42.0 # gridfinity pitch is defined as 42. self.opening = 38 self.opening_margin = 2 self.addSettingsArgs(edges.FingerJointSettings, space=3, finger=3, surroundingspaces=1) self.addSettingsArgs(edges.RoundedTriangleEdgeSettings, outset=1) self.addSettingsArgs(edges.StackableSettings) self.addSettingsArgs(edges.MountingSettings) self.addSettingsArgs(LidSettings) self.argparser.add_argument("--nx", type=int, default=3, help="number of gridfinity grids in X direction") self.argparser.add_argument("--ny", type=int, default=2, help="number of gridfinity grids in Y direction") self.argparser.add_argument("--margin", type=float, default=0.75, help="Leave this much total margin on the outside, in mm") self.argparser.add_argument( "--top_edge", action="store", type=ArgparseEdgeType("eStG"), choices=list("eStG"), default="e", help="edge type for top edge") self.buildArgParser(sh="5:25:10") def sideholes(self, l): t = self.thickness h = -0.5 * t for d in self.sh[:-1]: h += d + t self.fingerHolesAt(0, h, l, angle=0) def render(self): self.x = x = self.pitch * self.nx - self.margin - 2 * self.thickness self.y = y = self.pitch * self.ny - self.margin - 2 * self.thickness h = sum(self.sh) + self.thickness * (len(self.sh)-1) b = "F" t1, t2, t3, t4 = self.topEdges(self.top_edge) self.rectangularWall( x, h, [b, "f", t1, "f"], ignore_widths=[1, 6], callback=[lambda: self.sideholes(x)], move="right") self.rectangularWall( y, h, [b, "F", t2, "F"], callback=[lambda: self.sideholes(y)], ignore_widths=[1, 6], move="up") self.rectangularWall( y, h, [b, "F", t3, "F"], callback=[lambda: self.sideholes(y)], ignore_widths=[1, 6]) self.rectangularWall( x, h, [b, "f", t4, "f"], ignore_widths=[1, 6], callback=[lambda: self.sideholes(x)], move="left up") if b != "e": self.rectangularWall(x, y, "ffff", callback=[self.baseplate_etching], move="right") for d in self.sh[:-1]: self.rectangularWall( x, y, "ffff", move="right") self.lid(x, y, self.top_edge) foot = self.opening - self.opening_margin for i in range(min(self.nx * self.ny, 4)): self.rectangularWall(foot, foot, move="right")
3,790
Python
.py
76
41.526316
132
0.63064
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,597
universalbox.py
florianfesti_boxes/boxes/generators/universalbox.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * from boxes import lids from boxes.edges import Bolts from boxes.lids import _TopEdge class UniversalBox(_TopEdge): """Box with various options for different styles and lids""" ui_group = "Box" def __init__(self) -> None: Boxes.__init__(self) self.addTopEdgeSettings(roundedtriangle={"outset" : 1}, hinge={"outset" : True}) self.addSettingsArgs(edges.FlexSettings) self.addSettingsArgs(lids.LidSettings) self.buildArgParser("top_edge", "bottom_edge", "x", "y", "h", "outside") self.argparser.add_argument( "--vertical_edges", action="store", type=str, default="finger joints", choices=("finger joints", "finger holes"), help="connections used for the vertical edges") def top_hole(self, x, y, top_edge): t = self.thickness if top_edge == "f": edge = self.edges["F"] self.moveTo(2*t+self.burn, 2*t, 90) elif top_edge == "F": edge = self.edges["f"] self.moveTo(t+self.burn, 2*t, 90) else: raise ValueError("Only f and F supported") for l in (y, x, y, x): edge(l) if top_edge == "F": self.edge(t) self.corner(-90) if top_edge == "F": self.edge(t) def render(self): x, y, h = self.x, self.y, self.h t = self.thickness tl, tb, tr, tf = self.topEdges(self.top_edge) b = self.edges.get(self.bottom_edge, self.edges["F"]) d2 = Bolts(2) d3 = Bolts(3) d2 = d3 = None sideedge = "F" if self.vertical_edges == "finger joints" else "h" if self.outside: self.x = x = self.adjustSize(x, sideedge, sideedge) self.y = y = self.adjustSize(y) self.h = h = self.adjustSize(h, b, self.top_edge) with self.saved_context(): self.rectangularWall(x, h, [b, sideedge, tf, sideedge], ignore_widths=[1, 6], bedBolts=[d2], move="up", label="front") self.rectangularWall(x, h, [b, sideedge, tb, sideedge], ignore_widths=[1, 6], bedBolts=[d2], move="up", label="back") if self.bottom_edge != "e": self.rectangularWall(x, y, "ffff", bedBolts=[d2, d3, d2, d3], move="up", label="bottom") if self.top_edge in "fF": self.set_source_color(Color.MAGENTA) # I don't know why this part has a different color, but RED is not a good choice because RED is used for annotations self.rectangularWall(x+4*t, y+4*t, callback=[ lambda:self.top_hole(x, y, self.top_edge)], move="up", label="top hole") self.set_source_color(Color.BLACK) self.drawLid(x, y, self.top_edge, [d2, d3]) self.lid(x, y, self.top_edge) self.rectangularWall(x, h, [b, sideedge, tf, sideedge], ignore_widths=[1, 6], bedBolts=[d2], move="right only", label="invisible") self.rectangularWall(y, h, [b, "f", tl, "f"], ignore_widths=[1, 6], bedBolts=[d3], move="up", label="left") self.rectangularWall(y, h, [b, "f", tr, "f"], ignore_widths=[1, 6], bedBolts=[d3], move="up", label="right")
4,273
Python
.py
87
37.275862
172
0.555769
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,598
shadowbox.py
florianfesti_boxes/boxes/generators/shadowbox.py
# Copyright (C) 2024 Oliver Jensen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from boxes import * class Shadowbox(Boxes): """The frame and spacers necessary to display a shadowbox / lightbox.""" description = """ The frame needed to build a shadowbox from paper cutouts. The cutout used in the photographs can be downloaded [here](https://3axis.co/laser-cut-my-neighbor-totoro-3d-lightbox-lamp-cdr-file/eoxldrxo/). See the diagram below for dimensions. ![diagram](static/samples/Shadowbox-diagram.jpg) ![backlit](static/samples/Shadowbox-backlit.jpg) """ ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.DoveTailSettings, angle=10, depth=1.5, radius=0.1, size=1) self.buildArgParser(x=200, y=260) self.argparser.add_argument( "--layers", action="store", type=int, default=7, help="the number of paper layers; don't forget the back (blank) layer!") self.argparser.add_argument( "--framewidth", action="store", type=float, default=10, help="the width of the paper layer frames") self.argparser.add_argument( "--frameheight", action="store", type=float, default=10, help="the height of the paper layer frames") self.argparser.add_argument( "--extraheight", action="store", type=float, default=20, help="cumulative height of your paper layers, play between frames, the LED strip, battery/wiring, anything else you want to fit in the case") self.argparser.add_argument( "--casejoinery", action="store", type=boolarg, default=True, help="whether or not to join sides to front plate (disable if doing manual joins on fancy wood)") def render(self): x, y = self.x, self.y t = self.thickness extraheight = self.extraheight frameheight = self.frameheight framewidth = self.framewidth casejoinery = self.casejoinery layers = self.layers height = layers * t + extraheight # inner frames horizontal bars for _ in range(2*layers): self.polygonWall([ x, 90, frameheight, 90, framewidth, 0, x - framewidth*2, 0, framewidth, 90, frameheight, 90], "eeDeDe", move="up") # inner frames vertical bars for _ in range(2*layers): self.rectangularWall(y - frameheight*2, framewidth, "eded", move="up") # faceplate hypotenuse = math.sqrt((frameheight+t)**2 + (framewidth+t)**2) angle = math.degrees(math.acos((framewidth+t) / hypotenuse)) edgetypes = 'eFeeee' if casejoinery else 'eeeeee' vframe_poly = [ t, 0, y, 0, t, 90+angle, hypotenuse, 90-angle, y - frameheight*2, 90-angle, hypotenuse, 90+angle] hframe_poly = [ t, 0, x, 0, t, 180-angle, hypotenuse, angle, x - framewidth*2, angle, hypotenuse, 180-angle] self.polygonWall(vframe_poly, edgetypes, move="up") self.polygonWall(vframe_poly, edgetypes, move="up") self.polygonWall(hframe_poly, edgetypes, move="up") self.polygonWall(hframe_poly, edgetypes, move="up") # case sides if casejoinery: top_edge = 'f' else: top_edge = 'e' self.rectangularWall(x, height, f"ef{top_edge}f", move="up") self.rectangularWall(x, height, f"ef{top_edge}f", move="up") self.rectangularWall(y, height, f"eF{top_edge}F", move="up") self.rectangularWall(y, height, f"eF{top_edge}F", move="up") # led strip holder self.rectangularWall(x - 2*t, 10, "efef", move="up") self.rectangularWall(x - 2*t, 10, "efef", move="up") self.rectangularWall(y - 2*t, 10, "eFeF", move="up") self.rectangularWall(y - 2*t, 10, "eFeF", move="up")
4,666
Python
.py
97
39.618557
153
0.635245
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)
25,599
ottobody.py
florianfesti_boxes/boxes/generators/ottobody.py
# Copyright (C) 2013-2014 Florian Festi # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. try: from gettext import gettext as _ except ImportError: def _(message: str) -> str: return message from boxes import * class OttoBody(Boxes): """Otto LC - a laser cut chassis for Otto DIY - body""" ui_group = "Misc" def __init__(self) -> None: Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings) self.addSettingsArgs(edges.ChestHingeSettings) def bottomCB(self): self.hole(6, self.y/2, 6) self.hole(6, self.y/2-6, 3) self.hole(self.x-6, self.y/2, 6) self.hole(self.x-6, self.y/2-6, 3) #self.rectangularHole(20, self.y/2, 4, 30, 1.5) #self.rectangularHole(self.x-20, self.y/2, 4, 30, 1.5) self.rectangularHole(self.x/2, self.y/2, 10, 5, 1.5) # switch self.rectangularHole(self.x-7, self.y-2.8, 7, 4) self.moveTo(0, self.y-12) self.hexHolesCircle(12, HexHolesSettings( self, diameter=2, distance=2, style='circle')) def leftBottomCB(self): self.hole(7, self.y-7, 6) self.hole(6, self.y/2+9, 0.9) self.rectangularHole(6, self.y/2-5.5, 12, 23) self.hole(6, self.y/2-20, 0.9) def rightBottomCB(self): self.hole(7, self.y-5, 2) self.hole(8, self.y/2+9, 0.9) self.rectangularHole(8, self.y/2-5.5, 12, 23) self.hole(8, self.y/2-20, 0.9) def eyeCB(self): self.hole(self.x/2+13,self.hl/2, 8) self.hole(self.x/2-13,self.hl/2, 8) def frontCB(self): t = self.thickness self.rectangularHole(0.5*t, 2+t, t, 2.5) self.rectangularHole(self.x-0.5*t, 2+t, t, 2.5) def IOCB(self): self.rectangularHole(26, 18, 12, 10) # self.rectangularHole(42.2, 10.2, 9.5, 11.5) def buttonCB(self): px, py = 7.5, 7.5 self.rectangularHole(px, py-2.25, 5.2, 2.5) self.rectangularHole(px, py+2.25, 5.2, 2.5) def PCB_Clip(self, x , y, move=None): if self.move(x+4, y, move, True): return self.moveTo(1.5) self.polyline(x-1.5, 90, (y, 2), 90, x, 85, (y-2-4, 2), -30, 2, 120, 1, -90, 2, (180, 1.), y-7, -175, y-5) self.move(x+4, y, move) def PCB_Clamp(self, w, s, h, move=None): t = self. thickness f = 2**0.5 if self.move(w+4, h+8+t, move, True): return self.polyline(w, 90, s, -90, 1, (90, 1), (h-s-1, 2), 90, w-2, 90, h-8, (-180, 1), h-8+3*t, 135, f*(4), 90, f*2, -45, (h+t, 2)) self.move(w+4, h+8+t, move) def render(self): self.x = x = 60. self.y = y = 60. self.h = h = 35. self.hl = hl = 30. t = self.thickness hx = self.edges["O"].startwidth() hx2 = self.edges["P"].startwidth() e1 = edges.CompoundEdge(self, "Fe", (h-hx, hx)) e2 = edges.CompoundEdge(self, "eF", (hx, h-hx)) e_back = ("F", e1, "e", e2) # sides self.moveTo(hx) self.rectangularWall(x, h-hx, "FfOf", ignore_widths=[2], move="up", label=_("Left bottom side")) self.rectangularWall(x, hl-hx2, "pfFf", ignore_widths=[1], move="up", label=_("Left top side")) self.moveTo(-hx) self.rectangularWall(x, h-hx, "Ffof", ignore_widths=[5], callback=[ lambda: self.rectangularHole(y-7.5, h-4-7.5, 6.2, 7.)], move="up", label=_("Right bottom side")) self.rectangularWall(x, hl-hx2, "PfFf", ignore_widths=[6], callback=[None, None, self.IOCB], move="up", label=_("Right top side")) # lower walls self.rectangularWall(y, h, "FFeF", callback=[ None, None, self.frontCB], move="up", label=_("Lower front")) self.rectangularWall(y, h, e_back, move="up", label=_("Lower back")) # upper walls self.rectangularWall(y, hl, "FFeF", callback=[self.eyeCB], move="up", label=_("Upper front")) self.rectangularWall(y, hl-hx2, "FFqF", move="up", label=_("Upper back")) # top self.rectangularWall(x, y, "ffff", move="up", label=_("Top")) # bottom self.rectangularWall(x, y, "ffff", callback=[self.bottomCB], move="up", label=_("Bottom")) # PCB mounts with self.saved_context(): self.PCB_Clamp(y-53.5, 4.5, hl, move="right") self.PCB_Clamp(y-50, 4.5, hl, move="right") self.PCB_Clip(3.5, hl, move="right") self.rectangularWall(15, 15, callback=[self.buttonCB]) self.PCB_Clamp(y-53.5, 4.5, hl, move="up only") # servo mounts self.moveTo(0, 50) self.rectangularWall(y, 14, callback=[None, None, None, self.leftBottomCB], move="up", label=_("Servo mount")) self.rectangularWall(y-5.6, 14, callback=[ None, None, None, self.rightBottomCB], move="up", label=_("Servo mount"))
5,751
Python
.py
129
35.333333
114
0.563708
florianfesti/boxes
970
351
40
GPL-3.0
9/5/2024, 5:13:34 PM (Europe/Amsterdam)