[dali_2.3.21] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-physics / third-party / chipmunk2d / objectivec / include / ObjectiveChipmunk / ChipmunkSpace.h
1 /* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
2  * 
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to deal
5  * in the Software without restriction, including without limitation the rights
6  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7  * copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  * 
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  * 
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19  * SOFTWARE.
20  */
21
22
23 /// Default to using the NEON optimized solver.
24 #define CHIPMUNK_SPACE_USE_HASTY_SPACE 1
25
26
27 /**
28         Chipmunk spaces are simulation containers. You add a bunch of physics objects to a space (rigid bodies, collision shapes, and joints) and step the entire space forward through time as a whole.
29         If you have Chipmunk Pro, you'll want to use the ChipmunkHastySpace subclass instead as it has iPhone specific optimizations.
30         Unfortunately because of how Objective-C code is linked I can't dynamically substitute a ChipmunkHastySpace from a static library.
31 */
32 @interface ChipmunkSpace : NSObject {
33 @protected
34         struct cpSpace *_space;
35         ChipmunkBody *_staticBody;
36         
37         NSMutableSet *_children;
38         NSMutableArray *_handlers;
39         
40         id _userData;
41 }
42
43 /**
44         The iteration count is how many solver passes the space should use when solving collisions and joints (default is 10).
45         Fewer iterations mean less CPU usage, but lower quality (mushy looking) physics.
46 */
47 @property(nonatomic, assign) int iterations;
48
49 /// Global gravity value to use for all rigid bodies in this space (default value is @c cpvzero).
50 @property(nonatomic, assign) cpVect gravity;
51
52 /**
53         Global viscous damping value to use for all rigid bodies in this space (default value is 1.0 which disables damping).
54         This value is the fraction of velocity a body should have after 1 second.
55         A value of 0.9 would mean that each second, a body would have 80% of the velocity it had the previous second.
56 */
57 @property(nonatomic, assign) cpFloat damping;
58
59 /// If a body is moving slower than this speed, it is considered idle. The default value is 0, which signals that the space should guess a good value based on the current gravity.
60 @property(nonatomic, assign) cpFloat idleSpeedThreshold;
61
62 /**
63         Elapsed time before a group of idle bodies is put to sleep (defaults to infinity which disables sleeping).
64         If an entire group of touching or jointed bodies has been idle for at least this long, the space will put all of the bodies into a sleeping state where they consume very little CPU.
65 */
66 @property(nonatomic, assign) cpFloat sleepTimeThreshold;
67
68 /**
69         Amount of encouraged penetration between colliding shapes..
70         Used to reduce oscillating contacts and keep the collision cache warm.
71         Defaults to 0.1. If you have poor simulation quality,
72         increase this number as much as possible without allowing visible amounts of overlap.
73 */
74 @property(nonatomic, assign) cpFloat collisionSlop;
75
76 /**
77         Determines how fast overlapping shapes are pushed apart.
78         Expressed as a fraction of the error remaining after each second.
79         Defaults to pow(1.0 - 0.1, 60.0) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
80 */
81 @property(nonatomic, assign) cpFloat collisionBias;
82
83 /**
84         Number of frames that contact information should persist.
85         Defaults to 3. There is probably never a reason to change this value.
86 */
87 @property(nonatomic, assign) cpTimestamp collisionPersistence;
88
89 /// Returns a pointer to the underlying cpSpace C struct
90 @property(nonatomic, readonly) cpSpace *space;
91
92 /**
93         The space's designated static body.
94         Collision shapes added to the body will automatically be marked as static shapes, and rigid bodies that come to rest while touching or jointed to this body will fall asleep.
95 */
96 @property(nonatomic, readonly) ChipmunkBody *staticBody;
97
98 /**
99         Retrieves the current (if you are in a callback from [ChipmunkSpace step:]) or most recent (outside of a [ChipmunkSpace step:] call) timestep.
100 */
101 @property(nonatomic, readonly) cpFloat currentTimeStep;
102
103 /**
104         Returns true if the space is currently executing a timestep.
105 */
106 @property(nonatomic, readonly) BOOL isLocked;
107 @property(nonatomic, readonly) BOOL locked __deprecated;
108
109 /**
110         An object that this space is associated with. You can use this get a reference to your game state or controller object from within callbacks.
111         @attention Like most @c delegate properties this is a weak reference and does not call @c retain. This prevents reference cycles from occuring.
112 */
113 @property(nonatomic, assign) id userData;
114
115 /// Get the ChipmunkSpace object associciated with a cpSpace pointer.
116 /// Undefined if the cpSpace wasn't created using Objective-Chipmunk.
117 +(ChipmunkSpace *)spaceFromCPSpace:(cpSpace *)space;
118
119 /**
120   Set the default collision handler.
121   The default handler is used for all collisions when a specific collision handler cannot be found.
122   
123   The expected method selectors are as follows:
124         @code
125 - (bool)begin:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
126 - (bool)preSolve:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
127 - (void)postSolve:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
128 - (void)separate:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
129         @endcode
130 */
131 - (void)setDefaultCollisionHandler:(id)delegate
132         begin:(SEL)begin
133         preSolve:(SEL)preSolve
134         postSolve:(SEL)postSolve
135         separate:(SEL)separate;
136
137 /**
138   Set a collision handler to handle specific collision types.
139   The methods are called only when shapes with the specified collisionTypes collide.
140   
141   @c typeA and @c typeB should be the same object references set to ChipmunkShape.collisionType. They can be any uniquely identifying object.
142         Class and global NSString objects work well as collision types as they are easy to get a reference to and do not require you to allocate any objects.
143   
144   The expected method selectors are as follows:
145         @code
146 - (bool)begin:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
147 - (bool)preSolve:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
148 - (void)postSolve:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
149 - (void)separate:(cpArbiter *)arbiter space:(ChipmunkSpace*)space
150         @endcode
151 */
152 - (void)addCollisionHandler:(id)delegate
153         typeA:(cpCollisionType)a typeB:(cpCollisionType)b
154         begin:(SEL)begin
155         preSolve:(SEL)preSolve
156         postSolve:(SEL)postSolve
157         separate:(SEL)separate;
158
159
160 /**
161   Add an object to the space.
162   This can be any object that implements the ChipmunkObject protocol.
163         This includes all the basic types such as ChipmunkBody, ChipmunkShape and ChipmunkConstraint as well as any composite game objects you may define that implement the protocol.
164         @warning This method may not be called from a collision handler callback. See smartAdd: or ChipmunkSpace.addPostStepCallback:selector:context: for information on how to do that.
165 */
166 -(id)add:(NSObject<ChipmunkObject> *)obj;
167
168 /**
169   Remove an object from the space.
170   This can be any object that implements the ChipmunkObject protocol.
171         This includes all the basic types such as ChipmunkBody, ChipmunkShape and ChipmunkConstraint as well as any composite game objects you may define that implement the protocol.
172         @warning This method may not be called from a collision handler callback. See smartRemove: or ChipmunkSpace.addPostStepCallback:selector:context: for information on how to do that.
173 */
174 -(id)remove:(NSObject<ChipmunkObject> *)obj;
175
176 /// Check if a space already contains a particular object:
177 -(BOOL)contains:(NSObject<ChipmunkObject> *)obj;
178
179 /// If the space is locked and it's unsafe to call add: it will call addPostStepAddition: instead.
180 - (id)smartAdd:(NSObject<ChipmunkObject> *)obj;
181
182 /// If the space is locked and it's unsafe to call remove: it will call addPostStepRemoval: instead.
183 - (id)smartRemove:(NSObject<ChipmunkObject> *)obj;
184
185 /// Handy utility method to add a border of collision segments around a box. See ChipmunkShape for more information on the other parameters.
186 /// Returns an NSArray of the shapes. Since NSArray implements the ChipmunkObject protocol, you can use the [ChipmunkSpace remove:] method to remove the bounds.
187 - (NSArray *)addBounds:(cpBB)bounds thickness:(cpFloat)radius
188         elasticity:(cpFloat)elasticity friction:(cpFloat)friction
189         filter:(cpShapeFilter)filter collisionType:(id)collisionType;
190
191
192 /**
193   Define a callback to be run just before [ChipmunkSpace step:] finishes.
194   The main reason you want to define post-step callbacks is to get around the restriction that you cannot call the add/remove methods from a collision handler callback.
195         Post-step callbacks run right before the next (or current) call to ChipmunkSpace.step: returns when it is safe to add and remove objects.
196         You can only schedule one post-step callback per key value, this prevents you from accidentally removing an object twice. Registering a second callback for the same key is a no-op.
197   
198   The method signature of the method should be:
199   @code
200 - (void)postStepCallback:(id)key</code></pre>
201         @endcode
202         
203   This makes it easy to call a removal method on your game controller to remove a game object that died or was destroyed as the result of a collision:
204   @code
205 [space addPostStepCallback:gameController selector:@selector(remove:) key:gameObject];
206         @endcode
207         
208         @attention Not to be confused with post-solve collision handler callbacks.
209         @warning @c target and @c object cannot be retained by the ChipmunkSpace. If you need to release either after registering the callback, use autorelease to ensure that they won't be deallocated until after [ChipmunkSpace step:] returns.
210         @see ChipmunkSpace.addPostStepRemoval:
211 */
212 - (BOOL)addPostStepCallback:(id)target selector:(SEL)selector key:(id)key;
213
214 /// Block type used with [ChipmunkSpace addPostStepBlock:]
215 typedef void (^ChipmunkPostStepBlock)(void);
216
217 /// Same as [ChipmunkSpace addPostStepCallback:] but with a block. The block is copied.
218 - (BOOL)addPostStepBlock:(ChipmunkPostStepBlock)block key:(id)key;
219
220 /// Add the Chipmunk Object to the space at the end of the step.
221 - (void)addPostStepAddition:(NSObject<ChipmunkObject> *)obj;
222
223 /// Remove the Chipmunk Object from the space at the end of the step.
224 - (void)addPostStepRemoval:(NSObject<ChipmunkObject> *)obj;
225
226 /// Return an array of ChipmunkNearestPointQueryInfo objects for shapes within @c maxDistance of @c point.
227 /// The point is treated as having the given group and layers.
228 - (NSArray *)pointQueryAll:(cpVect)point maxDistance:(cpFloat)maxDistance filter:(cpShapeFilter)filter;
229
230 /// Find the closest shape to a point that is within @c maxDistance of @c point.
231 /// The point is treated as having the given layers and group.
232 - (ChipmunkPointQueryInfo *)pointQueryNearest:(cpVect)point maxDistance:(cpFloat)maxDistance filter:(cpShapeFilter)filter;
233
234 /// Return a NSArray of ChipmunkSegmentQueryInfo objects for all the shapes that overlap the segment. The objects are unsorted.
235 - (NSArray *)segmentQueryAllFrom:(cpVect)start to:(cpVect)end radius:(cpFloat)radius filter:(cpShapeFilter)filter;
236
237 /// Returns the first shape that overlaps the given segment. The segment is treated as having the given group and layers. 
238 - (ChipmunkSegmentQueryInfo *)segmentQueryFirstFrom:(cpVect)start to:(cpVect)end radius:(cpFloat)radius filter:(cpShapeFilter)filter;
239
240 /// Returns a NSArray of all shapes whose bounding boxes overlap the given bounding box. The box is treated as having the given group and layers. 
241 - (NSArray *)bbQueryAll:(cpBB)bb filter:(cpShapeFilter)filter;
242
243 /// Returns a NSArray of ChipmunkShapeQueryInfo objects for all the shapes that overlap @c shape.
244 - (NSArray *)shapeQueryAll:(ChipmunkShape *)shape;
245
246 /// Returns true if the shape overlaps anything in the space.
247 - (BOOL)shapeTest:(ChipmunkShape *)shape;
248
249 /// Get a copy of the list of all the bodies in the space.
250 - (NSArray *)bodies;
251
252 /// Get a copy of the list of all the shapes in the space
253 - (NSArray *)shapes;
254
255 /// Get a copy of the list of all the constraints in the space
256 - (NSArray *)constraints;
257
258 /// Update all the static shapes.
259 - (void)reindexStatic;
260
261 /// Update the collision info for a single shape.
262 /// Can be used to update individual static shapes that were moved or active shapes that were moved that you want to query against.
263 - (void)reindexShape:(ChipmunkShape *)shape;
264
265 /// Update the collision info for all shapes attached to a body.
266 - (void)reindexShapesForBody:(ChipmunkBody *)body;
267
268 /// Step time forward. While variable timesteps may be used, a constant timestep will allow you to reduce CPU usage by using fewer iterations.
269 - (void)step:(cpFloat)dt;
270
271 @end
272
273
274 /// ChipmunkHastySpace is an Objective-Chipmunk wrapper for cpHastySpace.
275 /// Subclass this class instead of ChipmunkSpace if you want to enable the cpHastySpace optimizations.
276 /// If ChipmunkHastySpace is linked correctly, calling [[ChipmunkSpace alloc] init] will actually return a ChipmunkHastySpace.
277 @interface ChipmunkHastySpace : ChipmunkSpace
278
279 /// Number of threads to use for the solver.
280 ///     Setting 0 will choose the thread count automatically (recommended).
281 /// There is currently little benefit in using more than 2 threads.
282 /// Defaults to 1.
283 @property(nonatomic, assign) NSUInteger threads;
284
285 @end
286
287
288 //MARK: Misc
289
290 /**
291         A macro that defines and initializes shape variables for you in a collision callback.
292         They are initialized in the order that they were defined in the collision handler associated with the arbiter.
293         If you defined the handler as:
294         
295         @code
296                 [space addCollisionHandler:target typeA:foo typeB:bar ...]
297         @endcode
298         
299         You you will find that @code a->collision_type == 1 @endcode and @code b->collision_type == 2 @endcode.
300 */
301 #define CHIPMUNK_ARBITER_GET_SHAPES(__arb__, __a__, __b__) ChipmunkShape *__a__, *__b__; { \
302         cpShape *__shapeA__, *__shapeB__; \
303         cpArbiterGetShapes(__arb__, &__shapeA__, &__shapeB__); \
304         __a__ = cpShapeGetUserData(__shapeA__); __b__ = cpShapeGetUserData(__shapeB__); \
305 }
306
307 #define CHIPMUNK_ARBITER_GET_BODIES(__arb__, __a__, __b__) ChipmunkBody *__a__, *__b__; { \
308         cpBody *__bodyA__, *__bodyB__; \
309         cpArbiterGetBodies(__arb__, &__bodyA__, &__bodyB__); \
310         __a__ = cpBodyGetUserData(__bodyA__); __b__ = cpBodyGetUserData(__bodyB__); \
311 }
312
313