pymxs参考手册

3ds Max Python 更新于 2026-11-24
目录(44)

文档概述

本手册整合了 pymxs 模块的所有核心知识,包括模块概述、API 参考和实用示例,为 3ds Max Python 脚本开发提供完整的参考资料。

目录

1. 模块简介与核心功能

2. 核心 API 函数参考

3. 实用示例与最佳实践

4. 性能优化与错误处理

5. 开发工作流与调试技巧

使用建议:建议按照章节顺序阅读,每个章节都包含实践示例和代码演示。


1. 模块简介与核心功能

1.1 模块简介

pymxs 是 Autodesk 3ds Max 提供的 Python 模块,用于在 Python 脚本中访问 MAXScript 运行时环境。该模块为 Python 开发者提供了与 3ds Max 场景对象、动画系统和渲染功能交互的能力。

1.2 核心功能

1.2.1 MAXScript 运行时访问

  • 通过 pymxs.runtime 访问 MAXScript 全局符号
  • 动态运行时环境,支持实时创建和修改场景对象
  • 完整的 MAXScript 构造函数和函数库访问

1.2.2 上下文表达式函数

  • 动画控制:pymxs.animate(True|False)
  • 时间控制:pymxs.attime(True|False)
  • 层级控制:pymxs.atlevel(True|False)
  • 静默模式:pymxs.quiet(True|False)
  • 重绘控制:pymxs.redraw(True|False)
  • 撤销控制:pymxs.undo(True|False)

1.2.3 撤销/重做系统

  • pymxs.run_undo() - 执行撤销操作
  • pymxs.run_redo() - 执行重做操作
  • 支持异常处理的撤销块机制

1.2.4 线程安全访问

  • pymxs.mxstoken() - 多线程同步令牌
  • 支持在工作者线程中安全访问运行时
  • *3ds max是单线程程序,在max环境中无法使用多线程,可以在对外部数据操作时使用

1.3 基本用法示例

创建基本几何体

示例代码:

import pymxs
rt = pymxs.runtime

# 创建茶壶
teapot = rt.Teapot()
print("创建茶壶: {}".format(rt.classOf(teapot)))

# 创建立方体
box = rt.Box()
box.length = 50
box.width = 50
box.height = 50

# 创建球体
sphere = rt.Sphere()
sphere.radius = 25

说明:这段代码演示了如何使用 pymxs 创建基本的 3ds Max 几何体对象。


1.3.1 数据类型映射

Python 到 MAXScript 类型转换:

  • int ↔ MAXScript Integer
  • float ↔ MAXScript Float
  • str ↔ MAXScript String
  • list ↔ MAXScript Array
  • tuple ↔ MAXScript Point3/Point2 (仅适用于特定构造函数)

注意:Python 的 tuple 和 MAXScript 的数组不是对等关系。tuple 主要用于传递给 MAXScript 的 Point3、Point2、Color 等构造函数。

1.3.2 正确的数据类型映射关系

Python list ↔ MAXScript Array

  • Python 的 list 可以直接转换为 MAXScript 数组
  • 使用 rt.array(python_list) 进行转换
  • 创建空数组:rt.array()
  • 支持索引访问和迭代操作
  • 注意:不要使用 MAXScript 的 #() 语法,在 Python 中会被识别为注释

Python tuple ↔ MAXScript 构造函数参数

  • tuple 主要用于解包作为构造函数参数
  • 例如:rt.Point3(*tuple) 或 rt.Color(*tuple)
  • tuple 不能直接作为数组使用

常见构造函数参数类型

  • Point3: 接受 3 个数值参数或解包的 tuple
  • Point2: 接受 2 个数值参数或解包的 tuple
  • Color: 接受 3 个数值参数或解包的 tuple
  • EulerAngles: 接受 3 个角度参数

示例:数据类型使用

示例代码:

import pymxs
rt = pymxs.runtime

# 基本数据类型
position = rt.Point3(10, 20, 30)  # 3D 点
color = rt.Color(255, 128, 0)     # 颜色
rotation = rt.EulerAngles(45, 0, 0)  # 旋转角度

# 使用 tuple 作为构造函数参数(正确用法)
pos_tuple = (10, 20, 30)
position = rt.Point3(*pos_tuple)  # 解包 tuple 作为参数

# 数组类型(与 Python list 对应)
vertices = rt.array()  # 创建空数组
vertices[1] = rt.Point3(0, 0, 0)
vertices[2] = rt.Point3(100, 0, 0)
vertices[3] = rt.Point3(100, 100, 0)

# Python list 转换为 MAXScript 数组
python_list = [1, 2, 3, 4, 5]
maxscript_array = rt.array(python_list)  # 正确转换方式

# 数组操作示例
numbers = rt.array(10, 20, 30, 40, 50)  # 直接创建数组
print("数组长度: {}".format(numbers.count))
print("第一个元素: {}".format(numbers[1]))

# 数组迭代
for i in range(numbers.count):
    print("元素 {}: {}".format(i, numbers[i]))

说明:这段代码展示了 pymxs 中各种数据类型的正确使用方法,包括基本类型、数组和构造函数参数。


返回目录 ↑


2. 核心 API 函数参考

2.1 pymxs.runtime

功能:提供对 MAXScript 运行时的访问

语法:

rt = pymxs.runtime

说明:

  • 动态运行时环境,包含所有 MAXScript 全局符号
  • 支持实时创建和修改场景对象
  • 所有 MAXScript 构造函数和函数都可通过此属性访问

示例代码:

import pymxs
rt = pymxs.runtime

# 创建几何体
teapot = rt.Teapot()
box = rt.Box()
sphere = rt.Sphere()

# 访问场景信息
scene_objects = rt.objects
current_time = rt.currentTime

# 调用 MAXScript 函数
object_count = rt.objects.count
print("场景中对象数量: {}".format(object_count))

说明:这段代码展示了如何使用 pymxs.runtime 访问 MAXScript 运行时环境。


2.2 上下文表达式函数

pymxs.animate(enable)

功能:控制动画记录状态

参数:

  • enable (bool): True 启用动画记录,False 禁用

实现细节:

  • 使用 runtime.animButtonState 保存和设置动画按钮状态
  • 直接修改 runtime.animButtonState 属性来控制动画记录
  • 退出上下文时恢复原始状态

示例代码:

import pymxs
rt = pymxs.runtime

# 创建动画对象
animated_box = rt.Box()

# 启用动画记录
with pymxs.animate(True):
    with pymxs.attime(0):
        animated_box.pos = rt.Point3(-100, 0, 0)
    with pymxs.attime(50):
        animated_box.pos = rt.Point3(0, 0, 0)
    with pymxs.attime(100):
        animated_box.pos = rt.Point3(100, 0, 0)

说明:这段代码演示了如何使用 pymxs.animate() 函数创建动画关键帧。


pymxs.attime(time)

功能: 设置当前时间上下文

参数:

  • time (int): 帧数或时间值

示例:

import pymxs
rt = pymxs.runtime

# 在不同时间点设置属性
with pymxs.animate(True):
    for frame in range(0, 101, 10):
        with pymxs.attime(frame):
            rt.Box().pos = rt.Point3(frame * 2, 0, 0)

pymxs.atlevel(node_name)

功能: 设置场景节点层级上下文(类似于 MAXScript 的 'at level' 和 'in')

参数:

  • node_name (str): 场景节点名称

重要说明:

  • atlevel 函数用于在指定的场景节点层级下创建子对象
  • 参数应为场景中已存在节点的名称,不是子对象层级名称
  • 该函数与子对象层级操作无关

用法示例:

import pymxs
rt = pymxs.runtime

# 创建父对象
parent_box = rt.Box()
parent_box.name = "parent_box"

# 在父对象层级下创建子对象
with pymxs.atlevel("parent_box"):
    # 创建的子对象将成为 parent_box 的子对象
    child_teapot = rt.Teapot()
    child_sphere = rt.Sphere()

正确的可编辑网格创建方法

重要说明: rt.Editable_Mesh() 可以直接创建可编辑网格对象,以下是几种创建方式:

import pymxs
rt = pymxs.runtime

# 方法1: 直接创建可编辑网格对象
mesh_obj = rt.Editable_Mesh()
print("直接创建的网格对象类型: {}".format(rt.classOf(mesh_obj)))

# 方法2: 创建基础几何体后转换为可编辑网格
box_obj = rt.Box()  # 创建基础盒子
mesh_obj = rt.convertToMesh(box_obj)  # 转换为可编辑网格

# 方法3: 创建球体后转换为可编辑网格
sphere_obj = rt.Sphere()
mesh_obj2 = rt.convertToMesh(sphere_obj)

# 方法4: 创建茶壶后转换为可编辑网格
teapot_obj = rt.Teapot()
mesh_obj3 = rt.convertToMesh(teapot_obj)

print("转换后的网格对象类型: {}".format(rt.classOf(mesh_obj)))
print("顶点数量: {}".format(rt.meshOp.getNumVerts(mesh_obj)))

注意事项:

  • rt.Editable_Mesh() 可以直接创建空的网格对象
  • rt.convertToMesh() 用于将现有几何体转换为可编辑网格
  • 不同的创建方法适用于不同的使用场景
  • 直接创建的网格对象是空的,需要手动添加顶点和面
  • 转换方法会保留原始几何体的顶点和面结构

使用 rt.subObjectLevel 属性

import pymxs
rt = pymxs.runtime

# 创建可编辑网格(正确方式:先创建基础几何体再转换)
box_obj = rt.Box()  # 创建基础盒子
mesh = rt.convertToMesh(box_obj)  # 转换为可编辑网格

# 设置顶点层级
rt.subObjectLevel = 1  # 顶点层级
# 顶点操作代码...

# 设置边层级
rt.subObjectLevel = 2  # 边层级
# 边操作代码...

# 设置面层级
rt.subObjectLevel = 3  # 面层级
# 面操作代码...

# 设置多边形层级
rt.subObjectLevel = 4  # 多边形层级
# 多边形操作代码...

# 设置元素层级
rt.subObjectLevel = 5  # 元素层级
# 元素操作代码...

# 返回对象层级
rt.subObjectLevel = 0  # 对象层级

子对象层级常量

import pymxs
rt = pymxs.runtime

# 常用的子对象层级常量
OBJECT_LEVEL = 0      # 对象层级
VERTEX_LEVEL = 1      # 顶点层级
EDGE_LEVEL = 2       # 边层级
FACE_LEVEL = 3       # 面层级
POLYGON_LEVEL = 4    # 多边形层级
ELEMENT_LEVEL = 5    # 元素层级

# 使用常量设置层级
rt.subObjectLevel = VERTEX_LEVEL
# 顶点操作...

完整的子对象操作示例

import pymxs
rt = pymxs.runtime

# 创建可编辑网格(正确方式:先创建基础几何体再转换)
box_obj = rt.Box()  # 创建基础盒子
mesh = rt.convertToMesh(box_obj)  # 转换为可编辑网格

# 顶点层级操作
rt.subObjectLevel = 1
print("当前层级: 顶点")
# 可以执行顶点选择、移动等操作

# 边层级操作
rt.subObjectLevel = 2  
print("当前层级: 边")
# 可以执行边选择、倒角等操作

# 返回对象层级
rt.subObjectLevel = 0
print("返回对象层级")

pymxs.quiet(silent)

功能: 控制输出静默模式

参数:

  • silent (bool): True 启用静默模式,False 禁用

实现细节:

  • 使用 runtime.GetQuietMode() 保存当前静默模式状态
  • 使用 runtime.SetQuietMode(onoff) 设置新的静默模式
  • 退出上下文时恢复原始状态

示例:

import pymxs
rt = pymxs.runtime

# 静默模式下批量创建对象
with pymxs.quiet(True):
    for i in range(100):
        rt.Box(pos=rt.Point3(i * 10, 0, 0))

pymxs.redraw(enable)

功能: 控制视口重绘

参数:

  • enable (bool): True 启用重绘,False 禁用

实现细节:

  • 使用 runtime.IsSceneRedrawDisabled() 保存当前重绘状态
  • 使用 runtime.EnableSceneRedraw() 和 runtime.DisableSceneRedraw() 控制重绘
  • 退出上下文时恢复原始状态

示例:

import pymxs
rt = pymxs.runtime

# 批量操作时不重绘以提高性能
with pymxs.redraw(False):
    for i in range(50):
        rt.Sphere(radius=10 + i, pos=rt.Point3(i * 20, 0, 0))

# 操作完成后强制重绘
rt.redrawViews()

pymxs.undo(enable, description=None)

功能: 控制撤销记录

参数:

  • enable (bool): True 启用撤销记录,False 禁用
  • description (str, 可选): 撤销操作的描述文本

示例:

import pymxs
rt = pymxs.runtime

# 创建不可撤销的基础对象
with pymxs.undo(False):
    base_objects = [rt.Box() for _ in range(10)]

# 创建可撤销的修改操作
with pymxs.undo(True, "位置随机化"):
    import random
    for obj in base_objects:
        obj.pos = rt.Point3(
            random.uniform(-100, 100),
            random.uniform(-100, 100),
            random.uniform(-100, 100)
        )

撤销/重做函数

pymxs.run_undo()

功能: 执行撤销操作

语法:

pymxs.run_undo()

说明:

  • 对应 MAXScript 的 max undo 命令
  • 撤销最近的可撤销操作
  • 在撤销菜单中显示为 "MAXScript" 条目

示例:

import pymxs
rt = pymxs.runtime

# 创建可撤销的操作
with pymxs.undo(True, "测试撤销"):
    test_box = rt.Box()
    test_box.pos = rt.Point3(50, 50, 50)

# 执行撤销
pymxs.run_undo()  # 撤销位置设置
pymxs.run_undo()  # 撤销对象创建

pymxs.run_redo()

功能: 执行重做操作

语法:

pymxs.run_redo()

说明:

  • 对应 MAXScript 的 max redo 命令
  • 重做最近撤销的操作

示例:

import pymxs
rt = pymxs.runtime

# 创建操作并撤销
with pymxs.undo(True, "测试重做"):
    test_sphere = rt.Sphere()

pymxs.run_undo()  # 撤销创建
pymxs.run_redo()  # 重做创建

引用参数处理函数

pymxs.byref(value)

功能: 处理 MAXScript 函数的引用参数(推荐使用)

参数:

  • value: 要传递的引用值

说明:

  • 用于处理接受引用参数的 MAXScript 函数
  • 推荐使用的新接口

详细案例:

import pymxs
rt = pymxs.runtime

# 案例1: 使用 maxOps.cloneNodes() 函数(推荐方式)
# 创建几何对象
box_obj = rt.Box()

# 使用 byref 的典型场景:克隆节点
# 调用 cloneNodes() 函数,该函数接受一个名为 'newNodes' 的引用参数
# 这是一个纯输出参数,可以传递 None
result, cloned_nodes = rt.maxOps.cloneNodes(box_obj, cloneType=rt.Name('reference'), 
                                           newNodes=pymxs.byref(None))

print('克隆结果: {}, 克隆的节点: {}'.format(result, cloned_nodes))

# 案例2: 使用 maxOps.colorById() 函数(推荐方式)
# 获取颜色ID对应的颜色值
# 这是一个纯输出参数,传递 None
result, color_value = rt.maxOps.colorById(2, pymxs.byref(None))

print('颜色结果: {}'.format(color_value))

# 案例3: 使用 FileResolutionManager.getFullFilePath() 函数(推荐方式)
# 这是一个输入和输出参数,需要提供初始值
file_name = 'Simple_Stone_Mtl_Marble_bump.jpg'
result, full_path = rt.FileResolutionManager.getFullFilePath(pymxs.byref(file_name), 
                                                           rt.name('bitmap'))

print('输入参数未改变: {}'.format(file_name))
print('返回的输出参数包含完整路径: {}'.format(full_path))

# 案例4: 使用 byref 处理多个引用参数
# 创建多个几何对象
box1 = rt.Box()
box2 = rt.Box(pos=rt.Point3(50, 0, 0))

# 批量克隆多个对象
objects_to_clone = rt.Array(box1, box2)
result, cloned_objects = rt.maxOps.cloneNodes(objects_to_clone, 
                                             cloneType=rt.Name('copy'), 
                                             newNodes=pymxs.byref(None))

print('批量克隆结果: {}'.format(result))
print('克隆的对象数量: {}'.format(len(cloned_objects)))

# 案例5: 使用 byref 处理复杂数据类型
# 创建变换矩阵
transform_matrix = rt.Matrix3(1)

# 假设有一个接受矩阵引用参数的函数
# result, updated_matrix = rt.someTransformFunction(pymxs.byref(transform_matrix))
# print(f'变换矩阵: {updated_matrix}')

实际应用场景:

import pymxs
rt = pymxs.runtime

# 实际应用: 批量文件路径解析
# 处理多个材质贴图文件
file_names = [
    'Simple_Stone_Mtl_Marble_bump.jpg',
    'Wood_Floor_Diffuse.png',
    'Metal_Brushed_Normal.jpg'
]

print("批量解析文件路径:")
for file_name in file_names:
    result, full_path = rt.FileResolutionManager.getFullFilePath(pymxs.byref(file_name), 
                                                               rt.name('bitmap'))
    if result:
        print("文件: {} -> 完整路径: {}".format(file_name, full_path))
    else:
        print("文件: {} -> 未找到".format(file_name))

# 实际应用: 批量对象克隆
# 创建多个几何对象
objects = [rt.Box(), rt.Sphere(), rt.Cylinder()]

print("批量克隆对象:")
for i, obj in enumerate(objects):
    # 设置不同位置
    obj.pos = rt.Point3(i * 100, 0, 0)
  
    # 克隆对象
    result, cloned_objects = rt.maxOps.cloneNodes(obj, cloneType=rt.Name('copy'), 
                                                 newNodes=pymxs.byref(None))
  
    if result and cloned_objects:
        print("对象 {} 克隆成功,创建了 {} 个副本".format(i+1, len(cloned_objects)))
    else:
        print("对象 {} 克隆失败".format(i+1))

# 实际应用: 颜色管理
# 获取不同颜色ID对应的颜色值
color_ids = [1, 2, 3, 4, 5]

print("颜色ID对应颜色值:")
for color_id in color_ids:
    result, color_value = rt.maxOps.colorById(color_id, pymxs.byref(None))
    if result:
        print("颜色ID {}: {}".format(color_id, color_value))
    else:
        print("颜色ID {}: 未找到".format(color_id))

引用参数处理说明

适用场景说明

需要使用引用参数的 MAXScript 函数场景:

  1. 变换操作函数
    • 获取和设置对象的位置、旋转、缩放信息
    • 处理对象的世界变换和局部变换
  2. 材质和纹理函数
    • 获取和设置对象的材质属性
    • 处理漫反射颜色、高光、透明度等材质参数
  3. 动画相关函数
    • 获取和设置动画时间范围
    • 处理关键帧和动画曲线
  4. 边界框和层级函数
    • 获取对象的边界框信息
    • 处理对象层级关系
  5. 射线检测函数
    • 射线与对象的相交检测
    • 获取相交点的位置、法线等信息

最佳实践

  1. **始终使用 **byref(): 这是推荐的引用参数处理方式
  2. 错误处理: 确保引用参数已正确初始化
  3. 类型安全: 确保引用参数类型与函数期望的类型匹配
# 正确用法示例
import pymxs
rt = pymxs.runtime

# 初始化引用参数
result = rt.Point3(0, 0, 0)  # 正确:使用正确的类型

# 使用 byref 传递引用
# 示例:使用 maxOps.cloneNodes() 函数(需要先创建对象)
# box_obj = rt.Box()
# result, cloned_nodes = rt.maxOps.cloneNodes(box_obj, cloneType=rt.Name('reference'), 
#                                            newNodes=pymxs.byref(None))

# 错误用法示例
# result = None  # 错误:未初始化
# result = "string"  # 错误:类型不匹配

坐标系设置

rt.coordsys 属性

功能: 设置当前操作的坐标系

语法:

rt.coordsys = rt.Name('坐标系名称')

说明:

  • 用于设置当前操作的坐标系上下文
  • 对应 MAXScript 的 in coordsys 语句
  • 必须在操作前设置,操作完成后建议恢复默认坐标系

可用的坐标系选项:

  • 'world' - 世界坐标系
  • 'local' - 局部坐标系
  • 'parent' - 父坐标系
  • 'grid' - 网格坐标系
  • 'screen' - 屏幕坐标系

示例:

import pymxs
rt = pymxs.runtime

# 保存当前坐标系
original_coordsys = rt.coordsys

# 在局部坐标系中操作
rt.coordsys = rt.Name('local')
for obj in rt.selection:
    random_offset = rt.Point3(
        rt.random(-20.0, 20.0),
        rt.random(-20.0, 20.0), 
        rt.random(-20.0, 20.0)
    )
    obj.pos = random_offset

# 在父坐标系中旋转
rt.coordsys = rt.Name('parent')
for obj in rt.selection:
    rt.rotate(obj, rt.EulerAngles(0, 0, 90))

# 恢复原始坐标系
rt.coordsys = original_coordsys

实用函数:

import pymxs

def set_coordsys(coord_system):
    """设置坐标系"""
    rt = pymxs.runtime
    rt.coordsys = rt.Name(coord_system)

def with_coordsys(coord_system, operation_func):
    """在指定坐标系中执行操作"""
    rt = pymxs.runtime
    original_coordsys = rt.coordsys
  
    try:
        rt.coordsys = rt.Name(coord_system)
        return operation_func()
    finally:
        rt.coordsys = original_coordsys

# 使用示例
def jiggle_objects_local():
    """在局部坐标系中随机抖动对象"""
    rt = pymxs.runtime
    for obj in rt.selection:
        random_offset = rt.Point3(
            rt.random(-20, 20),
            rt.random(-20, 20),
            rt.random(-20, 20)
        )
        obj.pos = random_offset

# 使用上下文管理器风格
with_coordsys('local', jiggle_objects_local)

常见错误:

  • 错误: pymxs.coordsys ❌ (不存在)
  • 正确: rt.coordsys = rt.Name('local') ✅

线程安全函数

pymxs.mxstoken()

功能: 创建线程安全令牌

语法:

token = pymxs.mxstoken()

说明:

  • 在多线程环境中安全访问运行时
  • 确保线程安全的 MAXScript 操作

函数存在性验证方法

在使用 MAXScript 函数时,特别是引用参数相关的函数,验证函数是否存在非常重要,可以避免运行时错误。

方法1: 使用 hasattr() 检查函数存在性

import pymxs
rt = pymxs.runtime

# 检查函数是否存在
if hasattr(rt, 'maxOps') and hasattr(rt.maxOps, 'cloneNodes'):
    # 函数存在,安全调用
    box_obj = rt.Box()
    result, cloned_nodes = rt.maxOps.cloneNodes(box_obj, cloneType=rt.Name('reference'), 
                                               newNodes=pymxs.byref(None))
    print("克隆结果: {}".format(result))
else:
    print("cloneNodes 函数不存在")

# 检查多个函数
functions_to_check = ['maxOps.cloneNodes', 'FileResolutionManager.getFullFilePath', 'maxOps.colorById']

for func_path in functions_to_check:
    parts = func_path.split('.')
    obj = rt
    exists = True
  
    for part in parts:
        if hasattr(obj, part):
            obj = getattr(obj, part)
        else:
            exists = False
            break
  
    print("函数 {}: {}".format(func_path, '存在' if exists else '不存在'))

方法2: 使用 try-except 异常处理

import pymxs
rt = pymxs.runtime

def safe_call_maxscript_function(func_name, *args, **kwargs):
    """安全调用 MAXScript 函数"""
    try:
        # 尝试获取函数
        func = getattr(rt, func_name)
  
        # 调用函数
        result = func(*args, **kwargs)
        return True, result
  
    except AttributeError:
        print("函数 {} 不存在".format(func_name))
        return False, None
    except Exception as e:
        print("调用函数 {} 时出错: {}".format(func_name, e))
        return False, None

# 安全调用示例
success, result = safe_call_maxscript_function('maxOps', 'cloneNodes', 
                                              rt.Box(), cloneType=rt.Name('reference'), 
                                              newNodes=pymxs.byref(None))

if success:
    print("函数调用成功: {}".format(result))

方法3: 使用 dir() 列出可用函数

import pymxs
rt = pymxs.runtime

# 列出 rt 对象的所有可用属性
print("可用的 MAXScript 函数和属性:")
available_functions = [attr for attr in dir(rt) if not attr.startswith('_')]
print(f"总数量: {len(available_functions)}")

# 列出 maxOps 模块的函数
if hasattr(rt, 'maxOps'):
    maxops_functions = [attr for attr in dir(rt.maxOps) if not attr.startswith('_')]
    print(f"maxOps 模块函数: {maxops_functions}")

# 列出 FileResolutionManager 模块的函数
if hasattr(rt, 'FileResolutionManager'):
    file_mgr_functions = [attr for attr in dir(rt.FileResolutionManager) if not attr.startswith('_')]
    print(f"FileResolutionManager 模块函数: {file_mgr_functions}")

方法4: 创建函数存在性验证工具

import pymxs
rt = pymxs.runtime

class MaxScriptFunctionValidator:
    """MAXScript 函数验证工具"""
  
    @staticmethod
    def function_exists(func_path):
        """检查函数是否存在"""
        parts = func_path.split('.')
        obj = rt
  
        for part in parts:
            if hasattr(obj, part):
                obj = getattr(obj, part)
            else:
                return False
        return True
  
    @staticmethod
    def get_function_signature(func_path):
        """获取函数签名(如果可能)"""
        if not MaxScriptFunctionValidator.function_exists(func_path):
            return None
  
        parts = func_path.split('.')
        obj = rt
  
        for part in parts:
            obj = getattr(obj, part)
  
        # 尝试获取函数信息
        try:
            # 在 MAXScript 中,可以使用 help() 或 showProperties() 获取函数信息
            # 这里返回基本类型信息
            return f"函数: {func_path}, 类型: {type(obj)}"
        except:
            return f"函数: {func_path}, 无法获取详细信息"

# 使用验证工具
validator = MaxScriptFunctionValidator()

# 验证常用函数
functions_to_validate = [
    'maxOps.cloneNodes',
    'FileResolutionManager.getFullFilePath', 
    'maxOps.colorById',
    'Box',
    'Sphere',
    'Teapot'
]

print("函数存在性验证结果:")
for func in functions_to_validate:
    exists = validator.function_exists(func)
    signature = validator.get_function_signature(func) if exists else "函数不存在"
    print(f"{func}: {exists} - {signature}")

方法5: 批量验证和错误报告

import pymxs
rt = pymxs.runtime

# 批量验证函数存在性
def batch_validate_functions(function_list):
    """批量验证函数存在性"""
    results = {}
  
    for func_path in function_list:
        parts = func_path.split('.')
        obj = rt
        exists = True
  
        for part in parts:
            if hasattr(obj, part):
                obj = getattr(obj, part)
            else:
                exists = False
                break
  
        results[func_path] = exists
  
    return results

# 测试函数列表
test_functions = [
    'maxOps.cloneNodes',
    'FileResolutionManager.getFullFilePath',
    'maxOps.colorById',
    'Box',
    'Sphere', 
    'Teapot',
    'Cylinder',
    'getNormal',  # 这个函数不存在
    'intersectRay',  # 这个函数不存在
    'getUVW'  # 这个函数不存在
]

# 执行批量验证
validation_results = batch_validate_functions(test_functions)

print("批量函数验证结果:")
for func, exists in validation_results.items():
    status = "✓ 存在" if exists else "✗ 不存在"
    print(f"{status}: {func}")

# 统计结果
existing_count = sum(validation_results.values())
missing_count = len(validation_results) - existing_count

print(f"\n统计: 存在 {existing_count} 个函数,缺失 {missing_count} 个函数")

最佳实践建议

  1. 开发阶段验证: 在开发过程中使用上述方法验证所有要使用的函数
  2. 版本兼容性: 不同版本的 3ds Max 可能包含不同的函数集
  3. 错误处理: 始终使用 try-except 包装函数调用
  4. 文档参考: 参考官方 MAXScript 文档了解可用的函数
  5. 测试驱动: 编写测试用例验证关键函数在不同环境下的行为

通过这些验证方法,可以确保代码的稳定性和兼容性,避免因函数不存在导致的运行时错误。

最佳实践

  1. 新项目: 始终使用 byref()
  2. 确保兼容性: 检查不同 3ds Max 版本的函数可用性
  3. 错误处理: 确保引用参数已正确初始化
  4. 类型安全: 确保引用参数类型与函数期望的类型匹配
# 正确用法示例
import pymxs
rt = pymxs.runtime

# 初始化引用参数
result = rt.Point3(0, 0, 0)  # 正确:使用正确的类型

# 使用 byref 传递引用
# 示例:使用 maxOps.cloneNodes() 函数(需要先创建对象)
# box_obj = rt.Box()
# result, cloned_nodes = rt.maxOps.cloneNodes(box_obj, cloneType=rt.Name('reference'), 
#                                            newNodes=pymxs.byref(None))

# 错误用法示例
# result = None  # 错误:未初始化
# result = "string"  # 错误:类型不匹配

线程安全函数

pymxs.mxstoken()

功能: 创建线程安全令牌

语法:

token = pymxs.mxstoken()

说明:

  • 在多线程环境中安全访问运行时
  • 确保线程安全的 MAXScript 操作
  • 线程已弃用,这个是不规范的

实用示例与最佳实践

场景管理工具

批量场景清理

import pymxs

def clean_scene(keep_lights=True, keep_cameras=True):
    """清理场景中的非必要对象"""
    rt = pymxs.runtime
  
    print("开始清理场景...")
  
    # 获取所有对象
    all_objects = rt.objects
    deleted_count = 0
  
    for obj in all_objects:
        obj_class = rt.classOf(obj)
        obj_name = getattr(obj, 'name', '无名对象')
  
        # 判断是否保留
        should_keep = False
  
        # 保留灯光
        if keep_lights and rt.isKindOf(obj, rt.Light):
            should_keep = True
  
        # 保留相机
        if keep_cameras and rt.isKindOf(obj, rt.Camera):
            should_keep = True
  
        # 保留帮助对象
        if rt.isKindOf(obj, rt.Helper):
            should_keep = True
  
        # 删除不需要的对象
        if not should_keep:
            with pymxs.undo(True, f"删除 {obj_name}"):
                rt.delete(obj)
            deleted_count += 1
  
    print(f"清理完成,删除了 {deleted_count} 个对象")
    return deleted_count

# 使用示例
clean_scene(keep_lights=True, keep_cameras=False)

场景对象统计

import pymxs

def analyze_scene():
    """分析场景统计信息"""
    rt = pymxs.runtime
  
    stats = {
        'total_objects': 0,
        'geometry': 0,
        'lights': 0,
        'cameras': 0,
        'helpers': 0,
        'shapes': 0
    }
  
    for obj in rt.objects:
        stats['total_objects'] += 1
  
        if rt.isKindOf(obj, rt.GeometryClass):
            stats['geometry'] += 1
        elif rt.isKindOf(obj, rt.Light):
            stats['lights'] += 1
        elif rt.isKindOf(obj, rt.Camera):
            stats['cameras'] += 1
        elif rt.isKindOf(obj, rt.Helper):
            stats['helpers'] += 1
        elif rt.isKindOf(obj, rt.Shape):
            stats['shapes'] += 1
  
    # 输出统计信息
    print("=== 场景分析报告 ===")
    for category, count in stats.items():
        print(f"{category}: {count}")
  
    return stats

# 使用示例
scene_stats = analyze_scene()

修改器工具

修改器创建和应用

示例代码:

import pymxs

def apply_modifiers_to_selected(modifier_configs):
    """为选中的对象应用修改器"""
    rt = pymxs.runtime
  
    selected_objects = rt.selection
  
    if not selected_objects:
        print("没有选中任何对象")
        return
  
    print(f"开始为 {len(selected_objects)} 个对象应用修改器...")
  
    with pymxs.undo(True, "批量应用修改器"):
        for obj in selected_objects:
            obj_name = getattr(obj, 'name', '无名对象')
  
            for config in modifier_configs:
                modifier_type = config.get('type')
                modifier_params = config.get('params', {})
      
                # 创建修改器
                if modifier_type == 'bend':
                    modifier = rt.Bend()
                elif modifier_type == 'twist':
                    modifier = rt.Twist()
                elif modifier_type == 'taper':
                    modifier = rt.Taper()
                elif modifier_type == 'noise':
                    modifier = rt.Noisemodifier()
                elif modifier_type == 'displace':
                    modifier = rt.Displace()
                else:
                    print(f"不支持的修改器类型: {modifier_type}")
                    continue
      
                # 设置修改器参数
                for param_name, param_value in modifier_params.items():
                    if hasattr(modifier, param_name):
                        setattr(modifier, param_name, param_value)
      
                # 应用修改器到对象
                rt.addModifier(obj, modifier)
                print(f"为对象 {obj_name} 应用 {modifier_type} 修改器")
  
    print("修改器应用完成")

# 使用示例
modifier_configs = [
    {
        'type': 'bend',
        'params': {
            'bendAngle': 45.0,
            'bendDirection': 90.0,
            'bendAxis': 0
        }
    },
    {
        'type': 'twist',
        'params': {
            'twistAngle': 180.0,
            'twistAxis': 0
        }
    }
]

apply_modifiers_to_selected(modifier_configs)

说明:这段代码演示了如何为选中的对象批量应用不同类型的修改器。

修改器堆栈管理

示例代码:

import pymxs

def manage_modifier_stack():
    """修改器堆栈管理工具 - 优化版本"""
    rt = pymxs.runtime
  
    selected_objects = rt.selection
  
    if not selected_objects:
        print("没有选中任何对象")
        return
  
    for obj in selected_objects:
        obj_name = getattr(obj, 'name', '无名对象')
  
        # 直接使用备用方法,因为主方法中的 handle 函数不存在
        manage_modifier_stack_fallback(obj, obj_name)

def manage_modifier_stack_fallback(obj, obj_name):
    """修改器堆栈管理的备用方法 - 动态参数版本"""
    rt = pymxs.runtime
  
    # 使用更简单的方法:直接遍历对象的 modifiers 属性
    if hasattr(obj, 'modifiers'):
        modifiers = obj.modifiers
        modifier_count = len(modifiers)
  
        if modifier_count == 0:
            print(f"对象 {obj_name} 没有修改器")
            return
  
        print(f"对象 {obj_name} 有 {modifier_count} 个修改器:")
  
        for i, modifier in enumerate(modifiers, 1):
            modifier_name = rt.classOf(modifier)
  
            # 简化启用状态检查
            try:
                modifier_enabled = getattr(modifier, 'enabled', True)
            except:
                modifier_enabled = True
  
            print(f"  {i}. {modifier_name} - {'启用' if modifier_enabled else '禁用'}")
  
            # 动态获取和显示参数
            display_modifier_parameters_dynamic(modifier)

def display_modifier_parameters_dynamic(modifier):
    """动态显示修改器参数 - 更灵活的方法"""
    rt = pymxs.runtime
  
    # 方法1: 获取所有可用的属性
    try:
        # 使用 MAXScript 的 showProperties 函数获取属性列表
        properties_str = rt.execute(f"showProperties {modifier}")
  
        # 解析属性字符串,提取有用的参数
        properties = parse_modifier_properties(properties_str)
  
        # 显示重要的参数
        for prop_name in properties:
            try:
                prop_value = getattr(modifier, prop_name)
                # 只显示数值、布尔值、字符串等简单类型的参数
                if isinstance(prop_value, (int, float, bool, str)):
                    print(f"     {prop_name}: {prop_value}")
            except:
                pass
      
    except:
        # 方法2: 使用预定义的重要参数列表
        display_modifier_parameters_smart(modifier)

def parse_modifier_properties(properties_str):
    """解析 showProperties 返回的属性字符串"""
    # 简单的解析逻辑,提取属性名称
    properties = []
    lines = properties_str.split('\n')
  
    for line in lines:
        line = line.strip()
        if line and ':' in line:
            prop_name = line.split(':')[0].strip()
            # 过滤掉一些系统属性
            if prop_name and not prop_name.startswith('_'):
                properties.append(prop_name)
  
    return properties

def display_modifier_parameters_smart(modifier):
    """智能显示修改器参数 - 基于修改器类型"""
    rt = pymxs.runtime
  
    # 获取修改器类型
    modifier_type = rt.classOf(modifier)
  
    # 根据修改器类型显示相关参数
    common_params = ['name', 'enabled', 'strength', 'scale', 'amount']
  
    # 类型特定的参数映射
    type_specific_params = {
        'Bend': ['bendAngle', 'bendDirection', 'bendAxis'],
        'Twist': ['twistAngle', 'twistAxis'],
        'Taper': ['taperAmount', 'taperCurve'],
        'Noisemodifier': ['scale', 'fractal', 'roughness', 'iterations'],
        'Displace': ['strength', 'map'],
        'FFD': ['latticeSize', 'controlPoints'],
        'Morpher': ['channels'],
        'Skin': ['bones', 'envelopes']
    }
  
    # 合并通用参数和类型特定参数
    all_params = common_params + type_specific_params.get(str(modifier_type), [])
  
    # 显示可用的参数
    param_count = 0
    for param_name in all_params:
        try:
            if hasattr(modifier, param_name):
                param_value = getattr(modifier, param_name)
                # 过滤掉 None 值和空字符串
                if param_value is not None and param_value != "":
                    print(f"     {param_name}: {param_value}")
                    param_count += 1
        except:
            pass
  
    # 如果没有显示任何参数,尝试动态获取
    if param_count == 0:
        display_modifier_parameters_generic(modifier)

def display_modifier_parameters_generic(modifier):
    """通用参数显示方法 - 遍历所有属性"""
    rt = pymxs.runtime
  
    # 获取修改器的所有属性
    try:
        # 使用 dir() 函数获取属性列表
        attributes = dir(modifier)
  
        # 过滤掉系统属性和方法
        for attr_name in attributes:
            if not attr_name.startswith('_') and not callable(getattr(modifier, attr_name)):
                try:
                    attr_value = getattr(modifier, attr_name)
                    # 只显示简单类型的值
                    if isinstance(attr_value, (int, float, bool, str)):
                        print(f"     {attr_name}: {attr_value}")
                except:
                    pass
    except:
        print("     无法获取参数信息")

# 使用示例
manage_modifier_stack()

说明:这段代码演示了如何管理和查看对象的修改器堆栈。

常用修改器操作示例

示例代码:

import pymxs

def create_advanced_modifiers():
    """创建高级修改器效果"""
    rt = pymxs.runtime
  
    # 创建基础几何体
    box = rt.Box(length=50, width=50, height=100)
    box.name = "高级修改器测试"
  
    # 应用弯曲修改器
    bend_modifier = rt.Bend()
    bend_modifier.bendAngle = 90.0
    bend_modifier.bendDirection = 0.0
    bend_modifier.bendAxis = 0
    rt.addModifier(box, bend_modifier)
  
    # 应用扭曲修改器
    twist_modifier = rt.Twist()
    twist_modifier.twistAngle = 180.0
    twist_modifier.twistAxis = 1
    rt.addModifier(box, twist_modifier)
  
    # 应用噪波修改器
    noise_modifier = rt.Noisemodifier()
    noise_modifier.scale = 25.0
    noise_modifier.fractal = True
    noise_modifier.roughness = 0.5
    noise_modifier.iterations = 6.0
    rt.addModifier(box, noise_modifier)
  
    # 应用锥化修改器
    taper_modifier = rt.Taper()
    taper_modifier.taperAmount = 0.5
    taper_modifier.taperCurve = 1.0
    rt.addModifier(box, taper_modifier)
  
    print("高级修改器效果创建完成")
    return box

# 使用示例
modified_object = create_advanced_modifiers()

说明:这段代码演示了如何创建复杂的修改器组合效果。


控制器操作工具

在 pymxs 中使用嵌套属性(如控制器)需要与 MAXScript 不同的方法。MAXScript 会自动处理嵌套对象属性的解析,而 Python 和 pymxs 对点表示法的属性处理方式不同:Python 始终返回属性的引用,而 MAXScript 返回值的副本。

pymxs 与 MAXScript 的属性访问差异

在 MAXScript 中,您可以直接这样做:

b = box()
b.pos.x = 20

但在 pymxs 中,b.pos.x 返回的是位置对象的副本,不再与盒子的位置关联,因此上述代码不会按预期工作。

解决方案

有三种方法可以解决这个问题:

  1. 使用 MAXScript 的 getProperty() 和 setProperty() 函数
  2. 使用 pymxs MXSWrapperBase 的 getmxsprop() 和 setmxsprop() 函数
  3. 处理目标属性的副本,然后将对象分配回去

示例:

from pymxs import runtime as rt

b = rt.box()

# 方法1: 使用 getmxsprop()/setmxsprop()
b.setmxsprop("pos.x", 9.0)  # 正确设置嵌套属性
print(b.getmxsprop("pos.x"))  # 获取嵌套属性值

# 方法2: 使用 MAXScript 的 getProperty()/setProperty()
rt.setProperty(b, "pos.x", 10.0)
print(rt.getProperty(b, "pos.x"))

# 方法3: 处理副本后分配回去
b_pos = b.pos
b_pos.x = 15  # 修改副本
b.pos = b_pos  # 分配回去
print(b.pos.x)

使用 getPropertyController/setPropertyController/setProperty()/getProperty()

在 pymxs 中,需要使用 getPropertyController() 和 setPropertyController() 函数来访问和修改控制器,使用setProperty()和getProperty()来修改和获取控制的参数。

示例:

from pymxs import runtime as rt

# 设置变换 -> 位置控制器
t = rt.teapot()
rt.setPropertyController(t.controller, 'Position', rt.noise_position())
print(rt.getPropertyController(t.controller, 'Position'))

# 设置变换 -> 位置 -> X 位置控制器
s = rt.sphere()
sphr_pos_ctrl = rt.getPropertyController(s.controller, 'Position')
rt.setPropertyController(sphr_pos_ctrl, 'X Position', rt.noise_float())
print(rt.getPropertyController(sphr_pos_ctrl, 'X Position'))

脚本控制器和表达式控制器的设置

脚本控制器示例:

import pymxs 
rt = pymxs.runtime 

sel = rt.selection[0] 

# 设置脚本控制器 
setattr(sel, "pos.controller", rt.position_script()) 
exp = getattr(sel, "pos.controller") 
print(exp) 
setattr(exp, "script", "[sin(T * 2) * 50,0,0]") 

表达式控制器示例:

from pymxs import runtime as rt

# 创建目标对象
s = rt.sphere()

# 创建受控制对象
t = rt.teapot(pos=rt.point3(20,20,0))

# 获取位置控制器
s_pos_ctl = rt.getPropertyController(s.controller, 'Position')

# 创建表达式控制器
expr_pos_ctl = rt.position_expression()

# 添加标量变量,目标是球体的 X 位置
expr_pos_ctl.addScalarTarget('sphere_x', rt.getPropertyController(s_pos_ctl, 'X Position'))

# 添加使用该变量的表达式
expr_pos_ctl.setExpression('[sphere_x, 20,0]')

# 设置控制器
rt.setPropertyController(t.controller, "Position", expr_pos_ctl)

为没有现有控制器的属性分配控制器

要为没有现有控制器的属性添加控制器,需要使用 getSubAnim() 函数找到属性在子动画树结构中的位置,然后通过索引分配控制器。

示例:

from pymxs import runtime as rt

b = rt.box()

# 获取盒子对象的第四个子动画(Object (Box))
box_obj_subanim = rt.getSubAnim(b, 4)

# 获取第二个子动画(Width 属性)
width_subanim = rt.getSubAnim(box_obj_subanim, 2)

# 为宽度属性分配贝塞尔浮点控制器
rt.setProperty(width_subanim, 'controller', rt.bezier_float())

遍历子动画树结构

以下示例展示了如何遍历对象的子动画树结构,以确定正确的索引来分配新控制器:

from pymxs import runtime as rt

b = rt.box()

for sub_i in range(b.numsubs):
    sub = rt.getSubAnim(b, sub_i+1)
    print(f'{sub.name} [{sub_i+1}]')

    if sub.controller is None:
        print(' No controller assigned to it')
    else:
        print(f' current controller: {sub.controller}')
    if sub.keys is None:
        print(' No keys assigned to it')

    for secsub_i in range(sub.numsubs):
        secsub = rt.getSubAnim(sub, secsub_i+1)
        print(f'\t{secsub.name} [{secsub_i+1}]')

        if secsub.controller is None:
            print('\t No controller assigned to it')
        else:
            print(f'\t current controller: {secsub.controller}')
        if secsub.keys is None:
            print('\t No keys assigned to it')
        for thirdsub_i in range(secsub.numsubs):
            thirdsub = rt.getSubAnim(secsub, thirdsub_i+1)
            print(f'\t\t{thirdsub.name} [{thirdsub_i+1}]')
            if secsub.controller is None:
                print('\t No controller assigned to it')
            else:
                print(f'\t\t current controller: {thirdsub.controller}')

说明:这段代码会显示对象的所有子动画及其控制器信息,帮助您确定正确的索引来分配新控制器。

列表控制器的使用

列表控制器(List Controller)将多个控制器组合成单一效果,是一种复合控制器,可管理内部控制器的计算顺序。

列表控制器类型:

  • float_list: 浮点列表控制器
  • point3_list: Point3列表控制器
  • position_list: 位置列表控制器
  • rotation_list: 旋转列表控制器
  • scale_list: 缩放列表控制器

向列表控制器添加子控制器的示例:

from pymxs import runtime as rt

# 创建一个对象
box = rt.box()

# 1. 将对象的位置控制器设置为列表控制器
rt.setPropertyController(box.controller, 'Position', rt.position_list())

# 获取列表控制器
pos_list_ctrl = rt.getPropertyController(box.controller, 'Position')
print(f"创建的列表控制器: {rt.classOf(pos_list_ctrl)}")

# 2. 添加第一个子控制器 (Position_XYZ)
rt.setPropertyController(pos_list_ctrl, 'Available', rt.Position_XYZ())
print(f"添加的第一个子控制器: {rt.classOf(rt.getProperty(pos_list_ctrl, 'Position_XYZ'))}")

# 3. 添加第二个子控制器 (TCB Position)
rt.setPropertyController(pos_list_ctrl, 'Available', rt.tcb_position())
print(f"添加的第二个子控制器: {rt.classOf(rt.getProperty(pos_list_ctrl, 'TCB_Position'))}")

# 4. 添加第三个子控制器 (Bezier Position)
rt.setPropertyController(pos_list_ctrl, 'Available', rt.bezier_position())
print(f"添加的第三个子控制器: {rt.classOf(rt.getProperty(pos_list_ctrl, 'Bezier_Position'))}")

# 5. 查看列表控制器的子控制器数量
print(f"列表控制器中的子控制器数量: {pos_list_ctrl.count}")

# 6. 访问和设置子控制器的权重
# 权重数组包含每个子控制器的权重值
weights = pos_list_ctrl.weight
print(f"当前权重: {weights}")

# 修改权重
if len(weights) >= 3:
    weights[0] = 0.5  # 设置第一个子控制器的权重为0.5
    weights[1] = 0.3  # 设置第二个子控制器的权重为0.3
    weights[2] = 0.2  # 设置第三个子控制器的权重为0.2
    pos_list_ctrl.weight = weights
    print(f"修改后的权重: {pos_list_ctrl.weight}")

# 7. 设置平均权重选项
pos_list_ctrl.average = True
print(f"平均权重选项: {pos_list_ctrl.average}")

说明:

  1. 要向列表控制器添加子控制器,需要使用Available.controller属性(重要:注意大写的A,pymxs中属性名是大小写敏感的)
  2. 每次分配新控制器到Available.controller后,会自动创建一个新的Available属性用于添加下一个控制器
  3. 可以通过weight属性调整每个子控制器的贡献权重
  4. 设置average属性为True可以启用权重平均功能
  5. 使用list接口的方法可以管理和激活特定的子控制器

常见错误:

  • 错误:available.controller(小写的a)
  • 正确:Available.controller(大写的A)

pymxs中所有MAXScript属性名都是大小写敏感的,必须严格按照正确的大小写形式使用。

浮点列表控制器示例:

from pymxs import runtime as rt

# 创建对象
box = rt.box()

# 获取位置控制器
pos_ctrl = rt.getPropertyController(box.controller, 'Position')

# 获取X位置子控制器
x_pos_ctrl = rt.getPropertyController(pos_ctrl, 'X Position')

# 将X位置控制器设置为浮点列表控制器
rt.setPropertyController(pos_ctrl, 'X Position', rt.float_list())

# 获取浮点列表控制器
x_float_list = rt.getPropertyController(pos_ctrl, 'X Position')

# 添加子控制器
rt.setPropertyController(x_float_list, 'Available', rt.bezier_float())
rt.setPropertyController(x_float_list, 'Available', rt.noise_float())

# 设置第二个子控制器的参数
noise_ctrl = rt.getPropertyController(x_float_list, 'Noise_Float')

rt.setProperty(noise_ctrl, 'seed', 1)
rt.setProperty(noise_ctrl, 'frequency', 0.1)
rt.setProperty(noise_ctrl, 'fractal', False)
rt.setProperty(noise_ctrl, 'roughness', 0.5)
rt.setProperty(noise_ctrl, 'rampin', 50)
rt.setProperty(noise_ctrl, 'rampout', 50)

print("浮点列表控制器设置完成")

通过这些示例,您可以了解如何在pymxs中创建、配置和管理列表控制器及其子控制器。


动画工具

关键帧批量设置

import pymxs

def set_keyframes_on_selected(property_name, values_dict):
    """为选中的对象设置关键帧"""
    rt = pymxs.runtime
  
    selected_objects = rt.selection
  
    if not selected_objects:
        print("没有选中任何对象")
        return
  
    print(f"开始为 {len(selected_objects)} 个对象设置关键帧...")
  
    with pymxs.animate(True):
        for obj in selected_objects:
            obj_name = getattr(obj, 'name', '无名对象')
  
            for frame, value in values_dict.items():
                with pymxs.attime(frame):
                    # 动态设置属性
                    if hasattr(obj, property_name):
                        setattr(obj, property_name, value)
                        print(f"对象 {obj_name} 在第 {frame} 帧设置 {property_name} = {value}")
                    else:
                        print(f"对象 {obj_name} 没有属性 {property_name}")
  
    print("关键帧设置完成")

# 使用示例:为选中的对象设置位置动画
position_animation = {
    0: pymxs.runtime.Point3(0, 0, 0),
    25: pymxs.runtime.Point3(100, 0, 0),
    50: pymxs.runtime.Point3(100, 100, 0),
    75: pymxs.runtime.Point3(0, 100, 0),
    100: pymxs.runtime.Point3(0, 0, 0)
}

set_keyframes_on_selected('pos', position_animation)

动画曲线编辑器

import pymxs

def analyze_animation_curves():
    """分析选中对象的动画曲线"""
    rt = pymxs.runtime
  
    selected_objects = rt.selection
  
    if not selected_objects:
        print("没有选中任何对象")
        return
  
    animation_data = {}
  
    for obj in selected_objects:
        obj_name = getattr(obj, 'name', '无名对象')
        animation_data[obj_name] = {}
  
        # 检查常见动画属性
        animatable_properties = ['pos', 'rotation', 'scale']
  
        for prop in animatable_properties:
            if hasattr(obj, prop):
                # 检查属性是否有动画
                prop_controller = getattr(obj, f"{prop}.controller")
  
                if prop_controller and hasattr(prop_controller, 'keys'):
                    keys = prop_controller.keys
                    if keys and keys.count > 0:
                        animation_data[obj_name][prop] = {
                            'key_count': keys.count,
                            'first_key': keys[0].time if keys.count > 0 else None,
                            'last_key': keys[keys.count].time if keys.count > 0 else None
                        }
  
    # 输出分析结果
    print("=== 动画曲线分析 ===\n")
    for obj_name, props in animation_data.items():
        print(f"对象: {obj_name}")
        for prop, data in props.items():
            print(f"  {prop}: {data['key_count']} 个关键帧 "
                        f"(从 {data['first_key']} 到 {data['last_key']})")
  
    return animation_data

# 使用示例
animation_info = analyze_animation_curves()

材质和渲染工具

批量材质应用

import pymxs

def apply_material_to_selected(material_settings):
    """为选中的对象应用材质"""
    rt = pymxs.runtime
  
    selected_objects = rt.selection
  
    if not selected_objects:
        print("没有选中任何对象")
        return
  
    # 创建标准材质
    std_mat = rt.Standard()
  
    # 设置材质属性
    if 'diffuse_color' in material_settings:
        std_mat.diffuse = material_settings['diffuse_color']
  
    if 'specular_level' in material_settings:
        std_mat.specularLevel = material_settings['specular_level']
  
    if 'glossiness' in material_settings:
        std_mat.glossiness = material_settings['glossiness']
  
    # 应用材质到选中的对象
    with pymxs.undo(True, "批量应用材质"):
        for obj in selected_objects:
            obj.material = std_mat
            obj_name = getattr(obj, 'name', '无名对象')
            print(f"为对象 {obj_name} 应用材质")
  
    print(f"成功为 {len(selected_objects)} 个对象应用材质")
    return std_mat

# 使用示例
material_config = {
    'diffuse_color': pymxs.runtime.Color(200, 100, 50),
    'specular_level': 80,
    'glossiness': 30
}

applied_material = apply_material_to_selected(material_config)

渲染设置自动化

import pymxs

def setup_render_settings(settings):
    """自动化渲染设置"""
    rt = pymxs.runtime
  
    print("开始配置渲染设置...")
  
    # 获取渲染器
    renderer = rt.renderers.production
  
    # 设置渲染参数
    if 'output_width' in settings:
        rt.renderWidth = settings['output_width']
  
    if 'output_height' in settings:
        rt.renderHeight = settings['output_height']
  
    if 'output_path' in settings:
        rt.rendOutputFilename = settings['output_path']
  
    # 设置渲染器特定参数
    if hasattr(renderer, 'gi_on') and 'global_illumination' in settings:
        renderer.gi_on = settings['global_illumination']
  
    if hasattr(renderer, 'primary_engine') and 'primary_gi_engine' in settings:
        renderer.primary_engine = settings['primary_gi_engine']
  
    print("渲染设置配置完成")
  
    # 返回当前设置
    current_settings = {
        'width': rt.renderWidth,
        'height': rt.renderHeight,
        'output_path': rt.rendOutputFilename
    }
  
    return current_settings

# 使用示例
render_config = {
    'output_width': 1920,
    'output_height': 1080,
    'output_path': r"C:\\renders\\output.png",
    'global_illumination': True,
    'primary_gi_engine': 0  # Irradiance map
}

current_settings = setup_render_settings(render_config)

性能优化与错误处理

性能优化建议

批量操作优化

import pymxs
rt = pymxs.runtime

# 优化前:频繁调用
for i in range(100):
    box = rt.Box()
    box.pos = rt.Point3(i * 10, 0, 0)

# 优化后:批量操作
boxes = []
for i in range(100):
    boxes.append(rt.Box())

for i, box in enumerate(boxes):
    box.pos = rt.Point3(i * 10, 0, 0)

缓存引用优化

import pymxs
rt = pymxs.runtime

# 优化前:重复访问
for i in range(100):
    rt.objects[i].pos = rt.Point3(i * 10, 0, 0)

# 优化后:缓存引用
objects = rt.objects
for i in range(100):
    objects[i].pos = rt.Point3(i * 10, 0, 0)

错误处理模式

异常处理

import pymxs
rt = pymxs.runtime

try:
        # 尝试创建对象
        obj = rt.NonExistentConstructor()
    except Exception as e:
        print(f"错误: {str(e)}")

# 使用撤销块的异常处理
with pymxs.undo(True, '安全操作'):
    try:
        box = rt.Box()
        # 可能引发异常的操作
        risky_operation()
    except:
        # 异常会被撤销块自动处理
        pass

对象存在性检查

import pymxs
rt = pymxs.runtime

def safe_object_operation(obj, operation):
    """安全的对象操作"""
    if not obj:
        print("对象不存在")
        return False
  
    if not hasattr(obj, operation):
        print(f"对象不支持操作: {operation}")
        return False
  
    try:
        getattr(obj, operation)()
        return True
    except Exception as e:
        print(f"操作失败: {str(e)}")
        return False

开发工作流与调试技巧

推荐开发流程

  1. 原型设计 - 在 MAXScript 监听器中测试概念
  2. Python 实现 - 将验证的概念转换为 Python 代码
  3. 模块化开发 - 将功能分解为可重用的函数和类
  4. 测试验证 - 在不同场景下测试脚本功能
  5. 性能优化 - 根据实际使用情况进行性能调优

调试技巧

调试输出

import pymxs

# 调试输出
print("调试信息")

# 变量检查
def debug_object(obj):
    rt = pymxs.runtime
    print(f"对象类型: {rt.classOf(obj)}")
    print(f"对象位置: {obj.pos}")
    print(f"对象名称: {obj.name}")

性能分析

import pymxs
import time

def profile_operation(operation_name, operation_func):
    """性能分析函数"""
    start_time = time.time()
  
    try:
        result = operation_func()
        elapsed_time = time.time() - start_time
        print(f"{operation_name} 耗时: {elapsed_time:.3f} 秒")
        return result
    except Exception as e:
        print(f"{operation_name} 失败: {str(e)}")
        return None

# 使用示例
profile_operation("批量创建对象", lambda: [pymxs.runtime.Box() for _ in range(100)])

与其他模块的集成

PySide2 GUI 开发示例

以下示例演示如何在 3ds Max 中创建 PySide2 用户界面,并与 pymxs 集成:

#coding:utf8 
import sys  # 导入sys模块 
from PySide2 import QtWidgets, QtCore, QtGui  # 导入 PySide2 中的 QtWidgets、QtCore 和 QtGui 模块 
from pymxs import runtime as rt  # 导入 pymxs 中的 runtime 模块,并重命名为 rt 
 
# 获取3ds Max的主窗口的QWidget 
def max_main_window(): 
    main_window = rt.windows.getMAXHWND()  # 获取3ds Max主窗口的句柄 
    return QtWidgets.QWidget.find(main_window)  # 返回对应的QWidget 
 
# 定义包含各种小部件的用户界面类 
class AllWidgetsUI(QtWidgets.QDialog): 
 
    def __init__(self, parent=None):  # 初始化方法,接受父窗口为参数,默认为3ds Max主窗口 
        super(AllWidgetsUI, self).__init__(parent)  # 调用父类的构造函数 
 
        self.setWindowTitle("All Widgets UI")  # 设置窗口标题 
        self.setMinimumWidth(300)  # 设置窗口最小宽度 
        self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)  # 设置窗口标志 
 
        self.create_widgets()  # 创建小部件 
        self.create_layouts()  # 创建布局 
        self.create_connections()  # 创建信号槽连接 
 
    def create_widgets(self):  # 创建小部件的方法 
        # 创建各种小部件 
        self.line_edit = QtWidgets.QLineEdit() 
        self.combo_box = QtWidgets.QComboBox() 
        self.spin_box = QtWidgets.QSpinBox() 
        self.double_spin_box = QtWidgets.QDoubleSpinBox() 
        self.check_box = QtWidgets.QCheckBox("Check Box") 
        self.radio_button = QtWidgets.QRadioButton("Radio Button") 
        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) 
        self.text_edit = QtWidgets.QTextEdit() 
        self.button = QtWidgets.QPushButton("Button") 
        self.ok_button = QtWidgets.QPushButton("OK") 
        self.cancel_button = QtWidgets.QPushButton("Cancel") 
  
        # 添加 QTableWidget 
        self.table_widget = QtWidgets.QTableWidget() 
 
        # 添加 QTreeWidget 
        self.tree_widget = QtWidgets.QTreeWidget() 
 
    def create_layouts(self):  # 创建布局的方法 
        form_layout = QtWidgets.QFormLayout()  # 创建表单布局 
        form_layout.addRow("Line Edit:", self.line_edit)  # 将 Line Edit 小部件添加到布局中 
        form_layout.addRow("Combo Box:", self.combo_box)  # 将 Combo Box 小部件添加到布局中 
        # 其他小部件的添加过程类似,省略 
  
        button_layout = QtWidgets.QHBoxLayout()  # 创建水平布局 
        button_layout.addStretch()  # 添加伸缩空间 
        button_layout.addWidget(self.ok_button)  # 将 OK 按钮添加到布局中 
        button_layout.addWidget(self.cancel_button)  # 将 Cancel 按钮添加到布局中 
 
        main_layout = QtWidgets.QVBoxLayout(self)  # 创建垂直布局 
        main_layout.addLayout(form_layout)  # 将表单布局添加到主布局中 
        main_layout.addLayout(button_layout)  # 将按钮布局添加到主布局中 
 
    def create_connections(self):  # 创建信号槽连接的方法 
        self.button.clicked.connect(self.print_hello)  # 连接 Button 的点击事件到 print_hello 方法 
        self.ok_button.clicked.connect(self.accept)  # 连接 OK 按钮的点击事件到 accept 方法 
        self.cancel_button.clicked.connect(self.reject)  # 连接 Cancel 按钮的点击事件到 reject 方法 
 
    def print_hello(self):  # 打印 Hello 的方法 
        print("Hello!") 
 
# 主程序入口 
if __name__ == "__main__": 
    try: 
        allWidgets_dialog.close()  # 尝试关闭之前的对话框 
        allWidgets_dialog.deleteLater()  # 尝试延迟删除之前的对话框 
    except: 
        pass 
 
    allWidgets_dialog = AllWidgetsUI()  # 创建 AllWidgetsUI 实例 
    allWidgets_dialog.show()  # 显示 AllWidgetsUI 窗口
示例1: 对话框界面
示例2: 停靠窗口界面

以下示例演示如何在 3ds Max 中创建 PySide2 停靠窗口,实现更紧密的界面集成:

#coding:utf8 
# 导入所需的模块 
from PySide2 import QtWidgets, QtCore  # 导入 PySide2 中的 QtWidgets 和 QtCore 模块 
from pymxs import runtime as rt  # 导入 pymxs 中的 runtime 模块,并重命名为 rt 
 
# 在3ds Max中创建一个圆柱体的函数 
def make_cylinder(): 
    cyl = rt.Cylinder(radius=10, height=30)  # 创建一个半径为10、高度为30的圆柱体 
    rt.redrawViews()  # 刷新3ds Max视图 
 
# 获取3ds Max的主窗口的QWidget 
def max_main_window(): 
    main_window = rt.windows.getMAXHWND()  # 获取3ds Max主窗口的句柄 
    return QtWidgets.QWidget.find(main_window)  # 返回对应的QWidget 
 
# 自定义的PyMaxDockWidget类,继承自QtWidgets.QDockWidget类 
class PyMaxDockWidget(QtWidgets.QDockWidget): 
    def __init__(self): 
        super(PyMaxDockWidget, self).__init__(max_main_window())  # 调用父类的构造函数,并传入主窗口的QWidget作为参数 
        self.setWindowFlags(QtCore.Qt.Tool)  # 设置窗口为工具窗口 
        self.setWindowTitle('PySide Qt Dock Window')  # 设置窗口标题 
        self.initUI()  # 初始化界面 
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)  # 设置关闭窗口时自动删除 
 
    # 初始化界面的方法 
    def initUI(self): 
        main_layout = QtWidgets.QVBoxLayout()  # 创建垂直布局 
        label = QtWidgets.QLabel("Click button to create a cylinder in the scene")  # 创建一个标签 
        main_layout.addWidget(label)  # 将标签添加到布局中 
 
        cylinder_btn = QtWidgets.QPushButton("Cylinder")  # 创建一个按钮 
        cylinder_btn.clicked.connect(make_cylinder)  # 按钮点击事件连接到创建圆柱体的函数 
        main_layout.addWidget(cylinder_btn)  # 将按钮添加到布局中 
 
        widget = QtWidgets.QWidget()  # 创建一个QWidget 
        widget.setLayout(main_layout)  # 将布局设置到QWidget中 
        self.setWidget(widget)  # 将QWidget设置为QDockWidget的内容 
        self.resize(250, 100)  # 设置窗口大小 
 
# 主程序入口 
if __name__ == '__main__': 
    try: 
        allWidgets_dialog.close()  # 尝试关闭之前的对话框 
        allWidgets_dialog.deleteLater()  # 尝试延迟删除之前的对话框 
    except Exception as e: 
        print(e)  # 捕获异常并打印 
 
    allWidgets_dialog = PyMaxDockWidget()  # 创建PyMaxDockWidget实例 
    allWidgets_dialog.show()  # 显示PyMaxDockWidget窗口
#coding:utf8 
import sys  # 导入sys模块 
from PySide2 import QtWidgets, QtCore, QtGui  # 导入 PySide2 中的 QtWidgets、QtCore 和 QtGui 模块 
from pymxs import runtime as rt  # 导入 pymxs 中的 runtime 模块,并重命名为 rt 
 
# 获取3ds Max的主窗口的QWidget 
def max_main_window(): 
    main_window = rt.windows.getMAXHWND()  # 获取3ds Max主窗口的句柄 
    return QtWidgets.QWidget.find(main_window)  # 返回对应的QWidget 
 
# 定义包含各种小部件的用户界面类 
class AllWidgetsUI(QtWidgets.QDialog): 
 
    def __init__(self, parent=None):  # 初始化方法,接受父窗口为参数,默认为3ds Max主窗口 
        super(AllWidgetsUI, self).__init__(parent)  # 调用父类的构造函数 
 
        self.setWindowTitle("All Widgets UI")  # 设置窗口标题 
        self.setMinimumWidth(300)  # 设置窗口最小宽度 
        self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)  # 设置窗口标志 
 
        self.create_widgets()  # 创建小部件 
        self.create_layouts()  # 创建布局 
        self.create_connections()  # 创建信号槽连接 
 
    def create_widgets(self):  # 创建小部件的方法 
        # 创建各种小部件 
        self.line_edit = QtWidgets.QLineEdit() 
        self.combo_box = QtWidgets.QComboBox() 
        self.spin_box = QtWidgets.QSpinBox() 
        self.double_spin_box = QtWidgets.QDoubleSpinBox() 
        self.check_box = QtWidgets.QCheckBox("Check Box") 
        self.radio_button = QtWidgets.QRadioButton("Radio Button") 
        self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) 
        self.text_edit = QtWidgets.QTextEdit() 
        self.button = QtWidgets.QPushButton("Button") 
        self.ok_button = QtWidgets.QPushButton("OK") 
        self.cancel_button = QtWidgets.QPushButton("Cancel") 
  
        # 添加 QTableWidget 
        self.table_widget = QtWidgets.QTableWidget() 
 
        # 添加 QTreeWidget 
        self.tree_widget = QtWidgets.QTreeWidget() 
 
    def create_layouts(self):  # 创建布局的方法 
        form_layout = QtWidgets.QFormLayout()  # 创建表单布局 
        form_layout.addRow("Line Edit:", self.line_edit)  # 将 Line Edit 小部件添加到布局中 
        form_layout.addRow("Combo Box:", self.combo_box)  # 将 Combo Box 小部件添加到布局中 
        # 其他小部件的添加过程类似,省略 
  
        button_layout = QtWidgets.QHBoxLayout()  # 创建水平布局 
        button_layout.addStretch()  # 添加伸缩空间 
        button_layout.addWidget(self.ok_button)  # 将 OK 按钮添加到布局中 
        button_layout.addWidget(self.cancel_button)  # 将 Cancel 按钮添加到布局中 
 
        main_layout = QtWidgets.QVBoxLayout(self)  # 创建垂直布局 
        main_layout.addLayout(form_layout)  # 将表单布局添加到主布局中 
        main_layout.addLayout(button_layout)  # 将按钮布局添加到主布局中 
 
    def create_connections(self):  # 创建信号槽连接的方法 
        self.button.clicked.connect(self.print_hello)  # 连接 Button 的点击事件到 print_hello 方法 
        self.ok_button.clicked.connect(self.accept)  # 连接 OK 按钮的点击事件到 accept 方法 
        self.cancel_button.clicked.connect(self.reject)  # 连接 Cancel 按钮的点击事件到 reject 方法 
 
    def print_hello(self):  # 打印 Hello 的方法 
        print("Hello!") 
 
# 主程序入口 
if __name__ == "__main__": 
    try: 
        allWidgets_dialog.close()  # 尝试关闭之前的对话框 
        allWidgets_dialog.deleteLater()  # 尝试延迟删除之前的对话框 
    except: 
        pass 
 
    allWidgets_dialog = AllWidgetsUI()  # 创建 AllWidgetsUI 实例 
    allWidgets_dialog.show()  # 显示 AllWidgetsUI 窗口

与标准 Python 模块集成

import pymxs
import json
import os

rt = pymxs.runtime

# 与文件系统集成
scene_path = rt.maxFilePath + rt.maxFileName
if os.path.exists(scene_path):
    print(f"场景文件: {scene_path}")

# 与 JSON 集成
config_data = {
    "objects": ["Box", "Teapot", "Sphere"],
    "count": 10
}

# 保存配置
with open("config.json", "w") as f:
    json.dump(config_data, f)

NumPy 集成模块

NumPy 是 Python 中用于科学计算的核心库,与 pymxs 结合可以实现高效的网格数据处理和批量操作。

基础集成示例

import pymxs 
import numpy as np 

rt = pymxs.runtime 

# 使用 NumPy 生成顶点数据 
vertices = np.array([ 
 [0, 0, 0], 
 [100, 0, 0], 
 [100, 100, 0], 
 [0, 100, 0] 
]) 

# 正确创建可编辑网格的方法:先创建基础几何体再转换 
box_obj = rt.Box() 
mesh_obj = rt.convertToMesh(box_obj) 

# 设置顶点数量(必须先设置顶点数量)- 转换为Python整数 
rt.meshOp.setNumVerts(mesh_obj, int(len(vertices))) 

# 使用 NumPy 数据设置顶点位置 - 转换为Python浮点数 
for i, vertex in enumerate(vertices): 
 rt.meshOp.setVert(mesh_obj, i+1, rt.Point3(float(vertex[0]), float(vertex[1]), float(vertex[2]))) 

# 创建面(示例:创建一个三角形面) 
# 使用mesh构造函数直接创建完整网格 
# 先准备MAXScript格式的顶点和面数组 
maxscript_verts = rt.array() 
for vertex in vertices: 
 rt.append(maxscript_verts, rt.Point3(float(vertex[0]), float(vertex[1]), float(vertex[2]))) 

# 创建面数据(一个三角形) 
maxscript_faces = rt.array() 
rt.append(maxscript_faces, rt.Point3(1, 2, 3))  # 使用前三个顶点创建面 

# 删除旧的网格对象 
rt.delete(mesh_obj) 

# 创建新的网格对象,直接传递顶点和面数据 
mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces) 

print(f"使用 NumPy 创建网格完成,顶点数量: {rt.meshOp.getNumVerts(mesh_obj)}") 
print(f"面数量: {rt.meshOp.getNumFaces(mesh_obj)}")

复杂网格创建示例

import pymxs
import numpy as np

rt = pymxs.runtime

# 使用 NumPy 生成更复杂的网格数据
# 创建一个简单的平面网格
vertices = np.array([
    [0, 0, 0],      # 顶点1
    [100, 0, 0],    # 顶点2
    [100, 100, 0],  # 顶点3
    [0, 100, 0]     # 顶点4
])

# 面数据(三角形面)
faces = np.array([
    [1, 2, 3],  # 第一个三角形面
    [1, 3, 4]   # 第二个三角形面
])

# 准备MAXScript格式的顶点和面数组
maxscript_verts = rt.array()
for vertex in vertices:
    rt.append(maxscript_verts, rt.Point3(float(vertex[0]), float(vertex[1]), float(vertex[2])))

# 准备MAXScript格式的面数组
maxscript_faces = rt.array()
for face in faces:
    rt.append(maxscript_faces, rt.Point3(float(face[0]), float(face[1]), float(face[2])))

# 创建完整的网格对象,直接传递顶点和面数据
mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)

# 更新网格显示
rt.update(mesh_obj)

print(f"使用 NumPy 创建复杂网格完成")
print(f"顶点数量: {rt.meshOp.getNumVerts(mesh_obj)}")
print(f"面数量: {rt.meshOp.getNumFaces(mesh_obj)}")

NumPy 批量操作示例

import pymxs
import numpy as np

rt = pymxs.runtime

# 使用 NumPy 批量创建对象
positions = np.random.rand(100, 3) * 200 - 100  # 生成100个随机位置

# 批量创建球体
spheres = []
for i, pos in enumerate(positions):
    sphere = rt.Sphere(radius=5 + np.random.rand() * 10)
    sphere.pos = rt.Point3(float(pos[0]), float(pos[1]), float(pos[2]))
    spheres.append(sphere)

print(f"使用 NumPy 批量创建了 {len(spheres)} 个球体")

# 使用 NumPy 批量修改对象属性
radii = np.random.rand(100) * 20 + 5  # 生成随机半径
for i, sphere in enumerate(spheres):
    sphere.radius = radii[i]

print("使用 NumPy 批量修改对象属性完成")

网格数据处理示例

import pymxs
import numpy as np

rt = pymxs.runtime

# 获取选中对象的网格数据
selected_objects = rt.selection

if selected_objects:
    for obj in selected_objects:
        if rt.isKindOf(obj, rt.Editable_Mesh):
            # 获取顶点数量
            num_verts = rt.meshOp.getNumVerts(obj)
  
            # 使用 NumPy 存储顶点数据
            vertices = np.zeros((num_verts, 3))
  
            # 读取顶点数据到 NumPy 数组
            for i in range(1, num_verts + 1):
                vertex_pos = rt.meshOp.getVert(obj, i)
                vertices[i-1] = [vertex_pos.x, vertex_pos.y, vertex_pos.z]
  
            # 使用 NumPy 进行数据处理(示例:缩放顶点)
            vertices *= 1.1  # 放大10%
  
            # 将处理后的数据写回网格 - 显式转换为Python浮点数
            for i in range(1, num_verts + 1):
                vert_data = vertices[i-1]
                rt.meshOp.setVert(obj, i, rt.Point3(float(vert_data[0]), float(vert_data[1]), float(vert_data[2])))
  
            # 更新网格显示
            rt.update(obj)
  
            print(f"使用 NumPy 处理了对象 {obj.name} 的网格数据")

性能优化技巧

import pymxs
import numpy as np
import time

rt = pymxs.runtime

# 性能对比:普通循环 vs NumPy 批量操作
def test_performance():
    # 创建测试数据
    num_objects = 1000
  
    # 方法1:普通循环
    start_time = time.time()
  
    with pymxs.redraw(False):
        for i in range(num_objects):
            box = rt.Box()
            box.pos = rt.Point3(i * 10, 0, 0)
  
    loop_time = time.time() - start_time
  
    # 清理场景
    rt.delete(rt.objects)
  
    # 方法2:NumPy 批量操作
    start_time = time.time()
  
    with pymxs.redraw(False):
        # 使用 NumPy 生成位置数据
        positions = np.arange(num_objects) * 10
  
        for i, pos in enumerate(positions):
            box = rt.Box()
            box.pos = rt.Point3(float(pos), 0.0, 0.0)
  
    numpy_time = time.time() - start_time
  
    print(f"普通循环时间: {loop_time:.3f}秒")
    print(f"NumPy 批量操作时间: {numpy_time:.3f}秒")
    print(f"性能提升: {loop_time/numpy_time:.1f}倍")

test_performance()

数学运算集成

import pymxs
import numpy as np

rt = pymxs.runtime

# 使用 NumPy 进行复杂的数学运算
def create_parametric_surface():
    # 生成参数化表面数据
    u = np.linspace(0, 2 * np.pi, 20)
    v = np.linspace(0, np.pi, 10)
  
    U, V = np.meshgrid(u, v)
  
    # 参数化表面方程(球面)
    x = 50 * np.sin(V) * np.cos(U)
    y = 50 * np.sin(V) * np.sin(U)
    z = 50 * np.cos(V)
  
    # 创建网格对象
    box_obj = rt.Box()
    mesh_obj = rt.convertToMesh(box_obj)
  
    # 设置顶点数量 - 转换为Python整数
    num_verts = int(x.size)
    rt.meshOp.setNumVerts(mesh_obj, num_verts)
  
    # 设置顶点位置 - 转换为Python浮点数
    for i in range(num_verts):
        rt.meshOp.setVert(mesh_obj, i+1, rt.Point3(float(x.flat[i]), float(y.flat[i]), float(z.flat[i])))
  
    # 创建面(根据球面网格拓扑)
    # 计算面的数量 - 转换为Python整数
    num_u = int(len(u))
    num_v = int(len(v))
  
    # 准备MAXScript格式的顶点数组
    maxscript_verts = rt.array()
    for i in range(num_verts):
        rt.append(maxscript_verts, rt.Point3(float(x.flat[i]), float(y.flat[i]), float(z.flat[i])))
  
    # 准备MAXScript格式的面数组
    maxscript_faces = rt.array()
    for i in range(num_u-1):
        for j in range(num_v-1):
            # 计算当前单元格的四个顶点索引
            v1 = i * num_v + j + 1
            v2 = i * num_v + j + 2
            v3 = (i + 1) * num_v + j + 1
            v4 = (i + 1) * num_v + j + 2
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(v1, v2, v4))
            rt.append(maxscript_faces, rt.Point3(v1, v4, v3))
  
    # 删除旧的网格对象
    rt.delete(mesh_obj)
  
    # 创建新的网格对象,直接传递顶点和面数据
    mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
  
    rt.update(mesh_obj)
    print(f"使用 NumPy 创建参数化表面完成,顶点数量: {num_verts}")

create_parametric_surface()

NumPy 集成优势:

  1. 高性能计算:NumPy 的向量化操作比 Python 循环快数十倍
  2. 内存效率:NumPy 数组比 Python 列表更节省内存
  3. 数学运算:提供丰富的数学函数库
  4. 数据交换:便于与其他科学计算库集成
  5. 批量处理:适合大规模数据操作

注意事项:

  • 确保 3ds Max 环境中已安装 NumPy
  • 大型数组操作时注意内存使用
  • 网格数据转换时注意索引从1开始(MAXScript 惯例)

Python 数学库集成模块

Python 内置的 math 模块提供了丰富的数学函数,与 pymxs 结合可以实现复杂的数学建模和算法应用。

基础数学函数应用

import pymxs
import math

rt = pymxs.runtime

# 使用数学函数创建几何图案
def create_math_pattern():
    # 创建基础几何体
    objects = []
  
    # 使用正弦函数创建波浪形排列
    for i in range(20):
        x = i * 20
        y = math.sin(i * math.pi / 5) * 50  # 正弦波
        z = 0
  
        sphere = rt.Sphere(radius=8)
        sphere.pos = rt.Point3(x, y, z)
        objects.append(sphere)
  
    print(f"使用数学函数创建了 {len(objects)} 个球体")
    return objects

# 使用余弦函数创建圆形排列
def create_circle_pattern():
    objects = []
    radius = 100
  
    for i in range(36):  # 36个对象,每10度一个
        angle = math.radians(i * 10)  # 转换为弧度
        x = math.cos(angle) * radius
        y = math.sin(angle) * radius
        z = 0
  
        box = rt.Box(length=10, width=10, height=10)
        box.pos = rt.Point3(x, y, z)
  
        # 使用数学函数设置旋转
        box.rotation = rt.EulerAngles(0, 0, math.degrees(angle))
        objects.append(box)
  
    print(f"使用三角函数创建了圆形排列的 {len(objects)} 个立方体")
    return objects

# 执行函数
wave_objects = create_math_pattern()
circle_objects = create_circle_pattern()

复杂数学建模示例

import pymxs
import math
import random

rt = pymxs.runtime

# 使用数学函数创建螺旋结构
def create_spiral_structure():
    objects = []
  
    # 螺旋参数
    turns = 3
    radius_start = 20
    radius_end = 80
    height = 100
    points_per_turn = 24
  
    total_points = turns * points_per_turn
  
    for i in range(total_points):
        # 计算螺旋坐标
        angle = 2 * math.pi * i / points_per_turn
        radius = radius_start + (radius_end - radius_start) * i / total_points
        z = height * i / total_points
  
        x = math.cos(angle) * radius
        y = math.sin(angle) * radius
  
        # 创建球体
        sphere = rt.Sphere(radius=5)
        sphere.pos = rt.Point3(x, y, z)
        objects.append(sphere)
  
    print(f"使用数学函数创建了螺旋结构的 {len(objects)} 个球体")
    return objects

# 使用随机数和数学函数创建自然分布
def create_natural_distribution():
    objects = []
  
    for i in range(50):
        # 使用随机数生成自然分布
        angle = random.uniform(0, 2 * math.pi)
        distance = random.gauss(50, 15)  # 高斯分布
  
        x = math.cos(angle) * distance
        y = math.sin(angle) * distance
        z = random.uniform(-10, 10)
  
        # 随机大小
        size = random.uniform(5, 15)
  
        # 随机选择几何体类型
        if random.random() > 0.5:
            obj = rt.Sphere(radius=size)
        else:
            obj = rt.Box(length=size, width=size, height=size)
  
        obj.pos = rt.Point3(x, y, z)
        objects.append(obj)
  
    print(f"使用随机数学函数创建了自然分布的 {len(objects)} 个对象")
    return objects

# 执行复杂数学建模
spiral_objects = create_spiral_structure()
natural_objects = create_natural_distribution()

数学函数与动画结合

import pymxs
import math

rt = pymxs.runtime

# 使用数学函数创建动画路径
def create_animated_path():
    # 创建动画对象
    animated_sphere = rt.Sphere(radius=10)
  
    # 设置动画
    with pymxs.animate(True):
        for frame in range(0, 101):
            with pymxs.attime(frame):
                # 使用数学函数计算位置
                t = frame / 100.0
  
                # Lissajous 曲线
                x = 100 * math.sin(2 * math.pi * t * 2)
                y = 100 * math.sin(2 * math.pi * t * 3 + math.pi/2)
                z = 50 * math.sin(2 * math.pi * t)
  
                animated_sphere.pos = rt.Point3(x, y, z)
  
                # 使用数学函数设置旋转
                rotation_x = math.sin(2 * math.pi * t) * 180
                rotation_y = math.cos(2 * math.pi * t) * 180
                animated_sphere.rotation = rt.EulerAngles(rotation_x, rotation_y, 0)
  
    print("使用数学函数创建了复杂的动画路径")
    return animated_sphere

# 执行动画函数
animated_object = create_animated_path()

高级数学应用:分形几何

import pymxs
import math

rt = pymxs.runtime

# 创建分形树结构
def create_fractal_tree():
    def create_branch(start_pos, direction, length, angle, depth, max_depth):
        if depth > max_depth:
            return []
  
        # 计算分支终点
        end_x = start_pos.x + math.cos(direction) * length
        end_y = start_pos.y + math.sin(direction) * length
        end_z = start_pos.z
        end_pos = rt.Point3(end_x, end_y, end_z)
  
        # 创建圆柱体作为树枝
        branch = rt.Cylinder()
        branch.height = length
        branch.radius = length * 0.05
  
        # 设置位置和旋转
        branch.pos = rt.Point3(
            (start_pos.x + end_pos.x) / 2,
            (start_pos.y + end_pos.y) / 2,
            (start_pos.z + end_pos.z) / 2
        )
  
        # 计算旋转(指向分支方向)
        branch.rotation = rt.EulerAngles(0, 0, math.degrees(direction))
  
        branches = [branch]
  
        # 递归创建子分支
        if depth < max_depth:
            # 左分支
            left_branches = create_branch(
                end_pos, 
                direction - angle, 
                length * 0.7, 
                angle, 
                depth + 1, 
                max_depth
            )
  
            # 右分支
            right_branches = create_branch(
                end_pos, 
                direction + angle, 
                length * 0.7, 
                angle, 
                depth + 1, 
                max_depth
            )
  
            branches.extend(left_branches)
            branches.extend(right_branches)
  
        return branches
  
    # 创建分形树
    start_pos = rt.Point3(0, 0, 0)
    initial_direction = math.pi / 2  # 向上
    initial_length = 50
    branch_angle = math.pi / 6  # 30度
    max_depth = 5
  
    tree_branches = create_branch(
        start_pos, initial_direction, initial_length, 
        branch_angle, 0, max_depth
    )
  
    print(f"使用递归数学函数创建了分形树,包含 {len(tree_branches)} 个分支")
    return tree_branches

# 创建数学曲面
def create_math_surface():
    # 设置网格参数
    grid_size = 10
    total_verts = grid_size * grid_size
  
    # 收集所有顶点位置
    maxscript_verts = rt.array()
    for i in range(grid_size):
        for j in range(grid_size):
            x = (i - grid_size/2) * 10
            y = (j - grid_size/2) * 10
  
            # 使用正弦函数创建波浪曲面
            z = 20 * math.sin(math.sqrt(x*x + y*y) * 0.1)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 计算面(三角形)
    maxscript_faces = rt.array()
    for i in range(grid_size - 1):
        for j in range(grid_size - 1):
            # 计算当前单元格的四个顶点索引
            v1 = i * grid_size + j + 1
            v2 = i * grid_size + j + 2
            v3 = (i + 1) * grid_size + j + 1
            v4 = (i + 1) * grid_size + j + 2
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(v1, v2, v4))
            rt.append(maxscript_faces, rt.Point3(v1, v4, v3))
  
    # 创建新的网格对象,直接传递顶点和面数据
    mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
  
    rt.update(mesh_obj)
    print(f"使用数学函数创建了参数化曲面,包含 {total_verts} 个顶点和 {len(maxscript_faces)} 个面")
    return mesh_obj

# 执行高级数学应用
fractal_tree = create_fractal_tree()
math_surface = create_math_surface()

数学库实用工具函数

import pymxs
import math
import random

rt = pymxs.runtime

# 数学工具函数集合
class MathUtils:
    @staticmethod
    def distance(point1, point2):
        """计算两点之间的距离"""
        dx = point2.x - point1.x
        dy = point2.y - point1.y
        dz = point2.z - point1.z
        return math.sqrt(dx*dx + dy*dy + dz*dz)
  
    @staticmethod
    def lerp(start, end, t):
        """线性插值"""
        return start + (end - start) * t
  
    @staticmethod
    def smoothstep(edge0, edge1, x):
        """平滑步进函数"""
        x = max(0, min(1, (x - edge0) / (edge1 - edge0)))
        return x * x * (3 - 2 * x)
  
    @staticmethod
    def random_point_in_sphere(radius):
        """在球体内生成随机点"""
        # 球坐标随机采样
        theta = random.uniform(0, 2 * math.pi)
        phi = math.acos(2 * random.random() - 1)
        r = radius * random.random() ** (1/3)  # 均匀分布
  
        x = r * math.sin(phi) * math.cos(theta)
        y = r * math.sin(phi) * math.sin(theta)
        z = r * math.cos(phi)
  
        return rt.Point3(x, y, z)

# 使用数学工具函数
utils = MathUtils()

# 示例:创建随机分布的球体
def create_random_sphere_distribution():
    objects = []
  
    for i in range(20):
        # 在半径为100的球体内随机分布
        pos = utils.random_point_in_sphere(100)
  
        sphere = rt.Sphere(radius=5 + random.random() * 10)
        sphere.pos = pos
        objects.append(sphere)
  
    print(f"使用数学工具函数创建了随机球体分布")
    return objects

# 示例:创建渐变颜色对象
def create_gradient_objects():
    objects = []
  
    for i in range(10):
        # 创建对象
        box = rt.Box(length=15, width=15, height=15)
        box.pos = rt.Point3(i * 20 - 90, 0, 0)
  
        # 使用线性插值设置颜色
        t = i / 9.0  # 0到1的渐变
  
        # 从红色渐变到蓝色
        red = utils.lerp(255, 0, t)
        green = utils.lerp(0, 0, t)
        blue = utils.lerp(0, 255, t)
  
        # 创建材质并应用颜色
        mat = rt.Standard()
        mat.diffuse = rt.Color(red, green, blue)
        box.material = mat
  
        objects.append(box)
  
    print(f"使用数学插值函数创建了颜色渐变的对象")
    return objects

# 执行工具函数示例
random_spheres = create_random_sphere_distribution()
gradient_objects = create_gradient_objects()

Python 数学库集成优势:

  1. 内置函数丰富:提供三角函数、指数函数、对数函数等
  2. 精度高:数学计算精度优于手动实现
  3. 性能优秀:C语言实现的底层函数,执行效率高
  4. 标准库:无需额外安装,Python环境自带
  5. 算法基础:为复杂建模提供数学基础

应用场景:

  • 几何图案生成
  • 动画路径计算
  • 随机分布建模
  • 分形几何创建
  • 参数化曲面设计
  • 物理模拟基础

三角函数动画案例

import pymxs
import math

rt = pymxs.runtime

# 创建三角函数波形动画
def create_trigonometric_animation():
    # 创建动画对象
    animated_spheres = []
    num_spheres = 10
    base_radius = 5
  
    # 创建多个球体,每个球体执行不同的三角函数动画
    for i in range(num_spheres):
        sphere = rt.Sphere(radius=base_radius)
        sphere.pos = rt.Point3(i * 30 - 135, 0, 0)
        animated_spheres.append(sphere)
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 将帧转换为时间参数(0到1)
                t = frame / (animation_end - animation_start)
  
                for i, sphere in enumerate(animated_spheres):
                    # 为每个球体分配不同的三角函数动画
                    if i % 4 == 0:
                        # 正弦波动画
                        y = 100 * math.sin(2 * math.pi * t * 2)
                        color = rt.Color(255, 0, 0)  # 红色
                    elif i % 4 == 1:
                        # 余弦波动画
                        y = 100 * math.cos(2 * math.pi * t * 2)
                        color = rt.Color(0, 255, 0)  # 绿色
                    elif i % 4 == 2:
                        # 正切波动画
                        y = 50 * math.tan(math.pi * t * 2)
                        # 限制范围以避免无穷大
                        y = max(-100, min(100, y))
                        color = rt.Color(0, 0, 255)  # 蓝色
                    else:
                        # 正弦+余弦组合波动画
                        y1 = 50 * math.sin(2 * math.pi * t * 2)
                        y2 = 50 * math.cos(2 * math.pi * t * 3)
                        y = y1 + y2
                        color = rt.Color(255, 255, 0)  # 黄色
  
                    # 更新球体位置
                    sphere.pos = rt.Point3(sphere.pos.x, y, 0)
  
                    # 创建材质并设置颜色
                    mat = rt.Standard()
                    mat.diffuse = color
                    sphere.material = mat
                    # 系统会自动为pos属性创建关键帧
  
    print(f"创建了 {num_spheres} 个球体的三角函数波形动画")
    return animated_spheres

# 创建双摆系统动画
def create_double_pendulum_animation():
    # 创建双摆组件
    pendulum_objects = []
  
    # 摆长和质量
    length1 = 50
    length2 = 50
  
    # 创建支点
    pivot = rt.Sphere(radius=3)
    pivot.pos = rt.Point3(0, 0, 0)
    pivot.wirecolor = rt.Color(0, 255, 255)  # 青色
    pendulum_objects.append(pivot)
  
    # 创建第一个摆
    pendulum1 = rt.Cylinder(radius=3, height=length1)
    pendulum1.pos = rt.Point3(0, -length1/2, 0)
    pendulum1.wirecolor = rt.Color(255, 0, 0)  # 红色
    pendulum_objects.append(pendulum1)
  
    # 创建第一个摆的球
    ball1 = rt.Sphere(radius=8)
    ball1.pos = rt.Point3(0, -length1, 0)
    ball1.wirecolor = rt.Color(255, 0, 0)  # 红色
    pendulum_objects.append(ball1)
  
    # 创建第二个摆
    pendulum2 = rt.Cylinder(radius=3, height=length2)
    pendulum2.pos = rt.Point3(0, -length1 - length2/2, 0)
    pendulum2.wirecolor = rt.Color(0, 255, 0)  # 绿色
    pendulum_objects.append(pendulum2)
  
    # 创建第二个摆的球
    ball2 = rt.Sphere(radius=8)
    ball2.pos = rt.Point3(0, -length1 - length2, 0)
    ball2.wirecolor = rt.Color(0, 255, 0)  # 绿色
    pendulum_objects.append(ball2)
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 双摆参数
    g = 9.8
    m1 = 1
    m2 = 1
  
    # 初始角度
    theta1_initial = math.pi / 4  # 45度
    theta2_initial = math.pi / 3  # 60度
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算时间
                t = frame * 0.05
  
                # 简化的双摆运动方程(实际应用中需要使用数值积分)
                theta1 = theta1_initial * math.cos(math.sqrt(g/(length1)) * t)
                theta2 = theta2_initial * math.cos(math.sqrt(g/(length2)) * t * 1.5)
  
                # 计算第一个摆的位置
                x1 = length1 * math.sin(theta1)
                y1 = -length1 * math.cos(theta1)
  
                # 计算第二个摆的位置
                x2 = x1 + length2 * math.sin(theta2)
                y2 = y1 - length2 * math.cos(theta2)
  
                # 更新第一个摆的位置和旋转 - 系统会自动创建关键帧
                pendulum1.pos = rt.Point3(x1, y1, 0)
                pendulum1.rotation = rt.EulerAngles(0, 0, math.degrees(theta1))
                ball1.pos = rt.Point3(x1, y1, 0)
  
                # 更新第二个摆的位置和旋转 - 系统会自动创建关键帧
                pendulum2.pos = rt.Point3(x2, y2, 0)
                pendulum2.rotation = rt.EulerAngles(0, 0, math.degrees(theta2))
                ball2.pos = rt.Point3(x2, y2, 0)
  
    print("创建了双摆系统的三角函数动画")
    return pendulum_objects

# 执行三角函数动画
trig_animation = create_trigonometric_animation()
double_pendulum = create_double_pendulum_animation()

对数和指数函数应用案例

import pymxs
import math
import random

rt = pymxs.runtime

# 创建对数螺旋图案
def create_logarithmic_spiral():
    objects = []
  
    # 对数螺旋参数
    a = 5
    b = 0.1
    turns = 5
    points = 100
  
    for i in range(points):
        # 计算角度
        theta = i * 2 * math.pi / points * turns
  
        # 对数螺旋公式:r = a * e^(b*theta)
        r = a * math.exp(b * theta)
  
        # 转换为笛卡尔坐标
        x = r * math.cos(theta)
        y = r * math.sin(theta)
        z = 0
  
        # 创建球体
        sphere = rt.Sphere(radius=2)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据半径设置颜色渐变
        color_factor = min(1, (r - a) / (a * math.exp(b * 2 * math.pi * turns) - a))
        sphere.wirecolor = rt.Color(255 * color_factor, 100, 255 * (1 - color_factor))
  
        objects.append(sphere)
  
    print(f"使用对数函数创建了包含 {len(objects)} 个点的对数螺旋")
    return objects

# 创建指数增长动画
def create_exponential_growth_animation():
    # 创建基础对象
    base_object = rt.Box(length=10, width=10, height=10)
    base_object.pos = rt.Point3(0, 0, 0)
  
    # 设置动画范围
    animation_start = 0
    animation_end = 50
  
    # 初始大小和增长率
    initial_size = 10
    growth_rate = 1.05  # 5%增长
  
    # 使用animate上下文和attime上下文创建动画,这是最接近MAXScript的方式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算增长因子(指数增长)
                growth_factor = math.pow(growth_rate, frame)
                size = initial_size * growth_factor
  
                # 限制最大大小
                size = min(size, 100)
  
                # 更新对象大小 - 系统会自动在当前帧创建关键帧
                base_object.length = size
                base_object.width = size
                base_object.height = size
  
    print(f"创建了对象的指数增长动画(从 {initial_size} 增长到 {size})")
    return base_object

# 创建对数分布的对象
def create_logarithmic_distribution():
    objects = []
    num_objects = 50
  
    for i in range(num_objects):
        # 生成对数分布的距离
        distance = math.exp(random.uniform(0, 4)) - 1  # 范围:0 到 e^4 -1 ≈ 53
  
        # 随机角度
        angle = random.uniform(0, 2 * math.pi)
  
        # 转换为笛卡尔坐标
        x = distance * math.cos(angle)
        y = distance * math.sin(angle)
        z = random.uniform(-10, 10)
  
        # 创建球体
        sphere = rt.Sphere(radius=3 + random.random() * 2)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据距离设置大小和颜色
        size_factor = min(1, distance / 50)
        sphere.wirecolor = rt.Color(255 * size_factor, 200, 100)
  
        objects.append(sphere)
  
    print(f"使用对数分布创建了 {len(objects)} 个对象")
    return objects

# 执行对数和指数函数应用
log_spiral = create_logarithmic_spiral()
exp_growth_anim = create_exponential_growth_animation()
log_distribution = create_logarithmic_distribution()

向量数学应用案例

import pymxs
import math
import random

rt = pymxs.runtime

# 创建向量数学工具类
class VectorMathUtils:
    @staticmethod
    def add(point1, point2):
        """向量加法"""
        return rt.Point3(point1.x + point2.x, point1.y + point2.y, point1.z + point2.z)
  
    @staticmethod
    def subtract(point1, point2):
        """向量减法"""
        return rt.Point3(point1.x - point2.x, point1.y - point2.y, point1.z - point2.z)
  
    @staticmethod
    def multiply(point, scalar):
        """向量乘以标量"""
        return rt.Point3(point.x * scalar, point.y * scalar, point.z * scalar)
  
    @staticmethod
    def divide(point, scalar):
        """向量除以标量"""
        return rt.Point3(point.x / scalar, point.y / scalar, point.z / scalar)
  
    @staticmethod
    def dot(point1, point2):
        """向量点积"""
        return point1.x * point2.x + point1.y * point2.y + point1.z * point2.z
  
    @staticmethod
    def cross(point1, point2):
        """向量叉积"""
        x = point1.y * point2.z - point1.z * point2.y
        y = point1.z * point2.x - point1.x * point2.z
        z = point1.x * point2.y - point1.y * point2.x
        return rt.Point3(x, y, z)
  
    @staticmethod
    def magnitude(point):
        """向量长度"""
        return math.sqrt(point.x**2 + point.y**2 + point.z**2)
  
    @staticmethod
    def normalize(point):
        """归一化向量"""
        mag = VectorMathUtils.magnitude(point)
        if mag > 0:
            return VectorMathUtils.divide(point, mag)
        return rt.Point3(0, 0, 0)

# 使用向量数学创建粒子系统
def create_vector_particle_system():
    particles = []
    num_particles = 30
  
    # 创建粒子
    for i in range(num_particles):
        particle = rt.Sphere(radius=2)
        # 随机初始位置
        pos = rt.Point3(random.uniform(-50, 50), random.uniform(-50, 50), random.uniform(-50, 50))
        particle.pos = pos
        particles.append(particle)
  
    # 创建目标点
    target = rt.Sphere(radius=5)
    target.pos = rt.Point3(0, 0, 0)
    target.wirecolor = rt.Color(255, 0, 0)
  
    # 向量工具
    vec_utils = VectorMathUtils()
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算时间参数
                t = frame / (animation_end - animation_start)
  
                for i, particle in enumerate(particles):
                    # 计算粒子到目标的向量
                    to_target = vec_utils.subtract(target.pos, particle.pos)
  
                    # 归一化方向向量
                    direction = vec_utils.normalize(to_target)
  
                    # 计算距离
                    distance = vec_utils.magnitude(to_target)
  
                    # 移动速度与距离成正比
                    speed = 2 * distance / 100
  
                    # 计算新位置
                    new_pos = vec_utils.add(particle.pos, vec_utils.multiply(direction, speed))
  
                    # 更新粒子位置 - 系统会自动创建关键帧
                    particle.pos = new_pos
  
                    # 根据距离设置颜色
                    color_factor = min(1, distance / 100)
                    particle.wirecolor = rt.Color(255 * color_factor, 255 * (1 - color_factor), 100)
  
    print(f"使用向量数学创建了包含 {num_particles} 个粒子的粒子系统")
    return particles, target

# 使用向量叉积创建螺旋运动
def create_cross_product_animation():
    # 创建运动对象
    moving_object = rt.Sphere(radius=5)
    moving_object.pos = rt.Point3(50, 0, 0)
  
    # 创建参考向量
    up_vector = rt.Point3(0, 0, 1)
  
    # 向量工具
    vec_utils = VectorMathUtils()
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算角度
                angle = frame * 2 * math.pi / 100
  
                # 计算圆上的点
                x = 50 * math.cos(angle)
                y = 50 * math.sin(angle)
                current_pos = rt.Point3(x, y, 0)
  
                # 计算下一个点用于确定方向
                next_angle = (frame + 1) * 2 * math.pi / 100
                next_x = 50 * math.cos(next_angle)
                next_y = 50 * math.sin(next_angle)
                next_pos = rt.Point3(next_x, next_y, 0)
  
                # 计算方向向量
                direction = vec_utils.subtract(next_pos, current_pos)
  
                # 计算叉积得到旋转轴
                rotation_axis = vec_utils.cross(direction, up_vector)
  
                # 根据叉积大小确定旋转角度
                rotation_angle = math.degrees(vec_utils.magnitude(rotation_axis) * 0.1)
  
                # 更新对象位置和旋转
                moving_object.pos = current_pos
                moving_object.rotation = rt.EulerAngles(0, 0, math.degrees(angle))
                # 系统会自动为pos和rotation属性创建关键帧
  
    print("使用向量叉积创建了螺旋运动动画")
    return moving_object

# 执行向量数学应用
vector_particles, target = create_vector_particle_system()
cross_product_anim = create_cross_product_animation()

复数应用案例

import pymxs
import math
import random

rt = pymxs.runtime

# 创建复数螺旋图案
def create_complex_number_spiral():
    objects = []
  
    # 螺旋参数
    num_points = 100
    start_radius = 10
    growth_factor = 1.03
    rotation_factor = 0.1
  
    for i in range(num_points):
        # 使用复数创建螺旋
        complex_num = complex(start_radius * (growth_factor ** i))
        rotated_num = complex_num * (complex(math.cos(rotation_factor * i), math.sin(rotation_factor * i)))
  
        # 转换为3D坐标
        x = rotated_num.real
        y = rotated_num.imag
        z = i * 2  # 沿z轴延伸
  
        # 创建球体
        sphere = rt.Sphere(radius=2)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据螺旋位置设置颜色
        color_factor = i / num_points
        sphere.wirecolor = rt.Color(255 * color_factor, 100, 255 * (1 - color_factor))
  
        objects.append(sphere)
  
    print(f"使用复数创建了包含 {len(objects)} 个点的螺旋图案")
    return objects

# 创建分形树结构(使用复数运算)
def create_complex_fractal_tree():
    def create_branch(start_point, direction, length, angle, depth, max_depth):
        if depth > max_depth:
            return []
  
        # 使用复数计算分支终点
        complex_dir = complex(math.cos(direction), math.sin(direction))
        complex_start = complex(start_point.x, start_point.y)
        complex_end = complex_start + complex_dir * length
  
        end_point = rt.Point3(complex_end.real, complex_end.imag, start_point.z)
  
        # 创建分支
        branch = rt.Cylinder(radius=length * 0.05, height=length)
        branch.pos = rt.Point3(
            (start_point.x + end_point.x) / 2,
            (start_point.y + end_point.y) / 2,
            start_point.z
        )
        branch.rotation = rt.EulerAngles(0, 0, math.degrees(direction))
  
        branches = [branch]
  
        if depth < max_depth:
            # 创建左分支(使用复数旋转)
            left_angle = direction - angle
            left_complex_dir = complex(math.cos(left_angle), math.sin(left_angle))
            left_branches = create_branch(
                end_point, left_angle, length * 0.7, angle, depth + 1, max_depth
            )
  
            # 创建右分支
            right_angle = direction + angle
            right_complex_dir = complex(math.cos(right_angle), math.sin(right_angle))
            right_branches = create_branch(
                end_point, right_angle, length * 0.7, angle, depth + 1, max_depth
            )
  
            branches.extend(left_branches)
            branches.extend(right_branches)
  
        return branches
  
    # 初始参数
    start_point = rt.Point3(0, 0, 0)
    initial_direction = math.pi / 2  # 向上
    initial_length = 50
    branch_angle = math.pi / 6  # 30度
    max_depth = 5
  
    # 创建分形树
    tree_branches = create_branch(
        start_point, initial_direction, initial_length, branch_angle, 0, max_depth
    )
  
    print(f"使用复数运算创建了分形树,包含 {len(tree_branches)} 个分支")
    return tree_branches

# 创建复数平面可视化
def create_complex_plane_visualization():
    objects = []
  
    # 复数平面参数
    grid_size = 20
    max_value = 5
  
    # 创建网格
    for i in range(-grid_size, grid_size + 1):
        for j in range(-grid_size, grid_size + 1):
            # 计算复数
            real = (i / grid_size) * max_value
            imag = (j / grid_size) * max_value
            complex_num = complex(real, imag)
  
            # 计算复数的模和幅角
            magnitude = abs(complex_num)
            angle = math.atan2(imag, real)
  
            # 创建3D点(将模映射到高度)
            x = real * 30
            y = imag * 30
            z = magnitude * 10  # 高度与模成正比
  
            sphere = rt.Sphere(radius=1)
            sphere.pos = rt.Point3(x, y, z)
  
            # 根据幅角设置颜色
            color_angle = (angle + math.pi) / (2 * math.pi)  # 映射到0-1范围
            sphere.wirecolor = rt.Color(
                255 * color_angle,
                100,
                255 * (1 - color_angle)
            )
  
            objects.append(sphere)
  
    print(f"创建了复数平面可视化,包含 {len(objects)} 个点")
    return objects

# 创建复数动画
def create_complex_number_animation():
    # 创建基础对象
    base_objects = []
    num_objects = 20
  
    # 创建初始位置
    for i in range(num_objects):
        sphere = rt.Sphere(radius=3)
        angle = i * 2 * math.pi / num_objects
        initial_radius = 50
        x = initial_radius * math.cos(angle)
        y = initial_radius * math.sin(angle)
        sphere.pos = rt.Point3(x, y, 0)
        base_objects.append(sphere)
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算时间参数
                t = frame / (animation_end - animation_start)
  
                # 复数旋转因子
                rotation_angle = math.pi * t * 2  # 两圈
                complex_rotation = complex(math.cos(rotation_angle), math.sin(rotation_angle))
  
                # 复数缩放因子
                scale_factor = 1 + t * 0.5  # 增加50%
                complex_scale = complex(scale_factor)
  
                for i, sphere in enumerate(base_objects):
                    # 初始复数位置
                    initial_angle = i * 2 * math.pi / num_objects
                    initial_pos = complex(50 * math.cos(initial_angle), 50 * math.sin(initial_angle))
  
                    # 使用复数运算更新位置
                    new_pos = initial_pos * complex_rotation * complex_scale
  
                    # 更新球体位置
                    sphere.pos = rt.Point3(new_pos.real, new_pos.imag, 0)
                    # 系统会自动为pos属性创建关键帧
  
    print(f"创建了 {num_objects} 个对象的复数动画")
    return base_objects

# 执行复数应用案例
complex_spiral = create_complex_number_spiral()
complex_fractal_tree = create_complex_fractal_tree()
complex_plane = create_complex_plane_visualization()
complex_animation = create_complex_number_animation()

统计函数应用案例

import pymxs
import math
import random

rt = pymxs.runtime

# 创建正态分布点云
def create_normal_distribution():
    objects = []
    num_points = 100
  
    # 正态分布参数
    mean_x = 0
    mean_y = 0
    mean_z = 0
    std_dev = 20
  
    for i in range(num_points):
        # 使用Box-Muller变换生成正态分布随机数
        u1 = random.random()
        u2 = random.random()
  
        z0 = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
        z1 = math.sqrt(-2 * math.log(u1)) * math.sin(2 * math.pi * u2)
        z2 = math.sqrt(-2 * math.log(random.random())) * math.cos(2 * math.pi * random.random())
  
        # 转换为指定均值和标准差的正态分布
        x = mean_x + z0 * std_dev
        y = mean_y + z1 * std_dev
        z = mean_z + z2 * std_dev
  
        # 创建球体
        sphere = rt.Sphere(radius=2)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据距离中心的远近设置颜色
        distance = math.sqrt(x**2 + y**2 + z**2)
        color_factor = min(1, distance / (3 * std_dev))
        sphere.wirecolor = rt.Color(255 * color_factor, 255 * (1 - color_factor), 100)
  
        objects.append(sphere)
  
    print(f"创建了包含 {len(objects)} 个点的正态分布点云")
    return objects

# 创建均匀分布点云
def create_uniform_distribution():
    objects = []
    num_points = 100
  
    # 均匀分布范围
    min_val = -50
    max_val = 50
  
    for i in range(num_points):
        # 生成均匀分布的随机数
        x = random.uniform(min_val, max_val)
        y = random.uniform(min_val, max_val)
        z = random.uniform(min_val, max_val)
  
        # 创建立方体
        cube = rt.Box(length=4, width=4, height=4)
        cube.pos = rt.Point3(x, y, z)
  
        # 设置随机颜色
        cube.wirecolor = rt.Color(
            random.randint(100, 255),
            random.randint(100, 255),
            random.randint(100, 255)
        )
  
        objects.append(cube)
  
    print(f"创建了包含 {len(objects)} 个点的均匀分布点云")
    return objects

# 创建泊松分布可视化
def create_poisson_distribution():
    objects = []
    num_intervals = 20
  
    # 泊松分布参数
    lambda_val = 5.0
  
    # 预先生成泊松分布概率
    def poisson_probability(k, lambda_val):
        # 使用斯特林公式近似计算阶乘
        if k < 0:
            return 0
        elif k == 0:
            return math.exp(-lambda_val)
        else:
            # 使用对数计算避免数值溢出
            log_prob = k * math.log(lambda_val) - lambda_val - sum(math.log(i) for i in range(1, k+1))
            return math.exp(log_prob)
  
    # 创建柱状图
    for k in range(num_intervals):
        probability = poisson_probability(k, lambda_val)
  
        # 转换为可视化高度
        height = probability * 500
  
        # 创建柱状图柱子
        bar = rt.Box(length=10, width=10, height=height)
        bar.pos = rt.Point3(k * 15 - 150, 0, height/2)
  
        # 设置颜色
        color_factor = probability / poisson_probability(math.floor(lambda_val), lambda_val)
        bar.wirecolor = rt.Color(255 * color_factor, 100, 100)
  
        objects.append(bar)
  
    print(f"创建了λ={lambda_val}的泊松分布可视化")
    return objects

# 创建累积分布函数可视化
def create_cumulative_distribution():
    objects = []
    num_points = 100
  
    # 正态分布参数
    mean = 0
    std_dev = 20
  
    # 计算累积分布函数
    def normal_cdf(x, mean, std_dev):
        return 0.5 * (1 + math.erf((x - mean) / (std_dev * math.sqrt(2))))
  
    # 创建CDF曲线
    for i in range(num_points):
        x = (i / num_points) * 100 - 50
        y = normal_cdf(x, mean, std_dev) * 100
  
        # 创建点
        sphere = rt.Sphere(radius=2)
        sphere.pos = rt.Point3(x, y, 0)
  
        # 设置颜色
        color_factor = y / 100
        sphere.wirecolor = rt.Color(100, 255 * color_factor, 255 * (1 - color_factor))
  
        objects.append(sphere)
  
    print(f"创建了正态分布的累积分布函数可视化")
    return objects

# 执行统计函数应用
normal_points = create_normal_distribution()
uniform_points = create_uniform_distribution()
poisson_plot = create_poisson_distribution()
cdf_plot = create_cumulative_distribution()

数学曲面和体积案例

本案例演示了如何使用 pymxs 创建各种数学曲面和体积模型。所有模型均采用直接创建网格的方式,使用参数方程生成顶点和面,而不是使用球体表示点云。

import pymxs
import math
import random

rt = pymxs.runtime

# 创建环形曲面
def create_torus_surface():
    # 环形参数
    major_radius = 50
    minor_radius = 20
    major_segments = 30
    minor_segments = 20
  
    # 准备顶点和面对象
    maxscript_verts = rt.array()
    maxscript_faces = rt.array()
  
    # 生成顶点
    for i in range(major_segments):
        for j in range(minor_segments):
            # 环形参数方程
            u = i / major_segments * 2 * math.pi
            v = j / minor_segments * 2 * math.pi
  
            x = (major_radius + minor_radius * math.cos(v)) * math.cos(u)
            y = (major_radius + minor_radius * math.cos(v)) * math.sin(u)
            z = minor_radius * math.sin(v)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 生成面
    for i in range(major_segments):
        for j in range(minor_segments):
            # 计算当前单元格的四个顶点索引
            base_index = i * minor_segments + j + 1
            next_index_u = ((i + 1) % major_segments) * minor_segments + j + 1
            next_index_v = i * minor_segments + ((j + 1) % minor_segments) + 1
            next_index_uv = ((i + 1) % major_segments) * minor_segments + ((j + 1) % minor_segments) + 1
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(base_index, next_index_v, next_index_uv))
            rt.append(maxscript_faces, rt.Point3(base_index, next_index_uv, next_index_u))
  
    # 创建网格对象
    torus_mesh = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
    torus_mesh.name = "数学环形曲面"
  
    # 创建材质
    mat = rt.Standard()
    mat.diffuse = rt.Color(150, 100, 255)
    torus_mesh.material = mat
  
    print(f"创建了环形曲面,包含 {maxscript_verts.count} 个顶点和 {maxscript_faces.count} 个面")
    return [torus_mesh]

# 创建马鞍面
def create_saddle_surface():
    # 马鞍面参数
    grid_size = 20
    scale = 30
  
    # 计算总顶点数
    vertex_count = (2 * grid_size + 1) * (2 * grid_size + 1)
  
    # 准备顶点和面对象
    maxscript_verts = rt.array()
    maxscript_faces = rt.array()
  
    # 创建顶点网格
    for i in range(-grid_size, grid_size + 1):
        for j in range(-grid_size, grid_size + 1):
            # 马鞍面方程: z = x² - y²
            x = i / grid_size * scale
            y = j / grid_size * scale
            z = (x**2 - y**2) / (scale * 2)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 创建面
    for i in range(2 * grid_size):
        for j in range(2 * grid_size):
            # 计算当前单元格的四个顶点索引
            v1 = i * (2 * grid_size + 1) + j + 1
            v2 = i * (2 * grid_size + 1) + j + 2
            v3 = (i + 1) * (2 * grid_size + 1) + j + 1
            v4 = (i + 1) * (2 * grid_size + 1) + j + 2
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(v1, v2, v4))
            rt.append(maxscript_faces, rt.Point3(v1, v4, v3))
  
    # 创建网格对象
    saddle_mesh = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
    saddle_mesh.name = "数学马鞍面"
  
    # 创建材质
    mat = rt.Standard()
    mat.diffuse = rt.Color(255, 150, 100)
    saddle_mesh.material = mat
  
    print(f"创建了马鞍面,包含 {maxscript_verts.count} 个顶点和 {maxscript_faces.count} 个面")
    return [saddle_mesh]

# 创建莫比乌斯带
def create_mobius_strip():
    # 莫比乌斯带参数
    radius = 50
    width = 20
    segments = 50
    width_segments = 21  # -10到10,共21个点
  
    # 准备顶点和面对象
    maxscript_verts = rt.array()
    maxscript_faces = rt.array()
  
    # 生成顶点
    for i in range(segments):
        for j in range(-10, 11):
            # 莫比乌斯带参数方程
            t = i / segments * 2 * math.pi
            s = j / 10 * width / 2
  
            # 计算点坐标
            x = (radius + s * math.cos(t/2)) * math.cos(t)
            y = (radius + s * math.cos(t/2)) * math.sin(t)
            z = s * math.sin(t/2)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 生成面
    for i in range(segments):
        for j in range(width_segments - 1):
            # 计算当前单元格的四个顶点索引
            base_index = i * width_segments + j + 1
  
            # 下一个角度段的索引(考虑莫比乌斯带的连接特性)
            if i == segments - 1:
                next_angle_index = (j + width_segments // 2) % width_segments + 1
            else:
                next_angle_index = (i + 1) * width_segments + j + 1
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(base_index, base_index + 1, next_angle_index + 1))
            rt.append(maxscript_faces, rt.Point3(base_index, next_angle_index + 1, next_angle_index))
  
    # 创建网格对象
    mobius_mesh = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
    mobius_mesh.name = "数学莫比乌斯带"
  
    # 创建材质
    mat = rt.Standard()
    mat.diffuse = rt.Color(255, 150, 100)
    mobius_mesh.material = mat
  
    print(f"创建了莫比乌斯带,包含 {maxscript_verts.count} 个顶点和 {maxscript_faces.count} 个面")
    return [mobius_mesh]

# 创建球谐函数可视化
def create_spherical_harmonic():
    # 球谐函数参数
    l = 2  # 角量子数
    m = 1  # 磁量子数
    radius = 50
    resolution = 20
  
    # 准备顶点和面对象
    maxscript_verts = rt.array()
    maxscript_faces = rt.array()
  
    def spherical_harmonic(l, m, theta, phi):
        # 简化的球谐函数计算(仅用于可视化)
        if l == 2 and m == 1:
            return math.sin(theta) * math.cos(theta) * math.cos(phi)
        return 1
  
    # 生成顶点
    for i in range(resolution):
        for j in range(resolution):
            # 球坐标系
            theta = i / resolution * math.pi
            phi = j / resolution * 2 * math.pi
  
            # 计算球谐函数值
            sh_value = spherical_harmonic(l, m, theta, phi)
  
            # 计算3D坐标
            r = radius * (1 + 0.3 * sh_value)
            x = r * math.sin(theta) * math.cos(phi)
            y = r * math.sin(theta) * math.sin(phi)
            z = r * math.cos(theta)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 生成面
    for i in range(resolution - 1):
        for j in range(resolution - 1):
            # 计算当前单元格的四个顶点索引
            base_index = i * resolution + j + 1
            next_row_index = (i + 1) * resolution + j + 1
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(base_index, base_index + 1, next_row_index + 1))
            rt.append(maxscript_faces, rt.Point3(base_index, next_row_index + 1, next_row_index))
  
    # 创建网格对象
    harmonic_mesh = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
    harmonic_mesh.name = "数学球谐函数可视化"
  
    # 创建材质
    mat = rt.Standard()
    mat.diffuse = rt.Color(200, 100, 255)
    harmonic_mesh.material = mat
  
    print(f"创建了球谐函数(l={l}, m={m})可视化,包含 {maxscript_verts.count} 个顶点和 {maxscript_faces.count} 个面")
    return [harmonic_mesh]

# 创建克莱因瓶(简化表示)
def create_klein_bottle():
    # 克莱因瓶参数
    segments = 30
    radius = 40
  
    # 准备顶点和面对象
    maxscript_verts = rt.array()
    maxscript_faces = rt.array()
  
    # 生成顶点
    for i in range(segments):
        for j in range(segments):
            # 简化的克莱因瓶参数方程
            u = i / segments * 2 * math.pi
            v = j / segments * 2 * math.pi
  
            if v < math.pi:
                x = (6 * math.cos(u) * (1 + math.sin(u))) + (radius * math.cos(u) * math.cos(v))
                y = 16 * math.sin(u) + (radius * math.sin(u) * math.cos(v))
                z = radius * math.sin(v)
            else:
                x = (6 * math.cos(u) * (1 + math.sin(u))) + (radius * math.cos(u + math.pi) * (1 - math.cos(v)))
                y = 16 * math.sin(u)
                z = (radius * math.sin(v)) + 20
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 生成面
    for i in range(segments - 1):
        for j in range(segments - 1):
            # 计算当前单元格的四个顶点索引
            base_index = i * segments + j + 1
            next_row_index = (i + 1) * segments + j + 1
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(base_index, base_index + 1, next_row_index + 1))
            rt.append(maxscript_faces, rt.Point3(base_index, next_row_index + 1, next_row_index))
  
    # 创建网格对象
    klein_mesh = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
    klein_mesh.name = "数学克莱因瓶"
  
    # 创建材质
    mat = rt.Standard()
    mat.diffuse = rt.Color(100, 200, 255)
    klein_mesh.material = mat
  
    print(f"创建了克莱因瓶(简化表示),包含 {maxscript_verts.count} 个顶点和 {maxscript_faces.count} 个面")
    return [klein_mesh]

# 执行数学曲面和体积案例
torus_surface = create_torus_surface()
saddle_surface = create_saddle_surface()
mobius_strip = create_mobius_strip()
spherical_harmonic = create_spherical_harmonic()
klein_bottle = create_klein_bottle()

几何变换与矩阵运算

import pymxs
import math

rt = pymxs.runtime

# 使用矩阵变换创建复杂几何体
def create_matrix_transformed_objects():
    objects = []
  
    # 应用不同的变换矩阵
    transformations = [
        # 单位矩阵(不变换)
        rt.Matrix3(1),
  
        # 平移变换
        rt.translate(rt.Matrix3(1), rt.Point3(50, 0, 0)),
  
        # 旋转变换
        rt.rotateX(rt.Matrix3(1), math.radians(45)),
        rt.rotateY(rt.Matrix3(1), math.radians(30)),
  
        # 缩放变换
        rt.scale(rt.Matrix3(1), rt.Point3(1.5, 0.8, 1.2)),
  
        # 组合变换
        rt.scale(rt.rotateX(rt.Matrix3(1), math.radians(60)), rt.Point3(0.7, 0.7, 1.5))
    ]
  
    for i, matrix in enumerate(transformations):
        # 创建新的几何体(而不是克隆)
        new_sphere = rt.Sphere(radius=10)
  
        # 应用变换矩阵
        new_sphere.transform = matrix
  
        # 设置不同颜色
        new_sphere.wirecolor = rt.Color(i * 40, 100, 200)
        objects.append(new_sphere)
  
    print(f"使用矩阵变换创建了 {len(objects)} 个几何体")
    return objects

# 使用数学函数计算变换矩阵
def create_custom_transformations():
    objects = []
  
    for i in range(12):
        # 创建基础立方体
        cube = rt.Box(length=15, width=15, height=15)
  
        # 计算角度(每小时30度)
        angle = math.radians(i * 30)
  
        # 计算位置(圆形排列)
        radius = 80
        x = math.cos(angle) * radius
        y = math.sin(angle) * radius
        z = 0
  
        # 创建变换矩阵
        # 平移矩阵
        translation = rt.translate(rt.Matrix3(1), rt.Point3(x, y, z))
  
        # 旋转矩阵(指向圆心)
        rotation = rt.rotateZ(rt.Matrix3(1), angle + math.pi/2)
  
        # 组合变换(使用矩阵乘法)
        transform = translation * rotation
  
        cube.transform = transform
        cube.wirecolor = rt.Color(150, i * 20, 100)
        objects.append(cube)
  
    print(f"使用自定义变换创建了时钟排列的 {len(objects)} 个立方体")
    return objects

# 执行几何变换示例
transformed_objects = create_matrix_transformed_objects()
clock_objects = create_custom_transformations()

物理模拟与运动学应用

import pymxs
import math
import random

rt = pymxs.runtime

# 抛物线运动模拟
def simulate_parabolic_motion():
    objects = []
  
    # 物理参数
    initial_velocity = 50  # 初始速度
    launch_angle = math.radians(45)  # 发射角度
    gravity = -9.8  # 重力加速度
    time_steps = 20  # 时间步数
  
    # 计算初始速度分量
    vx = initial_velocity * math.cos(launch_angle)
    vy = initial_velocity * math.sin(launch_angle)
  
    for t in range(time_steps):
        time = t * 0.2  # 时间增量
  
        # 计算位置(忽略空气阻力)
        x = vx * time
        y = vy * time + 0.5 * gravity * time**2
        z = 0
  
        # 创建球体表示轨迹点
        sphere = rt.Sphere(radius=3)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据高度设置颜色
        height_factor = max(0, min(1, y / 30))
        sphere.wirecolor = rt.Color(255 * height_factor, 100, 100)
        objects.append(sphere)
  
    print(f"模拟抛物线运动创建了 {len(objects)} 个轨迹点")
    return objects

# 弹簧振子模拟
def simulate_spring_oscillator():
    objects = []
  
    # 物理参数
    mass = 1.0  # 质量
    spring_constant = 10.0  # 弹簧常数
    damping = 0.1  # 阻尼系数
    equilibrium = 0  # 平衡位置
  
    # 初始条件
    position = 50  # 初始位移
    velocity = 0  # 初始速度
  
    time_steps = 60
  
    for t in range(time_steps):
        # 计算弹簧力(胡克定律)
        spring_force = -spring_constant * (position - equilibrium)
  
        # 计算阻尼力
        damping_force = -damping * velocity
  
        # 计算总力
        total_force = spring_force + damping_force
  
        # 计算加速度(牛顿第二定律)
        acceleration = total_force / mass
  
        # 更新速度和位置(欧拉积分)
        velocity += acceleration * 0.1
        position += velocity * 0.1
  
        # 创建振子位置
        sphere = rt.Sphere(radius=5)
        sphere.pos = rt.Point3(t * 10, position, 0)
  
        # 根据速度设置颜色
        speed_factor = min(1, abs(velocity) / 20)
        sphere.wirecolor = rt.Color(100, 255 * speed_factor, 100)
        objects.append(sphere)
  
    print(f"模拟弹簧振子创建了 {len(objects)} 个位置点")
    return objects

# 执行物理模拟
parabolic_trajectory = simulate_parabolic_motion()
spring_oscillator = simulate_spring_oscillator()

动画物理模拟与运动学应用

碰撞检测动画模拟
def create_collision_animation():
    # 创建移动球体
    moving_ball = rt.Sphere(radius=10)
    moving_ball.pos = rt.Point3(0, 0, -100)  # z轴向上
  
    # 创建固定球体
    fixed_ball = rt.Sphere(radius=15)
    fixed_ball.pos = rt.Point3(0, 0, 50)  # z轴向上
  
    # 创建可动画的材质(使用Standard材质)
    moving_material = rt.Standard()
    moving_material.diffuse = rt.Color(255, 0, 0)  # 初始红色
    moving_ball.material = moving_material
  
    fixed_material = rt.Standard()
    fixed_material.diffuse = rt.Color(0, 255, 0)  # 固定绿色
    fixed_ball.material = fixed_material
  
    # 物理参数
    velocity = 5.0  # 初始速度
    restitution = 0.8  # 弹性系数
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算当前位置(z轴)
                current_pos = moving_ball.pos.z
  
                # 检测碰撞(z轴方向)
                distance_to_fixed = fixed_ball.pos.z - current_pos - 10 - 15
  
                if distance_to_fixed <= 0:
                    # 发生碰撞,反转速度
                    velocity = -velocity * restitution
                    # 设置碰撞时的材质颜色(黄色)
                    moving_material.diffuse = rt.Color(255, 255, 0)
                else:
                    # 设置正常移动时的材质颜色(红色)
                    moving_material.diffuse = rt.Color(255, 0, 0)
  
                # 更新位置(z轴向上)
                new_pos = current_pos + velocity
                moving_ball.pos = rt.Point3(0, 0, new_pos)
                # 系统会自动为pos和diffuse属性创建关键帧
  
    print("碰撞检测动画创建完成")
    return [moving_ball, fixed_ball]
轨迹动画与运动路径
# 抛物线轨迹动画
def create_parabolic_trajectory_animation():
    # 创建抛射物体
    projectile = rt.Sphere(radius=5)
  
    # 创建可动画的材质
    projectile_material = rt.Standard()
    projectile_material.diffuse = rt.Color(255, 0, 0)  # 初始红色
    projectile.material = projectile_material
  
    # 物理参数
    initial_velocity = 40  # 初始速度
    launch_angle = math.radians(60)  # 发射角度
    gravity = -9.8  # 重力加速度
  
    # 计算初始速度分量(z轴向上)
    vx = initial_velocity * math.cos(launch_angle)
    vz = initial_velocity * math.sin(launch_angle)  # z轴方向
  
    # 设置动画范围
    animation_start = 0
    animation_end = 50
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算时间
                time = frame * 0.1
  
                # 计算位置(忽略空气阻力,z轴向上)
                x = vx * time
                z = vz * time + 0.5 * gravity * time**2  # z轴方向
  
                # 如果物体落地,停止动画
                if z < 0:
                    z = 0
                    projectile_material.diffuse = rt.Color(128, 0, 0)  # 落地后变暗红色
  
                # 更新位置(z轴向上)
                projectile.pos = rt.Point3(x, 0, z)
                # 系统会自动为pos和diffuse属性创建关键帧
  
    print("抛物线轨迹动画创建完成")
    return projectile

# 圆周运动动画
def create_circular_motion_animation():
    # 创建运动物体
    moving_object = rt.Sphere(radius=8)
  
    # 创建可动画的材质
    moving_material = rt.Standard()
    moving_material.diffuse = rt.Color(0, 0, 255)  # 蓝色
    moving_object.material = moving_material
  
    # 运动参数
    radius = 50  # 圆周半径
    angular_velocity = math.radians(10)  # 角速度(度/帧)
  
    # 设置动画范围
    animation_start = 0
    animation_end = 72  # 360度 / 5度每帧 = 72帧
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                # 计算角度
                angle = angular_velocity * frame
  
                # 计算位置(z轴向上,在XY平面做圆周运动)
                x = radius * math.cos(angle)
                y = radius * math.sin(angle)
  
                # 更新位置(z轴向上)
                moving_object.pos = rt.Point3(x, y, 0)
                # 系统会自动为pos属性创建关键帧
  
    print("圆周运动动画创建完成")
    return moving_object
实时物理模拟动画
# 粒子系统物理模拟
def create_particle_physics_animation():
    particles = []
    num_particles = 20
  
    # 创建粒子
    for i in range(num_particles):
        particle = rt.Sphere(radius=2)
        particle.wirecolor = rt.Color(random.randint(0, 255), 
                                     random.randint(0, 255), 
                                     random.randint(0, 255))
        particles.append(particle)
  
    # 物理参数
    gravity = -9.8
    damping = 0.95
  
    # 初始化粒子状态(z轴向上)
    positions = []
    velocities = []
  
    for i in range(num_particles):
        # 随机初始位置(z轴向上)
        x = random.uniform(-50, 50)
        z = random.uniform(0, 100)  # z轴方向
        y = random.uniform(-50, 50)
        positions.append(rt.Point3(x, y, z))
  
        # 随机初始速度(z轴向上)
        vx = random.uniform(-5, 5)
        vz = random.uniform(-2, 0)  # z轴方向
        vy = random.uniform(-5, 5)
        velocities.append(rt.Point3(vx, vy, vz))
  
    # 设置动画范围
    animation_start = 0
    animation_end = 100
  
    # 启用动画模式
    with pymxs.animate(True):
        for frame in range(animation_start, animation_end + 1):
            # 使用attime上下文设置当前时间和属性值
            with pymxs.attime(frame):
                for i in range(num_particles):
                    # 应用重力(z轴方向)
                    velocities[i].z += gravity * 0.1
  
                    # 更新位置
                    positions[i].x += velocities[i].x
                    positions[i].y += velocities[i].y
                    positions[i].z += velocities[i].z
  
                    # 地面碰撞检测(z轴方向)
                    if positions[i].z < 0:
                        positions[i].z = 0
                        velocities[i].z = -velocities[i].z * damping
                        velocities[i].x *= damping
                        velocities[i].y *= damping
  
                    # 更新粒子位置 - 系统会自动创建关键帧
                    particles[i].pos = positions[i]
  
    print(f"粒子系统物理模拟创建完成,包含 {num_particles} 个粒子")
    return particles

# 执行动画物理模拟
collision_animation = create_collision_animation()
parabolic_trajectory_anim = create_parabolic_trajectory_animation()
circular_motion_anim = create_circular_motion_animation()
particle_system = create_particle_physics_animation()

高级数学建模案例

import pymxs
import math

rt = pymxs.runtime

# 创建数学曲面 - 双曲面
def create_hyperbolic_paraboloid():
    # 网格参数
    grid_size = 20
    total_verts = grid_size * grid_size
  
    # 双曲面方程: z = x² - y²
    scale = 0.1
  
    # 收集所有顶点位置
    maxscript_verts = rt.array()
    for i in range(grid_size):
        for j in range(grid_size):
            x = (i - grid_size/2) * 5
            y = (j - grid_size/2) * 5
  
            # 双曲面方程
            z = (x*x - y*y) * scale
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 计算面(三角形)
    maxscript_faces = rt.array()
    for i in range(grid_size - 1):
        for j in range(grid_size - 1):
            # 计算当前单元格的四个顶点索引
            v1 = i * grid_size + j + 1
            v2 = i * grid_size + j + 2
            v3 = (i + 1) * grid_size + j + 1
            v4 = (i + 1) * grid_size + j + 2
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(v1, v2, v4))
            rt.append(maxscript_faces, rt.Point3(v1, v4, v3))
  
    # 创建新的网格对象,直接传递顶点和面数据
    mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
  
    # 更新网格显示
    rt.update(mesh_obj)
    print(f"创建双曲面网格,包含 {total_verts} 个顶点和 {len(maxscript_faces)} 个面")
    return mesh_obj

# 创建数学曲面 - 环面
def create_torus_surface():
    # 环面参数
    major_radius = 50  # 主半径
    minor_radius = 15  # 次半径
    u_steps = 24  # 经度分段
    v_steps = 12  # 纬度分段
  
    total_verts = u_steps * v_steps
  
    # 收集所有顶点位置
    maxscript_verts = rt.array()
    for i in range(u_steps):
        for j in range(v_steps):
            # 参数化坐标
            u = 2 * math.pi * i / u_steps  # 经度
            v = 2 * math.pi * j / v_steps  # 纬度
  
            # 环面参数方程
            x = (major_radius + minor_radius * math.cos(v)) * math.cos(u)
            y = (major_radius + minor_radius * math.cos(v)) * math.sin(u)
            z = minor_radius * math.sin(v)
  
            rt.append(maxscript_verts, rt.Point3(x, y, z))
  
    # 收集所有面数据
    maxscript_faces = rt.array()
    for i in range(u_steps):
        for j in range(v_steps):
            # 计算当前单元格的四个顶点索引(考虑循环连接)
            v1 = i * v_steps + j + 1
            v2 = i * v_steps + ((j + 1) % v_steps) + 1
            v3 = ((i + 1) % u_steps) * v_steps + j + 1
            v4 = ((i + 1) % u_steps) * v_steps + ((j + 1) % v_steps) + 1
  
            # 创建两个三角形面
            rt.append(maxscript_faces, rt.Point3(v1, v2, v4))
            rt.append(maxscript_faces, rt.Point3(v1, v4, v3))
  
    # 创建新的网格对象,直接传递顶点和面数据
    mesh_obj = rt.mesh(vertices=maxscript_verts, faces=maxscript_faces)
  
    # 更新网格显示
    rt.update(mesh_obj)
    print(f"创建环面网格,包含 {total_verts} 个顶点和 {len(maxscript_faces)} 个面")
    return mesh_obj

# 创建数学函数驱动的动画
def create_animated_math_pattern():
    objects = []
  
    # 创建多个随时间变化的几何体
    time_steps = 30
  
    for t in range(time_steps):
        time_factor = t / time_steps
  
        # 使用正弦函数创建波动效果
        wave_amplitude = 30 * math.sin(time_factor * 2 * math.pi)
  
        # 创建球体
        sphere = rt.Sphere(radius=8)
  
        # 设置位置(随时间变化)
        x = t * 15
        y = wave_amplitude
        z = 0
  
        sphere.pos = rt.Point3(x, y, z)
  
        # 设置颜色(随时间变化)
        red = int(128 + 127 * math.sin(time_factor * math.pi))
        green = int(128 + 127 * math.sin(time_factor * math.pi + 2 * math.pi / 3))
        blue = int(128 + 127 * math.sin(time_factor * math.pi + 4 * math.pi / 3))
  
        sphere.wirecolor = rt.Color(red, green, blue)
        objects.append(sphere)
  
    print(f"创建数学驱动的动画模式,包含 {len(objects)} 个几何体")
    return objects

# 执行高级数学建模
hyperbolic_surface = create_hyperbolic_paraboloid()
torus_surface = create_torus_surface()
animated_pattern = create_animated_math_pattern()

概率与统计应用

import pymxs
import math
import random

rt = pymxs.runtime

# 正态分布点云生成
def create_normal_distribution():
    objects = []
  
    # 正态分布参数
    mean_x, mean_y, mean_z = 0, 0, 0  # 均值
    std_dev = 20  # 标准差
    num_points = 100  # 点数
  
    for i in range(num_points):
        # 使用Box-Muller变换生成正态分布随机数
        u1 = random.random()
        u2 = random.random()
  
        # 生成标准正态分布随机数
        z0 = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
        z1 = math.sqrt(-2 * math.log(u1)) * math.sin(2 * math.pi * u2)
  
        # 转换为指定均值和标准差
        x = mean_x + z0 * std_dev
        y = mean_y + z1 * std_dev
        z = mean_z + random.gauss(0, std_dev/2)
  
        # 创建点
        sphere = rt.Sphere(radius=2)
        sphere.pos = rt.Point3(x, y, z)
  
        # 根据密度设置颜色
        density = math.exp(-(x*x + y*y + z*z) / (2 * std_dev*std_dev))
        intensity = int(255 * density)
        sphere.wirecolor = rt.Color(intensity, intensity, 200)
        objects.append(sphere)
  
    print(f"使用正态分布创建了 {len(objects)} 个点")
    return objects

# 泊松分布点生成(使用标准库实现)
def create_poisson_distribution():
    objects = []
  
    # 泊松分布参数
    lambda_param = 5  # 泊松参数
    area_size = 200  # 区域大小
    num_clusters = 10  # 聚类数量
  
    # 手动实现泊松分布生成器
    def generate_poisson(lam):
        """使用Knuth算法生成泊松分布随机数"""
        L = math.exp(-lam)
        k = 0
        p = 1.0
  
        while p > L:
            k += 1
            p *= random.random()
  
        return k - 1
  
    for cluster in range(num_clusters):
        # 随机选择聚类中心
        center_x = random.uniform(-area_size/2, area_size/2)
        center_y = random.uniform(-area_size/2, area_size/2)
        center_z = 0
  
        # 生成泊松分布的点数
        k = generate_poisson(lambda_param)
  
        for i in range(k):
            # 在聚类中心周围随机分布
            angle = random.uniform(0, 2 * math.pi)
            distance = random.expovariate(1.0) * 10
  
            x = center_x + distance * math.cos(angle)
            y = center_y + distance * math.sin(angle)
            z = center_z
  
            sphere = rt.Sphere(radius=3)
            sphere.pos = rt.Point3(x, y, z)
  
            # 根据聚类设置颜色
            hue = cluster * 36  # 每个聚类不同色调
            # 使用HSV到RGB的转换(简化版)
            h = hue / 360.0
            r = int(255 * (1 - abs((h * 6) % 2 - 1)))
            g = int(255 * (1 - abs((h * 6 + 4) % 2 - 1)))
            b = int(255 * (1 - abs((h * 6 + 2) % 2 - 1)))
            sphere.wirecolor = rt.Color(r, g, b)
            objects.append(sphere)
  
    print(f"使用泊松分布创建了 {len(objects)} 个聚类点")
    return objects

# 执行概率统计应用
normal_points = create_normal_distribution()
poisson_clusters = create_poisson_distribution()

应用场景:

  • 几何图案生成
  • 动画路径计算
  • 随机分布建模
  • 分形几何创建
  • 参数化曲面设计
  • 物理模拟基础
  • 几何变换与矩阵运算
  • 物理运动学模拟
  • 高级数学曲面建模
  • 概率统计分布生成

返回目录 ↑


文档更新记录

版本历史

2026-01-16

  • 添加坐标系设置相关内容
  • 详细说明 rt.coordsys 属性的正确使用方法
  • 提供坐标系转换的实用函数和示例
  • 修正常见的坐标系设置错误

2026-01-13

  • 添加真实的 MAXScript 函数使用案例
  • 添加函数存在性验证方法
  • 修复文档排版结构问题

2026-01-05

  • 创建完整的 pymxs 参考手册
  • 整合所有现有文档内容
  • 涵盖模块概述、API 参考、实用示例和最佳实践
  • 去除重复内容,优化文档结构

文档特性

  • ✅ 完整覆盖: 涵盖 pymxs 模块所有核心功能
  • ✅ 实用示例: 提供可直接使用的代码示例
  • ✅ 最佳实践: 包含性能优化和错误处理建议
  • ✅ 版本兼容: 适配不同版本的 3ds Max
  • ✅ 中文文档: 提供完整的中文参考手册

快速参考索引

核心函数

  • pymxs.runtime - MAXScript 运行时访问
  • pymxs.animate() - 动画记录控制
  • pymxs.attime() - 时间上下文设置
  • pymxs.atlevel() - 层级上下文设置
  • pymxs.byref() - 引用参数处理(推荐使用)

实用工具

  • 场景管理工具
  • 动画工具
  • 材质和渲染工具
  • 性能优化工具
  • 错误处理模式

开发技巧

  • 函数存在性验证
  • 多线程安全访问
  • 与其他模块集成
  • 调试和性能分析