1 meshlab documentation

64
1 MeshLab Documentation ALIGNMENT....................................................................................................................................... 6 SMALL TUTORIAL .............................................................................................................................................. 6 TRANSFER FUNCTION ....................................................................................................................................... 7 EQUALIZER.......................................................................................................................................................... 7 TUTORIALS ........................................................................................................................................ 8 STRESSING THE CURVATURE OF A MESH ....................................................................................................... 8 GIVING A TONE TO A MESH ............................................................................................................................... 8 APPLYING THE SAME MAPPING TO SEVERAL MESHES ................................................................................. 8 FEATURES............................................................................................................................................................ 9 SAMPLE USAGE................................................................................................................................................... 9 Basics ..................................................................................................................................................................9 Simple Straightening ................................................................................................................................ 10 Layer Composition ..................................................................................................................................... 10 Special Features .......................................................................................................................................... 10 POINT PICKING TOOL..................................................................................................................................... 11 Description .................................................................................................................................................... 11 Use With "Align Mesh using Picked Points" filter......................................................................... 12 Notes for Developers who want to use picked points in their plugin .................................. 12 Other information ...................................................................................................................................... 12 PREREQUISITIES.............................................................................................................................................. 13 Hole Selection: ............................................................................................................................................. 13 Hole Filling: ................................................................................................................................................... 13 Hole Bridging: .............................................................................................................................................. 13 Non Manifold Hole Splitting: ................................................................................................................. 14 Data Structures ........................................................................................................................................... 14 Mark interesting faces ............................................................................................................................. 14 Bridges bulding issue ................................................................................................................................ 15 POINT PICKING TOOL..................................................................................................................................... 30 Description .................................................................................................................................................... 30 Use With "Align Mesh using Picked Points" filter......................................................................... 31 Notes for Developers who want to use picked points in their plugin .................................. 31 Other information ...................................................................................................................................... 31 MORPHER TOOL.............................................................................................................................................. 31 Description .................................................................................................................................................... 31 Details ............................................................................................................................................................. 31 Other information ...................................................................................................................................... 32 QHULL FILTER ............................................................................................................................... 32 GENERAL DESCRIPTION................................................................................................................................. 32 FUNCTION FILTER LIST ................................................................................................................................. 33 Convex Hull ................................................................................................................................................... 33 Delaunay Triangulation .......................................................................................................................... 33 Voronoi Filtering ........................................................................................................................................ 33 Alpha Shapes ................................................................................................................................................ 34 Select Visible Points ................................................................................................................................... 35 SUPPORTED FORMATS ............................................................................................................... 35 IMPORT ............................................................................................................................................................. 36 EXPORT ............................................................................................................................................................. 36 COMPILING DEVEL ....................................................................................................................... 36 WHAT YOU NEED.......................................................................................................................... 36

Upload: tranminh

Post on 31-Dec-2016

242 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 MeshLab Documentation

1

MeshLabDocumentationALIGNMENT.......................................................................................................................................6SMALLTUTORIAL .............................................................................................................................................. 6TRANSFERFUNCTION ....................................................................................................................................... 7EQUALIZER.......................................................................................................................................................... 7

TUTORIALS........................................................................................................................................8STRESSINGTHECURVATUREOFAMESH ....................................................................................................... 8GIVINGATONETOAMESH............................................................................................................................... 8APPLYINGTHESAMEMAPPINGTOSEVERALMESHES ................................................................................. 8FEATURES............................................................................................................................................................ 9SAMPLEUSAGE................................................................................................................................................... 9Basics ..................................................................................................................................................................9SimpleStraightening................................................................................................................................10LayerComposition.....................................................................................................................................10SpecialFeatures..........................................................................................................................................10

POINTPICKINGTOOL..................................................................................................................................... 11Description....................................................................................................................................................11UseWith"AlignMeshusingPickedPoints"filter.........................................................................12NotesforDeveloperswhowanttousepickedpointsintheirplugin ..................................12Otherinformation......................................................................................................................................12

PREREQUISITIES.............................................................................................................................................. 13HoleSelection: .............................................................................................................................................13HoleFilling:...................................................................................................................................................13HoleBridging:..............................................................................................................................................13NonManifoldHoleSplitting:.................................................................................................................14DataStructures...........................................................................................................................................14Markinterestingfaces .............................................................................................................................14Bridgesbuldingissue................................................................................................................................15

POINTPICKINGTOOL..................................................................................................................................... 30Description....................................................................................................................................................30UseWith"AlignMeshusingPickedPoints"filter.........................................................................31NotesforDeveloperswhowanttousepickedpointsintheirplugin ..................................31Otherinformation......................................................................................................................................31

MORPHERTOOL.............................................................................................................................................. 31Description....................................................................................................................................................31Details .............................................................................................................................................................31Otherinformation......................................................................................................................................32

QHULLFILTER............................................................................................................................... 32GENERALDESCRIPTION................................................................................................................................. 32FUNCTIONFILTERLIST ................................................................................................................................. 33ConvexHull ...................................................................................................................................................33DelaunayTriangulation..........................................................................................................................33VoronoiFiltering ........................................................................................................................................33AlphaShapes ................................................................................................................................................34SelectVisiblePoints...................................................................................................................................35

SUPPORTEDFORMATS............................................................................................................... 35IMPORT ............................................................................................................................................................. 36EXPORT............................................................................................................................................................. 36

COMPILINGDEVEL....................................................................................................................... 36WHATYOUNEED.......................................................................................................................... 36

Page 2: 1 MeshLab Documentation

2

GETTINGTHESOURCES.................................................................................................................................. 36EXTERNALDEPENDENCIES........................................................................................................................... 37CODETREESTRUCTURE................................................................................................................................. 37COMPILING....................................................................................................................................................... 38UsingMicrosoftVisualStudio8expresseditionandQT...........................................................38

WRITINGAPLUGIN...................................................................................................................... 39MESHDATASTRUCTURE............................................................................................................................... 39WRITINGYOURFIRSTFILTER....................................................................................................................... 40SVN ...................................................................................................................................................................40

WHATISVCGLIB? ....................................................................................................................................... 40INSTALLATIONANDFOLDERSTRUCTURE................................................................................................... 41GettingVCGLib ...........................................................................................................................................41FolderStructure..........................................................................................................................................41

BASICCONCEPTS............................................................................................................................................. 41Howtodefineameshtype .....................................................................................................................41Howtocreateamesh...............................................................................................................................43Theflagsofthemeshelements ............................................................................................................43Howtoprocessamesh.............................................................................................................................43

OPTIONALCOMPONENT ................................................................................................................................ 44OptionalComponentFast.......................................................................................................................44OptionalComponentCompact .............................................................................................................45User­definedattributes............................................................................................................................46C++typeofameshandreflection.......................................................................................................47

ADJACENCY ...................................................................................................................................................... 47FFAdjacency ................................................................................................................................................48VFAdjacency ................................................................................................................................................50FewfactsonFFadjacencyandVFadjacency................................................................................51Boundaryrelationsandadjacency.....................................................................................................52

SPACECONCEPTS ............................................................................................................................................ 52VIEWINGANDMANIPULATION ..................................................................................................................... 52Shotandcamera.........................................................................................................................................52

FILEFORMATS............................................................................................................................... 55SAVINGMASKANDREADINGMASK............................................................................................................ 55ERRORREPORTING ........................................................................................................................................ 56VMIDUMPFILE............................................................................................................................................... 56

ACCESSTOMESH .......................................................................................................................... 57Accessingthecoordsofallthevertexes............................................................................................57Accessingallthefacesandcomputingtheirbarycenter ..........................................................57Creatingelements ......................................................................................................................................57DestroyingElements .................................................................................................................................57

ADJACENCYRELATIONS ................................................................................................................................. 58Countingborderedges(withouttopology) ....................................................................................58Countingborderedge(usingFFadjacency) ..................................................................................58

LICENSES ......................................................................................................................................... 59PRIVACYDISCLAIMER .................................................................................................................................... 59ACKNOWLEDGMENTS..................................................................................................................................... 60

AFULLYCOMPREHENSIVEGUIDEONWRITINGANIOPLUGINFORMESHLAB ...... 60

Page 3: 1 MeshLab Documentation

3

IntroductionMeshLab is a advanced mesh processing system, for the automatic and userassisted editing, cleaning, filtering converting and rendering of largeunstructured3Dtriangularmeshes.MeshLabisactivelydevelopedbytheasmallgroupofpeopleattheVisualComputingLabattheISTI‐CNRinstitute,a largegroup of university students and some great developers from the rest of theworld.Forthebasicmeshprocessingtasksandforthe internaldatastructuresthesystemreliesontheGPLVCGlibrary.InteractingwiththemeshWhenMeshLab starts you are in the so‐called cameramodewhere themouseactionsareusedtochangethewayinwhichyoulookatthemodel.Thismodalityis the default and allows to easily navigate and inspect your model withoutactuallymodifying it. The cameramode is turnedoffwhenyouuse oneof theInteractiveeditingtools,wherethemouseactionsareinterpretedinadifferentway(e.g. forpaintingthemesh),butyoucanalwaysswitchbacktothecameramode bypressingESC; in this case theedinting tool is just suspendedandyoucan goback to editingbypressing againESC.To exit froman editing tool youhavetopressagainthetoolbarbuttonthatstartedit.Standardcameramode

leftdrag Rotate orbit around the current center of the object. Click farfromthecentertorotatearoundthelineofview.

ctrl+leftdrag Panwheel Zoom

shift+leftdrag Zoom(ifyoudonothaveamousewheelorifyouwantsmoothzoom)ctrl+shift+leftdrag Lightrotate,tointeractivelychangethedefaultlightsetting.

leftdoubleclickcenter and zoom on clicked point; subsequent rotations andzoomswillbecenteredonthechosenpoint.

alt+leftdragZtranslate;movesthecameraalongtheviewingdirection,(theeffect can be similar to zoom, but it allows tomore preciselynavigateinthespacearoundtheobject)

shift+wheel

changefieldofviewandmovethecameratokeepthemodelofapproximately the same dimension (in practiceincrease/decreasetheperspectivedeformation,muchaliketheHitchcockzoomdepictedintheVertigomovie).

ctrl+wheel move near plane back and forth to section the object andrevealitsinterior.

alt+wheel changepointsizewhenrenderingmode isPoints.UsePointsrenderingtodisplayinteractivelyhugemeshes.

Page 4: 1 MeshLab Documentation

4

Otherusefulkeycombinationsformeshinspectingare:

• ctrl+dtoggledoublesidedlighting• ctrl+ktogglebackfaceculling• ctrl+ftoggleblue‐redback=frontlighting

Obviouslyformacusers,youshouldsubstitutethectrlwiththecommandkey.WithoneofthetwoselectiontoolenabledClick=clickleftbuttonofthemouse

click Selectallthefacesinthedirection(includingthehiddenonesbehind)

ctrl+click Addfacestoselectionshift+click Removefacestoselection

alt+click Select only the front faces (without the hidden onesbehind)

ctrl+alt+click Add only the front faces (without the hidden onesbehind)toselection

shift+alt+click Remove only the front faces (without the hidden onesbehind)toselection

wheel Zoommiddlemousebutton Translatemeshalt+ middle mousebutton Rotatemesh

InteractiveeditingtoolsYoucanaccesstothesetoolsbyactivatingthemfromtheeditmenuorfromthetoolbar(allthebuttonsontheright).Onlyoneofthesetoolscanbeactivatedatatime. When you have an active editing tools all the other tools are disabled.Activatingoneofthesetoolsusuallychangesthewayyouinteractwiththemesh:mouseactionsaredirectlyprocessedbythechosentool.ForexamplewhenyoustarttousethePaintingTool,yourmousedragsareinterpretedasbrushstrokesover the mesh. Remember that you can toggle back and forth between thestandardcameramovingmousemodeandthecurrenttoolmodebypressingesc.Switching to cameramode does not disable the tool. To exit from the editingmodepress again the same tool button. You can see that youhave completelyclosedaneditingmodebyseeingagainasactivealltheothereditingbuttons.PlaneSlicingToolTheEditingPlaneSlicingtoolallowsuserstocreateoneormoremesh’sslicesobtainedthroughtheintersectionofasetofparallelsplanswiththemesh.Thesemi‐transparentplansarepaintedinthemainwindows,centerstotheobject'sboundingboxthatwearemodifying,withsimplicityuserscanfoundtheexactlyposition of the plans through the geometry; the editing of the plans are notboundtotherestofthescene.

Page 5: 1 MeshLab Documentation

5

(Picture1.)Editingdialog

Thetoolincludeadialog(Picture1)withthefunction:

• 1Definethenumberofplans.• 2Restorethedefaultsettings.• 3Increase/decreasedistancewithaslideoreditingmanually.• 4Single/multifiledefinetheexportingmode

o SigleFileMode Single filedispose theresultof the intersectionsover a single SVG file, in a continuous strip, each item designedinsideofarectangle.

o Multi File Mode Each item has its file, the x‐th slice namednamefile_X.svghasasingleslice.

• 5Startwithexportingfunction.The intersection result could be exported in Scalable Vector Graphics (SVG),therearetwopossiblemodes:

• Single files, if theplansaremorethanoneall theresultarestored inasinglefile.

• Multifiles,foreachplansarecreatedafile.

(Picture2.)SVGpropertiesdialog.

Page 6: 1 MeshLab Documentation

6

Thedialogin(picture2)containsthemainpropertiesoftheSVGdocument:• 1Dimensionsincentimeters/pixelsoftheglobalcontext• 2Adinamicsetoflabelthatcalculateeachdimension’sitem,particularly

usefulinmultifileexporting.• 3Enable/disabledetailsandtextinsidethecontext.• 4Resolutionoftheglobalcontextinpixels.

AlignmentAlignment is a rather complicate process. First of all you should have wellunderstood the layersmechanism inMeshLaband the fact thateachmeshcanhave a transformation matrix. The alignment process simply modifies thetransformation of each layer. The main idea is that you iteratively glue yourmisalignedmeshesover thosealreadyaligned.Amesh that is aligned togetherwithasetalreadyalignedmeshissaidtobegluedanda* isshownnearto itsname. Initially all meshes are unglued. You task is to roughly align all yourmeshes.Oncethemeshesaregluedinarathergoodinitialpositionyoucanstartthealignmentprocess:thesystemchooseswhatmesheshavesomeoverlappingpartandforeachpairofmeshesthesystemstartsaICPalignmentalgorithmthatpreciselyalignsthechosenpair.At theendof theprocessall thegluedmesheswillhopefullybealignedtogether.KeyConcepts:

• ICP: Iterated closed point: The basic algorithm that automaticallypreciselyalignsamovingmeshMwithafixedoneF.Themainideaisthatwechooseasetof(welldistributed)pointsoverMandwesearchonFthecorrespondingnearestpoints.ThesepairsareusedtofindthebestrigidtransformationthatbringthepointsofMontothecorrespondingpointsonF.ICPhasalotoftunableparameters.

• GlobalAlignment:alsoknownasmultiviewregistration.Afinalstepthatevenlydistributesthealignmenterroramongallthealignmentsinordertoavoidthebiasedaccumulationoferror.

• Absolute Scale. The parameters of the alignment tool are in absoluteunits, and thedefaults areacceptable fora standard scanneroutputtingmeshesinmillimeterunits.Soforexamplethetargeterror(i.e.theerrorthat the ICP try to achieve) is 0.05mmsomething that canbe achievedwithagoodscanner.Obviouslyifyourrangemapsareinadifferentunit(microns, kilometers, etc.) you must adjust the default alignmentparametersorthealignmentprocesswillfail.

SmallTutorial

1. Open all the meshes provided in the SampleRangeMaps package, bysimply selecting all the mesh in the open dialog (use ctrl for multipleselectionasstandard).Allthemesheswillbeloadedtogetherindifferentlayers.

2. Startthealignmenttools(theAinthetoolbar)3. Chooseameshandglueinitscurrentposition(astarwillappearbeside

itsname).

Page 7: 1 MeshLab Documentation

7

4. Choose anothermesh (not glued) and glue it in the correct position bystarting the point based alignment. A newwindowwill popup and youhavetochoosefourcorrespondingpairofpointsonthetwomeshes(theset of the already glued one and the new unglued mesh). You choosepointsbydoubleclickingoverthetwomeshes.

5. Repeatstep4untilallthemesheshavebeenglued.6. Click on "Start process." Now the system will search for overlapping

meshes and for all themeshes that have some overlaps compute a fineICP.At the endof this process a "GlobalAlignment" stepwill distributeresidualerrorevenly.

7. Nowthealignmentiscompleteandyoucanlookatresultsandcheckforanyerrorsinthealignmentprocess.

8. ClosetheAlignTool.9. Flattenallthelayersintoasinglemesh.10. Startthemergeprocessbyusingasurfacereconstructionalgorithmlike

thePoissonbasedone.11. Savetoanewfile.

The editingQualityMapping Tool is a tool for the fine tuning of how scalarvalues,definedoveramesh,aremappedintocolors.Notethatthisfilterwillnotwork if quality values are not defined over the mesh vertexes. The tool iscomposedbytwomainsection:TransferFunctionTheTransferFunctionmaps,throughalinearchart,thedistributionofthevaluesof RGB channels over a linear space, identified by a color band. The transferfunction view is interactive, in fact the user canmodify the distribution of thechannelsvaluesusinghandles,thatcanbeadded,movedorremoved.ToaddanewhandletotheTransferfunction,it'snecessaryfirsttoselectthechannelforthehandle(byselectingtheforwardchannelinthetop‐rightradiobuttongroup,orbyclickingonanhandleofthesamechannel),andthendouble‐clickinginanempty place of the transfer function view. It's possible to remove an existinghandle by double‐clicking over it. Every time a change is performed to thetransferfunction,it'simmediatelyvisibleinthecolorbandbelow.Moreover,it'spossibletosavethecurrenttransferfunctioninaCSVfileor loadit. ImportantNote:Whenatransferfunctionisloadedfromanexternalfilethechangestothecurrenttransferfunctionwillbelost.EqualizerItrepresents,throughanhistogramchart,thedistributionofthequalityoverthemesh(x‐axisrepresentsqualitylevels,y‐axisrepresentsthenumberofvertexeswithacertainquality).Likethetransferfunctionview,thehistogramonetooisprovided of handles, exactly three. Each handle has a different meaning: theleftmost one, represents the minimum quality limit, the rightmost one themaximumqualitylimit,andthemiddleonerepresentsthepositionofthemiddlequality level respect to the minimum and the maximum actual values. Theportion of histogram delimited by lateral handles is mapped in the transfer

Page 8: 1 MeshLab Documentation

8

function(visibleasbackgroundoftheTFview).So,allthequalitylevelsincludedin therangebetweenthehistogrambeginningandthe lefthandlepositionwillbemappedwiththeleftmostcolorofthecolorband,whiletheonesbetweentherighthandleandthehistogramendwillbemappedwiththerightmostcolor.Alltheothervaluesofthehistogramaremappedinthecolorbanddependingbytherelativepositionof themiddlequalityvalue.Thisvalue is theparameterof theexponential (or logarithmic) function used to interpolate the TF nodes whenmapping quality levels on color band. The curve representing this function isviewed in thegammacorrectionpanel. Ifa lateralhandle ismovedoutside thehistogram,oriftheusersetsina"lateral"spinboxaqualityvaluegreaterthanmaxorlesserthemin,thehistogramwillautostretchitself.Finallyaslidercanbeusedtochangethebrightnessofthecolorbandcolors.TutorialsStressingthecurvatureofamesh

1. ApplythefilterColorize/GaussianCurvature(equalized)2. OpentheQualityMappingTool3. ChoosetheRGBcolorpreset4. Quality values over Gamma Curvature are often concentrated in a tight

rangebetween‐aand+b.Somanuallysetmiddlequalityto0.Trysettingminimumandmaximumequalizervaluestostretchthesignificantpartofthe histogram all over the color band, so that negative values will becolored in red and positive ones will be colored in blue, while qualityvaluesaround0willbecoloredingreen

5. You can evenmodify the transfer function to eliminate the green colorandextendredandbluetoallthecolorband

Givingatonetoamesh

1. ApplythefilterColorize/AmbientOcclusion2. OpentheQualityMappingTool3. Chooseacolorpreset(i.e.RedScale)4. Modifythetransferfunctiontoobtainthecolorscaleyoulike5. Set theminimum/middle/maximumquality value in equalizer to adjust

thetonedependingonthedistributionofqualityoverthemodelApplyingthesamemappingtoseveralmeshes

1. SettheQualityMappingtoolwithsignificantvalues2. Save preset to a file (it will contain transfer function and equalizer

parameters)andclosethetool3. Openanewmesh4. OpenQualityMappingtool5. Clickonloadpreset,locatetheCSVfileyoupreviouslysavedandapplythe

filter.AlternativelyopenthefilterQualityMapperApplier,locateCSVfileandapplythefilter. This filter can be used also inMeshlab command line. Note: all the filesshouldhavesimilarqualityvaluestobecoloredinasignificantway(i.e.applyingthesamecolorizefilter)

Page 9: 1 MeshLab Documentation

9

StraightenerThe Editing Straightener Tool is a tool for interactively change thetransformationmatrixassociatedwitheveryloadedmesh.Note:Thistoolisnotintendedforgenerictransformationslikescaling,shearingormirroring.Suchnon‐repositioningtransformationscanbeachievedusingthe"ApplyTransform"filter.FeaturesThistooloffersseveralwaystochangemeshalignmentandorigin:

• Buttons for flipping on, swapping between and rotating around all theprimaryaxes.

• Abuttontoaligntheaxeswiththecurrentview.• Buttons and sliders to put the coordinate origin in any point inside the

meshboundingbox.• Abuttontoputthecoordinateorigininthetrackballcenter.• Interactive"freehand"modes:

o Usercandragthemeshwrtthecoordinateframe.o Usercandragthecoordinate framewrtthemesh,usingaspecial

euleriantrackball,alsoabletomakeangle‐constrainedrotations.• Waystoliterally"draw"oneortwoaxisdirectiondirectlyonthemesh.• Ways to align the coordinate frame on the best fitting plane of the

eventuallyselectedvertexesinthemesh.• Abuttontofreezethecurrenttransformationinthemesh.

The tool alsooffers an integratedundo systemand control over several visualfeedbacks.SampleUsageHereweshow,throughexamples,severalwaystousethistool:Basics

• Openthefile"screwdriver.ply"inthe"sample"directory.Thismesh'sdefaultorientationissuchthatiftheviewtrackballisn'trotated,themeshitselfishardlyrecognizable.

• Clickonthe"Straightenupamesh"button.Nowthetooluserinterfaceisshown,anddraggingthemouseonthemeshwillhavenoeffect.

• ClickontheSwapZwithXbutton,thenontheRotate90degreesaroundXbutton

Now themesh transformationmatrix has been changed, but themeshhasnotbeenmodified.

• ClickonthefreezebuttonNowthemeshhasbeenupdated,andtheneworientationcanbesaved.Like every other editing tool, Straightener can be suspended using the "Notediting"button,andtheviewtrackballcanbemodified.

Page 10: 1 MeshLab Documentation

10

SimpleStraightening• Openthefile"sub.obj"inthe"sample"directoryandstartthetool.

Thismesh'sdefaultorientation isplainwrong, thiscanbeeasilyseenfromthevisualfeedback.

• Suspendthetool(esc)androtatetheviewtrackballuntilthesubmarinesideiscorrectlyviewed.

• Resume the tool (esc again) and click on the "align with actual view"button,thenclickoncenteronbboxbutton(intheorigintab).

Nowthemeshiscorrectlyorientated,andcanbefreezed.The coordinate frame orientation and position can be refined, toggling the"Freehandmeshdragging"button:

• Leftclickrotatesaroundthecurrentaxis• Rightclicktranlsatesalongthecurrentaxis• Thedefaultcurrentaxisisx,itcanbechangedtoyandzusingthectrland

shiftkeyboardmodifiers(visualfeedbackisprovidedforeaseofuse).• Rotationcanbedoneinacontrolledfashionsettingthesnapvalue.

The new coordinate frame can be accepted toggling the "Freehand meshdragging"buttonagain.LayerCompositionThistoolcanbeusedtocomposemultiplelayers.

• Openthefile"twirl.off"inthe"sample"directoryandstartthetool.• Clickonthe"flipyandz"button,freezeandclosethetool.• "Openinside"themeshthefile"sharpsphere"andrestartthetool.

Notethatthetoolworksalwaysinthelayeractivewhenthetoolstarted.• Click on the rotate 90 around z button, then toggle "Freehand mesh

dragging" (in the Drag tab). A blue wireframe sharp sphere is nowrenderedovertheoriginalone,thatcanbedraggedliketheviewtrackball(withoutscaling,ofcourse).

• Ctrl‐dragthewireframespheretopanitupthetopofthetwirl.Again,thetoolcanbesuspendedandtheviewchangedduringalltheseoperation,ifnecessary.

• Toggle back the "Freehand mesh dragging" button to accept the newsphereposition,thenfreezeandclosethetool.

Nowthecomposedlayerscanbemerged/flatteneddowntoapawn‐resemblingmesh.SpecialFeaturesThis tool has also two families of special features, useful if the mesh is notstraight and not regular, but has some regular surfaces that can be taken asreference(e.g.thebasementofascannedstatue).Thefirstfamilyisthe"drawaxesonmesh"one:usingoneortwo"rubberbands"(similiartotheMeasuringToolone)theusercandrawasegmentortwoonthemeshsurface,andthecoordinatesystemwillrotatearounditsorigintoalignthechosen first axis to the first drawn segment. Then, if another axis has beendrawn,thecoordinateframewillrotatearoundthefirstaxistoalignthesecondoneasmuchaspossible.

Page 11: 1 MeshLab Documentation

11

The second family is the "get from selection", and is available only if somevertexes are selected (obviously). From the selection a best fitting plane iscomputed,thenthechosencoordinateframeplaneisalignedwiththecomputedone,andtheoriginisputontheplaneprojectionoftheselectionboundingboxcenterPointPickingToolDescriptionThistoolcanbasicallybedescribedasameshlabelingtool.Itallowsyoutopickandnamepointsonameshandsavetheoutputtoxml.GeneralThe tool has twomainmodes, normal and templatemode. Templatemode isdescribedbelow.Therearetwomainmodesofinteractionwiththepoints,PickPoint,MovePoint,andSelectPointmode.Themodeofinteractionisindicatedby theradioat the top. Inpickmodeyouaddnewpoints to themeshbyrightclickingonthemesh.Inmovemodeyoucanmoveapointbyrightclickingnearthepointanddraggingittoadifferentlocation.Inselectmodeyoucanrightclickapointonthemeshanditwillbehighlightedinthepickpointsedittoolmenu.Here are some notes about the active checkbox. The immediate affect ofcheckingtheactivecheckboxistohide/showthepickedpointonthemesh.Thisfeatureismeanttoallowtouseatemplateforwhichscandatawillhaveoneofthetemplatepointsmissing.Inthiscaseyoucanunflagthispoint,labelingitin‐active.Whenpointsareaddedyouhaveagreencone,representingthenormal,withalabelnexttoit.YoucanalsochooseatthebottomwhereitsaysNormalOptions to have just a dot,which is the point, a label for that point, or a dot,label,andagreenlinewhichrepresentsthenormalofthefacethepointison.TemplateModeSummary:Templatesareusetofacilitatethelabelingofmanymesheswiththesamelabels.IfyouhaveatemplateloadedyouareinTemplateMode.Thenameof the templatewill bewritten in blue letters next to the place at the bottomwhere it says "Template Name:". "No Template Loaded" will be printed if notemplateisloaded.In Templatemode youwill only be able to pick andmove the points that arealreadydefinedaspartof the template.UsetheAddPointandRemovePointbuttons in theTemplateControlsarea tomodifya template.Youcanalsostartfromscratch,picksomepoints,thensavethemasatemplate(savingthenamessoyoucanusethemforothermeshes).Saving/LoadingPointsPointsaresavedtoaxmlfilebyusingthesavebuttonatthetop.Pointscanbeloaded from a file by pressing the load button. Alternately points areautomatically loaded froma file if youhadpreviously saved themusing thefilenamerecommendedbythetool.

Page 12: 1 MeshLab Documentation

12

PointsaresavedtoPerMeshAttributesautomaticallywhenyouclosetheeditpluginand loadedback fromPerMeshAttributewhentheplugin is loaded.Thistakesprecedentoverloadingpointsfromafile.OtherFeatures

1. Renameapointbyslowlydoubleclickingonit2. Undo:willundoonlythatlastmove

UseWith"AlignMeshusingPickedPoints"filterIn order to use theAlignMesh using Picked Points filter you need to haveeithersavedpoints:

1. toPerMeshAttributesor2. toafilewiththenamesuggestedbythepointpickingplugin.

Note:thatpointsareonlyneededif"UseMarkersforAlignment"ischecked.Note: that if "Scale the mesh" is checked then you need points and to havechecked"UseMarkersforAlignment".Note: the transform calculated is stored in per mesh data with keyAlignTools::getKey()NotesforDeveloperswhowanttousepickedpointsintheirpluginYoucanlookathowthefilterFP_ALIGN_WITH_PICKED_POINTSinthecleanfilterpluginusespointspickedbytheedit_pickpointsplugin.Note,mostcodeishere,cleanfilter/cleanfilter.cppbuttheimportantbitishere:MeshModel *stuckModel = par.getMesh(StuckMesh); PickedPoints*stuckPickedPoints = 0; ... //first try to get points from memoryif(vcg::tri::HasPerMeshAttribute(stuckModel‐>cm, PickedPoints::Key) ) { CMeshO::PerMeshAttributeHandle<PickedPoints*> ppHandle = vcg::tri::Allocator<CMeshO>::GetPerMeshAttribute<PickedPoints*>(stuckModel‐>cm,PickedPoints::Key); stuckPickedPoints=ppHandle();What you get is a PickedPoints object. To see what it does look here/meshlabplugins/edit_pickpoints/pickedPoints.h(cpp).Basically what you need to know is that this class hold astd::vector<PickedPoint*>where aPickedPoint is a simple object that has twomembers:

1. nameofpoint:QStringname;2. point:vcg::Point3fpoint;

Otherinformation

• sourcecodeinedit_pickpointsfolder

Page 13: 1 MeshLab Documentation

13

HoleFillerToolTheInteractiveHoleFillerToolisatoolallowtheuserselectholesandeditthemindifferentways.Thegoalfeatureofthispluginisfillholesasuserwant,buttodothisit'salsopossibleedithole'stopology.PrerequisitiesHoleFillerToolneedmeshesmanifoldness.HoleSelection:Usercanselectanholetoeditwithamouseclickoveraborderfaceorpinningthecheckboxindialog.HoleFilling:Basic filling algorithm use a tecnique wich adds a face between two adjacentborderedge(friendlycalled"ear").Thisisagreedyalgorithmwhichchooseeachtimethebestpairofadjacentborderedgeintothehole.Howeverselectedholescanbefilledfollowdifferentcriteria:

• Trivial:besteariscomputedonlywithface(triangle)quality• MinimumWeight: best ear is computed mixing quality face and angle

beetweenearandadjacentfaces.• SelfIntersection: as Minimumweight but pay attention to

autocompenetratingface.Whenholesarefilledusercanfillagain,maybewithdifferentparams,oracceptor discard patch applied by filling. As selection, acceptance could be doneclickingthemeshordirectlyintothedialog.HoleBridging:

BridgestypeSometimesrightfillingmustbedrivenbyuser,todothatit'spossibleaddsomebridge, manually or automatically. Bridge consist into 2 adjacent face whichconnect2differentborderedge.Withbridgeanusercan:

• split an hole, if bridge is builded with starting and final border edgebelongtosamehole

• unifymoreholesintoone,ifbridgesconnectedgesbelongdifferentholes.

Page 14: 1 MeshLab Documentation

14

ManualBridging:User select the twoedges to connectpicking theborder face. It cannotbuild abridgebeetween2adjacentedges.Automaticbridging:Automatic briding works on selected holes. User have to specify if he wantconnectallselectedholesorspliteachselectedhole.NonManifoldHoleSplitting:Fillingcanmanagenonmanifoldholes,butthispluginalloweditholestructuretosplitannonmanifoldholeintomanymanifoldones.DataStructures

• FgtHole:Extendvcg::tri::Hole<MESH>::Infoaddingsomeinformationlikethe hole status (selection, autocompenetration, filling...). Also addfunctionalitytodraw,fillandrestore...

• FgtBridgeBase: abstract class which exposes method used byHoleSetManager.

o FgtBridge: bridges used to connect 2 border edge. It can split anholeorunify2(ormore)holes.

o FgtNMBridge:facesaddedtoclosenonmanifoldholes.• HoleSetManager: it is an unique entity to manage the holes and the

bridgesexistingintothesamemesh(sowiththesameadditionaldata).• HoleListModel:modelofmodel/viewarchitectureusedbygui.

Markinterestingfaces

FlagsusageInteractive Hole Filler tool mark interesting faces using additional data. Thismarker,withholesproperties,areusedtoknowtopologyofholesanditsfilling.Characteristicfacetypesare:

• HoleBorderFace:marksfaceswhichhaveatleastanedgeadjacenttohole,borderfacesorfacesadjacenttohole'sfilling

• HolePatchFace:marksfacesaddedtofillhole• PatchCompFace:marksfacesself‐intersectingwithmesh• BridgeFace:marksfacesaddedtoeditholes

Page 15: 1 MeshLab Documentation

15

Bridgesbuldingissue

Topologyofbridge'sfaceFgtBridgeRappresenttherealmeaningofwordbridge.Itconnects2edge,has2abutmentover themeshandhas2borer side. It is apairof faces,bothadjacent toeachother. There is 2 way to triangulate 2 edges (4 vertex) so it'll chooseconfigurationwithbestqualityofitsface.Bridgeisbuildtohaveedge0adjacentto mesh for both its faces, and its faces share edge 1 or 2 following thetriangulateconfiguration.FgtNMBridgeIt's a single face used to change non‐manifold vertex in manifold one. It hasvertex0onnonmanifoldvertexandedge0and2adjacentmesh.Itsedge1couldbeaborderedgeofanotherhole,butitcouldfillentirelythesub‐hole(ifsubholehasonly3brderedge).SlicingameshVersion1.1.1ofMeshLabcandoslicing. It is abit (!)buggy, andwitha ratherclumsyinterfacebutmoreorlessworks.Nextversionwillhaveacleanermorerobustinterface(hopefully).Slicesareexportedinsvgformat.Conversionfrom2Dsvgto2Ddxfcanbedonebyinkscape.microtutorial

1. Openamesh2. rotateitwiththetransformationdialogsothatslicingwithplanesparallel

totheYZplaneisok(usetherender‐>showaxisforchecking)3. starttheslicingtool

Page 16: 1 MeshLab Documentation

16

4. dragging in thewindowmove the slicing plane orientation, so DONOTdragoverthewindowiftheyzplaneisokforyou.Ifyouwanttoexaminethemodelpressthetrackballiconinthetoolbar.

5. setthedesirednumberofplanes6. pressexport(youcanchoose ifyouwant tohaveallyourslice insingle

fileorinmultiplefiles)7. youcancustomizeabittheoutput,byremovinglabel,decidingthesizeof

theoutput.CleaningaMeshCleaning a mesh means trying to remove all the small geometrical andtopological inconsistencies that can be found in off‐the shelfmeshes. Commonproblemsthatusuallyhavetobecheckedarethefollowingones:

• Duplicatedvertices• Unreferencedvertices• NullFaces• SelfIntersectingfaces• NonManifoldfaces• Small Holes. Small holes (small in terms of number of the edges that

composetheirboundary)canbesafelyautmaticallyclosed.Largerholesneedssomespecialcare...

• Smalldanglingartifacts.Ithappensthataftera3Dscanningtherearealotofsmallpiecesfloatingintheair,unconnectedwiththerestofthesurface.Thesepiecesaresmallconnectedcomponents;youcanremovethemwiththe apposite filters, that can discriminate according to the size of thepiecesintermsoffacescomposingthemortheirspatialdiameter.

• RemovingNoise. This is amore complicated task. This happens usuallywhen managing 3D scanned meshes. It happens that surface that youexpect to be perfetly flat are affected by some kind of noise and areirregular. Just like for image processing noise removal has positive andnegative sides.MeshLab supportsdiffernt kindof smoothing filters thatareabletoremovevariouskindofnoise:

o Laplaciano HCLaplaciano TwoStepSmoothing

• Duplicatedvertices• If yourmodel is comingdirectly froma3D scanner, therewill bemany

duplicate definitions for each vertex. If the model is manipulated inMeshLabandthenexportedtoanothersoftwarepackage,theseduplicatepoints can cause problems with rendering and conversion to differentformats.Byremovingtheseduplicatevertexdefinitions,themodelcanbesimplifiedanddownstreamsoftwareproblemsreduced.

• Asmalldiscussiononduplicatedvertices,unreferencedverticesandhowtoremovethemwithMeshLabcanbefoundintheMeshLabstuffblog

• Openyourmodel• Themessagebaratthebottomofthescreenwillindicatethenumberof

facesandthenumberofverticesinthemodel

Page 17: 1 MeshLab Documentation

17

• Adialogwillpopupaskingifyouwanttounifyduplicatedvertices.SelectNo.

• Afterthemodelloads,clickontheFiltersTab• SelecttheCleansubmenu.• SelectRemoveDuplicatedVertex• Afterperformingthiscleaningstep,thereshouldbeasignificantdecrease

inthenumberofverticesassociatedwiththemodel.Image­based3DReconstructionMeshlab,inconjunctionwithanothertoolcalledEpoch3DWebserviceisabletoproduce accurate 3D model starting from a set of images of the object toreconstruct.Thestepstofolloware:

1. ProcessyourimageswiththeEpoch3DWebservice2. ImporttheoutputoftheEpoch3DWebservicewithMeshlab3. Mergetherangemapsandbuildthemodel

MergetherangemapsandbuildthemodelHerewedescribethevariousparametersinvolvedinthecreationofrangemapsfromtherawdatacomingoutfromthewebreconstructionservice.Itispossibleto modify several parameters in order to produce 3D range maps that arecleanerandaffectedbylowernoise.Parametersdescription:

• SubsampleIndicates the level of sub‐sampling of the range maps used.Example:forarangemapof600x400alevelof2indicatesthatyouusea300x200 pixels in total for each rangemap. This parameter is used toreducethefinalnumberofverticesofthemodel.Thereductionisdoneinaweightedmanner.

• MinimumCount• Indicates the minimum number of occurrences required for a value of

depth to be considered for the reconstruction.Example: if Minimum Count is set to 6 a value of depth that has nocorrespondencesinatleast6rangemapsisnotusedtobuildthemodel.

• MinimumAngle• facesthathavestheirnormalformingananglewithviewdirectionlarger

thantheindicatedvalue(indegree)aredeleted.• RemovePieceslessthan• Afterthemeshingallthedanglingpiecescomposedbyanumberoffaces

smaller than the indicated values are deleted. In this way you canautomatically delete all the small floating pieces that usually are justnoise.

• DepthFilter• Thedepthfilterisusedtoreducethenoiseoftheestimatedrangemaps.

Sometimes could happen that the computed range maps are noisy,especially near high depth gradient.With this parameters the user cancontrolafilterbank(dilationanderosion filter)toreducethisundesired

Page 18: 1 MeshLab Documentation

18

effect that results in geometric artifacts on the model's surface. Thedilationfilter isappliedbeforetheerosionone.Thedefaultsparametersare good in most cases. The erosion reduce the reconstructed surfacearea, hence to reconstruct more detail reduce the steps or size of thisfilter.Iftherangemapsstillremainsnoisyafterthefilteringincreasetheerosionstepsorsize.Increasedilationstepsorsizeincaseofholesinthereconstructedsurfaces.

• FastMerge• Thisoptionactiveafastmergeprocessbutproducealessaccuratemodel.

Ifhighaccuracyisnotrequiredormanyrangemapshavetobeprocessedthisoptionshouldbeactive.

LayersSinceversion1.1MeshLabsupportsthemanagementofmeshesorganized intomultiplelayers.Insimplewordsitispossibletohavemanymeshesinthesamewindow.Eachmeshiskeptonaseparatelayerandmostofthetools/filtersaredesignedtooperatetoonlyoneofthematatime(forexamplesmoothingfilterssmoothsoutonlythecurrentlayer).Savingandloadingareusuallysinglelayeroriented too (e.g. when you save a ply you save just the current layer). As areasonablemetaphorofthelayerinsidemeshlabyoucanconsiderhowthelayermechanismworksinabitmapeditingapplication(likegimp).Asetoflayerbuildupaprojectthatcanbesavedaseparateentity(inthesimpleALNasciiformat).Eachlayerstoresalsoa4x4transformationmatrix.Thistransformationmatrixisused mostly for rendering and has a leading role in the [[alignment] processwhereitcodestherelativetransformationbetweenthevariousrangemaps.Alltheprocessingfiltersnormallyworksinthenaturalspaceofthemesh,withtheplainexceptionoffiltersspecificallydesignedtoworkwiththesetransformation,likethetransformation filterandthe freeze filterthatmakethistransformationperpetualactuallychangingthecoordinatesofthemeshvertexes.Tohavemultipleactivelayersyoucanalternatively:

• selectmorethanasinglefileintheopendialogandpressok.• openameshandthenusethe'openasanewlayer'commandinthefile

menu• openamesh,showthelayerdialog(buttononthetoolbar)andpressthe

"+"button.Youcanmergedifferentlayerstogetherbymeansofthe'flatten'command.Theflattening operation simply put themesh together in the same layers freezingtheircoordinates.LayerManagmentMeshlabshasapowerfulLayerManagmentTools.ItissimilartoothersoftwareslikeAdobePhotoshop,TheGimp,etc.Tomanagedifferent layers,pressthe5thbuttoninthetaskbar(somegrayplanes).Atabopensattheleftside.Hereyouseeallyourlayers.

Page 19: 1 MeshLab Documentation

19

Be careful,when you opena newmesh, the layers box remains unchanged ­ youhavetoopenitagaintohavethecorrectlayers.ManagingtheLayersYou can add an externalmesh to a new layer by going in File >OpenAsNewLayer.Tomanagethelayers,youcaneitherright‐clickonthelayerbox,orgoinFilters>LayersManagement.Thenyouhave5options:

1. AutomaticPairAlignment‐>?2. FreezeCurrentMatrix‐>?3. MoveSelectiontoanotherLayer‐>Createanewlayerwiththeselected

faces. Select some faces on yourmodel, then choose "Move selection toanotherlayer".Youhaveaveryexplicitoption"Deleteoriginalselection":youeithermoveorduplicateyourselectiononthenewlayer.

4. DuplicateLayer‐>Createanewlayerwiththesamemeshastheselectedlayer.Thedifferencewiththeoptionabove is that itcopysall themesh,notonlytheselectedfaces.

5. Flatten visible Layers ‐> You can merged different visible layers. Theoptionsareagainexplicit.

InteractingwiththelayersYoucanworkwithonlyonelayerateachmoment,theonewhichisselectedinyellow. This includes saving (/!\only the selected layers is saved/!\),selection,andmoregloballyallinteractions.Tochoosethelayerwithwhomyouwanttowork,simplyleftclickonit inthelayerbox.Youcanalsohideorprinteachlayerwiththesmall"eye"icon.Tip:Somethingverypowerfulisthatyoucanselectfacesonalayer,thenhideit(thislayersbeingstillselected).Doingsoallowsyoutoseetheselectedfacesinred,buttransparent‐itisquiteusefultocomparemeshes,byexample.TransformingaMeshTo transform a Mesh (translation, rotation, scale), go in Filters > Normals,Curvature and Orientation > Apply Transform. There you have 3 tabs whichallowsyoutotranslate,rotateandscaleyourmesh.Tip:Thinktoshowtheaxis(Render>ShowAxis),itreallyhelps:)When you change the parameters, you can either choose: ‐Absolute option:clear the previous transformation and apply only the current set ‐Relativeoption: include the current set to the previous transformation. For eachtransformationpress"Apply"toseewhathappens.Translation Very simple to use, you can set a direction in X, Y or Z. The axishelpsyoutoknowthedirection.Thelengthvaluesarenotabsolute:ifyouapplyatransformation,thelengthunitcanchange.UsefuloptionMoveCenterToOrigin

Page 20: 1 MeshLab Documentation

20

ScaleVerysimpletousetoo,youcanchangethescaleinX,Y,orZ.UsefuloptionUniformtosetthesamescaleinthe3directions.Becareful:ifyoucombinethisoptionwithrotation,theresultsmightbesurprisingsometimes.RotationThemostdifficultoption.Youcansetarotationaroundanaxe(X,Y,Z)in degrees. The axis helps you too to know thedirection. Youhave2 options:turn around the center of themesh (center of gravity?) and turn around theorigin.Butthereisatrap(:p):theoriginisnotlocatedintheintersectionoftheaxis!Itislocatedontheoriginofthemesh,coordinates(0,0,0),whichisdifferentoftheoriginoftheshownaxis.Whenyouaresatisfiedwithyourtransformation,press "Close and Freeze". Warning: you cannot undo it! And you lost thetransformation matrix associated, so think to copy it before if you need it!"Close"cancelseverything.Tip: if youhave strange behaviorswith rotation or scale, close and freeze thetransform,thenopenthefiltersagain.Youmaybeinextremevalues,closetotheprecisionlevels.FiltersThe Filter List page presents a simple long list of all the filters that will beavailableonthe1.2.version.

• Simplification• Meshing• AlignMeshusingPickedPoints• MorphMesh• MLSSurfaces• ConvexHull/AlphaShape/VoronoiReconstructionfilter

FilterList1.2.0

• Aging Simulation Simulates the aging effects due to small collisions orvariouschippingevents

• VertexAmbientOcclusionGeneratesenvironmentocclusionsvalues fortheloadedmesh

• Face Ambient Occlusion Generates environment occlusions values fortheloadedmesh

• AutomaticpairAlignment AutomaticRoughAlignment of twomeshes.Based on the paper 4­Points Congruent Sets for Robust PairwiseSurfaceRegistration,byAiger,Mitra,Cohen‐Or.Siggraph2008

• Ball Pivoting Surface Reconstruction Reconstruct a surface using theBall Pivoting Algorithm (Bernardini et al. 1999). Startingwith a seedtriangle, theBPAalgorithmpivotsaballaroundanedge (i.e. it revolvesaroundtheedgewhilekeepingincontactwiththeedgeendpoints)untilittouches another point, forming another triangle. The process continuesuntilallreachableedgeshavebeentried.

• RemoveverticeswrtqualityRemovealltheverticeswithaqualitylowersmallerthanthespecifiedconstant

• Remove isolated pieces (wrt face num) Remove isolated connectedcomponentscomposedbyalimitednumberoftriangles

Page 21: 1 MeshLab Documentation

21

• Remove isolated pieces (wrt diameter) Remove isolated connectedcomponentswhosediameterissmallerthanthespecifiedconstant

• AlignMeshusingPickedPoints Align thismeshwith another that hascorrespondingpickedpoints.

• SelectFacesbyviewangle Select facesaccording to theanglebetweentheirnormalandtheviewdirection.Itisusedinrangemapprocessingtoselectanddeletesteepfacesparalleltoviewdirection

• Remove T­Vertices by edge flip Removes t‐vertices by flipping theoppositeedgeonthedegeneratefaceifthetriangulationqualityimproves

• RemoveT­VerticesbyedgecollapseRemoves t‐vertices fromthemeshbycollapsingtheshortestoftheincidentedges

• RemoveDuplicate Faces Remove all the duplicate faces. Two faces areconsidered equal if they are composed by the same set of verticies,regardlessoftheorderofthevertices.

• MergeCloseVerticesMergetogheteralltheverticesthatarenearerthanthe speicified threshold. Like a unify duplicated vertices butwith sometolerance.

• ColorizebyQualityColorizevertexandfacesdependingonqualityfield(manuallyequalized).

• Discrete Curvatures Colorize according to various discrete curvaturecomputed as described in: 'Discrete Differential­Geometry Operators forTriangulated2­Manifolds'M.Meyer,M.Desbrun,P.Schroder,A.H.Barr

• Triangle quality Colorize faces depending on triangle quality:1: minimum ratio height/edge among the edges2: ratio between radii of incenter and circumcenter3:2*sqrt(a,b)/(a+b),a,btheeigenvaluesofM^tM,Mtransformtriangleintoequilateral

• SelfIntersectingFacesSelectonlyselfintersectingfaces.• SelfIntersectionsColorizeonlyselfintersectingfaces.• BorderColorizeonlyborderedges.• TextureBorderColorizeonlyborderedges.• ColornonManifoldFacesColorizethenonmanifoldedges,egtheedges

wheretherearemorethantwoincidentfaces• ColornonManifoldVerticesColorizeonlynonmanifoldedgeseg.• LaplacianSmoothVertexColorLaplacianSmoothVertexColor• LaplacianSmoothFaceColorLaplacianSmoothFaceColor• VertextoFacecolortransferVertextoFacecolortransfer• FacetoVertexcolortransferFacetoVertexcolortransfer• TexturetoVertexcolortransferTexturetoVertexcolortransfer• Random Face Color Colorize Faces randomly. If internal edges are

presenttheyareused• VertexColorFillingFillsthecolorofthevertexesofthemeshwithacolor

choosedbytheuser.• VertexColorInvertInvertsthecolorsofthevertexesofthemesh.• VertexColorThresholdingReducesthecolorthevertexesofthemeshto

twocolorsaccordingtoathreshold.• Vertex Color Brightness Change the color the vertexes of the mesh

adjustingtheoverallbrightnessofthemesh.

Page 22: 1 MeshLab Documentation

22

• Vertex Color Contrast Change the color the vertexes of the meshadjustingthecontrastofthemesh.

• VertexColorContrastandBrightnessChange thecolor thevertexesofthemeshadjustingbothbrightnessandcontrastofthemesh.

• Vertex Color Gamma Correction Provides standard gamma correctionforadjustingthecolorthevertexesofthemesh.

• Vertex Color Levels Adjustment The filter allows adjustment of colorlevels.Itisacustomwaytomapanintervalofcolorintoanotherone.Theuser can set the input minimum and maximum levels, gamma and theoutputminimumandmaximumlevels(manytoolscallthemrespectivelyinput blackpoint,whitepoint, graypoint, output blackpoint andwhitepoint).

• VertexColorColourisationAllowstheapplicationofacolortothemesh.InspiteoftheFilloperation,thecolorisblendedwiththemeshaccordingtoagivenintensity..

• VertexColorDesaturationThefilterdesaturatesthecolorsofthemesh.Thisprovidesasimplewaytoconvertameshingraytones.Theusercanchoose the desaturationmethod to apply; they are based on Lightness,LuminosityandAverage.

• Equalize Vertex ColorThe filter equalizes the colors histogram. It is akindofautomaticregulationofcontrast;thecolorshistogramisexpandedtofitalltherangeofcolors.

• VertexColorWhiteBalanceThefilterprovidesastandardwhitebalancetransformation.ItisdonecorrectingtheRGBchannelswithafactorsuchthat,thebrightercolorinthemesh,thatissupposedtobewhite,becomesreallywhite.

• BoxCreateaBox• SphereCreateaSphere• IcosahedronCreateanIcosahedron• DodecahedronCreateanDodecahedron• TetrahedronCreateaTetrahedron• OctahedronCreateanOctahedron• ConeCreateaCone• Conditional Vertex Selection Boolean function using muparser lib to

perform vertex selection over current mesh. It's possible to useparenthesis, per‐vertex variables and boolean operator:(,),and,or,<>,=It'spossible touse the followingper‐vertexvariables in the expression:x, y, z, nx, ny, nz (normal), r, g, b (color), q (quality), rad, vi,andallcustomvertexattributesalreadydefinedbyuser.

• Conditional Face Selection Boolean function using muparser lib toperform faces selection over current mesh.It's possible to use parenthesis, per‐vertex variables and booleanoperator:(,),and,or,<>,=It's possible to use per‐face variables like attributes associated to thethree vertex of every face.x0,y0,z0 for first vertex; x1,y1,z1 for second vertex; x2,y2,z2 for thirdvertex.

Page 23: 1 MeshLab Documentation

23

and also nx0,ny0,nz0 nx1,ny1,nz1 etc. for normals and r0,g0,b0 forcolor,q0,q1,q2forquality.

• Geometric Function Geometric functionusingmuparser lib to generatenewCoordYoucanchangex,y,zforeveryvertexaccordingtothefunctionspecified.It's possible to use the following per‐vertex variables in theexpression:x, y, z, nx, ny, nz (normal), r, g, b (color), q (quality), rad, vi,andallcustomvertexattributesalreadydefinedbyuser.

• Per­Face Color Function Color function usingmuparser lib to generatenewRGBcolorforeveryface.Insertthreefunctioneachoneforred,greenandbluechannelrespectively. It'spossibletouseper‐facevariables likeattributes associated to the three vertex of every face.x0,y0,z0 for first vertex; x1,y1,z1 for second vertex; x2,y2,z2 for thirdvertexandalsonx0,ny0,nz0nx1,ny1,nz1etc. fornormalsandr0,g0,b0forcolor,q0,q1,q2forquality.

• Per­VertexColorFunctionColorfunctionusingmuparserlibtogeneratenewRGB color for every vertex. Insert three function each one for red,greenandbluechannelrespectively.It'spossibletousethefollowingper‐vertex variables in the expression: x, y, z, nx, ny, nz (normal), r, g, b(color), q (quality), rad, vi, and all custom vertex attributes alreadydefinedbyuser.

• Per­VertexQualityFunctionQualityfunctionusingmuparsertogeneratenewQualityforeveryvertex.It'spossibletousethefollowingper‐vertexvariables in the expression: x, y, z, nx, ny, nz (normal), r, g, b (color), q(quality),rad,vi,andallcustomvertexattributesalreadydefinedbyuser.

• Per­FaceQualityFunctionQuality functionusingmuparser togeneratenewQuality for every face. Insert three functioneachone forqualityofthe three vertex of a face. It's possible to use per‐face variables likeattributes associated to the three vertex of every face.x0,y0,z0 for first vertex; x1,y1,z1 for second vertex; x2,y2,z2 for thirdvertex.andalsonx0,ny0,nz0nx1,ny1,nz1etc.fornormalsandr0,g0,b0forcolor,q0,q1,q2forquality.

• DefineNewPer­VertexAttributeAddanewPer‐Vertexscalarattributeto current mesh and fill it with the defined function.ThenamespecifiedbelowcanbeusedinotherfilterfunctionIt'spossibleto use the following per‐vertex variables in the expression:x, y, z, nx, ny, nz (normal), r, g, b (color), q (quality), rad, vi,andallcustomvertexattributesalreadydefinedbyuser.

• DefineNewPer­FaceAttributeAddanewPer‐Faceattributetocurrentmesh.Youcanspecifycustomnameandafunctiontogenerateattribute'svalue. It's possible to use per‐face variables in the expression:x0,y0,z0 for first vertex; x1,y1,z1 for second vertex; x2,y2,z2 for thirdvertex.andalsonx0,ny0,nz0nx1,ny1,nz1etc.fornormalsandr0,g0,b0forcolor,q0,q1,q2forquality.namespecifiedbelowcanbeusedinotherfilterfunction

• GridGeneratorGenerateanew2DGridmeshwithnumberofverticesonX and Y axis specified by user with absolute length/height.It'spossibletocenterGridonorigin.

• ImplicitSurfaceGenerateanewmeshthatcorrespondstothe0valuedisosurfacedefinedbythescalarfieldgeneratedbythegivenexpression

Page 24: 1 MeshLab Documentation

24

• RefineUser­DefinedRefinecurrentmeshwithuserdefinedparameters.SpecifyaBooleanFunctionneeded to selectwhichedgeswillbe cut forrefinementpurpose.Eachedgeisidentifiedwithfirstandsecondvertex.Arguments accepted are first and second vertex attributes:x0,y0,z0 x1,y1,z1 for coord nx0,ny0,nz0 nx1,ny1,nz1 for normalr0,g0,b0 r1,g1,b1 for color q0 q1 for quality.Coords for new vertex on edge are generated with function x,y and zYoucanusex0,y0,z0andx1,y1,z1

• LoopSubdivisionSurfacesApplyLoop'sSubdivisionSurfacealgorithm.Itisanapproximatemethodwhichsubdivideeachtriangleinfourfaces.Itworksforeverytriangleandhasrulesforextraordinaryvertices

• Butterfly Subdivision Surfaces Apply Butterfly Subdivision Surfacealgorithm. It is an interpolatedmethod, defined on arbitrary triangularmeshes.TheschemeisknowntobeC1butnotC2onregularmeshes

• RemoveUnreferencedVertexCheckforeveryvertexonthemeshifitisreferencedbyafaceandremovesit

• RemoveDuplicatedVertexCheck foreveryvertexon themesh if therearetwoverticeswithsamecoordinatesandremovesit

• RemoveZeroAreaFacesRemovesnullfaces(theonewithareaequaltozero)

• Remove Faces with edges longer than... Remove from the mesh alltriangles whose have an edge with lenght greater or equal than athreshold

• ClusteringdecimationCollapseverticesbycreatingathreedimensionalgridenvelopingthemeshanddiscretizesthembasedonthecellsofthisgrid

• Quadric Edge Collapse Decimation Simplify a mesh using a QuadricbasedEdgeCollapseStrategy,betterthanclusteringbutslower

• Quadric Edge Collapse Decimation (with texture) Simplify a texturedmeshusingaQuadricbasedEdgeCollapseStrategy,betterthanclusteringbutslower

• MidpointSubdivisionSurfacesApplyaplainsubdivisionschemewhereeveryedgeissplitonitsmidpoint

• Re­OrientallfacescoherentlyRe‐orientinaconsistentwayallthefacesofthemesh

• InvertFacesOrientation Invert facesorientation, flip thenormalof themesh

• RemoveNonManifoldFacesRemovenon2‐manifoldedgesbyremovingsomeofthefacesincidentonnonmanifoldedges

• Remove Non Manifold Vertices Remove non 2‐manifold vertices, thatverticeswherethenumberof facesthatcanbereachedusingonly face‐face connectivity is different from thenumberof faces actually incidentonthatvertex.Typicalexamplethinktotwoisolatedtrianglesconnectedbyasinglevertexbuildingahourglassshape.

• ComputenormalsforpointsetsComputethenormalsoftheverticesofameshwithoutexploitingthetriangleconnectivity,usefulfordatasetwithnofaces

• Compute curvature principal directions Compute the principaldirectionsofcurvaturewithseveralalgorithms

Page 25: 1 MeshLab Documentation

25

• CloseHolesCloseholessmallerthanagiventhreshold• FreezeCurrentMatrixFreezethecurrenttransformationmatrixintothe

coordsoftheverticesofthemesh• ApplyTransformApplytransformation,youcanrotate,translateorscale

themesh• Geometric Cylindrical Unwrapping Unwrap the geometry of current

meshalongaclylindricalequatorialprojection.ThecylindricalprojectionaxisiscenteredontheoriginanddirectedalongtheverticalYaxis.

• MLS projection (RIMLS) Project a mesh (or a point set) onto the MLSsurfacedefinedby itselforanotherpointset.This is theRobustImplicitMLS (RIMLS) variant which is an extension of Implicit MLS preservingsharp features using non linear regression. For more details see:Oztireli, Guennebaud and Gross, 'Feature Preserving Point Set SurfacesbasedonNon‐LinearKernelRegression'Eurographics2009.

• MLS projection (APSS) Project a mesh (or a point set) onto the MLSsurfacedefinedby itselforanotherpoint set.This is thealgebraicpointsetsurfaces(APSS)variantwhichisbasedonthelocalfittingofalgebraicspheres. It requires points equipped with oriented normals.For all the details about APSS see: Guennebaud and Gross, 'AlgebraicPoint Set Surfaces', Siggraph 2007, andGuennebaud et al., 'DynamicSamplingandRenderingofAPSS',Eurographics2008

• Marching Cubes (RIMLS) Extract the iso‐surface (as amesh) of aMLSsurface defined by the current point set (or mesh)using the marchingcubes algorithm. The coarse extraction is followed by an accurateprojectionstep onto the MLS, and an extra zero removal procedure.ThisistheRobustImplicitMLS(RIMLS)variantwhichisanextensionofImplicitMLSpreserving sharp features usingnon linear regression. Formore details see: Oztireli, Guennebaud and Gross, 'Feature PreservingPointSetSurfacesbasedonNon‐LinearKernelRegression'Eurographics2009.

• Marching Cubes (APSS) Extract the iso‐surface (as a mesh) of a MLSsurface defined by the current point set (or mesh) using themarchingcubes algorithm. The coarse extraction is followed by an accurateprojection step onto the MLS, and an extra zero removal procedure.This is thealgebraicpoint set surfaces (APSS)variantwhich isbasedonthe local fitting of algebraic spheres. It requires points equipped withoriented normals. For all the details about APSS see:GuennebaudandGross,'AlgebraicPointSetSurfaces',Siggraph2007,andGuennebaud et al., 'Dynamic Sampling and Rendering of APSS',Eurographics2008

• Colorizecurvature(RIMLS)Colorizetheverticesofameshorpointsetusingthecurfvatureoftheunderlyingsurface.ThisistheRobustImplicitMLS (RIMLS) variant which is an extension of Implicit MLS preservingsharp features using non linear regression. For more details see:Oztireli, Guennebaud and Gross, 'Feature Preserving Point Set SurfacesbasedonNon‐LinearKernelRegression'Eurographics2009.

• Colorize curvature (APSS) Colorize the vertices of amesh or point setusingthecurvatureoftheunderlyingsurface.This isthealgebraicpointsetsurfaces(APSS)variantwhichisbasedonthelocalfittingofalgebraic

Page 26: 1 MeshLab Documentation

26

spheres. It requires points equipped with oriented normals.For all the details about APSS see: Guennebaud and Gross, 'AlgebraicPoint Set Surfaces', Siggraph 2007, and Guennebaud et al., 'DynamicSamplingandRenderingofAPSS',Eurographics2008

• Estimate radius from density Estimate the local point spacing (akaradius)aroundeachvertexusingabasicestimateofthelocaldensity.

• SmallcomponentselectionSelectthesmalldisconnectedcomponentsofamesh.

• Poisson Reconstruction Use the points and normal to build a surfaceusingthePoissonSurfacereconstructionapproach.

• QualityMapperapplierThefiltermapsqualitylevelsintocolorsusingacolorbandbuiltfromatransferfunction(maybeloadedfromanexternalfile) and colorizes the mesh vertexes. The minimum, medium andmaximum quality values can be set by user to obtain a custom qualityrangeformapping

• MeshElementSubsampling Create anew layerpopulatedwithapointsamplingofthecurrentmesh,Atmostonesampleforeachelementofthemesh is created. Samples are taking in a uniform way, one for eachelement(vertex/edge/face);alltheelementshavethesameprobabiltyofbeingchoosen.

• Montecarlo Sampling Create a new layer populated with a pointsampling of the current mesh; samples are generated in a randomlyuniform way, or with a distribution biased by the per‐vertex qualityvaluesofthemesh.

• StratifiedTriangleSamplingCreateanewlayerpopulatedwithapointsampling of the current mesh; to generate multiple samples inside atriangle each triangle is subdivided according to various stratifiedstrategies.Distributionisoftenbiasedbytriangleshape.

• Poisson­disk Sampling Create a new layer populated with a pointsampling of the current mesh; samples are generated according to aPoisson‐diskdistribution

• Variable density Disk Sampling Create a new layer populated with apointsamplingofthecurrentmesh;samplesaregeneratedaccordingtoaPoisson‐diskdistribution

• Hausdorff Distance Compute the Hausdorff Distance between twomeshes, samplingoneof the twoand finding foreachsample theclosestpointovertheothermesh.

• TexelSamplingCreateanewlayerwithapointsamplingofthecurrentmesh,asampleforeachtexelofthemeshisgenerated

• Vertex Attribute Transfer Transfer the choosen per‐vertex attributesfrom one mesh to another. Useful to transfer attributes to differentrepresentationsofasameobject.Foreachvertexof thetargetmeshtheclosest point (not vertex!) on the source mesh is computed, and therequested interpolatedattributes fromthatsourcepointarecopied intothe target vertex. The algorithm assumes that the two meshes arereasonablysimilarandaligned.

• Uniform Mesh Resampling Create a new mesh that is a resampledversionofthecurrentone.Theresamplingisdonebybuildingauniformvolumetricrepresentationwhereeachvoxelcontainsthesigneddistance

Page 27: 1 MeshLab Documentation

27

from the original surface. The resampled surface is reconstructed usingthemarchingcubealgorithmoverthisvolume.

• Voronoi Vertex Clustering Apply a clustering algorithm that buildsvoronoi cells over the mesh starting from random points,collapse eachvoronoicell toasinglevertex,andconstructthetriangulationaccordingto the clusters adjacency relations. Very similar to the techniquedescribed in 'Approximated Centroidal Voronoi Diagrams forUniformPolygonalMeshCoarsening'‐ValetteChassery‐Eurographics2004

• Voronoi Vertex Coloring Given a MeshM and a Pointset P, The filterproject each vertex of P overM and colorM according to the geodesicdistancefromtheseprojectedpoints.Projectionandcoloringaredoneonapervertexbasis.

• DiskVertexColoringGivenaMeshMandaPointsetP,ThefilterprojecteachvertexofPoverMandcolorMaccording to thegeodesicdistancefrom these projected points. Projection and coloring are done on a pervertexbasis.

• Regular Recursive Sampling The bbox is recrusively partitioned in aoctreestyle,centerofbboxareconsidered,whenthecenter isnearertothesurfacethanagiventhritisprojectedonit.Itworksalsoforbuildingofsettedsamples.

• SelectAllSelectallthefacesofthecurrentmesh• SelectNoneClearthecurrentsetofselectedfaces• Delete Selected Faces Delete the current set of selected faces, vertices

thatremainsunreferencedarenotdeleted.• Delete Selected Faces and Vertices Delete the current set of selected

facesandalltheverticessurroundedbythatfaces.• ErodeSelectionErode(reduce)thecurrentsetofselectedfaces• DilateSelectionDilate(expand)thecurrentsetofselectedfaces• SelectBorderFacesSelectallthefacesontheboundary• InvertSelectionInvertthecurrentsetofselectedfaces• SelectbyVertexQualitySelectall the faceswithall thevertexeswithin

thespecifiedqualityrange• SelectFacebyVertexColorSelectpartofthemeshbasedonitscolor.• Move selection on another layer Selected faces are moved (or

duplicated)inanewlayer• DuplicatecurrentlayerCreateanewlayercontainingthesamemodelas

thecurrentone• Planar flipping optimization Mesh optimization by edge flipping, to

improvelocaltrianglequality• CurvatureflippingoptimizationMeshoptimizationbyedgeflipping, to

improvelocalmeshcurvature• Laplaciansmooth(surfacepreserve)Laplaciansmoothwithoutsurface

modification: move each vertex in the average position of neighborsvertices,onlyifthenewpositionstill(almost)liesonoriginalsurface

• Cut mesh along crease edges Cut the mesh along crease edges,duplicatingtheverticesasnecessary.Creaseedgesaredefinedaccordingtothevariationofnormaloftheadjacentfaces

Page 28: 1 MeshLab Documentation

28

• Laplacian Smooth Laplacian smooth of the mesh: for each vertex itcalculatestheaveragepositionwithnearestvertex

• HC Laplacian Smooth HC Laplacian Smoothing, extended version ofLaplacianSmoothing,basedonthepaperofVollmer,Mencl,andMuller

• ScaleDependent Laplacian Smooth Scale Dependent LaplacianSmoothing, extended version of Laplacian Smoothing, based on theFujiwaraextendedumbrellaoperator

• TwoStep Smooth Two Step Smoothing, a feature preserving/enhancingfairing filter. It is based on a Normal Smoothing step where similarnormalsareaveragedtogetherandastepwherethevertexesarefittedonthenewnormals

• TaubinSmoothThe$lambda‐mu$taubinsmoothing,itmaketwostepsofsmoothing,forthandback,foreachiteration

• Depth Smooth A laplacian smooth that is constrained tomove verticesonlyalongtheviewdirection.

• DirectionalGeom.Preserv. Store andBlend the current geometrywiththe resultof anotherprevious smoothingprocessing step. It isuseful tolimit the influence of any smoothing algorithm along the viewingdirection.Thisisimporttocopewiththebiaseddistributionoftheerrorin many scanning devices. TOF scanner usually have very good x,yaccuracybutsufferofgreatdeptherrors.

• SmoothvertexqualityLaplaciansmoothofthequalityvalues.• Smooth Face Normals Smooth Face Normals without touching the

positionofthevertices.• UnSharpMaskNormalsUnsharpmaskfilteringofthenormals,puttingin

moreevidencenormalvariations• UnSharp Mask Geometry Unsharp mask filtering of geometric shape,

puttinginmoreevidenceridgesandvalleysvariations• UnSharpMaskQualityUnsharpmaskfilteringofthequalityfield• UnSharpMaskColorUnsharpmaskfilteringofthecolor,puttinginmore

evidencecoloredgevariations• Recompute Vertex Normals Recompute vertex normals as an area

weightedaverageofnormalsoftheincidentfaces• RecomputeWeighted Vertex Normals Recompute vertex normals as a

weighted sum of normals of the incident faces. Weights are definedaccordingtothepaperWeightsforComputingVertexNormalsfromFacetNormals,Nelsonmax,JGT1999

• RecomputeAngleWeightedVertexNormalsRecomputevertexnormalsasanangleweightedsumofnormalsoftheincidentfacesaccordingtothepaper Computing Vertex Normals from Polygonal Facet, G Thurmer, CAWuthrich,JGT1998

• RecomputeFaceNormalsRecomputefacenormalsasthenormaloftheplaneoftheface

• NormalizeFaceNormalsNormalizeFaceNormalLenghts• NormalizeVertexNormalsNormalizeVertexNormalLenghts• VertexLinearMorphingMorphcurrentmeshtowardsatargetwiththe

same number of vertices. The filter assumes that the twomeshes havealsothesamevertexordering.

Page 29: 1 MeshLab Documentation

29

• Removeborder facesRemoveall the faces thathasat leastonebordervertex.

• NoisyIsosurfaceCreateaisosurfaceperturbedbyanoisyisosurface.• Colorize by border distance Store in the quality field the geodesic

distancefrombordersandcolorthemeshaccordingly.• RandomvertexdisplacementMovetheverticesofthemeshofarandom

quantity.• Flatten visible layers Flatten all or only the visible layers into a single

new mesh. Transformations are preserved. Existing layers can beoptionallydeleted

• VertexColorNoiseRandomlyaddasmallamountofarandombasecolortothemesh

SimplificationSimplificationfiltersarefiltersthatgetininputameshandbuildanothermeshcomposedbyasmallernumberoftriangles.TherearethreesimplificationfiltersinsideMeshLab

• Clustering.Basedonasimplevertexclusteringapproach.Auniformgridisusedtocollapsealltheverticesfallinginthesamegridcellontoasinglevertex. It is a very fast algorithmbut not very accurate, a bound of theintroduced error is half of the diagonal of each grid cell. Topologicalinconsistencies are quite probable that will be created (non manifoldedges). This is a typical drawbackof any clustering‐based simplificationalgorithms. In our implementation the only parameter that can bespecifiedby theuser is the lengthof thesideof thecubicgridcell.Thislengthcanbe introducedeitherasanabsolutevalue in thespaceof themeshitself,orasapercentageofthediagonaloftheboundingboxoftheobject.Withthiskindofapproachyoucannotknowinadvancethefinalsize of the mesh, but only knowing what could be at the end the finalaverageedgelength(e.g.approx.thesameofthegridcellside).

• Quadric edge collapse. A variant of the well known edge collapsealgorithm based on quadric error metric proposed by Michael GarlandandPaulHeckbert.Theusercancontrolthequalityofthesimplificationthroughsomeparameters:

o Quality threshold for penalizing edge collapses that creates badshaped faces.The value is in the range [0..1] (0 a degeneratetriangle1aequilateralone); thevalueof thisparametermustbeinterpretedasfollows:

0acceptanykindofface(nopenalties), kpenalizefaceswithqualitythank,proportionallytotheir

shapequality.o Normalcheckingforpenalizingedgecollapsesthatflipthenormal

of theoriginal surfaces (it canhelp to avoid somenasty artifactsthatcanariseinveryflatareas).

• Quadricedgecollapsewithtexturecoordinatespreservation

Page 30: 1 MeshLab Documentation

30

PointPickingToolDescriptionThistoolcanbasicallybedescribedasameshlabelingtool.Itallowsyoutopickandnamepointsonameshandsavetheoutputtoxml.The tool has twomainmodes, normal and templatemode. Templatemode isdescribedbelow.Therearetwomainmodesofinteractionwiththepoints,PickPoint,MovePoint,andSelectPointmode.Themodeofinteractionisindicatedby theradioat the top. Inpickmodeyouaddnewpoints to themeshbyrightclickingonthemesh.Inmovemodeyoucanmoveapointbyrightclickingnearthepointanddraggingittoadifferentlocation.Inselectmodeyoucanrightclickapointonthemeshanditwillbehighlightedinthepickpointsedittoolmenu.Here are some notes about the active checkbox. The immediate affect ofcheckingtheactivecheckboxistohide/showthepickedpointonthemesh.Thisfeature ismeant to allowyou touse a template forwhich some scandatawillhaveoneof the templatepointsmissing. In thiscaseyoucanunflag thispoint,labelingitin‐active.Whenpointsareaddedyouhaveagreencone,representingthenormal,witha labelnext to it.Youcanalsochooseat thebottomwhere itsaysNormalOptionstohavejustadot,whichisthepoint,alabelforthatpoint,oradot,label,andagreenlinewhichrepresentsthenormalofthefacethepointison.TemplateModeSummary:Templatesareusetofacilitatethelabelingofmanymesheswiththesamelabels.IfyouhaveatemplateloadedyouareinTemplateMode.Thenameof the templatewill bewritten in blue letters next to the place at the bottomwhere it says "Template Name:". "No Template Loaded" will be printed if notemplateisloaded.InTemplatemodeyouwillonlybeabletopickandmovethepoints thatarealreadydefinedaspartof the template.Use theAddPointandRemovePointbuttonsintheTemplateControlsareatomodifyatemplate.Youcan also start from scratch, pick some points, then save them as a template(savingthenamessoyoucanusethemforothermeshes).Saving/LoadingPointsPointsaresavedtoaxmlfilebyusingthesavebuttonatthetop.Pointscanbeloaded from a file by pressing the load button. Alternately points areautomatically loaded froma file if youhadpreviously saved themusing thefilename recommended by the tool. Points are saved to PerMeshAttributesautomatically when you close the edit plugin and loaded back fromPerMeshAttributewhenthepluginis loaded.Thistakesprecedentoverloadingpointsfromafile.OtherFeatures

1. Renameapointbyslowlydoubleclickingonit2. Undo:willundoonlythatlastmove

Page 31: 1 MeshLab Documentation

31

UseWith"AlignMeshusingPickedPoints"filterIn order to use theAlignMesh using Picked Points filter you need to haveeithersavedpoints:

1. toPerMeshAttributesor2. toafilewiththenamesuggestedbythepointpickingplugin.

Note:thatpointsareonlyneededif"UseMarkersforAlignment"ischecked.Note: that if "Scale the mesh" is checked then you need points and to havechecked"UseMarkersforAlignment".Note: the transform calculated is stored in per mesh data with keyAlignTools::getKey()NotesforDeveloperswhowanttousepickedpointsintheirpluginYoucanlookathowthefilterFP_ALIGN_WITH_PICKED_POINTSinthecleanfilterpluginusespointspickedbytheedit_pickpointsplugin.Note,mostcodeishere,cleanfilter/cleanfilter.cppbuttheimportantbitishere:MeshModel *stuckModel = par.getMesh(StuckMesh); PickedPoints*stuckPickedPoints = 0; ... //first try to get points from memoryif(vcg::tri::HasPerMeshAttribute(stuckModel‐>cm, PickedPoints::Key) ) { CMeshO::PerMeshAttributeHandle<PickedPoints*> ppHandle = vcg::tri::Allocator<CMeshO>::GetPerMeshAttribute<PickedPoints*>(stuckModel‐>cm,PickedPoints::Key); stuckPickedPoints=ppHandle();What you get is a PickedPoints object. To see what it does look here/meshlabplugins/edit_pickpoints/pickedPoints.h(cpp).Basically what you need to know is that this class hold astd::vector<PickedPoint*>where aPickedPoint is a simple object that has twomembers:

1. nameofpoint:QStringname;2. point:vcg::Point3fpoint;

Otherinformation

• sourcecodeinedit_pickpointsfolderMorpherToolDescriptionThisisafairlysimplepluginthatallowsyoutomorphbetweenanytwomeshesthathavethesamenumberofvertexes.Themorphiscalculatedanddisplayedinrealtimeasyouslidetheslider.Details

• Themorph is a simple linearmorphbetween the correspondingpoints.Example:Amorphof50calculatesthepoint50%betweenthefirstpointofmeshAandthefirstpointofmeshB,thengoesontothesecondpoint,etc

• NOTE: does compact the mesh removeing deleted elements usingAllocator<MyMesh>::CompactVertexVector(m);andAllocator<MyMesh>::CompactFaceVector(m);

Page 32: 1 MeshLab Documentation

32

Otherinformation• sourcecodeinfilter_morphfolder

MLSSurfacesMoving least squares (MLS) filters provide suite of tools built upon variousmeshlesssurfacedefinitions.ThesetofsupportedMLSsurfacesvariantsinclude:

• Adamson and Alexa's point set surfaces based on normal averaging(specialcaseofAPSS),

• Guennebaud and Gross's algebraic point set surfaces (APSS) which arebasedofspherefitting,

• Kolluri'simplicitMLSvariantofShenetal.approach.Notethatallthesedefinitionsrequireverticesequippedwithorientednormals.If no local radius is provided, then they are automatically computed using thePointSet/Radiusestimationfilter.AllMLSfilterstakeasinputapointset(ortheverticesof amesh), implicitlydefine theunderlying surface, and thenperformvariousoperationssuchas:

• Meshingofthesurfaceusingamarchingcubealgorithm.• SmoothingbymeanofaprojectionontotheunderlyingMLSsurface.Itis

possibletoproject/smooththeinputverticesthemself,oranyothersetofpoints ofmeshing assuming they are close enough to the target surface(currently). If the geometry to project is a mesh, then it is possible torefineitduringtheprojectionaccordingtosomelocalerrormetrics(heretheanglebetweentwoadjacentfaces).

• Curvatureplots:colorizestheverticesofapointset(ormesh)accordingtothecurvatureoftheunderlyingMLSsurface.ItprovidesexactanalyticscurvaturecomputationsfortheGauss,meanandprincipalcurvatures.

Filtershighlyrelatedtopointsetsurfacesincludes:• PointSet/Radiusestimationwhichcomputesthelocalpointspacingof

each vertices of a point set. This filter use a basic estimate of the localdensityusingtheknearestneighborsandassumingalocallyuniformandflatsampling.

• Normals/Compute from point set which can be used to computeorientednormalsofarawpointcloud.

• Select/Small components which can be used to select (and thenremove) all the extra zero components which can appears after amarchingcubereconstructionoftheMLSsurface.

QhullFilterGeneralDescriptionTheQhull Filter plugin is a collection of filters used for computing the convexhull,Delaunaytriangulation,VoronoiFilteringandAlphaShapesoverthemesh.It also includes a filter for the selection of the visible points from a givenviewpoint. Every single filters uses the Qhull library for mathematicaloperations.

Page 33: 1 MeshLab Documentation

33

FunctionFilterListConvexHullThis filter computes theconvex hull of the currentmesh. It is contained in theRemeshingfilterclass.Theconvexhullofasetofpoints istheboundaryoftheminimal convex set containing the given non‐empty finite set of points.The filter takes the mesh vertices and builds a new mesh that contains theconvex hull. Here it is the Qhull library documentation of the program thatcalculates the convex hull of a set of points. The result is 2‐manifold bydefinition,soitispossibletore‐orientallfacescoherently.

Originalimage

ConvexHull

DelaunayTriangulationThis filter computes the Delaunay triangulation of the current mesh. It iscontainedintheRemeshingfilterclass.TheDelaunaytriangulationDT(S)ofasetofpointsSind‐dimensionalspacesisatriangulationoftheconvexhullsuchthatno point in S is inside the circum‐sphere of any simplex in DT(S).The filter takes the mesh vertices and builds a new mesh that contains theDelaunay triangulation. Here it is the Qhull library documentation of theprogramthatcalculatestheDelaunaytriangulationofasetofpointsS.

Originalimage

DelaunayTriangulation

VoronoiFilteringThefilterimplementsaVoronoifilteringonthecurrentmesh.It iscontainedinthe Remeshing filter class. The algorithm computes a piecewise‐linearapproximationofasmoothsurfacefromafinitesetofsamplepointsthatdefinesa "well‐sampled" curve. It uses a subset of the Voronoi vertices to removetrianglesfromtheDelaunaytriangulation.ThealgorithmpicksonlytwoVoronoivertices,calledpoles,persamplepoint:thefarthestverticesofthepoint'scelloneachsideofthesurface.

Page 34: 1 MeshLab Documentation

34

HereitisthemainstepsproposedbyAmentaandBern(1998):

1. ComputetheVoronoidiagramofthesamplepointsS.2. Foreachsamplepointsdo:

1. If s does not lie on the convex hull of S, let p+ be the vertex ofVor(s)farthestfroms.

2. If s does lie on the convex hull, let p+ be a point at "infinitedistance"outsidetheconvexhullwiththedirectionofsp+equaltotheaverageoftheoutwardnormalsofhullfacesmeetingats.

3. Pick the vertex p‐ of Vor(s) farthest from s with negativeprojectionontosp+.

3. LetPdenotesallpolesp+andp‐,exceptthosep+'sat infinitivedistance.ComputetheDelaunaytriangulationofSUP.

4. (Voronoi filtering) Keep only those triangles inwhich all three verticesaresamplepoints.

Thefilterallowstheusertochooseathreshold,afactorthatdefinesarange(0‐threshold*bbox.Diag()) used to discard the Voronoi vertices too far from theorigin.Theycancauseproblemstotheqhulllibrary.GrowingvaluesofthresholdwilladdmoreVoronoiverticesforabettersurfacereconstruction.AlphaShapesThe filter computes theAlpha Shape (Edelsbrunner and P.Mucke 1994) of thecurrentmesh. It is contained in theRemeshing filter class. Froma given finitepoint set in the space it computes the shape of the set. The alpha shape is theboundary of the alpha complex, that is a subcomplex of the Delaunaytriangulation of the given point set S. For a given value of 'alpha', the alphacomplex includesall thesimplices intheDelaunaytriangulationwhichhaveanempty circumsphere with radius equal or smaller than 'alpha'. Here 'empty'meansthattheopenshperedonotincludeanypointsofS.The algorithm uses the general‐position assumption by Edelsbrunner andP.Mucke that states that no smallest circumsphere of two or three points of ScontainsanotherpointofS.IfaspherecontainsthreepointsofSthennotwoofthemareantipodal,andifitcontains four points then no three lie on a great‐circle of the sphere. (ACMTransitiononGraphics,Vol.13,no1, January1994). 'alpha'controls thedesiredlevelofdetailoftheshape.Notethatfor'alpha'=0,boththealphacomplexandthe alpha shape consist just of the set S, and for sufficiently large 'alpha', thealphacomplexistheDelaunaytriangulationDT(S)ofS,insteadthealphashapeistheconvexhullofS.Thealphavalueiscomputedaspercentageofthediagonalof thebox.Usercanchoose toget thealphacomplexor thealphashapeof themesh. The filter inserts theminimum value of alpha (the circumradius of thetriangle)inattributeQualityforeachface,soitcanbeeasiertodefineafiltrationonthemesh(thealphashapes).

Page 35: 1 MeshLab Documentation

35

Imagesforalphacomplexes

Originalimage

Alpha=51.34

Alpha=85.57

Alpha=290.92

.Imagesforalphashapes

Originalimage

Alpha=2

Alpha=3

Alpha=4

SelectVisiblePointsThefilterselectsthevisibleverticesofthecurrentmesh,asviewedfromagivenviewpoint. It is contained in the Selection and Point Set filter class.The algorithm used (Katz, Tal and Basri 2007) determines visibility withoutreconstructingasurfaceorestimatingnormals.Apointisconsideredvisibleifitstransformedpointliesontheconvexhullofatransformedpointscloudfromtheoriginal given points. Here it is the equation used to perform the sphericalflipping(Katzetal.2005):f(p)=p+2*(R‐||p||)*p/||p||ItisimportanttochooseasuitablevalueforR.AsRincreases,morepointspassthe threshold of the convex hull and hence aremarked as visible. A largeR issuitable for dense point clouds, and a small R for sparse clouds. The radius iscomputedasthedistancebetweentheviewpointanditsfarthestpointandthenadjusted with a parameter (threshold)inserted by the user. radius=distancebetweenthecenteranditsfarthestpoint*10^threshold.UsercanchoosetousetheMeshlabCameraastheviewpointorinserthisownone.Usercanalsochoosetoshowthepartialconvexhullof thetransformedpoints(theviewpoint isnotincluded)andameshconnectingthevisiblepointsaccordingtotheconnectivityoftheflippedones.Itisalsopossibletore‐orientallfacescoherently.SupportedFormats

Page 36: 1 MeshLab Documentation

36

ThefollowingformatsaresupportedbyMeshLabImport

• PLY, ascii and binary. Many variants supported. Triangle strip loadingsupported.plyRangemapformatstillnotsupported

• STL,asciiandbinary.Colornotsupported.• OFF,• OBJ,• 3DS,• COLLADA,• PTX

Export

• PLY,• STL,• OFF,• OBJ,• 3DS,• COLLADA,• VRML,• DXF• U3D

CompilingdevelWhatyouneedTo compile MeshLab you need a C++ compiling environment, (we regularlycompile meshlab under VisualStudio 2005, gcc and xcode) and the followinglibraries:

• Qt4.4(notethatQt4.4arerequired,Qtversions<4.4couldnotcompile).CurrentversionofMeshLabcompileswellagainstQt4.4.3.

• Asvn‐client(foralistofexistingsvn‐clientsyoucouldtakealookhere).• the VCG libraries; http://vcg.sf.net, this library is not distributed by

means of easy‐to‐download packages, but it is only accessible throughanonymous svn (svn string: svn cohttps://vcg.svn.sourceforge.net/svnroot/vcg vcg ). If you get the currentversionoftheVCGlibrarywesuggestyoutoalsogetthecurrentversionofMeshLab.IfyouwanttocompilethedistributedsourcescheckoutfromtherepositorytheVCGlibwiththesamedateofthereleaseofMeshLab.

• MeshLab'ssourcecodeavailableviaSourceForgesvnserver.Forfurtherdetailspleasereferstothefollowingsection

GettingthesourcesForgetting the latest versionofMeshLabyouhave to anonymously access theMeshLab svn tree as explained in the sourceforge pagehttp://sourceforge.net/svn/?group_id=149444;forthelazyones,togettherightsubset of the svn trunk in thedevel folder you should issue the following svncommand:

Page 37: 1 MeshLab Documentation

37

svn co https://meshlab.svn.sourceforge.net/svnroot/meshlab/trunk/meshlabmeshlab svn co https://vcg.svn.sourceforge.net/svnroot/vcg/trunk/vcglibvcglibExternalDependenciesMeshLab and MeshLab's plugins invokes functions exported by externallibraries. The code of all these libraries is included in the MeshLab's currentdevelopment version downloadable via svn. You can find it in the folder~/devel/meshlab/src/external.

• glew ( http://glew.sourceforge.net/ ), strongly required. You just needthesources(.hand.c),(notthecompiledlibs),glewisstaticallycompiledintomeshlab,sonodynamiclibrariesarerequired.

• lib3ds‐1.3.0(http://lib3ds.sourceforge.net/)Thisoneisneededonlyforthe io_3ds plugin. Without this plugin the 3ds file formats will not beparsed.

• bzip2‐1.0.3thisoneisrequiredonlyfortheepochformatimportplugins;ifyoudonothavedatasetsproducedwiththearc3Dwebreconstructionservice,youdonotneedthisplugin.

• muParser 1.30 ( http://muparser.sourceforge.net/ ) This library isneededforfilter_funcplugin.

In order to successfully compile aMeshLab's pluginwith external dependencyyou have before to compile the referred library and put it into the folder~/devel/meshlab/src/external/lib/YOUR_OSwhereYOUR_OSisastringrelatedtoyouroperatingsystemandcompileraccordingtoQMAKESPECdefinition(likefor example macx or win32­msvc2005).Intothefolder~/devel/meshlab/src/externala .profile,external.pro,hasbeenprovidedtoeasilycompilealltheexternallibraries.Todothisyoucaneither:

• useaQt‐friendlyIDE,likeQtCreator,VisualStudioorEclipse(thelasttwowiththeIDE'sQtintegrationprovidedbyTrolltech)

• usecommandline.qmake‐recursiveexternal.promakeAnote:whenwesaythatalibraryisneededonlyforaspecificpluginwemeanthat if youdonothave that libraryyou shouldnot try to compile that specificplugin otherwise the compilation of that plugin could fail on that plugin and,dependingonyourcompilingenvironment,thewholecompilationcouldstop.Toavoidthecompilationofproblematicpluginssimplycommentstherelativeline(adding a # at the beginning of the line) in thesrc/meshlabplugins/meshlabpluginsv12.pro.CodetreestructureThemeshlabsourcesandthevcglibrarymustbeatthesamelevelandthevcglibraryrootshouldbenamed'vcglib'.Theexternalcompiledlibrariesshouldbeplaced in a dir named~/devel/meshlab/external/lib/YOUR_OS (see the abovesection).You should have setup your directories in away that should be similar to thefollowingones(obviouslyyouarenotforcedtocallyourbasedirdevelortoputitunderyourhomedir):

Page 38: 1 MeshLab Documentation

38

~/devel/vcglib/vcg/space/ ~/devel/meshlab/src/meshlab/interfaces.h~/devel/meshlab/external/lib/YOUR_OSIfyouputthingsindirswithdifferentrelations,youhavetomanuallychangethe.pro.Pleasenotethatifyouareadeveloperthatwillsoonorlatersubmitbackitswork, it isstronglydeprecated thatyouuseyourownversionof .pro files:usethestandardsetup.CompilingThe compiling step depends on the compiling environment. Using GCC (bothunderlinuxandusingthemingwgccprovidedwiththefreeQtdistribution)youshouldjusttype,fromthedevel/meshlab/srcdirectory:qmake‐recursivemeshlabv12.promakethedevel/meshlab/srcdirectorycontainsalso themeshlab_mini.proproject thatcontainsamuchsmallersetof themeshlabplugins. It iseasiertocater for(noneedforlib3dsandbzip)andcompilesfaster.Underwindows the suggested platform is the one formed by the open sourceversion ofQtwith themingwgcc compiler that is kindly included in the opensourceQtdistributionavailablefromTrollTech.If youwant touseVisual Studio, pleasebuy the commercial versionofQt thatoffersaniceintegrationoftheQttoolsintotheVisualStudioIDE.Inthatcaseyousimplyhavetoimportthetoplevelpro(~/devel/meshlab/src/meshlab.pro)intoVisualStudio.UsingMicrosoftVisualStudio8expresseditionandQTIt ispossibletousetheVisualStudio8expressedition(theonefreefromMS).Simplestepsforthelazyones:

• downloadandinstallMicrosoftVisualStudio8expressedition• download from trolltech QT 4.4.3 , the zip with the sources not the

precompiledbinformingw.• unzip it and rename the created folder to c:\Qt\4.4.3 (or something

differentifyoualreadyhaveinstalledtheqtdistributionwithmingw.• Nowopenthevisualstudioconsole(programfiles‐>visualstudio2008‐>

vs2008tools‐>vs2008commandpromt).Gotothedirectorywhereyouunzippedqt and type configure ‐debug‐and‐release.Wait a fewmins (itcompilesqmakeandrunsit,creatingthemakefilesforvs2008)

• typenmake.Waitafewhours(itrecompilesthewholeQt).• laststep:preparetheenvironment;youhavetoaddtotheenvironmentof

vs8commandprompt:set QTDIR=C:\Qtvs\4.4.3 set PATH=C:\Qtvs\4.4.3\bin setPATH=%PATH%;%SystemRoot%\System32setQMAKESPEC=win32‐msvc2008

• after that just start that enhanced vs8 command prompt, go in theappropriatedir,type

qmake‐tpvc‐recursivemeshlabv12.pro• andmagically a solution that containsmeshlab and all the pluginswill

appear.• In some cases it could help also to configure visual C++, so it can see

always Qt: (tools‐>options) and add: $(QTDIR)\include to the includedirectories and $(QTDIR)\lib to the lib directories, but it should not berequired(andperhapsabitdangerousifyouupgradeqt).

Page 39: 1 MeshLab Documentation

39

WritingaPluginMeshLabhas a reasonablymodular architecture,mostof its functionalities areimplemented as dynamically loaded plugins. To extend meshlab with newfunctionalities you have to write new plugins. There is a fixed small set ofpossiblepluginstypesformeshlab,themostimportantonesare:

• filter plugins. The most common class of plugins. These pluginsimplementstraightmeshfilteringoperations,e.g.proceduresthattakeininputameshandasetofparametersandmodifies itaccordingtosomealgorithm (smoothing, cleaning, simplification etc). Note that theparameter asking through a dialog is usually managed by the meshlabframework. These filters can be used also from meshlabserver thecommandlineversionofthemeshlab.

• i/oplugins.Theseplugins implement fileparsingmechanism.Theycanrequireparametersbeforeandaftertheprocessingofthefile,forexampletodecideifameshhastobesavedinbinaryformatornot,ortoloadonlya subset of the original data, or to perform some kind of standardpostprocessingontheinputmesh(likeforexamplestlvertexunification).

• editplugins. Theseplugins implement functionalities that require non‐trivial user input and direct mesh interaction, like painting, selection,measuringandthatcouldrequireacomplexcustomdialog.

o NOTE:Theeditpluginscannotbeusedfrommeshlabserver.o MeshEditInterfaceImplementationGuide

You can find very simple examples of the above described plugins in themeshlab/src/sampleplugins/directory.Obviouslyfollowingthecodingrecommendationisalwayswarmlysuggested.Thenewpluginsshouldbenamedaccordingtothefollowingnamingstrategy:

• editpluginsshouldbenamededit_something• filterpluginsshouldbenamedfilter_something• iopluginsshouldbenamedio_something

Thenameof thepluginandof the .pro fileshouldbethesameof thedirectoryname.Obviously,onceyouhavesucceedtosetuptheframeworkforyourplugin,youhave to actually make something on your mesh. For an introduction on howaccesstheelementsofthemeshandhowtouse/modifythemlookatthepagesthatexplainshowaccessingthemeshandwhatalgorithmsarepresentinthevcglibrary.MeshDatastructureTwo cents on the basic types inside MeshLab, whose declaration are inmeshmodel.h:

• the basic document type is aMeshDocument that is basically a list ofMeshModel.

• eachMeshModel corresponds to one layer and contains a vcgmesh oftypeCMeshO

Page 40: 1 MeshLab Documentation

40

• CMeshOisthevcgmeshtype(avcg::trimesh)thatyoushouldprovidetothevariousvcgAlgorithmsandfromwhichyoushouldgetFaceIterators,VertexIteratorsandotherstypes...

So for examplewhen you open a file, a newMeshDocument is created,with asingle layer that contains the loadedmesh. Some filters can create or destroylayers,forexamplethesamplingfiltersusuallycreateanewlayercontainingthesampledpointclouds.Filterscanworkoronasinglelayeroronallthelayers.It isvery important that filterskeepcoherentandupdated thesetofelementsthat are currently active for a givenmesh, like for example colors, curvature,adjacencyetc.WritingyourfirstfilterFirstsuggestion,startwithwritingapluginofthefilterclass.Theyaretheeasiestone,no interactionhas tobemanaged,nodialoghas tobedesigned, youhaveonlytodothefollowingsteps:

• think to your plugin in terms of something taking a mesh and someparametersandworkingonit.

• define the requirements for your mesh (do you need any kind oftopology?colors?etc)

• definetheparametersusingthestandardmethodofthefilterclass• define the applymethod that uses the provided parameters on a given

mesh.Look at the sample in the sampleplugins directory, at the 'samplefilter' pluginand try tomodify it a bit. Remember to change the name of the class you arederivingforyourpluginwhenyoustartwithyourownplugin.SVNFor committing back your code please follow CLOSELY the suggestions in theWritingCodepage.ObviouslyfordoingthatyouneedtobearegisteredMeshLabDeveloperonthesourceforgeproject.WhatisVCGLib?TheVCGLibcouldbedefinedasalibraryformanagingtrianglemeshes,butthatwould be unfair. VCG Lib is a library for managing 0,1,2 and 3‐simplicialcomplexes,whichmeansPointSets,EdgeMesh,TriangleMeshandTetrahedralMeshes.Tobecompletelyhonest,itisstartingtosupportpolygonmeshesaswell(staytuned).It justhappens that the research interestsof thedevelopers leaded todevelopmeshprocessingalgorithmsmostly for trianglemeshes,but thekernel is therewaiting... However, to avoid annoying the reader with 0‐simplices, maximalsimplicesandsoon, in this tutorialwewillalwaysrefer to thecaseof trianglemeshes,extendingtheexplanationtotheothercasesonlywhereappropriate.please note: this is not a referencemanual, but a short tutorial to guide youthrough the few basic concepts of VCG Lib. The idea is that after reading thistutorialandtryingthefewexamplesinapps/samples/referredinthefollowing,youwillhaveallittakestowriteyourowncode.

Page 41: 1 MeshLab Documentation

41

InstallationandfolderstructureGettingVCGLibVCGLibuses a SVN repository.To get the right subset of the svn trunk in thedevelfolderyoushouldissuethefollowingsvncommand:svncohttps://vcg.svn.sourceforge.net/svnroot/vcg/trunk/vcglibvcglibWindowsuserswithtortoisesvn(http://www.tortoisesvn.net)installedshould1.createafoldernamedvcglib.2.right‐clickinthenewlycreatedvcglibfolderand choose SVN Checkout 3. put in the first parameter:https://vcg.svn.sourceforge.net/svnroot/vcg/trunk/vcglib4.pressokandwait,itshouldstarttocheckoutthelastrevisionofthewholetree.FolderStructure

Mainarticle:FolderstructureVCGLib ismostlymadeofheader files(and itscorepart it'sonlyheader files).Just download the tarball fromhere anduncompress it in a folder, e.g. namedvcg,insideyoucompiler"include"directory.Afterwards,youwillincludethefileyouneed.Insidevcgfolderyouwillfind4sub‐folders:

• vcg: this is the core of the library, where all the algorithms and datastructures are defined. This part is pure, quite heavily templated, C++codewithSTLsupport forcommondatastructuresandalgorithms.Youwill not find a single include from here to anything else than standardlibraries.Notethatcorepartismadeofheaderfiles(.hfiles)only.

• wrap:hereyouwill findthewrappingofVCGconceptstowardsspecificneeds/contexts/libraries. For example you will find all the code toimport/export meshes from the hard disk in many formats, or theroutines for rendering triangle meshes with OpenGL, supports forcommonGUItoolslikeatrackball,andsoon..

• apps:thisfoldercontainsthecommandlineapplicationsdevelopedwiththeVCGLib.Many(muchmore)examplescanbefoundinMeshLab.Theapps/simpledirectorycontainsasub‐collectionofverybasicapps.Agoodstartingpointforbeginners!

• docs:documentationliveshere(includingthistutorial)BasicConceptsHowtodefineameshtypeTheVCGLibencodesameshasasetofverticesandtriangles(i.e. triangles fortrianglemeshes,tetrahedrafortetrahedralmeshes).ThefollowinglinewillbeapartofthedefinitionofaVCGtypeofmesh:class MyMesh: public vcg::TriMesh< std::vector<MyVertex>,std::vector<MyFace>>{}vcg::TriMeshisthebasetypeforatrianglemeshanditistemplatedon:

• thetypeofSTLcontainercontainingtheverticeso whichinturnistemplatedonyourvertextype

• thetypeofSTLcontainercontainingthefaceso whichinturnistemplatedonyourfacetype

Page 42: 1 MeshLab Documentation

42

ThefaceandthevertextypearethecrucialbitstounderstandinordertobeabletotakethebestfromVCGLib.Avertex,anedge,afaceandatetrahedronarejustan user defined (possibly empty) collection of attribute. For example youwillprobablyexpectMyVertextocontainthe(x,y,z)positionofthevertex,butwhatabout the surface normal at the vertex?.. and the color? VCG Lib gives you apretty elegant way to define whichever attributes you want to store in eachvertex,face,oredge.Forexample,thefollowingexampleshowsthreevaliddefinitionsofMyVertex:#include <vcg/simplex/vertex/base.h> #include<vcg/simplex/vertex/component.h> class MyFace; class MyEdge; classMyVertex0: public vcg::VertexSimp2<MyVertex0, MyEdge, MyFace,vcg::vertex::Coord3d, vcg::vertex::Normal3f> {}; class MyVertex1: publicvcg::VertexSimp2<MyVertex1, MyEdge, MyFace, vcg::vertex::Coord3d,vcg::vertex::Normal3f, vcg::vertex::Color4b> {}; class MyVertex2: publicvcg::VertexSimp2<MyVertex2,MyEdge,MyFace>{};vcg::VertexSimp2is theVCGbaseclass foravertexbelongingtoa2‐simplex. Ifwe were to define a tetraedral mesh, for example, we would have usedvcg::VertexSimp3. The first 3 templates of vcg::VertexSimp2 must specify thetypeofallthesimpliciesinvolvedinthemeshinascendingorder:thevertextypeitself, thetypeofedgeandthetypeoftriangle(andthetypeoftetrahedronforthetetrahedralmeshes).Itcanbeannoyingwhenyouseeitbutitisusefulthateveryentity involvedknowsthetypeof theothersandthis is thewayVCGLibdoesit.AsyoucanseethethreedefinitionsofMyVertexdifferfortheremainingtemplate parameters. These specify which attributes will be stored with thevertex type:MyVertex0 isa typestoringcoordinatesasa tripleofdoublesandnormal as a triple of floats, MyVertex1 also store a color value specified as 4bytes and MyVertex2 does not store any attribute, is an empty class.vcg::Coord3d,vcg::Normal3f,vcg::Color4bandmanyothersareimplementedinVCG, their complete list can be found here. You can place any combination ofthemasatemplateparametersofyourvertex(yoursimplex)type.NowwehaveallittakesforaworkingdefinitionofMyMeshtype:/* apps/sample/trimesh_base/trimesh_definition.h */ #include <vector>#include <vcg/simplex/vertex/base.h> #include<vcg/simplex/vertex/component.h> #include <vcg/simplex/face/base.h>#include <vcg/simplex/face/component.h> #include<vcg/complex/trimesh/base.h>classMyEdge;classMyFace;classMyVertex:public vcg::VertexSimp2<MyVertex, MyEdge, MyFace, vcg::vertex::Coord3d,vcg::vertex::Normal3f> {}; class MyFace: public vcg::FaceSimp2<MyVertex,MyEdge, MyFace, vcg::face::VertexRef> {}; class MyMesh: publicvcg::tri::TriMesh<std::vector<MyVertex>,std::vector<MyFace>>{};intmain(){MyMeshm;return0;}Onemorecomment:vcg::VertexRef isanattribute thatstores3pointers to thetypeofvertex,soimplementingtheIdexedDatastructure.ThisisanexampleofwhythetypeMyFaceneedstoknowthetypeMyVertex

Page 43: 1 MeshLab Documentation

43

note: Although we left the STL type of container of vertices and faces as atemplate parameter, at the current state many kernel algorithms of VCG LibassumestheyareSTLvector,so ifyoupassastd::listoramapyouruseof thelibrarywillbequitelimited.HowtocreateameshOnceyoudeclaredyourmeshtype,youmaywanttoinstanceanobjectandtofillitwithvertexesandtriangles.Itmaycrossyourmindthatyoucouldjustmakesomepush_backonthevertexesandfacescontainer(datamembervertandfaceofclassvcg::tri::Trimesh). In fact this is thewrongwaysince therecanbesideeffectsbyaddingelementtoacontainer.WedescribethisissueandthecorrectwayofaddingmeshelementintheAllocationpage.TheflagsofthemeshelementsUsually toeachelementof themeshweassociateasmallbitvectorcontainingusefulsingle‐bit informationaboutverticesandfaces.Forexamplethedeletionof vertex simply mark a the Deletion bit in thsi vector (more details on thevarious deletion/allocation issues in the Allocation page. More details on thevariouskindofflagsthatcanbeassociatedareintheFlagspage.HowtoprocessameshThe algorithms that do something on a mesh are generally written as staticmemberfunctionsofaclasstemplatedonthemeshtype.Forexamplethecodesnipped below is part of the class UpdateNormals, which contains the severalalgorithmstocomputethevalueofthenormal/** vcg/complex/trimesh/update/normal.h */ ... template <classComputeMeshType>classUpdateNormals{...///Calculatesthevertexnormal(ifstoredinthecurrentfacetype)staticvoidPerFace(ComputeMeshType&m)///Calculates the vertex normal.Without exploiting or touching face normals ///The normal of a vertex v is theweigthed average of the normals of the facesincidentonv.staticvoidPerVertex(ComputeMeshType&m)///Calculatesbothvertexandfacenormals.///Thenormalofavertexvistheweigthedaverageofthe normals of the faces incident on v. static voidPerVertexPerFace(ComputeMeshType&m)...};ThisclassispartofakernelofclasseswithnameUpdateValuethatcomputethevalue of the vertex or face attributes and that can be found altogether in thefolder vcg/complex/trimesh/update. For example, the followingexample showhowtocompute thevalueof thenormaland themeanandgaussiancurvaturepervertex:/* apps/sample/trimesh_base/trimesh_definition.h */ #include <vector>#include <vcg/simplex/vertex/base.h> #include<vcg/simplex/vertex/component.h> #include <vcg/simplex/face/base.h>#include <vcg/simplex/face/component.h> #include<vcg/complex/trimesh/base.h> #include<vcg/complex/trimesh/update/normals.h> //class UpdateNormals#include <vcg/complex/trimesh/update/curvature.h> //classUpdateCurvature class MyEdge; class MyFace; class MyVertex: publicvcg::VertexSimp2<MyVertex,MyEdge,MyFace, vcg::vertex::Coord3d,vcg::vertex::Normal3f,vcg::vertex::Curvaturef>{}; class MyFace: public

Page 44: 1 MeshLab Documentation

44

vcg::FaceSimp2<MyVertex,MyEdge,MyFace, vcg::face::VertexRef>{}; classMyMesh: public vcg::tri::TriMesh< std::vector<MyVertex>, std::vector<MyFace>>{};intmain(){MyMeshm;//fillthemesh...//computethenormalper‐vertex ‐> update the value of v.N() forall v (vcg::vertex::Normal3f)vcg::tri::UpdateNormals<MyMesh>::PerVertexPerFace(m); // compute thecurvature per‐vertex ‐> update the value of v.H() and v.K()(vcg::vertex::Curvaturef)vcg::tri::UpdateCurvature<MyMesh>::MeanAndGaussian(m);return0;}Other than algorithms that update values of the mesh attributes, VCG Libprovides algorithms to create a mesh from another source, for example frompoint sets (by means of the Ball Pivoting apprach) or as isosurfaces from avolumetric dataset (bymeans of Marching Cubes algorithm). Those algorithmcanbefoundinvcg/complex/trimesh/create/.Finally,youcanfindalgorithmsforrefinement(midpoint,Loop,Butterfly...),forsmoothing,forclosingholesandotherthatarenotcurrentlyclassifiedunderanyspecificheadingandthatyoucanfindunder/vcg/complex/trimesh.OptionalComponentTherearemanycaseswheresomevertexorfaceattributesarenotnecessaryallthetime.VCGLibgivesyouawaytospecifyoptionalcomponents, i.e.attributesthatarenotstaticallystoredwithinthesimplexbutcanbedynamicallyallocatedwhenyouneedthem.Weusethetermcomponenttoindicatethattheyarepartofthesimplextypeandthatthereisamemberfunctiontoaccesstheirvalue.To'define'optionalcomponentyouneedtodotwothings:

• touseaspecialtypeofcontainer(derivedfromstd::vector)• tospecifytherighttypeofcomponentinthetemplateparameters

An optional component can be accessed when the memory for it has beenallocated, in which case we say that the component is 'enabled'. An optionalcomponentcanbeenablebycallingthefunctionEnable.VCGLibhandlesoptionalcomponentswithtwoalternativemechanisms:thefirstis called 'Ocf' (for Optional Component Fast) which uses one pointer for eachsimplexbutitmakesaccessingoptionalattributealmostasfastasnon‐optionalones; the second is called 'Occ' (forOptional ComponentCompact)whichonlyrequires a little extra space for each mesh (unrelated to its size in terms ofnumberofsimplicies)butwhichcanresult inasloweraccess. Inthefollowing,onlytheiruseisdiscussed.Theimplementationdetailcanbefoundhere.OptionalComponentFastThefollowingdefinitionofMyMeshspecifiesthatthe'normal'componentofthetypeMyVertexisoptional.Thedifferencesfromthepreviousexampleareshowninbold.

• include theheader for theoptional_component_ocf.hwhichcontains thedefinitionsfortheoptionalattributes;

• include the special attribute <vcg::vertex::Info> as first attribute of thetypevcg::vertex::VertexSimp2;

• usethetypevcg::vector_ocfasthecontainerofyourvertices;• include the type vcg::vertex::Normal3fOcf among the template

parameters

Page 45: 1 MeshLab Documentation

45

/* check apps/sample/trimesh_optional/trimesh_optional.cpp */ #include<vector> #include <vcg/simplex/vertex/base.h> #include<vcg/simplex/vertex/component_ocf.h> #include<vcg/simplex/face/base.h> #include <vcg/simplex/face/component.h>#include<vcg/complex/trimesh/base.h> classMyEdge; classMyFace; classMyVertex: publicvcg::VertexSimp2<MyVertex,MyEdge,MyFace,vcg::vertex::InfoOcf,vcg::vertex::Coord3d, vcg::vertex::Normal3fOcf>{}; class MyFace: publicvcg::FaceSimp2<MyVertex,MyEdge,MyFace,vcg::face::VertexRef>{}; classMyMesh: public vcg::tri::TriMesh<vcg::vertex::vector_ocf<MyVertex>,std::vector<MyFace> >{}; int main() { MyMesh m; // ...fill the mesh...MyMesh::VertexIterator vi = m.vert.begin(); (*vi).N() =vcg::Point3f(1.0,1.0,1.0);//ERROR m.vert.EnableNormal();//thisallocatethe memory to store the normal (*vi).N() = vcg::Point3f(1.0,1.0,1.0); // OKm.vert.DisableNormal(); // this deallocate the memory to store the normal(*vi).N()=vcg::Point3f(1.0,1.0,1.0);//ERROR(again)!return0;}Beforeaccessingthedatacontainedinthenormalcomponent,youmustenabletheattributebycallingEnableNormal(),afterwardsthespaceforthecomponentwillbeallocatedandaccessibleuntilyoucallDisableNormal().Tryingtoaccessthe value of the normal before enabling or after disabling the correspondingcomponentwillthrowanassertion.OptionalComponentCompactThe following definition ofMyMesh specifies that the 'normal' attribute of thetypeMyVertexisoptional.TouseaOcccomponentyoumust:

• include#include<vcg/simplex/vertex/component_occ.h;• usethetypevcg::vector_occasthecontainerofyourvertices.• specify the attribute normal as optional by passing

vcg::vertex::Normal3fOccamongtemplateparametersofVertexSimp2./* check apps/sample/trimesh_optional/trimesh_optional.cpp */ #include<vector> #include <vcg/simplex/vertex/base.h> #include<vcg/simplex/vertex/component_occ.h> #include<vcg/simplex/face/base.h> #include <vcg/simplex/face/component.h>#include<vcg/complex/trimesh/base.h> classMyEdge;classMyFace; classMyVertex: public vcg::VertexSimp2<MyVertex,MyEdge,MyFace,vcg::vertex::Coord3d, vcg::vertex::Normal3fOcc>{}; class MyFace: publicvcg::FaceSimp2<MyVertex,MyEdge,MyFace,vcg::face::VertexRef>{}; classMyMesh: public vcg::tri::TriMesh< vcg::vertex::vector_occ<MyVertex>,std::vector<MyFace> >{}; int main() { MyMesh m; // ...fill the mesh...MyMesh::VertexIterator vi = m.vert.begin(); (*vi).N() =vcg::Point3f(1.0,1.0,1.0); // ERRORm.vert.Enable<vcg::vertex::NormalType>(); // this allocate the memory tostore the normal (*vi).N() = vcg::Point3f(1.0,1.0,1.0); // OKm.vert.Disable<vcg::vertex::NormalType>();//thisdeallocatethememorytostore the normal (*vi).N() = vcg::Point3f(1.0,1.0,1.0); // ERROR (again)!return0;}Beforeaccessingthedatacontainedinthenormal,youmustenabletheattributeby calling EnableAttribute<vcg::vertex::Normal3fOcc::NormalType>(),

Page 46: 1 MeshLab Documentation

46

afterwards the attribute will be allocated and accessible until you callDisableAttribute<vcg::vertex::Normal3fOcc::NormalType>().Tryingtoaccessthevalue of the normal before enabling or after disabling the correspondingattributewillthrowanassertion.Twoimportantthingsaboutoptionaloptionalcomponents:

• Theaccess function to thevalueofa component is the sameboth if thecomponentisoptionalandifit'snot.Thismeansthatyoudonothavetomakethisdistinctionwhencodingyouralgorithm

• Ifyoumakeacopyofthevertex(face)andthentrytoaccessacomponentitwon'twork. Themechanisms for optional attributesworks using thepositionofthevertex(face)inmemory.Inotherwords,theoptionaldataisassociatedwithapositionof thecontainer (vector_ocforvector_occ)andnotboundtothevertexitself.

User­definedattributesVCGLibalsoprovidesasimplemechanismtoassociateuser‐defined'attributes'to thesimpliciesand to themesh.Note thatboth 'attributes'and 'components'are basically accessory data that are bound to a simplex. Conceptually thedifference is thatwith the termcomponentVCGLib indicates those values thatare considered to 'define' the simplex (its position, its normal its connectivityinformation),while theuserdefinedattribute isanaccessorydatawhichmakesense to some specific algorithm, like "the number of time a vertex has beenmoved"or"apointertoastringcontainingadescriptionofthevertex".Practicallythedifference isthateveryoptionalcomponenthas itsnonoptionalcounterpartand isaccessedthroughamember functionof thesimplex,so thatwhenyouwriteyouralgorithmyouusev.N()toaccessthenormalbothitishasbeendeclaredasoptionalornot,while theattributesareaccessedbyahandlewhichisreturnedatthecreationoftheattribute.Thefollowingcodesnippetshowsanexample:/* apps/sample/trimesh_attribute/trimesh_attribute.cpp */#include<vcg/simplex/vertex/base.h>#include<vcg/simplex/vertex/component.h>#include<vcg/simplex/face/base.h> #include<vcg/simplex/face/component.h>#include<vcg/complex/trimesh/base.h>#include<vcg/complex/trimesh/allocate.h>classMyFace;classMyVertex;classMyEdge; // dummy prototype never used class MyVertex : publicvcg::VertexSimp2< MyVertex, MyEdge, MyFace,vcg::vertex::Coord3f,vcg::vertex::Normal3f>{}; class MyFace : publicvcg::FaceSimp2< MyVertex, MyEdge, MyFace, vcg::face::VertexRef,vcg::face::Normal3f> {}; class MyMesh: public vcg::tri::TriMesh<std::vector<MyVertex>, std::vector<MyFace> > {}; floatIrradiance(MyMesh::VertexTypev){ //..... return 1.0; } int main() {MyMeshm;//...heremisfilled//addaper‐vertexattributewithtypefloatnamed "Irradiance" MyMesh::PerVertexAttributeHandle<float> ih =vcg::tri::Allocator<MyMesh>::AddPerVertexAttribute<float>(m,std::string("Irradiance")); // add a per‐vertex attribute with type floatnamed "Radiosity"vcg::tri::Allocator<MyMesh>::AddPerVertexAttribute<float>

Page 47: 1 MeshLab Documentation

47

(m,std::string("Radiosity")); //addaper‐vertexattributewithtypeboolandno name specified MyMesh::PerVertexAttributeHandle<bool> blocked_h =vcg::tri::Allocator<MyMesh>::AddPerVertexAttribute<bool> (m);MyMesh::VertexIteratorvi;inti=0;for(vi=m.vert.begin();vi!=m.vert.end();++vi,++i){ ih[vi] = Irradiance(*vi); //[]operatortakesa iterator ih[*vi]=Irradiance(*vi);//oraMyMesh::VertexTypeobjectih[&*vi]=Irradiance(*vi);//orapointertoit ih[i] =Irradiance(*vi);//oranintegerindex} //Once created with AddPerVertexAttribute, an handle to the attribute can beobtained as follows MyMesh::PerVertexAttributeHandle<float> rh =vcg::tri::Allocator<MyMesh>::GetPerVertexAttribute<float>(m,"Radiosity");//you can query if an attribute is present or not bool hasRadiosity =vcg::tri::HasPerVertexAttribute(m,"Radiosity"); //youcandeleteanattibuteby namevcg::tri::Allocator<MyMesh>::DeletePerVertexAttribute<float>(m,"Radiosity");// you can delete an attibute by handlevcg::tri::Allocator<MyMesh>::DeletePerVertexAttribute<bool>(m,blocked_h);}The same can be done for the faces, just replace the occurrences of PerVertexwithPerFace.Notethatifyoucalladdanattributewithoutspecifyinganameandyoulosethehandle,youwillnotbeabletogetyourhandleback.Note:

• Donotgetmixupthescopeofthehandlewiththememoryallocationofthe attribute. If you do not delete an attribute explicitly, it will beallocated until the mesh itself is destroyed, even if you do not havehandlestoit.

C++typeofameshandreflectionVCGLibprovidesasetoffunctionstoimplementreflection,i.e.toinvestigatethetype of a mesh at runtime. These functions follow the formatHas[attribute](mesh)andreturnabooleanstating if thatparticularattribute ispresentornot.template<class ComputeMeshType> static voidUpdateNormals<ComputeMeshType>::PerVertex(ComputeMeshType &m) {if(!HasPerVertexNormal(m))return;...}You may wonder why those functions are not statically typed and why theyneeds the mesh object, i.e. why can't you just writeComputeMeshType::HasPerVertexNormal()? The reason is that VCG Libreflection takes into account optional components, thereforeHasPerVertexNormal(m)will return true if the type of the vertex contains theattributeaspermanent(e.g.vcg::vertex::Normal3f)ORifitcontainstheattributeas optional (e.g. vcg::vertex::Normal3fOcf) AND it is enabled, i.e. the relativeEnablefunctionhasbeencalled.AdjacencyVCG Lib does not have a hard‐coded way to encode the adjacencies amongsimplices. It alldependsonwhichattributesare storedwith the simplicesandhow they are used. I the previous examples the definition of face has alwaysincludedtheattributevcg::face::VertexRef,whichstores3pointerstoMyVertex

Page 48: 1 MeshLab Documentation

48

accessible with the member function V() (the well known Indexed DataStructure).Thereasonisthatalmostallofthealgorithmscurrentlyimplementedin VCG Lib assume its presence. So, if your typeMyFace does not include theattribute vcg::face::VertexRef, the definition will be correct but almost noalgorithmwillwork. There are other adjacency relations that can be useful tonavigate amesh, for example to collect theone‐ringneighborhoodof a vertex.VCGLibusestwomechanismswhichareexplainedinthefollowing,alongwiththeattributestheyuse.FFAdjacencyTheface‐to‐faceadjacency,storedintheattributeforthefacesvcg::face::FFAdj(vcg::face::TTAdj for tetrahedra), encodes the adjacency of faces (tetrahedra)through edges (faces). The image below shows two triangle faces with theconventionadoptedforindexingvertexesandedges.Thevertexesarenumberedfrom0to2inCCWsenseandtheedgei=0..2istheedge whose extremes are i and (i+1) mod 3 . Therefore the common edgebetweenfacesf1andf2istheedge1ofthefacef1andtheedge0ofthefacef0.vcg::face::FFAdjstores,foreachedgeeofthefacef:

• FFp(e):apointertoa facef'sharinge. Ife isaborderthanpointstothefacefitself

• FFi(e):theindexofeinthepointedface•

Indexingofvertexesandedges

f1‐>FFp(1)==f0f1‐>FFi(1)==0f0‐>FFp(0)==f1f0‐>FFi(0)==1

Note thatwespecified thatFFp(e)point toaadjacent face,not totheadjacentface.The reason is that there couldbemore than two faceson the sameedge,and this is seamlessly supportedbyVCGLib. In thepicturebelow is shownanexamplewith4facesincidenttothesameedge

Nonmanifoldedge

Page 49: 1 MeshLab Documentation

49

Inthiscasetheadjacenciesaresettoformacircularlist(notnecessarilysortedwiththeanglearoundtheedge).ThisisdonebytheVCGLibfunctionthatupdatethesevalues(UpdateTopology<MeshType>::FFTopology(MeshType&m)).InthiswayVCGLibprovidesawaytocheckifameshismanifoldonaspecificedge because the FF adjacency relation ismutual, i.e. the face f0 points to theface f1whichpoints to the face f0, if andonly if themesh ismanifold over thecorrespondingedge.boolIsManifold(MyFace*f,inte){return(f==f‐>FFp(e)‐>FFp(f‐>FFi(e)))}Referringtothepicture:(f0==f0‐>FFp(0)‐>FFp(f0‐>FFi(0))}equals(f0==f1‐>FFp(0)}equals(f0==f0}Ok!ItismanifoldPosThePosistheVCGLibimplementationoftheCell‐Tuple{ref}.Herewegiveaasshort as possible definition, trading formalisms for space. A Pos in a trianglemeshisatriplemadeofavertex:pos=(v,e,f),suchthatvisanextremeofeandebelong to the face f . The figure shows few pos in a triangle mesh as smalltriangles"pointing"toavertex,"leaning"againstanedgeandinsideaface.Forexamplec0=(v,e0,f).Averynicepropertyisthatgivenaposc, thereisonlyanotherneighborposc'thatcanbeobtainedfromcchangingonlyoneoftheelementsofthetriple.WecalltheoperationofpassingfromapostooneofitsneighborsFlipandwriteFlipV,FlipEandFlipFtoindicatethattheflippedelementisthevertex,theedgeorthefacerespectively.For example consider c1: there is only another pos which is the same as c0exceptforthevertexcomponentofthetriple,anditisc2.Forbrevity,wewritec2=FlipV(c1).In the leftof the table someotherexamplesare shown just tomake thispointclear.

c2 = FlipV(c1)c0 = FlipE(c1)c3 = FlipF(c0)CCW around vc4=FlipE(FlipF(c0))c5=FlipE(FlipF(c4))Bouncec6=FlipE(FlipF(c5))CW around vc3=FlipE(FlipF(c6))c1=FlipE(FlipF(c3))Bouncec0=FlipE(FlipF(c1))

Page 50: 1 MeshLab Documentation

50

Notethatconcatenatingtwoflips:FlipFandFlipEweobtainatransitionfromapos to the next in counterclockwise or in clockwise sense, depending if thestartingposisontheCCWedgeofthefacewithrespecttothevertexornot.Alsonotethat,thankstohowFFadjacencyisdefined,whenaposisontheborder,itbouncesback.ThispairofflipsarewidelyusedintheVCGLibtorunovertheoneringneighborhoodofmanifoldvertices.Thefollowingcodesnippetshowshowtousethepostoiteratearoundavertex:/* vcglib/apps/sample/trimesh_pos_demo/trimesh_pos_demo.cpp */ #include<vcg/simplex/face/pos.h>//includethedefinitionofpos//...includestodefineyour mesh type //class MyVertex: ... class MyFace: publicvcg::FaceSimp2<MyVertex,MyEdge,MyFace,vcg::face::VertexRef,vcg::face::FFAdj>{};voidOneRingNeighborhood(MyFace*f) { MyVertex * v = f‐>V(0); MyFace* start = f; vcg::face::Pos<MyFace>p(f,0,v);// constructor that takes face, edge and vertex do { p.FlipF();p.FlipE();}while(p.f!=start);}Twoimportantnotes:

• Wearbitrarilypickedf‐>V(0)aspivotvertex.Ingeneralonemaywanttostart knowing the vertex. This is done by including the attributevcg::vertex::VFAdj which basically associates to each vertex pointer tooneofthefacesincidentonit.SeetheVFAdjacencyfordetails.

• Thisimplementationdoesnotworkifthevertexisontheborder.Justtrywith theexample: fromtheposc4 itwould findc5,c6,c3which is in thesamefaceasc4.Ofcoursethisdoesnothappenifyouusethepositselfasa guard and not just the face. However, even in this case, you wouldobtain the sequence of pos: c5,c6,c3,c1,c0,c4 corresponding to the facesf2,f2,f1,f0,f0,f1whichprobably isnotwhatyouwant.VCGLibprovidesavariationofposthatsolvesthisproblem

JumpingPosThe Jumping Pos works exactly like the Pos, only it does not bounce when itencounterstheborder.Instead,itjumpsaroundthesharedvertexoftheborder‐facesasiftheywereadjacent(facesf0andf2intheimage)./* vcglib/apps/sample/trimesh_pos_demo/trimesh_pos_demo.cpp */ #include<vcg/simplex/face/jumping_pos.h> // include the definition of jumping pos//...includestodefineyourmeshtype//classMyVertex:...classMyFace:publicvcg::FaceSimp2<MyVertex,MyEdge,MyFace,vcg::face::VertexRef,vcg::face::FFAdj>{}; voidOneRingNeighborhoodJP(MyFace*f){MyVertex*v=f‐>V(0);MyFace*start=f;vcg::face::JumpingPos<MyFace>p(f,0,v);// constructor that takes face, edge and vertex do { p.NextFE();}while(p.f!=start);}VFAdjacencyVCGLibimplementsvertex‐to‐faceadjacency,i.e.givenavertexvwecanretrieveallthefacesincidenttov.Letv_star=(f0,f1,f2,...,fk)bethesetfacesincidenttovarranged inasequence(withnopreferredcriteria).VCGLiballows toretrievev_starinoptimaltime(O(#star_v)byusingthefollowingattributes:

• vcg::vertex::VFAdjwhichisavertexattributecontainingapointertof0

Page 51: 1 MeshLab Documentation

51

• vcg::face::VFAdjwhichisafaceattributecontainingapointertothenextfaceinthelistv_starforeachofits3vertices(4inthecaseoftetrahedra)

Thesetwoattributesarenotonlypointers,theyalsocontainanindexreferringthe index of the vertex in the pointed face in the same style as thevcg::face::FFAdjdoes.Thepicturebelowshowsacompleteexample:

exampleofvertex‐faceadjacency

v.VFp()==f2v.VFi()==0f2‐>VFp(0)==f3f2‐>VFi(0)==1f3‐>VFp(1)==f1f3‐>VFi(1)==2f1‐>VFp(2)==f0f1‐>VFi(2)==2f0‐>VFp(2)==NULLf0‐>VFi(2)==‐1

VFIteratorVFIteratorisasimpleiteratortorunoverthefacesintheone‐ringneighborhoodofavertexusingtheVFAdjacency(it is just likePosfortheFFAdjacency)ThefollowingcodesnippetshowshowtousetheVFIterator:/* vcglib/apps/sample/trimesh_pos_demo/trimesh_vfiter_demo.cpp */#include <vcg/simplex/face/pos.h> // include the definition of VFIterator//...includes to define your mesh type class MyVertex: publicvcg::VertexSimp2<MyVertex,MyEdge,MyFace, vcg::vertex::VFAdj /*,... otherattributes*/ >{}; class MyFace: publicvcg::FaceSimp2<MyVertex,MyEdge,MyFace,vcg::face::VertexRef,vcg::face::VFAd>{}; void OneRingNeighborhoodVF(MyVertex*v){ vcg::face::VFIterator<MyFace>vfi(v);//initializetheiteratortohefirstfacefor(;!vfi.End();++vfi){MyFace*f=vfi.F();//...dosomethingwithfacef}}FewfactsonFFadjacencyandVFadjacencyHerewemakea seriesof simple statements just toavoid confusionand try tohelpupchoosingtheadjacenciesthebestfityourneeds.

• Ifthemeshismanifold,theone‐ringneighborhoodofavertexcomputedbyusingPos(needsFFadjacency) is thesameas theonecomputedbyusingVFIterator(needsVFadjacency).Theorder inwhichthe facesarevisitedcanbeCWorCCWifusingPos,unspecifiedbyusingVFIterator

Page 52: 1 MeshLab Documentation

52

• Ifthemeshisnon‐manifold,Posmaynotfindallthefacesoftheone‐ringneighborhoodofthevertex,VFIteratoralwaysdoes

BoundaryrelationsandadjacencyInmanyalgorithmsyouneedtosimplytheboundary/borderconditionofaface,e.g.toknowifagivenfacefhasoneormoreadjacentfacesonaspecifiededgee.UsingFFadjacencythiscanbedonesimplybyusingtheface::IsBorder(f,e)staticfunctionthatsimplychecksifthepointerstoredinfacefontheedgeepointstofitself. If you are navigating the mesh using a Pos, you have a Pos memberfunction IsBorder() that reports the boundary condition of the current pos.Similarly, for testing manifoldness of specific places over a mesh, there is aface::IsManifold(f,e)static functionanda IsManifold(e) functionmemberof theposclass.If youarenotusingFFadjacencyevaluating theboundaryconditions couldbenot very efficient, so vcg library provides a technique to cook the currentboundaryconditionsofthemeshintovertexandfaceflags.Usethemembersofthe UpdateFlags static class to compute flags that reflects the current meshstatus and the access these flags using the IsB(e)member function of the faceclass. Remember that flags based boundary information can become invalid ifyouchangethemeshtopology.Ontheotherhandconsiderthatmanynon‐mesh‐modifying algorithms do not require explicit FF adjacency but just boundaryinformation (typical examples: most mesh smoothing and curvaturecomputationalgorithms).Pleasenotethattheboundaryflagsaresettruealsofornonmanifoldconditions.SpaceconceptsVCGLibimplementsthebasicfunctionalitiestohandlegeometricentitiessuchasthepoint,thesegment,thetriangleandsoon.Itisveryimportantnottoconfusethosegeometricentitiesandthetopologicalentitiestheycanbeacomponentof.In other words, the type vcg::Point3f (vcg/space/point3.h) is a point in 3dimensionalspaceandisdifferentfromavertex(vcg::VertexSimp2<...>)whichisa topological entity. The same goes for the vcg::Segment3 and thevcg::EdgeSimp2<..>,thevcg::Triangle3andthevcg::FaceSimp2.ViewingandmanipulationInthissection,allthatconcernsthedefinitionofaviewandthemanipulationofameshwillbeexplained.ShotandcameraThissectionpresentsthestructureoftheshotandcameraofthelibrary.Afteranoverview of the cameramodel used, all the components of the shot class arelistedanddescribed.Then,asetofexamplesof themost importantoperations(projection and un‐projection) and of the interactions between shots andbetween a shot and the trackball are presented. Finally, simple examples of ashotarevisuallyshown, inorder tohelpwith the implementationsofeventualwrappedtoandfromothershot‐cameraformats.

Page 53: 1 MeshLab Documentation

53

ThecameramodelIngeneral,thecameraparameterscanbedividedintwogroups:

• Extrinsic (or external) parameters: these are the parametersassociatedtothepositioninthespaceofthecamera.

• Intrinsic (or internal) parameters: these values are related to thepeculiarcharacteristicsofthecamera,likethefocallength(thezoom)orthedistortionintroducedbythelenses.

If these groups of values are put in a proper camera model, it is possible totransformanypointinthespaceinthecorrespondingpointontheimageplaneofthecamera(andviceversa).

AnexampleschemeofaperspectivecameramodelIn fact, given a simpleperspective cameramodel like theone shown in figure,extrinsicparameterscanbeusedtotransformapointfromitsworldcoordinates{xw,yw,zw}tothecamera3Dcoordinatesystem{x,y,z}):

In this case the extrinsic parameters are a 3 X 3 rotation matrix R and atranslationvectorT,whichdefinetheorientationandpositionofthecamera.Inorder to transform the 3D camera coordinate in 2D image plane coordinates(Xu,Yu)it'snecessarytoknowthemeasureofthedistancebetweenthepointofviewandtheimageplane(OO1infigure):thisvalue, indicatedwithf, isusuallyknown as the focal length. The relation between the camera and imagecoordinatesofthepointcanbeexpressedasfollows:

Page 54: 1 MeshLab Documentation

54

Another aspect of the structure of a camera that can be characterized is thedistortion introduced by the lenses: ifwe suppose that the distortion is radial(performedalongtheradialdirectionrespecttothecenterofdistortion)wecancalculatetheundistortedimagecoordinates

where

and

Inconclusion,aquiteaccuratemodelofacameracanbedescribedby:

• A3x3rotationmatrixandatranslationvectorforextrinsicparameters• The values of focal, center of distortion and one or more distortion

coefficientsforintrinsicparametersWhilethissetofparametersprovideseverythingtotransformany3Dpointinitscorresponding point in the image plane, this could be not enough in peculiarapplications.Ifanaccurateestimationoftherealpositionofthecamerarespecttotheobjectisneeded,somemoredataaboutthecameramodelareneeded:inparticular, the sensor physical size togetherwith the resolution in pixel of theacquired image. If these a‐priori data are known, a unique set of cameraparametersisassociatedtoanyshot.TheVCGShotTheimplementationofaShotintheVCGlibrarycanbefoundinvcg\math\shot.hTheshotiscomposedbytwoelements:

• theExtrinsicsparameters,whicharestoredintheclassShot(inthetypeReferenceFrame)thatcontainsviewpointandviewdirection.

TheExtrinsicsparametersarekeptasarotationmatrix "rot"anda translationvector"tra"NOTE:thetranslationmatrix"tra"correspondsto‐viewpointwhiletherotationmatrix"rot"correspondstotheaxisofthereferenceframebyrow,i.e.rot[0][012]==Xaxisrot[1][012]==Yaxisrot[2][012]==ZaxisItfollowsthatthematrixmadewiththeupperleft3x3equaltorotandthe4thcolumn equal to tra and (0,0,0,1) in the bottom row transform a point fromworldcoordinatestothereferenceframeoftheshot.

• the Instrinsics parameters, which are stored as a Camera type (checkvcg/math/camera)and thatdetermineshowapoint in the frameof thecameraisprojectedinthe2Dprojectionplane.Thisinformationwaskeptindendent of the extrinsic parameters becausemore than one shot cansharethesameintrinsicparametersset.

Page 55: 1 MeshLab Documentation

55

TheattributesofaCamera,whichisdefineinvcg\math\shot.h,are://‐‐‐‐‐‐cameraintrinsicsScalarType FocalMm; ///FocalDistance: thedistancebetween focalcenterand imageplane.Expressed inmmPoint2<int> ViewportPx; /// Dimension of the Image Plane(inpixels)Point2<S> PixelSizeMm; ///Dimension inmmof asinglepixelPoint2<S> CenterPx; /// Position of theprojectionofthefocalcenterontheimageplane.ExpressedinpixelsPoint2<S> DistorCenterPx; ///PositionoftheradialdistortioncenterontheimageplaneinpixelsS k[4]; /// 1st & 2ndorderradiallensdistortioncoefficient(onlythefirst2termsareused)//‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐While the extrinsic parameters usually change between the shots, some(sometimesall)oftheintrinsicarestronglyrelatedtothecameramodelused.Inparticular, some values are usually known before camera calibration:viewportPx and CenterPx. Moreover, if an accurate calibration is needed, it isnecessary to fill the PixelSizeMm value. This can be inferred from the cameradatasheet(itcanbecalculatedbydividingthesensorwidthandheight, inmm,bytheresolutionoftheimage)or,insomecases,fromtheEXIFoftheimage(intheCANONmodels,itistheinverseofFocalPlaneX‐resolutionandFocalPlaneY‐resolution, scaled from inches tomm if necessary). If a correctPixelSizeMm isnotset,thevaluesofthecameraparameterscanbedifferentfromtherealones,eventhoughtheimageisperfectlyalignedtoa3Dmodel.Alsothefocaldistancecan be inferred fromEXIF, but its value is indicative. If a calibrated camera isused,thenalltheintrinsicparametersshouldbeknowninadvance.FileFormatsVCGLibprovidesimporterandexporterforseveralfileformats

• import: PLY, STL, OFF, OBJ, 3DS, COLLADA, PTX, V3D, PTS, APTS, XYZ,GTS,TRI,ASC,X3D,X3DV,VRML,ALN

• export:PLY,STL,OFF,OBJ,3DS,COLLADA,VRML,DXF,GTS,U3D, IDTF,X3D

ThefollowingcodesnippetshowhowtousethePLYimporterandexporter:#include<wrap/io_trimesh/import.h>//definitionoftypeMyMeshMyMeshm;vcg::tri::io::ImporterPLY<MyMesh>::Open(m,"namefile_to_open.ply"); // ....vcg::tri::io::ExporterPLY<MyMesh>::Save(m,"namefile_to_save.ply");The previous one is the minimal required interface for all the importer andexporters. Additionally two other parameters can be specified: mask andcallback.Thecallbackisusedforprovidingafeedbackduringtheusuallylenghtimporting/exporting process. The mask is used to better specify/understandwhatisloaded/saved.SavingMaskandReadingMaskGenerally all file formats save at least vertex positions and basic connectivtyinformation, but beyond that you may want to choose which other data arestoredwiththefile.Tothisaim,VCGLibprovidesaclassvcg::tri::io::Maskwhichisessentiallyacollectionofbitnamesthatareusedtospecifywhichcomponentsyouwanttowritetothefile(e.g.stufflikevcg::tri::io::Mask::IOM_VERTCOLOR).

Page 56: 1 MeshLab Documentation

56

WhensavingthismaskisusedinaREADONLYmode(theyarejustconstants)tospecifywhat component youwant to save. For example, if you have stored inyourmeshnormalspervertex(forrenderingpurposes)butyouconsidersavingtheminplyformatjustawasteofspace,youshouldspecifyanappropriatemaskwiththeMask::IOM_VERTNORMALbitcleared.Obviouslynotalltheformatsareable to saveall thepossibledata. ForexampleSTL format cannot save texturecoordsorpervertexcolor.SotoknowwhatyouareabletosaveinagivenXXXformatthereisthefunctionExporterXXX::GetExportMaskCapability()thatgivesyouabitmaskwithallthecapabilityofthatfileformat.When loading thismask is used in aWRITEONLYmode to report to theuserwhatfieldshavebeenloadedfromthefileintothemesh(e.g.theinitialvalueofthe mask is ignored). In many cases it could be useful to know what data ispresentintoafiletopreparethemesh(e.g.toenableoptionalcomponents),forthis purpose all the importer have also aImporterXXX::LoadMask(filename,mask) that fill the mask only withouteffectivelyloadingamesh.Notethatforsomemeshformatsunderstandingwhatiscontainedintoafilemeansparsingthewholefile.ErrorReportingThemesh I/O functions returns ZERO on success and an error code differentfrom zero in case of failure or critical conditions. Use the static const char*ErrorMsg(interror)functiontogetahumanunderstandabledescriptionoftheerror code and static bool ErrorCritical(int err) to know if a given error is acriticaloneorjustawarning.ForexampleintheOBJformattheabsenceoftheaccompanyingmaterialdescription file, isconsiderednoncritical (youareabletogetthecorrectgeometryevenifyoumissmaterialinfo).VMIdumpfileVMIisanacronymforVcglibMeshImageanditisnotaproperfileformatbutasimpledumpofthevcg:TriMeshonafile.Notbeingafileformatmeansthat:

• thereisnospecification• it is bound to the current version of the VCGLib with no backward

compatibilityaVMIcanbeveryusefulfordebugpurpose,becauseitsaves:

• allthecomponents• all the temporary components (currently only of Optional Component

Fasttype)• allthevertex,faceormeshattributesyouhaveinyourmeshfile

So if, for example, your algorithm crashes at the n‐th step, you can saveintermediateresultsofyourcomputationwithVMIandreloadit.Note that in order to load a VMI the mesh passed as template tovcg::tri::ImporterVMI<MeshType>(..) must be of the same type as the meshpassed to vcg::tri::ExporterVMI<MeshType>(..) otherwise the loader returnsFALSE.

Page 57: 1 MeshLab Documentation

57

AccesstomeshAssumption:themeshisstoredinaobjectmoftypeMyMeshAccessingthecoordsofallthevertexesMyMesh::VertexIteratorvi;for(vi=m.vert.begin();vi!=m.vert.end();++vi) {DoSomething((*vi).P());}AccessingallthefacesandcomputingtheirbarycenterMyMesh::FaceIterator fi; for(fi =m.face.begin(); fi!=m.face.end(); ++fi ) {MyMesh::CoordTypeb=((*fi).V(0)‐>P()+(*fi).V(1)‐>P()+(*fi).V(2)‐>P())/3.0;}orusingacommonshorthandforaccessingtothecoordofafacevertex:MyMesh::FaceIterator fi; for(fi = m.face.begin(); fi!=m.face.end(); ++fi ) {MyMesh::CoordTypeb=((*fi).P(0)+(*fi).P(1)+(*fi).P(2))/3.0;}Oreveninashorterway:MyMesh::FaceIterator fi; for(fi = m.face.begin(); fi!=m.face.end(); ++fi ) {MyMesh::CoordTypeb=vcg::Barycenter(*fi);}CreatingelementsCreatingthesimplestsingletrianglemesh.m.Clear(); Allocator<MyMesh>::AddVertices(m,3);Allocator<MyMesh>::AddFaces(m,1); MyMesh::VertexPointer ivp[3];VertexIterator vi=in.vert.begin(); ivp[0]=&*vi;(*vi).P()=CoordType ( 1.0, 1.0,1.0); ++vi; ivp[1]=&*vi;(*vi).P()=CoordType (‐1.0, 1.0,‐1.0); ++vi;ivp[2]=&*vi;(*vi).P()=CoordType (‐1.0,‐1.0, 1.0); ++vi; FaceIteratorfi=in.face.begin();(*fi).V(0)=ivp[0];(*fi).V(1)=ivp[1];(*fi).V(2)=ivp[2];looktocomplex/trimesh/create/platonic.hplatonic.hformoreexamples.DestroyingElementsLazydeletionstrategy.Note that the two basic deletion strategies are very low level functions. Theysimplymarkasdeleted the correspondingentrieswithout affecting the restofthe structures. So for example if you delete a vertex with these structureswithoutcheckingthatallthefacesincidentonithavebeenremovedyoucreateanonconsistentsituation.Similarly,butlessdangerous,whenyoudeleteafaceitsvertices are left around so at the end you can have unreferenced floatingvertices.Allocator<MyMesh>::DeleteVertex(m,v);Allocator<MyMesh>::DeleteFace(m,v);If your algorithm performs deletion the size of a container could be differentfromthenumberofvalidelementofyourmeshes(e.g.:m.vert.size()!=m.vnm.face.size()!=m.fn

Page 58: 1 MeshLab Documentation

58

Therefore when you scan the containers of vertices and faces you couldencounterdeletedelementssoyoushouldtakecarewithasimple!IsD()check:MyMesh::FaceIterator vi; for(fi = m.face.begin(); vi!=m.face.end(); ++fi )if(!(*fi).IsD()) // <‐‐‐‐ Check added { MyMesh::CoordType b =vcg::Barycenter(*fi);}In some situations, particularlywhenyouhave to loopmanymany timesovertheelementof themeshwithoutdeleting/creatinganything, itcanbepracticaland convenient to get rid of deleted elements by explicitly calling the twogarbagecollectingfunctions:Allocator<MyMesh>::CompactVertexVector(m);Allocator<MyMesh>::CompactFaceVector(m);AftercallingthesefunctionitissafetonotchecktheIsD()stateofeveryelementandalwaysholdsthat:m.vert.size()==m.vnm.face.size()==m.fnNotethatiftherearenodeletedelementsinyourmesh,thecompactorfunctionsreturnsimmediately.AdjacencyrelationsVCG meshes DO NOT store edges, only vertex and triangles. Even the basicadjacencyrelationshavetobeexplicitlycomputed.Wealwaystrytodonotstoreper‐edge information and we try to keep such information only more or lessimplicitly.Thisissimplybecausetherearemanyalgorithmsthatdonotexplicitlyrequire this information and the cost of updating/storing should be avoidedwhen possible. Inmany cases algorithms that seems based on some kind per‐edge iteration or information can be re‐written in a more efficient way bymovingthelooptoothermeshelements.Countingborderedges(withouttopology)Typicalexampleareborderflags.Eachfacekeepabitforeachofitssidessayingifthatfacehasaboundaryonthatsideornot.Thisinformationcanbeaccessedbymean of the IsB(i) function. To compute the border flags there are variousalgorithmaccordingtotheavailabletopologicalinformations.Allocator<MyMesh>::CompactFaceVector(m);UpdateFlags<MyMesh>::FaceBorderFromNone(m); int BorderEdgeCounter=0;MyMesh::FaceIterator fi; for(fi = m.face.begin(); fi!=m.face.end(); ++fi ) {for(inti=0;i<3;++i)if((*fi).IsB(i))BorderEdgeCounter++;}Countingborderedge(usingFFadjacency)WhenyourmeshasFace‐FaceadjacencytheFFp(i)memberstorethepointerofthefacethatisadjacenttothecurrentfacealongthei‐thedgint BorderEdgeCounter=0; MyMesh::FaceIterator fi; for(fi = m.face.begin();fi!=m.face.end();++fi){for(inti=0;i<3;++i)if((*fi).FFp(i)==&*fi)BorderEdgeCounter++;}oralternativelyusingthesameflagbasedapproachasabove

Page 59: 1 MeshLab Documentation

59

UpdateFlags<MyMesh>::FaceBorderFromFFAdjacency(m); intBorderEdgeCounter=0; MyMesh::FaceIterator fi; for(fi = m.face.begin();fi!=m.face.end(); ++fi ) { for(int i=0;i<3;++i) if((*fi).IsB(i))BorderEdgeCounter++;}LicensesMeshLabusessomethirdpartyopensourcelibrariesforitsworking.Hereisthecomplete listsof theprojects thatwegratefully thanks for theirkind liberality.MeshLabislicensedundertheGNUGeneralPublicLicense(GPL).

• VCG Library, developed at the Visual Computing Group ‐ ISTI ‐ CNR.Responsibleforallthemeshprocessingandrenderingtasks.(GPL)

• QT, TrollTech the standard framework for high performance, cross‐platformapplicationdevelopment.

• GLEW:TheOpenGLExtensionWranglerLibrary(BSD)• lib3dsasoftwarelibraryformanaging3D‐StudioRelease3and4".3DS"

files.(LGPL)• bzip2afreelyavailable,patentfree,high‐qualitydatacompressor.(BSD)• Universal 3D Sample Software Set of libraries to write, read, extend,

render and interact with U3D‐formatted data, as defined by standardECMA‐363.ThislibraryisnotdirectlylinkedbuttheU3Dplugininvokesthe idtfcoverted executable, whose sources are provided with theexamplesofthelibrary.AbinaryoftheidtfconverterisdirectlyprovidedwiththeMeshLabdistribution.

• PoissonSurfacereconstrution,heavilybasedonthecodekindlyprovidedbyMichaelKazhdanandMatthewBolitho (custom license thanksMishaandMatthew!)

• movie15Latex package a LaTeX style to embedmovies, sounds and3Dobjects into PDF documents; the needed glue to generating pdf withembeddedU3Dobjects.

• SomeoftheeditingtoolsiconscamefromTangoIconLibraryprojects.PrivacyDisclaimerMeshLabwill automatically check for the availability of updated versions andwillnotifytheneedofupgradingthesoftwaretotheusers.Forthisreason,fromtime to time,MeshLabwill issue a httpnetwork connection. If youprefer thatMeshLab does not communicate in anywaywith its developers, simply use aplainfirewallandpreventanyMeshLabaccesstothenetwork.ThiswillnotlimitinanywaythenormalbehaviorofMeshLab(apartfromgettingnotifiedofnewMeshLab releases) Moreover, when using MeshLab, it locally collects someaggregatedstatisticaldataaboutonlythespecificusageofMeshLab:theoverallnumber and averaged size of the opened/saved meshes; nothing more.Periodically this information is sent back to the developers. This data will beused for statistical analysis and for the assessment of theMeshLab usage.Wewould like to remark that the kind of information collected by MeshLab isprobablyby far less sensitive than the information that is silently collectedbymost web sites when you surf them: IP address, visited pages, frequency ofreturn.WewouldalsoliketostressthatwereallyneedthisinformationinordertoassesshowdiffuseMeshLabisusedanditsimpactonthe3Dcommunity.

Page 60: 1 MeshLab Documentation

60

AcknowledgmentsSome of theMeshLab developers got financial support for theirwork. For theItalianCNRemployees(andfortheotherinvolvedpartners)weacknowledgethefinancialsupportofthefollowingprojects:

• 3D­CoForm(EUIST):"Theresearchleadingtotheseresultshasreceivedfunding from the European Community's Seventh FrameworkProgramme(FP7/2007‐2013)under

grantagreementn°231809"• “EPOCH”(EUNetworkofExcellence,IST‐2002‐507382)• MIUR"BLU‐ARCHEOSYS",2006‐2009

AfullycomprehensiveguideonwritinganIOPluginforMeshLabHowtodownloadMeshLabandalltherelatedstuffPleasenotethatMeshLabusesQtsdk,sofirstofallyouhavetodownloaditfromhttp://www.qtsoftware.com/downloads.In order to get the last version of MeshLab's code you need (if you haven'talready one) a SVN client.We suggest Tortoise SVN. It provides a simple andcompleteinterfacetointeroperatewithaSVNServer.InthenextstepsIwillassumeyouhaveit:

• createeverywhereyouwantanemptyfolderandcalleditmeshlab(forinstanceinc:\devel\meshlab)

• rightclickonthecreatedfolderthanonthemenuclikon"SVNcheckout"item . On the "url of repository" paste and copyhttps://meshlab.svn.sourceforge.net/svnroot/meshlab/trunk/meshlab

• atthesamelevelofthepreviouslycreatedmeshlab'sfolderaddanotherfolder and called it vcglib (following the assumption of the previousexamplec:\devel\vcglib)

• rightclickonthecreatedfolderthanonthemenuclikon"SVNcheckout"item . On the "url of repository" paste and copyhttps://vcg.svn.sourceforge.net/svnroot/vcg/trunk/vcglib . VCGLib is ageometricandalgorithmic librarydeveloped inour lab.MeshLabuses itextensively.

HowtocompileMeshLabandalltherelatedstuffNowyouhavesuccesfullydownloadedallyouneedinordertocompilemeshlab.MeshLab uses a few third parts GPL libraries. You will find them inmeshlab/src/external.Inthisfolderthereisalsoausefullfilecalledexternal.protosimplycompilealltheexternaldependecies.If you had correctly installed qt on your pc in the windows start menu youshouldhaveaQtitemandinthesubitemonelabelled"Qt4.xcommandprompt".Clickonit,adosshellwillappear.Youhavetogotofoldermeshlab/src/external.Thenwrite:

Page 61: 1 MeshLab Documentation

61

qmake‐recursiveexternal.promakewiththelasttwocommandsyouhavecompiledtheexternallibraries.Then, inthesamedosshell,youhavetodigitcd../qmake‐recursivemeshlabv12.promakeand after waiting a long time (depending on your pc's processor) you haveeventuallycompiledmeshlabandallhisplugins.PleasenotethatintheqtsdkpackageisincludedausefullIDEcalledQtCreatorwith wich you could avoid to manually digit the previous commands. All youhavetodoisclickon"file­>open"andimporttheprofileinitandthenclickonthe"build"option.QtCreatorisagoodtoolbutthebestwaytocompileandwritecodeformeshlabmaybeisVisualStudio2008ExpressEdition+QtVisualStudioIntegrationTool(youcoulddownload it in the"otherdownload"section). In thiscaseyouhaveonlytoclickon"qt­>opensolutionfrom.profile"tostarttoworkwithMeshLab'scode.HowtoworkwithMeshLab'smeshThenextstepistounderstandhowmeshworksinMeshLab.MeshLab'sdefinesaCMeshOclass.ACMeshOisacollectionofverticesandtriangularfaces.AFaceis(mainly) a three pointers structure to vertices that composed it. Every vertexcould be referred by zero, one or more faces. A Vertex is (mainly) a classcomposed by a 3d point in space, a vertex‐ normal, a color and a 2d texturecoordinates.WARNING!!!tousevertex­texturecoordinatesyouMUSTfirstenableit,otherwiseyourpluginwillcrash!Youwillfindalltheverticesinanc++vectorcalledvertandthefacesinavectorcalledface.TypicallyaMeshLabplugin'sfunctionhasaMeshModelparameter.AMeshModel contains a CMeshO you could refer to this instance via the cmMeshModel's member. In other words supposing you have a function with aMeshModelparametercalledmymeshyoucouldaccesstoCMeshOverticeswith:mymesh.cm.vert[ii];//iiisanunsignedintindextoaparticularvertexinthemeshwith:mymesh.cm.face[ii];//youcanaccesstotheiifaceandwith:mymesh.cm.face[ii].v(jj);//youwillgetthepointertothejjvertex(0<=jj<3)intheiifacevcglibalsoprovidesawaytosimplyandsafelyaddandremovefacesorverticesfromamesh.

Page 62: 1 MeshLab Documentation

62

vcg::tri::Allocator<CMeshO>::AddVertex(mymesh.cm,new vertex to be added);vcg::tri::Allocator<CMeshO>::AddFace(mymesh.cm,newfacetobeadded);Theaddfunctionsaredefinedinthevcglib\vcg\complex\trimesh\allocate.h.Toenabletexturecoordinatespervertex(orforexamplequalityforvertex)youMUSTcallthefunction:mymesh.updateDataMask(MeshModel::MM_VERTTEXCOORD);totestiftheattributeisalreadyenabled:mymesh.hasDataMask(MeshModel::MM_VERTTEXCOORD);Pleasenotethatyoucouldusealsoacombinationofattributes:mymesh.updateDataMask(MeshModel::MM_VERTTEXCOORD |MeshModel::MM_FACEQUALITY);If you needmore detailed info aboutMeshLab/VCGLibmesh you could take alooktothislink.HowtowriteanIOPluginSuppose we have to write an importer/exporter for an hypothetical .ext fileformat. I suggest to put your code in the meshlab's foldermeshlab\src\meshlabplugins\io_ext.Allthesubsequentinstructionswillrefertocodeinsertedinthisfolder.MeshLab has a plugin architecture. It means that you have to implement asoftwareinterfacetoletMeshLab'scoretointeroperatewithyourplugin.Allthesoftwate interfaces provided by meshlab are in the filemeshlab/src/meshlab/interfaces.hYou have to develop an input/output plugin. So you have to implement aMeshIOInterface. In other words, supposing you plugin will be calledEXTImporteryouhavetowritethesomethingsimilartothefollowingcode:// file ext_plugin.h#include "../../meshlab/meshmodel.h" #include "../../meshlab/interfaces.h"#include "../../meshlab/filterparameter.h" #include<QList>class EXTImporter: public MeshIOInterface { public: QList<Format>importFormats(); QList<Format> exportFormats();void GetExportMaskCapability(QString &format, int &capability, int&defaultBits);boolopen(constQString&format,constQString&fileName,MeshModel&m,int&mask,constFilterParameterSet&par,vcg::CallBackPos*cb=0,QWidget*parent=0); bool save(const QString &format,const QString &fileName,MeshModel &m,const int mask, const FilterParameterSet & par,vcg::CallBackPos*cb=0,QWidget*parent=0);};in file ext_plugin.cpp you have to provide implementation to all the previousdeclaredfunctions.

Page 63: 1 MeshLab Documentation

63

Iwillexplainthesemanticsofthesefunctionsonebyoneandwhattheyshoulddo.

• QList<Format>importFormats()• QList<Format>exportFormats()

o they say to MeshLab what kind of extensions the io plugin willreadorwrite.Youcouldcopy&pastethefollowingcode

QList<MeshIOInterface::Format> EXTImporter::exportFormats() const {QList<Format>formatList; formatList<<Format("EXTFileFormat",tr("EXT"));return formatList; }QList<MeshIOInterface::Format> EXTImporter::importFormats() const {QList<Format>formatList; formatList<<Format("EXTFileFormat",tr("EXT"));returnformatList;}

• voidGetExportMaskCapability(QString&format, int&capability, int&defaultBits)

o it say (mainly) to the framework what kind of extra‐attributes(vertexpositionsmustbeprovidedasdefault)anIOPlugincouldsaveonafile.Atypicalimplementationcouldbe:

void EXTImporter::GetExportMaskCapability(QString &format, int &capability,int &defaultBits) const { if(format.toUpper() ==tr("EXT")){capability=defaultBits= vcg::tri::io::Mask::IOM_VERTCOLOR |vcg::tri::io::Mask::IOM_FACECOLOR;}}

• bool open(const QString &format,const QString&fileName,MeshModel &m,int &mask,const FilterParameterSet &par,vcg::CallBackPos*cb=0,QWidget*parent=0)

o ItisTHEfunctionyouhavetoimplementtoimporta3dfileformatinMeshLab

Function'sparameters: const QString &format ‐ the extension of the format (e.g."EXT")

constQString&fileName‐thenameofthefiletobeopened MeshModel &m ‐ The mesh that is filled with the filecontent

int &mask ‐ a bitmask thatwill be filled reportingwhatkind of datawe have found in the file (per vertex color,texturecoordsetc).Itisavalueoracombinationofvalues(via |) of type vcg::tri::io::Mask (you could find it atvcglib\wrap\io_trimesh\mask_io.h)

constFilterParameterSet&par‐Theparametersthathavebeen set up in the initPreOpenParameter(). IN A FIRSTINSTANCEYOUCOULDFORGETABOUTIT.

vcg::CallBackPos *cb ‐ standard callback for reportingprogressintheloading

QWidget*parent‐youshouldnotusethis.• bool save(const QString &format,const QString &fileName,

MeshModel &m,const int mask,const FilterParameterSet & par,vcg::CallBackPos*cb=0,QWidget*parent=0)

o It is the function to save mesh info in a file. it has the sameparametersofopenfunction.

Page 64: 1 MeshLab Documentation

64

Howtowriteaworking.profileWARNING! This section will be most an "how to make quickly all the thingsworking"andabsolutelynotacompletereferenceto"howwriteagoodprofile".Aprofileisasortofmakefileforqt.ItiscouldbeusefullinordertocompileyourplugindirectlyfromyourpreferredIDEandtocreateyourownmeshlabrelease.In the next steps I will suppose you had put your code inmeshlab\src\meshlabplugins\io_ext.

• Open with a text editor (also notepad it's ok) the filemeshlab\src\meshlabplugins\meshlabpluginsv12.proandaddthefolderofyourownplugin(i.e.io_gsd)

• Fromthedirectorymeshlab\src\meshlabplugins\io_exttaketheio_ext.profile.

• copy and paste in meshlab\src\meshlabplugins\io_ext then change hisnameinio_ext.pro

• openitwithnotepado intheTARGETsectionchangethevaluetoio_gsd(thiswillbethe

nameofyourgeneratedplugin'sdll)o in the HEADERS section remove "io_pdb.h \

$$VCGDIR/wrap/ply/plylib.h" and add all the .h files needed byyourplugin

o in the SOURCES section remove "io_pdb.cpp \$$VCGDIR//wrap/ply/plylib.cpp\"andaddallthe.cppfiles.Plese,youMUSTN'Tremove../../meshlab/filterparameter.cppotherwiseyourpluginwillhaveproblemonlinkingtime.

• If you use QtCreator or Vs reopen themeshlabv12.pro. You should seeyourplugin'sfileslistedonthetreeviewwidget.

• Nowyoucansimplycompileyourplugin!