obj2vtk (2485B)
1 #!/bin/sh 2 3 # Copyright (C) 2026 Centre National de la Recherche Scientifique 4 # Copyright (C) 2026 |Méso|Star> (contact@meso-star.com) 5 # 6 # This program is free software: you can redistribute it and/or modify 7 # it under the terms of the GNU General Public License as published by 8 # the Free Software Foundation, either version 3 of the License, or 9 # (at your option) any later version. 10 # 11 # This program is distributed in the hope that it will be useful, 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 # GNU General Public License for more details. 15 # 16 # You should have received a copy of the GNU General Public License 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. */ 18 19 set -e 20 21 die() 22 { 23 rm -f "${tmp}" # cleanup temporary file 24 exit "${1:-1}" # return status code (default is 1) 25 } 26 27 # Configure signal processing 28 trap 'die $?' EXIT 29 30 usage() 31 { 32 >&2 printf 'usage: obj2vtk [file]\n' 33 } 34 35 ######################################################################## 36 # Conversion script 37 ######################################################################## 38 if [ "$#" -eq 0 ]; then # Read from stdin 39 tmp="$(mktemp "${TMPDIR:-/tmp}/obj2vtk_XXXXXX")" 40 41 awk '$1 ~ "[fv]" {print $1, $2, $3, $4}' > "${tmp}" 42 in="${tmp}" 43 44 elif [ ! -f "$1" ]; then 45 usage 46 die 1 47 48 else 49 in="$1" 50 fi 51 52 nnodes="$(grep -cEe '^[ ]*v[ ]' "${in}" || true)" 53 ncells="$(grep -cEe '^[ ]*f[ ]' "${in}" || true)" 54 55 [ "${ncells}" -eq 0 ] && die 0 # no triangle 56 57 printf '# vtk DataFile Version 2.0\n' 58 printf 'Triangular Mesh\n' 59 printf 'ASCII\n' 60 printf 'DATASET POLYDATA\n' 61 62 printf 'POINTS %s double\n' "${nnodes}" 63 64 # Add a "grep" directive to make the evaluation of the regular 65 # expression and the stream treatment calculations concurrent, so that 66 # they can be executed in parallel. This results in a slight improvement 67 # in performance. 68 grep -Ee '^[ ]*v[ ]' "${in}" | awk '{print $2, $3, $4}' 69 70 printf 'POLYGONS %s %s\n' "${ncells}" "$((ncells*4))" 71 72 # See above to find out why "grep" is used in addition to "awk" 73 # 74 # The numeric conversion performed by awk(1) only takes the first index 75 # of each vertex into account and ignores the others. See strtod(3), 76 # which describes the conversion as it should be performed by awk. 77 # Therefore, a vertex that has a texture and/or normal index is still 78 # correctly handled without any additional processing. 79 grep -Ee '^[ ]*f[ ]' "${in}" | awk '{print 3, $2-1, $3-1, $4-1}' 80 81 die 0