Blender V5.3
softbody.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
25
26#include <algorithm>
27#include <cmath>
28#include <cstdlib>
29#include <cstring>
30
31#include "CLG_log.h"
32
33#include "MEM_guardedalloc.h"
34
35/* types */
37#include "DNA_curve_types.h"
38#include "DNA_lattice_types.h"
39#include "DNA_mesh_types.h"
40#include "DNA_meshdata_types.h"
42#include "DNA_object_types.h"
43#include "DNA_scene_types.h"
44
45#include "BLI_listbase.hh"
46#include "BLI_math_geom_c.hh"
47#include "BLI_math_matrix_c.hh"
48#include "BLI_math_vector_c.hh"
49#include "BLI_threads.hh"
50#include "BLI_time.hh"
51#include "BLI_utildefines.hh"
52
53#include "BKE_collision.h"
54#include "BKE_curve.hh"
55#include "BKE_customdata.hh"
56#include "BKE_deform.hh"
57#include "BKE_effect.h"
58#include "BKE_global.hh"
59#include "BKE_layer.hh"
60#include "BKE_lib_id.hh"
61#include "BKE_mesh.hh"
62#include "BKE_modifier.hh"
63#include "BKE_pointcache.h"
64#include "BKE_scene.hh"
65#include "BKE_softbody.h"
66
67#include "DEG_depsgraph.hh"
69
70namespace blender {
71
72static CLG_LogRef LOG = {"physics.softbody"};
73
74/* callbacks for errors and interrupts and some goo */
75static int (*SB_localInterruptCallBack)() = nullptr;
76
77/* ********** soft body engine ******* */
78
79enum type_spring { SB_EDGE = 1, SB_BEND = 2, SB_STIFFQUAD = 3, SB_HANDLE = 4 };
80
81struct BodySpring {
82 int v1, v2;
83 float len, cf, load;
84 float ext_force[3]; /* edges colliding and sailing */
86 short flag;
87};
88
89struct BodyFace {
90 int v1, v2, v3;
91 float ext_force[3]; /* faces colliding */
92 short flag;
93};
94
96 float pos[3]; /* position relative to com */
97 float mass; /* node mass */
98};
99
101 float com[3]; /* Center of mass. */
102 ReferenceVert *ivert; /* List of initial values. */
103};
104
106
107/* Private scratch pad for caching and other data only needed when alive. */
117
122 float timenow;
124 int ilast;
125 ListBaseT<EffectorCache> *effectors;
129 int nr;
130 int tot;
131};
132
133#define MID_PRESERVE 1
134
135#define SOFTGOALSNAP 0.999f
136/* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
137 * removes *unnecessary* stiffness from ODE system
138 */
139#define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
140
141#define BSF_INTERSECT 1 /* edge intersects collider face */
142
143/* private definitions for body-point states */
144#define SBF_DOFUZZY 1 /* Body-point do fuzzy. */
145#define SBF_OUTOFCOLLISION 2 /* Body-point does not collide. */
146
147#define BFF_INTERSECT 1 /* collider edge intrudes face. */
148#define BFF_CLOSEVERT 2 /* collider vertex repulses face. */
149
150/* Hum .. this should be calculated from sb parameters and sizes. */
151static float SoftHeunTol = 1.0f;
152
153/* local prototypes */
154static void free_softbody_intern(SoftBody *sb);
155
156/* +++ frame based timing +++ */
157
158/* Physical unit of force is `kg * m / sec^2`. */
159
164static float sb_grav_force_scale(Object * /*ob*/)
165{
166 return (0.001f);
167}
168
173static float sb_fric_force_scale(Object * /*ob*/)
174{
175 return (0.01f);
176}
177
181static float sb_time_scale(Object *ob)
182{
183 SoftBody *sb = ob->soft; /* is supposed to be there */
184 if (sb) {
185 return (sb->physics_speed);
186 /* Hum .. this could be IPO as well :)
187 * estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)]
188 * 1 approx = a unit 1 pendulum at g = 9.8 [earth conditions] has period 65 frames
189 * theory would give a 50 frames period .. so there must be something inaccurate ..
190 * looking for that (BM). */
191 }
192 return (1.0f);
193 /*
194 * this would be frames/sec independent timing assuming 25 fps is default
195 * but does not work very well with NLA
196 * return (25.0f/scene->r.frs_sec)
197 */
198}
199/*--- frame based timing ---*/
200
201/* helper functions for everything is animatable jow_go_for2_5 +++++++ */
202/* introducing them here, because i know: steps in properties ( at frame timing )
203 * will cause unwanted responses of the softbody system (which does inter frame calculations )
204 * so first 'cure' would be: interpolate linear in time ..
205 * Q: why do i write this?
206 * A: because it happened once, that some eager coder 'streamlined' code to fail.
207 * We DO linear interpolation for goals .. and i think we should do on animated properties as well
208 */
209
210/* animate sb->maxgoal, sb->mingoal */
211static float _final_goal(Object *ob, BodyPoint *bp) /* jow_go_for2_5 */
212{
213 float f = -1999.99f;
214 if (ob) {
215 SoftBody *sb = ob->soft; /* is supposed to be there */
216 if (!(ob->softflag & OB_SB_GOAL)) {
217 return (0.0f);
218 }
219 if (sb && bp) {
220 if (bp->goal < 0.0f) {
221 return (0.0f);
222 }
223 f = sb->mingoal + bp->goal * fabsf(sb->maxgoal - sb->mingoal);
224 f = pow(f, 4.0f);
225 return f;
226 }
227 }
228 CLOG_ERROR(&LOG, "sb or bp == NULL");
229 return f; /* Using crude but spot able values some times helps debugging. */
230}
231
232static float _final_mass(Object *ob, BodyPoint *bp)
233{
234 if (ob) {
235 SoftBody *sb = ob->soft; /* is supposed to be there */
236 if (sb && bp) {
237 return (bp->mass * sb->nodemass);
238 }
239 }
240 CLOG_ERROR(&LOG, "sb or bp == NULL");
241 return 1.0f;
242}
243/* Helper functions for everything is animatable jow_go_for2_5. */
244
245/* +++ collider caching and dicing +++ */
246
247/*
248 * for each target object/face the axis aligned bounding box (AABB) is stored
249 * faces parallel to global axes
250 * so only simple "value" in [min, max] checks are used
251 * float operations still
252 */
253
254/* Just an ID here to reduce the prob for killing objects
255 * `ob->sumohandle` points to we should not kill :)
256 */
257static const int CCD_SAFETY = 190561;
258
261};
262
263struct ccd_Mesh {
270 /* Axis Aligned Bounding Box AABB */
271 float bbmin[3];
272 float bbmax[3];
273};
274
276{
278 ccd_Mesh *pccd_M = nullptr;
279 CCDF_MinMax *mima;
280 float hull;
281 int i;
282
283 cmd = reinterpret_cast<CollisionModifierData *>(
285
286 /* first some paranoia checks */
287 if (!cmd) {
288 return nullptr;
289 }
290 if (!cmd->mvert_num || !cmd->tri_num) {
291 return nullptr;
292 }
293
294 pccd_M = MEM_new_uninitialized<ccd_Mesh>("ccd_Mesh");
295 pccd_M->mvert_num = cmd->mvert_num;
296 pccd_M->tri_num = cmd->tri_num;
297 pccd_M->safety = CCD_SAFETY;
298 pccd_M->bbmin[0] = pccd_M->bbmin[1] = pccd_M->bbmin[2] = 1e30f;
299 pccd_M->bbmax[0] = pccd_M->bbmax[1] = pccd_M->bbmax[2] = -1e30f;
300 pccd_M->vert_positions_prev = nullptr;
301
302 /* Blow it up with force-field ranges. */
303 hull = max_ff(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
304
305 /* Allocate and copy verts. */
306 pccd_M->vert_positions = MEM_dupalloc(cmd->xnew);
307 /* note that xnew coords are already in global space, */
308 /* determine the ortho BB */
309 for (i = 0; i < pccd_M->mvert_num; i++) {
310 const float *v;
311
312 /* evaluate limits */
313 v = pccd_M->vert_positions[i];
314 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
315 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
316 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
317
318 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
319 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
320 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
321 }
322 /* Allocate and copy faces. */
323 pccd_M->vert_tris = reinterpret_cast<const int3 *>(MEM_dupalloc(cmd->vert_tris));
324
325 /* OBBs for idea1 */
326 pccd_M->mima = MEM_new_array_uninitialized<CCDF_MinMax>(size_t(pccd_M->tri_num),
327 "ccd_Mesh_Faces_mima");
328
329 /* Anyhow we need to walk the list of faces and find OBB they live in. */
330 for (i = 0, mima = pccd_M->mima; i < pccd_M->tri_num; i++, mima++) {
331 const float *v;
332
333 mima->minx = mima->miny = mima->minz = 1e30f;
334 mima->maxx = mima->maxy = mima->maxz = -1e30f;
335
336 v = pccd_M->vert_positions[pccd_M->vert_tris[i][0]];
337 mima->minx = min_ff(mima->minx, v[0] - hull);
338 mima->miny = min_ff(mima->miny, v[1] - hull);
339 mima->minz = min_ff(mima->minz, v[2] - hull);
340 mima->maxx = max_ff(mima->maxx, v[0] + hull);
341 mima->maxy = max_ff(mima->maxy, v[1] + hull);
342 mima->maxz = max_ff(mima->maxz, v[2] + hull);
343
344 v = pccd_M->vert_positions[pccd_M->vert_tris[i][1]];
345 mima->minx = min_ff(mima->minx, v[0] - hull);
346 mima->miny = min_ff(mima->miny, v[1] - hull);
347 mima->minz = min_ff(mima->minz, v[2] - hull);
348 mima->maxx = max_ff(mima->maxx, v[0] + hull);
349 mima->maxy = max_ff(mima->maxy, v[1] + hull);
350 mima->maxz = max_ff(mima->maxz, v[2] + hull);
351
352 v = pccd_M->vert_positions[pccd_M->vert_tris[i][2]];
353 mima->minx = min_ff(mima->minx, v[0] - hull);
354 mima->miny = min_ff(mima->miny, v[1] - hull);
355 mima->minz = min_ff(mima->minz, v[2] - hull);
356 mima->maxx = max_ff(mima->maxx, v[0] + hull);
357 mima->maxy = max_ff(mima->maxy, v[1] + hull);
358 mima->maxz = max_ff(mima->maxz, v[2] + hull);
359 }
360
361 return pccd_M;
362}
363static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M)
364{
366 CCDF_MinMax *mima;
367 float hull;
368 int i;
369
370 cmd = reinterpret_cast<CollisionModifierData *>(
372
373 /* first some paranoia checks */
374 if (!cmd) {
375 return;
376 }
377 if (!cmd->mvert_num || !cmd->tri_num) {
378 return;
379 }
380
381 if ((pccd_M->mvert_num != cmd->mvert_num) || (pccd_M->tri_num != cmd->tri_num)) {
382 return;
383 }
384
385 pccd_M->bbmin[0] = pccd_M->bbmin[1] = pccd_M->bbmin[2] = 1e30f;
386 pccd_M->bbmax[0] = pccd_M->bbmax[1] = pccd_M->bbmax[2] = -1e30f;
387
388 /* Blow it up with force-field ranges. */
389 hull = max_ff(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
390
391 /* rotate current to previous */
392 if (pccd_M->vert_positions_prev) {
393 MEM_delete(pccd_M->vert_positions_prev);
394 }
395 pccd_M->vert_positions_prev = pccd_M->vert_positions;
396 /* Allocate and copy verts. */
397 pccd_M->vert_positions = MEM_dupalloc(cmd->xnew);
398 /* note that xnew coords are already in global space, */
399 /* determine the ortho BB */
400 for (i = 0; i < pccd_M->mvert_num; i++) {
401 const float *v;
402
403 /* evaluate limits */
404 v = pccd_M->vert_positions[i];
405 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
406 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
407 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
408
409 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
410 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
411 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
412
413 /* evaluate limits */
414 v = pccd_M->vert_positions_prev[i];
415 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
416 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
417 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
418
419 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
420 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
421 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
422 }
423
424 /* Anyhow we need to walk the list of faces and find OBB they live in. */
425 for (i = 0, mima = pccd_M->mima; i < pccd_M->tri_num; i++, mima++) {
426 const float *v;
427
428 mima->minx = mima->miny = mima->minz = 1e30f;
429 mima->maxx = mima->maxy = mima->maxz = -1e30f;
430
431 /* vert_positions */
432 v = pccd_M->vert_positions[pccd_M->vert_tris[i][0]];
433 mima->minx = min_ff(mima->minx, v[0] - hull);
434 mima->miny = min_ff(mima->miny, v[1] - hull);
435 mima->minz = min_ff(mima->minz, v[2] - hull);
436 mima->maxx = max_ff(mima->maxx, v[0] + hull);
437 mima->maxy = max_ff(mima->maxy, v[1] + hull);
438 mima->maxz = max_ff(mima->maxz, v[2] + hull);
439
440 v = pccd_M->vert_positions[pccd_M->vert_tris[i][1]];
441 mima->minx = min_ff(mima->minx, v[0] - hull);
442 mima->miny = min_ff(mima->miny, v[1] - hull);
443 mima->minz = min_ff(mima->minz, v[2] - hull);
444 mima->maxx = max_ff(mima->maxx, v[0] + hull);
445 mima->maxy = max_ff(mima->maxy, v[1] + hull);
446 mima->maxz = max_ff(mima->maxz, v[2] + hull);
447
448 v = pccd_M->vert_positions[pccd_M->vert_tris[i][2]];
449 mima->minx = min_ff(mima->minx, v[0] - hull);
450 mima->miny = min_ff(mima->miny, v[1] - hull);
451 mima->minz = min_ff(mima->minz, v[2] - hull);
452 mima->maxx = max_ff(mima->maxx, v[0] + hull);
453 mima->maxy = max_ff(mima->maxy, v[1] + hull);
454 mima->maxz = max_ff(mima->maxz, v[2] + hull);
455
456 /* vert_positions_prev */
457 v = pccd_M->vert_positions_prev[pccd_M->vert_tris[i][0]];
458 mima->minx = min_ff(mima->minx, v[0] - hull);
459 mima->miny = min_ff(mima->miny, v[1] - hull);
460 mima->minz = min_ff(mima->minz, v[2] - hull);
461 mima->maxx = max_ff(mima->maxx, v[0] + hull);
462 mima->maxy = max_ff(mima->maxy, v[1] + hull);
463 mima->maxz = max_ff(mima->maxz, v[2] + hull);
464
465 v = pccd_M->vert_positions_prev[pccd_M->vert_tris[i][1]];
466 mima->minx = min_ff(mima->minx, v[0] - hull);
467 mima->miny = min_ff(mima->miny, v[1] - hull);
468 mima->minz = min_ff(mima->minz, v[2] - hull);
469 mima->maxx = max_ff(mima->maxx, v[0] + hull);
470 mima->maxy = max_ff(mima->maxy, v[1] + hull);
471 mima->maxz = max_ff(mima->maxz, v[2] + hull);
472
473 v = pccd_M->vert_positions_prev[pccd_M->vert_tris[i][2]];
474 mima->minx = min_ff(mima->minx, v[0] - hull);
475 mima->miny = min_ff(mima->miny, v[1] - hull);
476 mima->minz = min_ff(mima->minz, v[2] - hull);
477 mima->maxx = max_ff(mima->maxx, v[0] + hull);
478 mima->maxy = max_ff(mima->maxy, v[1] + hull);
479 mima->maxz = max_ff(mima->maxz, v[2] + hull);
480 }
481}
482
483static void ccd_mesh_free(ccd_Mesh *ccdm)
484{
485 /* Make sure we're not nuking objects we don't know. */
486 if (ccdm && (ccdm->safety == CCD_SAFETY)) {
487 MEM_delete(ccdm->vert_positions);
488 MEM_delete(ccdm->vert_tris);
489 if (ccdm->vert_positions_prev) {
490 MEM_delete(ccdm->vert_positions_prev);
491 }
492 MEM_delete(ccdm->mima);
493 MEM_delete(ccdm);
494 }
495}
496
498{
499 /* only with deflecting set */
500 if (ob->pd && ob->pd->deflect) {
501 hash->lookup_or_add_cb(ob, [&]() { return ccd_mesh_make(ob); });
502 }
503}
504
508static void ccd_build_deflector_hash(Depsgraph *depsgraph,
509 Collection *collection,
510 Object *vertexowner,
512{
513 if (!hash) {
514 return;
515 }
516
517 uint numobjects;
519 depsgraph, vertexowner, collection, &numobjects, eModifierType_Collision);
520
521 for (int i = 0; i < numobjects; i++) {
522 Object *ob = objects[i];
523
524 if (ob->type == OB_MESH) {
526 }
527 }
528
530}
531
533{
534 if (ob->pd && ob->pd->deflect) {
535 ccd_Mesh *ccdmesh = hash->lookup_default(ob, nullptr);
536 if (ccdmesh) {
537 ccd_mesh_update(ob, ccdmesh);
538 }
539 }
540}
541
545static void ccd_update_deflector_hash(Depsgraph *depsgraph,
546 Collection *collection,
547 Object *vertexowner,
549{
550 if ((!hash) || (!vertexowner)) {
551 return;
552 }
553
554 uint numobjects;
556 depsgraph, vertexowner, collection, &numobjects, eModifierType_Collision);
557
558 for (int i = 0; i < numobjects; i++) {
559 Object *ob = objects[i];
560
561 if (ob->type == OB_MESH) {
563 }
564 }
565
567}
568
569/*--- collider caching and dicing ---*/
570
572{
573 int result = 0;
574 const OffsetIndices faces = mesh->faces();
575 for (const int i : faces.index_range()) {
576 if (faces[i].size() == 4) {
577 result++;
578 }
579 }
580 return result;
581}
582
584{
585 Mesh *mesh = id_cast<Mesh *>(ob->data);
586 // BodyPoint *bp; /* UNUSED */
587 if (ob->soft) {
588 int nofquads;
589 // float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
590
591 nofquads = count_mesh_quads(mesh);
592 if (nofquads) {
593 const OffsetIndices faces = mesh->faces();
594 const Span<int> corner_verts = mesh->corner_verts();
595 BodySpring *bs;
596
597 /* resize spring-array to hold additional quad springs */
598 ob->soft->bspring = static_cast<BodySpring *>(MEM_realloc_zeroed(
599 ob->soft->bspring, sizeof(BodySpring) * (ob->soft->totspring + nofquads * 2)));
600
601 /* fill the tail */
602 bs = &ob->soft->bspring[ob->soft->totspring];
603 // bp = ob->soft->bpoint; /* UNUSED */
604 for (int a = 0; a < mesh->faces_num; a++) {
605 const int poly_size = faces[a].size();
606 if (poly_size == 4) {
607 bs->v1 = corner_verts[faces[a].start() + 0];
608 bs->v2 = corner_verts[faces[a].start() + 2];
610 bs++;
611 bs->v1 = corner_verts[faces[a].start() + 1];
612 bs->v2 = corner_verts[faces[a].start() + 3];
614 bs++;
615 }
616 }
617
618 /* now we can announce new springs */
619 ob->soft->totspring += nofquads * 2;
620 }
621 }
622}
623
624static void add_2nd_order_roller(Object *ob, float /*stiffness*/, int *counter, int addsprings)
625{
626 /* Assume we have a softbody. */
627 SoftBody *sb = ob->soft; /* is supposed to be there */
628 BodyPoint *bp, *bpo;
629 BodySpring *bs, *bs2, *bs3 = nullptr;
630 int a, b, c, notthis = 0, v0;
631 if (!sb->bspring) {
632 return;
633 } /* we are 2nd order here so 1rst should have been build :) */
634 /* First run counting second run adding. */
635 *counter = 0;
636 if (addsprings) {
637 bs3 = ob->soft->bspring + ob->soft->totspring;
638 }
639 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
640 /* Scan for neighborhood. */
641 bpo = nullptr;
642 v0 = (sb->totpoint - a);
643 for (b = bp->nofsprings; b > 0; b--) {
644 bs = sb->bspring + bp->springs[b - 1];
645 /* Nasty thing here that springs have two ends
646 * so here we have to make sure we examine the other */
647 if (v0 == bs->v1) {
648 bpo = sb->bpoint + bs->v2;
649 notthis = bs->v2;
650 }
651 else {
652 if (v0 == bs->v2) {
653 bpo = sb->bpoint + bs->v1;
654 notthis = bs->v1;
655 }
656 else {
657 CLOG_ERROR(&LOG, "oops we should not get here");
658 }
659 }
660 if (bpo) { /* so now we have a 2nd order humpdidump */
661 for (c = bpo->nofsprings; c > 0; c--) {
662 bs2 = sb->bspring + bpo->springs[c - 1];
663 if ((bs2->v1 != notthis) && (bs2->v1 > v0)) {
664 (*counter)++; /* hit */
665 if (addsprings) {
666 bs3->v1 = v0;
667 bs3->v2 = bs2->v1;
668 bs3->springtype = SB_BEND;
669 bs3++;
670 }
671 }
672 if ((bs2->v2 != notthis) && (bs2->v2 > v0)) {
673 (*counter)++; /* hit */
674 if (addsprings) {
675 bs3->v1 = v0;
676 bs3->v2 = bs2->v2;
677 bs3->springtype = SB_BEND;
678 bs3++;
679 }
680 }
681 }
682 }
683 }
684 /* Scan for neighborhood done. */
685 }
686}
687
688static void add_2nd_order_springs(Object *ob, float stiffness)
689{
690 int counter = 0;
691 BodySpring *bs_new;
692 stiffness *= stiffness;
693
694 add_2nd_order_roller(ob, stiffness, &counter, 0); /* counting */
695 if (counter) {
696 /* resize spring-array to hold additional springs */
697 bs_new = MEM_new_array_zeroed<BodySpring>(size_t(ob->soft->totspring) + size_t(counter),
698 "bodyspring");
699 memcpy(bs_new, ob->soft->bspring, (ob->soft->totspring) * sizeof(BodySpring));
700
701 if (ob->soft->bspring) {
702 MEM_delete(ob->soft->bspring);
703 }
704 ob->soft->bspring = bs_new;
705
706 add_2nd_order_roller(ob, stiffness, &counter, 1); /* adding */
707 ob->soft->totspring += counter;
708 }
709}
710
711static void add_bp_springlist(BodyPoint *bp, int springID)
712{
713 int *newlist;
714
715 if (bp->springs == nullptr) {
716 bp->springs = MEM_new_array_zeroed<int>(1, "bpsprings");
717 bp->springs[0] = springID;
718 bp->nofsprings = 1;
719 }
720 else {
721 bp->nofsprings++;
722 newlist = MEM_new_array_zeroed<int>(bp->nofsprings, "bpsprings");
723 memcpy(newlist, bp->springs, (bp->nofsprings - 1) * sizeof(int));
724 MEM_delete(bp->springs);
725 bp->springs = newlist;
726 bp->springs[bp->nofsprings - 1] = springID;
727 }
728}
729
735{
736 SoftBody *sb = ob->soft; /* is supposed to be there */
737 BodyPoint *bp;
738 BodySpring *bs;
739 int a, b;
740
741 if (sb == nullptr) {
742 return; /* paranoia check */
743 }
744
745 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
746 /* throw away old list */
747 if (bp->springs) {
748 MEM_delete(bp->springs);
749 bp->springs = nullptr;
750 }
751 /* scan for attached inner springs */
752 for (b = sb->totspring, bs = sb->bspring; b > 0; b--, bs++) {
753 if ((sb->totpoint - a) == bs->v1) {
754 add_bp_springlist(bp, sb->totspring - b);
755 }
756 if ((sb->totpoint - a) == bs->v2) {
757 add_bp_springlist(bp, sb->totspring - b);
758 }
759 } /* For springs. */
760 } /* For bp. */
761}
762
764{
765 SoftBody *sb = ob->soft; /* is supposed to be there */
766 BodyPoint *bp;
767 BodySpring *bs;
768 int a, b, akku_count;
769 float min, max, akku;
770
771 if (sb == nullptr) {
772 return; /* paranoia check */
773 }
774
775 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
776 bp->colball = 0;
777 akku = 0.0f;
778 akku_count = 0;
779 min = 1e22f;
780 max = -1e22f;
781 /* first estimation based on attached */
782 for (b = bp->nofsprings; b > 0; b--) {
783 bs = sb->bspring + bp->springs[b - 1];
784 if (bs->springtype == SB_EDGE) {
785 akku += bs->len;
786 akku_count++;
787 min = min_ff(bs->len, min);
788 max = max_ff(bs->len, max);
789 }
790 }
791
792 if (akku_count > 0) {
793 if (sb->sbc_mode == SBC_MODE_MANUAL) {
794 bp->colball = sb->colball;
795 }
796 if (sb->sbc_mode == SBC_MODE_AVG) {
797 bp->colball = akku / float(akku_count) * sb->colball;
798 }
799 if (sb->sbc_mode == SBC_MODE_MIN) {
800 bp->colball = min * sb->colball;
801 }
802 if (sb->sbc_mode == SBC_MODE_MAX) {
803 bp->colball = max * sb->colball;
804 }
805 if (sb->sbc_mode == SBC_MODE_AVGMINMAX) {
806 bp->colball = (min + max) / 2.0f * sb->colball;
807 }
808 }
809 else {
810 bp->colball = 0;
811 }
812 } /* For bp. */
813}
814
815/* creates new softbody if didn't exist yet, makes new points and springs arrays */
816static void renew_softbody(Object *ob, int totpoint, int totspring)
817{
818 SoftBody *sb;
819 int i;
820 short softflag;
821 if (ob->soft == nullptr) {
822 ob->soft = sbNew();
823 }
824 else {
826 }
827 sb = ob->soft;
828 softflag = ob->softflag;
829
830 if (totpoint) {
831 sb->totpoint = totpoint;
832 sb->totspring = totspring;
833
834 sb->bpoint = MEM_new_array_uninitialized<BodyPoint>(size_t(totpoint), "bodypoint");
835 if (totspring) {
836 sb->bspring = MEM_new_array_uninitialized<BodySpring>(size_t(totspring), "bodyspring");
837 }
838
839 /* initialize BodyPoint array */
840 for (i = 0; i < totpoint; i++) {
841 BodyPoint *bp = &sb->bpoint[i];
842
843 /* hum as far as i see this is overridden by _final_goal() now jow_go_for2_5 */
844 /* sadly breaks compatibility with older versions */
845 /* but makes goals behave the same for meshes, lattices and curves */
846 if (softflag & OB_SB_GOAL) {
847 bp->goal = sb->defgoal;
848 }
849 else {
850 bp->goal = 0.0f;
851 /* So this will definitely be below #SOFTGOALSNAP. */
852 }
853
854 bp->nofsprings = 0;
855 bp->springs = nullptr;
856 bp->choke = 0.0f;
857 bp->choke2 = 0.0f;
858 bp->frozen = 1.0f;
859 bp->colball = 0.0f;
860 bp->loc_flag = 0;
861 bp->springweight = 1.0f;
862 bp->mass = 1.0f;
863 }
864 }
865}
866
868{
869 SBVertex *key;
870 int k;
871
872 for (k = 0; k < sb->totkey; k++) {
873 key = *(sb->keys + k);
874 if (key) {
875 MEM_delete(key);
876 }
877 }
878 MEM_SAFE_DELETE(sb->keys);
879 sb->totkey = 0;
880}
881static void free_scratch(SoftBody *sb)
882{
883 if (sb->scratch) {
884 /* TODO: make sure everything is cleaned up nicely. */
885 if (sb->scratch->colliderhash) {
886 for (ccd_Mesh *ccdm : sb->scratch->colliderhash->values()) {
887 ccd_mesh_free(ccdm);
888 }
889 MEM_delete(sb->scratch->colliderhash);
890 sb->scratch->colliderhash = nullptr;
891 }
892 if (sb->scratch->bodyface) {
893 MEM_delete(sb->scratch->bodyface);
894 }
895 if (sb->scratch->Ref.ivert) {
896 MEM_delete(sb->scratch->Ref.ivert);
897 }
898 MEM_delete(sb->scratch);
899 sb->scratch = nullptr;
900 }
901}
902
903/* only frees internal data */
905{
906 if (sb) {
907 int a;
908 BodyPoint *bp;
909
910 if (sb->bpoint) {
911 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
912 /* free spring list */
913 if (bp->springs != nullptr) {
914 MEM_delete(bp->springs);
915 }
916 }
917 MEM_delete(sb->bpoint);
918 }
919
920 if (sb->bspring) {
921 MEM_delete(sb->bspring);
922 }
923
924 sb->totpoint = sb->totspring = 0;
925 sb->bpoint = nullptr;
926 sb->bspring = nullptr;
927
928 free_scratch(sb);
930 }
931}
932
933/* ************ dynamics ********** */
934
935/* the most general (micro physics correct) way to do collision
936 * (only needs the current particle position)
937 *
938 * it actually checks if the particle intrudes a short range force field generated
939 * by the faces of the target object and returns a force to drive the particle out
940 * the strength of the field grows exponentially if the particle is on the 'wrong' side of the face
941 * 'wrong' side : projection to the face normal is negative (all referred to a vertex in the face)
942 *
943 * flaw of this: 'fast' particles as well as 'fast' colliding faces
944 * give a 'tunnel' effect such that the particle passes through the force field
945 * without ever 'seeing' it
946 * this is fully compliant to heisenberg: h >= fuzzy(location) * fuzzy(time)
947 * besides our h is way larger than in QM because forces propagate way slower here
948 * we have to deal with fuzzy(time) in the range of 1/25 seconds (typical frame rate)
949 * yup collision targets are not known here any better
950 * and 1/25 second is very long compared to real collision events
951 * Q: why not use 'simple' collision here like bouncing back a particle
952 * --> reverting is velocity on the face normal
953 * A: because our particles are not alone here
954 * and need to tell their neighbors exactly what happens via spring forces
955 * unless sbObjectStep( .. ) is called on sub frame timing level
956 * BTW that also questions the use of a 'implicit' solvers on soft-bodies
957 * since that would only valid for 'slow' moving collision targets and ditto particles.
958 */
959
960/* +++ dependency information functions. */
961
965static int query_external_colliders(Depsgraph *depsgraph, Collection *collection)
966{
967 uint numobjects;
969 depsgraph, nullptr, collection, &numobjects, eModifierType_Collision);
971
972 return (numobjects != 0);
973}
974/* --- dependency information functions. */
975
976/* +++ the aabb "force" section. */
977static int sb_detect_aabb_collisionCached(float /*force*/[3], Object *vertexowner, float /*time*/)
978{
979 SoftBody *sb = vertexowner->soft;
980 float aabbmin[3], aabbmax[3];
981 int deflected = 0;
982#if 0
983 int a;
984#endif
985
986 if ((sb == nullptr) || (sb->scratch == nullptr)) {
987 return 0;
988 }
989 copy_v3_v3(aabbmin, sb->scratch->aabbmin);
990 copy_v3_v3(aabbmax, sb->scratch->aabbmax);
991
992 for (const auto &item : vertexowner->soft->scratch->colliderhash->items()) {
993 Object *ob = item.key;
994 ccd_Mesh *ccdm = item.value;
995 {
996 /* only with deflecting set */
997 if (ob->pd && ob->pd->deflect) {
998 if (ccdm) {
999 if ((aabbmax[0] < ccdm->bbmin[0]) || (aabbmax[1] < ccdm->bbmin[1]) ||
1000 (aabbmax[2] < ccdm->bbmin[2]) || (aabbmin[0] > ccdm->bbmax[0]) ||
1001 (aabbmin[1] > ccdm->bbmax[1]) || (aabbmin[2] > ccdm->bbmax[2]))
1002 {
1003 /* boxes don't intersect */
1004 continue;
1005 }
1006
1007 /* so now we have the 2 boxes overlapping */
1008 /* forces actually not used */
1009 deflected = 2;
1010 }
1011 else {
1012 /* Aye that should be cached. */
1013 CLOG_ERROR(&LOG, "missing cache error");
1014 continue;
1015 }
1016 } /* if (ob->pd && ob->pd->deflect) */
1017 }
1018 } /* while () */
1019 return deflected;
1020}
1021/* --- the aabb section. */
1022
1023/* +++ the face external section. */
1024static int sb_detect_face_pointCached(const float face_v1[3],
1025 const float face_v2[3],
1026 const float face_v3[3],
1027 float *damp,
1028 float force[3],
1029 Object *vertexowner,
1030 float time)
1031{
1032 float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1033 float facedist, outerfacethickness, tune = 10.0f;
1034 int a, deflected = 0;
1035
1036 aabbmin[0] = std::min({face_v1[0], face_v2[0], face_v3[0]});
1037 aabbmin[1] = std::min({face_v1[1], face_v2[1], face_v3[1]});
1038 aabbmin[2] = std::min({face_v1[2], face_v2[2], face_v3[2]});
1039 aabbmax[0] = std::max({face_v1[0], face_v2[0], face_v3[0]});
1040 aabbmax[1] = std::max({face_v1[1], face_v2[1], face_v3[1]});
1041 aabbmax[2] = std::max({face_v1[2], face_v2[2], face_v3[2]});
1042
1043 /* calculate face normal once again SIGH */
1044 sub_v3_v3v3(edge1, face_v1, face_v2);
1045 sub_v3_v3v3(edge2, face_v3, face_v2);
1046 cross_v3_v3v3(d_nvect, edge2, edge1);
1047 normalize_v3(d_nvect);
1048
1049 for (const auto &item : vertexowner->soft->scratch->colliderhash->items()) {
1050 Object *ob = item.key;
1051 ccd_Mesh *ccdm = item.value;
1052 {
1053 /* only with deflecting set */
1054 if (ob->pd && ob->pd->deflect) {
1055 const float (*vert_positions)[3] = nullptr;
1056 const float (*vert_positions_prev)[3] = nullptr;
1057 if (ccdm) {
1058 vert_positions = ccdm->vert_positions;
1059 a = ccdm->mvert_num;
1060 vert_positions_prev = ccdm->vert_positions_prev;
1061 outerfacethickness = ob->pd->pdef_sboft;
1062 if ((aabbmax[0] < ccdm->bbmin[0]) || (aabbmax[1] < ccdm->bbmin[1]) ||
1063 (aabbmax[2] < ccdm->bbmin[2]) || (aabbmin[0] > ccdm->bbmax[0]) ||
1064 (aabbmin[1] > ccdm->bbmax[1]) || (aabbmin[2] > ccdm->bbmax[2]))
1065 {
1066 /* boxes don't intersect */
1067 continue;
1068 }
1069 }
1070 else {
1071 /* Aye that should be cached. */
1072 CLOG_ERROR(&LOG, "missing cache error");
1073 continue;
1074 }
1075
1076 /* Use mesh. */
1077 if (vert_positions) {
1078 while (a) {
1079 copy_v3_v3(nv1, vert_positions[a - 1]);
1080 if (vert_positions_prev) {
1081 mul_v3_fl(nv1, time);
1082 madd_v3_v3fl(nv1, vert_positions_prev[a - 1], 1.0f - time);
1083 }
1084 /* Origin to face_v2. */
1085 sub_v3_v3(nv1, face_v2);
1086 facedist = dot_v3v3(nv1, d_nvect);
1087 if (fabsf(facedist) < outerfacethickness) {
1088 if (isect_point_tri_prism_v3(nv1, face_v1, face_v2, face_v3)) {
1089 float df;
1090 if (facedist > 0) {
1091 df = (outerfacethickness - facedist) / outerfacethickness;
1092 }
1093 else {
1094 df = (outerfacethickness + facedist) / outerfacethickness;
1095 }
1096
1097 *damp = df * tune * ob->pd->pdef_sbdamp;
1098
1099 df = 0.01f * expf(-100.0f * df);
1100 madd_v3_v3fl(force, d_nvect, -df);
1101 deflected = 3;
1102 }
1103 }
1104 a--;
1105 } /* while (a) */
1106 } /* if (vert_positions) */
1107 } /* if (ob->pd && ob->pd->deflect) */
1108 }
1109 } /* while () */
1110 return deflected;
1111}
1112
1113static int sb_detect_face_collisionCached(const float face_v1[3],
1114 const float face_v2[3],
1115 const float face_v3[3],
1116 float *damp,
1117 float force[3],
1118 Object *vertexowner,
1119 float time)
1120{
1121 float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1122 float t, tune = 10.0f;
1123 int a, deflected = 0;
1124
1125 aabbmin[0] = std::min({face_v1[0], face_v2[0], face_v3[0]});
1126 aabbmin[1] = std::min({face_v1[1], face_v2[1], face_v3[1]});
1127 aabbmin[2] = std::min({face_v1[2], face_v2[2], face_v3[2]});
1128 aabbmax[0] = std::max({face_v1[0], face_v2[0], face_v3[0]});
1129 aabbmax[1] = std::max({face_v1[1], face_v2[1], face_v3[1]});
1130 aabbmax[2] = std::max({face_v1[2], face_v2[2], face_v3[2]});
1131
1132 for (const auto &item : vertexowner->soft->scratch->colliderhash->items()) {
1133 Object *ob = item.key;
1134 ccd_Mesh *ccdm = item.value;
1135 {
1136 /* only with deflecting set */
1137 if (ob->pd && ob->pd->deflect) {
1138 const float (*vert_positions)[3] = nullptr;
1139 const float (*vert_positions_prev)[3] = nullptr;
1140 const int3 *vt = nullptr;
1141 const CCDF_MinMax *mima = nullptr;
1142
1143 if (ccdm) {
1144 vert_positions = ccdm->vert_positions;
1145 vt = ccdm->vert_tris;
1146 vert_positions_prev = ccdm->vert_positions_prev;
1147 mima = ccdm->mima;
1148 a = ccdm->tri_num;
1149
1150 if ((aabbmax[0] < ccdm->bbmin[0]) || (aabbmax[1] < ccdm->bbmin[1]) ||
1151 (aabbmax[2] < ccdm->bbmin[2]) || (aabbmin[0] > ccdm->bbmax[0]) ||
1152 (aabbmin[1] > ccdm->bbmax[1]) || (aabbmin[2] > ccdm->bbmax[2]))
1153 {
1154 /* boxes don't intersect */
1155 continue;
1156 }
1157 }
1158 else {
1159 /* Aye that should be cached. */
1160 CLOG_ERROR(&LOG, "missing cache error");
1161 continue;
1162 }
1163
1164 /* Use mesh. */
1165 while (a--) {
1166 if ((aabbmax[0] < mima->minx) || (aabbmin[0] > mima->maxx) ||
1167 (aabbmax[1] < mima->miny) || (aabbmin[1] > mima->maxy) ||
1168 (aabbmax[2] < mima->minz) || (aabbmin[2] > mima->maxz))
1169 {
1170 mima++;
1171 vt++;
1172 continue;
1173 }
1174
1175 if (vert_positions) {
1176
1177 copy_v3_v3(nv1, vert_positions[(*vt)[0]]);
1178 copy_v3_v3(nv2, vert_positions[(*vt)[1]]);
1179 copy_v3_v3(nv3, vert_positions[(*vt)[2]]);
1180
1181 if (vert_positions_prev) {
1182 mul_v3_fl(nv1, time);
1183 madd_v3_v3fl(nv1, vert_positions_prev[(*vt)[0]], 1.0f - time);
1184
1185 mul_v3_fl(nv2, time);
1186 madd_v3_v3fl(nv2, vert_positions_prev[(*vt)[1]], 1.0f - time);
1187
1188 mul_v3_fl(nv3, time);
1189 madd_v3_v3fl(nv3, vert_positions_prev[(*vt)[2]], 1.0f - time);
1190 }
1191 }
1192
1193 /* Switch origin to be nv2. */
1194 sub_v3_v3v3(edge1, nv1, nv2);
1195 sub_v3_v3v3(edge2, nv3, nv2);
1196 cross_v3_v3v3(d_nvect, edge2, edge1);
1197 normalize_v3(d_nvect);
1198 if (isect_line_segment_tri_v3(nv1, nv2, face_v1, face_v2, face_v3, &t, nullptr) ||
1199 isect_line_segment_tri_v3(nv2, nv3, face_v1, face_v2, face_v3, &t, nullptr) ||
1200 isect_line_segment_tri_v3(nv3, nv1, face_v1, face_v2, face_v3, &t, nullptr))
1201 {
1202 madd_v3_v3fl(force, d_nvect, -0.5f);
1203 *damp = tune * ob->pd->pdef_sbdamp;
1204 deflected = 2;
1205 }
1206 mima++;
1207 vt++;
1208 } /* while a */
1209 } /* if (ob->pd && ob->pd->deflect) */
1210 }
1211 } /* while () */
1212 return deflected;
1213}
1214
1215static void scan_for_ext_face_forces(Object *ob, float timenow)
1216{
1217 SoftBody *sb = ob->soft;
1218 BodyFace *bf;
1219 int a;
1220 float damp = 0.0f, choke = 1.0f;
1221 float tune = -10.0f;
1222 float feedback[3];
1223
1224 if (sb && sb->scratch->bodyface_num) {
1225
1226 bf = sb->scratch->bodyface;
1227 for (a = 0; a < sb->scratch->bodyface_num; a++, bf++) {
1228 bf->ext_force[0] = bf->ext_force[1] = bf->ext_force[2] = 0.0f;
1229 /* +++edges intruding. */
1230 bf->flag &= ~BFF_INTERSECT;
1231 zero_v3(feedback);
1233 sb->bpoint[bf->v2].pos,
1234 sb->bpoint[bf->v3].pos,
1235 &damp,
1236 feedback,
1237 ob,
1238 timenow))
1239 {
1240 madd_v3_v3fl(sb->bpoint[bf->v1].force, feedback, tune);
1241 madd_v3_v3fl(sb->bpoint[bf->v2].force, feedback, tune);
1242 madd_v3_v3fl(sb->bpoint[bf->v3].force, feedback, tune);
1243 // madd_v3_v3fl(bf->ext_force, feedback, tune);
1244 bf->flag |= BFF_INTERSECT;
1245 choke = min_ff(max_ff(damp, choke), 1.0f);
1246 }
1247 /* ---edges intruding. */
1248
1249 /* +++ close vertices. */
1250 if ((bf->flag & BFF_INTERSECT) == 0) {
1251 bf->flag &= ~BFF_CLOSEVERT;
1252 tune = -1.0f;
1253 zero_v3(feedback);
1255 sb->bpoint[bf->v2].pos,
1256 sb->bpoint[bf->v3].pos,
1257 &damp,
1258 feedback,
1259 ob,
1260 timenow))
1261 {
1262 madd_v3_v3fl(sb->bpoint[bf->v1].force, feedback, tune);
1263 madd_v3_v3fl(sb->bpoint[bf->v2].force, feedback, tune);
1264 madd_v3_v3fl(sb->bpoint[bf->v3].force, feedback, tune);
1265 // madd_v3_v3fl(bf->ext_force, feedback, tune);
1266 bf->flag |= BFF_CLOSEVERT;
1267 choke = min_ff(max_ff(damp, choke), 1.0f);
1268 }
1269 }
1270 /* --- close vertices. */
1271 }
1272 bf = sb->scratch->bodyface;
1273 for (a = 0; a < sb->scratch->bodyface_num; a++, bf++) {
1274 if ((bf->flag & BFF_INTERSECT) || (bf->flag & BFF_CLOSEVERT)) {
1275 sb->bpoint[bf->v1].choke2 = max_ff(sb->bpoint[bf->v1].choke2, choke);
1276 sb->bpoint[bf->v2].choke2 = max_ff(sb->bpoint[bf->v2].choke2, choke);
1277 sb->bpoint[bf->v3].choke2 = max_ff(sb->bpoint[bf->v3].choke2, choke);
1278 }
1279 }
1280 }
1281}
1282
1283/* --- the face external section. */
1284
1285/* +++ the spring external section. */
1286
1287static int sb_detect_edge_collisionCached(const float edge_v1[3],
1288 const float edge_v2[3],
1289 float *damp,
1290 float force[3],
1291 Object *vertexowner,
1292 float time)
1293{
1294 float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1295 float t, el;
1296 int a, deflected = 0;
1297
1298 minmax_v3v3_v3(aabbmin, aabbmax, edge_v1);
1299 minmax_v3v3_v3(aabbmin, aabbmax, edge_v2);
1300
1301 el = len_v3v3(edge_v1, edge_v2);
1302
1303 for (const auto &item : vertexowner->soft->scratch->colliderhash->items()) {
1304 Object *ob = item.key;
1305 ccd_Mesh *ccdm = item.value;
1306 {
1307 /* only with deflecting set */
1308 if (ob->pd && ob->pd->deflect) {
1309 const float (*vert_positions)[3] = nullptr;
1310 const float (*vert_positions_prev)[3] = nullptr;
1311 const int3 *vt = nullptr;
1312 const CCDF_MinMax *mima = nullptr;
1313
1314 if (ccdm) {
1315 vert_positions = ccdm->vert_positions;
1316 vert_positions_prev = ccdm->vert_positions_prev;
1317 vt = ccdm->vert_tris;
1318 mima = ccdm->mima;
1319 a = ccdm->tri_num;
1320
1321 if ((aabbmax[0] < ccdm->bbmin[0]) || (aabbmax[1] < ccdm->bbmin[1]) ||
1322 (aabbmax[2] < ccdm->bbmin[2]) || (aabbmin[0] > ccdm->bbmax[0]) ||
1323 (aabbmin[1] > ccdm->bbmax[1]) || (aabbmin[2] > ccdm->bbmax[2]))
1324 {
1325 /* boxes don't intersect */
1326 continue;
1327 }
1328 }
1329 else {
1330 /* Aye that should be cached. */
1331 CLOG_ERROR(&LOG, "missing cache error");
1332 continue;
1333 }
1334
1335 /* Use mesh. */
1336 while (a--) {
1337 if ((aabbmax[0] < mima->minx) || (aabbmin[0] > mima->maxx) ||
1338 (aabbmax[1] < mima->miny) || (aabbmin[1] > mima->maxy) ||
1339 (aabbmax[2] < mima->minz) || (aabbmin[2] > mima->maxz))
1340 {
1341 mima++;
1342 vt++;
1343 continue;
1344 }
1345
1346 if (vert_positions) {
1347
1348 copy_v3_v3(nv1, vert_positions[(*vt)[0]]);
1349 copy_v3_v3(nv2, vert_positions[(*vt)[1]]);
1350 copy_v3_v3(nv3, vert_positions[(*vt)[2]]);
1351
1352 if (vert_positions_prev) {
1353 mul_v3_fl(nv1, time);
1354 madd_v3_v3fl(nv1, vert_positions_prev[(*vt)[0]], 1.0f - time);
1355
1356 mul_v3_fl(nv2, time);
1357 madd_v3_v3fl(nv2, vert_positions_prev[(*vt)[1]], 1.0f - time);
1358
1359 mul_v3_fl(nv3, time);
1360 madd_v3_v3fl(nv3, vert_positions_prev[(*vt)[2]], 1.0f - time);
1361 }
1362 }
1363
1364 /* Switch origin to be nv2. */
1365 sub_v3_v3v3(edge1, nv1, nv2);
1366 sub_v3_v3v3(edge2, nv3, nv2);
1367
1368 cross_v3_v3v3(d_nvect, edge2, edge1);
1369 normalize_v3(d_nvect);
1370 if (isect_line_segment_tri_v3(edge_v1, edge_v2, nv1, nv2, nv3, &t, nullptr)) {
1371 float v1[3], v2[3];
1372 float intrusiondepth, i1, i2;
1373 sub_v3_v3v3(v1, edge_v1, nv2);
1374 sub_v3_v3v3(v2, edge_v2, nv2);
1375 i1 = dot_v3v3(v1, d_nvect);
1376 i2 = dot_v3v3(v2, d_nvect);
1377 intrusiondepth = -min_ff(i1, i2) / el;
1378 madd_v3_v3fl(force, d_nvect, intrusiondepth);
1379 *damp = ob->pd->pdef_sbdamp;
1380 deflected = 2;
1381 }
1382
1383 mima++;
1384 vt++;
1385 } /* while a */
1386 } /* if (ob->pd && ob->pd->deflect) */
1387 }
1388 } /* while () */
1389 return deflected;
1390}
1391
1393 Object *ob,
1394 float timenow,
1395 int ifirst,
1396 int ilast,
1397 ListBaseT<EffectorCache> *effectors)
1398{
1399 SoftBody *sb = ob->soft;
1400 int a;
1401 float damp;
1402 float feedback[3];
1403
1404 if (sb && sb->totspring) {
1405 for (a = ifirst; a < ilast; a++) {
1406 BodySpring *bs = &sb->bspring[a];
1407 bs->ext_force[0] = bs->ext_force[1] = bs->ext_force[2] = 0.0f;
1408 feedback[0] = feedback[1] = feedback[2] = 0.0f;
1409 bs->flag &= ~BSF_INTERSECT;
1410
1411 if (bs->springtype == SB_EDGE) {
1412 /* +++ springs colliding */
1413 if (ob->softflag & OB_SB_EDGECOLL) {
1415 sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos, &damp, feedback, ob, timenow))
1416 {
1417 add_v3_v3(bs->ext_force, feedback);
1418 bs->flag |= BSF_INTERSECT;
1419 // bs->cf=damp;
1420 bs->cf = sb->choke * 0.01f;
1421 }
1422 }
1423 /* ---- springs colliding */
1424
1425 /* +++ springs seeing wind ... n stuff depending on their orientation. */
1426 /* NOTE: we don't use `sb->mediafrict` but use `sb->aeroedge` for magnitude of effect. */
1427 if (sb->aeroedge) {
1428 float vel[3], sp[3], pr[3], force[3];
1429 float f, windfactor = 0.25f;
1430 /* See if we have wind. */
1431 if (effectors) {
1432 EffectedPoint epoint;
1433 float speed[3] = {0.0f, 0.0f, 0.0f};
1434 float pos[3];
1435 mid_v3_v3v3(pos, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1436 mid_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1437 pd_point_from_soft(scene, pos, vel, -1, &epoint);
1439 effectors, nullptr, sb->effector_weights, &epoint, force, nullptr, speed);
1440
1441 mul_v3_fl(speed, windfactor);
1442 add_v3_v3(vel, speed);
1443 }
1444 /* media in rest */
1445 else {
1446 add_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1447 }
1448 f = normalize_v3(vel);
1449 f = -0.0001f * f * f * sb->aeroedge;
1450 /* (todo) add a nice angle dependent function done for now BUT */
1451 /* still there could be some nice drag/lift function, but who needs it */
1452
1453 sub_v3_v3v3(sp, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1454 project_v3_v3v3(pr, vel, sp);
1455 sub_v3_v3(vel, pr);
1456 normalize_v3(vel);
1457 if (ob->softflag & OB_SB_AERO_ANGLE) {
1458 normalize_v3(sp);
1459 madd_v3_v3fl(bs->ext_force, vel, f * (1.0f - fabsf(dot_v3v3(vel, sp))));
1460 }
1461 else {
1462 madd_v3_v3fl(bs->ext_force, vel, f); /* to keep compatible with 2.45 release files */
1463 }
1464 }
1465 /* --- springs seeing wind */
1466 }
1467 }
1468 }
1469}
1470
1472{
1473 SB_thread_context *pctx = static_cast<SB_thread_context *>(data);
1475 pctx->scene, pctx->ob, pctx->timenow, pctx->ifirst, pctx->ilast, pctx->effectors);
1476 return nullptr;
1477}
1478
1479static void sb_sfesf_threads_run(Depsgraph *depsgraph,
1480 Scene *scene,
1481 Object *ob,
1482 float timenow,
1483 int totsprings,
1484 int *ptr_to_break_func(void))
1485{
1486 UNUSED_VARS(ptr_to_break_func);
1487 ListBaseT<ThreadSlot> threads;
1488 SB_thread_context *sb_threads;
1489 int i, totthread, left, dec;
1490
1491 /* wild guess .. may increase with better thread management 'above'
1492 * or even be UI option sb->spawn_cf_threads_nopts */
1493 int lowsprings = 100;
1494
1495 ListBaseT<EffectorCache> *effectors = BKE_effectors_create(
1496 depsgraph, ob, nullptr, ob->soft->effector_weights, false);
1497
1498 /* figure the number of threads while preventing pretty pointless threading overhead */
1499 totthread = BKE_scene_num_threads(scene);
1500 /* What if we got zillions of CPUs running but less to spread. */
1501 while ((totsprings / totthread < lowsprings) && (totthread > 1)) {
1502 totthread--;
1503 }
1504
1505 sb_threads = MEM_new_array_zeroed<SB_thread_context>(totthread, "SBSpringsThread");
1506 left = totsprings;
1507 dec = totsprings / totthread + 1;
1508 for (i = 0; i < totthread; i++) {
1509 sb_threads[i].scene = scene;
1510 sb_threads[i].ob = ob;
1511 sb_threads[i].forcetime = 0.0; /* not used here */
1512 sb_threads[i].timenow = timenow;
1513 sb_threads[i].ilast = left;
1514 left = left - dec;
1515 if (left > 0) {
1516 sb_threads[i].ifirst = left;
1517 }
1518 else {
1519 sb_threads[i].ifirst = 0;
1520 }
1521 sb_threads[i].effectors = effectors;
1522 sb_threads[i].do_deflector = false; /* not used here */
1523 sb_threads[i].fieldfactor = 0.0f; /* not used here */
1524 sb_threads[i].windfactor = 0.0f; /* not used here */
1525 sb_threads[i].nr = i;
1526 sb_threads[i].tot = totthread;
1527 }
1528 if (totthread > 1) {
1530
1531 for (i = 0; i < totthread; i++) {
1532 BLI_threadpool_insert(&threads, &sb_threads[i]);
1533 }
1534
1535 BLI_threadpool_end(&threads);
1536 }
1537 else {
1538 exec_scan_for_ext_spring_forces(&sb_threads[0]);
1539 }
1540 /* clean up */
1541 MEM_delete(sb_threads);
1542
1543 BKE_effectors_free(effectors);
1544}
1545
1546/* --- the spring external section. */
1547
1548static int choose_winner(
1549 float *w, float *pos, float *a, float *b, float *c, float *ca, float *cb, float *cc)
1550{
1551 float mindist, cp;
1552 int winner = 1;
1553 mindist = fabsf(dot_v3v3(pos, a));
1554
1555 cp = fabsf(dot_v3v3(pos, b));
1556 if (mindist < cp) {
1557 mindist = cp;
1558 winner = 2;
1559 }
1560
1561 cp = fabsf(dot_v3v3(pos, c));
1562 if (mindist < cp) {
1563 mindist = cp;
1564 winner = 3;
1565 }
1566 switch (winner) {
1567 case 1:
1568 copy_v3_v3(w, ca);
1569 break;
1570 case 2:
1571 copy_v3_v3(w, cb);
1572 break;
1573 case 3:
1574 copy_v3_v3(w, cc);
1575 }
1576 return winner;
1577}
1578
1579static int sb_detect_vertex_collisionCached(float opco[3],
1580 float facenormal[3],
1581 float *damp,
1582 float force[3],
1583 Object *vertexowner,
1584 float time,
1585 float vel[3],
1586 float *intrusion)
1587{
1588 float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3],
1589 avel[3] = {0.0, 0.0, 0.0}, vv1[3], vv2[3], vv3[3], coledge[3] = {0.0f, 0.0f, 0.0f},
1590 mindistedge = 1000.0f, outerforceaccu[3], innerforceaccu[3], facedist,
1591 /* n_mag, */ /* UNUSED */ force_mag_norm, minx, miny, minz, maxx, maxy, maxz,
1592 innerfacethickness = -0.5f, outerfacethickness = 0.2f, ee = 5.0f, ff = 0.1f, fa = 1;
1593 int a, deflected = 0, cavel = 0, ci = 0;
1594 /* init */
1595 *intrusion = 0.0f;
1596 outerforceaccu[0] = outerforceaccu[1] = outerforceaccu[2] = 0.0f;
1597 innerforceaccu[0] = innerforceaccu[1] = innerforceaccu[2] = 0.0f;
1598 /* go */
1599 Object *ob = nullptr;
1600 for (const auto &item : vertexowner->soft->scratch->colliderhash->items()) {
1601 ob = item.key;
1602 ccd_Mesh *ccdm = item.value;
1603 {
1604 /* only with deflecting set */
1605 if (ob->pd && ob->pd->deflect) {
1606 const float (*vert_positions)[3] = nullptr;
1607 const float (*vert_positions_prev)[3] = nullptr;
1608 const int3 *vt = nullptr;
1609 const CCDF_MinMax *mima = nullptr;
1610
1611 if (ccdm) {
1612 vert_positions = ccdm->vert_positions;
1613 vert_positions_prev = ccdm->vert_positions_prev;
1614 vt = ccdm->vert_tris;
1615 mima = ccdm->mima;
1616 a = ccdm->tri_num;
1617
1618 minx = ccdm->bbmin[0];
1619 miny = ccdm->bbmin[1];
1620 minz = ccdm->bbmin[2];
1621
1622 maxx = ccdm->bbmax[0];
1623 maxy = ccdm->bbmax[1];
1624 maxz = ccdm->bbmax[2];
1625
1626 if ((opco[0] < minx) || (opco[1] < miny) || (opco[2] < minz) || (opco[0] > maxx) ||
1627 (opco[1] > maxy) || (opco[2] > maxz))
1628 {
1629 /* Outside the padded bound-box -> collision object is too far away. */
1630 continue;
1631 }
1632 }
1633 else {
1634 /* Aye that should be cached. */
1635 CLOG_ERROR(&LOG, "missing cache error");
1636 continue;
1637 }
1638
1639 /* do object level stuff */
1640 /* need to have user control for that since it depends on model scale */
1641 innerfacethickness = -ob->pd->pdef_sbift;
1642 outerfacethickness = ob->pd->pdef_sboft;
1643 fa = (ff * outerfacethickness - outerfacethickness);
1644 fa *= fa;
1645 fa = 1.0f / fa;
1646 avel[0] = avel[1] = avel[2] = 0.0f;
1647 /* Use mesh. */
1648 while (a--) {
1649 if ((opco[0] < mima->minx) || (opco[0] > mima->maxx) || (opco[1] < mima->miny) ||
1650 (opco[1] > mima->maxy) || (opco[2] < mima->minz) || (opco[2] > mima->maxz))
1651 {
1652 mima++;
1653 vt++;
1654 continue;
1655 }
1656
1657 if (vert_positions) {
1658
1659 copy_v3_v3(nv1, vert_positions[(*vt)[0]]);
1660 copy_v3_v3(nv2, vert_positions[(*vt)[1]]);
1661 copy_v3_v3(nv3, vert_positions[(*vt)[2]]);
1662
1663 if (vert_positions_prev) {
1664 /* Grab the average speed of the collider vertices before we spoil nvX
1665 * hum could be done once a SB steps but then we' need to store that too
1666 * since the AABB reduced probability to get here drastically
1667 * it might be a nice tradeoff CPU <--> memory.
1668 */
1669 sub_v3_v3v3(vv1, nv1, vert_positions_prev[(*vt)[0]]);
1670 sub_v3_v3v3(vv2, nv2, vert_positions_prev[(*vt)[1]]);
1671 sub_v3_v3v3(vv3, nv3, vert_positions_prev[(*vt)[2]]);
1672
1673 mul_v3_fl(nv1, time);
1674 madd_v3_v3fl(nv1, vert_positions_prev[(*vt)[0]], 1.0f - time);
1675
1676 mul_v3_fl(nv2, time);
1677 madd_v3_v3fl(nv2, vert_positions_prev[(*vt)[1]], 1.0f - time);
1678
1679 mul_v3_fl(nv3, time);
1680 madd_v3_v3fl(nv3, vert_positions_prev[(*vt)[2]], 1.0f - time);
1681 }
1682 }
1683
1684 /* Switch origin to be nv2. */
1685 sub_v3_v3v3(edge1, nv1, nv2);
1686 sub_v3_v3v3(edge2, nv3, nv2);
1687 /* Abuse dv1 to have vertex in question at *origin* of triangle. */
1688 sub_v3_v3v3(dv1, opco, nv2);
1689
1690 cross_v3_v3v3(d_nvect, edge2, edge1);
1691 /* n_mag = */ /* UNUSED */ normalize_v3(d_nvect);
1692 facedist = dot_v3v3(dv1, d_nvect);
1693 /* so rules are */
1694
1695 if ((facedist > innerfacethickness) && (facedist < outerfacethickness)) {
1696 if (isect_point_tri_prism_v3(opco, nv1, nv2, nv3)) {
1697 force_mag_norm = float(exp(double(-ee * facedist)));
1698 if (facedist > outerfacethickness * ff) {
1699 force_mag_norm = force_mag_norm * fa * (facedist - outerfacethickness) *
1700 (facedist - outerfacethickness);
1701 }
1702 *damp = ob->pd->pdef_sbdamp;
1703 if (facedist > 0.0f) {
1704 *damp *= (1.0f - facedist / outerfacethickness);
1705 madd_v3_v3fl(outerforceaccu, d_nvect, force_mag_norm);
1706 deflected = 3;
1707 }
1708 else {
1709 madd_v3_v3fl(innerforceaccu, d_nvect, force_mag_norm);
1710 deflected = std::max(deflected, 2);
1711 }
1712 if ((vert_positions_prev) && (*damp > 0.0f)) {
1713 choose_winner(ve, opco, nv1, nv2, nv3, vv1, vv2, vv3);
1714 add_v3_v3(avel, ve);
1715 cavel++;
1716 }
1717 *intrusion += facedist;
1718 ci++;
1719 }
1720 }
1721
1722 mima++;
1723 vt++;
1724 } /* while a */
1725 } /* if (ob->pd && ob->pd->deflect) */
1726 }
1727 } /* while () */
1728
1729 if (deflected == 1) { /* no face but 'outer' edge cylinder sees vert */
1730 force_mag_norm = float(exp(double() - ee * mindistedge));
1731 if (mindistedge > outerfacethickness * ff) {
1732 force_mag_norm = force_mag_norm * fa * (mindistedge - outerfacethickness) *
1733 (mindistedge - outerfacethickness);
1734 }
1735 madd_v3_v3fl(force, coledge, force_mag_norm);
1736 *damp = ob->pd->pdef_sbdamp;
1737 if (mindistedge > 0.0f) {
1738 *damp *= (1.0f - mindistedge / outerfacethickness);
1739 }
1740 }
1741 if (deflected == 2) { /* face inner detected */
1742 add_v3_v3(force, innerforceaccu);
1743 }
1744 if (deflected == 3) { /* face outer detected */
1745 add_v3_v3(force, outerforceaccu);
1746 }
1747
1748 if (cavel) {
1749 mul_v3_fl(avel, 1.0f / float(cavel));
1750 }
1751 copy_v3_v3(vel, avel);
1752 if (ci) {
1753 *intrusion /= ci;
1754 }
1755 if (deflected) {
1756 normalize_v3_v3(facenormal, force);
1757 }
1758 return deflected;
1759}
1760
1761/* Sandbox to plug in various deflection algorithms. */
1763 float *actpos,
1764 float *facenormal,
1765 float *force,
1766 float *cf,
1767 float time,
1768 float *vel,
1769 float *intrusion)
1770{
1771 float s_actpos[3];
1772 int deflected;
1773 copy_v3_v3(s_actpos, actpos);
1775 s_actpos, facenormal, cf, force, ob, time, vel, intrusion);
1776#if 0
1777 deflected = sb_detect_vertex_collisionCachedEx(
1778 s_actpos, facenormal, cf, force, ob, time, vel, intrusion);
1779#endif
1780 return deflected;
1781}
1782
1783/* Hiding this for now, but the jacobian may pop up on other tasks - so I'd like to keep it. */
1784#if 0
1785static void dfdx_spring(int ia, int ic, int op, float dir[3], float L, float len, float factor)
1786{
1787 float m, delta_ij;
1788 int i, j;
1789 if (L < len) {
1790 for (i = 0; i < 3; i++) {
1791 for (j = 0; j < 3; j++) {
1792 delta_ij = (i == j ? (1.0f) : (0.0f));
1793 m = factor * (dir[i] * dir[j] + (1 - L / len) * (delta_ij - dir[i] * dir[j]));
1794 EIG_linear_solver_matrix_add(ia + i, op + ic + j, m);
1795 }
1796 }
1797 }
1798 else {
1799 for (i = 0; i < 3; i++) {
1800 for (j = 0; j < 3; j++) {
1801 m = factor * dir[i] * dir[j];
1802 EIG_linear_solver_matrix_add(ia + i, op + ic + j, m);
1803 }
1804 }
1805 }
1806}
1807
1808static void dfdx_goal(int ia, int ic, int op, float factor)
1809{
1810 int i;
1811 for (i = 0; i < 3; i++) {
1812 EIG_linear_solver_matrix_add(ia + i, op + ic + i, factor);
1813 }
1814}
1815
1816static void dfdv_goal(int ia, int ic, float factor)
1817{
1818 int i;
1819 for (i = 0; i < 3; i++) {
1820 EIG_linear_solver_matrix_add(ia + i, ic + i, factor);
1821 }
1822}
1823#endif /* if 0 */
1824
1825static void sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float /*forcetime*/)
1826{
1827 SoftBody *sb = ob->soft; /* is supposed to be there */
1828 BodyPoint *bp1, *bp2;
1829
1830 float dir[3], dvel[3];
1831 float distance, forcefactor, kd, absvel, projvel, kw;
1832#if 0 /* UNUSED */
1833 int ia, ic;
1834#endif
1835 /* prepare depending on which side of the spring we are on */
1836 if (bpi == bs->v1) {
1837 bp1 = &sb->bpoint[bs->v1];
1838 bp2 = &sb->bpoint[bs->v2];
1839#if 0 /* UNUSED */
1840 ia = 3 * bs->v1;
1841 ic = 3 * bs->v2;
1842#endif
1843 }
1844 else if (bpi == bs->v2) {
1845 bp1 = &sb->bpoint[bs->v2];
1846 bp2 = &sb->bpoint[bs->v1];
1847#if 0 /* UNUSED */
1848 ia = 3 * bs->v2;
1849 ic = 3 * bs->v1;
1850#endif
1851 }
1852 else {
1853 /* TODO: make this debug option. */
1854 CLOG_WARN(&LOG, "bodypoint <bpi> is not attached to spring <*bs>");
1855 return;
1856 }
1857
1858 /* do bp1 <--> bp2 elastic */
1859 sub_v3_v3v3(dir, bp1->pos, bp2->pos);
1860 distance = normalize_v3(dir);
1861 if (bs->len < distance) {
1862 iks = 1.0f / (1.0f - sb->inspring) - 1.0f; /* inner spring constants function */
1863 }
1864 else {
1865 iks = 1.0f / (1.0f - sb->inpush) - 1.0f; /* inner spring constants function */
1866 }
1867
1868 if (bs->len > 0.0f) { /* check for degenerated springs */
1869 forcefactor = iks / bs->len;
1870 }
1871 else {
1872 forcefactor = iks;
1873 }
1874 kw = (bp1->springweight + bp2->springweight) / 2.0f;
1875 kw = kw * kw;
1876 kw = kw * kw;
1877 switch (bs->springtype) {
1878 case SB_EDGE:
1879 case SB_HANDLE:
1880 forcefactor *= kw;
1881 break;
1882 case SB_BEND:
1883 forcefactor *= sb->secondspring * kw;
1884 break;
1885 case SB_STIFFQUAD:
1886 forcefactor *= sb->shearstiff * sb->shearstiff * kw;
1887 break;
1888 default:
1889 break;
1890 }
1891
1892 madd_v3_v3fl(bp1->force, dir, (bs->len - distance) * forcefactor);
1893
1894 /* do bp1 <--> bp2 viscous */
1895 sub_v3_v3v3(dvel, bp1->vec, bp2->vec);
1896 kd = sb->infrict * sb_fric_force_scale(ob);
1897 absvel = normalize_v3(dvel);
1898 projvel = dot_v3v3(dir, dvel);
1899 kd *= absvel * projvel;
1900 madd_v3_v3fl(bp1->force, dir, -kd);
1901}
1902
1903/* since this is definitely the most CPU consuming task here .. try to spread it */
1904/* core function _softbody_calc_forces_slice_in_a_thread */
1905/* result is int to be able to flag user break */
1907 Object *ob,
1908 float forcetime,
1909 float timenow,
1910 int ifirst,
1911 int ilast,
1912 int *ptr_to_break_func(void),
1913 ListBaseT<EffectorCache> *effectors,
1914 int do_deflector,
1915 float fieldfactor,
1916 float windfactor)
1917{
1918 UNUSED_VARS(ptr_to_break_func);
1919 float iks;
1920 int bb, do_selfcollision, do_springcollision, do_aero;
1921 int number_of_points_here = ilast - ifirst;
1922 SoftBody *sb = ob->soft; /* is supposed to be there */
1923 BodyPoint *bp;
1924
1925 /* initialize */
1926 if (sb) {
1927 /* check conditions for various options */
1928 /* +++ could be done on object level to squeeze out the last bits of it */
1929 do_selfcollision = ((ob->softflag & OB_SB_EDGES) && (sb->bspring) &&
1930 (ob->softflag & OB_SB_SELF));
1931 do_springcollision = do_deflector && (ob->softflag & OB_SB_EDGES) &&
1932 (ob->softflag & OB_SB_EDGECOLL);
1933 do_aero = ((sb->aeroedge) && (ob->softflag & OB_SB_EDGES));
1934 /* --- could be done on object level to squeeze out the last bits of it */
1935 }
1936 else {
1937 CLOG_ERROR(&LOG, "expected a SB here");
1938 return 999;
1939 }
1940
1941 /* Debugging. */
1942 if (sb->totpoint < ifirst) {
1943 printf("Aye 998");
1944 return 998;
1945 }
1946 /* Debugging. */
1947
1948 bp = &sb->bpoint[ifirst];
1949 for (bb = number_of_points_here; bb > 0; bb--, bp++) {
1950 /* Clear forces accumulator. */
1951 bp->force[0] = bp->force[1] = bp->force[2] = 0.0;
1952 /* naive ball self collision */
1953 /* needs to be done if goal snaps or not */
1954 if (do_selfcollision) {
1955 int attached;
1956 BodyPoint *obp;
1957 BodySpring *bs;
1958 int c, b;
1959 float velcenter[3], dvel[3], def[3];
1960 float distance;
1961 float compare;
1962 float bstune = sb->ballstiff;
1963
1964 /* Running in a slice we must not assume anything done with obp
1965 * neither alter the data of obp. */
1966 for (c = sb->totpoint, obp = sb->bpoint; c > 0; c--, obp++) {
1967 compare = (obp->colball + bp->colball);
1968 sub_v3_v3v3(def, bp->pos, obp->pos);
1969 /* rather check the AABBoxes before ever calculating the real distance */
1970 /* mathematically it is completely nuts, but performance is pretty much (3) times faster */
1971 if ((fabsf(def[0]) > compare) || (fabsf(def[1]) > compare) || (fabsf(def[2]) > compare)) {
1972 continue;
1973 }
1974 distance = normalize_v3(def);
1975 if (distance < compare) {
1976 /* exclude body points attached with a spring */
1977 attached = 0;
1978 for (b = obp->nofsprings; b > 0; b--) {
1979 bs = sb->bspring + obp->springs[b - 1];
1980 if (ELEM(ilast - bb, bs->v2, bs->v1)) {
1981 attached = 1;
1982 continue;
1983 }
1984 }
1985 if (!attached) {
1986 float f = bstune / (distance) + bstune / (compare * compare) * distance -
1987 2.0f * bstune / compare;
1988
1989 mid_v3_v3v3(velcenter, bp->vec, obp->vec);
1990 sub_v3_v3v3(dvel, velcenter, bp->vec);
1991 mul_v3_fl(dvel, _final_mass(ob, bp));
1992
1993 madd_v3_v3fl(bp->force, def, f * (1.0f - sb->balldamp));
1994 madd_v3_v3fl(bp->force, dvel, sb->balldamp);
1995 }
1996 }
1997 }
1998 }
1999 /* naive ball self collision done */
2000
2001 if (_final_goal(ob, bp) < SOFTGOALSNAP) { /* omit this bp when it snaps */
2002 float auxvect[3];
2003 float velgoal[3];
2004
2005 /* do goal stuff */
2006 if (ob->softflag & OB_SB_GOAL) {
2007 /* true elastic goal */
2008 float ks, kd;
2009 sub_v3_v3v3(auxvect, bp->pos, bp->origT);
2010 ks = 1.0f / (1.0f - _final_goal(ob, bp) * sb->goalspring) - 1.0f;
2011 bp->force[0] += -ks * (auxvect[0]);
2012 bp->force[1] += -ks * (auxvect[1]);
2013 bp->force[2] += -ks * (auxvect[2]);
2014
2015 /* Calculate damping forces generated by goals. */
2016 sub_v3_v3v3(velgoal, bp->origS, bp->origE);
2017 kd = sb->goalfrict * sb_fric_force_scale(ob);
2018 add_v3_v3v3(auxvect, velgoal, bp->vec);
2019
2020 /* Make sure friction does not become rocket motor on time reversal. */
2021 if (forcetime > 0.0f) {
2022 bp->force[0] -= kd * (auxvect[0]);
2023 bp->force[1] -= kd * (auxvect[1]);
2024 bp->force[2] -= kd * (auxvect[2]);
2025 }
2026 else {
2027 bp->force[0] -= kd * (velgoal[0] - bp->vec[0]);
2028 bp->force[1] -= kd * (velgoal[1] - bp->vec[1]);
2029 bp->force[2] -= kd * (velgoal[2] - bp->vec[2]);
2030 }
2031 }
2032 /* done goal stuff */
2033
2034 /* gravitation */
2036 float gravity[3];
2037 copy_v3_v3(gravity, scene->physics_settings.gravity);
2038
2039 /* Individual mass of node here. */
2040 mul_v3_fl(gravity,
2041 sb_grav_force_scale(ob) * _final_mass(ob, bp) *
2043
2044 add_v3_v3(bp->force, gravity);
2045 }
2046
2047 /* particle field & vortex */
2048 if (effectors) {
2049 EffectedPoint epoint;
2050 float kd;
2051 float force[3] = {0.0f, 0.0f, 0.0f};
2052 float speed[3] = {0.0f, 0.0f, 0.0f};
2053
2054 /* just for calling function once */
2055 float eval_sb_fric_force_scale = sb_fric_force_scale(ob);
2056
2057 pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint - bp, &epoint);
2059 effectors, nullptr, sb->effector_weights, &epoint, force, nullptr, speed);
2060
2061 /* Apply force-field. */
2062 mul_v3_fl(force, fieldfactor * eval_sb_fric_force_scale);
2063 add_v3_v3(bp->force, force);
2064
2065 /* BP friction in moving media */
2066 kd = sb->mediafrict * eval_sb_fric_force_scale;
2067 bp->force[0] -= kd * (bp->vec[0] + windfactor * speed[0] / eval_sb_fric_force_scale);
2068 bp->force[1] -= kd * (bp->vec[1] + windfactor * speed[1] / eval_sb_fric_force_scale);
2069 bp->force[2] -= kd * (bp->vec[2] + windfactor * speed[2] / eval_sb_fric_force_scale);
2070 /* now we'll have nice centrifugal effect for vortex */
2071 }
2072 else {
2073 /* BP friction in media (not) moving. */
2074 float kd = sb->mediafrict * sb_fric_force_scale(ob);
2075 /* assume it to be proportional to actual velocity */
2076 bp->force[0] -= bp->vec[0] * kd;
2077 bp->force[1] -= bp->vec[1] * kd;
2078 bp->force[2] -= bp->vec[2] * kd;
2079 /* friction in media done */
2080 }
2081 /* +++cached collision targets */
2082 bp->choke = 0.0f;
2083 bp->choke2 = 0.0f;
2084 bp->loc_flag &= ~SBF_DOFUZZY;
2085 if (do_deflector && !(bp->loc_flag & SBF_OUTOFCOLLISION)) {
2086 float cfforce[3], defforce[3] = {0.0f, 0.0f, 0.0f}, vel[3] = {0.0f, 0.0f, 0.0f},
2087 facenormal[3], cf = 1.0f, intrusion;
2088 float kd = 1.0f;
2089
2090 if (sb_deflect_face(ob, bp->pos, facenormal, defforce, &cf, timenow, vel, &intrusion)) {
2091 if (intrusion < 0.0f) {
2092 sb->scratch->flag |= SBF_DOFUZZY;
2093 bp->loc_flag |= SBF_DOFUZZY;
2094 bp->choke = sb->choke * 0.01f;
2095 }
2096
2097 sub_v3_v3v3(cfforce, bp->vec, vel);
2098 madd_v3_v3fl(bp->force, cfforce, -cf * 50.0f);
2099
2100 madd_v3_v3fl(bp->force, defforce, kd);
2101 }
2102 }
2103 /* ---cached collision targets */
2104
2105 /* +++springs */
2106 iks = 1.0f / (1.0f - sb->inspring) - 1.0f; /* inner spring constants function */
2107 if (ob->softflag & OB_SB_EDGES) {
2108 if (sb->bspring) { /* Spring list exists at all? */
2109 int b;
2110 BodySpring *bs;
2111 for (b = bp->nofsprings; b > 0; b--) {
2112 bs = sb->bspring + bp->springs[b - 1];
2113 if (do_springcollision || do_aero) {
2114 add_v3_v3(bp->force, bs->ext_force);
2115 if (bs->flag & BSF_INTERSECT) {
2116 bp->choke = bs->cf;
2117 }
2118 }
2119 // sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float forcetime)
2120 sb_spring_force(ob, ilast - bb, bs, iks, forcetime);
2121 } /* loop springs. */
2122 } /* existing spring list. */
2123 } /* Any edges. */
2124 /* ---springs */
2125 } /* Omit on snap. */
2126 } /* Loop all bp's. */
2127 return 0; /* Done fine. */
2128}
2129
2131{
2132 SB_thread_context *pctx = static_cast<SB_thread_context *>(data);
2134 pctx->ob,
2135 pctx->forcetime,
2136 pctx->timenow,
2137 pctx->ifirst,
2138 pctx->ilast,
2139 nullptr,
2140 pctx->effectors,
2141 pctx->do_deflector,
2142 pctx->fieldfactor,
2143 pctx->windfactor);
2144 return nullptr;
2145}
2146
2147static void sb_cf_threads_run(Scene *scene,
2148 Object *ob,
2149 float forcetime,
2150 float timenow,
2151 int totpoint,
2152 int *ptr_to_break_func(void),
2153 ListBaseT<EffectorCache> *effectors,
2154 int do_deflector,
2155 float fieldfactor,
2156 float windfactor)
2157{
2158 UNUSED_VARS(ptr_to_break_func);
2159 ListBaseT<ThreadSlot> threads;
2160 SB_thread_context *sb_threads;
2161 int i, totthread, left, dec;
2162
2163 /* wild guess .. may increase with better thread management 'above'
2164 * or even be UI option sb->spawn_cf_threads_nopts. */
2165 int lowpoints = 100;
2166
2167 /* figure the number of threads while preventing pretty pointless threading overhead */
2168 totthread = BKE_scene_num_threads(scene);
2169 /* What if we got zillions of CPUs running but less to spread. */
2170 while ((totpoint / totthread < lowpoints) && (totthread > 1)) {
2171 totthread--;
2172 }
2173
2174 // printf("sb_cf_threads_run spawning %d threads\n", totthread);
2175
2176 sb_threads = MEM_new_array_zeroed<SB_thread_context>(totthread, "SBThread");
2177 left = totpoint;
2178 dec = totpoint / totthread + 1;
2179 for (i = 0; i < totthread; i++) {
2180 sb_threads[i].scene = scene;
2181 sb_threads[i].ob = ob;
2182 sb_threads[i].forcetime = forcetime;
2183 sb_threads[i].timenow = timenow;
2184 sb_threads[i].ilast = left;
2185 left = left - dec;
2186 if (left > 0) {
2187 sb_threads[i].ifirst = left;
2188 }
2189 else {
2190 sb_threads[i].ifirst = 0;
2191 }
2192 sb_threads[i].effectors = effectors;
2193 sb_threads[i].do_deflector = do_deflector;
2194 sb_threads[i].fieldfactor = fieldfactor;
2195 sb_threads[i].windfactor = windfactor;
2196 sb_threads[i].nr = i;
2197 sb_threads[i].tot = totthread;
2198 }
2199
2200 if (totthread > 1) {
2201 BLI_threadpool_init(&threads, exec_softbody_calc_forces, totthread);
2202
2203 for (i = 0; i < totthread; i++) {
2204 BLI_threadpool_insert(&threads, &sb_threads[i]);
2205 }
2206
2207 BLI_threadpool_end(&threads);
2208 }
2209 else {
2210 exec_softbody_calc_forces(&sb_threads[0]);
2211 }
2212 /* clean up */
2213 MEM_delete(sb_threads);
2214}
2215
2217 Depsgraph *depsgraph, Scene *scene, Object *ob, float forcetime, float timenow)
2218{
2219 /* rule we never alter free variables :bp->vec bp->pos in here !
2220 * this will ruin adaptive stepsize AKA heun! (BM)
2221 */
2222 SoftBody *sb = ob->soft; /* is supposed to be there */
2223 // BodyPoint *bproot; /* UNUSED */
2224 // float gravity; /* UNUSED */
2225 // float iks;
2226 float fieldfactor = -1.0f, windfactor = 0.25;
2227 int do_deflector /* , do_selfcollision */, do_springcollision, do_aero;
2228
2229 // gravity = sb->grav * sb_grav_force_scale(ob); /* UNUSED */
2230
2231 /* check conditions for various options */
2232 do_deflector = query_external_colliders(depsgraph, sb->collision_group);
2233#if 0
2234 do_selfcollision = ((ob->softflag & OB_SB_EDGES) && (sb->bspring) &&
2235 (ob->softflag & OB_SB_SELF));
2236#endif
2237 do_springcollision = do_deflector && (ob->softflag & OB_SB_EDGES) &&
2238 (ob->softflag & OB_SB_EDGECOLL);
2239 do_aero = ((sb->aeroedge) && (ob->softflag & OB_SB_EDGES));
2240
2241 // iks = 1.0f / (1.0f - sb->inspring) - 1.0f; /* Inner spring constants function. */ /* UNUSED */
2242 // bproot = sb->bpoint; /* Need this for proper spring addressing. */ /* UNUSED */
2243
2244 if (do_springcollision || do_aero) {
2245 sb_sfesf_threads_run(depsgraph, scene, ob, timenow, sb->totspring, nullptr);
2246 }
2247
2248 /* After spring scan because it uses effectors too. */
2249 ListBaseT<EffectorCache> *effectors = BKE_effectors_create(
2250 depsgraph, ob, nullptr, sb->effector_weights, false);
2251
2252 if (do_deflector) {
2253 float defforce[3];
2254 do_deflector = sb_detect_aabb_collisionCached(defforce, ob, timenow);
2255 }
2256
2257 sb_cf_threads_run(scene,
2258 ob,
2259 forcetime,
2260 timenow,
2261 sb->totpoint,
2262 nullptr,
2263 effectors,
2264 do_deflector,
2265 fieldfactor,
2266 windfactor);
2267
2268 /* finally add forces caused by face collision */
2269 if (ob->softflag & OB_SB_FACECOLL) {
2270 scan_for_ext_face_forces(ob, timenow);
2271 }
2272
2273 /* finish matrix and solve */
2274 BKE_effectors_free(effectors);
2275}
2276
2277static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err, int mid_flags)
2278{
2279 /* time evolution */
2280 /* actually does an explicit euler step mode == 0 */
2281 /* or heun ~ 2nd order runge-kutta steps, mode 1, 2 */
2282 SoftBody *sb = ob->soft; /* is supposed to be there */
2283 BodyPoint *bp;
2284 float dx[3] = {0}, dv[3], aabbmin[3], aabbmax[3], cm[3] = {0.0f, 0.0f, 0.0f};
2285 float timeovermass /*, freezeloc=0.00001f, freezeforce=0.00000000001f*/;
2286 float maxerrpos = 0.0f, maxerrvel = 0.0f;
2287 int a, fuzzy = 0;
2288
2289 forcetime *= sb_time_scale(ob);
2290
2291 aabbmin[0] = aabbmin[1] = aabbmin[2] = 1e20f;
2292 aabbmax[0] = aabbmax[1] = aabbmax[2] = -1e20f;
2293
2294 /* old one with homogeneous masses */
2295 /* claim a minimum mass for vertex */
2296#if 0
2297 if (sb->nodemass > 0.009999f) {
2298 timeovermass = forcetime / sb->nodemass;
2299 }
2300 else {
2301 timeovermass = forcetime / 0.009999f;
2302 }
2303#endif
2304
2305 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2306 /* Now we have individual masses. */
2307 /* claim a minimum mass for vertex */
2308 if (_final_mass(ob, bp) > 0.009999f) {
2309 timeovermass = forcetime / _final_mass(ob, bp);
2310 }
2311 else {
2312 timeovermass = forcetime / 0.009999f;
2313 }
2314
2315 if (_final_goal(ob, bp) < SOFTGOALSNAP) {
2316 /* this makes t~ = t */
2317 if (mid_flags & MID_PRESERVE) {
2318 copy_v3_v3(dx, bp->vec);
2319 }
2320
2335 mul_v3_fl(bp->force, timeovermass); /* individual mass of node here */
2336 /* some nasty if's to have heun in here too */
2337 copy_v3_v3(dv, bp->force);
2338
2339 if (mode == 1) {
2340 copy_v3_v3(bp->prevvec, bp->vec);
2341 copy_v3_v3(bp->prevdv, dv);
2342 }
2343
2344 if (mode == 2) {
2345 /* be optimistic and execute step */
2346 bp->vec[0] = bp->prevvec[0] + 0.5f * (dv[0] + bp->prevdv[0]);
2347 bp->vec[1] = bp->prevvec[1] + 0.5f * (dv[1] + bp->prevdv[1]);
2348 bp->vec[2] = bp->prevvec[2] + 0.5f * (dv[2] + bp->prevdv[2]);
2349 /* compare euler to heun to estimate error for step sizing */
2350 maxerrvel = max_ff(maxerrvel, fabsf(dv[0] - bp->prevdv[0]));
2351 maxerrvel = max_ff(maxerrvel, fabsf(dv[1] - bp->prevdv[1]));
2352 maxerrvel = max_ff(maxerrvel, fabsf(dv[2] - bp->prevdv[2]));
2353 }
2354 else {
2355 add_v3_v3(bp->vec, bp->force);
2356 }
2357
2358 /* This makes `t~ = t+dt`. */
2359 if (!(mid_flags & MID_PRESERVE)) {
2360 copy_v3_v3(dx, bp->vec);
2361 }
2362
2363 /* So here is: `(x)'= v(elocity)`.
2364 * The euler step for location then becomes:
2365 * `x(t + dt) = x(t) + v(t~) * dt` */
2366 mul_v3_fl(dx, forcetime);
2367
2368 /* the freezer coming sooner or later */
2369#if 0
2370 if ((dot_v3v3(dx, dx) < freezeloc) && (dot_v3v3(bp->force, bp->force) < freezeforce)) {
2371 bp->frozen /= 2;
2372 }
2373 else {
2374 bp->frozen = min_ff(bp->frozen * 1.05f, 1.0f);
2375 }
2376 mul_v3_fl(dx, bp->frozen);
2377#endif
2378 /* again some nasty if's to have heun in here too */
2379 if (mode == 1) {
2380 copy_v3_v3(bp->prevpos, bp->pos);
2381 copy_v3_v3(bp->prevdx, dx);
2382 }
2383
2384 if (mode == 2) {
2385 bp->pos[0] = bp->prevpos[0] + 0.5f * (dx[0] + bp->prevdx[0]);
2386 bp->pos[1] = bp->prevpos[1] + 0.5f * (dx[1] + bp->prevdx[1]);
2387 bp->pos[2] = bp->prevpos[2] + 0.5f * (dx[2] + bp->prevdx[2]);
2388 maxerrpos = max_ff(maxerrpos, fabsf(dx[0] - bp->prevdx[0]));
2389 maxerrpos = max_ff(maxerrpos, fabsf(dx[1] - bp->prevdx[1]));
2390 maxerrpos = max_ff(maxerrpos, fabsf(dx[2] - bp->prevdx[2]));
2391
2392 /* bp->choke is set when we need to pull a vertex or edge out of the collider.
2393 * the collider object signals to get out by pushing hard. on the other hand
2394 * we don't want to end up in deep space so we add some <viscosity>
2395 * to balance that out */
2396 if (bp->choke2 > 0.0f) {
2397 mul_v3_fl(bp->vec, (1.0f - bp->choke2));
2398 }
2399 if (bp->choke > 0.0f) {
2400 mul_v3_fl(bp->vec, (1.0f - bp->choke));
2401 }
2402 }
2403 else {
2404 add_v3_v3(bp->pos, dx);
2405 }
2406 } /*snap*/
2407 /* so while we are looping BPs anyway do statistics on the fly */
2408 minmax_v3v3_v3(aabbmin, aabbmax, bp->pos);
2409 if (bp->loc_flag & SBF_DOFUZZY) {
2410 fuzzy = 1;
2411 }
2412 } /*for*/
2413
2414 if (sb->totpoint) {
2415 mul_v3_fl(cm, 1.0f / sb->totpoint);
2416 }
2417 if (sb->scratch) {
2418 copy_v3_v3(sb->scratch->aabbmin, aabbmin);
2419 copy_v3_v3(sb->scratch->aabbmax, aabbmax);
2420 }
2421
2422 if (err) { /* so step size will be controlled by biggest difference in slope */
2423 if (sb->solverflags & SBSO_OLDERR) {
2424 *err = max_ff(maxerrpos, maxerrvel);
2425 }
2426 else {
2427 *err = maxerrpos;
2428 }
2429 // printf("EP %f EV %f\n", maxerrpos, maxerrvel);
2430 if (fuzzy) {
2431 *err /= sb->fuzzyness;
2432 }
2433 }
2434}
2435
2436/* used by heun when it overshoots */
2438{
2439 SoftBody *sb = ob->soft; /* is supposed to be there. */
2440 BodyPoint *bp;
2441 int a;
2442
2443 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2444 copy_v3_v3(bp->vec, bp->prevvec);
2445 copy_v3_v3(bp->pos, bp->prevpos);
2446 }
2447}
2448
2449#if 0
2450static void softbody_store_step(Object *ob)
2451{
2452 SoftBody *sb = ob->soft; /* is supposed to be there. */
2453 BodyPoint *bp;
2454 int a;
2455
2456 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2457 copy_v3_v3(bp->prevvec, bp->vec);
2458 copy_v3_v3(bp->prevpos, bp->pos);
2459 }
2460}
2461
2462/* used by predictors and correctors */
2463static void softbody_store_state(Object *ob, float *ppos, float *pvel)
2464{
2465 SoftBody *sb = ob->soft; /* is supposed to be there. */
2466 BodyPoint *bp;
2467 int a;
2468 float *pp = ppos, *pv = pvel;
2469
2470 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2471
2472 copy_v3_v3(pv, bp->vec);
2473 pv += 3;
2474
2475 copy_v3_v3(pp, bp->pos);
2476 pp += 3;
2477 }
2478}
2479
2480/* used by predictors and correctors */
2481static void softbody_retrieve_state(Object *ob, float *ppos, float *pvel)
2482{
2483 SoftBody *sb = ob->soft; /* is supposed to be there. */
2484 BodyPoint *bp;
2485 int a;
2486 float *pp = ppos, *pv = pvel;
2487
2488 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2489
2490 copy_v3_v3(bp->vec, pv);
2491 pv += 3;
2492
2493 copy_v3_v3(bp->pos, pp);
2494 pp += 3;
2495 }
2496}
2497
2498/* used by predictors and correctors */
2499static void softbody_swap_state(Object *ob, float *ppos, float *pvel)
2500{
2501 SoftBody *sb = ob->soft; /* is supposed to be there. */
2502 BodyPoint *bp;
2503 int a;
2504 float *pp = ppos, *pv = pvel;
2505 float temp[3];
2506
2507 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2508
2509 copy_v3_v3(temp, bp->vec);
2510 copy_v3_v3(bp->vec, pv);
2511 copy_v3_v3(pv, temp);
2512 pv += 3;
2513
2514 copy_v3_v3(temp, bp->pos);
2515 copy_v3_v3(bp->pos, pp);
2516 copy_v3_v3(pp, temp);
2517 pp += 3;
2518 }
2519}
2520#endif
2521
2530{
2531 SoftBody *sb = ob->soft; /* is supposed to be there */
2532 BodyPoint *bp;
2533 int a;
2534
2535 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2536 if (_final_goal(ob, bp) >= SOFTGOALSNAP) {
2537 copy_v3_v3(bp->prevpos, bp->pos);
2538 copy_v3_v3(bp->pos, bp->origT);
2539 }
2540 }
2541}
2542
2544{
2545 SoftBody *sb = ob->soft;
2546 BodySpring *bs;
2547 BodyPoint *bp1, *bp2;
2548 int a;
2549 float b, l, r;
2550
2551 if (sb && sb->totspring) {
2552 b = sb->plastic;
2553 for (a = 0; a < sb->totspring; a++) {
2554 bs = &sb->bspring[a];
2555 bp1 = &sb->bpoint[bs->v1];
2556 bp2 = &sb->bpoint[bs->v2];
2557 l = len_v3v3(bp1->pos, bp2->pos);
2558 r = bs->len / l;
2559 if ((r > 1.05f) || (r < 0.95f)) {
2560 bs->len = ((100.0f - b) * bs->len + b * l) / 100.0f;
2561 }
2562 }
2563 }
2564}
2565
2566/* expects full initialized softbody */
2567static void interpolate_exciter(Object *ob, int timescale, int time)
2568{
2569 SoftBody *sb = ob->soft;
2570 BodyPoint *bp;
2571 float f;
2572 int a;
2573
2574 f = float(time) / float(timescale);
2575
2576 for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) {
2577 bp->origT[0] = bp->origS[0] + f * (bp->origE[0] - bp->origS[0]);
2578 bp->origT[1] = bp->origS[1] + f * (bp->origE[1] - bp->origS[1]);
2579 bp->origT[2] = bp->origS[2] + f * (bp->origE[2] - bp->origS[2]);
2580 if (_final_goal(ob, bp) >= SOFTGOALSNAP) {
2581 bp->vec[0] = bp->origE[0] - bp->origS[0];
2582 bp->vec[1] = bp->origE[1] - bp->origS[1];
2583 bp->vec[2] = bp->origE[2] - bp->origS[2];
2584 }
2585 }
2586}
2587
2588/* ************ converters ********** */
2589
2590/* for each object type we need;
2591 * - xxxx_to_softbody(Object *ob) : a full (new) copy, creates SB geometry
2592 */
2593
2594/* Resetting a Mesh SB object's springs */
2595/* Spring length are calculated from 'raw' mesh vertices that are NOT altered by modifier stack. */
2597{
2598 SoftBody *sb;
2599 Mesh *mesh = id_cast<Mesh *>(ob->data);
2600 BodyPoint *bp;
2601 int a;
2602 float scale = 1.0f;
2603 const Span<float3> positions = mesh->vert_positions();
2604
2605 sb = ob->soft;
2606 if (mesh && sb) {
2607 /* using bp->origS as a container for spring calculations here
2608 * will be overwritten sbObjectStep() to receive
2609 * actual modifier stack vert_positions
2610 */
2611 if (mesh->verts_num) {
2612 bp = ob->soft->bpoint;
2613 for (a = 0; a < mesh->verts_num; a++, bp++) {
2614 copy_v3_v3(bp->origS, positions[a]);
2615 mul_m4_v3(ob->object_to_world().ptr(), bp->origS);
2616 }
2617 }
2618 /* recalculate spring length for meshes here */
2619 /* public version shrink to fit */
2620 if (sb->springpreload != 0) {
2621 scale = sb->springpreload / 100.0f;
2622 }
2623 for (a = 0; a < sb->totspring; a++) {
2624 BodySpring *bs = &sb->bspring[a];
2625 bs->len = scale * len_v3v3(sb->bpoint[bs->v1].origS, sb->bpoint[bs->v2].origS);
2626 }
2627 }
2628}
2629
2630/* makes totally fresh start situation */
2631static void mesh_to_softbody(Object *ob)
2632{
2633 SoftBody *sb;
2634 Mesh *mesh = id_cast<Mesh *>(ob->data);
2635 const Span<int2> edges = mesh->edges();
2636 BodyPoint *bp;
2637 int a, totedge;
2638 int defgroup_index, defgroup_index_mass, defgroup_index_spring;
2639
2640 if (ob->softflag & OB_SB_EDGES) {
2641 totedge = mesh->edges_num;
2642 }
2643 else {
2644 totedge = 0;
2645 }
2646
2647 /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2648 renew_softbody(ob, mesh->verts_num, totedge);
2649
2650 /* we always make body points */
2651 sb = ob->soft;
2652 bp = sb->bpoint;
2653
2654 const MDeformVert *dvert = mesh->deform_verts().data();
2655
2656 defgroup_index = dvert ? (sb->vertgroup - 1) : -1;
2657 defgroup_index_mass = dvert ? BKE_id_defgroup_name_index(&mesh->id, sb->namedVG_Mass) : -1;
2658 defgroup_index_spring = dvert ? BKE_id_defgroup_name_index(&mesh->id, sb->namedVG_Spring_K) : -1;
2659
2660 for (a = 0; a < mesh->verts_num; a++, bp++) {
2661 /* get scalar values needed *per vertex* from vertex group functions,
2662 * so we can *paint* them nicely ..
2663 * they are normalized [0.0..1.0] so may be we need amplitude for scale
2664 * which can be done by caller but still .. i'd like it to go this way
2665 */
2666
2667 if (ob->softflag & OB_SB_GOAL) {
2668 BLI_assert(bp->goal == sb->defgoal);
2669 }
2670 if ((ob->softflag & OB_SB_GOAL) && (defgroup_index != -1)) {
2671 bp->goal *= BKE_defvert_find_weight(&dvert[a], defgroup_index);
2672 }
2673
2674 /* to proof the concept
2675 * this enables per vertex *mass painting*
2676 */
2677
2678 if (defgroup_index_mass != -1) {
2679 bp->mass *= BKE_defvert_find_weight(&dvert[a], defgroup_index_mass);
2680 }
2681
2682 if (defgroup_index_spring != -1) {
2683 bp->springweight *= BKE_defvert_find_weight(&dvert[a], defgroup_index_spring);
2684 }
2685 }
2686
2687 /* but we only optionally add body edge springs */
2688 if (ob->softflag & OB_SB_EDGES) {
2689 if (!edges.is_empty()) {
2690 for (const int i : edges.index_range()) {
2691 sb->bspring[i].v1 = edges[i][0];
2692 sb->bspring[i].v2 = edges[i][1];
2693 sb->bspring[i].springtype = SB_EDGE;
2694 }
2695
2696 /* insert *diagonal* springs in quads if desired */
2697 if (ob->softflag & OB_SB_QUADS) {
2699 }
2700
2701 build_bps_springlist(ob); /* Scan for springs attached to body-points *once*. */
2702 /* insert *other second order* springs if desired */
2703 if (sb->secondspring > 0.0000001f) {
2704 /* Exploits the first run of `build_bps_springlist(ob)`. */
2706 /* yes we need to do it again. */
2708 }
2709 springs_from_mesh(ob); /* write the *rest*-length of the springs */
2710 if (ob->softflag & OB_SB_SELF) {
2712 }
2713 }
2714 }
2715}
2716
2718{
2719 SoftBody *sb = ob->soft;
2720 const Mesh *mesh = id_cast<const Mesh *>(ob->data);
2721 BodyFace *bodyface;
2722 int a;
2723 const Span<int> corner_verts = mesh->corner_verts();
2724
2725 /* Allocate and copy faces. */
2726
2727 sb->scratch->bodyface_num = poly_to_tri_count(mesh->faces_num, mesh->corners_num);
2728 Array<int3> corner_tris(sb->scratch->bodyface_num);
2730 mesh->vert_positions(), mesh->faces(), mesh->corner_verts(), corner_tris);
2731
2733 size_t(sb->scratch->bodyface_num), "SB_body_Faces");
2734
2735 for (a = 0; a < sb->scratch->bodyface_num; a++, bodyface++) {
2736 bodyface->v1 = corner_verts[corner_tris[a][0]];
2737 bodyface->v2 = corner_verts[corner_tris[a][1]];
2738 bodyface->v3 = corner_verts[corner_tris[a][2]];
2739 zero_v3(bodyface->ext_force);
2740 bodyface->ext_force[0] = bodyface->ext_force[1] = bodyface->ext_force[2] = 0.0f;
2741 bodyface->flag = 0;
2742 }
2743}
2745{
2746 SoftBody *sb = ob->soft;
2747 ReferenceVert *rp;
2748 BodyPoint *bp;
2749 float accu_pos[3] = {0.0f, 0.0f, 0.0f};
2750 float accu_mass = 0.0f;
2751 int a;
2752
2754 "SB_Reference");
2755 bp = ob->soft->bpoint;
2756 rp = sb->scratch->Ref.ivert;
2757 for (a = 0; a < sb->totpoint; a++, rp++, bp++) {
2758 copy_v3_v3(rp->pos, bp->pos);
2759 add_v3_v3(accu_pos, bp->pos);
2760 accu_mass += _final_mass(ob, bp);
2761 }
2762 mul_v3_fl(accu_pos, 1.0f / accu_mass);
2763 copy_v3_v3(sb->scratch->Ref.com, accu_pos);
2764 // printf("reference_to_scratch\n");
2765}
2766
2771static float globallen(float *v1, float *v2, Object *ob)
2772{
2773 float p1[3], p2[3];
2774 copy_v3_v3(p1, v1);
2775 mul_m4_v3(ob->object_to_world().ptr(), p1);
2776 copy_v3_v3(p2, v2);
2777 mul_m4_v3(ob->object_to_world().ptr(), p2);
2778 return len_v3v3(p1, p2);
2779}
2780
2781static void makelatticesprings(Lattice *lt, BodySpring *bs, int dostiff, Object *ob)
2782{
2783 BPoint *bp = lt->def, *bpu;
2784 int u, v, w, dv, dw, bpc = 0, bpuc;
2785
2786 dv = lt->pntsu;
2787 dw = dv * lt->pntsv;
2788
2789 for (w = 0; w < lt->pntsw; w++) {
2790
2791 for (v = 0; v < lt->pntsv; v++) {
2792
2793 for (u = 0, bpuc = 0, bpu = nullptr; u < lt->pntsu; u++, bp++, bpc++) {
2794
2795 if (w) {
2796 bs->v1 = bpc;
2797 bs->v2 = bpc - dw;
2798 bs->springtype = SB_EDGE;
2799 bs->len = globallen((bp - dw)->vec, bp->vec, ob);
2800 bs++;
2801 }
2802 if (v) {
2803 bs->v1 = bpc;
2804 bs->v2 = bpc - dv;
2805 bs->springtype = SB_EDGE;
2806 bs->len = globallen((bp - dv)->vec, bp->vec, ob);
2807 bs++;
2808 }
2809 if (u) {
2810 bs->v1 = bpuc;
2811 bs->v2 = bpc;
2812 bs->springtype = SB_EDGE;
2813 bs->len = globallen((bpu)->vec, bp->vec, ob);
2814 bs++;
2815 }
2816
2817 if (dostiff) {
2818
2819 if (w) {
2820 if (v && u) {
2821 bs->v1 = bpc;
2822 bs->v2 = bpc - dw - dv - 1;
2823 bs->springtype = SB_BEND;
2824 bs->len = globallen((bp - dw - dv - 1)->vec, bp->vec, ob);
2825 bs++;
2826 }
2827 if ((v < lt->pntsv - 1) && (u != 0)) {
2828 bs->v1 = bpc;
2829 bs->v2 = bpc - dw + dv - 1;
2830 bs->springtype = SB_BEND;
2831 bs->len = globallen((bp - dw + dv - 1)->vec, bp->vec, ob);
2832 bs++;
2833 }
2834 }
2835
2836 if (w < lt->pntsw - 1) {
2837 if (v && u) {
2838 bs->v1 = bpc;
2839 bs->v2 = bpc + dw - dv - 1;
2840 bs->springtype = SB_BEND;
2841 bs->len = globallen((bp + dw - dv - 1)->vec, bp->vec, ob);
2842 bs++;
2843 }
2844 if ((v < lt->pntsv - 1) && (u != 0)) {
2845 bs->v1 = bpc;
2846 bs->v2 = bpc + dw + dv - 1;
2847 bs->springtype = SB_BEND;
2848 bs->len = globallen((bp + dw + dv - 1)->vec, bp->vec, ob);
2849 bs++;
2850 }
2851 }
2852 }
2853 bpu = bp;
2854 bpuc = bpc;
2855 }
2856 }
2857 }
2858}
2859
2860/* makes totally fresh start situation */
2862{
2863 Lattice *lt = id_cast<Lattice *>(ob->data);
2864 SoftBody *sb;
2865 int totvert, totspring = 0, a;
2866 BodyPoint *bp;
2867 BPoint *bpnt = lt->def;
2868 int defgroup_index, defgroup_index_mass, defgroup_index_spring;
2869
2870 totvert = lt->pntsu * lt->pntsv * lt->pntsw;
2871
2872 if (ob->softflag & OB_SB_EDGES) {
2873 totspring = ((lt->pntsu - 1) * lt->pntsv + (lt->pntsv - 1) * lt->pntsu) * lt->pntsw +
2874 lt->pntsu * lt->pntsv * (lt->pntsw - 1);
2875 if (ob->softflag & OB_SB_QUADS) {
2876 totspring += 4 * (lt->pntsu - 1) * (lt->pntsv - 1) * (lt->pntsw - 1);
2877 }
2878 }
2879
2880 /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2881 renew_softbody(ob, totvert, totspring);
2882 sb = ob->soft; /* can be created in renew_softbody() */
2883 bp = sb->bpoint;
2884
2885 defgroup_index = lt->dvert ? (sb->vertgroup - 1) : -1;
2886 defgroup_index_mass = lt->dvert ? BKE_id_defgroup_name_index(&lt->id, sb->namedVG_Mass) : -1;
2887 defgroup_index_spring = lt->dvert ? BKE_id_defgroup_name_index(&lt->id, sb->namedVG_Spring_K) :
2888 -1;
2889
2890 /* same code used as for mesh vertices */
2891 for (a = 0; a < totvert; a++, bp++, bpnt++) {
2892
2893 if (ob->softflag & OB_SB_GOAL) {
2894 BLI_assert(bp->goal == sb->defgoal);
2895 }
2896
2897 if ((ob->softflag & OB_SB_GOAL) && (defgroup_index != -1)) {
2898 bp->goal *= BKE_defvert_find_weight(&lt->dvert[a], defgroup_index);
2899 }
2900 else {
2901 bp->goal *= bpnt->weight;
2902 }
2903
2904 if (defgroup_index_mass != -1) {
2905 bp->mass *= BKE_defvert_find_weight(&lt->dvert[a], defgroup_index_mass);
2906 }
2907
2908 if (defgroup_index_spring != -1) {
2909 bp->springweight *= BKE_defvert_find_weight(&lt->dvert[a], defgroup_index_spring);
2910 }
2911 }
2912
2913 /* create some helper edges to enable SB lattice to be useful at all */
2914 if (ob->softflag & OB_SB_EDGES) {
2915 makelatticesprings(lt, ob->soft->bspring, ob->softflag & OB_SB_QUADS, ob);
2916 build_bps_springlist(ob); /* link bps to springs */
2917 if (ob->softflag & OB_SB_SELF) {
2919 }
2920 }
2921}
2922
2923/* makes totally fresh start situation */
2925{
2926 Curve *cu = id_cast<Curve *>(ob->data);
2927 SoftBody *sb;
2928 BodyPoint *bp;
2929 BodySpring *bs;
2930 BezTriple *bezt;
2931 BPoint *bpnt;
2932 int a, curindex = 0;
2933 int totvert, totspring = 0, setgoal = 0;
2934
2935 totvert = BKE_nurbList_verts_count(&cu->nurb);
2936
2937 if (ob->softflag & OB_SB_EDGES) {
2938 if (ob->type == OB_CURVES_LEGACY) {
2939 totspring = totvert - cu->nurb.count();
2940 }
2941 }
2942
2943 /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2944 renew_softbody(ob, totvert, totspring);
2945 sb = ob->soft; /* can be created in renew_softbody() */
2946
2947 /* set vars now */
2948 bp = sb->bpoint;
2949 bs = sb->bspring;
2950
2951 /* Weights from bpoints, same code used as for mesh vertices. */
2952 /* if ((ob->softflag & OB_SB_GOAL) && sb->vertgroup) 2.4x hack. */
2953 /* new! take the weights from curve vertex anyhow */
2954 if (ob->softflag & OB_SB_GOAL) {
2955 setgoal = 1;
2956 }
2957
2958 for (Nurb &nu : cu->nurb) {
2959 if (nu.bezt) {
2960 /* Bezier case; this is nicely said naive; who ever wrote this part,
2961 * it was not me (JOW) :).
2962 *
2963 * a: never ever make tangent handles (sub) and or (ob)ject to collision.
2964 * b: rather calculate them using some C2
2965 * (C2= continuous in second derivative -> no jump in bending ) condition.
2966 *
2967 * Not too hard to do, but needs some more code to care for;
2968 * some one may want look at it (JOW 2010/06/12). */
2969 for (bezt = nu.bezt, a = 0; a < nu.pntsu; a++, bezt++, bp += 3, curindex += 3) {
2970 if (setgoal) {
2971 bp->goal *= bezt->weight;
2972
2973 /* All three triples. */
2974 (bp + 1)->goal = bp->goal;
2975 (bp + 2)->goal = bp->goal;
2976 /* Do not collide handles. */
2977 (bp + 1)->loc_flag |= SBF_OUTOFCOLLISION;
2978 (bp + 2)->loc_flag |= SBF_OUTOFCOLLISION;
2979 }
2980
2981 if (totspring) {
2982 if (a > 0) {
2983 bs->v1 = curindex - 3;
2984 bs->v2 = curindex;
2985 bs->springtype = SB_HANDLE;
2986 bs->len = globallen((bezt - 1)->vec[0], bezt->vec[0], ob);
2987 bs++;
2988 }
2989 bs->v1 = curindex;
2990 bs->v2 = curindex + 1;
2991 bs->springtype = SB_HANDLE;
2992 bs->len = globallen(bezt->vec[0], bezt->vec[1], ob);
2993 bs++;
2994
2995 bs->v1 = curindex + 1;
2996 bs->v2 = curindex + 2;
2997 bs->springtype = SB_HANDLE;
2998 bs->len = globallen(bezt->vec[1], bezt->vec[2], ob);
2999 bs++;
3000 }
3001 }
3002 }
3003 else {
3004 for (bpnt = nu.bp, a = 0; a < nu.pntsu * nu.pntsv; a++, bpnt++, bp++, curindex++) {
3005 if (setgoal) {
3006 bp->goal *= bpnt->weight;
3007 }
3008 if (totspring && a > 0) {
3009 bs->v1 = curindex - 1;
3010 bs->v2 = curindex;
3011 bs->springtype = SB_EDGE;
3012 bs->len = globallen((bpnt - 1)->vec, bpnt->vec, ob);
3013 bs++;
3014 }
3015 }
3016 }
3017 }
3018
3019 if (totspring) {
3020 build_bps_springlist(ob); /* link bps to springs */
3021 if (ob->softflag & OB_SB_SELF) {
3023 }
3024 }
3025}
3026
3027/* copies softbody result back in object */
3028static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts, int local)
3029{
3030 SoftBody *sb = ob->soft;
3031 if (sb) {
3032 BodyPoint *bp = sb->bpoint;
3033 int a;
3034 if (sb->solverflags & SBSO_ESTIMATEIPO) {
3035 SB_estimate_transform(ob, sb->lcom, sb->lrot, sb->lscale);
3036 }
3037 /* Inverse matrix is not up to date. */
3038 invert_m4_m4(ob->runtime->world_to_object.ptr(), ob->object_to_world().ptr());
3039
3040 for (a = 0; a < numVerts; a++, bp++) {
3041 copy_v3_v3(vertexCos[a], bp->pos);
3042 if (local == 0) {
3043 /* softbody is in global coords, baked optionally not */
3044 mul_m4_v3(ob->world_to_object().ptr(), vertexCos[a]);
3045 }
3046 }
3047 }
3048}
3049
3050/* +++ ************ maintaining scratch *************** */
3051static void sb_new_scratch(SoftBody *sb)
3052{
3053 if (!sb) {
3054 return;
3055 }
3056 sb->scratch = MEM_new_zeroed<SBScratch>("SBScratch");
3057 sb->scratch->colliderhash = MEM_new<ColliderMeshMap>(__func__);
3058 sb->scratch->bodyface = nullptr;
3059 sb->scratch->bodyface_num = 0;
3060 sb->scratch->aabbmax[0] = sb->scratch->aabbmax[1] = sb->scratch->aabbmax[2] = 1.0e30f;
3061 sb->scratch->aabbmin[0] = sb->scratch->aabbmin[1] = sb->scratch->aabbmin[2] = -1.0e30f;
3062 sb->scratch->Ref.ivert = nullptr;
3063}
3064/* --- ************ maintaining scratch *************** */
3065
3066/* ************ Object level, exported functions *************** */
3067
3069{
3070 SoftBody *sb;
3071
3072 sb = MEM_new<SoftBody>("softbody");
3073
3074 sb->mediafrict = 0.5f;
3075 sb->nodemass = 1.0f;
3076 sb->grav = 9.8f;
3077 sb->physics_speed = 1.0f;
3078 sb->rklimit = 0.1f;
3079
3080 sb->goalspring = 0.5f;
3081 sb->goalfrict = 0.0f;
3082 sb->mingoal = 0.0f;
3083 sb->maxgoal = 1.0f;
3084 sb->defgoal = 0.7f;
3085
3086 sb->inspring = 0.5f;
3087 sb->infrict = 0.5f;
3088 /* TODO: backward file compatibility should copy `inspring` to `inpush` while reading old files.
3089 */
3090 sb->inpush = 0.5f;
3091
3092 sb->colball = 0.49f;
3093 sb->balldamp = 0.50f;
3094 sb->ballstiff = 1.0f;
3095 sb->sbc_mode = SBC_MODE_AVG;
3096
3097 sb->minloops = 10;
3098 sb->maxloops = 300;
3099
3100 sb->choke = 3;
3101 sb->fuzzyness = 1;
3102 sb_new_scratch(sb);
3103 /* TODO: backward file compatibility should set `sb->shearstiff = 1.0f` while reading old files.
3104 */
3105 sb->shearstiff = 1.0f;
3106 sb->solverflags |= SBSO_OLDERR;
3107
3108 sb->shared = MEM_new<SoftBody_Shared>("SoftBody_Shared");
3110
3111 if (!sb->effector_weights) {
3113 }
3114
3115 sb->last_frame = MINFRAME - 1;
3116
3117 return sb;
3118}
3119
3121{
3122 SoftBody *sb = ob->soft;
3123 if (sb == nullptr) {
3124 return;
3125 }
3126
3127 const bool is_orig = (ob->id.tag & ID_TAG_COPIED_ON_EVAL) == 0;
3128
3130
3131 if (is_orig) {
3132 /* Only free shared data on non-evaluated copies */
3134 sb->shared->pointcache = nullptr;
3135 MEM_delete(sb->shared);
3136 }
3137 if (sb->effector_weights) {
3138 MEM_delete(sb->effector_weights);
3139 }
3140 MEM_delete(sb);
3141
3142 ob->soft = nullptr;
3143}
3144
3145SoftBody *sbCopy(SoftBody *sb, int flag)
3146{
3147 SoftBody *sbn = MEM_dupalloc(sb);
3148 const bool is_orig = (flag & LIB_ID_COPY_SET_COPIED_ON_WRITE) == 0;
3149
3150 if ((flag & LIB_ID_COPY_CACHES) == 0) {
3151 sbn->totspring = sbn->totpoint = 0;
3152 sbn->bpoint = nullptr;
3153 sbn->bspring = nullptr;
3154 }
3155 else {
3156 sbn->totspring = sb->totspring;
3157 sbn->totpoint = sb->totpoint;
3158
3159 if (sbn->bpoint) {
3160 int i;
3161
3162 sbn->bpoint = MEM_dupalloc(sbn->bpoint);
3163
3164 for (i = 0; i < sbn->totpoint; i++) {
3165 if (sbn->bpoint[i].springs) {
3166 sbn->bpoint[i].springs = MEM_dupalloc(sbn->bpoint[i].springs);
3167 }
3168 }
3169 }
3170
3171 if (sb->bspring) {
3172 sbn->bspring = MEM_dupalloc(sb->bspring);
3173 }
3174 }
3175
3176 sbn->keys = nullptr;
3177 sbn->totkey = sbn->totpointkey = 0;
3178
3179 sbn->scratch = nullptr;
3180
3181 if (is_orig) {
3182 sbn->shared = MEM_dupalloc(sb->shared);
3184 &sbn->shared->ptcaches, &sb->shared->ptcaches, flag);
3185 }
3186
3187 if (sb->effector_weights) {
3188 sbn->effector_weights = MEM_dupalloc(sb->effector_weights);
3189 }
3190
3191 return sbn;
3192}
3193
3195{
3197}
3198
3200{
3201 // ob->softflag |= OB_SB_REDO;
3202
3204}
3205
3206static bool object_has_edges(const Object *ob)
3207{
3208 if (ob->type == OB_MESH) {
3209 return (id_cast<Mesh *>(ob->data))->edges_num;
3210 }
3211 if (ob->type == OB_LATTICE) {
3212 return true;
3213 }
3214
3215 return false;
3216}
3217
3219{
3221}
3222
3224 SoftBody *sb,
3225 float (*vertexCos)[3],
3226 int numVerts)
3227{
3228 BodyPoint *bp;
3229 int a;
3230
3231 if (!sb || !sb->bpoint) {
3232 return;
3233 }
3234
3235 for (a = 0, bp = sb->bpoint; a < numVerts; a++, bp++) {
3236 /* store where goals are now */
3237 copy_v3_v3(bp->origS, bp->origE);
3238 /* copy the position of the goals at desired end time */
3239 copy_v3_v3(bp->origE, vertexCos[a]);
3240 /* vertexCos came from local world, go global */
3241 mul_m4_v3(ob->object_to_world().ptr(), bp->origE);
3242 /* just to be save give bp->origT a defined value
3243 * will be calculated in interpolate_exciter() */
3244 copy_v3_v3(bp->origT, bp->origE);
3245 }
3246}
3247
3248void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float lscale[3][3])
3249{
3250 BodyPoint *bp;
3251 ReferenceVert *rp;
3252 SoftBody *sb = nullptr;
3253 float (*opos)[3];
3254 float (*rpos)[3];
3255 float com[3], rcom[3];
3256 int a;
3257
3258 if (!ob || !ob->soft) {
3259 return; /* why did we get here ? */
3260 }
3261 sb = ob->soft;
3262 if (!sb || !sb->bpoint) {
3263 return;
3264 }
3265 opos = MEM_new_array_zeroed<float[3]>(sb->totpoint, "SB_OPOS");
3266 rpos = MEM_new_array_zeroed<float[3]>(sb->totpoint, "SB_RPOS");
3267 /* might filter vertex selection with a vertex group */
3268 for (a = 0, bp = sb->bpoint, rp = sb->scratch->Ref.ivert; a < sb->totpoint; a++, bp++, rp++) {
3269 copy_v3_v3(rpos[a], rp->pos);
3270 copy_v3_v3(opos[a], bp->pos);
3271 }
3272
3274 sb->totpoint, opos, nullptr, rpos, nullptr, com, rcom, lrot, lscale);
3275 // sub_v3_v3(com, rcom);
3276 if (lloc) {
3277 copy_v3_v3(lloc, com);
3278 }
3279 copy_v3_v3(sb->lcom, com);
3280 if (lscale) {
3281 copy_m3_m3(sb->lscale, lscale);
3282 }
3283 if (lrot) {
3284 copy_m3_m3(sb->lrot, lrot);
3285 }
3286
3287 MEM_delete(opos);
3288 MEM_delete(rpos);
3289}
3290
3291static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int numVerts)
3292{
3293 BodyPoint *bp;
3294 int a;
3295
3296 for (a = 0, bp = sb->bpoint; a < numVerts; a++, bp++) {
3297 copy_v3_v3(bp->pos, vertexCos[a]);
3298 mul_m4_v3(ob->object_to_world().ptr(), bp->pos); /* Yep, soft-body is global coords. */
3299 copy_v3_v3(bp->origS, bp->pos);
3300 copy_v3_v3(bp->origE, bp->pos);
3301 copy_v3_v3(bp->origT, bp->pos);
3302 bp->vec[0] = bp->vec[1] = bp->vec[2] = 0.0f;
3303
3304 /* The `bp->prev*` 's are for rolling back from a canceled try to propagate in time
3305 * adaptive step size algorithm in a nutshell:
3306 * 1) set scheduled time step to new dtime
3307 * 2) try to advance the scheduled time step, being optimistic execute it
3308 * 3) check for success
3309 * 3a) we 're fine continue, may be we can increase scheduled time again ?? if so, do so!
3310 * 3b) we did exceed error limit --> roll back, shorten the scheduled time and try again at 2.
3311 * 4) check if we did reach dtime
3312 * 4a) nope we need to do some more at 2.
3313 * 4b) yup we're done
3314 */
3315
3316 copy_v3_v3(bp->prevpos, bp->pos);
3317 copy_v3_v3(bp->prevvec, bp->vec);
3318 copy_v3_v3(bp->prevdx, bp->vec);
3319 copy_v3_v3(bp->prevdv, bp->vec);
3320 }
3321
3322 /* make a nice clean scratch struct */
3323 free_scratch(sb); /* clear if any */
3324 sb_new_scratch(sb); /* make a new */
3326 zero_v3(sb->lcom);
3327 unit_m3(sb->lrot);
3328 unit_m3(sb->lscale);
3329
3330 /* copy some info to scratch */
3331 /* we only need that if we want to reconstruct IPO */
3332 if (true) {
3334 SB_estimate_transform(ob, nullptr, nullptr, nullptr);
3335 SB_estimate_transform(ob, nullptr, nullptr, nullptr);
3336 }
3337 switch (ob->type) {
3338 case OB_MESH:
3339 if (ob->softflag & OB_SB_FACECOLL) {
3341 }
3342 break;
3343 case OB_LATTICE:
3344 break;
3345 case OB_CURVES_LEGACY:
3346 case OB_SURF:
3347 break;
3348 default:
3349 break;
3350 }
3351}
3352
3353static void softbody_step(
3354 Depsgraph *depsgraph, Scene *scene, Object *ob, SoftBody *sb, float dtime)
3355{
3356 /* the simulator */
3357 float forcetime;
3358 double sct, sst;
3359
3360 sst = BLI_time_now_seconds();
3361 /* Integration back in time is possible in theory, but pretty useless here.
3362 * So we refuse to do so. Since we do not know anything about 'outside' changes
3363 * especially colliders we refuse to go more than 10 frames.
3364 */
3365 if (dtime < 0 || dtime > 10.5f) {
3366 return;
3367 }
3368
3370
3371 if (sb->scratch->needstobuildcollider) {
3374 }
3375
3376 if (sb->solver_ID < 2) {
3377 /* special case of 2nd order Runge-Kutta type AKA Heun */
3378 int mid_flags = 0;
3379 float err = 0;
3380 /* Set defaults guess we shall do one frame */
3381 float forcetimemax = 1.0f;
3382 /* Set defaults guess 1/100 is tight enough */
3383 float forcetimemin = 0.01f;
3384 /* How far did we get without violating error condition. */
3385 float timedone = 0.0;
3386 /* Loops = counter for emergency brake we don't want to lock up the system if physics fail. */
3387 int loops = 0;
3388
3389 SoftHeunTol = sb->rklimit; /* Hum .. this should be calculated from sb parameters and sizes */
3390 /* adjust loop limits */
3391 if (sb->minloops > 0) {
3392 forcetimemax = dtime / sb->minloops;
3393 }
3394 if (sb->maxloops > 0) {
3395 forcetimemin = dtime / sb->maxloops;
3396 }
3397
3398 if (sb->solver_ID > 0) {
3399 mid_flags |= MID_PRESERVE;
3400 }
3401
3402 forcetime = forcetimemax; /* hope for integrating in one step */
3403 while ((fabsf(timedone) < fabsf(dtime)) && (loops < 2000)) {
3404 /* set goals in time */
3405 interpolate_exciter(ob, 200, int(200.0f * (timedone / dtime)));
3406
3407 sb->scratch->flag &= ~SBF_DOFUZZY;
3408 /* do predictive euler step */
3409 softbody_calc_forces(depsgraph, scene, ob, forcetime, timedone / dtime);
3410
3411 softbody_apply_forces(ob, forcetime, 1, nullptr, mid_flags);
3412
3413 /* crop new slope values to do averaged slope step */
3414 softbody_calc_forces(depsgraph, scene, ob, forcetime, timedone / dtime);
3415
3416 softbody_apply_forces(ob, forcetime, 2, &err, mid_flags);
3418
3419 if (err > SoftHeunTol) { /* error needs to be scaled to some quantity */
3420
3421 if (forcetime > forcetimemin) {
3422 forcetime = max_ff(forcetime / 2.0f, forcetimemin);
3424 // printf("down, ");
3425 }
3426 else {
3427 timedone += forcetime;
3428 }
3429 }
3430 else {
3431 float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */
3432
3433 if (sb->scratch->flag & SBF_DOFUZZY) {
3434 // /* stay with this stepsize unless err really small */
3435 // if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) {
3436 newtime = forcetime;
3437 // }
3438 }
3439 else {
3440 if (err > SoftHeunTol / 2.0f) { /* stay with this stepsize unless err really small */
3441 newtime = forcetime;
3442 }
3443 }
3444 timedone += forcetime;
3445 newtime = min_ff(forcetimemax, max_ff(newtime, forcetimemin));
3446 // if (newtime > forcetime) printf("up, ");
3447 if (forcetime > 0.0f) {
3448 forcetime = min_ff(dtime - timedone, newtime);
3449 }
3450 else {
3451 forcetime = max_ff(dtime - timedone, newtime);
3452 }
3453 }
3454 loops++;
3455 if (sb->solverflags & SBSO_MONITOR) {
3456 sct = BLI_time_now_seconds();
3457 if (sct - sst > 0.5) {
3458 printf("%3.0f%% \r", 100.0f * timedone / dtime);
3459 }
3460 }
3461 /* ask for user break */
3463 break;
3464 }
3465 }
3466 /* move snapped to final position */
3467 interpolate_exciter(ob, 2, 2);
3469
3470 // if (G.debug & G_DEBUG) {
3471 if (sb->solverflags & SBSO_MONITOR) {
3472 if (loops > HEUNWARNLIMIT) { /* monitor high loop counts */
3473 printf("\r needed %d steps/frame", loops);
3474 }
3475 }
3476 }
3477 else if (sb->solver_ID == 2) {
3478 /* do semi "fake" implicit euler */
3479 /* removed */
3480 } /* SOLVER SELECT */
3481 else if (sb->solver_ID == 4) {
3482 /* do semi "fake" implicit euler */
3483 } /* SOLVER SELECT */
3484 else if (sb->solver_ID == 3) {
3485 /* do "stupid" semi "fake" implicit euler */
3486 /* removed */
3487
3488 } /* SOLVER SELECT */
3489 else {
3490 CLOG_ERROR(&LOG, "softbody no valid solver ID!");
3491 } /* SOLVER SELECT */
3492 if (sb->plastic) {
3494 }
3495
3496 if (sb->solverflags & SBSO_MONITOR) {
3497 sct = BLI_time_now_seconds();
3498 if ((sct - sst > 0.5) || (G.debug & G_DEBUG)) {
3499 printf(" solver time %f sec %s\n", sct - sst, ob->id.name);
3500 }
3501 }
3502}
3503
3504static void sbStoreLastFrame(Depsgraph *depsgraph, Object *object, float framenr)
3505{
3506 if (!DEG_is_active(depsgraph)) {
3507 return;
3508 }
3509 Object *object_orig = DEG_get_original(object);
3510 object->soft->last_frame = framenr;
3511 object_orig->soft->last_frame = framenr;
3512}
3513
3514void sbObjectStep(Depsgraph *depsgraph,
3515 Scene *scene,
3516 Object *ob,
3517 float cfra,
3518 float (*vertexCos)[3],
3519 int numVerts)
3520{
3521 SoftBody *sb = ob->soft;
3522 PointCache *cache;
3523 PTCacheID pid;
3524 float dtime, timescale;
3525 int framedelta, framenr, startframe, endframe;
3526 int cache_result;
3527 cache = sb->shared->pointcache;
3528
3529 framenr = int(cfra);
3530 framedelta = framenr - cache->simframe;
3531
3532 BKE_ptcache_id_from_softbody(&pid, ob, sb);
3533 BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
3534
3535 /* check for changes in mesh, should only happen in case the mesh
3536 * structure changes during an animation */
3537 if (sb->bpoint && numVerts != sb->totpoint) {
3539 return;
3540 }
3541
3542 /* clamp frame ranges */
3543 if (framenr < startframe) {
3545 return;
3546 }
3547 framenr = std::min(framenr, endframe);
3548
3549 /* verify if we need to create the softbody data */
3550 if (sb->bpoint == nullptr ||
3551 ((ob->softflag & OB_SB_EDGES) && !ob->soft->bspring && object_has_edges(ob)))
3552 {
3553
3554 switch (ob->type) {
3555 case OB_MESH:
3556 mesh_to_softbody(ob);
3557 break;
3558 case OB_LATTICE:
3560 break;
3561 case OB_CURVES_LEGACY:
3562 case OB_SURF:
3564 break;
3565 default:
3566 renew_softbody(ob, numVerts, 0);
3567 break;
3568 }
3569
3570 softbody_update_positions(ob, sb, vertexCos, numVerts);
3571 softbody_reset(ob, sb, vertexCos, numVerts);
3572 }
3573
3574 /* still no points? go away */
3575 if (sb->totpoint == 0) {
3576 return;
3577 }
3578 if (framenr == startframe) {
3580
3581 /* first frame, no simulation to do, just set the vert_positions */
3582 softbody_update_positions(ob, sb, vertexCos, numVerts);
3583
3584 BKE_ptcache_validate(cache, framenr);
3585 cache->flag &= ~PTCACHE_REDO_NEEDED;
3586
3587 sbStoreLastFrame(depsgraph, ob, framenr);
3588
3589 return;
3590 }
3591
3592 /* try to read from cache */
3593 bool can_write_cache = DEG_is_active(depsgraph);
3594 bool can_simulate = (framenr == sb->last_frame + 1) && !(cache->flag & PTCACHE_BAKED) &&
3595 can_write_cache;
3596
3597 cache_result = BKE_ptcache_read(&pid, float(framenr) + scene->r.subframe, can_simulate);
3598
3599 if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED ||
3600 (!can_simulate && cache_result == PTCACHE_READ_OLD))
3601 {
3602 /* Keep goal positions in track. */
3603 softbody_update_positions(ob, sb, vertexCos, numVerts);
3604 softbody_to_object(ob, vertexCos, numVerts, sb->local);
3605
3606 BKE_ptcache_validate(cache, framenr);
3607
3608 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED &&
3609 can_write_cache)
3610 {
3611 BKE_ptcache_write(&pid, framenr);
3612 }
3613
3614 sbStoreLastFrame(depsgraph, ob, framenr);
3615
3616 return;
3617 }
3618 if (cache_result == PTCACHE_READ_OLD) {
3619 /* pass */
3620 }
3621 else if (/* ob->id.lib || */
3622 /* "library linking & point-caches" has to be solved properly at some point. */
3623 (cache->flag & PTCACHE_BAKED))
3624 {
3625 /* If baked and nothing in cache, do nothing. */
3626 if (can_write_cache) {
3628 }
3629 return;
3630 }
3631
3632 if (!can_simulate) {
3633 return;
3634 }
3635
3636 /* if on second frame, write cache for first frame */
3637 if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0))
3638 {
3639 BKE_ptcache_write(&pid, startframe);
3640 }
3641
3642 softbody_update_positions(ob, sb, vertexCos, numVerts);
3643
3644 /* checking time: */
3645 dtime = framedelta * timescale;
3646
3647 /* do simulation */
3648 softbody_step(depsgraph, scene, ob, sb, dtime);
3649
3650 softbody_to_object(ob, vertexCos, numVerts, 0);
3651
3652 BKE_ptcache_validate(cache, framenr);
3653 BKE_ptcache_write(&pid, framenr);
3654
3655 sbStoreLastFrame(depsgraph, ob, framenr);
3656}
3657
3658} // namespace blender
#define SOFTGOALSNAP
Definition BKE_cloth.hh:32
CustomData interface, see also DNA_customdata_types.h.
support for deformation groups and hooks.
#define PTCACHE_READ_INTERPOLATED
#define PTCACHE_READ_OLD
#define PTCACHE_RESET_OUTDATED
#define PTCACHE_READ_EXACT
Platform independent time functions.
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
Object groups, one object can be in many groups at once.
Object is a sort of wrapper for general info.
#define MINFRAME
Read Blender memory allocation and freeing.
#define UNUSED_VARS(...)
#define ELEM(...)
#define MEM_realloc_zeroed(vmemh, len)
btScalar max
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
ValueIterator values() const &
Definition BLI_map.hh:884
ItemIterator items() const &
Definition BLI_map.hh:902
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr bool is_empty() const
Definition BLI_span.hh:264
#define expf(x)
#define pow
#define exp
float distance(float, float) RET
float3x3 scale(float3x3 mat, float2 scale)
void EIG_linear_solver_matrix_add(LinearSolver *solver, int row, int col, double value)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
ccl_device_inline void copy_v3_v3(ccl_private float *r, const float3 val)
#define L
void corner_tris_calc(Span< float3 > vert_positions, OffsetIndices< int > faces, Span< int > corner_verts, MutableSpan< int3 > corner_tris)
BMesh Iterators.
MINLINE float min_ff(float a, float b)
static void calculate_collision_balls(Object *ob)
Definition softbody.cc:763
static float sb_grav_force_scale(Object *)
Definition softbody.cc:164
void * MEM_new_uninitialized(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old)
static void curve_surf_to_softbody(Object *ob)
Definition softbody.cc:2924
static void softbody_restore_prev_step(Object *ob)
Definition softbody.cc:2437
static void ccd_update_deflector_hash_single(ColliderMeshMap *hash, Object *ob)
Definition softbody.cc:532
static float _final_goal(Object *ob, BodyPoint *bp)
Definition softbody.cc:211
int BKE_scene_num_threads(const Scene *scene)
Definition scene.cc:3163
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
static const int CCD_SAFETY
Definition softbody.cc:257
static void reference_to_scratch(Object *ob)
Definition softbody.cc:2744
void minmax_v3v3_v3(float min[3], float max[3], const float vec[3])
bool DEG_is_active(const Depsgraph *depsgraph)
Definition depsgraph.cc:324
ATTR_WARN_UNUSED_RESULT const BMLoop * l
void sbFreeSimulation(struct SoftBody *sb)
Definition softbody.cc:3194
MINLINE void add_v3_v3v3(float r[3], const float a[3], const float b[3])
void copy_m3_m3(float m1[3][3], const float m2[3][3])
static void mesh_to_softbody(Object *ob)
Definition softbody.cc:2631
static int sb_detect_face_pointCached(const float face_v1[3], const float face_v2[3], const float face_v3[3], float *damp, float force[3], Object *vertexowner, float time)
Definition softbody.cc:1024
BLI_INLINE void dfdx_spring(float to[3][3], const float dir[3], float length, float L, float k)
int BKE_ptcache_id_reset(struct Scene *scene, PTCacheID *pid, int mode)
static void add_mesh_quad_diag_springs(Object *ob)
Definition softbody.cc:583
static int sb_detect_face_collisionCached(const float face_v1[3], const float face_v2[3], const float face_v3[3], float *damp, float force[3], Object *vertexowner, float time)
Definition softbody.cc:1113
static float sb_fric_force_scale(Object *)
Definition softbody.cc:173
static int(*) SB_localInterruptCallBack()
Definition softbody.cc:75
bool invert_m4_m4(float inverse[4][4], const float mat[4][4])
void BLI_threadpool_insert(ListBaseT< ThreadSlot > *threadbase, void *callerdata)
Definition threads.cc:189
static void ccd_build_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, ColliderMeshMap *hash)
Definition softbody.cc:508
static void interpolate_exciter(Object *ob, int timescale, int time)
Definition softbody.cc:2567
void BLI_threadpool_end(ListBaseT< ThreadSlot > *threadbase)
Definition threads.cc:239
static float SoftHeunTol
Definition softbody.cc:151
static void softbody_update_positions(Object *ob, SoftBody *sb, float(*vertexCos)[3], int numVerts)
Definition softbody.cc:3223
static ccd_Mesh * ccd_mesh_make(Object *ob)
Definition softbody.cc:275
void BKE_effectors_apply(ListBaseT< EffectorCache > *effectors, ListBaseT< ColliderCache > *colliders, struct EffectorWeights *weights, struct EffectedPoint *point, float *force, float *wind_force, float *impulse)
Definition effect.cc:1134
static void sb_cf_threads_run(Scene *scene, Object *ob, float forcetime, float timenow, int totpoint, int *ptr_to_break_func(void), ListBaseT< EffectorCache > *effectors, int do_deflector, float fieldfactor, float windfactor)
Definition softbody.cc:2147
ATTR_WARN_UNUSED_RESULT const BMVert * v
static int count_mesh_quads(Mesh *mesh)
Definition softbody.cc:571
static void makelatticesprings(Lattice *lt, BodySpring *bs, int dostiff, Object *ob)
Definition softbody.cc:2781
static void sb_sfesf_threads_run(Depsgraph *depsgraph, Scene *scene, Object *ob, float timenow, int totsprings, int *ptr_to_break_func(void))
Definition softbody.cc:1479
static void softbody_to_object(Object *ob, float(*vertexCos)[3], int numVerts, int local)
Definition softbody.cc:3028
bool isect_line_segment_tri_v3(const float p1[3], const float p2[3], const float v0[3], const float v1[3], const float v2[3], float *r_lambda, float r_uv[2])
void sbObjectStep(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, float cfra, float(*vertexCos)[3], int numVerts)
Definition softbody.cc:3514
@ LIB_ID_COPY_SET_COPIED_ON_WRITE
@ LIB_ID_COPY_CACHES
MINLINE void mul_v3_fl(float r[3], float f)
static void sb_new_scratch(SoftBody *sb)
Definition softbody.cc:3051
int BKE_id_defgroup_name_index(const ID *id, StringRef name)
Definition deform.cc:557
static int sb_detect_edge_collisionCached(const float edge_v1[3], const float edge_v2[3], float *damp, float force[3], Object *vertexowner, float time)
Definition softbody.cc:1287
struct SoftBody * sbNew()
Definition softbody.cc:3068
void project_v3_v3v3(float out[3], const float p[3], const float v_proj[3])
Global G
Definition blender.cc:57
MINLINE void sub_v3_v3(float r[3], const float a[3])
static int choose_winner(float *w, float *pos, float *a, float *b, float *c, float *ca, float *cb, float *cc)
Definition softbody.cc:1548
void mul_m4_v3(const float M[4][4], float r[3])
static void add_2nd_order_roller(Object *ob, float, int *counter, int addsprings)
Definition softbody.cc:624
SoftBody * sbCopy(struct SoftBody *sb, int flag)
Definition softbody.cc:3145
MINLINE void madd_v3_v3fl(float r[3], const float a[3], float f)
void vcloud_estimate_transform_v3(int list_size, const float(*pos)[3], const float *weight, const float(*rpos)[3], const float *rweight, float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3])
float BKE_defvert_find_weight(const MDeformVert *dvert, int defgroup)
Definition deform.cc:779
static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp, float force[3], Object *vertexowner, float time, float vel[3], float *intrusion)
Definition softbody.cc:1579
static void apply_spring_memory(Object *ob)
Definition softbody.cc:2543
VecBase< int32_t, 3 > int3
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err, int mid_flags)
Definition softbody.cc:2277
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
BMesh const char void * data
static void ccd_mesh_free(ccd_Mesh *ccdm)
Definition softbody.cc:483
void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float lscale[3][3])
Definition softbody.cc:3248
static void ccd_build_deflector_hash_single(ColliderMeshMap *hash, Object *ob)
Definition softbody.cc:497
static void free_softbody_baked(SoftBody *sb)
Definition softbody.cc:867
static void mesh_faces_to_scratch(Object *ob)
Definition softbody.cc:2717
static void _scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow, int ifirst, int ilast, ListBaseT< EffectorCache > *effectors)
Definition softbody.cc:1392
static void sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float)
Definition softbody.cc:1825
void BKE_ptcache_id_time(PTCacheID *pid, struct Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
static void scan_for_ext_face_forces(Object *ob, float timenow)
Definition softbody.cc:1215
void sbSetInterruptCallBack(int(*f)())
Definition softbody.cc:3218
static void softbody_reset(Object *ob, SoftBody *sb, float(*vertexCos)[3], int numVerts)
Definition softbody.cc:3291
static void add_2nd_order_springs(Object *ob, float stiffness)
Definition softbody.cc:688
static void add_bp_springlist(BodyPoint *bp, int springID)
Definition softbody.cc:711
MINLINE int poly_to_tri_count(int poly_count, int corner_count)
MINLINE void zero_v3(float r[3])
static void * exec_scan_for_ext_spring_forces(void *data)
Definition softbody.cc:1471
MINLINE float normalize_v3_v3(float r[3], const float a[3])
void BKE_ptcache_validate(struct PointCache *cache, int framenr)
static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, float forcetime, float timenow, int ifirst, int ilast, int *ptr_to_break_func(void), ListBaseT< EffectorCache > *effectors, int do_deflector, float fieldfactor, float windfactor)
Definition softbody.cc:1906
MINLINE float normalize_v3(float n[3])
ModifierData * BKE_modifiers_findby_type(const Object *ob, ModifierType type)
MINLINE void add_v3_v3(float r[3], const float a[3])
static void springs_from_mesh(Object *ob)
Definition softbody.cc:2596
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
void mid_v3_v3v3(float r[3], const float a[3], const float b[3])
static int sb_deflect_face(Object *ob, float *actpos, float *facenormal, float *force, float *cf, float time, float *vel, float *intrusion)
Definition softbody.cc:1762
T * DEG_get_original(T *id)
void BKE_ptcache_free_list(ListBaseT< PointCache > *ptcaches)
void unit_m3(float m[3][3])
static float sb_time_scale(Object *ob)
Definition softbody.cc:181
ATTR_WARN_UNUSED_RESULT const BMVert * v2
struct Object ** BKE_collision_objects_create(struct Depsgraph *depsgraph, struct Object *self, struct Collection *collection, unsigned int *numcollobj, unsigned int modifier_type)
static int query_external_colliders(Depsgraph *depsgraph, Collection *collection)
Definition softbody.cc:965
MINLINE float max_ff(float a, float b)
static void * exec_softbody_calc_forces(void *data)
Definition softbody.cc:2130
ListBaseT< EffectorCache > * BKE_effectors_create(struct Depsgraph *depsgraph, struct Object *ob_src, struct ParticleSystem *psys_src, struct EffectorWeights *weights, bool use_rotation)
Definition effect.cc:316
static void softbody_calc_forces(Depsgraph *depsgraph, Scene *scene, Object *ob, float forcetime, float timenow)
Definition softbody.cc:2216
@ ID_TAG_COPIED_ON_EVAL
Definition DNA_ID.h:1000
void sbFree(struct Object *ob)
Definition softbody.cc:3120
struct PointCache * BKE_ptcache_add(ListBaseT< PointCache > *ptcaches)
void pd_point_from_soft(struct Scene *scene, float *loc, float *vel, int index, struct EffectedPoint *point)
Definition effect.cc:439
struct PointCache * BKE_ptcache_copy_list(ListBaseT< PointCache > *ptcaches_new, const ListBaseT< PointCache > *ptcaches_old, int flag)
static CLG_LogRef LOG
Definition logging.cpp:12
double BLI_time_now_seconds()
Definition time.cc:30
void sbObjectToSoftbody(struct Object *ob)
Definition softbody.cc:3199
Map< Object *, struct ccd_Mesh * > ColliderMeshMap
Definition softbody.cc:105
static float _final_mass(Object *ob, BodyPoint *bp)
Definition softbody.cc:232
bool isect_point_tri_prism_v3(const float p[3], const float v1[3], const float v2[3], const float v3[3])
static void renew_softbody(Object *ob, int totpoint, int totspring)
Definition softbody.cc:816
void BKE_ptcache_id_from_softbody(PTCacheID *pid, struct Object *ob, struct SoftBody *sb)
static void sbStoreLastFrame(Depsgraph *depsgraph, Object *object, float framenr)
Definition softbody.cc:3504
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
static void ccd_update_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, ColliderMeshMap *hash)
Definition softbody.cc:545
struct EffectorWeights * BKE_effector_add_weights(struct Collection *collection)
Definition effect.cc:63
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
void BKE_ptcache_invalidate(struct PointCache *cache)
@ SB_HANDLE
Definition softbody.cc:79
@ SB_STIFFQUAD
Definition softbody.cc:79
@ SB_EDGE
Definition softbody.cc:79
@ SB_BEND
Definition softbody.cc:79
static int sb_detect_aabb_collisionCached(float[3], Object *vertexowner, float)
Definition softbody.cc:977
void BLI_threadpool_init(ListBaseT< ThreadSlot > *threadbase, void *(*do_thread)(void *), int tot)
Definition threads.cc:123
static void free_scratch(SoftBody *sb)
Definition softbody.cc:881
void BKE_collision_objects_free(struct Object **objects)
static void build_bps_springlist(Object *ob)
Definition softbody.cc:734
static void softbody_apply_goalsnap(Object *ob)
Definition softbody.cc:2529
static bool object_has_edges(const Object *ob)
Definition softbody.cc:3206
int BKE_nurbList_verts_count(const ListBaseT< Nurb > *nurb)
Definition curve.cc:559
static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M)
Definition softbody.cc:363
static float globallen(float *v1, float *v2, Object *ob)
Definition softbody.cc:2771
void BKE_effectors_free(ListBaseT< EffectorCache > *lb)
Definition effect.cc:371
static void free_softbody_intern(SoftBody *sb)
Definition softbody.cc:904
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
static void lattice_to_softbody(Object *ob)
Definition softbody.cc:2861
static void softbody_step(Depsgraph *depsgraph, Scene *scene, Object *ob, SoftBody *sb, float dtime)
Definition softbody.cc:3353
#define hash
Definition noise_c.cc:156
#define fabsf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define BFF_INTERSECT
Definition softbody.cc:147
#define SBF_OUTOFCOLLISION
Definition softbody.cc:145
#define SBF_DOFUZZY
Definition softbody.cc:144
#define HEUNWARNLIMIT
Definition softbody.cc:139
#define MID_PRESERVE
Definition softbody.cc:133
#define BFF_CLOSEVERT
Definition softbody.cc:148
#define BSF_INTERSECT
Definition softbody.cc:141
#define min(a, b)
Definition sort.cc:38
float ext_force[3]
Definition softbody.cc:91
type_spring springtype
Definition softbody.cc:85
ListBaseT< Nurb > nurb
char name[258]
Definition DNA_ID.h:433
struct MDeformVert * dvert
struct BPoint * def
const c_style_mat & ptr() const
BezTriple * bezt
struct PartDeflect * pd
bke::ObjectRuntime * runtime
struct SoftBody * soft
ReferenceVert * ivert
Definition softbody.cc:102
ReferenceState Ref
Definition softbody.cc:115
ColliderMeshMap * colliderhash
Definition softbody.cc:109
short needstobuildcollider
Definition softbody.cc:110
BodyFace * bodyface
Definition softbody.cc:112
ListBaseT< EffectorCache > * effectors
Definition softbody.cc:125
struct PhysicsSettings physics_settings
struct RenderData r
ListBaseT< PointCache > ptcaches
struct EffectorWeights * effector_weights
eSoftBody_SolverFlag solverflags
struct SoftBody_Shared * shared
struct Collection * collision_group
struct SBScratch * scratch
struct BodyPoint * bpoint
struct BodySpring * bspring
const int3 * vert_tris
Definition softbody.cc:267
CCDF_MinMax * mima
Definition softbody.cc:269
const float(* vert_positions)[3]
Definition softbody.cc:265
const float(* vert_positions_prev)[3]
Definition softbody.cc:266