Example #1
0
def run():
    clear()
    wireframe()

    a = 5 # verdeelparameter
    x = -((1-sqrt(5))/2) # gulden getal
    s = 30. # overspanning
    m = 5; b = 360./m # pentacap (script nog vervolledigen zodat m andere waarden kan aannemen)
    k1 = 0.035 # steilte
    hoek = (90.-b)/2
    d = 2. # laagdikte
    c = (x*s+k1*s*s/2*sin(radians(2*hoek)))/(k1*s*cos(radians(hoek))+k1*s*sin(radians(hoek))) # pentacapvoorwaarde

    # compret van 1 blad
    T = Formex([[[-a,0,d],[-a+2,0,d]],[[-a,0,d],[1-a,3,d]],[[1-a,3,d],[2-a,0,d]]],1)
    B = Formex([[[1-a,-1,0],[3-a,-1,0]],[[1-a,-1,0],[2-a,2,0]],[[2-a,2,0],[3-a,-1,0]]],2)
    W1 = Formex([[[2-a,2,0],[1-a,3,d]],[[2-a,2,0],[3-a,3,d]],[[2-a,2,0],[2-a,0,d]]])
    W2 = Formex([[[1-a,-1,0],[-a,0,d]],[[1-a,-1,0],[2-a,0,d]],[[1-a,-1,0],[1-a,-3,d]]])
    W3 = Formex([[[0,3*a,d],[0,3*(a-1)-1,0]]])
    top = T.replic2(a,a,2,3,bias=1,taper=-1).reflect(1,0,True).unique()
    bot = B.replic2(a-1,a-1,2,3,bias=1,taper=-1).reflect(1,-1,True).unique()
    web = W1.replic2(a-1,a-1,2,3,bias=1,taper=-1) + W2.replic2(a,a,2,-3,bias=1,taper=-1) + W3
    blad = (top+bot+web).scale([1.,1./3,1.]).translate([0,a,0])
    # herschalen
    vlakblad = blad.scale([s*sin(radians(b/2))/a,s*cos(radians(b/2))/a,1.]).rotate(-45.)
    # transleren en mappen op hyperbolische paraboloide (z=k1*x*y)
    vlakblad2=vlakblad.translate([-c,-c,0])
    j=vlakblad2.map(lambda x,y,z:[x,y,k1*x*y])
    #overige bladen genereren
    hyparcap=j.translate([c,c,0]).rosette(m,360/m,2,[0.,0.,0.])
    draw(hyparcap)
Example #2
0
def sliceBranch(S, cp, s0, s1, cl, nslices):
    """Slice a single branch of the bifurcation

    - `S`: the bifurcation surface, oriented parallel to xy.
    - `cp` : the center of the bifurcation.
    - `s0`, `s1`: the control polylines along the branch.
    - `cl`: the centerline of the branch.
    - `nslices`: the number of slices used to approximate the branch
      surface.
    """
    visual = drawOption('visual')

    cl = cl.approx(ntot=nslices)
    s0 = s0.approx(ntot=nslices)
    s1 = s1.approx(ntot=nslices)

    h0 = slicer(S, s0, cl, cutat=-1, visual=visual)
    if visual:
        clear()
        draw(h0, color='black')
    h1 = slicer(S, cl, s1, cutat=-1, visual=visual)
    #    if visual:
    #        draw(h0,color='red')
    #        draw(h1,color='blue')
    return [h0, h1]
Example #3
0
 def showDeformation():
     clear()
     linewidth(1)
     draw(F,color=black)
     linewidth(3)
     deformed_plot(optimscale)
     view('last',True)
Example #4
0
def createScene(text=None, caged=True, color=None, move=0):
    """Create a scene of the story.

    The scene draws the horse (H), with the specified color number (0..7),
    caged or not, with the local axes (CS), and possibly a text.
    If move > 0, the horse moves before the scene is drawn.
    The horse and cage actors are returned.
    """
    global line, H, C, CS
    if move:
        H, C, CS = [
            i.rotate(30, 1).rotate(-10., 2).translate([0., -move * 0.1, 0.])
            for i in [H, C, CS]
        ]

    if caged:
        cage = draw(
            C,
            mode='wireframe',
            wait=False,
        )
    else:
        cage = None
    if color is None:
        color = 1 + random.randint(6)
    H.setProp(color)
    horse = draw(H)
    if text:
        drawText(text, 20, line, size=20)
        line += line_inc
    axes = drawAxes(CS, size=0.4, draw_planes=False)
    zoomAll()
    zoom(0.7)
    return horse, cage
Example #5
0
def spliner():
    """Slice the surface to a sequence of cross sections."""
    import olist
    from plugins.curve import BezierSpline
    S = selection.check(single=True)
    if not S:
        return
    res = askItems([_I('Direction',[1.,0.,0.]),
                    _I('# slices',20),
                    _I('remove_invalid',False),
                    ],caption = 'Define the slicing planes')
    if res:
        axis = res['Direction']
        nslices = res['# slices']
        remove_cruft = res['remove_invalid']
        pf.GUI.setBusy(True)
        slices = S.slice(dir=axis,nplanes=nslices)
        pf.GUI.setBusy(False)
        print([ s.nelems() for s in slices ])
        split = [ s.splitProp() for s in slices if s.nelems() > 0 ]
        split = olist.flatten(split)
        hasnan = [ isnan(s.coords).any() for s in split ]
        print(hasnan)
        print(sum(hasnan))
        #print [s.closed for s in split]
        export({'%s/split' % selection[0]:split})
        draw(split,color='blue',bbox='last',view=None)
        splines = [ BezierSpline(s.coords[s.elems[:,0]],closed=True) for s in split ]
        draw(splines,color='red',bbox='last',view=None)
        export({'%s/splines' % selection[0]:splines})
Example #6
0
def fillBorders():
    _data_ = _name_+'fillBorders_data'
    S = showBorder()
    try:
        B = named('border')
    except:
        return
    if B:
        props = [ b.prop[0] for b in B ]
        dia = Dialog([
            _I('Fill which borders',itemtype='radio',choices=['All','One']),
            _I('Filling method',itemtype='radio',choices=['radial','border']),
            _I('merge',False,text='Merge fills into current surface'),
            ])
        if _data_ in pf.PF:
            dia.updateData(pf.PF[_data_])
        res = dia.getResults()
        if res:
            pf.PF[_data_] = res

            if res['Fill which borders'] == 'One':
                B = B[:1]
            fills = [ fillBorder(b,method=res['Filling method']).setProp(i+1) for i,b in enumerate(B) ]
            if res['merge']:
                name = selection.names[0]
                S = named(name)
                for f in fills:
                    S += f
                export({name:S})
                selection.draw()
            else:
                draw(fills)
                export(dict([('fill-%s'%i,f) for i,f in enumerate(fills)]))
Example #7
0
def run():
    clear()
    flat()
    reset()
    examples = {
        'Square': square_example,
        'Rectangle': rectangle_example,
        'Circle': circle_example,
        'CloseLoop': close_loop_example,
    }

    res = askItems([
        _I('example', text='Select an example', choices=examples.keys()),
    ])
    if res:
        F = examples[res['example']]()
        if F is None:
            return
        draw(F)
        S = sectionChar(F)
        S.update(extendedSectionChar(S))
        print(mydict.CDict(S))
        G = Formex([[[S['xG'], S['yG']]]])
        draw(G, bbox='last')
        showaxes([S['xG'], S['yG'], 0.], S['alpha'], F.dsize(), 'red')
Example #8
0
def run():
    layout(2)
    wireframe()

    # draw in viewport 0
    viewport(0)
    view('front')
    clear()
    rtri = Formex('3:016932').scale([1.5,1,0])
    F = rtri + rtri.shear(0,1,-0.5).trl(0,-4.0) + rtri.shear(0,1,0.75).trl(0,3.0)
    draw(F)

    drawCircles(F,triangleCircumCircle,color=red)
    zoomAll()   
    drawCircles(F,triangleInCircle,color=blue)
    drawCircles(F,triangleBoundingCircle,color=black)
    zoomAll()   


    # draw in viewport 1
    viewport(1)
    view('iso')
    clear()
    F,c = cube_tri()
    draw(F)
    drawCircles(F,triangleInCircle)
    zoomAll()   

    if not ack("Keep both viewports ?"):
        print("Removing a viewport")
        # remove last viewport
        removeViewport()
Example #9
0
def run():
    m = 36  # number of cells along torus big circle
    n = 36  # number of cells along torus small circle
    message("Create a triangle with three colored members")
    F = Formex('l:164', [1, 2, 3])
    clear()
    draw(F)
    pause()
    message("Replicate it into a rectangular pattern")
    F = F.replic2(m, n, 1, 1)
    clear()
    draw(F)
    pause()
    message("Fold the rectangle into a tube")
    G = F.translate(2, 1).cylindrical([2, 1, 0], [1., 360. / n, 1.])
    clear()
    draw(G, view='right')
    pause()
    message("Bend the tube into a torus with mean radius 5")
    H = G.translate(0, 5).cylindrical([0, 2, 1], [1., 360. / m, 1.])
    clear()
    draw(H, view='iso')
    pause()
    message("Cut a part from the torus")

    K = H.cutWithPlane([0., 2., 0.], [1., 1., 1.], side='-')
    clear()
    draw(K)
Example #10
0
def run():
    clear()
    wireframe()
    n = 10
    a = 2. / 3.
    d = 1. / n
    e1 = Formex([[[0, 0, d], [2, 0, d]], [[2, 0, d], [1, 1, d]],
                 [[1, 1, d], [0, 0, d]]],
                prop=1)
    e2 = Formex([[[0, 0, d], [1, 1 - a, 0]], [[2, 0, d], [1, 1 - a, 0]],
                 [[1, 1, d], [1, 1 - a, 0]]],
                prop=3)
    # top and bottom layers
    e4 = e1.replic2(n, n, 2, 1, bias=1, taper=-1).bb(1. / (2 * n),
                                                     1. / (2 * n) / tand(30))
    e5 = e1.replic2(n - 1, n - 1, 2, 1, bias=1,
                    taper=-1).translate([1, 1 - a,
                                         -d]).bb(1. / (2 * n),
                                                 1. / (2 * n) / tand(30))
    # diagonals
    e6 = e2.replic2(n, n, 2, 1, bias=1, taper=-1).bb(1. / (2 * n),
                                                     1. / (2 * n) / tand(30))
    e5.setProp(2)
    # full structure
    out = (e4 + e5 + e6).translate(2, -d)
    draw(out)
Example #11
0
def run():
    clear()
    smoothwire()

    # The object to reposition
    A = Formex('4:0123', 1).replic2(6, 3)
    # The object to define the position
    B = Formex('3:016', 2).replic2(4, 4, taper=-1).trl(0, 7.)

    drawObjectWithName(A, 'Object A')
    drawObjectWithName(B, 'Object B')

    #define matching points

    X = A[0, [0, 3, 1]]
    drawPointsNumbered(X, red, 'X')

    Y = B[3, [1, 2, 0]]
    Y[2] = Y[0].trl([0., 1., 1.])
    drawPointsNumbered(Y, green, 'Y')
    zoomAll()

    pause()

    # Reposition A so that X are aligned with Y
    C = A.position(X, Y)
    draw(C, color=blue)
    zoomAll()
Example #12
0
def run():
    reset()
    smoothwire()

    res = askItems([
        dict(name='m', value=12, text='number of modules in axial direction'),
        dict(name='n',
             value=8,
             text='number of modules in tangential direction'),
        dict(name='r', value=10., text='barrel radius'),
        dict(name='a', value=180., text='barrel opening angle'),
        dict(name='l', value=30., text='barrel length'),
        dict(name='eltype',
             value='quad8',
             text='element type',
             itemtype='radio',
             choices=['tri3', 'quad4', 'quad8', 'quad9']),
    ])
    if not res:
        return

    globals().update(res)

    # Grid
    g = Formex('4:0123').replic2(m, n).toMesh().convert(eltype)

    # Create barrel
    barrel = g.rotate(90, 1).translate(0, r).scale([1., a / n,
                                                    l / m]).cylindrical()

    draw(barrel, color=red, bkcolor=blue)

    export({'Barrel': barrel})
Example #13
0
    def update(self):
        """Perform every updates of the game logic, events handling and drawing.
        Also known as the game loop."""

        # Events handling
        for event in pygame.event.get():
            event_handlers = [
                self._event_quit,
                gui.event_handler
            ]

            for handler in event_handlers:
                if handler(event):
                    break

        # Drawings
        self.window.blit(self.images['window'], self.images['window'].get_rect())

        self._draw_name_input()
        self._draw_classes_selector()
        self._draw_abilities()
        self._draw_skills()

        gui.draw(self.window)

        # PyGame-related updates
        pygame.display.update()

        self.clock.tick(settings.FPS)
Example #14
0
def drawAxis(len,dir,text):
    """Draw an axis of given length and direction annotated with text."""
    F = Formex('l:1').scale(len).rotate(dir)
    #T = F[0][1].scale(1.1)
    draw(F,linewidth=2.0)
    drawText3D(F[0][1]+(2.,-0.5,0.),text,size=18)
    return F
Example #15
0
def RotatingCircle():
    """Rotating Circle

    When staring at the cross in the middle,
    the disappearing magenta circles create the illusion of a green
    rotating circle. If you keep concentrating your gaze on the centre,
    the green circle wil seem to devour the magenta circle, up to a point
    where you no longer see the magenta circles.
    Blinking or changing your focus will immediately undo the effect.
    """
    resetview([0.8,0.8,0.8])
    ask = askItems([('Number of circles',12),('Radius of circles',1.2),('Radius of the figure',12),('Number of rotations',16),('color of circles',[1.0,0.40,1.0]),('Sleep time',0.03),('Zoom',14.)])
    if not ask: return
    N = ask['Number of circles']
    r = ask['Radius of circles']
    R = ask['Radius of the figure']
    n = ask['Number of rotations']
    col = ask['color of circles']
    sl = ask['Sleep time']
    sc = ask['Zoom']
    box=[[-sc,-sc,-sc],[sc,sc,sc]]
    draw(shape('plus'),bbox=box)
    F = sector(r,360.,1,16).trl(0,R).rosette(N-1,360./N)
    delay(sl)
    for i in range(n*N):
        F = F.rotate(-360./N)
        dr = draw(F,color=col,bbox=box)
        if i>0: undraw(DR)
        DR=dr
Example #16
0
def run():
    """Ask the user for data and show the corresponding Wire Stent."""
    wireframe()
    reset()

    res = askItems([
        _I('L', 80., text='Length of the stent'),
        _I('D', 10., text='Diameter of the stent'),
        _I('n', 12, text='Total number of wires'),
        _I('b', 30., text='Pitch angle of the wires'),
        _I('d', 0.2, text='Diameter of the wires'),
        _I('show', itemtype='radio', choices=['Formex', 'Curves']),
    ])

    if not res:
        return

    globals().update(res)
    if (n % 2) != 0:
        warning('Number of wires must be even!')
        return

    H = DoubleHelixStent(D, L, d, n, b)
    clear()

    if show == 'Formex':
        draw(H.getFormex(), view='iso')

    else:
        view('iso')
        for w, c in zip(H.getWireAxes(), ['black', 'magenta']):
            draw(w, color=c)
Example #17
0
def Cussion():
    """Cussion

    This is a powerful illusion, though again some color combinations might
    not work as well as others.
    The smaller squares on this 'chessboard' tend to give a distortion.
    Again, all horizontal and vertical lines are perfectly parallel and
    straight!
    """
    resetview()
    b,h = 17,17
    if b%2==0: b+=1
    if h%2==0: h+=1
    chess = Formex('4:0123').replic2(b,h,1,1).translate([-b/2+0.5,-h/2+0.5,0])
    col=[random.rand(3),random.rand(3)]
    sq1 = Formex('4:0123').scale([0.25,0.25,1]).translate([-0.45,0.2,0])
    sq2 = Formex('4:0123').scale([0.25,0.25,1]).translate([0.2,-0.45,0])
    F = sq1.translate([1,0,0]).replic(int(b/2)-1,1)+sq2.translate([0,1,0]).replic(int(h/2)-1,1,dir=1)
    sq = sq1+sq2
    for i in range(int(b/2)):
        for j in range(int(h/2)):
            if i+j < (int(b/2)+int(b/2))/2-1: F += sq.translate([i+1,j+1,0])
    colors=ndarray([0,0])
    for i in F:
        if (int(i[0,0])+int(i[0,1])-1)%2 == 0: colors=append(colors,col[1])
        else: colors=append(colors,col[0])
    colors= colors.reshape(-1,3)
    F = F.rosette(4,90)
    draw(F,color=colors.reshape(-1,3))
    draw(chess,color=col)
Example #18
0
def MotionInducedBlindness():
    """Motion Induced Blindness

    This is a very nice illusion.
    Look at the centre of the image.
    The moving background will give the illusion that the other static points
    disappear.
    Blinking or changing your focus will immediately undo the effect.
    Cool huh?
    """
    resetview('black')
    res = askItems([('Number of static points',10),('Background',None,'radio',{'choices':['Tiles','Structured points','Random points']}),('Rotations',2),('Rotation angle',2),('Number of random points',300)])
    if not res: return
    nr,a,rot,back,n = res['Number of random points'],res['Rotation angle'],res['Rotations'],res['Background'],res['Number of static points']
    draw(shape('star').scale(0.4),color=red,linewidth=2)
    points = Formex([[0,-10,0]]).rosette(n,360./n)
    draw(points,color=random.rand(3),marksize=10)
    col=random.rand(3)
    if back=='Tiles': F = shape('plus').replic2(11,11,3,3).translate([-15,-15,0])
    elif back=='Structured points': F = Formex([[0,0,0]]).replic2(30,30,1).translate([-15,-15,0])
    else: F = Formex(random.rand((nr,3))).scale([30,30,0]).translate([-15,-15,0])
    for i in range(rot*360/a):
        F = F.rotate(a)
        dr = draw(F,color=col,linewidth=2,bbox=[[-10,-10,0],[10,10,0]])
        if i>0: undraw(DR)
        DR = dr
Example #19
0
def run():
    global barrel
    reset()
    wireframe()

    res = askItems([
        dict(name='m', value=10, text='number of modules in axial direction'),
        dict(name='n',
             value=8,
             text='number of modules in tangential direction'),
        dict(name='r', value=10., text='barrel radius'),
        dict(name='a', value=180., text='barrel opening angle'),
        dict(name='l', value=30., text='barrel length'),
    ])
    if not res:
        return

    globals().update(res)

    # Diagonals
    d = Formex('l:5', 1).rosette(4, 90).translate([1, 1,
                                                   0]).replic2(m, n, 2, 2)
    # Longitudinals
    h = Formex('l:1', 3).replic2(2 * m, 2 * n + 1, 1, 1)
    # End bars
    e = Formex('l:2', 0).replic2(2, 2 * n, 2 * m, 1)
    # Create barrel
    barrel = (d + h + e).rotate(90, 1).translate(0, r).scale(
        [1., a / (2 * n), l / (2 * m)]).cylindrical()

    draw(barrel)
Example #20
0
def RunningInCircles():
    """Running In Circles

    If you don't look directly at the rectangles, both rectangles will
    appear to 'overtake' each other constantly, although they are moving
    at equal and constant speed.
    """
    resetview()
    box= [[-8,-8,-8],[8,8,8]]
    N = 72
    R = 10
    C = circle(a1=360./N).points()
    O =[0,0,0]
    F = Formex([[C[i],C[i+1],O] for i in arange(0,2*N,2)]).scale([R,R,0])
    F.setProp([0,7])
    p = circle(a1=360./N).points()
    centre = Formex([add(p[0:len(p):2],p[-1])]).translate([-1,0,0])
    centre.setProp(1)
    draw(centre,bbox=box)
    draw(F,bbox=box)
    b1 = Formex('4:0123').scale([1.5,0.8,0]).translate([0,8.5,0.1])
    b1.setProp(3)
    b2 = Formex('4:0123').scale([1.5,0.8,0]).translate([0,7,0.1])
    b2.setProp(6)
    b = b1+b2
    col = [random.rand(3)/3,[1,1,1]-random.rand(3)/8]
    for i in range(4*N):
        b = b.rotate(360./N/4)
        dr = draw(b,bbox=box,color=col)
        if i>0:
            undraw(DR)
        DR = dr
Example #21
0
def run():
    layout(2)
    wireframe()

    # draw in viewport 0
    viewport(0)
    view('front')
    clear()
    rtri = Formex('3:016932').scale([1.5, 1, 0])
    F = rtri + rtri.shear(0, 1, -0.5).trl(0, -4.0) + rtri.shear(
        0, 1, 0.75).trl(0, 3.0)
    draw(F)

    drawCircles(F, triangleCircumCircle, color=red)
    zoomAll()
    drawCircles(F, triangleInCircle, color=blue)
    drawCircles(F, triangleBoundingCircle, color=black)
    zoomAll()

    # draw in viewport 1
    viewport(1)
    view('iso')
    clear()
    F, c = cube_tri()
    draw(F)
    drawCircles(F, triangleInCircle)
    zoomAll()

    if not ack("Keep both viewports ?"):
        print("Removing a viewport")
        # remove last viewport
        removeViewport()
def showSurfaceValue(S,txt,val,onEdges):
    val = nan_to_num(val)
    mi,ma = val.min(),val.max()
    print(mi,ma)
    # Test: replace min with max
    dec = min(abs(mi),abs(ma))
    print(dec)
    if dec > 0.0:
        dec = max(0,3-int(log10(dec)))
    else:
        dec = 2
    # create a colorscale and draw the colorlegend
    CS = ColorScale('RAINBOW',mi,ma,0.5*(mi+ma),1.)
    cval = array(map(CS.color,ravel(val)))
    cval = cval.reshape(append(val.shape,cval.shape[-1]))
    clear()
    if onEdges:
        F = Formex(S.coords[S.getEdges()])
        draw(F,color=cval)#,linewidth=2)
    else:
        draw(S,color=cval)
    lights(False)
    CL = ColorLegend(CS,100)
    CLA = decors.ColorLegend(CL,10,10,30,200,dec=dec) 
    GD.canvas.addDecoration(CLA)
    drawtext(txt,10,230,'hv18')
Example #23
0
def create():
    """Create a closed surface and a set of points."""
    nx,ny,nz = npts

    # Create surface
    if surface == 'file':
        S = TriSurface.read(filename).centered()
    elif surface == 'sphere':
        S = simple.sphere(ndiv=grade)

    if refine > S.nedges():
        S = S.refine(refine)

    draw(S, color='red')

    if not S.isClosedManifold():
        warning("This is not a closed manifold surface. Try another.")
        return None,None

    # Create points

    if points == 'grid':
        P = simple.regularGrid([-1.,-1.,-1.],[1., 1., 1.],[nx-1,ny-1,nz-1])
    else:
        P = random.rand(nx*ny*nz*3)

    sc = array(scale)
    siz = array(S.sizes())
    tr = array(trl)
    P = Formex(P.reshape(-1, 3)).resized(sc*siz).centered().translate(tr*siz)
    draw(P, marksize=1, color='black')
    zoomAll()

    return S,P
Example #24
0
def run():
    global barrel
    reset()
    wireframe()
    
    res = askItems([
        dict(name='m',value=10,text='number of modules in axial direction'),
        dict(name='n',value=8,text='number of modules in tangential direction'),
        dict(name='r',value=10.,text='barrel radius'),
        dict(name='a',value=180.,text='barrel opening angle'),
        dict(name='l',value=30.,text='barrel length'),
        ])
    if not res:
        return

    globals().update(res)

    # Diagonals
    d = Formex('l:5',1).rosette(4,90).translate([1,1,0]).replic2(m,n,2,2)
    # Longitudinals
    h = Formex('l:1',3).replic2(2*m,2*n+1,1,1)
    # End bars
    e = Formex('l:2',0).replic2(2,2*n,2*m,1)
    # Create barrel
    barrel = (d+h+e).rotate(90,1).translate(0,r).scale([1.,a/(2*n),l/(2*m)]).cylindrical()

    draw(barrel)
Example #25
0
def run():
    reset()
    smooth()
    lights(True)

    S = TriSurface.read(getcfg('datadir')+'/horse.off')
    SA = draw(S)

    res = askItems([
        ('direction',[1.,0.,0.]),
        ('number of sections',20),
        ('color','red'),
        ('ontop',False),
        ('remove surface',False),
        ]) 
    if not res:
        return

    d = res['direction']
    n = res['number of sections']
    c = res['color']

    slices = S.slice(dir=d,nplanes=n)
    linewidth(2)
    draw(slices,color=c,view=None,bbox='last',nolight=True,ontop=res['ontop'])
    export({'_HorseSlice_slices':slices})
    
    if res['remove surface']:
        undraw(SA)
        
    zoomAll()
Example #26
0
def convertToFormex():
    """Convert all dxf parts to a plex-2 Formex

    This uses the :func:`dxf.toLines` function to transform all Lines, Arcs
    and PolyLines to a plex-2 Formex. 
    The parameters chordal and arcdiv used to set the precision of the
    Arc approximation are asked from the user..
    """
    parts = named('_dxf_sel_')
    if not parts:
        return
    res = askItems(
        [  _I('method',choices=['chordal error','fixed number'],tooltip="What method should be used to approximate the Arcs by straight line segments."),
           _I('chordal',0.01),
           _I('ndiv',8),
           ],
        enablers = [
            ('method','chordal error','chordal'),
            ('method','fixed number','ndiv'),
            ]
        )
    if res:
        chordal = res['chordal']
        if res['method'][0] == 'c':
            ndiv = None
        else:
            ndiv = res['ndiv']

        coll = dxf.collectByType(parts)
        lines = dxf.toLines(chordal=chordal,arcdiv=ndiv)
        print("Number of lines: %s" % _lines.nelems())
        export({'_dxf_lines_':lines})

        clear()
        draw(lines)
def clip_surface():
    """Clip the stl model."""
    if not check_surface():
        return
    itemlist = [['axis',0],['begin',0.0],['end',1.0],['nodes','any']]
    res = askItems(itemlist,caption='Clipping Parameters')
    if res:
        updateGUI()
        nodes,elems = PF['old_surface'] = PF['surface']
        F = Formex(nodes[elems])
        bb = F.bbox()
        GD.message("Original bbox: %s" % bb) 
        xmi = bb[0][0]
        xma = bb[1][0]
        dx = xma-xmi
        axis = int(res[0][1])
        xc1 = xmi + float(res[1][1]) * dx
        xc2 = xmi + float(res[2][1]) * dx
        nodid = res[3][1]
        #print(nodid)
        clear()
        draw(F,color='yellow')
        w = F.test(nodes='any',dir=axis,min=xc1,max=xc2)
        F = F.clip(w)
        draw(F,color='red')
Example #28
0
def run():
    items = [
        widgets.simpleInputItem(n,
                                globals()[n])
        for n in ['r0', 'r1', 'h', 't', 'nr', 'nt']
    ] + [
        widgets.simpleInputItem(
            'diag', diag, itemtype='radio', choices=['', 'u', 'd'])
    ]
    dialog = widgets.InputDialog(items)

    while not dialog.result() == widgets.TIMEOUT:
        res = dialog.getResults()
        if not res:
            break

        globals().update(res)
        F = cone(r0, r1, h, t, nr, nt, diag)
        G = cone1(r0, r1, h, t, nr, nt,
                  diag).swapAxes(1, 2).trl(0, 2 * max(r0, r1))
        G.setProp(1)
        H = F + G
        clear()
        draw(H)
        return
Example #29
0
def sliceBranch(S,cp,s0,s1,cl,nslices):
    """Slice a single branch of the bifurcation

    - `S`: the bifurcation surface, oriented parallel to xy.
    - `cp` : the center of the bifurcation.
    - `s0`, `s1`: the control polylines along the branch.
    - `cl`: the centerline of the branch.
    - `nslices`: the number of slices used to approximate the branch
      surface.
    """
    visual = drawOption('visual')

    cl = cl.approx(ntot=nslices)
    s0 = s0.approx(ntot=nslices)
    s1 = s1.approx(ntot=nslices)

    h0 = slicer(S,s0,cl,cutat=-1,visual=visual)
    if visual:
        clear()
        draw(h0,color='black')
    h1 = slicer(S,cl,s1,cutat=-1,visual=visual)
#    if visual:
#        draw(h0,color='red')
#        draw(h1,color='blue')
    return [h0,h1]
Example #30
0
def undo_stl():
    """Undo the last transformation."""
    global F,oldF
    clear()
    linewidth(1)
    F = oldF
    draw(F,color='green')
Example #31
0
def run():
    clear()
    smoothwire()

    # The object to reposition
    A = Formex('4:0123',1).replic2(6,3)
    # The object to define the position
    B = Formex('3:016',2).replic2(4,4,taper=-1).trl(0,7.)

    drawObjectWithName(A,'Object A')
    drawObjectWithName(B,'Object B')

    #define matching points

    X = A[0,[0,3,1]]
    drawPointsNumbered(X,red,'X')

    Y = B[3,[1,2,0]]
    Y[2] = Y[0].trl([0.,1.,1.])
    drawPointsNumbered(Y,green,'Y')
    zoomAll()

    pause()

    # Reposition A so that X are aligned with Y
    C = A.position(X,Y)
    draw(C,color=blue)
    zoomAll()
Example #32
0
def ShadesOfGrey():
    """Shades Of Grey

    Our perception of brightness is relative.
    Therefore, the figure on the left looks a little darker than the one right.
    The effect can be somewhat subtle though.
    """
    resetview([0.8,0.8,0.8])
    sc = 2
    box = [[-2,0,-2],[2,8,2]]
    back = Formex('4:0123').scale([8,8,1])
    back += back.translate([-8,0,0])
    back.setProp([0,7])
    C = circle(a1=11.25).rotate(-90,2).points()
    F = Formex([[C[i],C[i+1],2*C[i+1],2*C[i]] for i in range(0,32,2)]).translate([2,4,0])
    n = 40
    for i in range(n):
        F = F.translate([-2./n,0,0])
        G = F.reflect(0)
        dr1 = draw(F+G,color=[0.6,0.6,0.6],bbox=box)
        dr2 = draw(back,bbox=box)
        if i>0:
            undraw(DR2)
            undraw(DR1)
        else:
            sleep(2)
        DR1 = dr1
        DR2 = dr2
Example #33
0
def cutPart(M, x0, x1):
    """Cut part of section at plane thru x0 and return part between x0 and x1"""
    M = M.clipAtPlane(x1, x0 - x1, nodes='all')

    meshlist = M.splitProp()

    meshlist = [meshToPolyLine2(m) for m in meshlist]
    #meshlist = [ p.cutWithPlane(x0,x1-x0,side='+') for p in meshlist ]
    draw(meshlist, flat=True, alpha=1, linewidth=3)

    #print erf
    meshlist = olist.flatten(meshlist)
    if len(meshlist) == 1:
        pl = meshlist[0]
    elif len(meshlist) == 2:
        p1, p0 = meshlist
        pl = PolyLine(Coords.concatenate([p0.coords, p1.coords]))
    else:
        print([p.nelems() for p in meshlist])
        [
            draw(p, color=c)
            for p, c in zip(meshlist, pf.canvas.settings.colormap)
        ]
        pl = longestItem(meshlist)
    return pl
Example #34
0
def drawCSys(ax=Formex([[[1., 0., 0.]],[[0., 1., 0.]],[[0., 0., 1.]], [[0., 0., 0.]]]), color='black'):
    """it draws the coordinate system with origin in ax[0] and directions determined by the 3 points in ax[1:4]"""
    assex=array([ax[3], ax[0]])
    assey=array([ax[3], ax[1]])
    assez=array([ax[3], ax[2]])
    for asse in [assex, assey, assez]:draw(Formex(asse.reshape(1, 2, 3)), color=color)
    drawNumbers(Formex([assex[1], assey[1],assez[1] ]))#
Example #35
0
def run():
    reset()
    smoothwire()

    res = askItems([
        dict(name='m',value=12,text='number of modules in axial direction'),
        dict(name='n',value=8,text='number of modules in tangential direction'),
        dict(name='r',value=10.,text='barrel radius'),
        dict(name='a',value=180.,text='barrel opening angle'),
        dict(name='l',value=30.,text='barrel length'),
        dict(name='eltype',value='quad8',text='element type',itemtype='radio',choices=['tri3','quad4','quad8','quad9']),
        ])
    if not res:
        return

    globals().update(res)

    # Grid
    g = Formex('4:0123').replic2(m,n).toMesh().convert(eltype)

    # Create barrel
    barrel = g.rotate(90,1).translate(0,r).scale([1.,a/n,l/m]).cylindrical()

    draw(barrel,color=red,bkcolor=blue)

    export({'Barrel':barrel})
Example #36
0
def series():
    view='iso'
    for n in [3,4,6,8,12]:
        for m in [3,4,6,12,36]:
            clear()
            draw(torus(m,n),view)
            view=None
Example #37
0
def inputLongitudinalSeeds():
    """Interactive input of the longitudinal meshing seeds.

    """
    global dialog

    def show():
        """Show the current seeds"""
        global dialog, SA
        undraw(SA)
        dialog.acceptData()
        res = dialog.results
        if not res:
            return
        sat = [
            seeding3zones(nseeds=eval(res['nseeds%s' % i]),
                          zonesizes=eval(res['ratios%s' % i]))
            for i in range(3)
        ]
        print('# of seeds in branches: %s' %
              [sum([len(i) for i in j]) - 1 for j in sat])
        SA = drawLongitudinalSeeding(long_splines, sat)
        return sat

    def accept():
        """Accept the current seeds"""
        sat = show()
        if sat:
            export({'sat': [concatenate(ati) for ati in sat]})
        dialog.accept()

    def help():
        showInfo(
            "Set the seeding parameters for the 3 branches. Each branch is divided in 3 parts: close to the bifurcation, far from the bifurcation and the central part between these two. Only the data for the first two need to be entered. The 3rd (central) is calculated as transition."
        )

    clear()
    long_splines = named('long_splines')
    draw(long_splines, linewidth=1, color='gray', flat=True, alpha=1)
    drawNumbers(
        Formex([long_splines[i][0].subPoints(1)[-1] for i in [0, 2, 4]]))

    nseeds = '[5,3 ]'
    ratios = '[0.3, 0.4]'
    dialog = Dialog(
        caption='Ratio Seeding Spline',
        items=[
            _I('nseeds0', nseeds),
            _I('ratios0', ratios),
            _I('nseeds1', nseeds),
            _I('ratios1', ratios),
            _I('nseeds2', nseeds),
            _I('ratios2', ratios),
        ],
        actions=[('Cancel', ), ('Show', show), ('Accept', accept),
                 ('Help', help)],
    )
    dialog.move(100, 100)
    dialog.getResults()
 def showModel(self,nodes=True,elems=True):
     if nodes:
         Fn = Formex(self.DB.nodes)
         draw(Fn)
     if elems:
         Fe = [ Formex(self.DB.nodes[e],i+1) for i,e in enumerate(self.DB.elems.itervalues()) ]
         draw(Fe)
     zoomAll()
Example #39
0
def drawFrame(P):
    """Draw a dashed frame at position P."""
    d,e = (2,3) # dash length and step
    h = Formex('l:1').scale(d)
    v = h.rotate(-90).replic(4,-e,1)
    h = h.replic(6,e,0)
    frame = (h + v).trl(P)
    draw(frame,linewidth=1.0,bbox=None)
Example #40
0
def drawHelperLines():
    branch = named('branch')
    for i in range(3):
        draw(branch[2 * i:2 * i + 2],
             color=['red', 'green', 'blue'][i],
             flat=True,
             alpha=1,
             linewidth=3)
Example #41
0
def drawCrossSplines():
    sp = getData('cross_splines')
    if drawOption('fill_cross'):
        [draw(Formex([si.coords for si in s]),color='black' ,flat=True, alpha=1) for s in sp]
    else:
        [draw(s,color=c,flat=True, alpha=1) for s,c in zip(sp,color_half_branch)]
        if drawOption('numbers'):
            [[drawNumbers(si.coords) for si in s] for s in sp]
Example #42
0
 def drawTransform(transform):
     print("Transforming grid")
     trf = transforms[transform]
     G = trf(F)
     clear()
     print("Drawing Colored grid")
     draw(G,color=color,colormap=colortable)
     drawText('Created with pyFormex',20,20,size=24)
Example #43
0
    def drawChanges(self):
        """Draws old and new version of a Formex with differrent colors.

        old and new can be a either Formex instances or names or lists thereof.
        old are drawn in yellow, new in the current color.
        """
        self.draw(wait=False)
        draw(self.values,color='yellow',bbox=None,clear=False,shrink=self.shrink)
Example #44
0
def run():

    # Locate calpy and load interface
    from plugins import calpy_itf
    try:
        Q = calpy_itf.QuadInterpolator
    except:
        print("NO CALPY: I'm out of here!")
        return

    # Now, let's create a grid of 'quad8' elements
    # size of the grid
    nx, ny = 4, 3
    # plexitude
    nplex = 8
    clear()
    flatwire()
    M = Formex('4:0123').replic2(nx, ny).toMesh().convert('quad%s' % nplex,
                                                          fuse=True)
    #draw(M,color=yellow)

    # Create the Mesh interpolateor
    gprule = (5, 1)  # integration rule: minimum (1,1),  maximum (5,5)
    Q = calpy_itf.QuadInterpolator(M.nelems(), M.nplex(), gprule)

    # Define some random data at the GP.
    # We use 3 data per GP, because we will use the data directly as colors
    ngp = prod(gprule)  # number of datapoints per element
    data = random.rand(M.nelems(), ngp, 3)
    print("Number of data points per element: %s" % ngp)
    print("Original element data: %s" % str(data.shape))
    # compute the data at the nodes, per element
    endata = Q.GP2Nodes(data)
    print("Element nodal data: %s" % str(endata.shape))
    # compute nodal averages
    nodata = Q.NodalAvg(M.elems + 1, endata, M.nnodes())
    print("Average nodal data: %s" % str(nodata.shape))
    # extract the colors per element
    colors = nodata[M.elems]
    print("Color data: %s" % str(colors.shape))
    layout(2)

    viewport(0)
    clear()
    smoothwire()
    lights(False)
    draw(M, color=endata)
    drawNumbers(M.coords)
    drawText("Per element interpolation", 20, 20, font='9x15')

    viewport(1)
    clear()
    smoothwire()
    lights(False)
    draw(M, color=colors)
    drawNumbers(M.coords)
    drawText("Averaged nodal values", 20, 20, font='9x15')
Example #45
0
def readProperties(fn=None):
    """Read properties from file."""
    if not fn:
        fn = askFilename(filter="Property files (*.prop)")
    if fn:
        p = fromfile(fn, sep=',')
        F.setProp(p)
        clear()
        draw(F)
def drawSelection(*args,**kargs):
    """Draws the current selection.

    Any arguments are passed to draw()"""
    clear()
    if selection:
        draw(selection,*args,**kargs)
        if show_numbers:
            showSelectionNumbers()
def drawChanges():
    """Draws old and new version of a Formex with differrent colors.

    old and new can be a either Formex instances or names or lists thereof.
    old are drawn in yellow, new in the current color.
    """
    clear()
    draw(selection, wait=False)
    draw(oldvalues, color="yellow", bbox=None)
Example #48
0
def surfMesh():
    spc = getData('cross_splines')
    Fspc = [[ci.toFormex() for ci in c] for c in spc]
    surf = [[
        connect([Fi, Fi, Fj, Fj], nodid=[0, 1, 1, 0])
        for Fi, Fj in zip(f[:-1], f[1:])
    ] for f in Fspc]
    draw(surf)
    export({'surface_mesh': surf})
Example #49
0
def drawSpiralCurves(PL, nwires, color1, color2=None):
    if color2 is None:
        color2 = color1
    # Convert to Formex, because that has a rosette() method
    PL = PL.toFormex()
    if nwires > 1:
        PL = PL.rosette(nwires, 360. / nwires)
    draw(PL, color=color1)
    draw(PL.points(), color=color2)
Example #50
0
def run():
    reset()
    smoothwire()

    res = askItems([
        ('w', 2, {
            'text': 'width'
        }),
        ('l', 30, {
            'text': 'length'
        }),
        ('n', 1, {
            'text': 'number of turns'
        }),
    ])
    if not res:
        return

    globals().update(res)

    C = Formex('l:1234')
    cell = connect([C, C, C, C], bias=[0, 1, 2, 3])
    strip = cell.replic2(l, w, 1., 1.).translate(1, -0.5 * w)
    TA = draw(strip, color='orange', bkcolor='red')

    sleep(1)

    nsteps = 40
    step = n * 180. / nsteps / l
    for i in arange(nsteps + 1):
        a = i * step
        torded = strip.map(
            lambda x, y, z: [x, y * cosd(x * a), y * sind(x * a)])
        TB = draw(torded, color='orange', bkcolor='red')
        undraw(TA)
        TA = TB

    sleep(1)
    #TA = None
    nsteps = 60
    step = 360. / nsteps
    for i in arange(1, nsteps + 1):
        ring = torded.trl(2, l * nsteps / pi / i).scale(
            [i * step / l, 1., 1.]).trl(0, -90).cylindrical(dir=[2, 0, 1])
        TB = draw(ring, color='orange', bkcolor='red')
        undraw(TA)
        TA = TB

    sleep(1)
    nsteps = 80
    step = 720. / nsteps
    for i in arange(1, nsteps + 1):
        mobius = ring.rotate(i * step, 1)
        TB = draw(mobius, color='orange', bkcolor='red', bbox='last')
        undraw(TA)
        TA = TB
Example #51
0
def drawCentralPoint():
    cp = named('central_point')
    print("Central Point = %s" % cp)
    draw(cp,
         bbox='last',
         color='black',
         marksize=8,
         flat=True,
         alpha=1,
         ontop=True)
Example #52
0
def drawCSys(ax=Formex([[[1., 0., 0.]], [[0., 1., 0.]], [[0., 0., 1.]],
                        [[0., 0., 0.]]]),
             color='black'):
    """it draws the coordinate system with origin in ax[0] and directions determined by the 3 points in ax[1:4]"""
    assex = array([ax[3], ax[0]])
    assey = array([ax[3], ax[1]])
    assez = array([ax[3], ax[2]])
    for asse in [assex, assey, assez]:
        draw(Formex(asse.reshape(1, 2, 3)), color=color)
    drawNumbers(Formex([assex[1], assey[1], assez[1]]))  #
Example #53
0
def showCube(base, color):
    #print base,color
    if base == 'Triangle':
        cube = cube_tri
    else:
        cube = cube_quad
    cube, color = cube(color)
    clear()
    draw(cube, color=color)
    export({'cube': cube})