← Back to team overview

yade-users team mailing list archive

Re: [Question #497350]: Export a polyhedron into a *.stl or * .gts file

 

Question #497350 on Yade changed:
https://answers.launchpad.net/yade/+question/497350

    Status: Open => Answered

Jan Stránský proposed the following answer:
Hi Tina,

based on [1] and tested on [2], you can save to stl directly using the
following function. It saves all polyhedrons, if you need just some, it
should be easy to modify it.

############################
def polyhedra2stl(stl): # stl is string file name, e.g. 'test.stl'
  # get triangles
  trisCoords = []
  for b in O.bodies:
    if not isinstance(b.shape,Polyhedra): # skip non-polyhedra bodies
      continue
    vs = [b.state.pos + b.state.ori*v for v in b.shape.v] # vertices in
global coords
    trisIds = b.shape.GetSurfaceTriangulation() # "triangles" in one array
    l = len(trisIds) / 3
    trisIds = [trisIds[3*i:3*i+3] for i in range(l)] # triangles as array
of three indices
    for t in trisIds:
      trisCoords.append([vs[i] for i in t]) # triangles as coords of its
vertices
  # generate content of stl file, see [1]
  lines = ['solid polyhedra']
  for v1,v2,v3 in trisCoords:
    n = (v2-v1).cross(v3-v1)
    lines.append('facet normal {} {} {}'.format(n[0],n[1],n[2]))
    lines.append(' outer loop')
    for v in (v1,v2,v3):
      lines.append('  vertex {} {} {}'.format(v[0],v[1],v[2]))
    lines.append(' endloop')
    lines.append('endfacet')
  lines.append('endsolid polyhedra')
  # write to file
  with open(stl,'w') as f:
    f.writelines(l+'\n' for l in lines)
############################

cheers
Jan

[1] https://en.wikipedia.org/wiki/STL_(file_format)
[2] http://www.viewstl.com/

-- 
You received this question notification because your team yade-users is
an answer contact for Yade.