How to add material to mesh in C++ SDK

@stevebaer, @dale, @nathanletwory, @piac, @jean.davy.77, @Helvetosaur,

I currently have Python code which adds a bitmap texture from a .jpg file to a mesh = meshObj.Id using this working code:

# Add material to mesh.
index = doc.Materials.Add()
mat = doc.Materials[index]
filename = root + '\\' + name
#Example: filename = 'D:\Photoscan\TerryFebResults\MediumModel1p4MFaces16384x1Texure\MediumModel1p4MFaces16384x1Texure.jpg'
# Add .jpg texture to material definition.
mat.SetBitmapTexture(filename)
# Set name of material.
mat.Name = name
# Turn on self-illumination for brighter view.
mat.DisableLighting = True
# Update material.
mat.CommitChanges()
# Get Rhino object for mesh.
obj = doc.Objects.Find(mesh)
# Get attribues of mesh.
attr = obj.Attributes;
# Add Material index and source to attributes.
attr.MaterialIndex = index
attr.MaterialSource = DocObjects.ObjectMaterialSource.MaterialFromObject
doc.Objects.ModifyAttributes(obj, attr, False);

I have looked thru the C++ SDK documentation but have not gotten past translating the first line,

index = doc.Materials.Add()

to C++ SDK code. Can anyone give me a hand with translating this Python code to C++?

Currently I create the mesh in C++ and then have to return its serial number to the Python script to recover the mesh object Id,

meshObj = doc.Objects.Find(cmesh_serial_number.value)
mesh = meshObj.Id

in order to add the .jpg texture using the code above. Instead I want to simplify this and add the texture in the C++ code and thus eliminate fooling around with serial numbers.

Regards,
Terry.

Hopefully in this New Year of 2021, I may receive some help in translating my Python code to C++ SDK code.

See if the following code helps you out:

Nathan,

This was a big help. Between the code example you provided, Intellisense in Visual Studio and the C++ SDK documentation, I was able to create this translation to C++ which seems to work:

ON_3dmObjectAttributes attribs;
pDoc->GetDefaultObjectAttributes(attribs);
// If .jpg texture file exists for this mesh, add material to mesh.
if (stat(jpg_path.c_str(), &buffer) == 0) {
    // Create new material.
    ON_Material mat;
    // Add.jpg texture to material definition.
    // NOTE: wide_ indicates string was converted to: const wchar_t*.
    mat.AddTexture(wide_jpg_path, ON_Texture::TYPE::bitmap_texture);
    // Set name of material.
    mat.SetName(wide_jpg_name);
    // Turn on self-illumination for brighter view.
    mat.SetDisableLighting(true);
    // Get material index for new material.
    const int matIndex = pDoc->m_material_table.AddMaterial(mat);
    // Add Material index and source to attributes.
    attribs.m_material_index = matIndex;
    attribs.SetMaterialSource(ON::material_from_object);
}
CRhinoMeshObject *meshObject = new CRhinoMeshObject(attribs);
meshObject->SetMesh(mesh);

This makes a nice start to the New Year.

Regards,
Terry.

1 Like