コード例 #1
0
ファイル: cq_cmd.py プロジェクト: adam-urbanczyk/cadquery
def run(args):

    info("Reading from file '%s'" % args.in_spec)
    input_script = read_input_script(args.in_spec)
    script_name = 'stdin' if args.in_spec is None else args.in_spec
    cq_model = cqgi.parse(input_script)
    info("Parsed Script '%s'." % script_name)

    param_handler = ParameterHandler()
    param_handler.apply_file(args.param_file)
    param_handler.apply_string(args.params)
    user_params = param_handler.get()
    describe_parameters(user_params,cq_model.metadata.parameters)

    check_input_format(args.format)

    build_result = cq_model.build(build_parameters=user_params)

    info("Output Format is '%s'. Use --output-format to change it." % args.format)
    info("Output Path is '%s'. Use --out_spec to change it." % args.out_spec)

    if build_result.success:
        result_list = build_result.results
        info("Script Generated %d result Objects" % len(result_list))
        shape_writer = create_shape_writer(args.out_spec,args.format)
        shape_writer.write_shapes(result_list)
    else:
        error("Script Error: '%s'" % build_result.exception,ErrorCodes.SCRIPT_ERROR)
コード例 #2
0
def handle(req):
    """handle a request to the function
    Args:
        req (str): request body
    """
    import io
    import sys
    from cadquery import cqgi
    from cadquery.occ_impl.exporters.json import JsonMesh

    # stdout redirect trap
    text_trap = io.StringIO()
    sys.stderr = text_trap

    mesher = JsonMesh()

    # Parse and build using the text
    cqModel = cqgi.parse(req)
    build_result = cqModel.build({})

    if build_result.success:
        # Display all the results that the caller
        for result in build_result.results:
            tess = result.shape.val().tessellate(0.001)

            # Add vertices
            for v in tess[0]:
                mesher.addVertex(v.x, v.y, v.z)

            # Add triangles
            for ixs in tess[1]:
                mesher.addTriangleFace(*ixs)

    return mesher.toJson()
コード例 #3
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there is no script to check, ignore this command
        if cqCodePane is None:
            FreeCAD.Console.PrintMessage("There is no script to validate.")
            return

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        if (b"show_object(" not in scriptText) and  (b"debug(" not in scriptText):
            FreeCAD.Console.PrintError("Script did not call show_object or debug, no output available. Script must be CQGI compliant to get build output, variable editing and validation.\r\n")
            return

        # A repreentation of the CQ script with all the metadata attached
        cqModel = cqgi.parse(scriptText)

        # Allows us to present parameters to users later that they can alter
        parameters = cqModel.metadata.parameters

        Shared.populateParameterEditor(parameters)
コード例 #4
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there is no script to check, ignore this command
        if cqCodePane is None:
            FreeCAD.Console.PrintMessage("There is no script to validate.")
            return

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        if ("show_object(" not in scriptText and "# show_object(" in scriptText and "#show_boject(" in scriptText) or ("debug(" not in scriptText and "# debug(" in scriptText and "#debug(" in scriptText):
            FreeCAD.Console.PrintError("Script did not call show_object or debug, no output available. Script must be CQGI compliant to get build output, variable editing and validation.\r\n")
            return

        # A repreentation of the CQ script with all the metadata attached
        cqModel = cqgi.parse(scriptText)

        # Allows us to present parameters to users later that they can alter
        parameters = cqModel.metadata.parameters

        Shared.populateParameterEditor(parameters)
コード例 #5
0
 def test_that_assinging_number_to_string_works(self):
     script = textwrap.dedent("""
             h = "this is a string"
             show_object(h)
         """)
     result = cqgi.parse(script).build({"h": 33.33})
     self.assertEqual(result.results[0].shape, "33.33")
コード例 #6
0
ファイル: cq_cmd.py プロジェクト: zignig/cadquery
def run(args):

    info("Reading from file '%s'" % args.in_spec)
    input_script = read_input_script(args.in_spec)
    script_name = 'stdin' if args.in_spec is None else args.in_spec
    cq_model = cqgi.parse(input_script)
    info("Parsed Script '%s'." % script_name)

    param_handler = ParameterHandler()
    param_handler.apply_file(args.param_file)
    param_handler.apply_string(args.params)
    user_params = param_handler.get()
    describe_parameters(user_params, cq_model.metadata.parameters)

    check_input_format(args.format)

    build_result = cq_model.build(build_parameters=user_params)

    info("Output Format is '%s'. Use --output-format to change it." %
         args.format)
    info("Output Path is '%s'. Use --out_spec to change it." % args.out_spec)

    if build_result.success:
        result_list = build_result.results
        info("Script Generated %d result Objects" % len(result_list))
        shape_writer = create_shape_writer(args.out_spec, args.format)
        shape_writer.write_shapes(result_list)
    else:
        error("Script Error: '%s'" % build_result.exception,
              ErrorCodes.SCRIPT_ERROR)
コード例 #7
0
ファイル: cq-cli.py プロジェクト: jmwright/cq-cli
def build_and_parse(script_str, params, errfile):
    """
    Uses CQGI to parse and build a script, substituting in parameters if any were supplied.
    """
    # We need to do a broad try/catch to let the user know if something higher-level fails
    try:
        # Do the CQGI handling of the script here and, if successful, pass the build result to the codec
        cqModel = cqgi.parse(script_str)
        build_result = cqModel.build(params)

        # Handle the case of the build not being successful, otherwise pass the codec the build result
        if not build_result.success:
            # Re-throw the exception so that it will be caught and formatted correctly
            raise (build_result.exception)
        else:
            return build_result
    except Exception:
        out_tb = traceback.format_exc()

        # If there was an error file specified write to that, otherwise send it to stderr
        if errfile != None:
            with open(errfile, 'w') as file:
                file.write(str(out_tb))
        else:
            print(str(out_tb), file=sys.stderr)

    # Return None here to prevent a failed build from slipping through
    return None
コード例 #8
0
 def test_that_not_calling_build_object_raises_error(self):
     script = textwrap.dedent(
         """
             h = 20.0
         """
     )
     result = cqgi.parse(script).build()
     self.assertTrue(isinstance(result.exception, cqgi.NoOutputError))
コード例 #9
0
 def test_that_not_calling_build_object_raises_error(self):
     script = textwrap.dedent(
         """
             h = 20.0
         """
     )
     result = cqgi.parse(script).build()
     self.assertTrue(isinstance(result.exception, cqgi.NoOutputError))
コード例 #10
0
 def test_that_assigning_string_to_number_fails(self):
     script = textwrap.dedent("""
             h = 20.0
             show_object(h)
         """)
     result = cqgi.parse(script).build({"h": "a string"})
     self.assertTrue(
         isinstance(result.exception, cqgi.InvalidParameterError))
コード例 #11
0
 def test_that_assinging_number_to_string_works(self):
     script = textwrap.dedent(
         """
             h = "this is a string"
             build_object(h)
         """
     )
     result = cqgi.parse(script).build( {'h': 33.33})
     self.assertEquals(result.results[0], "33.33")
コード例 #12
0
    def test_that_assigning_unknown_var_fails(self):
        script = textwrap.dedent("""
                h = 20.0
                show_object(h)
            """)

        result = cqgi.parse(script).build({"w": "var is not there"})
        self.assertTrue(
            isinstance(result.exception, cqgi.InvalidParameterError))
コード例 #13
0
    def test_that_options_can_be_passed(self):
        script = textwrap.dedent("""
                r = cadquery.Workplane('XY').box(1,2,3)
                show_object(r, options={"rgba":(128, 255, 128, 0.0)})
            """)

        result = cqgi.parse(script).build()
        self.assertTrue(result.success)
        self.assertIsNotNone(result.first_result.options)
コード例 #14
0
    def test_that_cq_objects_are_visible(self):
        script = textwrap.dedent("""
                r = cadquery.Workplane('XY').box(1,2,3)
                show_object(r)
            """)

        result = cqgi.parse(script).build()
        self.assertTrue(result.success)
        self.assertIsNotNone(result.first_result)
コード例 #15
0
 def test_that_assigning_string_to_number_fails(self):
     script = textwrap.dedent(
         """
             h = 20.0
             build_object(h)
         """
     )
     result = cqgi.parse(script).build( {'h': "a string"})
     self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError))
コード例 #16
0
    def test_that_assigning_unknown_var_fails(self):
        script = textwrap.dedent(
            """
                h = 20.0
                build_object(h)
            """
        )

        result = cqgi.parse(script).build( {'w': "var is not there"})
        self.assertTrue(isinstance(result.exception, cqgi.InvalidParameterError))
コード例 #17
0
    def test_setting_boolean_variable(self):
        script = textwrap.dedent("""
                h = True
                show_object( "*%s*" % str(h)  )
            """)

        result = cqgi.parse(script).build({"h": False})

        self.assertTrue(result.success)
        self.assertEqual(result.first_result.shape, "*False*")
コード例 #18
0
def convscript(user_script):
    parsed_script = cqgi.parse(user_script)
    build_result = parsed_script.build(build_parameters={}, build_options={})
    if build_result.results:
        b = build_result.results[0]
        s = io.StringIO()
        exporters.exportShape(b.shape, "STL", s, 0.01)
        res = s.getvalue()
    else:
        res = str(build_result.exception)
    return res
コード例 #19
0
    def test_that_cq_objects_are_visible(self):
        script = textwrap.dedent(
            """
                r = cadquery.Workplane('XY').box(1,2,3)
                build_object(r)
            """
        )

        result = cqgi.parse(script).build()
        self.assertTrue(result.success)
        self.assertIsNotNone(result.first_result)
コード例 #20
0
def cq_directive(
    name,
    arguments,
    options,
    content,
    lineno,
    content_offset,
    block_text,
    state,
    state_machine,
):
    # only consider inline snippets
    plot_code = "\n".join(content)

    # Since we don't have a filename, use a hash based on the content
    # the script must define a variable called 'out', which is expected to
    # be a CQ object
    out_svg = "Your Script Did not assign call build_output() function!"

    try:
        _s = io.StringIO()
        result = cqgi.parse(plot_code).build()

        if result.success:
            exporters.exportShape(result.first_result.shape, "SVG", _s)
            out_svg = _s.getvalue()
        else:
            raise result.exception

    except Exception:
        traceback.print_exc()
        out_svg = traceback.format_exc()

    # now out
    # Now start generating the lines of output
    lines = []

    # get rid of new lines
    out_svg = out_svg.replace("\n", "")

    txt_align = "left"
    if "align" in options:
        txt_align = options["align"]

    lines.extend((template % locals()).split("\n"))

    lines.extend(["::", ""])
    lines.extend(["    %s" % row.rstrip() for row in plot_code.split("\n")])
    lines.append("")

    if len(lines):
        state_machine.insert_input(lines, state_machine.input_lines.source(0))

    return []
コード例 #21
0
ファイル: TestCQGI.py プロジェクト: justbuchanan/cadquery
    def test_setting_boolean_variable(self):
        script = textwrap.dedent("""
                h = True
                build_object( "*%s*" % str(h)  )
            """)

        #result = cqgi.execute(script)
        result = cqgi.parse(script).build({'h': False})

        self.assertTrue(result.success)
        self.assertEqual(result.first_result, '*False*')
コード例 #22
0
    def test_setting_boolean_variable(self):
        script = textwrap.dedent(
            """
                h = True
                build_object( "*%s*" % str(h)  )
            """
        )

        #result = cqgi.execute(script)
        result = cqgi.parse(script).build({'h': False})

        self.assertTrue(result.success)
        self.assertEquals(result.first_result,'*False*')
コード例 #23
0
ファイル: cq_directive.py プロジェクト: luzpaz/cadquery
    def run(self):

        options = self.options
        content = self.content
        state_machine = self.state_machine

        # only consider inline snippets
        plot_code = "\n".join(content)

        # Since we don't have a filename, use a hash based on the content
        # the script must define a variable called 'out', which is expected to
        # be a CQ object
        out_svg = "Your Script Did not assign call build_output() function!"

        try:
            result = cqgi.parse(plot_code).build()

            if result.success:
                out_svg = exporters.getSVG(
                    exporters.toCompound(result.first_result.shape))
            else:
                raise result.exception

        except Exception:
            traceback.print_exc()
            out_svg = traceback.format_exc()

        # now out
        # Now start generating the lines of output
        lines = []

        # get rid of new lines
        out_svg = out_svg.replace("\n", "")

        txt_align = "left"
        if "align" in options:
            txt_align = options["align"]

        lines.extend((template % locals()).split("\n"))

        lines.extend(["::", ""])
        lines.extend(
            ["    %s" % row.rstrip() for row in plot_code.split("\n")])
        lines.append("")

        if len(lines):
            state_machine.insert_input(lines,
                                       state_machine.input_lines.source(0))

        return []
コード例 #24
0
    def test_that_only_top_level_vars_are_detected(self):
        script = textwrap.dedent("""
                h = 1.0
                w = 2.0

                def do_stuff():
                   x = 1
                   y = 2

                show_object( "result"  )
            """)

        model = cqgi.parse(script)

        self.assertEqual(2, len(model.metadata.parameters))
コード例 #25
0
def test_example(code):

    # build
    res = cqgi.parse(code).build()

    assert res.exception is None

    # check if the resulting objects are valid
    for r in res.results:
        r = r.shape
        if isinstance(r, cq.Workplane):
            for v in r.vals():
                if isinstance(v, cq.Shape):
                    assert v.isValid()
        elif isinstance(r, cq.Shape):
            assert r.isValid()
コード例 #26
0
def cq_directive(name, arguments, options, content, lineno,
                 content_offset, block_text, state, state_machine):
    # only consider inline snippets
    plot_code = '\n'.join(content)

    # Since we don't have a filename, use a hash based on the content
    # the script must define a variable called 'out', which is expected to
    # be a CQ object
    out_svg = "Your Script Did not assign call build_output() function!"

    try:
        _s = StringIO.StringIO()
        result = cqgi.parse(plot_code).build()

        if result.success:
            exporters.exportShape(result.first_result, "SVG", _s)
            out_svg = _s.getvalue()
        else:
            raise result.exception

    except Exception:
        traceback.print_exc()
        out_svg = traceback.format_exc()

    # now out
    # Now start generating the lines of output
    lines = []

    # get rid of new lines
    out_svg = out_svg.replace('\n', '')

    txt_align = "left"
    if "align" in options:
        txt_align = options['align']

    lines.extend((template % locals()).split('\n'))

    lines.extend(['::', ''])
    lines.extend(['    %s' % row.rstrip()
                  for row in plot_code.split('\n')])
    lines.append('')

    if len(lines):
        state_machine.insert_input(
            lines, state_machine.input_lines.source(0))

    return []
コード例 #27
0
    def test_that_only_top_level_vars_are_detected(self):
        script = textwrap.dedent(
            """
                h = 1.0
                w = 2.0

                def do_stuff():
                   x = 1
                   y = 2

                build_object( "result"  )
            """
        )

        model = cqgi.parse(script)

        self.assertEquals(2, len(model.metadata.parameters))
コード例 #28
0
# appending <current directory>/lib/ to python system path
#   This allows for importing local files outside of current WD
# sys.path.append(os.getcwd() + "/lib/");

# Load CQGI
import cadquery.cqgi as cqgi
import cadquery as cq

model = cqgi.parse(open("88_assembly/casing.py").read())
build_result = model.build()
if build_result.success:
    count = 0
    for result in build_result.results:
        with open('88_assembly/output/casing' + str(count) + '.stl', 'w') as f:
            f.write(cq.exporters.toString(result.shape, 'STL', 10))
        f.close()
        count = count + 1
else:
    print("BUILD FAILED: " + str(build_result.exception) + "\n")
コード例 #29
0
def show_object(result):
    'returns an object to the Jupyter Widgets area with interactive options'
    # Get the Script's text from the IPython shell's history
    # TODO: sanitizing function that removes dangerous imports.
    # Eg. strip any lines that have 'import cqjupyter'
    # luckily, the cell which has just been run by user
    # is immediately placed as the latest entry in the history
    script_text = get_ipython().history_manager.input_hist_raw[-1]

    def find_between(src, first, last):
        'returns string between two specified substrings'
        # credit: https://stackoverflow.com/a/3368991
        try:
            start = src.index(first) + len(first)
            end = src.index(last, start)
            return src[start:end]
        except ValueError:
            return ""

    obj_name = find_between(script_text, 'show_object(', ')')

    # A representation of the CQ script with all the metadata attached
    # stop parse func from printing to the shell to avoid excessive warnings
    # TODO: fix this the real way... find out proper way to handle this from CQGI author
    block_print()
    # change show_object() to build_object until I have opportunity to update CQ...
    # script_text = script_text.replace('show_object(', 'build_object(')
    cq_model = cqgi.parse(script_text)
    # re-enable printing to shell
    enable_print()

    build_result = cq_model.build()

    # function that creates and updates the model view along with param. interactions
    # kwargs is built up in a loop over the parameters which CQGI supplies
    def mkui(**kwargs):
        'assembles widgets area according to parameters found in parsed script'
        new_vals = {}
        # kwargs is linked to ipywidget interactive vals
        # set the kwarg's name as key, set kwarg's value as value.
        # pass new vals as dict into update_build so that CQGI processes the model with
        # the values that the user has input into the interactive boxes
        for arg in kwargs:
            new_vals[arg] = kwargs[arg]
        try:
            mkui.base.close()
            mkui.export_filename.close()
            mkui.export_filetype.close()
            mkui.export_button.close()
        except AttributeError:
            pass
        color = mkui.display_options['display_color'].value
        units = mkui.display_options['display_units'].value
        scale = mkui.display_options['display_scale'].value

        if units == 'in':
            final_scale = scale*25.4
        else:
            final_scale = scale

        mkui.base, mkui.new_model = update_build(cq_model, new_vals, color=color, scale=final_scale)

        # Create the Export options + Button
        mkui.export_filename = ipywidgets.Text(
            description='Filename',
            value=obj_name,
            continuous_update=False
            )
        mkui.export_filetype = ipywidgets.Dropdown(
            description='Filetype',
            options=['STEP', 'JSON', 'STL', 'SVG'],
            value='STEP',
            continuous_update=False
            )

        def export_function(button):
            'executes export of user selected filetype, only on button press'
            filename = mkui.export_filename.value
            filetype = mkui.export_filetype.value
            fullname = filename + '.' + filetype
            if filetype == 'STEP':
                mkui.new_model.shape.findSolid().scale(final_scale).exportStep(fullname)
            if filetype == 'STL':
                mkui.new_model.shape.findSolid().scale(final_scale).wrapped.exportStl(fullname)
            elif filetype == 'JSON':
                cqgen(mkui.new_model.shape.findSolid().scale(final_scale), name=filename)
            elif filetype == 'SVG':
                cq.CQ(mkui.new_model.shape.findSolid().scale(final_scale)).exportSvg(fullname)
            else:
                print 'nothing exported, sorry'
            print 'exported model as: ' + fullname

        gui_layout = ipywidgets.Layout(
            display='flex',
            justify_content='center',
            align_items='center',
            max_width='30%',
        )
        options_layout = ipywidgets.Layout(
            max_width='50%',
        )

        mkui.export_button = ipywidgets.Button(description='Export', continuous_update=False)
        mkui.export_button.on_click(export_function)
        export_gui = ipywidgets.HBox([
            ipywidgets.VBox([mkui.export_filename, mkui.export_filetype]),
            mkui.export_button
            ])

        render_window = ipywidgets.VBox([mkui.base, export_gui])
        display(render_window)

    mkui.base = None
    mkui.export_filename = None
    mkui.export_filetype = None
    mkui.export_button = None

    # Make sure that the build was successful
    if build_result.success:
        # Allows us to present parameters for editing through some interface
        params = cq_model.metadata.parameters
        interactions, mkui.display_options = cq_interact(params)
        # Display all the results that the user requested
        # for result in build_result.results:
        # Render the solid and its parameter interactions
        # display(mkui.display_options)
        display(mkui.display_options['display_color'])
        display(mkui.display_options['display_units'])
        display(mkui.display_options['display_scale'])
        ipywidgets.interact_manual(mkui, **interactions)
        return
    else:
        print "Error executing CQGI-compliant script."
コード例 #30
0
# Load CQGI
import cadquery.cqgi as cqgi
import cadquery as cq
import sys
import os
from slicer.slice import getSliceCmd

cadfile = sys.argv[1]
cadfile_base = os.path.splitext(cadfile)[0].replace("cq_files", "target")
# load the cadquery script
model = cqgi.parse(open(cadfile).read())

# run the script and store the result (from the show_object call in the script)
build_result = model.build()

# test to ensure the process worked.
if build_result.success:
    stl = f"{cadfile_base}.stl"
    if not os.path.exists(os.path.dirname(stl)):
        try:
            os.makedirs(os.path.dirname(stl))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise
    last = len(build_result.results) - 1
    shape = build_result.results[last].shape
    cq.exporters.export(shape, stl)
    bat = open(f"{cadfile_base}.slice.bat", "w")
    bat.write(getSliceCmd(shape, stl))

else:
コード例 #31
0
ファイル: cq_directive.py プロジェクト: luzpaz/cadquery
    def run(self):

        options = self.options
        content = self.content
        state_machine = self.state_machine
        env = self.state.document.settings.env
        build_path = Path(env.app.builder.outdir)
        out_path = build_path / "_static"

        # only consider inline snippets
        plot_code = "\n".join(content)

        # collect the result
        try:
            result = cqgi.parse(plot_code).build()

            if result.success:
                if result.first_result:
                    shape = result.first_result.shape
                else:
                    shape = result.env[options.get("select", "result")]

                if isinstance(shape, Assembly):
                    assy = shape
                else:
                    assy = Assembly(shape, color=Color(*DEFAULT_COLOR))
            else:
                raise result.exception

        except Exception:
            traceback.print_exc()
            assy = Assembly(Compound.makeText("CQGI error", 10, 5))

        # save vtkjs to static
        fname = Path(str(uuid()))
        exporters.assembly.exportVTKJS(assy, out_path / fname)
        fname = str(fname) + ".zip"

        # add the output
        lines = []

        data = dumps(toJSON(assy))

        lines.extend(
            template_vtk.format(
                code=indent(TEMPLATE_RENDER.format(), "    "),
                data=data,
                ratio="null",
                element="document.currentScript.parentNode",
                txt_align=options.get("align", "left"),
                width=options.get("width", "100%"),
                height=options.get("height", "500px"),
            ).splitlines())

        lines.extend(["::", ""])
        lines.extend(
            ["    %s" % row.rstrip() for row in plot_code.split("\n")])
        lines.append("")

        if len(lines):
            state_machine.insert_input(lines,
                                       state_machine.input_lines.source(0))

        return []
コード例 #32
0
ファイル: cqtest.py プロジェクト: goatchurchprime/tunnelvr
user_script = """
base_cube = cq.Workplane('XY').rect(1.0,1.0).extrude(1.0)
top_of_cube_plane = base_cube.faces(">Z").workplane()
debug(top_of_cube_plane, { 'color': 'yellow', } )
debug(top_of_cube_plane.center, { 'color' : 'blue' } )

circle=top_of_cube_plane.circle(0.5)
debug(circle, { 'color': 'red' } )

show_object( circle.extrude(1.0) )
"""

user_script = """
result = cq.Workplane("front").box(2.0, 2.0, 0.5); show_object(result)
"""

# must fix the time.clock() call in the cqgi https://github.com/jmwright/cadquery-freecad-module/issues/147
from cadquery import cqgi, exporters
import io

parsed_script = cqgi.parse(user_script)
build_result = parsed_script.build(build_parameters={}, build_options={})
if build_result.results:
    b = build_result.results[0]
    s = io.StringIO()
    exporters.exportShape(b.shape, "STL", s, 0.01)
    res = s.getvalue()
else:
    res = str(build_result.exception)
print(res)
コード例 #33
0
import os

parser = argparse.ArgumentParser(
    description=
    "Utility to render cqparts models to gltf. Each model in a given file is rendered to a separate gltf."
)
parser.add_argument('--file',
                    required=True,
                    help="cqparts python file to render models from")
parser.add_argument('--out_dir', required=True, help="Output directory")
args = parser.parse_args()

fname = args.file

with open(fname, 'r') as f:
    build_result = cqgi.parse(f.read()).build()

print("Build results: %s" % str(build_result.results))

out_basedir = args.out_dir

for res in build_result.results:
    asm = res.shape
    clsname = asm.__class__.__name__
    outdir = os.path.join(out_basedir, clsname)
    os.mkdir(outdir)

    outfile = os.path.join(outdir, clsname + '.gltf')

    print("Writing '%s' object to '%s'" % (clsname, outfile))
コード例 #34
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        # Check to see if we are executig a CQGI compliant script
        if b"show_object(" in scriptText or b"debug(" in scriptText:
            FreeCAD.Console.PrintMessage("Executing CQGI-compliant script.\r\n")

            # A repreentation of the CQ script with all the metadata attached
            cqModel = cqgi.parse(scriptText)

            # Allows us to present parameters to users later that they can alter
            parameters = cqModel.metadata.parameters
            build_parameters = {}

            # Collect the build parameters from the Parameters Editor view, if they exist
            mw = FreeCADGui.getMainWindow()

            # Tracks whether or not we have already added the variables editor
            isPresent = False

            # If the widget is open, we need to close it
            dockWidgets = mw.findChildren(QtGui.QDockWidget)
            for widget in dockWidgets:
                if widget.objectName() == "cqVarsEditor":
                    # Toggle the visibility of the widget
                    if not widget.visibleRegion().isEmpty():
                        # Find all of the controls that will have parameter values in them
                        valueControls = mw.findChildren(QtGui.QLineEdit)
                        for valueControl in valueControls:
                            objectName = valueControl.objectName()

                            # We only want text fields that will have parameter values in them
                            if objectName != None and objectName != '' and objectName.find('pcontrol_') >= 0:
                                # Associate the value in the text field with the variable name in the script
                                build_parameters[objectName.replace('pcontrol_', '')] = valueControl.text()

            build_result = cqModel.build(build_parameters=build_parameters)

            # if Settings.report_execute_time:
            #     FreeCAD.Console.PrintMessage("Script executed in " + str(build_result.buildTime) + " seconds\r\n")

            # Make sure that the build was successful
            if build_result.success:
                # Display all the results that the user requested
                for result in build_result.results:
                    # Apply options to the show function if any were provided
                    if result.options and result.options["rgba"]:
                        show(result.shape, result.options["rgba"])
                    else:
                        show(result.shape)

                for debugObj in build_result.debugObjects:
                    # Mark this as a debug object
                    debugObj.shape.val().label = "Debug" + str(random())

                    # Apply options to the show function if any were provided
                    if debugObj.options and debugObj.options["rgba"]:
                        show(debugObj.shape, debugObj.options["rgba"])
                    else:
                        show(debugObj.shape, (255, 0, 0, 0.80))
            else:
                FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n")
        else:
            # Save our code to a tempfile and render it
            tempFile = tempfile.NamedTemporaryFile(delete=False)
            tempFile.write(scriptText)
            tempFile.close()

            # Set some environment variables that may help the user
            os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.get_path()
            os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.get_path()))

            # We import this way because using execfile() causes non-standard script execution in some situations
            with revert_sys_modules():
                imp.load_source('__cq_freecad_module__', tempFile.name)

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Executed ",
            None)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.get_path() + "\r\n")
コード例 #35
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        # Check to see if we are executig a CQGI compliant script
        if ("show_object(" in scriptText and "# show_object(" not in scriptText and "#show_boject(" not in scriptText) or ("debug(" in scriptText and "# debug(" not in scriptText and "#debug(" not in scriptText):
            FreeCAD.Console.PrintMessage("Executing CQGI-compliant script.\r\n")

            # A repreentation of the CQ script with all the metadata attached
            cqModel = cqgi.parse(scriptText)

            # Allows us to present parameters to users later that they can alter
            parameters = cqModel.metadata.parameters
            build_parameters = {}

            # Collect the build parameters from the Parameters Editor view, if they exist
            mw = FreeCADGui.getMainWindow()

            # Tracks whether or not we have already added the variables editor
            isPresent = False

            # If the widget is open, we need to close it
            dockWidgets = mw.findChildren(QtGui.QDockWidget)
            for widget in dockWidgets:
                if widget.objectName() == "cqVarsEditor":
                    # Toggle the visibility of the widget
                    if not widget.visibleRegion().isEmpty():
                        # Find all of the controls that will have parameter values in them
                        valueControls = mw.findChildren(QtGui.QLineEdit)
                        for valueControl in valueControls:
                            objectName = valueControl.objectName()

                            # We only want text fields that will have parameter values in them
                            if objectName != None and objectName != '' and objectName.find('pcontrol_') >= 0:
                                # Associate the value in the text field with the variable name in the script
                                build_parameters[objectName.replace('pcontrol_', '')] = valueControl.text()

            build_result = cqModel.build(build_parameters=build_parameters)

            if Settings.report_execute_time:
                FreeCAD.Console.PrintMessage("Script executed in " + str(build_result.buildTime) + " seconds\r\n")

            # Make sure that the build was successful
            if build_result.success:
                # Display all the results that the user requested
                for result in build_result.results:
                    # Apply options to the show function if any were provided
                    if result.options and result.options["rgba"]:
                        show(result.shape, result.options["rgba"])
                    else:
                        show(result.shape)

                for debugObj in build_result.debugObjects:
                    # Mark this as a debug object
                    debugObj.shape.val().label = "Debug" + str(random())

                    # Apply options to the show function if any were provided
                    if debugObj.options and debugObj.options["rgba"]:
                        show(debugObj.shape, debugObj.options["rgba"])
                    else:
                        show(debugObj.shape, (255, 0, 0, 0.80))
            else:
                FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n")
        else:
            # Save our code to a tempfile and render it
            tempFile = tempfile.NamedTemporaryFile(delete=False)
            tempFile.write(scriptText)
            tempFile.close()

            # Set some environment variables that may help the user
            os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.file.path
            os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path))

            # We import this way because using execfile() causes non-standard script execution in some situations
            with revert_sys_modules():
                imp.load_source('temp_module', tempFile.name)

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Executed ",
            None)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
コード例 #36
0
def main(argv):
    script_file = ''
    output_format = ''
    parameters = ''
    output_file_name = ''

    # Make sure that everything is good with our arguments
    try:
        opts, args = getopt.getopt(
            argv, "hrf:o:p:",
            ["help", "file=", "outputFormat=", "parameters="])
    except getopt.GetoptError as e:
        # print (str(e))
        print("Improper command line arguments supplied.")
        print(usage)
        sys.exit(2)

    # Handling command line options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(usage)
            sys.exit()
        elif opt in ("-f", "--file"):
            script_file = arg
        elif opt in ("-o", "--outputFormat"):
            output_format = arg
        elif opt in ("-p", "--parameters"):
            parameters = arg
        elif opt in ("-r", "--outputFileName"):
            output_file_name = arg

    # Make sure we got the parameters and arguments we need
    if script_file == '':
        print("You must supply a CadQuery input script file name.")
    if output_format == '':
        print("You must supply an output file format.")
    if script_file == '' or output_format == '':
        print(usage)

    # Read the user's script file in and execute it
    with open(script_file, 'r') as content_file:
        user_script = content_file.read()

    build_result = cqgi.parse(user_script).build()

    # In case we have multipe objects to pass back
    jsonMeshes = []

    # Step through all of the objects returned
    for obj in build_result.results:
        # Convert the object that was returned to JSON that we can render
        s = obj.shape.val()
        tess = s.tessellate(0.1)  #TODO: user provided tolerance needed

        mesher = JsonMesh(
        )  #warning: needs to be changed to remove buildTime and exportTime!!!
        #add vertices
        for vec in tess[0]:
            mesher.addVertex(vec.x, vec.y, vec.z)

        #add faces
        for f in tess[1]:
            mesher.addTriangleFace(f[0], f[1], f[2])

        jsonMeshes.append(mesher.toJson())

    # Stuff all of the JSON meshes into an array so that the environment can display all of them
    allJSONResults = '{"geometry": ['
    i = 0
    for curMesh in jsonMeshes:
        allJSONResults += curMesh

        # If there is only one object or this is the last object, we do not want a trailing comma
        if i < len(jsonMeshes) - 1:
            allJSONResults += ","

        i += 1
    allJSONResults += "],"

    allJSONResults += '"error": "' + str(build_result.exception) + '"}'

    # Passing the JSON to stdout will allow the GUI to render the object
    print(allJSONResults)
コード例 #37
0
ファイル: cq_process.py プロジェクト: jmwright/cadquery-gui
def main(argv):
    script_file = ''
    output_format = ''
    parameters = ''
    output_file_name = ''

    # Make sure that everything is good with our arguments
    try:
        opts, args = getopt.getopt(argv,"hrf:o:p:",["help", "file=","outputFormat=","parameters="])
    except getopt.GetoptError as e:
        # print (str(e))
        print("Improper command line arguments supplied.")
        print(usage)
        sys.exit(2)

    # Handling command line options
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(usage)
            sys.exit()
        elif opt in ("-f", "--file"):
            script_file = arg
        elif opt in ("-o", "--outputFormat"):
            output_format = arg
        elif opt in ("-p", "--parameters"):
            parameters = arg
        elif opt in ("-r", "--outputFileName"):
            output_file_name = arg

    # Make sure we got the parameters and arguments we need
    if script_file == '':
        print("You must supply a CadQuery input script file name.")
    if output_format == '':
        print("You must supply an output file format.")
    if script_file == '' or output_format == '':
        print(usage)

    # Read the user's script file in and execute it
    with open(script_file, 'r') as content_file:
      user_script = content_file.read()

    build_result = cqgi.parse(user_script).build()

    # In case we have multipe objects to pass back
    jsonMeshes = []

    # Step through all of the objects returned
    for obj in build_result.results:
        # Convert the object that was returned to JSON that we can render
        s = obj.shape.val()
        tess = s.tessellate(0.1) #TODO: user provided tolerance needed

        mesher = JsonMesh() #warning: needs to be changed to remove buildTime and exportTime!!!
        #add vertices
        for vec in tess[0]:
            mesher.addVertex(vec.x, vec.y, vec.z)

        #add faces
        for f in tess[1]:
            mesher.addTriangleFace(f[0],f[1], f[2])

        jsonMeshes.append(mesher.toJson())

    # Stuff all of the JSON meshes into an array so that the environment can display all of them
    allJSONResults = '{"allResults": ['
    i = 0
    for curMesh in jsonMeshes:
      allJSONResults += curMesh

      # If there is only one object or this is the last object, we do not want a trailing comma
      if i < len(jsonMeshes) - 1:
        allJSONResults += ","

      i += 1
    allJSONResults += "]}"

    # Passing the JSON to stdout will allow the GUI to render the object
    print(allJSONResults)