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

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

  1. pornhub

    I was recommended this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble.
    You’re incredible! Thanks!

    Reply
  2. Edwinundom

    Информационный портал https://fines.com.ua для женщин, где собраны советы экспертов, модные тренды, рекомендации по здоровью, обзоры косметики, идеи для дома, рецепты, лайфхаки и материалы о саморазвитии.

    Reply
  3. CharlieVip

    Онлайн-журнал https://mirlady.kyiv.ua для женщин с актуальными статьями о моде, красоте, здоровье, семье, детях, фитнесе, правильном питании, косметике, карьере, вдохновении и современных тенденциях.

    Reply
  4. h2 math tuition

    Personalized support frοm OMT’s seasoned tutors aids trainees gеt
    օveг math hurdles, promoting ɑ genuine link tо the subject and ideas fоr tests.

    Dive intо self-paced math proficiency ᴡith OMT’s 12-month e-learning courses, total with practice worksheets аnd recorded sessions
    fоr extensive modification.

    Singapore’ѕ emphasis on crucial thinking tһrough mathematics highlights tһe vaⅼue of
    math tuition, ԝhich helps students establish tһe
    analytical abilities required ƅy tһe nation’s forward-thinking curriculum.

    primary math tuition develops test stamina tһrough timed drills, mimicking tһe PSLE’ѕ two-paper format аnd assisting
    trainees manage timе effectively.

    Normal mock О Level examinations inn tuition settings replicate genuine ρroblems, allowing
    students tto improve tһeir approach and lower mistakes.

    Customized junior college tuition assists link tһe void from O Level to A Level mathematics, ensuring pupils adapt tо the boosted rigor ɑnd depth neеded.

    OMT’s exclusive cuyrriculum boosts MOE requirements ԝith
    a holistic method tһat nurtures bⲟth academic skills and ɑn іnterest fօr mathematics.

    OMT’ѕ on the internet community offeгs support leh, where
    you can asқ questions and improve уour understanding for much
    ƅetter grades.

    Ꮃith worldwide competition rising, math tuition placements Singapore pupils аѕ
    leading entertainers іn worldwide math assessments.

    my web-site … h2 math tuition

    Reply
  5. CalvinHog

    Женский портал https://nicegirl.kyiv.ua для тех, кто ценит красоту, здоровье и комфорт. Полезные советы по уходу за собой, обзоры косметики, идеи образов, секреты гармоничных отношений, домашнего уюта и активного образа жизни.

    Reply
  6. https://x.com/nahis_al

    Very good website you have here but I was wanting to know if you knew of any forums that cover the same topics talked about here?

    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. Thanks!

    Reply
  7. toket besar

    Ahaa, its fastidious discussion on the topic of this post here at this webpage, I have read all that, so
    at this time me also commenting here.

    Reply
  8. live sex

    I’m gone to say to my little brother, that he should also go to see
    this blog on regular basis to get updated from most recent information.

    Reply
  9. bokep anak

    I am not positive where you’re getting your info, but great topic.
    I must spend a while learning much more or working out more.
    Thanks for magnificent information I used to be looking for this information for my mission.

    Reply
  10. 1xbet indir_wjPn

    Selam arkadaşlar Ama doğru uygulamayı bulmak şart En iyisini bulmak için çok zaman harcadım Sonunda en iyi uygulamayı keşfettim — 1xbet giriş indir kolay Bonuslar ve promolar her gün var Neyse, tüm detaylar linkte — 1xbet indir [url=https://1xbet-indir-mnk.com]1xbet indir[/url] Tek adres 1xbet indir Bahis yapan herkese gönder

    Reply
  11. 1xbet indir_ioKt

    Beyler bahisçiler Sürekli bilgisayar açmak zor oluyor Çoğu site mobil uygulama sunmuyor Sonunda en iyi uygulamayı buldum — 1xbet mobil uygulama apk Bonuslar ve promolar her gün var Neyse, her şey mevcut — 1xbet mobile yukle [url=https://1xbet-indir-abc.com]1xbet mobile yukle[/url] Tek adres 1xbet indir Bahis yapan herkese gönder

    Reply
  12. Garage Door Repair

    My brother recommended I may like this web site. He was once entirely right.
    This post actually made my day. You cann’t believe simply how so much time I had spent for this info!

    Thanks!

    Reply
  13. Trisha

    Good way of describing, and good paragraph to
    take information about my presentation subject,
    which i am going to convey in school.

    Reply
  14. Davidnah

    Читайте полезные https://mr.org.ua материалы о строительстве домов, ремонте квартир, выборе строительных материалов, инженерных системах, дизайне интерьера, благоустройстве участка, современных технологиях и профессиональных строительных решениях.

    Reply
  15. slot gacor

    You could definitely see your expertise within the work you write.
    The world hopes for more passionate writers like you who aren’t
    afraid to say how they believe. Always follow your heart.

    Reply
  16. Robertavalp

    Строительный портал https://smallbusiness.dp.ua с практическими рекомендациями по строительству, ремонту и отделке. Обзоры инструментов, материалов, оборудования, инженерных систем, технологии монтажа, советы специалистов и строительные лайфхаки.

    Reply
  17. MartinBob

    Все для строительства https://valkbolos.com дома и ремонта квартиры: статьи, инструкции, обзоры материалов, советы по выбору инструментов, монтажу инженерных коммуникаций, утеплению, кровельным и отделочным работам.

    Reply
  18. Michaelbeauh

    Актуальная информация https://vitamax.dp.ua о строительстве, ремонте и благоустройстве. Новости отрасли, технологии, строительные материалы, проекты домов, советы по эксплуатации зданий, инженерным решениям и организации строительных работ.

    Reply
  19. Davidtinna

    Портал о строительстве https://stroy-portal.kyiv.ua с ежедневными публикациями о современных технологиях, ремонте, проектировании, выборе материалов, строительной технике, инструментах, ландшафтном дизайне и обустройстве участка.

    Reply
  20. Adrianna

    Świetny artykuł. Mnóstwo wartościowych porad.
    Dzięki za podzielenie się. Będę zaglądać częściej.

    Zgadzam się – temat doboru mebli bywa trudna. Wreszcie konkrety.

    Naprawdę przydatne. Szukałem takich informacji
    od dawna. Dziękuję!

    Feel free to visit my website :: Adrianna

    Reply
  21. 강릉출장샵

    최근에 피로가 많이 쌓여서 힐링을 알아보고 있었어요.

    지인 소개로 이 정보를 찾고 강릉홈케어를 이용해 봤어요.

    전문가의 케어가 정말 좋았어요.
    강릉안마를 경험하고 나니 몸이 훨씬 가벼워졌어요.

    Check out my website … 강릉출장샵

    Reply
  22. โปรโมชั่น

    Hmm is anyone else encountering problems with the images on this blog loading?
    I’m trying to find out if its a problem on my end or
    if it’s the blog. Any suggestions would be greatly appreciated.

    Reply
  23. ee88

    It’s remarkable to pay a visit this website and reading the views of all mates regarding this
    piece of writing, while I am also zealous of getting knowledge.

    Reply
  24. Darmowe spiny bez depozytu 2026

    Kasyno Compensation bez Depozytu za Rejestracje to jedna
    z najbardziej popularnych billet c preserve up promocji oferowanych przez legalne platformy
    hazardowe online. Tego typu salary pozwala nowym uzytkownikom
    rozpoczac gre bez koniecznosci wplacania wlasnych srodkow na konto.
    Wystarczy zazwyczaj zalozenie konta oraz spelnienie okreslonych warunkow
    regulaminowych, aby otrzymac darmowe srodki lub darmowe obroty na
    wybranych automatach. Dla wielu graczy jest to atrakcyjna mozliwosc sprawdzenia funkcji kasyna bez ponoszenia
    dodatkowych kosztow.

    Reply
  25. ngentot

    Quality articles is the crucial to attract the viewers to pay a
    quick visit the web site, that’s what this web page is providing.

    Reply
  26. 33win

    Attractive section of content. I just stumbled upon your blog
    and in accession capital to assert that I get in fact enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement
    you access consistently quickly.

    Reply
  27. Kaizenare math tuition

    Aesthetic һelp in OMT’s educational program mɑke abstract concepts substantial, cultivating ɑ deep recognition fߋr math ɑnd
    inspiration tο dominate examinations.

    Dive іnto self-paced math proficiency ᴡith OMT’s 12-month е-learning
    courses, comρlete ѡith practice worksheets аnd recorded
    sessions for thorough modification.

    Ꮤith mathematics integrated seamlessly іnto Singapore’ѕ class settings tο benefit bߋth
    instructors аnd trainees, committed math tuition enhances tһesе gains by providing customized
    assistance fօr continual accomplishment.

    Tuition іn primary mathematics іѕ crucial fⲟr PSLE preparation, аs it
    introduces sophisticated methods fοr managing non-routine pгoblems that stump lots of prospects.

    Presenting heuristic aⲣproaches early in secondary
    tuition prepares pupils fߋr the non-routine issues tһat often appwar іn Ο Level analyses.

    Ԝith A Levels demanding effectiveness іn vectors and intricate numƄers, math tuition supplies targeted
    technique t᧐ handle thesе abstract principles effectively.

    Ԝhat sets ɑρart OMT іs its exclusive program tһаt enhances
    MOE’s through focus on moral analytical іn mathematical contexts.

    Integration wіth school reseаrch leh,making tuition ɑ smooth extension for grade improvement.

    Math tuition constructs а strong portfolio of skills, boosting Singapore students’
    resumes f᧐r scholarships based оn examination outcomes.

    Check ⲟut my webpage – Kaizenare math tuition

    Reply
  28. kudolab.Sakura.Ne.jp

    Klasse Post. Zahlreiche praktische Anregungen. Grüße für diesen Inhalt.
    Ich werde öfter reinschauen.
    Sehe ich genauso – die Frage der Raumgestaltung ist nicht
    einfach. Danke für die klare Erklärung.
    Wirklich hilfreich. Ich war schon nach solchen Informationen genau danach
    gesucht. Super Arbeit!

    my web-site … kudolab.Sakura.Ne.jp

    Reply
  29. Isexsex.Com

    Klasse Artikel. Zahlreiche nützliche Tipps. Vielen Dank für den Beitrag.
    Ich speichere mir die Seite ab.
    Du hast recht – die Sache des Wohnstils kann nicht einfach.
    Danke für die klare Erklärung.
    Aufrichtig hilfreich. Ich war schon nach so etwas lange gesucht.
    Viele Grüße!

    Review my web blog Isexsex.Com

    Reply
  30. Billymap

    Все важные события https://novosti24.com.ua Украины и мира в удобном формате. Новости бизнеса, финансов, политики, общества, транспорта, науки, медицины, культуры, спорта и других сфер с ежедневным обновлением материалов.

    Reply

Leave a Reply

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