Skip to content

Commit 74caa68

Browse files
committed
greedy scad interface
1 parent fa7dc9f commit 74caa68

7 files changed

Lines changed: 214 additions & 1 deletion

File tree

‎solid/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# from solid import *
33
# from solid.utils import *
44
from .solidpython import scad_render, scad_render_to_file
5+
from .greedy_scad_interface import *
56
from .solidpython import scad_render_animated, scad_render_animated_file
67
from .solidpython import OpenSCADObject, IncludedOpenSCADObject
78
from .objects import *
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# ======================================================
2+
# = add relative path to the solid package to sys.path =
3+
# ======================================================
4+
import sys
5+
from pathlib import Path
6+
solidPath = Path(__file__).absolute().parent.parent.parent.as_posix()
7+
sys.path.insert(0, solidPath)
8+
#======================================================
9+
from solid import *
10+
11+
set_global_fn(32)
12+
set_global_viewport_distance(abs(sin(get_animation_time() * 360)) * 10 + 5)
13+
set_global_viewport_translation([0, -1, 0])
14+
set_global_viewport_rotation([63, 0, get_animation_time() * 360])
15+
set_global_viewport_fov(25)
16+
17+
def funny_cube():
18+
customized_color = CustomizerDropdownVariable(name = "cube_color",
19+
default_value = "blue",
20+
options = ["red", "green", "blue"],
21+
label = "The color of the cube",
22+
tab="Colors")
23+
24+
customized_animation_factor = CustomizerSliderVariable(name = "anim_factor",
25+
default_value = 1,
26+
min_ = 1,
27+
max_ = 10,
28+
step = 0.5,
29+
label = "Animation speed factor",
30+
tab = "Animation")
31+
32+
return color(customized_color) (
33+
cube(abs(sin(get_animation_time() * 360 * customized_animation_factor)), center=True)
34+
)
35+
36+
def funny_sphere():
37+
customized_color = ScadValue("cube_color")
38+
customized_animation_factor = ScadValue("anim_factor")
39+
40+
return translate([0, -2, 0]) (
41+
color(customized_color) (
42+
sphere(r = abs(sin(get_animation_time() * 360 * customized_animation_factor - 90)))
43+
)
44+
)
45+
46+
def do_nots():
47+
customized_color = ScadValue("cube_color")
48+
customized_animation_factor = ScadValue("anim_factor")
49+
50+
#if customized_color == "blue":
51+
# print("This causes a python runtime error!")
52+
53+
#for i in range(customized_animation_factor):
54+
# print("This causes a python runtime error!")
55+
56+
#f = 1.0
57+
#f *= customized_animation_factor
58+
#for i in range(f):
59+
# print("This causes a python runtime error! (and this is why it is called greedy)")
60+
61+
scad_render_to_file(funny_cube() + funny_sphere())
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .customizer_widgets import *
2+
from .scad_variable import *
3+
from .scad_interface import *
4+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from .scad_variable import ScadVariable
2+
3+
class CustomizerDropdownVariable(ScadVariable):
4+
def __init__(self, name, default_value, options='', label='', tab=''):
5+
if isinstance(options, list):
6+
options_str = '[' + ", ".join(map(str, options)) + ']'
7+
8+
if isinstance(options, dict):
9+
reverse_options = [ f"{options[k]} : {k}" for k in options.keys()]
10+
options_str = f'[{", ".join(reverse_options)}]'
11+
12+
super().__init__(name, default_value, options_str, label=label, tab=tab)
13+
14+
class CustomizerSliderVariable(ScadVariable):
15+
def __init__(self, name, default_value, min_, max_, step='', label='', tab=''):
16+
options_str = '['
17+
options_str += min_ and str(min_) + ':'
18+
options_str += step and str(step) + ':'
19+
options_str += str(max_) + ']'
20+
21+
super().__init__(name, default_value, options_str, label=label, tab=tab)
22+
23+
class CustomizerCheckboxVariable(ScadVariable):
24+
def __init__(self, name, default_value, label='', tab=''):
25+
super().__init__(name, default_value, label=label, tab=tab)
26+
27+
class CustomizerTextboxVariable(ScadVariable):
28+
def __init__(self, name, default_value, max_length='', label='', tab=''):
29+
options_str = max_length and str(max_length)
30+
super().__init__(name, f'"{default_value}"', options_str, label=label, tab=tab)
31+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from .scad_variable import ScadVariable, ScadValue
2+
3+
def get_animation_time():
4+
return ScadValue("$t")
5+
6+
def set_global_fn(_fn):
7+
ScadVariable("$fn", _fn)
8+
9+
def set_global_fa(_fa):
10+
ScadVariable("$fa", _fa)
11+
12+
def set_global_fs(_fs):
13+
ScadVariable("$fs", _fs)
14+
15+
def set_global_viewport_translation(trans):
16+
ScadVariable("$vpt", trans)
17+
18+
def set_global_viewport_rotation(rot):
19+
ScadVariable("$vpr", rot)
20+
21+
def set_global_viewport_fov(fov):
22+
ScadVariable("$vpf", fov)
23+
24+
def set_global_viewport_distance(d):
25+
ScadVariable("$vpd", d)
26+
27+
def get_scad_header():
28+
base_str = "\n\n".join(ScadVariable.registered_variables.values())
29+
return f'//=== custmizer variables start ===\n{base_str}\n//=== customizer variables end===\n'
30+
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import math
2+
3+
sin = lambda x: ScadValue(f'sin({x})') if isinstance(x, ScadValue) else math.sin(x)
4+
cos = lambda x: ScadValue(f'cos({x})') if isinstance(x, ScadValue) else math.cos(x)
5+
tan = lambda x: ScadValue(f'tan({x})') if isinstance(x, ScadValue) else math.tan(x)
6+
asin = lambda x: ScadValue(f'asin({x})') if isinstance(x, ScadValue) else math.asin(x)
7+
acos = lambda x: ScadValue(f'acos({x})') if isinstance(x, ScadValue) else math.acos(x)
8+
atan = lambda x: ScadValue(f'atan({x})') if isinstance(x, ScadValue) else math.atan(x)
9+
sqrt = lambda x: ScadValue(f'sqrt({x})') if isinstance(x, ScadValue) else math.sqrt(x)
10+
not_ = lambda x: ScadValue(f'!{x}')
11+
12+
class ScadValue:
13+
def __init__(self, value):
14+
self.value = value
15+
16+
def __repr__(self):
17+
return f'{self.value}'
18+
19+
def __operator_base__(self, op, other):
20+
return ScadValue(f'({self} {op} {other})')
21+
22+
def __unary_operator_base__(self, op):
23+
return ScadValue(f'({op}{self})')
24+
25+
#basic operators +, -, *, /, %, **
26+
def __add__(self, other): return self.__operator_base__("+", other)
27+
def __sub__(self, other): return self.__operator_base__("-", other)
28+
def __mul__(self, other): return self.__operator_base__("*", other)
29+
def __mod__(self, other): return self.__operator_base__("%", other)
30+
def __pow__(self, other): return self.__operator_base__("^", other)
31+
def __truediv__(self, other): return self.__operator_base__("/", other)
32+
33+
def __radd__(self, other): return self.__operator_base__("+", other)
34+
def __rsub__(self, other): return self.__operator_base__("-", other)
35+
def __rmul__(self, other): return self.__operator_base__("*", other)
36+
def __rmod__(self, other): return self.__operator_base__("%", other)
37+
def __rpow__(self, other): return self.__operator_base__("^", other)
38+
def __rtruediv__(self, other): return self.__operator_base__("/", other)
39+
40+
#unary operators
41+
def __neg__(self): return self.__unary_operator_base__("-")
42+
43+
#other operators
44+
def __abs__(self): return ScadValue(f'abs({self})')
45+
46+
def __bool__(self):
47+
raise Exception("You can't use scad variables as truth statement because " +\
48+
"we don't know the value of a customized variable at SolidPython " +\
49+
"runtime.")
50+
51+
def __illegal_operator__(self):
52+
raise Exception("You can't compare a ScadValue with something else, " +\
53+
"because we don't know the customized value at SolidPythons runtime " +\
54+
"because it might get customized at OpenSCAD runtime.")
55+
56+
def __eq__(self, other): return self.__illegal_operator__()
57+
def __ne__(self, other): return self.__illegal_operator__()
58+
def __le__(self, other): return self.__illegal_operator__()
59+
def __ge__(self, other): return self.__illegal_operator__()
60+
def __lt__(self, other): return self.__illegal_operator__()
61+
def __gt__(self, other): return self.__illegal_operator__()
62+
63+
class ScadVariable(ScadValue):
64+
registered_variables = {}
65+
66+
def __init__(self, name, default_value, options_str='', label='', tab=''):
67+
super().__init__(name)
68+
69+
if name in self.registered_variables.keys():
70+
raise ValueError("Multiple instances of ScadVariable with the same name.")
71+
72+
def_str = self.get_definition(name, default_value, options_str, label, tab)
73+
self.registered_variables.update({name : def_str})
74+
75+
def get_definition(self, name, default_value, options_str, label, tab):
76+
tab = tab and f'/* [{tab}] */\n'
77+
label = label and f'//{label}\n'
78+
options_str = options_str and f' //{options_str}'
79+
80+
if isinstance(default_value, str):
81+
default_value = f'"{default_value}"'
82+
83+
return f'{tab}{label}{name} = {default_value};{options_str}'
84+

‎solid/solidpython.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import pkg_resources
2727
import re
2828

29+
from . import greedy_scad_interface
30+
2931
PathStr = Union[Path, str]
3032
AnimFunc = Callable[[Optional[float]], 'OpenSCADObject']
3133
# These are features added to SolidPython but NOT in OpenSCAD.
@@ -427,7 +429,7 @@ def scad_render(scad_object: OpenSCADObject, file_header: str = '') -> str:
427429
if file_header and not file_header.endswith('\n'):
428430
file_header += '\n'
429431

430-
return file_header + includes + scad_body
432+
return file_header + greedy_scad_interface.get_scad_header() + includes + scad_body
431433

432434
def scad_render_animated(func_to_animate: AnimFunc,
433435
steps: int =20,

0 commit comments

Comments
 (0)