**Mesh Pattern** Version 1.0 ![](image/final_result.png width="900px") This part of the workshop is discussing how to create mesh tessellation in blender with the help of **pybind(C++)** and **compas(Python)**. Installation ============================================================== ## Mac Before compiling the c++ source code, make sure you have following tools. * `cmake` version >= 3.12 (`brew install cmake`) * `python` version >= 3.7 (after install anaconda, it will automatically install python3.7) * `anaconda` version >= 2019.03 ([download link](https://www.anaconda.com/distribution/#download-section)) * `blender` version >= 2.8.0 ([download link](https://builder.blender.org/download)) Then, use anaconda to create a new python environment named "blender" `````` sh $ conda config --add channels conda-forge $ conda create --name blender python=3.7 compas $ conda activate blender $ pip install tessagon `````` Confirm the current python version is 3.7 by typing `python --version` in terminal and replace blender's python (the directory of blender could be different in your computer, please change it accordingly): `````` sh $ cd /Applications/blender/blender.app/Contents/Resources/2.80 $ mv python original_python $ ln -s $CONDA_PREFIX python `````` It is better to add blender directory into system enviroment variable `PATH`: `````` sh $ nano ~/.bash_profile # `add one line in the .bash_profile` export PATH=/Applications/blender/blender.app/Contents/MacOS:$PATH $ source ~/.bash_profile & conda activate blender `````` Last thing before compiling is to change the settings `PYTHON_EXECUTABLE` of `CMakeLists.txt` in project folder to the new created python enviroment (you can get it by typing `which python` in the terminal`. `````` C #set(PYTHON_EXECUTABLE "$ENV{HOME}/anaconda3/envs/blender/bin/python3.7") set(PYTHON_EXECUTABLE YOUR_PYTHON_BIN_FILE_PATH) `````` Finally, it is time to compile the C++ source code. Please first `cd` to the project folder. `````` sh $ mkdir build $ cd build $ cmake -DCMAKE_BUILD_TYPE=Release .. $ make -j4 `````` If no error occurs, we can open the blender file in `/blender/MeshPattern.blender` and click `Run Script` Button, which will give the the following result: ![](image/blender_init.png) ## Windows Before compiling the c++ source code, make sure you have following tools. * `Visual Studio 2017` * `python` version >= 3.7 (after install anaconda, it will automatically install python3.7) * `anaconda` version >= 2019.03 ([download link](https://www.anaconda.com/distribution/#download-section)) * `blender` version >= 2.8.0 ([download link](https://builder.blender.org/download)) Visual Studio 2017: 1. Download Visual Studio 2017 2. Open Visual Studio 2017. Click "Tools" - "Get Tools and Feature" to open the Visual Studio Installer. 3. Choose Use C++ and Linux Developement options which would download necessary cmake component. Create Conda Enviroment ``` console $ conda config --add channels conda-forge $ conda create --name blender python=3.7 compas $ conda activate blender $ pip install tessagon ``` Replace Blender Python ``` sh $ cd %PROGRAMFILES%\Blender Foundation\Blender\2.80 $ ren python original_python $ mklink /j python %CONDA_PREFIX% ``` Compile C++ Source Code 1. Open Visual Studio 2017 2. In menu, "File" - "Open" - "CMake", open CMakeList.txt in the project folder 3. In menu, "CMake" - "Build All" 4. Don't forgot to change compile mode from Debug to Release. Run Blender 1. Open `blender/MeshPattern.blender` 2. Click `Run Script` Load Mesh ============================================================== The compas library offer us an easy way to load mesh from file. ([compas mesh](https://compas-dev.github.io/main/tutorials/meshes.html)) ````````````````````````````````````````````` py # you can change here to import your own file, like : # surfaceOBJ = Mesh.from_obj(dir_path + '/../data/igloo.obj') surfaceOBJ = Mesh.from_obj(dir_path + '/../data/minimal_surface.obj') ````````````````````````````````````````````` To link the input mesh into scene, compas also offer us some very useful function. ([compas_blender.utilities](https://compas-dev.github.io/main/api/compas_blender.utilities.html)) ````````````````````````````````````````````` #getting the vertices and faces list from compas mesh vertices, faces = surfaceOBJ.to_vertices_and_faces() #draw the mesh in the blender scene drawMeshVF(vertices, faces) ````````````````````````````````````````````` Here the input mesh is not correct oriented in blender because in OBJ file, the down screen (gravity) direction is usually -Y instead of -Z in blender. To correct this, add followings after load mesh code. ````````````````````````````````````````````` py # iterate each vertex in compas mesh and swap its Y and Z coordinate for key, attr in surfaceOBJ.vertices(True): y = attr['y'] attr['y'] = -attr['z'] attr['z'] = y ````````````````````````````````````````````` Rerun the `Run Script` and a correct oriented mesh should be rendered on your screen. ![](image/load_mesh.png width = 500px) Simple Parametrization ============================================================== Open the file in `src/iglMesh.h`, you will found we already create a simple interface between `libigl` and `compas`. ``````````````````` C++ void loadMesh(vector> &_vertices, vector>& _faces); vector> getVertices(); vector> getUVs(); vector> getFaces(); ``````````````````` Assume we can get the data from compas library and we want to make some process on the mesh. For example, compute the uv texture coordinates for this mesh and store it in the `iglMesh` variable `UV_`. Go to the unimplemented function `void parametrization_simple()` in `src/iglMesh.cpp`. Instead of thinking a fancy parametrization strategy, we first directly map the 3D coordinate $(x, y, z) \rightarrow (x, y)$ and scale the 2D points into a square $[0, 1]\times[0, 1]$. Following code will do the job: ``````````````````` C++ void iglMesh::parametrization_simple() { UV_.setZero(); UV_ = V_.leftCols(2); Eigen::Vector2d min_coeff, max_coeff; min_coeff = UV_.colwise().minCoeff(); max_coeff = UV_.colwise().maxCoeff(); for(int id = 0; id < UV_.rows(); id++) { UV_(id, 0) = (UV_(id, 0) - min_coeff(0)) / (max_coeff(0) - min_coeff(0)); UV_(id, 1) = (UV_(id, 1) - min_coeff(1)) / (max_coeff(1) - min_coeff(1)); } } ``````````````````` You can try to re-compile your program, but you will not be able to use this function in the python. It is because we have not linked this function through pybind. Go to the file `src/MeshPattern.cpp` and add one more line: ```````````````````` C++ py::class_(m, "iglMesh") .def(py::init()) .def("loadMesh", &iglMesh::loadMesh) .def("getUVs", &iglMesh::getUVs) .def("getVertices", &iglMesh::getVertices) .def("getFaces", &iglMesh::getFaces) //add one more line here, link the parametrization_simple through pybind .def("parametrization_simple", &iglMesh::parametrization_simple); ```````````````````` Let see whether we can use this new created function in the blender. First, recompile the whole project and go the the `blender/MeshPattern.blender`. Change the code of main function and run the script. ``````````````` py if __name__ == "__main__": # you can change here to import your own file, like : # surfaceOBJ = Mesh.from_obj(dir_path + '/../data/igloo.obj') surfaceOBJ = Mesh.from_obj(dir_path + '/../data/minimal_surface.obj') # iterate each vertex in compas mesh and swap its Y and Z for key, attr in surfaceOBJ.vertices(True): y = attr['y'] attr['y'] = -attr['z'] attr['z'] = y #getting the vertices and faces list from compas mesh vertices, faces = surfaceOBJ.to_vertices_and_faces() #load iglMesh mesh = iglMesh() mesh.loadMesh(vertices, faces) #do parametrization mesh.parametrization_simple() #output uv and face vertices = mesh.getUVs() faces = mesh.getFaces() #draw the mesh in the blender scene drawMeshVF(vertices, faces) ``````````````` ![](image/parametrization_simple.png width = 500px) 2D Tessellation ============================================================== Tessagon is a python library which can create surface tessellation. However, it requires the parametric representation of the surface which limits its applicable range for general triangle mesh. Despite this, we can easily use this library to create 2D pattern. Change the code of main function in blender and run the script. ```````` py if __name__ == "__main__": # read 2d hexagon pattern [vertices, faces] = create2DPattern() drawMeshVF(vertices, faces) ```````` ![](image/2dpattern.png width = 500px) Lift 2D Pattern into 3D ============================================================== ![](image/pattern_texture.png width = 400px) Drawing the 2D pattern and parameterization mesh in a same image, some 2D hexagons locates outside of the parameterization area. Therefore, those hexagons should be ignored when we lift the pattern into 3D. To simplify the process, we only accept those hexagons which vertices are all inside the parameterization area and remove the rest hexagons. Libigl barycentric coordinate function can help us easy handle this task. ## Barycentric Coordinate ![](image/barycentric.png width = 400px) the barycentric coordiante $(\alpha, \beta, \gamma), \alpha + \beta + \gamma = 1$ describe where a point $P$ locates with respect to a triangle ($A, B , C$) . $$ P = \alpha A + \beta B + \gamma C $$ For example, the barycentric coordinate of point $P_1(\frac{1}{3}, \frac{1}{3}, \frac{1}{3})$, $P_2(0, \frac{1}{2}, \frac{1}{2})$, $P_3(\frac{1}{2} + \frac{1}{2\sqrt{3}}, -\frac{1}{\sqrt{3}}, \frac{1}{2} + \frac{1}{2\sqrt{3}})$. In fact for a non degenerate triangle: * all coordinate within $(0, 1)$ means point is inside the triangle * at least one coordinate equals to $0$ means point is on the boundary of the triangle * at least one coordinate is negative means point is outside the triangle. Given a point in 2D, we can determine whether its is inside the parametrization area if there exists at least one triangle of the area where the given point's barycentric coordinate have negative components. in `src/iglMesh.h`, create a new function called: `````` C++ //check the input point pt if is inside the UV space of this mesh //if true return barycentric coordinate and the which triangle this point is belong to. //else return false bool mapPoint3D_simple(Eigen::Vector3d pt, Eigen::Vector3d &barycentric, int &faceID); `````` and in `src/iglMesh.cpp` complete this function: `````````` C++ bool iglMesh::mapPoint3D_simple(Eigen::Vector3d pt, Eigen::Vector3d &l, int &faceID){ if(UV_.isZero()) { return false; } else{ Eigen::MatrixXd P(1, 3), L(1, 3); P << pt(0), pt(1), pt(2); for(int id = 0; id < F_.rows(); id++) { Eigen::MatrixXd A, B, C; getTriFace(id, UV_, A, B, C); igl::barycentric_coordinates(P, A, B, C, L); if(L.minCoeff() < -1e-5 || L.maxCoeff() > 1 + 1e-5){ continue; } else{ l = L.row(0); faceID = id; return true; } } } return false; } `````````` ## Lift 2D Pattern To map from 2D to 3D, store the triange id in uv-space which the point is belong to and recompute the position of the point by using the same barycentric coordinate for the triangle with same id from the original input mesh. in `src/iglMesh.h`, create a new function called: ``````` C++ void mapMesh3D_simple(iglMesh &baseMesh); ``````` and in `src/iglMesh.cpp` do the following: ``````` C++ oid iglMesh::mapMesh3D_simple(iglMesh &baseMesh) { if(UV_.isZero()){ parametrization_simple(); } vector inMesh; int count = 0; for(int id = 0; id < baseMesh.V_.rows(); id++) { Eigen::Vector3d pt = baseMesh.V_.row(id); Eigen::Vector3d l(0, 0, 0); int faceID = -1; if(mapPoint3D_simple(pt, l, faceID)) { Eigen::MatrixXd A, B, C; getTriFace(faceID, V_, A, B, C); baseMesh.V_.row(id) = A.row(0) * l(0) + B.row(0) * l(1) + C.row(0) * l(2); inMesh.push_back(true); } else{ inMesh.push_back(false); } } for(auto it = baseMesh.faces_.begin(); it != baseMesh.faces_.end();) { bool all_in_refMesh = true; for(int jd = 0; jd < (*it).size(); jd++) { int vid = (*it)[jd]; if(inMesh[vid] == false){ all_in_refMesh = false; break; } } if(!all_in_refMesh) { it = baseMesh.faces_.erase(it); } else{ it++; } } baseMesh.cleanMesh(); } ``````` and do not forget to link this function through pybind and recompile C++ source code, in `src/MeshPattern.cpp` ``````` C++ .def("mapMesh3D_simple", &iglMesh::mapMesh3D_simple) ``````` ## Blender in blender, rewrite the main function: ``````` py if __name__ == "__main__": [vertices, faces] = create2DPattern() pattern2D = iglMesh() pattern2D.loadMesh(vertices, faces) # you can change here to import your own file, like : # surfaceOBJ = Mesh.from_obj(dir_path + '/../data/igloo.obj') surfaceOBJ = Mesh.from_obj(dir_path + '/../data/minimal_surface.obj') # iterate each vertex in compas mesh and swap its Y and Z for key, attr in surfaceOBJ.vertices(True): y = attr['y'] attr['y'] = -attr['z'] attr['z'] = y #getting the vertices and faces list from compas mesh vertices, faces = surfaceOBJ.to_vertices_and_faces() #load iglMesh mesh = iglMesh() mesh.loadMesh(vertices, faces) #do parametrization mesh.parametrization_simple() #do lift mesh.mapMesh3D_simple(pattern2D) vertices = pattern2D.getVertices() faces = pattern2D.getFaces() #draw the mesh in the blender scene drawMeshVF(vertices, faces) ``````` Yeah! We have our first mesh tessellation result: ![](image/mesh_tessellation.png width=500px) Advanced Topics ============================================================== ## Conformal Mapping Libigl offers other advanced parametrization algorithm, like least-square conformal mapping. in `src/iglMesh.h` create a new function ````` C++ void parametrization_lscm(); ````` and in `src/iglMesh.cpp` ````` C++ void iglMesh::parametrization_lscm() { UV_.setZero(); Eigen::VectorXi bnd,b(2); igl::boundary_loop(F_,bnd); b(0) = bnd(0); b(1) = bnd(((int)round(bnd.size() / 2))); MatrixXd bc(2,2); bc<<0,0,1,0; igl::lscm(V_,F_,b,bc,UV_); Eigen::Vector2d min_coeff, max_coeff; min_coeff = UV_.colwise().minCoeff(); max_coeff = UV_.colwise().maxCoeff(); for(int id = 0; id < UV_.rows(); id++) { UV_(id, 0) = (UV_(id, 0) - min_coeff(0)); UV_(id, 1) = (UV_(id, 1) - min_coeff(1)); } return; } ````` and don't forgot to link this function through pybind as well as change the parameterization part in blender python code. ![Simple Map](image/simple_map.png width = 500px) ![Conformal Map](image/conformal_map.png width = 500px) ## AABB Tree You probably feel the running time of this mesh tessellation is a little bit too long. This is because we need to check every pattern vertices whether is inside one of the triangle in parametrization area. To reduce the time complexity, applying `libigl AABB` datastructure can accelerate the process by hundred times. in `src/iglMesh.h` add ````` C++ void mapMesh3D_AABB(iglMesh &baseMesh); ````` and in `src/iglMesh.cpp` ````` C++ void iglMesh::mapMesh3D_AABB(iglMesh &baseMesh) { if(UV_.isZero()){ parametrization_lscm(); } igl::AABB< MatrixXd, 2 > tree; tree.init(UV_, F_); vector inMesh; baseMesh.parametrization_simple(); MatrixXd C; Eigen::VectorXi I; Eigen::VectorXd sqrD; tree.squared_distance(UV_, F_, baseMesh.UV_, sqrD, I, C); for(int id = 0; id < baseMesh.UV_.rows(); id++) { if(std::fabs(sqrD[id]) < 1e-5) { Eigen::MatrixXd A, B, C, L, P(1, 3); P << baseMesh.UV_(id, 0), baseMesh.UV_(id, 1), 0; getTriFace(I(id), UV_, A, B, C); igl::barycentric_coordinates(P, A, B, C, L); inMesh.push_back(true); getTriFace(I(id), V_, A, B, C); baseMesh.V_.row(id) = A.row(0) * L(0, 0) + B.row(0) * L(0, 1) + C.row(0) * L(0, 2); } else{ inMesh.push_back(false); } } for(vector>::iterator it = baseMesh.faces_.begin(); it != baseMesh.faces_.end();) { bool all_in_refMesh = true; for(int jd = 0; jd < (*it).size(); jd++) { int vid = (*it)[jd]; if(inMesh[vid] == false){ all_in_refMesh = false; break; } } if(!all_in_refMesh){ it = baseMesh.faces_.erase(it); } else{ it++; } } baseMesh.cleanMesh(); } ````` and don't forgot to link this function through pybind as well as change the parameterization part in blender python code. ## ShapeOp ShapeOp is a tool for optimizing polygonal mesh's planarity, regularity, ... etc. I already write a simple wrap in `src/ShapeOpt.h` which includes * addPlanarConstraint * addRegularConstraint * addBoundaryConstraint To use it, in blender add these code after lift the pattern in 3D. ````` py #ShapeOp solver = ShapeOpt() solver.loadMesh(pattern2D) solver.addPlanarConstraint(1.0) solver.addRegularConstraint(1.0) solver.addBoundaryConstraint(1.0) solver.runShapeOp(10) pattern3D = solver.getMesh() vertices = pattern3D.getVertices() faces = pattern3D.getFaces() ````` ![Before Opt](image/before_opt.png width = 500px) ![After Opt](image/after_opt.png width = 500px) ## Wireframe I found the draw cylinder commands of compas is extremly slow. So I write a simple C++ code to create wireframe of the tessellated mesh. in `src/iglMesh.h` `````` C++ iglMesh saveWireFrame(double thickness, int cylinder_pts); `````` and in `src/iglMesh.cpp` `````` C++ iglMesh iglMesh::saveWireFrame(double thickness, int cylinder_pts) { MatrixXi E; igl::edges(F_, E); vector> vv; vv.resize(V_.rows()); for(int id = 0; id < faces_.size(); id++){ for(int jd = 0; jd < faces_[id].size(); jd++){ int prev = (jd - 1 + faces_[id].size()) % faces_[id].size(); int next = (jd + 1) % faces_[id].size(); vv[faces_[id][jd]].push_back(faces_[id][prev]); vv[faces_[id][jd]].push_back(faces_[id][next]); } } vector> vers; vector> faces; for(int id = 0; id < E.rows(); id++) { int sta = E(id, 0); int end = E(id, 1); Vector3d staPt = V_.row(sta); Vector3d endPt = V_.row(end); if(std::any_of(vv[sta].begin(), vv[sta].end(), [=](int a){return a == end;})) { Vector3d z_axis = endPt - staPt; z_axis /= (z_axis).norm(); Vector3d x_axis = Vector3d(0, 1, 0).cross(z_axis); if(x_axis.norm() < 1e-4) x_axis = Vector3d(1, 0, 0).cross(z_axis); x_axis /= z_axis.norm(); Vector3d y_axis = z_axis.cross(x_axis); y_axis /= y_axis.norm(); for(int id = 0; id < cylinder_pts; id++) { float angle0 = 2 * 3.1415926/cylinder_pts * id; float angle1 = 2 * 3.1415926/cylinder_pts * (id + 1); Vector3d v_sta0 = staPt + x_axis * thickness * cos(angle0) + y_axis * thickness * sin(angle0); Vector3d v_sta1 = staPt + x_axis * thickness * cos(angle1) + y_axis * thickness * sin(angle1); Vector3d v_end0 = v_sta0 + (endPt - staPt); Vector3d v_end1 = v_sta1 + (endPt - staPt); int f = vers.size(); vers.push_back({v_sta0(0),v_sta0(1), v_sta0(2)}); vers.push_back({v_sta1(0),v_sta1(1), v_sta1(2)}); vers.push_back({v_end1(0),v_end1(1), v_end1(2)}); vers.push_back({v_end0(0),v_end0(1), v_end0(2)}); faces.push_back({f, f + 1, f + 2, f + 3}); } } } iglMesh mesh; mesh.loadMesh(vers, faces); return mesh; } ``````` ![](image/wireframe.png width = 600px) ## Final Blender Python File ``````py if __name__ == "__main__": [vertices, faces] = create2DPattern() pattern2D = iglMesh() pattern2D.loadMesh(vertices, faces) # you can change here to import your own file, like : # surfaceOBJ = Mesh.from_obj(dir_path + '/../data/igloo.obj') surfaceOBJ = Mesh.from_obj(dir_path + '/../data/minimal_surface.obj') # iterate each vertex in compas mesh and swap its Y and Z for key, attr in surfaceOBJ.vertices(True): y = attr['y'] attr['y'] = -attr['z'] attr['z'] = y #getting the vertices and faces list from compas mesh vertices, faces = surfaceOBJ.to_vertices_and_faces() #load iglMesh mesh = iglMesh() mesh.loadMesh(vertices, faces) #do parametrization mesh.parametrization_lscm() #do lift mesh.mapMesh3D_AABB(pattern2D) vertices = pattern2D.getVertices() faces = pattern2D.getFaces() #do shapeop #ShapeOp solver = ShapeOpt() solver.loadMesh(pattern2D) solver.addPlanarConstraint(1.0) solver.addRegularConstraint(1.0) solver.addBoundaryConstraint(1.0) solver.runShapeOp(10) pattern3D = solver.getMesh() vertices = pattern3D.getVertices() faces = pattern3D.getFaces() #output wireframe wire = pattern3D.saveWireFrame(0.01, 10) vertices = wire.getVertices() faces = wire.getFaces() #draw the mesh in the blender scene drawMeshVF(vertices, faces) ``````