-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathGSRobot.m
356 lines (302 loc) · 11.1 KB
/
GSRobot.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//
// GSRobot.m
// XBolo
//
// Created by Michael Ash on 9/7/09.
//
#import "GSRobot.h"
#import "bolo.h"
#import "client.h"
#define INTERNAL_GSROBOT_INCLUDE 1 // what a horrible hack
#import "GSRobotExternal.h"
#undef INTERNAL_GSROBOT_INCLUDE
#define ENABLE_LOGGING 0
#if ENABLE_LOGGING
#define LOG(...) NSLog(__VA_ARGS__)
#else
#define LOG(...) (void)0
#endif
@interface GSRobot (internal)
- (id)initWithBundle: (NSBundle *)bundle;
@end
@implementation GSRobot
#define NO_NEW_DATA 0
#define NEW_DATA 1
#define THREAD_EXITED 2
+ (NSArray *)availableRobots
{
static NSMutableArray *robots = nil;
if(!robots)
{
robots = [NSMutableArray array];
NSString *myPath = [[NSBundle mainBundle] bundlePath];
NSString *enclosingPath = [myPath stringByDeletingLastPathComponent];
NSString *botsPath = [enclosingPath stringByAppendingPathComponent: @"Robots"];
NSEnumerator *enumerator = [[[NSFileManager defaultManager] directoryContentsAtPath:botsPath] objectEnumerator];
NSString *name;
LOG(@"availableRobots: myPath:%@ enclosingPath:%@ botsPath:%@ enumerator:%@", myPath, enclosingPath, botsPath, enumerator);
while((name = [enumerator nextObject]))
{
LOG(@"availableRobots: checking file %@", name);
NSString *fullPath = [botsPath stringByAppendingPathComponent: name];
LOG(@"availableRobots: full path %@", fullPath);
if([fullPath hasSuffix: @".xbolorobot"])
{
NSBundle *bundle = [NSBundle bundleWithPath: fullPath];
LOG(@"availableRobots: bundle:%@", bundle);
if([bundle load])
{
[robots addObject: [[[self alloc] initWithBundle: bundle] autorelease]];
LOG(@"availableRobots: load succeeded");
}
}
}
}
return robots;
}
- (id)initWithBundle: (NSBundle *)bundle
{
if((self = [self init]))
{
_bundle = [bundle retain];
_condLock = [[NSConditionLock alloc] initWithCondition: NO_NEW_DATA];
_messages = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
[self unload];
[_bundle release];
[super dealloc];
}
- (NSString *)name
{
return [[_bundle bundlePath] lastPathComponent];
}
- (NSError *)load
{
Class class = [_bundle principalClass];
if([class minimumRobotInterfaceVersionRequired] > GS_ROBOT_CURRENT_INTERFACE_VERSION)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
@"The robot could not be loaded because it requires a newer version of XBolo.", NSLocalizedDescriptionKey,
@"Check to see if a newer version of XBolo is available, and try again.", NSLocalizedRecoverySuggestionErrorKey,
nil];
return [NSError errorWithDomain: NSPOSIXErrorDomain code: EINVAL userInfo: userInfo];
}
_robot = [[class alloc] init];
_halt = NO;
[NSThread detachNewThreadSelector: @selector(_watcherThread) toTarget: self withObject: nil];
return nil; // no errors, never any error, hooray!
}
- (void)unload
{
[_condLock lock];
_halt = YES;
[_condLock unlockWithCondition: NEW_DATA];
[_condLock lockWhenCondition: THREAD_EXITED];
[_condLock unlock];
[_robot release];
_robot = nil;
}
- (void)step
{
NSParameterAssert(_robot);
struct GSRobotGameState gameState;
gameState.worldwidth = WIDTH;
gameState.worldheight = WIDTH;
gameState.tankposition = client.players[client.player].tank;
float gunAngle = client.players[client.player].dir;
float gunDeltaX = cos(gunAngle) * client.range;
float gunDeltaY = -sin(gunAngle) * client.range;
gameState.gunsightposition.x = gameState.tankposition.x + gunDeltaX;
gameState.gunsightposition.y = gameState.tankposition.y + gunDeltaY;
gameState.tankdirection = gunAngle * 8 / M_PI - 0.5;
if(gameState.tankdirection < 0) gameState.tankdirection += 16;
gameState.tankarmor = client.armour;
gameState.tankshells = client.shells;
gameState.tankmines = client.mines;
gameState.tanktrees = client.trees;
gameState.tankhasboat = client.players[client.player].boat ? 1 : 0;
gameState.tankpillcount = 0;
int i;
for(i = 0; i < client.npills; i++)
if(client.pills[i].owner == client.player && client.pills[i].armour == ONBOARD)
gameState.tankpillcount++;
switch(client.players[client.player].builderstatus)
{
case kBuilderReady:
gameState.builderstate = 1;
break;
case kBuilderParachute:
gameState.builderstate = 0;
break;
default:
{
gameState.builderstate = 2;
Vec2f builderDelta = sub2f(gameState.tankposition, client.players[client.player].builder);
gameState.builderdirection = _atan2f(builderDelta);
break;
}
}
struct Tank tanks[MAXPLAYERS];
int readi, writei;
for(readi = 0, writei = 0; readi < MAXPLAYERS; readi++)
{
if(readi != client.player) // don't include self
{
if(client.players[readi].connected && !client.players[readi].dead)
{
if(calcvis(client.players[readi].tank) > 0.1)
{
tanks[writei].friendly = (client.players[readi].alliance & (1 << client.player)
? YES : NO);
tanks[writei].position = client.players[readi].tank;
tanks[writei].direction = client.players[readi].dir * 8 / M_PI - 0.5;
writei++;
}
}
}
}
gameState.tankscount = writei;
// FIXME: should make this be variable
const int maxShellPositions = 256;
struct ExternalShell shells[maxShellPositions];
for(readi = 0, writei = 0; readi < MAXPLAYERS; readi++)
{
if(client.players[readi].connected)
{
struct ListNode *node;
for(node = nextlist(&client.players[readi].shells); node != NULL; node = nextlist(node))
{
struct Shell *shell = ptrlist(node);
if(fogvis(shell->point) > 0.1)
if(writei < maxShellPositions)
{
shells[writei].direction = shell->dir;
shells[writei].position = shell->point;
writei++;
}
}
}
}
gameState.shellscount = writei;
struct Builder builders[MAXPLAYERS];
for(readi = 0, writei = 0; readi < MAXPLAYERS; readi++)
{
if(client.players[readi].connected)
{
int status = client.players[readi].builderstatus;
if(status != kBuilderReady)
if(fogvis(client.players[readi].builder) > 0.1)
{
builders[writei].isParachute = status == kBuilderParachute;
builders[writei].position = client.players[readi].builder;
writei++;
}
}
}
gameState.builderscount = writei;
int totalLength = (sizeof(gameState) +
WIDTH * WIDTH * sizeof(*gameState.visibletiles) +
gameState.tankscount * sizeof(*gameState.tanks) +
gameState.shellscount * sizeof(*gameState.shells) +
gameState.builderscount * sizeof(*gameState.builders));
NSMutableData *data = [NSMutableData dataWithLength: totalLength];
void *ptr = [data mutableBytes];
memcpy(ptr, &gameState, sizeof(gameState));
struct GSRobotGameState *gsp = ptr;
ptr += sizeof(gameState);
memcpy(ptr, client.seentiles, WIDTH * WIDTH * sizeof(*gameState.visibletiles));
gsp->visibletiles = ptr;
ptr += WIDTH * WIDTH * sizeof(*gameState.visibletiles);
int size;
size = gameState.tankscount * sizeof(*gameState.tanks);
memcpy(ptr, tanks, size);
gsp->tanks = ptr;
ptr += size;
size = gameState.shellscount * sizeof(*gameState.shells);
memcpy(ptr, shells, size);
gsp->shells = ptr;
ptr += size;
size = gameState.builderscount * sizeof(*gameState.builders);
memcpy(ptr, builders, size);
gsp->builders = ptr;
ptr += size;
[_condLock lock];
if([_condLock condition] == THREAD_EXITED)
{
[_condLock unlock];
}
else
{
[_gamestateData release];
_gamestateData = [data retain];
[_condLock unlockWithCondition: NEW_DATA];
}
}
- (void)receivedMessage: (NSString *)message
{
[_messages addObject: message];
}
- (void)_watcherThread
{
while(1)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[_condLock lockWhenCondition: NEW_DATA];
if(_halt)
{
[_condLock unlockWithCondition: THREAD_EXITED];
return;
}
NSMutableData *gsdata = [_gamestateData retain];
NSArray *messages = [_messages copy];
[_messages removeAllObjects];
((struct GSRobotGameState *)[gsdata mutableBytes])->messages = messages;
[_condLock unlockWithCondition: NO_NEW_DATA];
NSArray *objectsToDestroy = [[NSArray alloc] initWithObjects: gsdata, messages, nil];
struct GSRobotCommandState commandState = [_robot stepXBoloRobotWithGameState: (void *)[gsdata bytes] freeFunction: (void *)CFRelease freeContext: objectsToDestroy];
[gsdata release];
[messages release];
int keys = 0;
if(commandState.accelerate) keys |= ACCELMASK;
if(commandState.decelerate) keys |= BRAKEMASK;
if(commandState.left) keys |= TURNLMASK;
if(commandState.right) keys |= TURNRMASK;
if(commandState.gunup) keys |= INCREMASK;
if(commandState.gundown) keys |= DECREMASK;
if(commandState.mine) keys |= LMINEMASK;
if(commandState.fire) keys |= SHOOTMASK;
keyevent(keys, 1);
keyevent(~keys, 0);
if(commandState.buildercommand != BUILDERNILL)
{
Pointi p = { commandState.builderx, commandState.buildery };
buildercommand(commandState.buildercommand, p);
}
if([commandState.playersToAllyWith count])
{
lockclient();
uint16_t players = 0;
int i, j;
for(j = 0; j < [commandState.playersToAllyWith count]; j++)
{
NSString *name = [commandState.playersToAllyWith objectAtIndex: j];
const char *cname = [name UTF8String];
for(i = 0; i < MAXPLAYERS; i++)
{
if(client.players[i].connected)
if(strncmp(client.players[i].name, cname, MAXNAME) == 0)
players |= 1 << i;
}
}
if(players)
requestalliance(players);
unlockclient();
}
[pool release];
}
}
@end