Support for multi-touch stroke drawing in tuioinput.py
[numtypysics.git] / Scene.cpp
blob416acfccda62e8df1d7796cbf93332456205f9df
1 /*
2 * This file is part of NumptyPhysics
3 * Copyright (C) 2008 Tim Edmonds
4 *
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.
9 *
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.
16 #include "Common.h"
17 #include "Array.h"
18 #include "Config.h"
19 #include "Scene.h"
21 #include <sstream>
22 #include <fstream>
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) ) {
33 m_bypass = true;
34 } else {
35 m_rot.Set( rotation );
36 m_pos = translation;
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();
42 m_bypass = false;
46 Transform worldToScreen( 0.5f, M_PI/2, Vec2(240,0) );
48 void configureScreenTransform( int w, int h )
50 SCREEN_WIDTH = w;
51 SCREEN_HEIGHT = 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) );
55 } else {
56 float rot = 0.0f;
57 Vec2 tr(0,0);
58 if ( h > w ) { //portrait
59 rot = M_PI/2;
60 tr = Vec2( w, 0 );
61 b2Swap( h, w );
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 );
67 } else {
68 worldToScreen.set( scaleh, rot, tr );
74 class Stroke
76 public:
78 private:
79 struct JointDef : public b2RevoluteJointDef
81 JointDef( b2Body* b1, b2Body* b2, const b2Vec2& pt )
83 Initialize( b1, b2, pt );
84 maxMotorTorque = 10.0f;
85 motorSpeed = 0.0f;
86 enableMotor = true;
90 struct BoxDef : public b2PolygonDef
92 void init( const Vec2& p1, const Vec2& p2, int attr )
94 b2Vec2 barOrigin = p1;
95 b2Vec2 bar = p2 - 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 ));
102 friction = 0.3f;
103 if ( attr & ATTRIB_GROUND ) {
104 density = 0.0f;
105 } else if ( attr & ATTRIB_GOAL ) {
106 density = 100.0f;
107 } else if ( attr & ATTRIB_TOKEN ) {
108 density = 3.0f;
109 friction = 0.1f;
110 } else {
111 density = 5.0f;
113 restitution = 0.2f;
117 public:
118 Stroke( const Path& path )
119 : m_rawPath(path)
121 m_colour = brushColours[DEFAULT_BRUSH];
122 m_attributes = 0;
123 m_origin = m_rawPath.point(0);
124 m_rawPath.translate( -m_origin );
125 setPlayer(0);
126 reset();
129 Stroke( const std::string& str )
131 setPlayer(0);
132 int col = 0;
133 m_colour = brushColours[DEFAULT_BRUSH];
134 m_attributes = 0;
135 m_origin = Vec2(400,240);
136 reset();
137 const char *s = str.c_str();
138 while ( *s && *s!=':' && *s!='\n' ) {
139 switch ( *s ) {
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;
147 default:
148 if ( *s >= '0' && *s <= '9' ) {
149 col = col*10 + *s -'0';
151 break;
153 s++;
155 if ( col >= 0 && col < NUM_BRUSHES ) {
156 m_colour = brushColours[col];
158 if ( *s++ == ':' ) {
159 m_rawPath = Path(s);
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 );
174 m_body = NULL;
175 m_xformAngle = 7.0f;
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;
180 m_hide = 0;
181 m_drawn = false;
184 std::string asString()
186 std::stringstream s;
187 s << 'S';
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;
196 s << ":";
197 transform();
198 for ( int i=0; i<m_xformedPath.size(); i++ ) {
199 const Vec2& p = m_xformedPath.point(i);
200 s <<' '<< p.x << ',' << p.y;
202 s << std::endl;
203 return s.str();
206 void setAttribute( Attribute a )
208 m_attributes |= 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 )
215 m_player = player;
218 int getPlayer()
220 return m_player;
223 void clearAttribute( Attribute a )
225 m_attributes &= ~a;
228 bool hasAttribute( Attribute a )
230 return (m_attributes&a) != 0;
232 void setColour( int c )
234 m_colour = c;
237 void createBodies( b2World& world )
239 process();
240 if ( hasAttribute( ATTRIB_DECOR ) ){
241 return; //decorators have no physical embodiment
243 int n = m_shapePath.numPoints();
244 if ( n > 1 ) {
245 b2BodyDef bodyDef;
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++ ) {
254 BoxDef boxDef;
255 boxDef.init( m_shapePath.point(i-1),
256 m_shapePath.point(i),
257 m_attributes );
258 m_body->CreateShape( &boxDef );
260 m_body->SetMassFromShapes();
263 transform();
266 bool maybeCreateJoint( b2World& world, Stroke* other )
268 if ( (m_attributes&ATTRIB_CLASSBITS)
269 != (other->m_attributes&ATTRIB_CLASSBITS) ) {
270 return false; // can only joint matching classes
271 } else if ( hasAttribute(ATTRIB_GROUND) ) {
272 return true; // no point jointing grounds
273 } else if ( m_body && other->body() ) {
274 transform();
275 int n = m_xformedPath.numPoints();
276 for ( int end=0; end<2; end++ ) {
277 if ( !m_jointed[end] ) {
278 const Vec2& p = m_xformedPath.point( end ? n-1 : 0 );
279 if ( other->distanceTo( p ) <= JOINT_TOLERANCE ) {
280 //printf("jointed end %d d=%f\n",end,other->distanceTo( p ));
281 b2Vec2 pw = p;
282 pw *= 1.0f/PIXELS_PER_METREf;
283 JointDef j( m_body, other->m_body, pw );
284 world.CreateJoint( &j );
285 m_jointed[end] = true;
290 if ( m_body ) {
291 return m_jointed[0] && m_jointed[1];
293 return true; ///nothing to do
296 void draw( Canvas& canvas )
298 if ( m_hide < HIDE_STEPS ) {
299 bool thick = (canvas.width() > 400);
300 transform();
301 canvas.drawPath( m_screenPath, canvas.makeColour(m_colour), thick );
302 m_drawn = true;
304 m_drawnBbox = m_screenBbox;
307 void addPoint( const Vec2& pp )
309 Vec2 p = pp; p -= m_origin;
310 if ( p == m_rawPath.point( m_rawPath.numPoints()-1 ) ) {
311 } else {
312 m_rawPath.append( p );
313 m_drawn = false;
317 void origin( const Vec2& p )
319 // todo
320 if ( m_body ) {
321 b2Vec2 pw = p;
322 pw *= 1.0f/PIXELS_PER_METREf;
323 m_body->SetXForm( pw, m_body->GetAngle() );
325 m_origin = p;
328 b2Body* body() { return m_body; }
330 float32 distanceTo( const Vec2& pt )
332 float32 best = 100000.0;
333 transform();
334 for ( int i=1; i<m_xformedPath.numPoints(); i++ ) {
335 Segment s( m_xformedPath.point(i-1), m_xformedPath.point(i) );
336 float32 d = s.distanceTo( pt );
337 //printf(" d[%d]=%f %d,%d\n",i,d,m_rawPath.point(i-1).x,m_rawPath.point(i-1).y);
338 if ( d < best ) {
339 best = d;
342 return best;
345 Rect screenBbox()
347 transform();
348 return m_screenBbox;
351 Rect lastDrawnBbox()
353 return m_drawnBbox;
356 Rect worldBbox()
358 return m_xformedPath.bbox();
361 bool isDirty()
363 return (!m_drawn || transform()) && !hasAttribute(ATTRIB_DELETED);
366 void hide()
368 if ( m_hide==0 ) {
369 m_hide = 1;
371 if (m_body) {
372 // stash the body where no-one will find it
373 m_body->SetXForm( b2Vec2(0.0f,SCREEN_HEIGHT*2.0f), 0.0f );
374 m_body->SetLinearVelocity( b2Vec2(0.0f,0.0f) );
375 m_body->SetAngularVelocity( 0.0f );
380 bool hidden()
382 return m_hide >= HIDE_STEPS;
385 int numPoints()
387 return m_rawPath.numPoints();
390 private:
391 static float32 vec2Angle( b2Vec2 v )
393 return b2Atan2(v.y, v.x);
396 void process()
398 float32 thresh = SIMPLIFY_THRESHOLDf;
399 m_rawPath.simplify( thresh );
400 m_shapePath = m_rawPath;
402 while ( m_shapePath.numPoints() > MULTI_VERTEX_LIMIT ) {
403 thresh += SIMPLIFY_THRESHOLDf;
404 m_shapePath.simplify( thresh );
408 bool transform()
410 // distinguish between xformed raw and shape path as needed
411 if ( m_hide ) {
412 if ( m_hide < HIDE_STEPS ) {
413 //printf("hide %d\n",m_hide);
414 Vec2 o = m_screenBbox.centroid();
415 m_screenPath -= o;
416 m_screenPath.scale( 0.99 );
417 m_screenPath += o;
418 m_screenBbox = m_screenPath.bbox();
419 m_hide++;
420 return true;
422 } else if ( m_body ) {
423 if ( hasAttribute( ATTRIB_DECOR ) ) {
424 return false; // decor never moves
425 } else if ( hasAttribute( ATTRIB_GROUND )
426 && m_xformAngle == m_body->GetAngle() ) {
427 return false; // ground strokes never move.
428 } else if ( m_xformAngle != m_body->GetAngle()
429 || ! (m_xformPos == m_body->GetPosition()) ) {
430 //printf("transform stroke - rot or pos\n");
431 b2Mat22 rot( m_body->GetAngle() );
432 b2Vec2 orig = PIXELS_PER_METREf * m_body->GetPosition();
433 m_xformedPath = m_rawPath;
434 m_xformedPath.rotate( rot );
435 m_xformedPath.translate( Vec2(orig) );
436 m_xformAngle = m_body->GetAngle();
437 m_xformPos = m_body->GetPosition();
438 worldToScreen.transform( m_xformedPath, m_screenPath );
439 m_screenBbox = m_screenPath.bbox();
440 } else {
441 //printf("transform none\n");
442 return false;
444 } else {
445 //printf("transform no body\n");
446 m_xformedPath = m_rawPath;
447 m_xformedPath.translate( m_origin );
448 worldToScreen.transform( m_xformedPath, m_screenPath );
449 m_screenBbox = m_screenPath.bbox();
450 return false;
452 return true;
455 Path m_rawPath;
456 int m_colour;
457 int m_attributes;
458 int m_player;
459 Vec2 m_origin;
460 Path m_shapePath;
461 Path m_xformedPath;
462 Path m_screenPath;
463 float32 m_xformAngle;
464 b2Vec2 m_xformPos;
465 Rect m_screenBbox;
466 Rect m_drawnBbox;
467 bool m_drawn;
468 b2Body* m_body;
469 bool m_jointed[2];
470 int m_hide;
473 Scene::Scene( bool noWorld )
474 : m_world( NULL ),
475 m_bgImage( NULL ),
476 m_protect( 0 )
478 if ( !noWorld ) {
479 b2AABB worldAABB;
480 worldAABB.lowerBound.Set(-100.0f, -100.0f);
481 worldAABB.upperBound.Set(100.0f, 100.0f);
483 b2Vec2 gravity(0.0f, 10.0f*PIXELS_PER_METREf/GRAVITY_FUDGEf);
484 bool doSleep = true;
485 m_world = new b2World(worldAABB, gravity, doSleep);
486 m_world->SetContactListener( this );
490 Scene::~Scene()
492 clear();
493 if ( m_world ) {
494 step();
495 delete m_world;
499 Stroke* Scene::newStroke( const Path& p, int colour, int attribs ) {
500 Stroke *s = new Stroke(p);
501 switch ( colour ) {
502 case 0: s->setAttribute( ATTRIB_TOKEN ); break;
503 case 1: s->setAttribute( ATTRIB_GOAL ); break;
504 default: s->setColour( brushColours[colour] ); break;
506 s->setPlayer(0);
507 m_strokes.append( s );
508 return s;
511 bool Scene::deleteStroke( Stroke *s ) {
512 if ( s ) {
513 int i = m_strokes.indexOf(s);
514 if ( i >= m_protect ) {
515 reset(s);
516 m_strokes.erase( m_strokes.indexOf(s) );
517 return true;
520 return false;
524 void Scene::extendStroke( Stroke* s, const Vec2& pt )
526 if ( s ) {
527 s->addPoint( pt );
531 void Scene::moveStroke( Stroke* s, const Vec2& origin )
533 if ( s ) {
534 int i = m_strokes.indexOf(s);
535 if ( i >= m_protect ) {
536 s->origin( origin );
542 bool Scene::activate( Stroke *s )
544 if ( s->numPoints() > 1 ) {
545 s->createBodies( *m_world );
546 createJoints( s );
547 return true;
549 return false;
552 void Scene::activateAll()
554 m_num_goal = 0;
555 m_num_token = 0;
556 m_num_player = 0;
557 m_winner = -1;
559 for ( int i=0; i < m_strokes.size(); i++ ) {
560 m_strokes[i]->createBodies( *m_world );
561 if (m_strokes[i]->hasAttribute(ATTRIB_TOKEN)) { m_num_token++;}
562 if (m_strokes[i]->hasAttribute(ATTRIB_GOAL)) { m_num_goal++; }
563 if (m_strokes[i]->getPlayer() + 1 > m_num_player) { m_num_player = m_strokes[i]->getPlayer() + 1; }
565 for ( int i=0; i < m_strokes.size(); i++ ) {
566 createJoints( m_strokes[i] );
570 void Scene::createJoints( Stroke *s )
572 for ( int j=m_strokes.size()-1; j>=0; j-- ) {
573 if ( s != m_strokes[j] ) {
574 //printf("try join to %d\n",j);
575 s->maybeCreateJoint( *m_world, m_strokes[j] );
576 m_strokes[j]->maybeCreateJoint( *m_world, s );
581 void Scene::step()
583 m_world->Step( ITERATION_TIMESTEPf, SOLVER_ITERATIONS );
584 // clean up delete strokes
585 for ( int i=0; i< m_strokes.size(); i++ ) {
586 if ( m_strokes[i]->hasAttribute(ATTRIB_DELETED) ) {
587 m_strokes[i]->clearAttribute(ATTRIB_DELETED);
588 m_strokes[i]->hide();
591 // check for token respawn
592 for ( int i=0; i < m_strokes.size(); i++ ) {
593 if ( m_strokes[i]->hasAttribute( ATTRIB_TOKEN )
594 && !BOUNDS_RECT.intersects( m_strokes[i]->worldBbox() ) ) {
595 reset( m_strokes[i] );
596 activate( m_strokes[i] );
601 // b2ContactListener callback when a new contact is detected
602 void Scene::Add(const b2ContactPoint* point)
604 // check for completion
605 //if (c->GetManifoldCount() > 0) {
606 Stroke* s1 = (Stroke*)point->shape1->GetBody()->GetUserData();
607 Stroke* s2 = (Stroke*)point->shape2->GetBody()->GetUserData();
609 if ( s1 && s2 ) {
610 if ( s2->hasAttribute(ATTRIB_TOKEN) ) {
611 b2Swap( s1, s2 );
613 if ( s1->hasAttribute(ATTRIB_TOKEN)
614 && s2->hasAttribute(ATTRIB_GOAL) ) {
615 s2->setAttribute(ATTRIB_DELETED);
616 if (m_num_goal == 1) {
617 m_winner = s1->getPlayer();
623 bool Scene::isCompleted()
625 /* if we only have one goal, m_winner has already been set */
626 if ((m_num_goal == 1) && (m_winner != -1)) {
627 return true;
630 else if (m_num_goal > 1)
632 int left[m_num_player];
633 for(int n=0; n<m_num_player; n++) {
634 left[n] = 0;
637 for ( int i=0; i < m_strokes.size(); i++ ) {
638 if ( m_strokes[i]->hasAttribute( ATTRIB_GOAL )
639 && !m_strokes[i]->hidden() ) {
640 left[m_strokes[i]->getPlayer()]++;
644 for ( int n=0; n<m_num_player; n++) {
645 if (left[n] == 0) {
646 m_winner = n;
647 return true;
652 return false;
655 int Scene::getWinner()
657 return m_num_player == 1 ? -1 : m_winner;
660 Rect Scene::dirtyArea()
662 Rect r(0,0,0,0),temp;
663 int numDirty = 0;
664 for ( int i=0; i<m_strokes.size(); i++ ) {
665 if ( m_strokes[i]->isDirty() ) {
666 // acumulate new areas to draw
667 temp = m_strokes[i]->screenBbox();
668 if ( !temp.isEmpty() ) {
669 if ( numDirty==0 ) {
670 r = temp;
671 } else {
672 r.expand( m_strokes[i]->screenBbox() );
674 // plus prev areas to erase
675 r.expand( m_strokes[i]->lastDrawnBbox() );
676 numDirty++;
680 if ( !r.isEmpty() ) {
681 // expand to allow for thick lines
682 r.tl.x--; r.tl.y--;
683 r.br.x++; r.br.y++;
685 return r;
688 void Scene::draw( Canvas& canvas, const Rect& area )
690 if ( m_bgImage ) {
691 canvas.setBackground( m_bgImage );
692 } else {
693 canvas.setBackground( 0 );
695 canvas.clear( area );
696 Rect clipArea = area;
697 clipArea.tl.x--;
698 clipArea.tl.y--;
699 clipArea.br.x++;
700 clipArea.br.y++;
701 for ( int i=0; i<m_strokes.size(); i++ ) {
702 if ( area.intersects( m_strokes[i]->screenBbox() ) ) {
703 m_strokes[i]->draw( canvas );
706 //canvas.drawRect( area, 0xffff0000, false );
709 void Scene::reset( Stroke* s )
711 for ( int i=0; i<m_strokes.size(); i++ ) {
712 if (s==NULL || s==m_strokes[i]) {
713 m_strokes[i]->reset(m_world);
718 Stroke* Scene::strokeAtPoint( const Vec2 pt, float32 max )
720 Stroke* best = NULL;
721 for ( int i=0; i<m_strokes.size(); i++ ) {
722 float32 d = m_strokes[i]->distanceTo( pt );
723 //printf("stroke %d dist %f\n",i,d);
724 if ( d < max ) {
725 max = d;
726 best = m_strokes[i];
729 return best;
732 void Scene::clear()
734 reset();
735 while ( m_strokes.size() ) {
736 delete m_strokes[0];
737 m_strokes.erase(0);
739 if ( m_world ) {
740 //step is required to actually destroy bodies and joints
741 m_world->Step( ITERATION_TIMESTEPf, SOLVER_ITERATIONS );
745 void Scene::setGravity( const std::string& s )
747 float32 x,y;
748 if ( sscanf( s.c_str(), "%f,%f", &x, &y )==2) {
749 if ( m_world ) {
750 b2Vec2 g(x,y);
751 g *= PIXELS_PER_METREf/GRAVITY_FUDGEf;
752 m_world->SetGravity( g );
754 } else {
755 fprintf(stderr,"invalid gravity vector\n");
759 bool Scene::load( unsigned char *buf, int bufsize )
761 std::string s( (const char*)buf, bufsize );
762 std::stringstream in( s, std::ios::in );
763 return load( in );
766 bool Scene::load( const std::string& file )
768 std::ifstream in( file.c_str(), std::ios::in );
769 return load( in );
772 bool Scene::load( std::istream& in )
774 clear();
775 if ( g_bgImage==NULL ) {
776 g_bgImage = new Image("paper.png");
777 g_bgImage->scale( SCREEN_WIDTH, SCREEN_HEIGHT );
779 m_bgImage = g_bgImage;
780 std::string line;
781 while ( !in.eof() ) {
782 getline( in, line );
783 parseLine( line );
785 protect();
786 return true;
789 bool Scene::parseLine( const std::string& line )
791 try {
792 switch( line[0] ) {
793 case 'T': m_title = line.substr(line.find(':')+1); return true;
794 case 'B': m_bg = line.substr(line.find(':')+1); return true;
795 case 'A': m_author = line.substr(line.find(':')+1); return true;
796 case 'S': {
797 Stroke *s = new Stroke(line);
798 m_strokes.append(s);
799 return true;
801 case 'G': setGravity(line.substr(line.find(':')+1));return true;
803 } catch ( const char* e ) {
804 printf("Stroke error: %s\n",e);
806 return false;
809 void Scene::protect( int n )
811 m_protect = (n==-1 ? m_strokes.size() : n );
814 bool Scene::save( const std::string& file )
816 printf("saving to %s\n",file.c_str());
817 std::ofstream o( file.c_str(), std::ios::out );
818 if ( o.is_open() ) {
819 o << "Title: "<<m_title<<std::endl;
820 o << "Author: "<<m_author<<std::endl;
821 o << "Background: "<<m_bg<<std::endl;
822 for ( int i=0; i<m_strokes.size(); i++ ) {
823 o << m_strokes[i]->asString();
825 o.close();
826 return true;
827 } else {
828 return false;
833 Image *Scene::g_bgImage = NULL;