NuMRI/codes/MATLAB/leo/writemesh.m

98 lines
2.8 KiB
Matlab
Executable File

function writemesh(varargin)
%% writemesh(path, mesh)
% Save triangulation as path.xml and path.msh
% mesh is a struct with fields Pts, Tet, Tri
% alernatively one can use writemesh(path, Pts, Tet, Tri)
% Pts should by a n times 3 matrix consisting points of the mesh
% Tet is the m times 4 matrix consisting the tetrahedra
% Tri is the l times 3 matrix consisting the triangles at the boundary
if nargin > 3
mesh.Pts=varargin{2};
mesh.Tet=varargin{3};
mesh.Tri=varargin{4};
writemesh(varargin{1},mesh,varargin(nargin));
elseif isstruct(varargin{2})
rootMeshFile = varargin{1};
% NEW FILE
obj = [rootMeshFile,'.msh'];
meshfile = fopen(obj,'w');
obj2 = [rootMeshFile,'.xml'];
xmlfile = fopen(obj2,'w');
% MESH
fprintf(meshfile,['$MeshFormat','\n']);
fprintf(meshfile,['2.2 0 8','\n']);
fprintf(meshfile,['$EndMeshFormat','\n']);
fprintf(xmlfile,['<?xml version="1.0" encoding="UTF-8"?>','\n']);
fprintf(xmlfile,'\n');
fprintf(xmlfile,['<dolfin xmlns:dolfin="http://www.fenicsproject.org">','\n']);
mesh = varargin{2};
Nodes = mesh.('Pts');
mesh = rmfield(mesh,'Pts');
Nodes = [(1:size(Nodes,1))' Nodes(:,1:3)];
% POINTS
if ~strcmp(varargin{nargin},'mute')
disp('Write Points')
end
fprintf(meshfile,['$Nodes','\n']);
fprintf(meshfile,['%i','\n'],size(Nodes,1));
fprintf(xmlfile,[' <mesh celltype="tetrahedron" dim="3">','\n']);
fprintf(xmlfile,[' <vertices size="%i">','\n'],size(Nodes,1));
fprintf(meshfile,'%i %13.6f %13.6f %13.6f\n',Nodes');
Nodes(:,1) = Nodes(:,1) - 1;
fprintf(xmlfile,' <vertex index="%i" x="%0.16e" y="%0.16e" z="%0.16e"/>\n',Nodes');
fprintf(meshfile,['$EndNodes','\n']);
fprintf(meshfile,['$Elements','\n']);
fprintf(meshfile,['%i','\n'],size(mesh.Tet,1)+size(mesh.Tri,1));
fprintf(xmlfile,[' </vertices>','\n']);
fprintf(xmlfile,[' <cells size="%i">','\n'],size(mesh.Tet,1));
% Triangles
if ~strcmp(varargin{nargin},'mute')
disp('Write Triangles')
end
tri = mesh.('Tri');
tri = [(1:size(tri,1))' 2*ones(size(tri,1),1) 2*ones(size(tri,1),1) zeros(size(tri,1),1) 2*ones(size(tri,1),1) tri(:,1:3)];
fprintf(meshfile,'%i %i %i %i %i %i %i %i\n',tri');
% Tetrahedra
if ~strcmp(varargin{nargin},'mute')
disp('Write Tetrahedra')
end
tet = mesh.('Tet');
tet = [(size(tri,1)+1:size(tri,1)+size(tet,1))' 4*ones(size(tet,1),1) 2*ones(size(tet,1),1) zeros(size(tet,1),1) ones(size(tet,1),1) tet(:,1:4)];
fprintf(meshfile,'%i %i %i %i %i %i %i %i %i\n',tet');
tet = mesh.('Tet');
tet = [(0:size(tet,1)-1)' (tet(:,1:4)-1)];
fprintf(xmlfile,' <tetrahedron index="%i" v0="%i" v1="%i" v2="%i" v3="%i"/>\n',tet');
fprintf(meshfile,['$EndElements','\n']);
fprintf(xmlfile,' </cells>\n </mesh>\n</dolfin>\n');
fclose('all');
end