예제 #1
0
파일: ModelLoader.py 프로젝트: rosedu/hfall
 def saveModel(self):
     self.model = Model([], [1, 0, 0, 0] +
                            [0, 1, 0, 0] +
                            [0, 0, 1, 0] +
                            [0, 0, 0, 1], self.modelName)
     for m in self.parser.object.meshes:
         if m.type != 1:
             continue
         mesh = Mesh([], None, None, 16*[0])
         
         # get system coordinates
         for i in range(0, 3):
             for j in range(0, 4):
                 mesh.matrix4[i*3+j] = m.data.matrix[i+j*3]
         # get vertices & texCoordinates
         for i in range(0, m.data.nrOfVertices):
             mesh.vertices += m.data.vertices[i]
             if m.data.coordinates:
                 if not mesh.texels:
                     mesh.texels = []
                 mesh.texels += m.data.coordinates[i]
         # get faces
         if m.data.faces:
             mesh.triangles = []
             for group in m.data.faces.materialGroups:
                 triangles = Mesh.Triangles([], self.materialMng.get(group.materialName))
                 for i in group.faces:
                     triangles.faces += m.data.faces.faces[i]
                 mesh.triangles.append(triangles)
         self.model.meshes.append(mesh)
     self.modelMng.add(self.model)
예제 #2
0
  def __init__(self, engine, editorMode = False):
    self.engine         = engine
    self.boardWidth     = 4.0
    self.boardLength    = 12.0
    self.beatsPerBoard  = 5.0
    self.strings        = 5
    self.fretWeight     = [0.0] * self.strings
    self.fretActivity   = [0.0] * self.strings
    self.fretColors     = Theme.fretColors
    self.playedNotes    = []
    self.editorMode     = editorMode
    self.selectedString = 0
    self.time           = 0.0
    self.pickStartPos   = 0
    self.leftyMode      = False
    self.currentBpm     = 50.0
    self.currentPeriod  = 60000.0 / self.currentBpm
    self.targetBpm      = self.currentBpm
    self.lastBpmChange  = -1.0
    self.baseBeat       = 0.0
    self.setBPM(self.currentBpm)
    self.vertexCache    = numpy.empty((8 * 4096, 3), numpy.float32)
    self.colorCache     = numpy.empty((8 * 4096, 4), numpy.float32)

    engine.resource.load(self,  "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae")))
    engine.resource.load(self,  "keyMesh",  lambda: Mesh(engine.resource.fileName("key.dae")))
    engine.loadSvgDrawing(self, "glowDrawing", "glow.png")
    engine.loadSvgDrawing(self, "neckDrawing", "neck.png")
    engine.loadSvgDrawing(self, "stringDrawing", "string.png")
    engine.loadSvgDrawing(self, "barDrawing", "bar.png")
    engine.loadSvgDrawing(self, "noteDrawing", "note.png")
예제 #3
0
파일: Builder.py 프로젝트: jdavid1385/pyFEM
    def BuildSpace(self):
        #   Generating the Mesh
        Params = {'Nelems': self.Nelems,'a': self.a,'b': self.b}        
        mesh = Mesh(**Params)
        #   Retreiving the mesh ends up with a tuple with the Grid and its iterator
        (self.Grid, Grid_itr) = mesh.get_Mesh()
        print self.Grid
        i = 0
        #   Generate the elements over the Grid
        NodesPerElem = len(self.Shape_Funct.getSF_Names())
        for k in Grid_itr:
            Segment_Props = {'k':i,'Interval':self.Grid[k:k+NodesPerElem]}
            self.FE.insert(i,Finite_Element(**Segment_Props))
            i=i+1

        #   Calculate functionals
        for Element in self.FE:
            for funct in self.Shape_Funct.getSF_Names():
                Element.Functional(self.Shape_Funct.getFunctional(funct))(Element.interval)

        #   For each element assign p(x), q(x) and f(x)
        for Element in self.FE:
            Element.p_x = self.p_x
            Element.q_x = self.q_x
            Element.f_x = self.f_x
    
        #   Creating the local symbolic Matrices and evaluating the numerical integrals over the interval
        for Element in self.FE:
            Element.create_stiff_local_Sym()
            Element.create_nodal_forces_local_Sym()
            Element.solve_stiff_local()
            Element.solve_forces_local()
예제 #4
0
파일: Builder.py 프로젝트: zxx4477/pyFEM
    def BuildSpace(self):
        #   Generating the Mesh
        Params = {'Nelems': self.Nelems, 'a': self.a, 'b': self.b}
        mesh = Mesh(**Params)
        #   Retreiving the mesh ends up with a tuple with the Grid and its iterator
        (self.Grid, Grid_itr) = mesh.get_Mesh()
        print self.Grid
        i = 0
        #   Generate the elements over the Grid
        NodesPerElem = len(self.Shape_Funct.getSF_Names())
        for k in Grid_itr:
            Segment_Props = {'k': i, 'Interval': self.Grid[k:k + NodesPerElem]}
            self.FE.insert(i, Finite_Element(**Segment_Props))
            i = i + 1

        #   Calculate functionals
        for Element in self.FE:
            for funct in self.Shape_Funct.getSF_Names():
                Element.Functional(self.Shape_Funct.getFunctional(funct))(
                    Element.interval)

        #   For each element assign p(x), q(x) and f(x)
        for Element in self.FE:
            Element.p_x = self.p_x
            Element.q_x = self.q_x
            Element.f_x = self.f_x

        #   Creating the local symbolic Matrices and evaluating the numerical integrals over the interval
        for Element in self.FE:
            Element.create_stiff_local_Sym()
            Element.create_nodal_forces_local_Sym()
            Element.solve_stiff_local()
            Element.solve_forces_local()
def Farthest_Point_Sampling(mesh_name,n):
    """
    add the new farest point to set and print n out of all of mesh
    :param mesh_name:
    :param n:
    :return:
    """
    mesh = read(mesh_name + ".ply")
    v, f = (np.array(mesh.points), np.array(mesh.cells_dict['triangle'], dtype=np.int32))
    geodesics_dist = gdist.local_gdist_matrix(v.astype(np.float64), f.astype(np.int32))

    mesh = Mesh(v=v,f=f)
    mesh.render_pointcloud(scalar_function=mesh.gaussianCurvature())

    s=[]
    s.append(np.random.randint(0, len(v)))
    while (len(s)!=n):
        max_dist = 0
        selected_v = None
        for i,v_i in enumerate(v):
            min_by_s = np.inf
            for s_i in s: #get minimum ovver all s_i
                dist = geodesics_dist[s_i][v_i]
                if dist < min_by_s:
                    min_by_s = dist
            if min_by_s > max_dist:
                max_dist = min_by_s
                selected_v = v_i

        v = np.delete(v,selected_v) #dont iterate v over this node anymore
        s.append(selected_v)
    f_new=gen_f(s)
    mesh = Mesh(v=v[np.array(s)], f=f_new)
    mesh.render_pointcloud(scalar_function=mesh.gaussianCurvature())
예제 #6
0
파일: ModelLoader.py 프로젝트: rosedu/hfall
    def saveModel(self):
        self.model = Model([], self.modelName)
        for m in self.parser.object.meshes:
            if m.type != 1:
                continue
            geom = Mesh.Geometry([], [], [])
            # get vertices & texCoordinates
            triangles = []
            geom.vertices = m.data.vertices
            if m.data.coordinates:
                geom.texCoords = m.data.coordinates

            # get faces
            if m.data.faces:
                geom.faces = m.data.faces.faces
                for group in m.data.faces.materialGroups:
                    faces = []
                    for i in group.faces:
                        faces.extend(m.data.faces.faces[i])
                    triangles.append(Mesh.Triangles(faces, self.materialMng.get(group.materialName)))
            # get mesh coordinates
            mat = m.data.matrix
            rot = 9 * [0]
            for i in range(3):
                for j in range(3):
                    rot[3 * i + j] = mat[3 * j + i]

            mesh = Mesh(geom, triangles, Coordinate(rot, mat[9:]))
            mesh.name = m.name
            mesh.init()
            self.model.meshes.append(mesh)
        self.modelMng.add(self.model)
def deflectomotery(objectName, imgDir):

    Img = Image(imgDir, objectName)

    Gradient_V = setGrad(Img.imgVSet, 3.8)
    Gradient_H = setGrad(Img.imgHSet, 3.8)

    #cv2.imwrite(os.path.join(imgDir, 'GradV.png'), np.array(Gradient_V * 255, dtype=np.uint8))
    #cv2.imwrite(os.path.join(imgDir, 'GradH.png'), np.array(Gradient_H * 255, dtype=np.uint8))

    N = np.zeros((Img.height, Img.width, 3), dtype=Img.PRECISION_IMG)
    N[..., 0] = -Gradient_V / np.sqrt(np.square(Gradient_V) + np.square(Gradient_H) + 1)
    N[..., 1] = -Gradient_H / np.sqrt(np.square(Gradient_V) + np.square(Gradient_H) + 1)
    N[..., 2] = 1 / np.sqrt(np.square(Gradient_V) + np.square(Gradient_H) + 1)

    # crop valid region
    Ncrop = N[Img.mask[0]:Img.mask[2], Img.mask[1]:Img.mask[3]]
    A = Img.A[Img.mask[0]:Img.mask[2], Img.mask[1]:Img.mask[3]]

    [newHeight, newWidth, _] = A.shape

    Nfname = os.path.join(imgDir, 'normal.png')
    # xyz to zyx because of OPENCV BGR order
    cv2.imwrite(Nfname, cv2.cvtColor(np.array((Ncrop + 1) / 2.0 * 255, dtype=np.uint8), cv2.COLOR_RGB2BGR))

    mesh = Mesh(objectName, newHeight, newWidth, Img.mask)
    mesh.setNormal(N)
    mesh.setDepth()
    mesh.setTexture(A)
    mesh.exportOBJ(imgDir, True)
예제 #8
0
 def _gen_space_btn_clicked(self):
     width = int(self._width.text())
     height = int(self._height.text())
     if self._canvas:
         self._canvas.close()
     self._mesh = Mesh(width, height, PROB)
     self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
     self._canvas.show()
예제 #9
0
 def createCubeBoundary(self):
   """
   Returns a Mesh that is the boundary of the unit cube
   """
   mesh = Mesh()
   self._createCppHandle()
   mesh.cppHandle = self.cppHandle.createCubeBoundary(self.debug)
   return mesh
예제 #10
0
 def create(self, faults=None):
   """
   Generate a Mesh from a boundary
   """
   mesh = Mesh()
   self._createCppHandle()
   mesh.cppHandle = self.cppHandle.generate(self.boundary.cppHandle)
   return mesh
예제 #11
0
 def clear_btn_clicked(self):
     width = int(self._width.text())
     height = int(self._height.text())
     prob_rule4 = int(self._prob_rule4.text())
     self._mesh = Mesh(width, height, prob_rule4)
     self._canvas.close()
     self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
     self._canvas.show()
     self._canvas.repaint()
예제 #12
0
    def saveMeshToFile(self):
        dialog = QtWidgets.QInputDialog(self)

        directory, ok = dialog.getText(self, 'Input Directory', 'Directory:')
        if ok:
            name, ok = dialog.getText(self, 'Name the project', 'Name:')
            if ok:
                self.mesh.params = self.phasesControls.getAllParams()
                Mesh.saveMeshToFile(self.mesh, directory, name)
예제 #13
0
    def Calc_Mesh_Type_Num(self,mtype):
        mesh=Mesh(self.N,mtype,"Num")

        method=getattr(self,"Calc_Num_"+mtype)
        
        for n in range( self.N ):
            mesh[n]=method(  self.ts[n]  )

        mesh.__Canvas__=self.__Canvas__
        return mesh
예제 #14
0
파일: Dialogs.py 프로젝트: twcb/FoF
    def __init__(self,
                 engine,
                 prompt="",
                 selectedSong=None,
                 selectedLibrary=None):
        self.prompt = prompt
        self.engine = engine
        self.time = 0
        self.accepted = False
        self.selectedIndex = 0
        self.camera = Camera()
        self.cassetteHeight = .8
        self.cassetteWidth = 4.0
        self.libraryHeight = 1.2
        self.libraryWidth = 4.0
        self.itemAngles = None
        self.itemLabels = None
        self.selectedOffset = 0.0
        self.cameraOffset = 0.0
        self.selectedItem = None
        self.song = None
        self.songCountdown = 1024
        self.songLoader = None
        self.initialItem = selectedSong
        self.library = selectedLibrary
        self.searchText = ""

        # Use the default library if this one doesn't exist
        if not self.library or not os.path.isdir(
                self.engine.resource.fileName(self.library)):
            self.library = Song.DEFAULT_LIBRARY

        self.loadCollection()
        self.engine.resource.load(
            self,
            "cassette",
            lambda: Mesh(self.engine.resource.fileName("cassette.dae")),
            synch=True)
        self.engine.resource.load(
            self,
            "label",
            lambda: Mesh(self.engine.resource.fileName("label.dae")),
            synch=True)
        self.engine.resource.load(
            self,
            "libraryMesh",
            lambda: Mesh(self.engine.resource.fileName("library.dae")),
            synch=True)
        self.engine.resource.load(
            self,
            "libraryLabel",
            lambda: Mesh(self.engine.resource.fileName("library_label.dae")),
            synch=True)

        self.engine.loadSvgDrawing(self, "background", "cassette.svg")
예제 #15
0
def load_mesh(path):
    with open(path, 'r') as f:
        width, height = f.readline().split(' ')
        mesh = Mesh(int(width), int(height))
        points = mesh.get_points()
        for line in f.read().splitlines():
            x, y, phase, id = line.split(' ')
            points[int(x)][int(y)].id = int(id)
            points[int(x)][int(y)].phase = int(phase)

        return mesh
예제 #16
0
파일: R.py 프로젝트: olesmith/Poopys
    def Calc_Rs(self):
        self.Rs = Mesh(self.N, "R", "")

        err = 0
        for n in range(self.N):
            try:
                self.Rs[n] = self.R(self.ts[n])
            except ValueError:
                err = 1

        return err
예제 #17
0
    def Calc_Mesh_Type_Ana(self,mtype):
        mesh=Mesh(self.N,mtype,"Ana")

        method=getattr(self,mtype)
        for n in range( self.N ):
            mesh[n]=None
            if (method):
                mesh[n]=method(  self.ts[n]  )

        mesh.__Canvas__=self.__Canvas__
        return mesh
def CPP(Mesh):
    vertexs = Mesh.getVertexs()
    output = []
    output.append('void ' + formatName(Mesh.getName()) + '(){\n')
    output.append('   glBegin("GL_POLYGON")\n')
    for vertex in vertexs:
        x, y, z = vertex
        output.append('   glVertex3f({},{},{})\n'.format(x, y, z))
    output.append('   glEnd()\n')
    output.append('}\n')
    return output
예제 #19
0
def LoadObj(fileName):
    mesh = Mesh()
    mesh.LoadFromObj(fileName)
    return mesh
    print len(mesh.vertexs)
    for vertex in mesh.vertexs:
        print str(vertex.pos[0]) + ' ' + str(vertex.pos[1]) + ' ' + str(
            vertex.pos[2])
    print len(mesh.faces)
    for face in mesh.faces:
        print str(face[0])
    print len(mesh.textureCoords)
예제 #20
0
 def __init__(self, params):
   Mesh.__init__(self, params)
   self.n_cell = params.get("n_cell")
   self.L = params.get("length")
   self.x_min = params.get("x_min")
   h = self.L / self.n_cell
   self.h = [h for e in xrange(self.n_cell)]
   self.x = np.zeros(self.n_cell + 1)
   self.x_max = self.x_min + self.L
   self.x[0] = self.x_min
   for e in xrange(self.n_cell):
     self.x[e + 1] = self.x[e] + self.h[e]
예제 #21
0
 def __init__(self, app):
     super().__init__()
     self._app = app
     MainWindow.geometry = QRect(app.desktop().screenGeometry().width() - MENU_WIDTH, 300, MENU_WIDTH, MENU_HEIGHT)
     self._init_ui()
     self._started = False
     self._mesh = Mesh(DEF_POINTS_SIZE.width(), DEF_POINTS_SIZE.height(), PROB)
     self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
     self._nhood = NHOODS[0]
     self._periodic = False
     self._canvas.show()
     self._thread = None
예제 #22
0
def findHypotheses(Q: Queue, cloud, cloudNormals):
    mesh = Mesh('../Models/ToyScrew-Yellow.stl')
    #mesh = Mesh('Models/three_screws_two.ply')
    mesh.compileFeatures(N=10000)
    finder = ModelFinder(mesh)
    bestScore = None
    for o, r in finder.findInCloud(cloud, cloudNormals):
        score = scoreHypothesis(mesh, cloud, o, r)
        if bestScore is None or score > bestScore:
            bestScore = score
            faces = (mesh.Faces @ r.T) + o
            Q.put(np.copy(faces))
    return
예제 #23
0
 def Calc_Ana_v2s(self):
     self.v2s_Ana = Mesh(self.N, "v2", "Ana")
     for n in range(self.N):
         self.v2s_Ana[n] = None
         v2 = self.v2(self.ts[n])
         if (v2.__class__.__name__ == "float"):
             self.v2s_Ana[n] = Vector([self.ts[n], v2])
예제 #24
0
파일: Det.py 프로젝트: olesmith/Poopys
 def Calc_Ana_Dets(self):
     self.Dets_Ana = Mesh(self.N, "Det", "Ana")
     for n in range(self.N):
         self.Dets_Ana[n] = None
         det = self.Det(self.ts[n])
         if (det != None):
             self.Dets_Ana[n] = Vector([self.ts[n], det])
예제 #25
0
    def __init__(self,
                 fanout,
                 depth,
                 spread=default_spread,
                 rootColor=default_rootColor,
                 edgeColor=default_edgeColor,
                 scale=default_scale,
                 actor=None):
        Component.__init__(self, actor)
        self.fanout = fanout
        self.depth = depth
        self.spread = spread
        self.rootColor = rootColor
        self.edgeColor = edgeColor
        self.scale = scale
        self.rootScale = self.scale  # NOTE this will also apply to children
        #self.childScale = np.float32([1.0, 1.0, 1.0])  # NOTE this will get compounded if the radial tree is a true hierarchy, better to use scale = 1 (default)

        # Recursively generate radial tree
        treeRoot = self.createRadialTree(
            self.fanout, self.depth, self.spread,
            isRoot=True)  # creates full hierarchy and returns root actor
        treeRoot.components['Transform'] = Transform(
            rotation=np.random.uniform(-pi / 2, pi / 2, size=3),
            scale=self.rootScale,
            actor=treeRoot
        )  # NOTE random rotation ensures child vectors are not always generated close to the same canonical vectors
        treeRoot.components['Material'] = Material(color=self.rootColor,
                                                   actor=treeRoot)
        treeRoot.components['Mesh'] = Mesh.getMesh(src=self.treeRootModelFile,
                                                   actor=treeRoot)

        # Attach this hierarchy to current actor
        self.actor.children.append(treeRoot)
예제 #26
0
def Render(mesh=Mesh(), textureImg=None, textureHandle=None, angle=0.0):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    glPushMatrix()
    #    gluLookAt(0.0, 0.0, mesh.radius,
    #          0.0, 0.0, 0.0,
    #          0.0, mesh.radius, 0.0)
    #    gluLookAt(0.0, 0.0, 100,
    #          0.0, 0.0, 0.0,
    #          0.0, 100, 0.0)
    #    glPushMatrix()
    glRotatef(-180, 1.0, 0.0, 0.0)
    glRotatef(angle, 0.0, 1.0, 0.0)
    glTranslatef(-mesh.center[0], -mesh.center[1], -mesh.center[2])
    #

    #    glPopMatrix()
    #    textureImg.
    #    glColor3f(1.0, 0.0, 0.5)
    glBindTexture(GL_TEXTURE_2D, textureHandle)
    #    DrawPlane()
    #DrawTriangle()
    DrawMesh(mesh)
    glPopMatrix()
예제 #27
0
파일: Det.py 프로젝트: olesmith/Poopys
 def Calc_Num_Dets(self):
     self.Dets_Num = Mesh(self.N, "Det", "Num")
     for n in range(self.N):
         self.Dets_Num[n] = None
         det = self.Calc_Num_Det(self.ts[n])
         if (det.__class__.__name__ == "float"):
             self.Dets_Num[n] = Vector([self.ts[n], det])
예제 #28
0
 def __init__(self, parent):
     super(QGLWidget, self).__init__(parent)
     self.setMinimumSize(560, 480)
     self.mesh = Mesh('Test', "/home/romain/Bureau/3D PRINT/SanguinololuEnclosureBot_Doom.stl")
     self.mesh.scale(1/2)
     from utils.math import Vec3d
     self.mesh.rotate(90, Vec3d(-1, 0, 0))
예제 #29
0
    def Calc_Ana_Function(self,function):
        attr=function
        if (not self.Curve_Type_Has_Analytical(function)):
            print "No analytical method:",attr
            return None

        if (not hasattr(self,attr)):
            print "No class attribute:",attr
            return None

        method=getattr(self,attr)
        mesh=Mesh(self.N,function,"Ana")
        
        errors=0
        for n in range( self.N ):
            mesh[n]=None

            value=None
            try:
                value=method( self.ts[n] )
            except:
                errors+=1
                
            if (value!=None):
                mesh[n]=Vector([  self.ts[n],value  ])
            
        return mesh
예제 #30
0
    def validatePose(self, mesh : Mesh, pose, error):
        ''' Given a mesh, pose, and representation of the scene (self.SceneKd), figure out how
            good the pose is at describing the scene.

            Then return True if its good enough, and False otherwise.
        '''
        R, o = pose
        if R is None or o is None:
            return False, None
        return error < self.MaxDistanceError, -error
        nearbyDistances, nearbyPoints_ind = self.SceneKd.query(o.reshape((1,3)), k = 10000, distance_upper_bound = mesh.Radius)
        nearbyPoints_ind = np.array(nearbyPoints_ind)
        nearbyPoints = self.Scene[nearbyPoints_ind[nearbyPoints_ind < len(self.Scene)]]
        maxPoints = DENSITY * mesh.SurfaceArea
        if len(nearbyPoints) < 0.3 * maxPoints:
            return False, None

        nearbyPoints = (nearbyPoints - o) @ R
        distanceToMesh = mesh.distanceQuery(nearbyPoints)
        outliers = np.sum(distanceToMesh > error)
        inliers = np.sum(np.abs(distanceToMesh) <= error)
        # print(outliers, inliers)
        return inliers / maxPoints > 0.2, inliers / maxPoints
        if outliers > 0:
            return False, None
        if inliers < 60:
            return False, None
        return True
예제 #31
0
 def Calc_Num_v2s(self):
     self.v2s_Num = Mesh(self.N, "v2", "Num")
     for n in range(self.N):
         self.v2s_Num[n] = None
         v2 = self.Calc_Num_v2(self.ts[n])
         if (v2.__class__.__name__ == "float"):
             self.v2s_Num[n] = Vector([self.ts[n], v2])
예제 #32
0
 def Calc_Ana_Ss(self):
     self.S1 = self.S(self.t1)
     self.Ss_Ana = Mesh(self.N, "S", "Ana")
     for n in range(self.N):
         self.Ss_Ana[n] = None
         s = self.S(self.ts[n]) - self.S1
         if (s.__class__.__name__ == "float"):
             self.Ss_Ana[n] = Vector([self.ts[n], s])
예제 #33
0
 def Calc_Num_dRhos(self):
     self.dRhos_Num = Mesh(self.N, "dRho", "Num")
     for n in range(self.N):
         drho = self.Calc_Num_dRho(self.ts[n])
         v = None
         if (drho):
             v = Vector([self.ts[n], drho])
         self.dRhos_Num[n] = v
예제 #34
0
파일: dPhi.py 프로젝트: olesmith/Poopys
 def Calc_Num_dPhis(self):
     self.dPhis_Num = Mesh(self.N, "dPhi", "Num")
     for n in range(self.N):
         dphi = self.Calc_Num_dPhi(self.ts[n])
         v = None
         if (dphi):
             v = Vector([self.ts[n], dphi])
         self.dPhis_Num[n] = v
예제 #35
0
파일: Kappa.py 프로젝트: olesmith/Poopys
 def Calc_Num_Kappas(self):
     self.Kappas_Num = Mesh(self.N, "Kappa", "Num")
     for n in range(self.N):
         kappa = self.Calc_Num_Kappa(self.ts[n])
         v = None
         if (kappa):
             v = Vector([self.ts[n], kappa])
         self.Kappas_Num[n] = v
예제 #36
0
    def Calc_Ana_Psis(self):
        self.Psis_Ana = Mesh(self.N, "Psi", "Ana")
        for n in range(self.N):
            psi = self.Psi(self.ts[n])
            v = None
            if (psi):
                v = Vector([self.ts[n], psi])

            self.Psis_Ana[n] = v
예제 #37
0
파일: Cube.py 프로젝트: Pallavistar/pyTANG
 def __init__(self, scale=cube_scale, actor=None):
   Component.__init__(self, actor)
   Trackable.__init__(self)
   self.scale = scale
   
   # Scale vertices of base cube, specify edges, and initialize list of markers
   self.vertices = cube_vertices * self.scale
   self.vertex_colors = cube_vertex_colors
   self.vertex_scale = 0.3 * self.scale  # NOTE for rendering only, depends on 3D model
   
   self.edges = cube_edges
   self.edge_scale = 0.1 * self.scale  # NOTE for rendering only, depends on 3D model
   self.edge_color = np.float32([0.8, 0.7, 0.5])  # NOTE for rendering only
   # TODO make some of these parameters come from XML
   
   # NOTE Mark generated child actors (corners and edges) as transient, to prevent them from being exported in XML
   
   # Add spheres at cube corners (vertices) with appropriate color; also add color markers
   for vertex, colorName in zip(self.vertices, self.vertex_colors):
     vertexActor = Actor(self.actor.renderer, isTransient=True)
     vertexActor.components['Transform'] = Transform(translation=vertex, scale=self.vertex_scale, actor=vertexActor)
     vertexActor.components['Material'] = Material(color=colors_by_name[colorName], actor=vertexActor)
     vertexActor.components['Mesh'] = Mesh.getMesh(src="SmallSphere.obj", actor=vertexActor)
     self.actor.children.append(vertexActor)
     marker = ColorMarker(self, colorName)
     marker.worldPos = vertex
     self.markers.append(marker)
   
   # Add edges
   for u, v in self.edges:
     if u < len(self.vertices) and v < len(self.vertices) and self.vertices[u] is not None and self.vertices[v] is not None:  # sanity check
       midPoint = (self.vertices[u] + self.vertices[v]) / 2.0
       diff = self.vertices[v] - self.vertices[u]
       mag = np.linalg.norm(diff, ord=2)
       xy_mag = hypot(diff[0], diff[1])
       #zx_mag = hypot(diff[2], diff[0])
       rotation = np.degrees(np.float32([atan2(diff[1], diff[0]), acos(diff[1] / mag), 0])) if (mag != 0 and xy_mag != 0) else np.float32([0.0, 0.0, 0.0])
       #print "u: ", self.vertices[u], ", v: ", self.vertices[v], ", v-u: ", diff, ", mag: ", mag, ", rot:", rotation
       edgeActor = Actor(self.actor.renderer, isTransient=True)
       edgeActor.components['Transform'] = Transform(translation=midPoint, rotation=rotation, scale=self.edge_scale, actor=edgeActor)
       edgeActor.components['Material'] = Material(color=self.edge_color, actor=edgeActor)
       edgeActor.components['Mesh'] = Mesh.getMesh(src="CubeEdge.obj", actor=edgeActor)  # TODO fix Z-fighting issue and use CubeEdge_cylinder.obj
       self.actor.children.append(edgeActor)
예제 #38
0
class GLViewWidget(QGLWidget):
    def __init__(self, parent):
        super(QGLWidget, self).__init__(parent)
        self.setMinimumSize(560, 480)
        self.mesh = Mesh('Test', "/home/romain/Bureau/3D PRINT/SanguinololuEnclosureBot_Doom.stl")
        self.mesh.scale(1/2)
        from utils.math import Vec3d
        self.mesh.rotate(90, Vec3d(-1, 0, 0))

    def paintGL(self):
        glClear(GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glRotate(20, 1, 1, 0)
        glTranslatef(-20, -80, -70.0)
        self.mesh.displayGL()

    def resizeGL(self, w, h):
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, 560 / 480, 0.1, 100.0)

    def initializeGL(self):
        glClearColor(0.05, 0.2, 0.4, 1.0)
        glClearDepth(1.0)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LEQUAL)
        glShadeModel(GL_FLAT)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
예제 #39
0
  def refine(self, mesh):
    """
    Refine mesh.
    """
    self._setupLogging()
    logEvent = "%srefine" % self._loggingPrefix
    self._eventLogger.eventBegin(logEvent)

    from pylith.mpi.Communicator import petsc_comm_world
    comm = petsc_comm_world()
    if 0 == comm.rank:
      self._info.log("Refining mesh using uniform refinement.")

    from Mesh import Mesh
    newMesh = Mesh()
    newMesh.debug(mesh.debug())
    newMesh.coordsys(mesh.coordsys())
    ModuleRefineUniform.refine(self, newMesh, mesh, self.levels)
    mesh.cleanup()

    self._eventLogger.eventEnd(logEvent)
    return newMesh
예제 #40
0
파일: test.py 프로젝트: Daiver/jff
def bigRandomMeshTest():
    width, height = 900, 900
    numOfPoints = 2000
    mesh = Mesh(width, height)
    for i in xrange(numOfPoints):
        x = random.randint(0, width/5)*5
        y = random.randint(0, height/5)*5
        mesh.addPointAndTriangulate((x, y))
        if i % 10 == 0:
            if countOfNotDelTriangles(mesh) > 0:
                print 'ERROR', countOfNotDelTriangles(mesh), '>', x, y
                cv2.imshow('', mesh.draw())
                cv2.imwrite('dump.png', mesh.draw())
                with open('fail_vertexes_dump', 'w') as f:
                    for v in mesh.vertexes:
                        f.write('%d %d\n' % (v.point[0], v.point[1]))
                exit()
                cv2.waitKey(1000)
        if i % 50 == 0:
            print 'i', i
    #cv2.imshow('', mesh.draw())
    print 'End'
    return mesh
예제 #41
0
  def refine(self, mesh):
    """
    Refine mesh.
    """
    self._setupLogging()
    logEvent = "%srefine" % self._loggingPrefix
    self._eventLogger.eventBegin(logEvent)

    newMesh = mesh
    from Mesh import Mesh
    newMesh = Mesh(dim=mesh.dimension(), comm=mesh.comm())
    newMesh.debug(mesh.debug())
    newMesh.coordsys(mesh.coordsys())
    ModuleRefineUniform.refine(self, newMesh, mesh, self.levels)
    if not newMesh == mesh:
      #from pylith.utils.petsc import MemoryLogger
      #memoryLogger =  MemoryLogger.singleton()
    
      #memoryLogger.stagePush(mesh.memLoggingStage)      
      mesh.cleanup()
      #memoryLogger.stagePop()

    self._eventLogger.eventEnd(logEvent)
    return newMesh
예제 #42
0
 def __init__(self, fanout, depth, spread=default_spread, rootColor=default_rootColor, edgeColor=default_edgeColor, scale=default_scale, actor=None):
   Component.__init__(self, actor)
   self.fanout = fanout
   self.depth = depth
   self.spread = spread
   self.rootColor = rootColor
   self.edgeColor = edgeColor
   self.scale = scale
   self.rootScale = self.scale  # NOTE this will also apply to children
   #self.childScale = np.float32([1.0, 1.0, 1.0])  # NOTE this will get compounded if the radial tree is a true hierarchy, better to use scale = 1 (default)
   
   # Recursively generate radial tree
   treeRoot = self.createRadialTree(self.fanout, self.depth, self.spread, isRoot=True)  # creates full hierarchy and returns root actor
   treeRoot.components['Transform'] = Transform(rotation=np.random.uniform(-pi/2, pi/2, size=3), scale=self.rootScale, actor=treeRoot)  # NOTE random rotation ensures child vectors are not always generated close to the same canonical vectors 
   treeRoot.components['Material'] = Material(color=self.rootColor, actor=treeRoot)
   treeRoot.components['Mesh'] = Mesh.getMesh(src=self.treeRootModelFile, actor=treeRoot)
   
   # Attach this hierarchy to current actor
   self.actor.children.append(treeRoot)
예제 #43
0
mepyDir = "E:\\My\\GitHub\\mepy"
import sys

sys.path.append(mepyDir)
import mepy

mepy.CleanCacheModules(mepyDir)

from Mesh import Mesh

mesh = Mesh()
mesh.Name = "polySurface1047"
vertexs = mesh.GetVertexsPos()
for v in vertexs:
    print(v.ToString())
예제 #44
0
파일: ply.py 프로젝트: rbmj/SimpleRender
def parse_ply(fname):
	m = Mesh()
	state = 'init'
	format_re = re.compile('format\\s+ascii\\s+1.0')
	comment_re = re.compile('comment\\s.*')
	element_re = re.compile('element\\s+(?P<name>\\w+)\\s+(?P<num>\\d+)')
	property_re = re.compile('property\\s+(?P<type>\\w+)\\s+(?P<name>\\w+)')
	property_list_re = re.compile('property\\s+list\\s+(?P<itype>\\w+)\\s+(?P<etype>\\w+)\\s+(?P<name>\\w+)')
	element_types = []
	vertex_names = {
		'x': lambda v, x: v.setX(x),
		'y': lambda v, y: v.setY(y),
		'z': lambda v, z: v.setZ(z),
		'nx': lambda v, nx: v.setNX(nx),
		'ny': lambda v, ny: v.setNY(ny),
		'nz': lambda v, nz: v.setNZ(nz),
		's': lambda v, s: v.setS(s),
		't': lambda v, t: v.setT(t)
	}
	face_names = {
		#'vertex_indices': (lambda f, l, m=m: f.set([m.getVertex(v) for v in l])) #real values of vertices
		'vertex_indices': (lambda f, l, m=m: f.set(l))                            #references to vertices
	}
	element_type_dict = {
		'vertex' : (lambda: Vertex(), vertex_names, lambda v, m=m: m.addVertex(v)),
		'face' : (lambda: Face(), face_names, lambda f, m=m: m.addFace(f))
	}
	type_handles = {
		'float' : get_float,
		'double' : get_double,
		'char' : get_char,
		'uchar' : get_uchar,
		'short' : get_short,
		'ushort' : get_ushort,
		'int' : get_int,
		'uint' : get_uint
	}
	i = 0
	j = 0
	for line in open(fname, 'r'):
		line = line.rstrip()
		if state == 'init':
			if line != 'ply':
				raise RuntimeError('PLY: file is not a ply file')
			state = 'format'
		elif state == 'format':
			if not format_re.match(line):
				raise RuntimeError('PLY: unsupported ply format')
			state = 'header'
		elif state == 'header':
			if comment_re.match(line):
				#comment, do nothing
				continue
			match = element_re.match(line)
			if match:
				element_types.append((match.group('name'), int(match.group('num')), []))
				continue
			match = property_list_re.match(line)
			if match:
				element_types[-1][2].append((match.group('name'), 'list', match.group('itype'), match.group('etype')))
				continue
			match = property_re.match(line)
			if match:
				element_types[-1][2].append((match.group('name'), match.group('type')))
				continue
			if line == 'end_header':
				state = 'body'
				continue
			raise RuntimeError('PLY: unknown header field')
		elif state == 'body':
			if j >= element_types[i][1]:
				j = 0
				i = i + 1
			if i >= len(element_types):
				raise RuntimeExeception('PLY: too much data in file')
			line = line.split()
			actions = element_type_dict[element_types[i][0]]
			obj = actions[0]()
			for property in element_types[i][2]:
				x = None
				if property[1] == 'list':
					numelems = type_handles[property[2]](line[0])
					line = line[1:]
					x = []
					for count in range(numelems):
						x.append(type_handles[property[3]](line[0]))
						line = line[1:]
				else:
					x = type_handles[property[1]](line[0])
					line = line[1:]
				actions[1][property[0]](obj, x)
			actions[2](obj)
			j = j + 1
	return m
예제 #45
0
파일: main3.py 프로젝트: Daiver/jff
    res = []
    with open(fname) as f:
        for s in f:
            if len(s) > 1:
                x, y = map(int, s.split())
                res.append((x, y))
    return res
    
scale = 1
if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        points = readPoints(sys.argv[1])
        width = max(points, key=lambda (x, y): x)[0] + 0
        height = max(points, key=lambda (x, y): y)[1] + 0
        mesh = Mesh(width, height)
        for p in points:
            mesh.addPointAndTriangulate(p)
    else:
        mesh = Mesh(600, 600)

    print 'num of errors', test.countOfNotDelTriangles(mesh)

    def mouseClick(event, x, y, f, mesh):
        if event == cv2.EVENT_LBUTTONDOWN:
            print x, y
            point = (x/scale, (y)/scale)
            mesh.addPointAndTriangulate(point)
            cv2.imshow('2', mesh.draw())
            print test.countOfNotDelTriangles(mesh)
            #img1 = cv2.flip(mesh.draw(), 0)
예제 #46
0
 def createRadialTree(self, fanout, depth, spread, isRoot=False):
   if depth <= 0:
     return None
   
   # * Create this node (an actor)
   treeNode = Actor(self.actor.renderer, isTransient=True)
   
   # * Attach children if depth > 1
   if depth > 1:
     if isRoot:
       # ** Pick all random directions first, to ensure a good spread, and then generate children
       childVectors = np.float32(
         [[ -1, -1, -1 ],
          [  1, -1, -1 ],
          [  1,  1, -1 ],
          [ -1,  1, -1 ],
          [ -1, -1,  1 ],
          [  1, -1,  1 ],
          [  1,  1,  1 ],
          [ -1,  1,  1 ]])  # NOTE these canonical directions are same as cube vertices!
       
       # ** Perturb child vectors, and compute unit direction vectors
       perturbation = np.random.normal(scale=1.0, size=childVectors.shape)
       #print "RadialTree.__init__(): Child:-\norig. vectors:\n", childVectors, "\nperturbation :\n", perturbation
       childVectors += perturbation
       #print "pert. vectors:\n", childVectors
       childNorms = np.apply_along_axis(lambda vec:np.linalg.norm(vec, ord=2), 1, childVectors)
       #print "child norms:\n", childNorms
       childUnits = childVectors / childNorms[:, np.newaxis]
       
       # ** Use child unit vectors one by one to create fanout first-level children
       numChildren = fanout if fanout <= childUnits.shape[0] else childUnits.shape[0]  # NOTE assert/enforce: actual fanout <= childUnits.shape[0]
       # TODO randomly pick from child unit vectors without replacement?
       for unit in childUnits[0:numChildren]:
         translation = self.treeEdgeLength * unit
         phi = np.arctan2(-unit[2], unit[0])
         theta = np.arcsin(unit[1])
         rotation = np.degrees(np.float32([ 0, phi, theta ]))  # NOTE random X-axis rotation can be added (but won't make any difference): np.random.uniform(-pi, pi)
         
         #print "RadialTree.__init__(): Child:-\nunit:", unit, "[ norm = ", np.linalg.norm(unit, ord=2), "]\ntranslation:", translation, "\nrotation:", rotation
         childNode = self.createRadialTree(np.random.random_integers(3, 4), depth - 1, spread)  # recurse down, decreasing depth
         childNode.components['Transform'] = Transform(translation=translation, rotation=rotation, actor=childNode)  # NOTE scaling will accumulate, so use scale = 1 (default)
         childNode.components['Material'] = Material(color=self.edgeColor, actor=childNode)
         childNode.components['Mesh'] = Mesh.getMesh(src=self.treeEdgeModelFile, actor=childNode)
         treeNode.children.append(childNode)
     else:
       while len(treeNode.children) < fanout:
         # ** Pick a random direction for creating a new child
         spread_rad = np.radians(spread)
         phi = np.random.uniform(-spread_rad, spread_rad)  # rotation around Y axis
         theta = np.random.uniform(-spread_rad, spread_rad)  # rotation around Z axis
         rotation = np.degrees(np.float32([ 0.0, phi, theta ]))  # this will serve as orientation for the tree edge
         
         # TODO pick a random length; scale X axis accordingly (how? flatten tree hierarchy? pick from discrete lengths and use different models accordingly?)
         
         # ** Compute relative position of new child (in cartesian coordinates) and normalized unit vector
         translation = np.float32([
           self.treeEdgeLength * cos(theta) * cos(phi),
           self.treeEdgeLength * sin(theta),
           -self.treeEdgeLength * cos(theta) * sin(phi)
         ])
         norm = np.linalg.norm(translation, ord=2)
         unit = translation / norm
         
         # TODO check closeness condition (too close to existing nodes? parent? - need absolute coordinates for that!)
         
         # ** Generate and add child (with nested tree)
         childNode = self.createRadialTree(np.random.random_integers(3, 4), depth - 1, spread)  # recurse down, decreasing depth
         childNode.components['Transform'] = Transform(translation=translation, rotation=rotation, actor=childNode)  # NOTE scaling will accumulate, so use scale = 1 (default)
         childNode.components['Material'] = Material(color=self.edgeColor, actor=childNode)
         childNode.components['Mesh'] = Mesh.getMesh(src=self.treeEdgeModelFile, actor=childNode)
         treeNode.children.append(childNode)
   
   return treeNode
예제 #47
0
def Fractal_Tree_3D(param):
    """This fuction creates the fractal tree.
    Args:
        param (Parameters object): this object contains all the parameters that define the tree. See the parameters module documentation for details:
        
    Returns:
        branches (dict): A dictionary that contains all the branches objects.
        nodes (nodes object): the object that contains all the nodes of the tree.
    """
    #Read Mesh
    m=Mesh(param.meshfile)
    #Define the initial direction
    init_dir=(param.second_node-param.init_node)/np.linalg.norm(param.second_node-param.init_node)
    
    #Initialize the nodes object, contains the nodes and all the distance functions
    nodes=Nodes(param.init_node)
    #Project the first node to the mesh.
    point,tri=m.project_new_point(nodes.nodes[0])
    if tri>=0:
        init_tri=tri
    else:
        print 'initial point not in mesh'
        sys.exit(0)
    #Initialize the dictionary that stores the branches objects
    branches={}
    last_branch=0
    #Compute the first branch
    branches[last_branch]=Branch(m,0,init_dir,init_tri,param.init_length,0.0,0.0,nodes,[0],int(param.init_length/param.l_segment))
    branches_to_grow=[]
    branches_to_grow.append(last_branch)
    
    
    ien=[]
    for i_n in range(len(branches[last_branch].nodes)-1):
        ien.append([branches[last_branch].nodes[i_n],branches[last_branch].nodes[i_n+1]]) 
    #To grow fascicles 
    if param.Fascicles:
        brother_nodes=[]    
        brother_nodes+=branches[0].nodes    
        for i_branch in range(len(param.fascicles_angles)):
            last_branch+=1
            angle=param.fascicles_angles[i_branch]
            branches[last_branch]=Branch(m,branches[0].nodes[-1],branches[0].dir,branches[0].tri,param.fascicles_length[i_branch],angle,0.0,nodes,brother_nodes,int(param.fascicles_length[i_branch]/param.l_segment))
            brother_nodes+=branches[last_branch].nodes 
            
            for i_n in range(len(branches[last_branch].nodes)-1):
                ien.append([branches[last_branch].nodes[i_n],branches[last_branch].nodes[i_n+1]])                 
        branches_to_grow=range(1,len(param.fascicles_angles)+1)

        
    for i in range(param.N_it):
        shuffle(branches_to_grow)
        new_branches_to_grow=[]
        for g in branches_to_grow:
            angle=-param.branch_angle*np.random.choice([-1,1])
            for j in range(2):
                brother_nodes=[]
                brother_nodes+=branches[g].nodes
                if j>0:
                    brother_nodes+=branches[last_branch].nodes
                
                #Add new branch
                last_branch+=1
                print last_branch
                l=param.length+np.random.normal(0,param.std_length)
                if l<param.min_length:
                    l=param.min_length
                branches[last_branch]=Branch(m,branches[g].nodes[-1],branches[g].dir,branches[g].tri,l,angle,param.w,nodes,brother_nodes,int(param.length/param.l_segment))
                #Add nodes to IEN
                for i_n in range(len(branches[last_branch].nodes)-1):
                    ien.append([branches[last_branch].nodes[i_n],branches[last_branch].nodes[i_n+1]]) 

                #Add to the new array
                if branches[last_branch].growing:
                    new_branches_to_grow.append(last_branch)
                
                branches[g].child[j]=last_branch
                angle=-angle                
        branches_to_grow=new_branches_to_grow
        
    if param.save:
        if param.save_paraview:
            from ParaviewWriter import write_line_VTU
            print 'Finished growing, writing paraview file'
            xyz=np.zeros((len(nodes.nodes),3))
            for i in range(len(nodes.nodes)):
                xyz[i,:]=nodes.nodes[i]                    
            write_line_VTU(xyz, ien, param.filename + '.vtu')                
        
        np.savetxt(param.filename+'_ien.txt',ien,fmt='%d')
        np.savetxt(param.filename+'_xyz.txt',xyz)
        np.savetxt(param.filename+'_endnodes.txt',nodes.end_nodes,fmt='%d')
        

    return branches,nodes