2 * This file is part of NumptyPhysics
3 * Copyright (C) 2008 Tim Edmonds
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
25 Transform::Transform( float32 scale
, float32 rotation
, const Vec2
& translation
)
27 set( scale
, rotation
, translation
);
30 void Transform::set( float32 scale
, float32 rotation
, const Vec2
& translation
)
32 if ( scale
==0.0f
&& rotation
==0.0f
&& translation
==Vec2(0,0) ) {
35 m_rot
.Set( rotation
);
37 m_rot
.col1
.x
*= scale
;
38 m_rot
.col1
.y
*= scale
;
39 m_rot
.col2
.x
*= scale
;
40 m_rot
.col2
.y
*= scale
;
41 m_invrot
= m_rot
.Invert();
46 Transform
worldToScreen( 0.5f
, M_PI
/2, Vec2(240,0) );
48 void configureScreenTransform( int w
, int h
)
52 FULLSCREEN_RECT
= Rect(0,0,w
-1,h
-1);
53 if ( w
==WORLD_WIDTH
&& h
==WORLD_HEIGHT
) { //unity
54 worldToScreen
.set( 0.0f
, 0.0f
, Vec2(0,0) );
58 if ( h
> w
) { //portrait
63 float scalew
= (float)w
/(float)WORLD_WIDTH
;
64 float scaleh
= (float)h
/(float)WORLD_HEIGHT
;
65 if ( scalew
< scaleh
) {
66 worldToScreen
.set( scalew
, rot
, tr
);
68 worldToScreen
.set( scaleh
, rot
, tr
);
79 struct JointDef
: public b2RevoluteJointDef
81 JointDef( b2Body
* b1
, b2Body
* b2
, const b2Vec2
& pt
)
83 Initialize( b1
, b2
, pt
);
84 maxMotorTorque
= 10.0f
;
90 struct BoxDef
: public b2PolygonDef
92 void init( const Vec2
& p1
, const Vec2
& p2
, int attr
)
94 b2Vec2 barOrigin
= p1
;
96 bar
*= 1.0f
/PIXELS_PER_METREf
;
97 barOrigin
*= 1.0f
/PIXELS_PER_METREf
;;
98 SetAsBox( bar
.Length()/2.0f
, 0.1f
,
99 0.5f
*bar
+ barOrigin
, vec2Angle( bar
));
100 // SetAsBox( bar.Length()/2.0f+b2_toiSlop, b2_toiSlop*2.0f,
101 // 0.5f*bar + barOrigin, vec2Angle( bar ));
103 if ( attr
& ATTRIB_GROUND
) {
105 } else if ( attr
& ATTRIB_GOAL
) {
107 } else if ( attr
& ATTRIB_TOKEN
) {
118 Stroke( const Path
& path
, int attributes
)
121 m_colour
= brushColours
[DEFAULT_BRUSH
];
122 m_attributes
= attributes
;
123 m_origin
= m_rawPath
.point(0);
124 m_rawPath
.translate( -m_origin
);
129 Stroke( const std::string
& str
)
133 m_colour
= brushColours
[DEFAULT_BRUSH
];
135 m_origin
= Vec2(400,240);
137 const char *s
= str
.c_str();
138 while ( *s
&& *s
!=':' && *s
!='\n' ) {
140 case 't': setAttribute( ATTRIB_TOKEN
); setPlayer(0); break;
141 case 'T': setAttribute( ATTRIB_TOKEN
); setPlayer(1); break;
142 case 'g': setAttribute( ATTRIB_GOAL
); setPlayer(0); break;
143 case 'G': setAttribute( ATTRIB_GOAL
); setPlayer(1); break;
144 case 'f': setAttribute( ATTRIB_GROUND
); break;
145 case 's': setAttribute( ATTRIB_SLEEPING
); break;
146 case 'd': setAttribute( ATTRIB_DECOR
); break;
148 if ( *s
>= '0' && *s
<= '9' ) {
149 col
= col
*10 + *s
-'0';
155 if ( col
>= 0 && col
< NUM_BRUSHES
) {
156 m_colour
= brushColours
[col
];
161 if ( m_rawPath
.size() < 2 ) {
162 throw "invalid stroke def";
164 m_origin
= m_rawPath
.point(0);
165 m_rawPath
.translate( -m_origin
);
166 setAttribute( ATTRIB_DUMMY
);
169 void reset( b2World
* world
=NULL
)
171 if (m_body
&& world
) {
172 world
->DestroyBody( m_body
);
176 m_drawnBbox
.tl
= m_origin
;
177 m_drawnBbox
.br
= m_origin
;
178 m_jointed
[0] = m_jointed
[1] = false;
179 m_shapePath
= m_rawPath
;
184 std::string
asString()
188 if ( hasAttribute(ATTRIB_TOKEN
) ) s
<<'t';
189 if ( hasAttribute(ATTRIB_GOAL
) ) s
<<'g';
190 if ( hasAttribute(ATTRIB_GROUND
) ) s
<<'f';
191 if ( hasAttribute(ATTRIB_SLEEPING
) ) s
<<'s';
192 if ( hasAttribute(ATTRIB_DECOR
) ) s
<<'d';
193 for ( int i
=0; i
<NUM_BRUSHES
; i
++ ) {
194 if ( m_colour
==brushColours
[i
] ) s
<<i
;
198 for ( int i
=0; i
<m_xformedPath
.size(); i
++ ) {
199 const Vec2
& p
= m_xformedPath
.point(i
);
200 s
<<' '<< p
.x
<< ',' << p
.y
;
206 void setAttribute( Attribute a
)
209 if ( m_attributes
& ATTRIB_TOKEN
) m_colour
= brushColours
[RED_BRUSH
];
210 else if ( m_attributes
& ATTRIB_GOAL
) m_colour
= brushColours
[YELLOW_BRUSH
];
213 void setPlayer( int player
)
223 void clearAttribute( Attribute a
)
228 bool hasAttribute( Attribute a
)
230 return (m_attributes
&a
) != 0;
232 void setColour( int c
)
237 void createBodies( b2World
& world
)
240 if ( hasAttribute( ATTRIB_DECOR
) ){
241 return; //decorators have no physical embodiment
243 int n
= m_shapePath
.numPoints();
246 bodyDef
.position
= m_origin
;
247 bodyDef
.position
*= 1.0f
/PIXELS_PER_METREf
;
248 bodyDef
.userData
= this;
249 if ( m_attributes
& ATTRIB_SLEEPING
) {
250 bodyDef
.isSleeping
= true;
252 m_body
= world
.CreateBody( &bodyDef
);
253 for ( int i
=1; i
<n
; i
++ ) {
255 boxDef
.init( m_shapePath
.point(i
-1),
256 m_shapePath
.point(i
),
258 m_body
->CreateShape( &boxDef
);
260 m_body
->SetMassFromShapes();
268 b2MassData m
= {0.0, b2Vec2(0.0, 0.0), 0.0};
272 void setDefaultMass()
274 m_body
->SetMassFromShapes();
277 bool maybeCreateJoint( b2World
& world
, Stroke
* other
)
279 if ( (m_attributes
&ATTRIB_CLASSBITS
)
280 != (other
->m_attributes
&ATTRIB_CLASSBITS
) ) {
281 return false; // can only joint matching classes
282 } else if ( hasAttribute(ATTRIB_GROUND
) ) {
283 return true; // no point jointing grounds
284 } else if ( m_body
&& other
->body() ) {
286 int n
= m_xformedPath
.numPoints();
287 for ( int end
=0; end
<2; end
++ ) {
288 if ( !m_jointed
[end
] ) {
289 const Vec2
& p
= m_xformedPath
.point( end
? n
-1 : 0 );
290 if ( other
->distanceTo( p
) <= JOINT_TOLERANCE
) {
291 //printf("jointed end %d d=%f\n",end,other->distanceTo( p ));
293 pw
*= 1.0f
/PIXELS_PER_METREf
;
294 JointDef
j( m_body
, other
->m_body
, pw
);
295 world
.CreateJoint( &j
);
296 m_jointed
[end
] = true;
302 return m_jointed
[0] && m_jointed
[1];
304 return true; ///nothing to do
307 void draw( Canvas
& canvas
)
309 if ( m_hide
< HIDE_STEPS
) {
310 bool thick
= (canvas
.width() > 400);
312 canvas
.drawPath( m_screenPath
, canvas
.makeColour(m_colour
), thick
);
315 m_drawnBbox
= m_screenBbox
;
318 void addPoint( const Vec2
& pp
)
320 Vec2 p
= pp
; p
-= m_origin
;
321 if ( p
== m_rawPath
.point( m_rawPath
.numPoints()-1 ) ) {
323 m_rawPath
.append( p
);
328 void origin( const Vec2
& p
)
333 pw
*= 1.0f
/PIXELS_PER_METREf
;
334 m_body
->SetXForm( pw
, m_body
->GetAngle() );
339 b2Body
* body() { return m_body
; }
341 float32
distanceTo( const Vec2
& pt
)
343 float32 best
= 100000.0;
345 for ( int i
=1; i
<m_xformedPath
.numPoints(); i
++ ) {
346 Segment
s( m_xformedPath
.point(i
-1), m_xformedPath
.point(i
) );
347 float32 d
= s
.distanceTo( pt
);
348 //printf(" d[%d]=%f %d,%d\n",i,d,m_rawPath.point(i-1).x,m_rawPath.point(i-1).y);
369 return m_xformedPath
.bbox();
374 return (!m_drawn
|| transform()) && !hasAttribute(ATTRIB_DELETED
);
383 // stash the body where no-one will find it
384 m_body
->SetXForm( b2Vec2(0.0f
,SCREEN_HEIGHT
*2.0f
), 0.0f
);
385 m_body
->SetLinearVelocity( b2Vec2(0.0f
,0.0f
) );
386 m_body
->SetAngularVelocity( 0.0f
);
393 return m_hide
>= HIDE_STEPS
;
398 return m_rawPath
.numPoints();
402 static float32
vec2Angle( b2Vec2 v
)
404 return b2Atan2(v
.y
, v
.x
);
409 float32 thresh
= SIMPLIFY_THRESHOLDf
;
410 m_rawPath
.simplify( thresh
);
411 m_shapePath
= m_rawPath
;
413 while ( m_shapePath
.numPoints() > MULTI_VERTEX_LIMIT
) {
414 thresh
+= SIMPLIFY_THRESHOLDf
;
415 m_shapePath
.simplify( thresh
);
421 // distinguish between xformed raw and shape path as needed
423 if ( m_hide
< HIDE_STEPS
) {
424 //printf("hide %d\n",m_hide);
425 Vec2 o
= m_screenBbox
.centroid();
427 m_screenPath
.scale( 0.99 );
429 m_screenBbox
= m_screenPath
.bbox();
433 } else if ( m_body
) {
434 if ( hasAttribute( ATTRIB_DECOR
) ) {
435 return false; // decor never moves
436 } else if ( hasAttribute( ATTRIB_GROUND
)
437 && m_xformAngle
== m_body
->GetAngle() ) {
438 return false; // ground strokes never move.
439 } else if ( m_xformAngle
!= m_body
->GetAngle()
440 || ! (m_xformPos
== m_body
->GetPosition()) ) {
441 //printf("transform stroke - rot or pos\n");
442 b2Mat22
rot( m_body
->GetAngle() );
443 b2Vec2 orig
= PIXELS_PER_METREf
* m_body
->GetPosition();
444 m_xformedPath
= m_rawPath
;
445 m_xformedPath
.rotate( rot
);
446 m_xformedPath
.translate( Vec2(orig
) );
447 m_xformAngle
= m_body
->GetAngle();
448 m_xformPos
= m_body
->GetPosition();
449 worldToScreen
.transform( m_xformedPath
, m_screenPath
);
450 m_screenBbox
= m_screenPath
.bbox();
452 //printf("transform none\n");
456 //printf("transform no body\n");
457 m_xformedPath
= m_rawPath
;
458 m_xformedPath
.translate( m_origin
);
459 worldToScreen
.transform( m_xformedPath
, m_screenPath
);
460 m_screenBbox
= m_screenPath
.bbox();
474 float32 m_xformAngle
;
484 Scene::Scene( bool noWorld
)
491 worldAABB
.lowerBound
.Set(-100.0f
, -100.0f
);
492 worldAABB
.upperBound
.Set(100.0f
, 100.0f
);
494 b2Vec2
gravity(0.0f
, 10.0f
*PIXELS_PER_METREf
/GRAVITY_FUDGEf
);
496 m_world
= new b2World(worldAABB
, gravity
, doSleep
);
497 m_world
->SetContactListener( this );
510 Stroke
* Scene::newStroke( const Path
& p
, int colour
, int attribs
) {
511 Stroke
*s
= new Stroke(p
, attribs
);
513 case 0: s
->setAttribute( ATTRIB_TOKEN
); break;
514 case 1: s
->setAttribute( ATTRIB_GOAL
); break;
515 default: s
->setColour( brushColours
[colour
] ); break;
518 m_strokes
.append( s
);
522 bool Scene::deleteStroke( Stroke
*s
) {
524 int i
= m_strokes
.indexOf(s
);
525 if ( i
>= m_protect
) {
527 m_strokes
.erase( m_strokes
.indexOf(s
) );
535 void Scene::extendStroke( Stroke
* s
, const Vec2
& pt
)
542 void Scene::moveStroke( Stroke
* s
, const Vec2
& origin
)
545 int i
= m_strokes
.indexOf(s
);
546 if ( i
>= m_protect
) {
552 void Scene::setNoMass(Stroke
* s
)
557 void Scene::setDefaultMass(Stroke
* s
)
562 bool Scene::activate( Stroke
*s
)
564 if ( s
->numPoints() > 1 ) {
565 s
->createBodies( *m_world
);
572 void Scene::activateAll()
579 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
580 m_strokes
[i
]->createBodies( *m_world
);
581 if (m_strokes
[i
]->hasAttribute(ATTRIB_TOKEN
)) { m_num_token
++;}
582 if (m_strokes
[i
]->hasAttribute(ATTRIB_GOAL
)) { m_num_goal
++; }
583 if (m_strokes
[i
]->getPlayer() + 1 > m_num_player
) { m_num_player
= m_strokes
[i
]->getPlayer() + 1; }
585 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
586 createJoints( m_strokes
[i
] );
590 void Scene::createJoints( Stroke
*s
)
592 for ( int j
=m_strokes
.size()-1; j
>=0; j
-- ) {
593 if ( s
!= m_strokes
[j
] ) {
594 //printf("try join to %d\n",j);
595 s
->maybeCreateJoint( *m_world
, m_strokes
[j
] );
596 m_strokes
[j
]->maybeCreateJoint( *m_world
, s
);
603 m_world
->Step( ITERATION_TIMESTEPf
, SOLVER_ITERATIONS
);
604 // clean up delete strokes
605 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
606 if ( m_strokes
[i
]->hasAttribute(ATTRIB_DELETED
) ) {
607 m_strokes
[i
]->clearAttribute(ATTRIB_DELETED
);
608 m_strokes
[i
]->hide();
611 // check for token respawn
612 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
613 if ( m_strokes
[i
]->hasAttribute( ATTRIB_TOKEN
)
614 && !BOUNDS_RECT
.intersects( m_strokes
[i
]->worldBbox() ) ) {
615 reset( m_strokes
[i
] );
616 activate( m_strokes
[i
] );
621 // b2ContactListener callback when a new contact is detected
622 void Scene::Add(const b2ContactPoint
* point
)
624 // check for completion
625 //if (c->GetManifoldCount() > 0) {
626 Stroke
* s1
= (Stroke
*)point
->shape1
->GetBody()->GetUserData();
627 Stroke
* s2
= (Stroke
*)point
->shape2
->GetBody()->GetUserData();
630 if ( s2
->hasAttribute(ATTRIB_TOKEN
) ) {
633 if ( s1
->hasAttribute(ATTRIB_TOKEN
)
634 && s2
->hasAttribute(ATTRIB_GOAL
) ) {
635 s2
->setAttribute(ATTRIB_DELETED
);
636 if (m_num_goal
== 1) {
637 m_winner
= s1
->getPlayer();
643 bool Scene::isCompleted()
645 /* if we only have one goal, m_winner has already been set */
646 if ((m_num_goal
== 1) && (m_winner
!= -1)) {
650 else if (m_num_goal
> 1)
652 int left
[m_num_player
];
653 for(int n
=0; n
<m_num_player
; n
++) {
657 for ( int i
=0; i
< m_strokes
.size(); i
++ ) {
658 if ( m_strokes
[i
]->hasAttribute( ATTRIB_GOAL
)
659 && !m_strokes
[i
]->hidden() ) {
660 left
[m_strokes
[i
]->getPlayer()]++;
664 for ( int n
=0; n
<m_num_player
; n
++) {
675 int Scene::getWinner()
677 return m_num_player
== 1 ? -1 : m_winner
;
680 Rect
Scene::dirtyArea()
682 Rect
r(0,0,0,0),temp
;
684 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
685 if ( m_strokes
[i
]->isDirty() ) {
686 // acumulate new areas to draw
687 temp
= m_strokes
[i
]->screenBbox();
688 if ( !temp
.isEmpty() ) {
692 r
.expand( m_strokes
[i
]->screenBbox() );
694 // plus prev areas to erase
695 r
.expand( m_strokes
[i
]->lastDrawnBbox() );
700 if ( !r
.isEmpty() ) {
701 // expand to allow for thick lines
708 void Scene::draw( Canvas
& canvas
, const Rect
& area
)
711 canvas
.setBackground( m_bgImage
);
713 canvas
.setBackground( 0 );
715 canvas
.clear( area
);
716 Rect clipArea
= area
;
721 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
722 if ( area
.intersects( m_strokes
[i
]->screenBbox() ) ) {
723 m_strokes
[i
]->draw( canvas
);
726 //canvas.drawRect( area, 0xffff0000, false );
729 void Scene::reset( Stroke
* s
)
731 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
732 if (s
==NULL
|| s
==m_strokes
[i
]) {
733 m_strokes
[i
]->reset(m_world
);
738 Stroke
* Scene::strokeAtPoint( const Vec2 pt
, float32 max
)
741 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
742 float32 d
= m_strokes
[i
]->distanceTo( pt
);
743 //printf("stroke %d dist %f\n",i,d);
755 while ( m_strokes
.size() ) {
760 //step is required to actually destroy bodies and joints
761 m_world
->Step( ITERATION_TIMESTEPf
, SOLVER_ITERATIONS
);
765 void Scene::setGravity( const std::string
& s
)
768 if ( sscanf( s
.c_str(), "%f,%f", &x
, &y
)==2) {
771 g
*= PIXELS_PER_METREf
/GRAVITY_FUDGEf
;
772 m_world
->SetGravity( g
);
775 fprintf(stderr
,"invalid gravity vector\n");
779 bool Scene::load( unsigned char *buf
, int bufsize
)
781 std::string
s( (const char*)buf
, bufsize
);
782 std::stringstream
in( s
, std::ios::in
);
786 bool Scene::load( const std::string
& file
)
788 std::ifstream
in( file
.c_str(), std::ios::in
);
792 bool Scene::load( std::istream
& in
)
795 if ( g_bgImage
==NULL
) {
796 g_bgImage
= new Image("paper.png");
797 g_bgImage
->scale( SCREEN_WIDTH
, SCREEN_HEIGHT
);
799 m_bgImage
= g_bgImage
;
801 while ( !in
.eof() ) {
809 void Scene::trimWhitespace( std::string
& s
)
811 static const char* whitespace
= " \t";
812 size_t start
= s
.find_first_not_of(whitespace
);
813 size_t end
= s
.find_last_not_of(whitespace
);
815 if (std::string::npos
== start
|| std::string::npos
== end
) {
818 s
= s
.substr(start
, end
-start
+1);
822 bool Scene::parseLine( const std::string
& line
)
826 case 'T': m_title
= line
.substr(line
.find(':')+1);
827 trimWhitespace(m_title
); return true;
828 case 'B': m_bg
= line
.substr(line
.find(':')+1); return true;
829 case 'A': m_author
= line
.substr(line
.find(':')+1);
830 trimWhitespace(m_author
);
831 /* The original levels have their author set
832 * to "test". Remove the author in that case. */
833 if (m_author
.compare("test") == 0) {
837 Stroke
*s
= new Stroke(line
);
841 case 'G': setGravity(line
.substr(line
.find(':')+1));return true;
843 } catch ( const char* e
) {
844 printf("Stroke error: %s\n",e
);
849 void Scene::protect( int n
)
851 m_protect
= (n
==-1 ? m_strokes
.size() : n
);
854 bool Scene::save( const std::string
& file
)
856 printf("saving to %s\n",file
.c_str());
857 std::ofstream
o( file
.c_str(), std::ios::out
);
859 o
<< "Title: "<<m_title
<<std::endl
;
860 o
<< "Author: "<<m_author
<<std::endl
;
861 o
<< "Background: "<<m_bg
<<std::endl
;
862 for ( int i
=0; i
<m_strokes
.size(); i
++ ) {
863 o
<< m_strokes
[i
]->asString();
873 Image
*Scene::g_bgImage
= NULL
;