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跑半个小时。显然不完美,蒙人没问题。

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

  1. comment-136475

    Hi, i think that i saw you visited my blog thus i
    came to “return the favor”.I am attempting to find things
    to improve my website!I suppose its ok to use some of
    your ideas!!

    Reply
  2. regenerative cell therapy for knees

    First of all I would like to say superb blog! I had a quick question in which I’d like to ask if you don’t mind.
    I was interested to know how you center yourself and clear your head prior to writing.
    I’ve had difficulty clearing my mind in getting my ideas out.
    I truly do take pleasure in writing however it just seems like the first 10 to
    15 minutes are wasted simply just trying to figure out how
    to begin. Any ideas or tips? Cheers!

    Reply
  3. 김포마사지

    원래 홈케어에 고민하고 있었는데,

    이 포스팅 덕분에 김포출장마사지를 이용해 보기로 했어요.

    경험해 보니 완전 만족했어요.
    김포안마가 이렇게 편리한 줄 몰랐네요.

    자주 이용할 것 같아요.

    Here is my website; 김포마사지

    Reply
  4. Narkolog na dom_baPl

    Привет из столицы Близкий человек снова сорвался Мать на грани Домашние методы бесполезны Короче, помог только этот врач — нарколог на дом срочно Через пару часов человек пришёл в себя В общем, жмите чтобы сохранить — вызов наркологической помощи на дом [url=https://narkolog-na-dom-moskva-kjl.ru]вызов наркологической помощи на дом[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

    Reply
  5. mrcheck-1c.ru

    Промокод 1xBet — выгодное решение использовать дополнительные средства при регистрации.

    Скопируйте и вставьте промокод 1xbet в форме регистрации
    и активируйте больше средств на счёте сразу после регистрации.

    Букмекер 1xBet обеспечивает пользователям одни из лучших условий на рынке.
    Код активации распространяется только для новых аккаунтов.
    Важно применить код до завершения регистрации — акция не активируется.

    После активации появится на счёте увеличенный баланс
    согласно условиям акции. Компания также предлагает кэшбэк
    — код делает выгоднее ваши возможности.

    Используйте промокод 1xbet сегодня и начните с дополнительными средствами
    на платформе 1xBet. Создание аккаунта требует минимум времени — а бонус
    поможет в игре.

    Reply
  6. true fortune casino_himt

    true fortune casino [url=https://graph.org/Payment-Methods-at-True-Fortune-Casino-in-2026-Fees-Speed-and-What-UK-Players-Should-Actually-Choose-07-05-3]true fortune casino[/url]
    The site combines a varied game library with regular promotions and multiple payment options.

    Many games can be tried in demo mode before playing for real money.

    Regular players can benefit from reload bonuses, cashback and tournaments.

    Withdrawal times depend on the chosen method and any verification checks.

    As with any casino, players should gamble responsibly and set personal limits.

    Reply
  7. sec 3 na math paper

    Connecting modules іn OMT’ѕ curriculum simplicity transitions
    іn between levels, supporting continuous love fоr math аnd examination confidence.

    Join ᧐ur smaⅼl-grоup on-site classes in Singapore fߋr customized
    assistance іn a nurturing environment tһɑt constructs strong foundational mathematics abilities.

    Ƭhe holistic Singapore Math technique, ᴡhich builds multilayered analytical capabilities, highlights ᴡhy math tuition іѕ vital fοr mastering tһe curriculum ɑnd ցetting ready fоr
    future careers.

    Math tuition іn primary school bridges gaps іn classroom knowing, mɑking sսre trainees grasp complicated topics
    sսch aѕ geometry and іnformation analysis befߋre thе PSLE.

    ProvideԀ the high risks of Ⲟ Levels for senior hiցh school progression іn Singapore, math tuition optimizes chances fߋr
    top qualities and preferred positionings.

    In ɑn affordable Singaporean education ѕystem, junior college math tuition ρrovides pupils tһе edge to
    achieve hіgh qualities neеded fоr university admissions.

    OMT’ѕ proprietary math program matches MOE requirements Ьʏ stressing conceptual proficiency οvеr rote knowing, leading t᧐ much deeper long-term retention.

    Bite-sized lessons mɑke it simple to suit leh, brіng aƄout
    regular practice and muсһ better totaⅼ qualities.

    Singapore’s emphasis ᧐n analytical in math exams mɑkes tuition vital for creating
    vital believing skills Ьeyond school һourѕ.

    My homepage; sec 3 na math paper

    Reply
  8. Onewave solar water heater

    hi!,I love your writing so a lot! percentage we
    communicate extra about your article on AOL? I need a
    specialist in this space to unravel my problem. Maybe that’s you!

    Taking a look forward to peer you.

    Reply
  9. true fortune casino_gzmt

    true fortune casino [url=https://te.legra.ph/True-Fortune-Casino-Cryptocurrency-Deposits-in-2026-The-UK-Players-Practical-Guide-07-05-2]true fortune casino[/url]
    The casino focuses on ease of use, offering quick access to games and cashier from one account.

    The platform also includes live dealer tables for a more immersive experience.

    Signing up can unlock a welcome package designed to boost the starting balance.

    True Fortune Casino supports a range of payment methods for deposits and withdrawals.

    A help team can be reached for questions about accounts, bonuses and payments.

    Reply
  10. Narkolog na dom_azKa

    Привет из Москвы Жесть полная Соседи звонят в полицию Никакие таблетки не помогают Короче, помог только этот врач — вызов нарколога на дом недорого Через пару часов человек пришёл в себя В общем, вся инфа по ссылке — вывести из запоя на дому анонимно [url=https://narkolog-na-dom-moskva-qwe.ru]https://narkolog-na-dom-moskva-qwe.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

    Reply
  11. Best Crypto Casino

    What i do not understood is if truth be told how you are no
    longer really a lot more smartly-appreciated than you might be now.
    You’re very intelligent. You know thus significantly in the case
    of this topic, produced me individually imagine
    it from numerous various angles. Its like men and women are not interested until it’s one thing to do with Girl
    gaga! Your individual stuffs outstanding. At all times care for it up!

    Reply
  12. true fortune casino_hfmt

    true fortune casino [url=https://graph.org/Online-Casino-UK-in-2026-The-Rules-Changed-Here-Is-What-Matters-06-30]true fortune casino[/url]
    The casino focuses on ease of use, offering quick access to games and cashier from one account.

    A free-play option lets players sample games without any financial risk.

    New players are typically welcomed with a deposit bonus and, in some cases, free spins.

    Secure logins and data protection are standard across the platform.

    The casino is optimised for mobile play on both smartphones and tablets.

    Reply
  13. Tuhost Cloud

    El mejor servicio de hosting web en México y Latinoamérica. Ofrecemos hosting para WordPress, hosting compartido, hosting para empresas y PYMES, hosting profesional, servidores
    VPS, registro de dominios, certificados SSL, correo empresarial y constructor de
    páginas web con Inteligencia Artificial (IA).
    Obtén el rendimiento, la velocidad y la seguridad que tu sitio web necesita para crecer.

    Reply
  14. Narkolog na dom_ofkn

    Доброго вечера, земляки Муж просто потерял себя Дети в страхе Нужен специалист прямо сейчас Короче, нарколог приехал за час — наркологическая служба на дом профессионально Осмотрел и поставил капельницу В общем, жмите чтобы сохранить — консультация нарколога на дому [url=https://narkolog-na-dom-moskva-rty.ru]консультация нарколога на дому[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

    Reply
  15. muB

    Разумное отношение к азарту — это принцип к азартным сессиям, основанный на самоограничении и осознании последствий.
    Она подразумевает добровольное лимитирование продолжительности и бюджета на игру.
    Каждый участник должен заранее определять пределы ставок и неукоснительно их придерживаться.
    https://souzmultdesign.ru/culture/1327-responsible-gambling-tools-and-resources-for-players.html

    Reply

Leave a Reply

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