首页 文章

在 SceneKit 中按名称获取材质

提问于
浏览
2

我已将 collada .dae 文件导入到 scenekit 中。我可以在场景 editor/inspector 中看到有一个带有命名材料的实体和材料列表。但我不知道如何以编程方式请求这些。

如果我知道一个节点和使用它的几何体,我可以从几何对象中按名称要求材料,如下所示:

myscene.rootNode.childNodes[68].geometry?.materialWithName("carpaint")

但这些是在许多子几何上使用的可重用材料,所以应该有某个地方的全局索引(?)

我会期待类似的东西

myscene.materialWithName("carpaint")

1 回答

  • 2

    我最终做的是创建 SCNNode 和 SCNScene 的扩展,为我提供所有材料的索引:

    import SceneKit
    
    extension SCNScene {
        func buildMaterialIndex() -> Dictionary<String, SCNMaterial> {
            return self.rootNode.buildMaterialIndex()
        }
    }
    
    extension SCNNode {
        func isPartOf(node: SCNNode) -> Bool {
            return (node === self) || (parentNode?.isPartOf(node) ?? false)
        }
    
        private class _DictBox {
            var dict = Dictionary<String, SCNMaterial>()
        }
        private func _populateMaterialIndex(dictbox: _DictBox, node: SCNNode) {
            if let g = node.geometry {
                for m in g.materials {
                    if let n = m.name {
                        dictbox.dict[n] = m
                    }
                }
            }
            for n in node.childNodes {
                _populateMaterialIndex(dictbox, node: n)
            }
        }
        func buildMaterialIndex() -> Dictionary<String, SCNMaterial> {
            let dictbox = _DictBox()
            _populateMaterialIndex(dictbox, node: self)
            return dictbox.dict
        }
    }
    

相关问题