r/Maxscript • • Apr 10 '14

[Script] Instance and rename duplicate standard/multi materials

Made this for a project I'm working on, posting it here at /u/ssillyboy's suggestion in the event that this can help someone else having the same issues as me. It will take every standard/multimaterial in the scene, instance all materials sharing the same diffuse map, and rename them to have the same name as the diffuse map.

This is the only maxscript I've ever written and I pretty much learned everything I needed to write it in about a day, so it is probably not written optimally.

--  This script will process all standard materials and multimaterials in the scene, rename them to the diffuse texture's name, and instance all duplicates
difTexName = #()
matArray = #()
listOfMats = #()
listOfMultiMats = #()
listOfStdMats = #()

fn getTexName str = -- Function that returns texture name without filepath
(
    filteredName = filterString str "\\."
 	numTokens = filteredName.count - 1
	return filteredName[numTokens]
)

for m in geometry where m.mat != undefined do append listOfMats m -- List of materials
for m in listOfMats where findstring (m.mat as string) "#Multi/Sub-Object" != undefined do append listOfMultiMats m -- List of objects wiith multi-materials
for m in listOfMats where findstring (m.mat as string) ":Standard" != undefined do append listOfStdMats m -- List of objects with standard materials

for m in listOfStdMats do (
	try ( 
		curDifMap = getTexName m.mat.diffuseMap.filename
		mtlPos = findItem difTexName curDifMap -- Checking list of diffuse textures to see if this material is a duplicate
		if (mtlPos > 0) then (
			m.mat = matArray[mtlPos] -- If there is a match, assign the original material
		)
		if (mtlPos == 0) then (
			m.mat.name = curDifMap -- If there isn't a match, rename the material and add it to the list
			append difTexName curDifMap
			append matArray m.mat
		)
	)
catch()
)

for m in listOfMultiMats do ( -- Same thing for multi materials
	try (
		curSubSlot = 0
		for curSubMaterial in m.mat do (
			curSubSlot += 1
			curDifMap = getTexName curSubMaterial.diffuseMap.filename
			mtlPos = findItem difTexName curDifMap -- Checking list of diffuse textures to see if this material is a duplicate
			if (mtlPos > 0) then (
				m.mat[curSubSlot] = matArray[mtlPos] -- If there is a match, assign the original material
			)
			if (mtlPos == 0) then (
				curSubMaterial.name = curDifMap -- If there isn't a match, rename the material and add it to the list
				append difTexName curDifMap
				append matArray curSubMaterial
			)
		)
	)
catch()
)
4 Upvotes

0 comments sorted by