Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠


Youtube

Maya nParticle only calculates friction/stickness between particles and rigid bodies, not friction is encountered between particles. My guess is the algorithm complexity is too high. Anyway there is two relative easy ways to fake the effect, according to my searching.

想要用一个一包糖粒堆在物体(对又是它..)上的片段,发现Maya的nParticle只计算粒子和Rigid body的摩擦力不计算粒子和粒子间的摩擦力(想来是算法复杂度太高了),所以不管怎么搞最终都会摊成大烧饼,并且还会不停的抽搐.. 查了下大概有两个相对简单的方法

1. hold particles with a invisible rigid body. 2. Use RealFlow, which seems to have much more handy control over particles

I’m not happy with either. 1 is lame. 2 too much trouble, have to get hang of another environment. If I must do scripting, I choose to learn mel.

So the algorithm is:

It’s unlikely to mess with friction as I guessed above. I tried to modify per particle mass to let them stuck in the space. Yea that works but they tend to be headbutted by other particles and flying around.. for science. Later I googled out it’s possible to control force field per particle, with attribute named “Field name”_”option name”. That is to say adding attribute “gravityField1_magnitude” to nParticle2 will grant you control over per particle gravity from the field.

On creation:

[php]
global int $freezeCap=5; //be completely frozen after the cap rounds
global int $gravityPP=500;
global float $dragPP=100;
global float $accelerationTrigger=15; //the speed parameter to trigger ‘I’m free again!", which leads to free droping.
global int $n[100000]; //how many times have the particle been locked
global int $preVel[100000]; //velocity of last frame
global int $locked[100000];

nParticleShape4.dragField1_magnitude=0;
nParticleShape4.gravityField1_magnitude=$gravityPP;

global int $init=1;
if($init==1) {
int $i;
for($i=0;$i<100000;$i++) {
$n[$i]=0;
$locked[$i]=0;
}
$init=0;
}
[/php]

Before dynamics:
[php]
int $id=nParticleShape4.particleId;
float $vel=abs(nParticleShape4.velocity);

//print("nParticleShape2.velocity "+$nParticleShape2.velocity+"\n");

if($vel>$preVel[$id]+$accelerationTrigger) {
$n[$id]=0;
nParticleShape4.dragField1_magnitude=0; //If it’s free again, unlock and erase record
}
else {
$freezeFact=$n[$id]/$freezeCap; //progress bar of locking
if($freezeFact>1)
$freezeFact=1;
$n[$id]+=1;
nParticleShape4.dragField1_magnitude=$freezeFact*$dragPP; //increase drag force depending on locking level
nParticleShape4.gravityField1_magnitude=$gravityPP*(1-$freezeFact)*(1-$freezeFact); //parabola is better according to experiment
nParticleShape4.velocity=<<0,0,0>>;
}

$preVel[$id]=nParticleShape4.velocity;
[/php]

The script is not bad to me.. adjustable parameters are handy. Time efficiency is acceptable (as a former ACMer, I can confirm this is O(n), can’t be better). 20 million particles * 100 frames cost my i7 half an hour. Not perfect but enough for bragging.
1. 弄个透明的动画的rigid body来把粒子圈起来。 2. 用RealFlow,我只用RealFlow模拟水,但是显然那它对粒子的控制比Maya厉害得多。

两个方法我都不高兴,1太不屌爆,2太麻烦,要做很多熟悉另一个环境的工作,且要写脚本,所以不如来学下mel。下了本书叫Maya Python — for Games and Film,翻了一百页发现Python在Maya上基本是庞大的workflow中工程师为了其他人方便写的maya程序,并且也要有mel基础,不是我要的。

总之,思路是:

想要计算摩擦力显然是不现实的,说过了。我先通过改质量的途径让粒子满足条件时失去质量以停在原地不受重力影响,停是能停住但是会被别的particle撞飞.. 非常科学。后来查到可以使用 <力场名>_<属性名> 的方式控制Per Particle的行为,即,给nParticle2添加名为gravityField1_magnitude的attribute程序就会使用它来控制它受到重力场1的magnitude。然后通过DragField让particle稳定。我在注释里详细说。

粒子生成时脚本:

[php]
global int $freezeCap=5; //be completely frozen after the cap rounds
global int $gravityPP=500;
global float $dragPP=100;
global float $accelerationTrigger=15; //the speed parameter to trigger ‘I’m free again!", which leads to free droping.
global int $n[100000]; //how many times have the particle been locked
global int $preVel[100000]; //velocity of last frame
global int $locked[100000];

nParticleShape4.dragField1_magnitude=0;
nParticleShape4.gravityField1_magnitude=$gravityPP;

global int $init=1;
if($init==1) {
int $i;
for($i=0;$i<100000;$i++) {
$n[$i]=0;
$locked[$i]=0;
}
$init=0;
}
[/php]

动态前的脚本:

[php]
int $id=nParticleShape4.particleId;
float $vel=abs(nParticleShape4.velocity);

//print("nParticleShape2.velocity "+$nParticleShape2.velocity+"\n");

if($vel>$preVel[$id]+$accelerationTrigger) {
$n[$id]=0;
nParticleShape4.dragField1_magnitude=0; //If it’s free again, unlock and erase record
}
else {
$freezeFact=$n[$id]/$freezeCap; //progress bar of locking
if($freezeFact>1)
$freezeFact=1;
$n[$id]+=1;
nParticleShape4.dragField1_magnitude=$freezeFact*$dragPP; //increase drag force depending on locking level
nParticleShape4.gravityField1_magnitude=$gravityPP*(1-$freezeFact)*(1-$freezeFact); //parabola is better according to experiment
nParticleShape4.velocity=<<0,0,0>>;
}

$preVel[$id]=nParticleShape4.velocity;
[/php]

个人感觉这个还不错,有很多参数可以控制,效率也还行(前ACMer表示这个就是O(n)..不能再低了),200万粒子100帧i7跑半个小时。显然不完美,蒙人没问题。

11,027 thoughts on “Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠”

  1. spookyswap

    [url=https://telegra.ph/SpookySwap-for-Sonic-Traders-Who-Need-Simple-On-Chain-Swaps-08-18]spookyswap[/url] aggregates liquidity so your swap fills at a tighter rate with less slippage

    Reply ↓
  2. best fantom dex

    no custodial risk with [url=https://cryptozoo.notion.site/SpookySwap-Verdict-Worth-It-in-10-Minutes-3c085c7503308032b2c5f2fbda6dff30]swap on fantom[/url], funds never leave your wallet until it settles

    Reply ↓
  3. swap on syncswap

    [url=https://dawudtybl493453.blogs-service.com/73829878/is-syncswap-worth-it-in-2026-the-new-way-to-use-it]syncswap[/url] is my default for routine swaps, simple ui but smart routing underneath

    Reply ↓
  4. LewisMarry

    I think this post does a great job of presenting the topic in a thoughtful and approachable way, since the wording feels clear and easygoing while still leaving enough room for readers to interpret and discuss the ideas openly.
    anal sex porn viagra pills

    Reply ↓
  5. LhaneCaw

    The way this post is organized makes the discussion much easier to understand and engage with, since the ideas are explained in a clear way and the overall tone encourages positive interaction and thoughtful participation from readers.
    anal sex porn pills buy amoxicillin

    Reply ↓
  6. abseseezer

    Explicit material are a genre of entertainment designed for mature audiences.
    This content may serve for exploring sexuality as well as for personal enjoyment.
    Yet, it is vital to tell apart among authentic experiences and staged performances.
    Responsible engagement involves acknowledging consent and choosing legal sources.
    gay anime porn

    Reply ↓
  7. DwellShift

    If you’re into Maya particle simulation and need realistic powder or granular pile effects without switching to RealFlow or relying on clunky rigid-body workarounds, this mel script is a gem. It cleverly uses per-particle drag and gravity modulation—no external plugins, no Python overhead—just clean, efficient O(n) logic that scales well (20M particles × 100 frames in ~30 min on i7). As someone who’s battled nParticle’s lack of inter-particle friction for years, I can confirm: this is one of the most practical, adjustable, and engineer-friendly solutions out there. For more real-world Maya workflow hacks, check out Asher.GG.

    Reply ↓
  8. calc.you

    Calc.you provides focused calculators for everyday plans involving dates, routines, personal goals, and shared costs. Each calculation runs locally and presents its units, assumptions, and method without requiring an account.

    calc.you

    Reply ↓
  9. адрес

    Свое дело является ключевым двигателем прогресса экономики.
    Оно создаёт новые вакансии и даёт гражданам стабильный доход.
    https://companies.rbc.ru/news/WEeL8WRI03/oleg-belaj—delovyie-printsipyi-i-zhiznennyie-tsennosti-seo-trinfiko/
    Более того, бизнес стимулирует инновации и внедрение современных технологий.
    Таким образом, бизнес делает жизнь более устойчивой и создаёт шанс для личностному росту.

    Reply ↓
  10. белай тринфико

    Коммерческая деятельность служит важным локомотивом развития экономики.
    Оно формирует дополнительные вакансии и даёт гражданам надёжный заработок.
    https://www.klerk.ru/materials/2025-06-06/650105/?srsltid=AfmBOopflDgxpe80BVSMmMIWs-mdA3-mhuB-2ck3R3VxDK_l5DqmhaWx
    Помимо этого, свое дело ускоряет инновации и разработку новых технологий.
    Таким образом, бизнес формирует жизнь намного более динамичной и создаёт путь для успеху.

    Reply ↓
  11. на странице

    Предпринимательство выступает значимым двигателем развития экономики.
    Оно открывает свежие вакансии и приносит людям стабильный заработок.
    https://1istochnik.ru/news/135326
    Помимо этого, предпринимательство поощряет прогресс и разработку новых продуктов.
    В итоге, предпринимательство формирует экономику намного более устойчивой и открывает шанс к самореализации.

    Reply ↓
  12. сайт

    Свое дело служит значимым двигателем прогресса экономики.
    Свое дело открывает дополнительные рабочие позиции и приносит населению стабильный заработную плату.
    белай олег викторович
    Кроме того, свое дело стимулирует нововведения и появление передовых продуктов.
    В итоге, предпринимательство делает экономику намного более динамичной и даёт путь к самореализации.

    Reply ↓
  13. Songspot

    The per-particle field name trick is clever, and the O(n) breakdown makes the 20-million-particle benchmark believable. I like that you rejected the invisible rigid body and RealFlow routes instead of just listing them. The drag/gravity parabola for freezing is a neat hack. Curious how it handles sudden collisions once particles unfreeze. On a related note, recognition-based challenges like the songspot music quiz show how timing and staged reveals can make simple mechanics feel engaging.

    Reply ↓
  14. MobCash

    El juego consciente representa un conjunto de principios mediante el cual tiene como objetivo preservar el equilibrio en las apuestas y evitar las consecuencias negativas asociados con esta actividad.
    Requiere definir restricciones de tiempo previo a empezar a jugar, y también identificar los indicios que indican una conducta problemática.
    https://www.apkfiles.com/apk-622658/descargar-mobcash-apk-oficial-gesti-n-de-caja-m-vi
    Igualmente, promueve elecciones responsables y procura que la la diversión continúe siendo el objetivo esencial al el juego.
    En resumen, el juego responsable facilita a las personas a preservar la rienda suelta de su comportamiento y a vivir la experiencia de forma saludable.

    Reply ↓
  15. Infographics ai

    Great script for achieving realistic powder pile effects in Maya—very clever use of per-particle drag and gravity modulation! If you’re looking to visualize particle-based data (like simulation results or material distributions) as clean, shareable infographics without manual rendering, check out Genaraera: an AI-powered tool that turns raw numbers into stunning infographics in seconds. Perfect for technical artists and VFX teams who need to communicate complex simulations clearly. Try it here

    Reply ↓
  16. Roth IRA Calculator

    Great breakdown of a clever per-particle drag & gravity modulation technique in Maya nParticle—much more elegant than invisible rigid bodies or switching to RealFlow! As a TD who’s battled powder pile instability for years, this mel-based solution is refreshingly practical and scalable. If you’re looking for a no-plugin, script-driven way to simulate realistic granular stacking (sand, sugar, dust), this is gold. For those wanting an even faster workflow—including eligibility checks, growth projections, and Roth vs. Traditional IRA comparisons—I highly recommend checking out this free, browser-based tool: Roth IRA Calculator.

    Reply ↓

Leave a Reply

Your email address will not be published. Required fields are marked *