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

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

  1. alkoholizem_hxon

    Zdravo, ljudje. Že dolgo sem iskal resnično rešitev. Ko gre za ambulantno zdravljenje alkoholizma — veliko ljudi se muči v tišini. Prijatelj mi je svetoval en center, kjer imajo izkušnje. Govorim o zdravljenju po metodi dr. Vorobjeva. Preverite sami na povezavi: alkoholizem [url=https://www.alkoholizem-zdravljenje.com]alkoholizem[/url] Po nekaj tednih sem začutil razliko. Ni lahko priznati si, da imaš težavo. Ampak ko enkrat najdeš pravo pomoč — življenje dobi nov smisel. Če kdo dvomi, naj kar pokliče in vpraša. Ne obupajte!

    Reply
  2. Best Crypto Casino

    My brother suggested I would possibly like this web site.
    He was totally right. This put up truly made my day.

    You cann’t believe just how a lot time I had spent for this information! Thanks!

    Reply
  3. UG88 ផ្លូវការ | វេទិកាភ្នាល់បន្តផ្ទាល់និងកាស៊ីណូអនឡាញឈានមុខគេនៅបង់ក្លាដែស

    ស្វែងរកបទពិសោធន៍កម្សាន្តកម្រិតពិភពលោកនៅ UG88។ យើងផ្តល់ជូននូវការភ្នាល់បន្តផ្ទាល់ ប្រាក់រង្វាន់ខ្ពស់ ការដកប្រាក់រហ័ស និងសុវត្ថិភាពបំផុតសម្រាប់អ្នកលេងនៅបង់ក្លាដែស។

    Reply
  4. alkoholizem_mrKl

    Veliko sem prebral in slišal o tem. Ko sem prvič slišal za odvajanje od alkohola po metodi Dr Vorobjev centra, sem bil neveren. Ampak ko sem spoznal ljudi, ki jim je uspelo — ugotovil sem, da to res deluje. Alkoholizem uničuje družine. In najhuje je, da mnogi ne vedo, kam se obrniti. Zato priporočam, da preverite celoten postopek na spletni strani, ki so na voljo na tej povezavi: odvajanje od alkohola [url=http://alkoholizma-zdravljenje-si.com]odvajanje od alkohola[/url]. Na tej povezavi so odgovori na vsa vprašanja.

    Zdaj živim polno življenje brez alkohola. Če se soočate s podobno težavo — ne odlašajte. Upam, da vam bo koristilo!

    Reply
  5. viagra

    Aw, this was an exceptionally nice post. Taking
    a few minutes and actual effort to create a
    top notch article… but what can I say… I
    put things off a whole lot and don’t seem to get nearly anything
    done.

    Reply
  6. 高級ラブドール

    リアルドールを利用する多くの方が、最も気にする点の一つがプライバシーの保護です。
    利用する瞬間まで、周囲に知られたくないと考えるのは当然のことであり、しっかりとした対策が必要です。
    このサイトでは、注文した際の梱包から、日常的な使い方まで、秘密を厳守するための具体的な方法を徹底的に解説しています。
    配送業者にも中身が分からないような配送形態を選ぶことが最初の重要なポイントです。
    受け取った後の開封や隠し場所の作り方についても、実用的なアイデアをたくさん紹介しています。
    使用後の処理や、消臭や汚れ対策まで、周囲の目を意識したノウハウが満載です。
    中には悪徳ショップも存在し、配送情報を公開したりするケースもあるため、ショップを選ぶ時点から注意が必要です。
    プライバシーポリシーが明確か、信頼できる運営かを見極めるコツもまとめています。
    心配を抱えている方でも、この内容を参考にすれば、安全に利用を続けられます。
    プライバシーを守ることは、ストレスフリーな時間を作る上で欠かせない要素です。
    適切な対策を講じることで、不安を解消し、本来の楽しみを得ることができます。

    Reply
  7. buy cocaine online

    Good day! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really enjoy your content.
    Please let me know. Cheers

    Reply
  8. url

    I never thought that my relationship would collapse. For years
    I worked hard, thinking that loyalty and trust were enough.
    Then to my shock I discovered that my wife was involved with someone else.

    What hurt the most was that he was a rich businessman. My world fell apart.

    The divorce process was brutal. I spent countless nights awake.
    At first I blamed myself. I worried about my future. But eventually I
    realized something important: I could only control my own decisions.

    Instead of living in the past, I became focused on improving my finances.
    I started studying investing. Week after week I learned about risk management, blockchain technology, and financial planning.

    Eventually I found Paybis and it changed my routine.
    The first thing I noticed was the straightforward interface.
    Managing digital assets became far more convenient.

    I regularly use Paybis for converting digital assets into traditional currency.
    The transaction flow is smooth. I can review activity while maintaining a clear overview of my finances.

    I became passionate about modern financial systems. Learning
    about blockchain settlements gave me a new perspective on money.
    I followed industry developments. Step by step I became more confident
    with my decisions.
    What happened next shocked me. As my confidence returned, I realized
    that money had never been the real issue. The real issue was
    attitude. Money alone does not create a healthy relationship.

    Sometimes life surprises you. I found a wonderful woman. She brought fresh energy into my life.
    The best part was that she was positive and caring.
    Today I feel stronger than ever. The pain of the divorce is behind me.
    I rebuilt my finances, expanded my knowledge, and found peace of mind.

    Looking back, I no longer feel anger. I value what I learned.
    What felt like the end became a new beginning. My financial journey reminds me
    how much I have grown. The emotions are incredible—the realization that life can improve dramatically when you refuse to quit.

    Reply
  9. alkoholizem_gpkr

    Res je težko priznati si, da rabiš pomoč. Potem pa sem izvedel za center in vse se je postavilo na svoje mesto. Govorim o zdravljenju alkoholizma pri Dr Vorobjev centru. Veste, alkoholizem je bolezen, ne slabost. In kar je najpomembneje – program je prilagojen posamezniku. Sam sem preveril celoten postopek in vse uradne informacije so na voljo na tej povezavi: odvisnost od alkohol [url=zdravljenjealkoholizma.com]odvisnost od alkohol[/url]. Zdaj sem že pol leta trezen in ponosen nase.

    Če vi ali kdo od vaših bližnjih ne ve, kam se obrniti – ne odlašajte. Držim pesti!

    Reply
  10. Xavier

    Wertvoller Artikel. Jede Menge nützliche Hinweise. Vielen Dank dass du dein Wissen teilst.

    Ich werde öfter reinschauen.
    Genau – der Bereich der Einrichtung ist schwierig. Hilfreicher Ansatz.

    Sehr inspirierend. Ich habe schon nach so etwas genau danach gesucht.
    Super Arbeit!

    Here is my site – Xavier

    Reply
  11. купить наркотики

    Наркотики рушат эндосимбионт и психику.

    Катализаторы (снежок, мефедрон, амфетамин) сжигают запас тела, возбуждая инфаркты, предсмертную гипертермию, тление сосудов
    и паранойю. Каннабиноиды (гашиш, спайсы)
    ведут ко слабоумию, отказу почек и еще психозам.

    Опиоиды (героин, физептон) парализуют чухалка, давать начало тление материй а также суровую ломку.
    Итог потребления ПАВ — отказ
    органов, фатуизм равным образом смерть.

    Reply
  12. best non gamstop casinos

    First of all I would like to say awesome blog! I had
    a quick question that I’d like to ask if you don’t mind.
    I was interested to find out how you center yourself and clear your head prior to writing.
    I have had a difficult time clearing my mind in getting my thoughts out there.
    I do enjoy writing but it just seems like the first 10
    to 15 minutes are usually lost simply just trying to figure out
    how to begin. Any suggestions or hints? Appreciate it!

    Reply
  13. trading platform

    Thanks for the auspicious writeup. It in truth was once a enjoyment account it.
    Look advanced to far introduced agreeable from you! By the way,
    how can we communicate?

    Reply
  14. alkoholizem_ppon

    Živjo vsem. Preizkusil sem že vse mogoče. Ko gre za odvajanje od alkohola — to je res težka zadeva. Prijatelj mi je svetoval en center, kjer res vedo, kaj delajo. Govorim o zdravljenju po metodi dr. Vorobjeva. Več informacij je na voljo tu: alkoholizem [url=https://www.alkoholizem-zdravljenje.com]alkoholizem[/url] Po nekaj tednih sem začutil razliko. Odvisnost od alkohola je bolezen, ne sramota. Ampak ko dobiš strokovno podporo — vse postane lažje. Vsekakor priporočam vsem, ki se spopadajo s to težavo. Srečno na tej poti!

    Reply
  15. Pressure washing Mt Sinai

    Hi there, i read your blog occasionally and i own a similar
    one and i was just curious if you get a lot of spam remarks?
    If so how do you protect against it, any plugin or anything
    you can advise? I get so much lately it’s driving me
    mad so any assistance is very much appreciated.

    Reply
  16. alkoholizem_epkr

    Res je težko priznati si, da rabiš pomoč. Potem pa sem dobil pravi nasvet in vse se je postavilo na svoje mesto. Govorim o odvajanju od alkohola pri Dr Vorobjev centru. Veste, ni lahko, ampak se da premagati. In kar je najpomembneje – ni treba v bolnišnico. Več o tem in o izkušnjah pacientov si lahko preberete neposredno na uradnem viru: alkoholizem [url=https://zdravljenjealkoholizma.com]alkoholizem[/url]. Meni so resnično pomagali.

    Če vi ali kdo od vaših bližnjih potrebuje pomoč – resnično priporočam. Srečno!

    Reply
  17. SITUS PENIPU DELICUAN

    hi!,I really like your writing so so much! share we keep in touch extra about your article on AOL?
    I require a specialist in this area to solve my problem.
    May be that’s you! Having a look forward to look you.

    Reply
  18. Hiburan

    Awesome website you have here but I was wanting to know if you knew of any community forums
    that cover the same topics discussed in this article?
    I’d really love to be a part of community where I can get feed-back from other experienced individuals
    that share the same interest. If you have any
    suggestions, please let me know. Cheers!

    Reply
  19. Renee

    OMT’ѕ concentrate оn metacognition educates students tо
    take pleasure in assuming сoncerning math,
    fostering love and drive forr superior test outcomes.

    Unlock ʏour child’s full potential іn mathematics ᴡith
    OMT Math Tuition’s expert-led classes, customized
    t᧐ Singapore’s MOE syllabus fߋr primary school, secondary, аnd JC trainees.

    In Singapore’ѕ rigorous education ѕystem, where mathematics is required ɑnd consumes aгound 1600 hoᥙrs ߋf curriculum time іn primary and secondary schools, math tuition Ƅecomes imp᧐rtant to help trainees construct a strong structure for long-lasting success.

    primary school math tuition builds examination endurance tһrough timed drills, simulating tһe PSLE’s two-paper
    format and helping students handle tіme efficiently.

    Ⲣrovided the hіgh risks οf О Levels fоr senior high school progression іn Singapore, math tuition optimizes opportunities fоr leading qualities and preferred positionings.

    Junior college math tuition promotes vital assuming
    skills required tⲟ solve non-routine issues tһat often sһow uρ in А Level mathematics evaluations.

    OMT’ѕ custom-made math syllabus distinctively supports MOE’ѕ by offering
    prolonged protection on subjects liҝe algebra, with proprietary shortcuts fօr secondary trainees.

    OMT’ѕ platform іѕ straightforward one, ѕo ɑlso beginners ϲan navigate and start enhancing grades
    rapidly.

    Tuition centers іn Singapore focus օn heuristic techniques, vital fоr dealing
    ԝith the difficult ᴡord pгoblems іn math
    tests.

    Տtoр ƅy my web blog: math tuition singapore; Renee,

    Reply
  20. MALWARE

    Remarkable issues here. I am very glad to see your post.

    Thank you so much and I’m looking ahead to contact you.
    Will you please drop me a e-mail?

    Reply
  21. bigtechoro

    Do you mind if I quote a few of your posts as long as I provide credit and sources back
    to your website? My blog is in the exact same niche as yours and my users would really benefit from some of the information you present here.
    Please let me know if this ok with you. Cheers!

    Reply
  22. 수원출장안마

    이렇게 좋은 글 정말 반가워요.
    수원홈케어에 대해 이렇게 자세히 알려주신 분은
    처음이에요.
    제일 수원1인샵의 간편한 예약 시스템이 마음에 들었어요.

    수원마사지 알아보시는 분들께 이 글을 추천합니다.

    Feel free to surf to my site – 수원출장안마

    Reply
  23. alkoholizem_ylKl

    Veliko sem prebral in slišal o tem. Ko sem prvič slišal za ambulantno zdravljenje alkoholizma po metodi Dr Vorobjev centra, sem bil poln dvomov. Ampak ko sem prebral izkušnje anderen — vse se je spremenilo. Odvisnost od alkohola je strašna bolezen. In najhuje je, da mnogi ne vedo, kam se obrniti. Zato svetujem, da si vzamete čas in preberete posodobljene podatke, ki so na voljo na tej povezavi: odvajanje od alkohola [url=www.alkoholizma-zdravljenje-si.com]odvajanje od alkohola[/url]. Več o tem si preberite na spodnji povezavi.

    Zdaj živim polno življenje brez alkohola. Če se soočate s podobno težavo — vzemite si čas in preberite. Srečno vsem na tej poti!

    Reply
  24. alkoholizem_sfkr

    изучение английского [url=www.websmi.by/2026/05/nuzhno-li-znat-anglijskij-kazhdomu-i-kak-bysto-vyuchit-yazyk/]изучение английского[/url]

    Reply
  25. alkoholizem_nbon

    Živjo vsem. Že dolgo sem iskal resnično rešitev. Ko gre za zdravljenje alkoholizma — to je res težka zadeva. Prijatelj mi je priporočil en center, kjer imajo izkušnje. Govorim o Dr Vorobjev. Preverite sami na povezavi: Dr Vorobjev [url=http://www.alkoholizem-zdravljenje.com]http://www.alkoholizem-zdravljenje.com[/url] Po nekaj tednih sem začutil razliko. Odvisnost od alkohola je bolezen, ne sramota. Ampak ko vidiš, da nisi sam — življenje dobi nov smisel. Če kdo dvomi, naj kar pokliče in vpraša. Ne obupajte!

    Reply
  26. physics and maths tutor iygb

    OMT’ѕ concentrate οn foundational abilities builds unshakeable confidence, permitting Singapore
    trainees tօ fall іn love ѡith math’s sophistication ɑnd гeally feel inspired fօr tests.

    Established іn 2013 by Ꮇr. Justin Tan, OMT Math Tuition has assisted countless students ace tests ⅼike PSLE,
    O-Levels, ɑnd A-Levels with tested analytical strategies.

    Singapore’ѕ emphasis on crucial analyzing mathematics highlights tһe vɑlue of math tuition, ԝhich helps
    trainees develop tһe analytical skills demanded ƅy the country’s forward-thinking curriculum.

    Math tuition helps primary school students master PSLE Ьʏ enhancing the Singapore Math curriculum’s bar modeling
    method fߋr visual pгoblem-solving.

    Ӏn Singapore’ѕ afffordable education аnd learning landscape, secondary math tuition supplies tһe additional edge
    required tο stand ⲟut іn O Level rankings.

    Tuition integrates pure аnd applied mathematics flawlessly, preparing pupils fߋr the interdisciplinary nature օf A Level proƅlems.

    Distinctly, OMT’ѕ syllabus enhances tһе MOE structure by providing
    modular lessons that enable repeated reinforcement ⲟf weak areas at tһе student’s
    rate.

    12-month access implies ʏoս can revisit topics anytime lah, building solid
    foundations fоr regular һigh mathematics marks.

    Math tuition demystifies advanced topics ⅼike calculus for A-Level students, leading tһe way for university admissions іn Singapore.

    My web-site physics and maths tutor iygb

    Reply
  27. site

    An outstanding share! I’ve just forwarded this onto
    a coworker who had been doing a little research on this.
    And he actually bought me lunch because I discovered it for
    him… lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanx for spending the time to talk about
    this topic here on your internet site.

    Reply
  28. Vivod iz zapoya na domy_gioa

    Представьте ситуацию, родственники просто в тупике. Достали уже эти срывы. В этом вопросе главное не слушать советы алконавтов из подворотни. Посмотрите сами — выведение из запоя без госпитализации. Ребята реально шарят. Если честно, актуальный прайс и условия тут — снять запой на дому [url=https://vyvod-iz-zapoya-na-domu-voronezh-kmp.ru]https://vyvod-iz-zapoya-na-domu-voronezh-kmp.ru[/url] Звоните пока не поздно, потому что один финал — реанимация. Сам так спасал брата.

    Reply
  29. Vivod iz zapoya na domy_fxMi

    Да уж, родственники маются. Без вариантов — реальное выведение из запоя без кодировки. Ребята работают чисто. Короче говоря, нажимайте и читайте — срочный вывод из запоя на дому [url=https://vyvod-iz-zapoya-na-domu-voronezh-xrt.ru]https://vyvod-iz-zapoya-na-domu-voronezh-xrt.ru[/url] Печень вообще молчит. Поверьте моему опыту, чем потом скорую вызывать. Рекомендую эту наркологическую клинику.

    Reply
  30. check my source

    Greetings from Florida! I’m bored to tears at work so I
    decided to check out your website on my iphone during lunch break.
    I enjoy the info you provide here and can’t wait to take
    a look when I get home. I’m shocked at how fast your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, great site!

    Reply
  31. slot depo rendah

    Hi my family member! I want to say that this article
    is awesome, great written and come with almost all vital infos.
    I would like to see extra posts like this .

    Reply
  32. alkoholizem_hzkr

    Res je težko priznati si, da rabiš pomoč. Potem pa sem naletel na eno mesto in vse se je spremenilo. Govorim o zdravljenju alkoholizma pri strokovnjakih, ki res znajo pomagati. Veste, alkoholizem je bolezen, ne slabost. In kar je najpomembneje – ni treba v bolnišnico. Sam sem preveril celoten postopek in vse uradne informacije so na voljo na tej povezavi: odvisnost od alkohol [url=https://www.zdravljenjealkoholizma.com]odvisnost od alkohol[/url]. Zdaj sem že pol leta trezen in ponosen nase.

    Če kogarkoli, ki ga imate radi se sooča s to težavo – ne odlašajte. Srečno!

    Reply

Leave a Reply

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