/* aircraft.c */ /* aircraft initialization module for hypothetical gaming system */ #include "ray.h" #define AC_COOKIE 12345932 #define AC_MASK 7 typedef struct aircraft_type { int cookie; int attrmask; char name[NAME_LEN]; vec_t position; vec_t direction; double speed; } aircraft_t; static inline int getndx( char *attrs[], /* Table of attribute names */ int count, /* Number of attribute names */ char *target) /* name from input */ { int code = -1; int i; for (i = 0; i < count; i++) { if (strcmp(target, attrs[i]) == 0) return(i); } return(code); } static char *ac_attrs[] = { "position", /* Current location of aircraft */ "direction", /* Direction of travel */ "speed", /* Speed in NM/hr */ }; #define NUM_ATTRS (sizeof(ac_attrs)/ sizeof(char *)) static inline void aircraft_load_position( FILE *in, aircraft_t *ac) { int count; assert(ac->cookie == AC_COOKIE); count = fscanf(in, "%lf %lf %lf", &ac->position.x, &ac->position.y, &ac->position.z); assert(count == 3); } static inline void aircraft_load_direction( FILE *in, aircraft_t *ac) { int count; assert(ac->cookie == AC_COOKIE); count = fscanf(in, "%lf %lf %lf", &ac->direction.x, &ac->direction.y, &ac->direction.z); assert(count == 3); } static inline void aircraft_load_speed( FILE *in, aircraft_t *ac) { int count; assert(ac->cookie == AC_COOKIE); count = fscanf(in, "%lf", &ac->speed); assert(count == 1); } static inline void aircraft_attr_load( FILE *in, aircraft_t *aircraft, char *attr) { char buf[18]; int ndx; assert(aircraft->cookie == AC_COOKIE); ndx = getndx(ac_attrs, NUM_ATTRS, attr); assert(ndx >= 0); aircraft->attrmask |= 1 << ndx; if (ndx == 0) aircraft_load_position(in, aircraft); else if (ndx == 1) aircraft_load_direction(in, aircraft); else aircraft_load_speed(in, aircraft); } /**/ /* Initialize aircraft data */ aircraft_t *aircraft_init( FILE *in) { char buf[256]; int count; /* Create new aircraft structure */ aircraft_t *aircraft = malloc(sizeof(aircraft_t)); assert(aircraft != NULL); memset(aircraft, 0, sizeof(aircraft_t)); aircraft->cookie = AC_COOKIE; /* Verify the entity name */ fscanf(in, "%s", buf); assert(strcmp(buf, "aircraft") == 0); /* Acquire the name of the aircraft */ fscanf(in, "%s", aircraft->name); /* consume the "{" and verify we found it */ fscanf(in, "%s", buf); assert(buf[0] == '{'); /* load required attributes */ count = fscanf(in, "%s", buf); while ((count == 1) && (buf[0] != '}')) { aircraft_attr_load(in, aircraft, buf); *buf = 0; count = fscanf(in, "%s", buf); } /* verify the closing '}' */ assert(buf[0] == '}'); /* Verify all required attributes loaded */ assert(aircraft->attrmask == AC_MASK); return(aircraft); } main() { aircraft_init(stdin); }