Ejemplo n.º 1
0
    def Activated(self):

        import FreeCADGui
        project = None
        sel = FreeCADGui.Selection.getSelection()
        for o in sel:
            if "Renderer" in o.PropertiesList:
                project = o
                break
        if not project:
            for o in FreeCAD.ActiveDocument.Objects:
                if "Renderer" in o.PropertiesList:
                    project = o
                    break
        if not project:
            FreeCAD.Console.PrintError(
                translate(
                    "Render",
                    "Unable to find a valid project in selection or document"))
            return
        img = project.Proxy.render(project, external=True)
        if img and hasattr(project,
                           "OpenAfterRender") and project.OpenAfterRender:
            import ImageGui
            ImageGui.open(img)
Ejemplo n.º 2
0
 def __init__(self, x, y, disp, xcb, ship):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param x X coordinates.
     @param y Transversal areas.
     @param disp Ship displacement.
     @param xcb Bouyancy center length.
     @param ship Active ship instance.
     """
     if self.createDirectory():
         return
     if self.saveData(x, y, ship):
         return
     if self.saveLayout(x, y, disp, xcb, ship):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'areas.png')
Ejemplo n.º 3
0
 def __init__(self, x, y, disp, draft, trim):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param x Roll angles [deg].
     @param y GZ value [m].
     @param disp Ship displacement [tons].
     @param draft Ship draft [m].
     @param trim Ship trim angle [deg].
     """
     if self.createDirectory():
         return
     if self.saveData(x,y):
         return
     if self.saveLayout(x,y, disp, draft, trim):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'gz.png')
Ejemplo n.º 4
0
 def __init__(self, x, y, disp, draft, trim):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param x Roll angles [deg].
     @param y GZ value [m].
     @param disp Ship displacement [tons].
     @param draft Ship draft [m].
     @param trim Ship trim angle [deg].
     """
     if self.createDirectory():
         return
     if self.saveData(x, y):
         return
     if self.saveLayout(x, y, disp, draft, trim):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'gz.png')
Ejemplo n.º 5
0
 def __init__(self, x, y, disp, xcb, ship):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param x X coordinates.
     @param y Transversal areas.
     @param disp Ship displacement.
     @param xcb Bouyancy center length.
     @param ship Active ship instance.
     """
     if self.createDirectory():
         return
     if self.saveData(x,y,ship):
         return
     if self.saveLayout(x,y,disp,xcb,ship):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'areas.png')
Ejemplo n.º 6
0
def render(project, external=True):

    if not project.PageResult:
        return
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Render")
    rpath = p.GetString("PovRayPath", "")
    args = p.GetString("PovRayParameters", "")
    if not rpath:
        raise
    if args:
        args += " "
    import os
    exe = rpath + " " + args + project.PageResult
    print("Executing " + exe)
    os.system(exe)
    import ImageGui
    print("Saving image as " + imgname)
    imgname = os.path.splitext(project.PageResult)[0] + ".png"
    ImageGui.open(imgname)
    return
Ejemplo n.º 7
0
def renderWidget():
	child=w
	child=w.mw
	image = QtGui.QPixmap(child.size())
	child.render(image)
	imagename=cm.get('imageName','c:/t2.jpg')
	imageformat=cm.get('imageFormat','JPG')
	image.save( 'c:/t.jpg', 'JPG')
	
	#displaymode=cm.get('displayMode','extern')
	displaymode=cm.get('displayMode','intern')
	displayCmd=cm.get('displayCmd','eog')
	
	displaymode='intern'
	displayCmd="c:/i_view32.exe"
	
	if displaymode=='intern':
		import os, tempfile
		d=tempfile.mktemp()
		os.makedirs(d)
		imagename = d + '/tree.' + imageformat
		FreeCAD.Console.PrintMessage("tempfile !" + imagename +'!\n')
		
	image.save(imagename,imageformat)
	
	if displaymode == 'extern':
		image.save( '/tmp/snapshot.png', 'PNG')
		import os
		#os.system("eog /tmp/snapshot.png &")
		import subprocess
		DETACHED_PROCESS = 0x00000008

		pid = subprocess.Popen([displayCmd,"c:\\t3.jpg"],creationflags=DETACHED_PROCESS).pid
		#subprocess.call(["c:/i_view32.exe","c:\\t3.jpg"])
		
		
	else:
		import ImageGui
		ImageGui.open(imagename)
		FreeCAD.Console.PrintMessage("Image saved to:" +str(imagename))
Ejemplo n.º 8
0
def renderWidget():
    child = w
    child = w.mw
    image = QtGui.QPixmap(child.size())
    child.render(image)
    imagename = cm.get('imageName', 'c:/t2.jpg')
    imageformat = cm.get('imageFormat', 'JPG')
    image.save('c:/t.jpg', 'JPG')

    #displaymode=cm.get('displayMode','extern')
    displaymode = cm.get('displayMode', 'intern')
    displayCmd = cm.get('displayCmd', 'eog')

    displaymode = 'intern'
    displayCmd = "c:/i_view32.exe"

    if displaymode == 'intern':
        import os, tempfile
        d = tempfile.mktemp()
        os.makedirs(d)
        imagename = d + '/tree.' + imageformat
        FreeCAD.Console.PrintMessage("tempfile !" + imagename + '!\n')

    image.save(imagename, imageformat)

    if displaymode == 'extern':
        image.save('/tmp/snapshot.png', 'PNG')
        import os
        #os.system("eog /tmp/snapshot.png &")
        import subprocess
        DETACHED_PROCESS = 0x00000008

        pid = subprocess.Popen([displayCmd, "c:\\t3.jpg"],
                               creationflags=DETACHED_PROCESS).pid
        #subprocess.call(["c:/i_view32.exe","c:\\t3.jpg"])

    else:
        import ImageGui
        ImageGui.open(imagename)
        FreeCAD.Console.PrintMessage("Image saved to:" + str(imagename))
Ejemplo n.º 9
0
 def __init__(self, ship, trim, drafts):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param ship Selected ship instance
     @param trim Trim in degrees.
     @param drafts List of drafts to be performed.
     """
     if self.createDirectory():
         return
     if self.saveData(ship, trim, drafts):
         return
     if self.saveLayout(trim):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'volume.png')
     ImageGui.open(self.path + 'stability.png')
     ImageGui.open(self.path + 'coeffs.png')
Ejemplo n.º 10
0
 def __init__(self, ship, trim, drafts):
     """ Constructor. performs plot and show it (Using pyxplot).
     @param ship Selected ship instance
     @param trim Trim in degrees.
     @param drafts List of drafts to be performed.
     """
     if self.createDirectory():
         return
     if self.saveData(ship, trim, drafts):
         return
     if self.saveLayout(trim):
         return
     if self.execute():
         return
     ImageGui.open(self.path + 'volume.png')
     ImageGui.open(self.path + 'stability.png')
     ImageGui.open(self.path + 'coeffs.png')
Ejemplo n.º 11
0
def interpol2(filename,show=True):
	''' interpolate data from filename_out.txt to filename_post.txt'''

	filename2=filename + "_out.txt"
	tv=[]
	xv=[]
	yv=[]
	zv=[]

	rx=[]
	ry=[]
	rz=[]
	ra=[]

	for line in open(filename + "_out.txt", "r"):
		line=line.rstrip('\r\n')
		ll= line.split(' ')
		if ll[0] == '#': 
			continue
		llf=[]
		for z in ll:
			llf.append(float(z))

		tv.append(llf[0])
		xv.append(llf[1])
		yv.append(llf[2])
		zv.append(llf[3])
		
		rx.append(llf[4])
		ry.append(llf[5])
		rz.append(llf[6])
		ra.append(llf[7])

	# interpolate
	import numpy as np
	import scipy
	from scipy.interpolate import interp1d
	#import matplotlib.pyplot as plt

	fx = interp1d(tv, xv, )
	fy = interp1d(tv, yv, )
	fz = interp1d(tv, zv, )
	frx = interp1d(tv, rx,)
	fry = interp1d(tv, ry, )
	frz = interp1d(tv, rz, )
	fra = interp1d(tv, ra, )

	xnew = np.linspace(0, 0.99, num=100, endpoint=True)
	#try:
	if show:
		plt.plot(tv, xv, 'o',tv,yv,'+',tv,zv,'*')
		plt.plot( xnew, fx(xnew), '-', xnew, fy(xnew), '--',xnew, fz(xnew), '.-', )
#		plt.legend(['aaa','x','y','z'], loc='best')
		plt.title('Placement Interpolation Data')
		plt.xlabel('time relative')
		plt.ylabel('Placement Base')
		plt.savefig(filename +'.png')
		# plt.show()
		import ImageGui
		ImageGui.open(filename +'.png')
	#except:
	#	pass

	# export data
	fout = open(filename + "_post.txt",'w')
	for t in xnew:
		try:
			l=' '.join(str(k) for k in [t,fx(t),fy(t),fz(t),frx(t),fry(t),frz(t),fra(t)])
			fout.write(l+'\n')
		except:
			pass
	fout.close()
Ejemplo n.º 12
0
def interpol2(filename, show=True):
    ''' interpolate data from filename_out.txt to filename_post.txt'''

    filename2 = filename + "_out.txt"
    tv = []
    xv = []
    yv = []
    zv = []

    rx = []
    ry = []
    rz = []
    ra = []

    for line in open(filename + "_out.txt", "r"):
        line = line.rstrip('\r\n')
        ll = line.split(' ')
        if ll[0] == '#':
            continue
        llf = []
        for z in ll:
            llf.append(float(z))
        print llf
        tv.append(llf[0])
        xv.append(llf[1])
        yv.append(llf[2])
        zv.append(llf[3])

        rx.append(llf[4])
        ry.append(llf[5])
        rz.append(llf[6])
        ra.append(llf[7])

    # interpolate
    import numpy as np
    import scipy
    from scipy.interpolate import interp1d
    import matplotlib.pyplot as plt

    fx = interp1d(
        tv,
        xv,
    )
    fy = interp1d(
        tv,
        yv,
    )
    fz = interp1d(
        tv,
        zv,
    )
    frx = interp1d(
        tv,
        rx,
    )
    fry = interp1d(
        tv,
        ry,
    )
    frz = interp1d(
        tv,
        rz,
    )
    fra = interp1d(
        tv,
        ra,
    )

    xnew = np.linspace(0, 0.99, num=100, endpoint=True)
    #try:
    if show:
        plt.plot(tv, xv, 'o', tv, yv, '+', tv, zv, '*')
        plt.plot(
            xnew,
            fx(xnew),
            '-',
            xnew,
            fy(xnew),
            '--',
            xnew,
            fz(xnew),
            '.-',
        )
        #		plt.legend(['aaa','x','y','z'], loc='best')
        plt.title('Placement Interpolation Data')
        plt.xlabel('time relative')
        plt.ylabel('Placement Base')
        plt.savefig(filename + '.png')
        # plt.show()
        import ImageGui
        ImageGui.open(filename + '.png')
    #except:
    #	pass

    # export data
    fout = open(filename + "_post.txt", 'w')
    for t in xnew:
        try:
            l = ' '.join(
                str(k) for k in
                [t, fx(t),
                 fy(t), fz(t),
                 frx(t),
                 fry(t),
                 frz(t),
                 fra(t)])
            fout.write(l + '\n')
        except:
            pass
    fout.close()
Ejemplo n.º 13
0
    def render(self, external=True):
        """Render the project, calling external renderer

        Parameters
        ----------
        external: switch between internal/external version of renderer

        Returns
        -------
        Output file path
        """
        obj = self.fpo

        # Get a handle to renderer module
        try:
            renderer = RendererHandler(obj.Renderer)
        except ModuleNotFoundError:
            msg = translate(
                "Render", "Cannot render project: Renderer '%s' not found\n")
            App.Console.PrintError(msg % obj.Renderer)
            return ""

        # Get the rendering template
        assert (obj.Template and os.path.exists(obj.Template)),\
            "Cannot render project: Template not found"
        template = None
        with open(obj.Template, "r") as template_file:
            template = template_file.read()
        if sys.version_info.major < 3:
            template = template.decode("utf8")

        # Build a default camera, to be used if no camera is present in the
        # scene
        camstr = (Gui.ActiveDocument.ActiveView.getCamera()
                  if App.GuiUp else camera.DEFAULT_CAMERA_STRING)
        defaultcamview = SimpleNamespace()
        defaultcamview.Source = SimpleNamespace()
        defaultcamview.Source.Proxy = SimpleNamespace()
        defaultcamview.Source.Proxy.type = "Camera"
        defaultcamview.Source.Name = "Default_Camera"
        defaultcamview.Source.Label = "Default_Camera"
        defaultcamview.Name = "Default_CameraView"
        defaultcamview.Label = View.view_label(defaultcamview.Source, obj)
        camera.set_cam_from_coin_string(defaultcamview.Source, camstr)
        cam = renderer.get_rendering_string(defaultcamview)
        del defaultcamview, camstr

        # Get objects rendering strings (including lights, cameras...)
        views = self.all_views()
        get_rdr_string =\
            renderer.get_rendering_string if obj.DelayedBuild\
            else attrgetter("ViewResult")
        objstrings = [
            get_rdr_string(v) for v in views if v.Source.ViewObject.Visibility
        ]

        # Add a ground plane if required
        if getattr(obj, "GroundPlane", False):
            objstrings.append(self.write_groundplane(renderer))

        # Merge all strings (cam, objects, ground plane...) into rendering
        # template
        renderobjs = '\n'.join(objstrings)
        if "RaytracingCamera" in template:
            template = re.sub("(.*RaytracingCamera.*)", cam, template)
            template = re.sub("(.*RaytracingContent.*)", renderobjs, template)
        else:
            template = re.sub("(.*RaytracingContent.*)",
                              cam + "\n" + renderobjs, template)
        template = (template.encode("utf8")
                    if sys.version_info.major < 3 else template)

        # Write instantiated template into a temporary file
        fhandle, fpath = mkstemp(prefix=obj.Name,
                                 suffix=os.path.splitext(obj.Template)[-1])
        with open(fpath, "w") as fobj:
            fobj.write(template)
        os.close(fhandle)
        obj.PageResult = fpath
        os.remove(fpath)
        assert obj.PageResult, "Rendering error: No page result"

        App.ActiveDocument.recompute()

        # Fetch the rendering parameters
        params = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Render")
        prefix = params.GetString("Prefix", "")
        if prefix:
            prefix += " "

        try:
            output = obj.OutputImage
            assert output
        except (AttributeError, AssertionError):
            output = os.path.splitext(obj.PageResult)[0] + ".png"

        try:
            width = int(obj.RenderWidth)
        except (AttributeError, ValueError, TypeError):
            width = 800

        try:
            height = int(obj.RenderHeight)
        except (AttributeError, ValueError, TypeError):
            height = 600

        # Run the renderer on the generated temp file, with rendering params
        img = renderer.render(obj, prefix, external, output, width, height)

        # Open result in GUI if relevant
        try:
            if img and obj.OpenAfterRender:
                ImageGui.open(img)
        except (AttributeError, NameError):
            pass

        # And eventually return result path
        return img