Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Hello Apollo    Diederick Huijbersdiederick@apollomedia.nl   www.apollomedia.nl
This presentation is part of the openFrameworksfreakDays meetings which are given by a group of    Creative Coders and art...
c++     templates   PhysicsCloth
Basic C++  structs  classes  pointerstemplates<>
... use the keyword “struct”  struct Particle {    float x;    float y;    float mass;  }                      .. green me...
... use the keyword “class”  class Particle {    float x;    float y;    float mass;  }                         .. red mea...
Differences:  Struct members arepublic by default those of       a class not.
Check how the keyword                    A struct doesn’t need this              public makes the members                 ...
When to use struct <-> class?  It doesn’t really matter;   it’s a personal thing....
...though, typically structs  are used for simple data  containers and classesfor more advanced things.
Classes for more advanced stuffclass Particle {public:  Particle();  void setPosition(float x, float y);  void update();  ...
Structs for simple data containers          struct User {            string name;            string password;            s...
Pointers !!!
Pointers are not that hard! Instead of pointing to a      value hold a   a memory address!
Pointers are not that hard          Values   Address in memory            f      #1            r      #2            e     ...
char* name = “freakday”                                        Values            Address in memory                        ...
Values         Do not go into unauthorized  f  r         #1         #2                  memory ....or else.....  e      #3...
Check XCode project“freakday_S03E02_pointers”
Memory Alignment + packing                                                                  32 bit wide                   ...
Memory Alignment + packing                                               32 bit wide                                      ...
Memory Alignment + packing              Check XCode project         “freakday_S03E02_packing”
Templates [TYPE_ADDRESS]: some value[ADDRESS_ENTRY]: some value   [TYPE_PHONE]: some value
TemplatesOffice address: some valueBilling address: some valueMobile phone: some value Work phone: some value
TemplatesTemplates are a way to write more generic code: writeone special thing (algorithm) which you can use formany kind...
2D particles....Particle  class Particle2D {    ofVec2f position;    ofVec2f velocity;    ofVec2f forces;    void draw(); ...
3D particles....Particle  class Particle3D {    ofVec3f position;    ofVec3f velocity;    ofVec3f forces;    void draw(); ...
4D particles....Particle  class Particle4D {    ofVec4f position;    ofVec4f velocity;    ofVec4f forces;    void draw(); ...
5D, 6D, 7D ... or template Add this before your template class: “template<typename T>”.The “T” is the type parameter: Part...
Templated Particle  template<typename T>  class Particle {  public:    Particle(T oPosition, float nMass);    void addForc...
Templated Particle-Group  template<typename P, typename V>  class ParticleGroup {  public:    ParticleGroup();    void add...
Example of templated particles  template<typename P, typename V>  class ParticleGroup {  public:    ParticleGroup();    vo...
Keyword TypenameConsider the following code:   template<typename T>   class SomeClass {   public:     typename T::SubType*...
class WithStatic {                class WithType {public:                           public:   static int MyType;          ...
When to use the keyword typename  -- pseudo code --  template<typename T>  class MyContainer {     vector<T> items;     vo...
Physics
Newtons first law An object continues withconstant velocity unless a   force acts upon it[1]
Newtons first law    Note that the red arrow stays the same size. The red arrow     represents the velocity vector and sho...
When creating particle systems I often simulate    drag by degreasing the velocity by a small percentage.       Note how t...
Newtons second lawA force acting on a objectproduces acceleration that   is proportional to the      object’s mass.       ...
Newtons second law                                              this is the resulting forcethis arrow represents the      ...
Newtons second law                                        this is the resulting forcethis arrow represents the            ...
Newtons second law     The math of how force,acceleration and mass is related....     “The law” ( F = ma )          force ...
Newtons second law     This one is important!The bigger the mass, the less the          acceleration             ration = ...
How does this look like in code?  class Particle {     ofxVec2f position;     ofxVec2f velocity;     ofxVec2f forces;     ...
Springs “Springs are structural  elements that, whenconnected between twoobjects, apply equal andopposite forces to each  ...
SpringsObject 1                                        Object 2           The red arrows represent force           vectors...
Springs      The rule related to springs     forces is called “Hooks” law!                 f = -k∆L-k = spring strength; i...
∆L = (r - d)                 difference between springs                “compressed/rest length” and                       ...
∆L = (r - d)                                                  Two particles connected by a spring                      (r)...
Spring force vector           Rest length              Spring force vector                                                ...
SpringsExample: click mouse to add particle + spring...                    Check XCode project            “freakday_S03E02...
Cloth Physics
Cloth PhysicsSimple cloth physics usedmultiple springs connected   to particles in a grid.
Cloth Physics        Particles are positioned on        a grid and then connected by 3        kind of springs:        - st...
Cloth PhysicsStructural springs
Cloth PhysicsShear springs
Cloth PhysicsBending springs
Check XCode project “freakday_S03E02_10_cloth”                     re )                 s ul :               or tif       ...
Creating the particle grid // lets create the grid. for(int i = 0; i < nCols; ++i) { ! for(int j = 0; j < nRows; ++j) { ! ...
Creating the structural springs  // create springs.                                       For more info on  Particle3D* a;...
Next time C++/...:Initializer listsVirtual functionsInheritanceMore templates.....Debugging linker errors (file, nm)Operat...
Next time particles/3d  Integrators  (euler, verlet, runge kutta)  Fast particle systems  (buckets, sorting)  Billboarding...
Other suggestions.......
References1. Ian Millington, Game Physics Engine Development, 2007
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animation/Templates
Upcoming SlideShare
Loading in …5
×

openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animation/Templates

5,711 views

Published on

Presentation given at the monthly "freakDays" meetings in Amsterdam on Creative Coding.

Published in: Technology, Education
  • Be the first to comment

openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animation/Templates

  1. 1. Hello Apollo Diederick Huijbersdiederick@apollomedia.nl www.apollomedia.nl
  2. 2. This presentation is part of the openFrameworksfreakDays meetings which are given by a group of Creative Coders and artists in Amsterdam. During these monthly meetings we givepresentation on innovative techniques and show projects we’re involved in.For more information checkout www.roxlu.com or contact us at info@roxlu.com
  3. 3. c++ templates PhysicsCloth
  4. 4. Basic C++ structs classes pointerstemplates<>
  5. 5. ... use the keyword “struct” struct Particle { float x; float y; float mass; } .. green means “members are accessible”.. Particle x y mass
  6. 6. ... use the keyword “class” class Particle { float x; float y; float mass; } .. red means “members are Particle NOT accessible”.. x y mass
  7. 7. Differences: Struct members arepublic by default those of a class not.
  8. 8. Check how the keyword A struct doesn’t need this public makes the members public keyword. Their green ;) and so accessible! members are public by default! That’s nice!class Particle { class Particle { struct Particle { float x; public: float x; float x; float y; float y; float y; float mass; float mass; float mass;} } } Particle Particle Particle x x x y y y mass mass mass
  9. 9. When to use struct <-> class? It doesn’t really matter; it’s a personal thing....
  10. 10. ...though, typically structs are used for simple data containers and classesfor more advanced things.
  11. 11. Classes for more advanced stuffclass Particle {public: Particle(); void setPosition(float x, float y); void update(); void draw(); void applyRepulsiveForce(); void addForce(float x, float y);private: float x; float y; float mass;}
  12. 12. Structs for simple data containers struct User { string name; string password; string homepage; int age; float weight; }; struct Tweet { uint16 userid; string homepage; string avatar_url; int timestamp; bool has_gps; };
  13. 13. Pointers !!!
  14. 14. Pointers are not that hard! Instead of pointing to a value hold a a memory address!
  15. 15. Pointers are not that hard Values Address in memory f #1 r #2 e #3 a #4 k #5 d #6 a #7 y #8
  16. 16. char* name = “freakday” Values Address in memory f #1 name + 0char * r #2 name + 1Check the char* the star (*)tells the compiler we want a e #3 name + 2pointer a char. A normal charis just one character. The 0 is a #4 name + 3automatically added and tellsthe compiler it’s the end of the k #5 name + 4“string”A pointer points hold an d #6 name + 5memory address. We canstep through the memory a #7 name + 6addresses using this typeof variable. y #8 name + 7 0 #9 name + 8 ? #10 ? #11
  17. 17. Values Do not go into unauthorized f r #1 #2 memory ....or else..... e #3 “EXC_BAD_ACCESS” or a #4 k #5 “UNDEFINED” behavior d #6 a #7 ...which is .... y #8 0 #9 ? #10 name + 9 ? #11 name + 10
  18. 18. Check XCode project“freakday_S03E02_pointers”
  19. 19. Memory Alignment + packing 32 bit wide }When the CPU reads frommemory it uses a natural class Particle { enabledalignment which must be bool enabled; // 8 bitsrespected to permit the CPU float x; // 32 bits xto read and write memory float y; // 32 bits yeffectively. A compiler will bool flying; // 8 bitsleave holes in memory when flyingmembers/objects aren’t }aligned properly. = memory needed WRONG! = memory actually used You should align your bytes nicely
  20. 20. Memory Alignment + packing 32 bit wide } class Particle { float x; // 32 bits x float y; // 32 bits y bool flying; // 8 bits f e bool enabled; // 8 bits }= memory needed CORRECT! = memory actually used The members are aligned nicely
  21. 21. Memory Alignment + packing Check XCode project “freakday_S03E02_packing”
  22. 22. Templates [TYPE_ADDRESS]: some value[ADDRESS_ENTRY]: some value [TYPE_PHONE]: some value
  23. 23. TemplatesOffice address: some valueBilling address: some valueMobile phone: some value Work phone: some value
  24. 24. TemplatesTemplates are a way to write more generic code: writeone special thing (algorithm) which you can use formany kind of types.Create one template for a particle for both 2D and 3D.Particle<2D> and Particle<3D>
  25. 25. 2D particles....Particle class Particle2D { ofVec2f position; ofVec2f velocity; ofVec2f forces; void draw(); }Particle-Group class 2DParticlesGroup { vector<Particle2D*> particles; void addForce(ofVec2f f) { for(int i = 0; i < particles.size(); ++i) { particles.at(i)->addForce(f); } } }
  26. 26. 3D particles....Particle class Particle3D { ofVec3f position; ofVec3f velocity; ofVec3f forces; void draw(); }Particle-Group class 3DParticlesGroup { vector<Particle3D*> particles; void addForce(ofVec3f f) { for(int i = 0; i < particles.size(); ++i) { particles.at(i)->addForce(f); } } }
  27. 27. 4D particles....Particle class Particle4D { ofVec4f position; ofVec4f velocity; ofVec4f forces; void draw(); }Particle-Group class 4DParticlesGroup { vector<Particle4D*> particles; void addForce(ofVec4f f) { for(int i = 0; i < particles.size(); ++i) { particles.at(i)->addForce(f); } } }
  28. 28. 5D, 6D, 7D ... or template Add this before your template class: “template<typename T>”.The “T” is the type parameter: Particle2D, Particle3D, etc..The name “T” can be anything you like, but T is convention.Also correct:template<typename SomeType>template<class SomeType>template<class T>“Typename” and “class” can be used both, “typename”is preferred.
  29. 29. Templated Particle template<typename T> class Particle { public: Particle(T oPosition, float nMass); void addForce(T oForce); void update(); void draw(); private: T position; T forces; T velocity; float mass; };
  30. 30. Templated Particle-Group template<typename P, typename V> class ParticleGroup { public: ParticleGroup(); void addParticle(P oParticle); void addForce(V oForce); void update(); void draw(); private: vector<P> particles };
  31. 31. Example of templated particles template<typename P, typename V> class ParticleGroup { public: ParticleGroup(); void addParticle(P oParticle); void addForce(V oForce); void update(); void draw(); private: vector<P> particles }; Check XCode project “freakday_S03E02_templates”
  32. 32. Keyword TypenameConsider the following code: template<typename T> class SomeClass { public: typename T::SubType* ptr; }; Makes sure that subtype is seen as a type, not a static member.
  33. 33. class WithStatic { class WithType {public: public: static int MyType; class MyType {} } } Here T::MyType * ptr WRONG: Here T::MyType * ptr would refer to the nested type would mean a multiplication in the WithType class.template<typename T> template<typename T>class SomeClass { class SomeClass {public: public: typename T::MyType* ptr; T::MyType * ptr; };};
  34. 34. When to use the keyword typename -- pseudo code -- template<typename T> class MyContainer { vector<T> items; void draw() { typename vector<T>::iterator it = items.begin(); while(it != items.end()) { (*it)->draw(); ++it; } } }; -- add some particles to container MyContainer<Particle2D*> particles; particles.items.push_back(new Particle2D()); particles.items.push_back(new Particle2D()); particles.draw(); Here we make sure that iterator is a type, not a static member! Usually you use the keyword typename with STL iterators
  35. 35. Physics
  36. 36. Newtons first law An object continues withconstant velocity unless a force acts upon it[1]
  37. 37. Newtons first law Note that the red arrow stays the same size. The red arrow represents the velocity vector and showing the first law Velocity vector(s): ofxVec2f, ofxVec3ftime and position1 2 3 4 5 6 7 Check XCode project “freakday_S03E02_5_simple_motion”
  38. 38. When creating particle systems I often simulate drag by degreasing the velocity by a small percentage. Note how the velocity vector below get’s smaller.// example faking drag The amount of drag, the 0.98void Particle::update() { in this example, totally velocity *= 0.98; depends on what you want. It’s a case of tweaking to get} the right behavior.time and position1 2 3 4 5 6 7 Check XCode project “freakday_S03E02_6_simple_motion_with_drag”
  39. 39. Newtons second lawA force acting on a objectproduces acceleration that is proportional to the object’s mass. [1]
  40. 40. Newtons second law this is the resulting forcethis arrow represents the when mass is taken intoforce acting on the object account 160-200 KG (?)
  41. 41. Newtons second law this is the resulting forcethis arrow represents the when mass is taken intoforce acting on the object account 75-80 KG
  42. 42. Newtons second law The math of how force,acceleration and mass is related.... “The law” ( F = ma ) force = mass * acceleration ...to get the acceleration we do: acceleration = 1/mass * force this is what I use in particle systems
  43. 43. Newtons second law This one is important!The bigger the mass, the less the acceleration ration = 1/mass * force accele This is what we call inverse mass. We do not need to recalculate this for each update! We store this in a member of the Particle class and can be used to represent “infinite” mass when set to zero: 0 * force = 0
  44. 44. How does this look like in code? class Particle { ofxVec2f position; ofxVec2f velocity; ofxVec2f forces; float inverse_mass; Particle(float fMass) { if(mass <= 0) { inverse_mass = 0; } else { inverse_mass = 1/mass; } } void addForce(ofxVec2f oForce) { D’Alembert’s Principle (simplified): forces += oForce; We can accumulate all forces acting } on an object. void update() { forces *= inverse_mass; velocity += forces; velocity *= 0.99; position += velocity; forces.set(0,0); } }; Check XCode project “freakday_S03E02_7_simple_motion_inverse_mass”
  45. 45. Springs “Springs are structural elements that, whenconnected between twoobjects, apply equal andopposite forces to each object.”
  46. 46. SpringsObject 1 Object 2 The red arrows represent force vectors in opposite directions: so the two objects are pulled towards each other
  47. 47. Springs The rule related to springs forces is called “Hooks” law! f = -k∆L-k = spring strength; in code just a“float strength” which often gets avalue like 0.1, 0.001∆L = difference between springs“compressed/rest length” and currentlength.
  48. 48. ∆L = (r - d) difference between springs “compressed/rest length” and current length.Two springs notstretched/compressedand showing their restlength. } r = rest length
  49. 49. ∆L = (r - d) Two particles connected by a spring (r) rest lengthSpring force vector Spring force vector (d) distance
  50. 50. Spring force vector Rest length Spring force vector (d) distanceSpring template 2d/3d/.. template<typename P, typename V> class Spring { public: ! Spring(P pParticleA, P pParticleB, float nStrength = 0.01) ! :a(pParticleA) ! ,b(pParticleB) ! ,k(nStrength) ! { Rest length: distance ! ! rest_length = (b->position - a->position).length(); between particles when ! } creating the spring ! void update() { ! ! V dir = b->position - a->position; Current ! ! float dist = dir.length(); distance ! ! if(dist == 0.0) { ! ! ! dist = 0.0001; // division by zero ! ! } ! ! ! ! float f = (rest_length - dist) * k; The force spring ! ! dir.normalize(); ! ! a->addForce(dir * -f); ! ! b->addForce(dir * f); ! } ! ! P a,b; Force spring multiplied by normalized direction vector and in opposite directions
  51. 51. SpringsExample: click mouse to add particle + spring... Check XCode project “freakday_S03E02_8_spring_forces” Example: right click mouse to add particle + spring and use sliders to see the result of different “k” and “drag” values. Check XCode project “freakday_S03E02_9_spring_forces_with_gui”
  52. 52. Cloth Physics
  53. 53. Cloth PhysicsSimple cloth physics usedmultiple springs connected to particles in a grid.
  54. 54. Cloth Physics Particles are positioned on a grid and then connected by 3 kind of springs: - structural springs - shear springs - bending springs
  55. 55. Cloth PhysicsStructural springs
  56. 56. Cloth PhysicsShear springs
  57. 57. Cloth PhysicsBending springs
  58. 58. Check XCode project “freakday_S03E02_10_cloth” re ) s ul : or tif a rr u E ea b
  59. 59. Creating the particle grid // lets create the grid. for(int i = 0; i < nCols; ++i) { ! for(int j = 0; j < nRows; ++j) { ! ! ofxVec3f position(i * nSize, j * nSize); ! ! Particle3D* particle = new Particle3D(position, 1.1); ! ! particles[j * cols + i] = particle; ! ! if(j == 0) { ! ! ! particle->inverse_mass = 0; ! ! } ! } Calculating the index in the vector. We position the } particle just like normal image pixels are stored, by column and row. This is handy when we need to lookup (see getAt) a particle based on a column and row.
  60. 60. Creating the structural springs // create springs. For more info on Particle3D* a; how to create the Particle3D* b; for(int i = 0; i < nCols; ++i) { other springs see ! for(int j = 0; j < nRows; ++j) { the source; it’s ! ! quite similar. ! ! // structural spring - right. ! ! if(i < nCols-1) { ! ! ! a = getAt(i,j);! ! ! ! b = getAt(i+1, j); ! ! ! springs.createSpring(a,b); ! ! } ! ! ! ! // structural spring - down ! ! if(j < nRows-1) { ! ! ! a = getAt(i,j); ! ! ! b = getAt(i, j+1); ! ! ! springs.createSpring(a,b); ! ! } ! } } Check XCode project “freakday_S03E02_11_with_gui”
  61. 61. Next time C++/...:Initializer listsVirtual functionsInheritanceMore templates.....Debugging linker errors (file, nm)Operator overloading (=,[],*,etc.)Const, static
  62. 62. Next time particles/3d Integrators (euler, verlet, runge kutta) Fast particle systems (buckets, sorting) Billboarding Matrices / 3D Shaders
  63. 63. Other suggestions.......
  64. 64. References1. Ian Millington, Game Physics Engine Development, 2007

×