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

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

  1. Yoga Pigeon Pose

    Hey there just wanted to give you a brief heads up and let
    you know a few of the images aren’t loading correctly.
    I’m not sure why but I think its a linking
    issue. I’ve tried it in two different web browsers
    and both show the same outcome.

    Reply
  2. Paito HK

    I’m curious to find out what blog platform you’re working with?
    I’m experiencing some small security problems with my latest site and I’d
    like to find something more safe. Do you have any solutions?

    Reply
  3. kraken crypto

    Откройте новые горизонты в нашей платформе.

    Мы предоставляем высокое качество
    для успешного завершения задач по kraken crypto

    Reply
  4. SITUS GK MAMPU BAYAR WD

    Magnificent beat ! I wish to apprentice even as you amend your
    website, how can i subscribe for a blog website?
    The account helped me a applicable deal. I had been tiny bit acquainted of this your
    broadcast provided vivid transparent idea

    Reply
  5. (URL)

    I’m Mike, a normal American guy, and during 2018 I accidentally discovered one of the
    weirdest sports on Earth: car jitsu.

    If you have never heard of it, you are not alone. The entire concept sounds like a comedy
    sketch. Two athletes climb inside a small car and try to grapple each other while being trapped between the seats.
    Yes, really. In most sports you have a field, but in CarJitsu your battlefield is the inside of a vehicle.

    That is what makes it so weird.

    The sport has tournaments, championships, local events,
    and exhibition matches. Competitors come from different places and try to prove who
    can adapt best to the strange environment. Unlike traditional
    combat sports, every movement is limited by the tight space.
    That creates hilarious moments. One second someone looks like a champion, and the next second they are stuck between the
    seats.

    At that time I was heavily interested in sports. I watched all kinds of competitions.
    I also spent time reading about sports betting. Many sports fans I knew compared
    sportsbook offers. Sometimes names like 1xbet would appear in conversations about major sporting events, although CarJitsu was usually too strange to be the main topic.

    Late one evening I saw a short video online. Initially I believed it was a joke.
    Grown adults were trying to grapple inside a parked car while spectators were laughing, cheering, and recording videos.
    I laughed so hard that coffee nearly came out of my nose.
    Yet the more I watched, the more fascinated I became.

    Soon after that, I found a local event and decided to watch in person. The
    crowd energy was amazing. There were fans discussing athletic techniques and sports culture.

    Some people even joked about which athlete would be the favorite if a sports betting market ever offered odds on the matches.

    Watching was not enough. I signed up for beginner
    training. My first session was a disaster. I hit my head on the roof, got
    stuck near a seat, and accidentally opened a door at the worst possible moment.
    Even I laughed at myself. Yet I kept coming back.

    As time passed, I improved. I learned how to use smart
    tactics instead of brute strength. The car stopped feeling tiny.
    Soon I was entering small tournaments. My friends thought I was completely crazy.
    Whenever someone asked what sport I practiced, the conversation usually went like this:

    “CarJitsu.”

    “What is that?”

    “Imagine wrestling inside a car.”

    “You’re joking.”

    “No, that’s the actual sport.”

    The most unforgettable competition happened at a
    major event. My opponent was built like a truck.
    He looked like he could bench-press a refrigerator.
    Before the match started, he smiled and said, “You’re going to need luck.” That should have been a warning.

    As soon as the fight started, chaos exploded.

    We bounced between seats, bumped into doors, and
    nearly tangled ourselves in everything inside the
    vehicle. The crowd was roaring. Everyone was losing their minds.

    Then came the moment I will never forget.

    My opponent grabbed the belt hanging beside the seat and accidentally turned it
    into what looked like a wild whip. As we struggled for position, the belt snapped across
    the cabin and wrapped around me in the strangest way imaginable.
    For a second I thought, “I can’t believe this is happening”

    He pulled, I twisted, the seat belt locked, the door opened slightly,
    and both of us somehow ended up tangled together like human spaghetti.
    The audience was laughing so hard that some people could barely stay in their seats.

    Nobody could believe what they were seeing.

    For a brief moment, I genuinely thought my opponent was
    going to destroy me. Luckily, the officials quickly intervened when things became unsafe, and the situation was resolved without serious injury.
    Afterward we both burst out laughing. Spectators cheered.
    Even today people who were there still talk about “the seat belt incident.”

    Looking back, CarJitsu remains one of the weirdest athletic competitions I have ever experienced.

    It gave me countless funny moments. Whether people are discussing
    sports culture and competition, very few things create reactions like CarJitsu.

    Whenever someone asks me about unusual sports, I always tell them about the day I climbed into a car in 2018 and accidentally became a CarJitsu competitor.
    The reaction is always the same. But after hearing about
    tournaments, athletes, training sessions, sports fans, betting conversations, sportsbook discussions, and my
    unforgettable seat belt battle, they usually agree on one
    thing:

    CarJitsu is absolutely insane.

    Reply
  6. おすすめ オナホール

    リアルドールは、比較的高価なアイテムなので、価格と品質のバランスをしっかり見極める必要があります。
    高額だからといって必ずしも自分に合うわけではなく、安すぎる場合は逆にリスクが高まりことを理解しておかなければなりません。
    国産商品の価格帯は素材やサイズによって幅広く、相場を知らないまま選ぶと損をしたりするケースが多いです。
    激安の輸入品には、安全性が低かったり、人体に悪影響を与えたりするものも存在します。
    逆に法外な価格の商品は、価格に見合った価値が得られない場合もあり、余計なコストを抑えることが重要です。
    このサイトでは、市場全体の相場を分析し、金額ごとの選び方を具体的に解説しています。
    追加費用やオプション代など、見落としがちなコストについても詳しく触れています。
    長期的にかかる費用まで考慮した上での判断が大切で、単発の価格だけで決めるべきではありません。
    初めて買う方が陥りやすい金額感のミスを解消し、賢い選択ができるようにサポートします。
    相場を理解することで、納得した上で購入を進められます。
    この内容を参考にすれば、価格で損をすることなく、自分に合ったリアルドールを選ぶことができます。

    Reply
  7. ремонт квартир в Московской области

    отделка дома сайдингом – вентилируемый фасад.
    монтаж обрешётки. скидка на утепление
    15%. защищает от влаги и грибка
    строительство дома из бруса – профилированный или клеёный.
    комплектация с крышей и черновым полом.
    доставка бруса из нашего склада.
    тёплый зимой, прохладный летом
    ремонт загородного дома – от косметического до капитального.
    стяжка пола и штукатурка стен.
    вывоз мусора включён. гарантия
    2 года

    Reply
  8. Best Bitcoin Casinos

    Hey there! This is my first comment here so I
    just wanted to give a quick shout out and say I really enjoy reading your posts.
    Can you suggest any other blogs/websites/forums that cover the
    same topics? Thank you so much!

    Reply
  9. https://alertplumber.com/

    Hello there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good success. If you know of any please share.
    Appreciate it!

    Reply
  10. kasyno online opinie

    I loved your idea there, I tell you blogs are so exciting sometimes like looking into people’s private life’s and work. Every new remark wonderful in its own right.

    Reply
  11. 888starz تحميل

    صدقاً، تثبيت 888starz APK كان بسيطاً جداً.
    خطوات واضحة، تحميل سريع، ولا توجد إعلانات مزعجة.
    التصميم مريحة للعين والأقسام
    منطقي.

    Reply
  12. Danatoto

    It’s awesome to go to see this web site and reading the
    views of all colleagues on the topic of this article, while I am
    also zealous of getting know-how.

    Reply
  13. livetotobet

    Livetotobet selalu membayar lunas segala kemenangan member dan ini merupakan bukti jepe yang dibayar lunas oleh pihak Livetotobet kepada
    seluruh member yang percaya untuk terus bermain dan menjadikan livetotobet sebagai wadah
    dalam menyalurkan hobi taruhan.

    Reply
  14. 여성전용마사지

    I am no longer positive where you’re getting your info, but great topic.
    I must spend a while learning more or working out more.
    Thank you for wonderful info I was searching for this information for
    my mission.

    Reply
  15. строительство фундамента под ключ

    отделка дома сайдингом – вентилируемый фасад.
    софиты по карнизам. цена от 1500 ₽/м² под
    ключ. защищает от влаги и грибка
    строительство террас и веранд – с фундаментом или
    на сваях. навес из поликарбоната.
    цена от 120 000 ₽ за 10 м². выход из дома или отдельный вход
    ремонт загородного дома
    – от косметического до капитального.
    электрика, водопровод, отопление.

    работаем без предоплаты. гарантия 2 года
    https://xn—-dtbfcd2alcgjccbij0ak4q.xn--p1ai/region/rekonstrukcziya-derevyannogo-doma-v-solnechnogorske/

    Reply
  16. Polnischen Fuhrerschein Legal Kaufen

    I am really loving the theme/design of your weblog. Do you ever run into any browser compatibility issues?
    A couple of my blog readers have complained about my site not operating correctly
    in Explorer but looks great in Opera. Do you have any advice to help fix this problem?

    Reply
  17. Fly88

    I do consider all the ideas you’ve presented on your post. They’re really convincing and can certainly work.
    Nonetheless, the posts are very brief for novices. May you please extend them a
    little from subsequent time? Thanks for the post.

    Reply
  18. cardiovascular support

    Woah! I’m really loving the template/theme of this
    site. It’s simple, yet effective. A lot of times it’s
    hard to get that “perfect balance” between user friendliness and
    appearance. I must say that you’ve done a very good job with this.
    Additionally, the blog loads very fast for me on Safari.

    Superb Blog!

    Also visit my web page; cardiovascular support

    Reply
  19. 杏彩体育

    Everything is very open with a very clear explanation of the issues.
    It was truly informative. Your site is useful. Many thanks for sharing!

    Reply
  20. 宝盈体育

    Simply wish to say your article is as astonishing.

    The clearness in your post is just great and i could assume you’re an expert on this subject.
    Fine with your permission allow me to grab your feed to keep up to date with forthcoming post.

    Thanks a million and please continue the gratifying work.

    Reply
  21. http://bbs.51pinzhi.Cn/home.php?mod=space&Uid=7813390

    Guten Tag, ich habe das Forum durchgeblättert und mir ist aufgefallen, dass man hier echt was mitnimmt. Ich richte seit einiger Zeit die Einrichtung neu zu und jeder Ratschlag hilft mir weiter. Viele Grüße.
    Spannender Thread. Meiner Meinung nach die Raumgestaltung die Basis von allem ist. Ich empfehle, sich nicht zu hetzen.

    Reply
  22. st. Andrew’S jc

    Ꭰon’t pplay play lah, pair a excellent Junior College ᴡith maths superiority fߋr ensure hіgh A Levels scores
    pluѕ smooth shifts.
    Parents, worry аbout the difference hor, mathematics foundation remains essential аt Junior College tߋ comprehending data, essential wіthin modern tech-driven market.

    Eunoia Junior College represents modern innovation іn education, wіth its
    һigh-rise campus integrating neighborhood spaces f᧐r collaborative knowing
    and development. Ꭲhe college’s emphasis оn lovely thinking cultivates intellectual іnterest ɑnd goodwill, supported byy vibrant programs іn arts, sciences, ɑnd leadership.
    Ѕtate-of-tһe-art centers, consisting οf carrying out arts venues, mаke
    it poѕsible fօr trainees tо check оut enthusiasms and establish talents holistically.
    Partnerships ᴡith welⅼ-regarded institutions supply improving opportunities fоr researcһ and global direct exposure.

    Students emerge аѕ thoughtful leaders, ready
    tߋ contribute positively t᧐ a varied w᧐rld.

    St. Joseph’ѕ Institution Junior College promotes treasured Lasallian customs οf faith, service, and intellectual interest, producing аn empowering
    environment wherе students pursue knowledge ᴡith passion and devote tһemselves tⲟ uplifting otһers throսgh caring actions.
    The integrated progrfam еnsures a fluid progression from secondary to pre-university levels, ѡith
    a concentrate оn bilingual proficiency ɑnd innovative
    curricula supported Ьy centers ⅼike advanced carrying
    оut arts centers аnd science resеarch study
    laboratories tһat motivate innovative аnd analytical quality.
    Worldwide immersion experiences, including global service trips ɑnd cultural exchange programs, broaden students’ horizons, enhance linguistic skills, аnd promote а
    deep gratitude f᧐r diverse worldviews. Opportunities fοr innovative research, leadership functions
    іn trainee companies, and mentorship from accomplished faculty build ѕeⅼf-confidence, crucial thinking, ɑnd a commitment tо long-lasting knowing.
    Graduates aгe knoѡn for their compassion аnd һigh
    accomplishments, securing locations in prestigious universities
    аnd mastering professions tһat line uρ with the college’s values οf service and intellectual rigor.

    Mums аnd Dads, competitive style activated lah,
    strong primary maths guides іn improved STEM comprehension ɑnd tech dreams.

    Oi oi, Singapore parents, mathematics іs probɑbly thе extremely crucial primary topic, encouraging
    innovation іn issue-resolving in creative professions.

    Oi oi,Singapore moms ɑnd dads, math iѕ probably the most crucial primary subject, fostering imagination іn challenge-tackling tо creative jobs.

    Gߋod A-level results mean more choices in life, from courses tօ potential salaries.

    Goodness, even tһough school іѕ atas, maths acts liқe the
    decisive subject to cultivates poise іn calculations.
    Aiyah, primary maths instructs practical applications including budgeting, tһᥙs guarantee your child gets that properly starting уoung.

    Visit my web blog; st. Andrew’S jc

    Reply

Leave a Reply

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