static void triangleDrawTileFast(float *tilebuffer, const Triangle3DSetup &t, int x, int y)
{
	const Vec denom = vecRcp(vec(t.dx1 * t.dy2 - t.dy1 * t.dx2));

	const Vec DY2 = vec(t.dy2);
	const Vec DY3 = vec(t.dy3);
	const Vec DX2 = vec(t.dx2);
	const Vec DX3 = vec(t.dx3);

	const Vec X3  = vec(t.x3);
	const Vec Y3  = vec(t.y3);
	const Vec Z1  = vec(t.z1);
	const Vec Z2  = vec(t.z2);
	const Vec Z3  = vec(t.z3);

	const Vec One  = vec(1);
	const Vec Step = vec(0, 1, 2, 3);

	for(int iy = 0; iy < tileHeight; iy++)
	{
		Vec yp = vec(float(y + iy));

		float fx = (float)x;
		const Vec ypos = vecSub(yp, Y3);
		const Vec dxypos2 = vecMul(DX2, ypos);
		const Vec dxypos3 = vecMul(DX3, ypos);
		for(int ix = 0; ix < tileWidth; ix += 4, fx += 4)
		{
			void * ptr  = &tilebuffer[ix + iy * tileWidth];

			const Vec xp    = vecAdd(vec(fx), Step);

			// Calculate barycentric coordinates and depth
			const Vec xpos = vecSub(xp, X3);

			const Vec dyxpos2 = vecMul(DY2, xpos);
			const Vec dyxpos3 = vecMul(DY3, xpos);

			const Vec delta2 = vecSub(dyxpos2, dxypos2);
			const Vec delta3 = vecSub(dyxpos3, dxypos3);

			const Vec t1 = vecMul(delta2, denom);
			const Vec t2 = vecMul(delta3, denom);
			const Vec t3 = vecSub(vecSub(One, t1), t2);

			const Vec tz1 = vecMul(Z1, t1);
			const Vec tz2 = vecMul(Z2, t2);
			const Vec tz3 = vecMul(Z3, t3);

			const Vec z  = vecAdd(tz1, vecAdd(tz2, tz3));

			// Depth compare
			const Vec Value			= vecLoadAligned(ptr);
			const Vec DepthCompare	= vecCmpGE(Value, z);
			const Vec Result		= vecSel(Value, z, DepthCompare);

			vecStoreAligned(ptr, Result);
		}
	}
}
Example #2
0
	void SpecialCallBack(int key, int x, int y) {
		bool needRedisplay = true;

        switch (key) {
			case GLUT_KEY_LEFT: {
				animCamera = false;
				cl_float3 t = scene->cam.viewCenter;
				vecSub(t,  scene->cam.eye);
				t.s[0] = t.s[0] * cosf(-ROTATE_STEP) - t.s[2] * sinf(-ROTATE_STEP);
				t.s[2] = t.s[0] * sinf(-ROTATE_STEP) + t.s[2] * cosf(-ROTATE_STEP);
				vecAdd(t, scene->cam.eye);
				camLookAt(scene->cam, t);
				break;
			}
			case GLUT_KEY_RIGHT: {
				animCamera = false;
				cl_float3 t = scene->cam.viewCenter;
				vecSub(t,  scene->cam.eye);
				t.s[0] = t.s[0] * cosf(ROTATE_STEP) - t.s[2] * sinf(ROTATE_STEP);
				t.s[2] = t.s[0] * sinf(ROTATE_STEP) + t.s[2] * cosf(ROTATE_STEP);
				vecAdd(t, scene->cam.eye);
				camLookAt(scene->cam, t);
				break;
			}
			case GLUT_KEY_PAGE_UP: {
				animCamera = false;
				cl_float3 t;
				vecInit(t, 0.f, MOVE_STEP / 4.f, 0.f);
				vecAdd(scene->cam.viewCenter, t);
				camUpdate(scene->cam);
				break;
			}
			case GLUT_KEY_PAGE_DOWN: {
				animCamera = false;
				cl_float3 t;
				vecInit(t, 0.f, -MOVE_STEP / 4.f, 0.f);
				vecAdd(scene->cam.viewCenter, t);
				camUpdate(scene->cam);
				break;
			}
			default:
				needRedisplay = false;
				break;
		}

		if (needRedisplay)
			glutPostRedisplay();
	}
void ModifyRepairEffect(Effect *effect,Ship *ship,vector *trajectory,real32 distance, SpaceObjRotImpTarg *target)
{
    ShipStaticInfo *shipstatic = (ShipStaticInfo *)ship->staticinfo;
    RepairNozzleStatic *repnozzlestatic = shipstatic->repairNozzleStatic;
    vector repairBeamPosition;

    dbgAssertOrIgnore(effect);

    matMultiplyMatByVec(&repairBeamPosition,&ship->rotinfo.coordsys,&repnozzlestatic->position);

    vecAdd(effect->posinfo.position,repairBeamPosition,ship->posinfo.position);

    matCreateCoordSysFromHeading(&effect->rotinfo.coordsys,trajectory);

	distance = max(200.0f,distance);
	if(target->objtype == OBJ_ShipType)
	{
		if(((Ship *)target)->shiptype == Mothership)
		{
			distance = max(800.0f,distance);
		}
	}


    ((real32 *)effect->variable)[ETG_ResourceLengthParam] = distance;
    ((real32 *)effect->variable)[ETG_ResourceRadiusParam] = target->staticinfo->staticheader.staticCollInfo.collspheresize;
}
Example #4
0
void getRotatePoint(Ship *ship, vector *point, real32 *distance)
{
    Node *slavenode;
    Ship *slave;
    udword count;
    vector dist;

    dbgAssertOrIgnore(ship->flags & SOF_Slaveable);     //ship should be slaveable
    dbgAssertOrIgnore(ship->slaveinfo->slaves.num >= 5);    //need enough for a pie plate!

    slavenode = ship->slaveinfo->slaves.head;
    point->x = ship->posinfo.position.x;
    point->y = ship->posinfo.position.y;
    point->z = ship->posinfo.position.z;

    count = 0;
    while (count < 5)
    {
        slave = (Ship *) listGetStructOfNode(slavenode);
        vecAdd(*point, *point, slave->posinfo.position);
        slavenode = slavenode->next;
        count++;
    }
    point->x /= 6.0f;
    point->y /= 6.0f;
    point->z /= 6.0f;

    vecSub(dist,ship->posinfo.position, *point);
    *distance = vecMagnitudeSquared(dist);
    *distance = fsqrt(*distance);
}
Example #5
0
void updateCamera(Scene* scene) {
	double time = WallClockTime() - sceneTimeOffset;
	double rtime = (time / 21.35634); // camera rotation time
	rtime = rtime - floor(rtime);

	double btime = (time / 59.8752); // camera bobbing time
	btime = btime - floor(btime);

	double ltime = (time / 98.7654); // light rotation time
	ltime = ltime - floor(ltime);

	double lbtime = (time / 92.764); // light bobbing time
	lbtime = lbtime - floor(lbtime);

	camInit(scene->cam);
	cl_float3 pos;
	cl_float3 center;
	vecInit(center, 14.9f, 9.7f, -14.85f);
	vecInit(pos, 33.0f * sin(rtime * M_PI * 2.0),
			8.0f * sin(btime * M_PI * 2.0 + 0.3),
			33.0f * (cos(rtime * M_PI * 2.0) - 0.11));
	vecAdd(pos, center);
	camMove(scene->cam, pos);
	camLookAt(scene->cam, center);

	vecInit(pos, 5.0f * sin(-ltime * M_PI * 2.0),
			8.0f + 6.0f * sin(lbtime * M_PI * 2.0),
			5.0f * cos(ltime * M_PI * 2.0));
	vecNormalize(pos);
	scene->lightDir = pos;
}
Example #6
0
static void update_system( uFloat *z, uFloat *x_pre,
			 uFloat **K, uFloat *x_post )
{
#ifdef PRINT_DEBUG
  printf( "ekf: updating system\n" );
#endif

  apply_measurement( x_pre, z_estimate ); /* z_estimate = h ( x_pre ) */
  vecSub( z, z_estimate, z_estimate, MEAS_SIZE ); /* z_estimate = z - z_estimate */
  matMultVector( K, z_estimate, x_post, STATE_SIZE, MEAS_SIZE ); /* x_post = K * (z- z_estimate) */
  vecAdd( x_post, x_pre, x_post, STATE_SIZE ); /* x_post + x_pre + K * (z-z_estimate) */
}
Example #7
0
void fpscont(Camera* cam) {

    // Rip out position
    //
    float vec_pos[4];
    float* mat_world = cam->mat_world;
    memcpy(vec_pos, &mat_world[12], sizeof(vec_pos));
    memset(&mat_world[12], 0, sizeof(float) * 3);


    // Mouse-look
    //
    short center_x = display.getWidth()/2;
    short center_y = display.getHeight()/2;

    short delta_x = mouse.pos[0] - center_x;
    short delta_y = mouse.pos[1] - center_y;
    mouse.setPos(center_x, center_y);

    float mat_rotx[16];
    matRot(mat_rotx, delta_y * -0.001f, 0);
    matMul(mat_world, mat_rotx, mat_world);

    float mat_roty[16];
    matRot(mat_roty, delta_x * -0.001f, 1);
    matMul(mat_roty, mat_world, mat_world);


    // Movement
    //
    char up_down = keyboard.keyDown('w') - keyboard.keyDown('s');
    char right_left = keyboard.keyDown('d') - keyboard.keyDown('a');

    float speed = 0.5;
    float vec_vel[4];
    vec_vel[0] = right_left * speed;
    vec_vel[1] = 0;
    vec_vel[2] = -up_down * speed;
    vec_vel[3] = 1;

    matMulVec(mat_world, vec_vel, vec_vel);

    vecAdd(vec_pos, vec_vel, vec_pos);
    vec_pos[3] = 1;

    memcpy(cam->mat_view, cam->mat_world, sizeof(float) * 16);
    memcpy(&cam->mat_world[12], vec_pos, sizeof(vec_pos));

    cameraWorldToView(cam);



}
Example #8
0
void getAvgNormal(float *retNorm, float *depthBuf, int x, int y, int width, int height, int nSampleRad)
{
	float tmp[3] = {0};
	unsigned nAvailableCount = 0;

	for(int j = -nSampleRad; j <= nSampleRad; j ++)
	for(int i = -nSampleRad; i <= nSampleRad; i ++)
	{
		int currX = x + i;
		int currY = y + j;
		if( currX >=0 && currX < width &&
			currY >=0 && currY < height )
		{
			float fd = *(depthBuf + (currX + currY * width));
			if(fd > 0)
			{
				float currNorm[3];

				//	The sampled normal should get an average value ...
				float dz_x = dz2x(currX, currY, width, height, depthBuf);
				float dz_y = dz2y(currX, currY, width, height, depthBuf);

				float Cx = i == 0 ? 0 : 2.f / (width * currX);	
				float Cy = j == 0 ? 0 : 2.f / (height * currY);	

				float D = Cy * Cy * dz_x * dz_x + Cx * Cx * dz_y * dz_y + Cx * Cx * Cy * Cy * (1 - fd) * (1 - fd);
				if(D == 0)
				{
					continue;
				}
				float rv_sqrtD = 1.f / sqrt(D);

				currNorm[0] = - Cy * dz_x * rv_sqrtD;
				currNorm[1] = - Cx * dz_y * rv_sqrtD;
				currNorm[2] = Cx * Cy * (1 - fd) * rv_sqrtD;

				vecAdd(tmp, currNorm, tmp);
				nAvailableCount ++;
			}
		}
	}

	if(nAvailableCount > 0)
	{
		vecScale(tmp, 1.f/nAvailableCount, tmp);
		normalize(tmp);
		vecCopy(retNorm, tmp);
	}
}
Example #9
0
/* take the definition of a camera and a point within the film plane of the camera and generate a RAY
   x and y both have a range of -0.5 to +0.5 */
Ray *camGenerateRay(Camera *camera, double x, double y, Ray *ray){
	Vec direction;
	Vec cameraX, cameraY;
	
	/* work out direction camera is pointing in */
	vecSub(&(camera->lookAt), &(camera->at), &direction);
	vecNormalise(&direction, &direction);

	/* using that and DOWN, work out the camera axes and normalise */
	vecProduct(&direction, &(camera->down), &cameraX);
	vecProduct(&direction, &cameraX, &cameraY);
	vecNormalise(&cameraX, &cameraX);
	vecNormalise(&cameraY, &cameraY);
	
	/* finally combine film offset and camera axes to work out film position */
	vecScale(x * camera->width, &cameraX, &cameraX);
	vecScale(y * camera->height, &cameraY, &cameraY);
	vecScale(camera->depth, &direction, &direction);
	vecAdd(&cameraX, &direction, &direction);
	vecAdd(&cameraY, &direction, &direction);
	
	rayInit(&(camera->at), &direction, ray);
	return ray;
}
Example #10
0
Path *
pathNew( Vertex* origin, int init_size, int expand_delta ) {
    Path *this = (Path*)malloc(sizeof(Path));
    
    this->vertices = vecNew( init_size, expand_delta );
    this->edges = vecNew( init_size, expand_delta );
    
    /*
     * A path is an alternating series of (vertex, edge, vertex, edge, vertex) 
     * elements. As such a complete path always has one more vertices than 
     * edges. One way to deal with this inconveniently dangling Vertex is to
     * specify it at path initialization.
     */
    vecAdd( this->vertices, origin );
    
    return this;
}
Example #11
0
void PhysicsWorld::StepPhysics()
{
	for(unsigned int i = 0; i < staticEntities.size(); i++)
	{
		StaticPhysicsEntity *s = staticEntities[i];
		Transform *t = entGetTransform(s->ent);
		s->position = t->GetPosition();
	}

	for(unsigned int j = 0; j < dynamicEntities.size(); j++)
	{
		DynamicPhysicsEntity *d = dynamicEntities[j];

		Transform *t = entGetTransform(d->ent);
		d->position = t->GetPosition();
		d->position = vecAdd(d->position, d->velocity);
		t->SetPosition(d->position);
	}
}
Example #12
0
static void
get_target_position(stateVector *st, double look, double yaw,
                    double sr, vector *targPos)
{
  vector relPos = vecNew(sin(yaw), -sin(look)*cos(yaw), -cos(look)*cos(yaw));

  // relPos unit vector points from s/c to targPos.
  // Rotate into earth axes
  vector look_matrix[3];
  look_matrix[2] = st->pos;
  vecNormalize(&look_matrix[2]);
  vector v = st->vel;
  vecNormalize(&v);
  vecCross(look_matrix[2],v,&look_matrix[1]);
  vecCross(look_matrix[1],look_matrix[2],&look_matrix[0]);
  vecMul(look_matrix,relPos,&relPos);

  // scale relPos so it reaches from s/c to targPos 
  vecScale(&relPos,sr);
  vecAdd(relPos,st->pos,targPos);
}
Example #13
0
void PhysicsWorld::ResolveCollisions()
{
	for(unsigned int i = 0; i < collidedObjectsCnt; i++)
	{
		CollisionInfo &inf = collidedObjects[i];

		// Just push the contact out by the velocity so we never
		// end up in a state where the two objects are still intersecting
		Transform *t = entGetTransform(inf.obj->ent);
		inf.obj->position = t->GetPosition();
		inf.obj->position = vecSub(inf.obj->position, inf.obj->velocity);

		inf.obj->velocity = vecReflect(inf.obj->velocity, inf.normal);
		inf.obj->velocity = vecMul(inf.obj->velocity, vec(1, 1, 0, 0));

		inf.obj->position = vecAdd(inf.obj->position, inf.obj->velocity);
		t->SetPosition(inf.obj->position);
	}

	collidedObjectsCnt = 0;
}
Example #14
0
main () 
{
  int *a,*b,*c;
  clock_t begin, end;
	double time_spent;
	a = NULL;
  b = NULL;
  c = NULL;
  a = (int *) malloc ( sizeof(int) * TAM);
  b = (int *) malloc ( sizeof(int) * TAM);
  c = (int *) malloc ( sizeof(int) * TAM);
  initialize(a,b);
  begin = clock();
  vecAdd(a,b,c);
  end = clock();
  printAdd(a,b,c);
  time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
  printf("Se ha demorado %f segundos.\n",time_spent);
  free(a);
  free(b);
  free(c);
}
int triangleClipToPlane(Vec *src, Vec *dst, int size, Vec plane)
{
	int idx = 0;

	Vec current = *src;

	for(int i = 1; i < size + 1; i++)
	{
		Vec next = src[i % size];

		Vec distNext	= vecDot(plane, next);
		Vec distCurrent = vecDot(plane, current);
		Vec delta       = vecSub(distCurrent, distNext);

		bool goingInNext  = vecGetElem(distNext, 0) > 0;
		bool crossingEdge = goingInNext != vecGetElem(distCurrent, 0) > 0;

		if(crossingEdge)
		{
			// output interpolated vertex
			Vec ratio = vecMul(distCurrent, vecRcp(delta));
			dst[idx]  = vecAdd(current, vecMul(vecSub(next, current), ratio));
			idx++;
		}

		if(goingInNext)
		{
			// output vertex as-is
			dst[idx] = next;
			idx++;
		}

		current = next;
	}

	return idx;
}
Example #16
0
static void rungeKutta( uFloat *old_state, uFloat *new_state )
{

#ifdef PRINT_DEBUG
  printf( "ekf: rungeKutta\n" );
#endif

  /* k1 = period * F( old_state ) */	
  systemF( tempState, old_state );
  vecScalarMult( tempState, PERIOD, k1, STATE_SIZE );

  /* k2 = period * F( old_state + k1 * 0.5) */
  vecScalarMult( k1, 0.5, tempState, STATE_SIZE ); /* tempState = k1 * 0.5 */
  vecAdd( old_state, tempState, tempState, STATE_SIZE );  /* tempState = old_state + k1 * 0.5 */
  systemF( tempState, old_state );
  vecScalarMult( tempState, PERIOD, k2, STATE_SIZE );

  /* k3 = period * F( old_state + k2 * 0.5) */
  vecScalarMult( k2, 0.5, tempState, STATE_SIZE ); /* tempState = k2 * 0.5 */
  vecAdd( old_state, tempState, tempState, STATE_SIZE );  /* tempState = old_state + k2 * 0.5 */
  systemF( tempState, old_state );
  vecScalarMult( tempState, PERIOD, k3, STATE_SIZE );
  
  /* k4 = period * F( old_state + k3) */
  vecAdd( old_state, tempState, tempState, STATE_SIZE );  /* tempState = old_state + k3 */
  systemF( tempState, old_state );
  vecScalarMult( tempState, PERIOD, k4, STATE_SIZE );

  /*  new_state = old_state + 0.16667 * ( k1 + 2*k2 + 2*k3 + k4 ) */
  vecCopy( k1, new_state, STATE_SIZE );
  vecScalarMult( k2, 2.0, tempState, STATE_SIZE );
  vecAdd( new_state, tempState, new_state, STATE_SIZE);
  vecScalarMult( k3, 2.0, tempState, STATE_SIZE );
  vecAdd( new_state, tempState, new_state, STATE_SIZE);
  vecAdd( new_state, k4, new_state, STATE_SIZE);
  vecScalarMult( new_state, 0.16667, new_state, STATE_SIZE );
  vecAdd( new_state, old_state, new_state, STATE_SIZE);

}
bool FindBestPlaceForAdvanceSupportFrigate(vector *destination)
{
    Ship *myMothership = aiCurrentAIPlayer->player->PlayerMothership;
    Ship *enemyMothership = aiuFindEnemyMothership(aiCurrentAIPlayer->player);
    vector diff;

    if (myMothership == NULL)
    {
        return FALSE;
    }

    if (enemyMothership == NULL)
    {
        return FALSE;
    }

    vecSub(diff,enemyMothership->posinfo.position,myMothership->posinfo.position);

    vecMultiplyByScalar(diff,ASF_POSITION_TO_ENEMY_MOTHERSHIP);

    vecAdd(*destination,myMothership->posinfo.position,diff);

    return TRUE;
}
void doKamikazeAttack(Ship *ship,SpaceObjRotImpTarg *target)
{
    real32 mag,dist,range,shipvel;
    vector destination,trajectory,heading,shipheading,EinsteinVelocity;
    ShipStaticInfo *shipstaticinfo = ship->staticinfo;

    vecSub(trajectory,target->collInfo.collPosition,ship->posinfo.position);
    mag = vecMagnitudeSquared(trajectory);
    dist = fsqrt(mag);

    destination = trajectory;
    vecNormalize(&destination);
    heading = destination;

    //this hokey fudge factor is needed so the kamikaze ship doesn't
    //slow down as it reaches its destination
    mag = dist + 500.0f;
    vecScalarMultiply(destination,destination,mag);
    vecAddTo(destination,target->collInfo.collPosition);

    range = RangeToTargetGivenDist(ship,target,dist);

    switch(ship->kamikazeState)
    {
    case K_Start:
        //if within a threshold range
        bitClear(ship->specialFlags,SPECIAL_KamikazeCrazyFast);
        if(range < 500.0f)
        {
            //calculate flyby dist
            matGetVectFromMatrixCol3(shipheading, ship->rotinfo.coordsys);
            vecScalarMultiply(shipheading,shipheading,kamikazeFlyByDist);
            vecAdd(ship->kamikazeVector,shipheading,target->collInfo.collPosition);
            ship->kamikazeState = K_TurnAround;
        }
        ship->kamikazeState = K_Ram;

        break;

    case K_Ram:
        if (range < 400.0f)
        {
            ship->kamikazeState = K_Yell;
        }
    case K_Ram2:
        //lets use...mmmmm..twister theor...no...relativity
        vecSub(EinsteinVelocity,ship->posinfo.velocity,target->posinfo.velocity);
        shipvel = fsqrt(vecMagnitudeSquared(EinsteinVelocity));
        if(ship->shiptype == MinelayerCorvette)
        {
            ((MinelayerCorvetteSpec *)(ship->ShipSpecifics))->mineaistate = MINE_DROP_ATTACK;
        }
        else if (ship->shiptype == DefenseFighter)
        {
            goto dontshoot;
        }

        if (isShipStaticInterceptor(shipstaticinfo))
        {
            if (range < shipstaticinfo->bulletRange[ship->tacticstype])
            {
                GenericInterceptorStatics *interceptorstat = (GenericInterceptorStatics *)shipstaticinfo->custstatinfo;
                uword targetIndex;

                if (target->objtype == OBJ_ShipType)
                {
                    targetIndex = (uword)((ShipStaticInfo *)target->staticinfo)->shipclass;
                }
                else
                {
                    targetIndex = (uword)NUM_CLASSES;
                }

                if (GenericInterceptorCanFire(ship,target,&trajectory,interceptorstat->triggerHappy[ship->tacticstype][targetIndex]))
                {
                    ship->staticinfo->custshipheader.CustShipFire(ship,target);
                }
            }
        }
        else
        {
            gunShootGunsAtTarget(ship,target,range,&trajectory);
        }
dontshoot:
        aishipFlyToPointAvoidingObjs(ship,&destination,AISHIP_PointInDirectionFlying | AISHIP_FirstPointInDirectionFlying | AISHIP_FastAsPossible,0.0f);
        if(range < 1500.0f)
        {
            bitSet(ship->specialFlags,SPECIAL_KamikazeCrazyFast);
        }
        else
        {
            bitClear(ship->specialFlags,SPECIAL_KamikazeCrazyFast);
        }

/*
        if(range < 400.0f && (shipvel < ship->staticinfo->staticheader.maxvelocity*0.7f ||
                   vecDotProduct(trajectory,heading) < 0))
        {
            //ship is inside 400.0f, and isn't faceing ship, or isn't
            //going fast enough

            //calculate flyby dist
            matGetVectFromMatrixCol3(shipheading, ship->rotinfo.coordsys);
            vecScalarMultiply(shipheading,shipheading,kamikazeFlyByDist);
            vecAdd(ship->kamikazeVector,shipheading,target->posinfo.position);
            ship->kamikazeState = K_TurnAround;
        }
*/
        break;
    case K_TurnAround:
        bitClear(ship->specialFlags,SPECIAL_KamikazeCrazyFast);
        aishipFlyToPointAvoidingObjs(ship,&ship->kamikazeVector,AISHIP_PointInDirectionFlying | AISHIP_FirstPointInDirectionFlying | AISHIP_FastAsPossible,0.0f);
        if(MoveReachedDestinationVariable(ship,&ship->kamikazeVector,300.0f))
            ship->kamikazeState = K_TurnAround2;
        break;
    case K_TurnAround2:
        bitClear(ship->specialFlags,SPECIAL_KamikazeCrazyFast);
        if(aitrackHeadingWithFlags(ship,&heading,0.90f,AITRACKHEADING_IGNOREUPVEC))
            ship->kamikazeState = K_Ram;
        break;
    case K_Yell:
//      speechEvent(ship, COMM_LInt_Kamikaze, 0);
        battleChatterAttempt(SOUND_EVENT_DEFAULT, BCE_Kamikaze, ship, SOUND_EVENT_DEFAULT);
        ship->kamikazeState = K_Ram2;
        break;
    }

        //fire guns here...
    //
    //
    //Sound note:   Could put in kamikaze state change here after
    //              getting to within a certain distance of target
    //
    //          ask bryce how to...
}
void defensefightertargetbullet(Ship *ship, Bullet *bullettotarget)
{
    DefenseFighterSpec *spec = (DefenseFighterSpec *)ship->ShipSpecifics;
    DefenseFighterStatics *defensefighterstatics;
    DefenseStruct *newdefensestruct;
    Bullet *laser;
    GunStatic *gunstatic;
    Gun *gun;
    ShipStaticInfo *shipstatic;
    vector positionInWorldCoordSys,tempvec;
    real32 floatDamage;
    udword intDamage;
    udword intVelocity;
    udword intLength;
    etgeffectstatic *stat;
    etglod *etgLOD;
    sdword LOD;
    Effect *newEffect;

#ifdef HW_BUILD_FOR_DEBUGGING
/*    dbgMessagef("B: %d %x %x %f %f %f %x %f %x",universe.univUpdateCounter,
                                    bullettotarget->flags,
                                    bullettotarget->owner,
                                    bullettotarget->timelived,
                                    bullettotarget->damage,
                bullettotarget->damageFull,
                bullettotarget->SpecialEffectFlag,
                bullettotarget->BulletSpeed,
                bullettotarget);
*/
#endif
    gun = &ship->gunInfo->guns[0];
    gunstatic = gun->gunstatic;
    shipstatic = (ShipStaticInfo *)ship->staticinfo;
    defensefighterstatics = (DefenseFighterStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;

    bitSet(bullettotarget->SpecialEffectFlag, 0x0002);   //set the flag

    laser = memAlloc(sizeof(Bullet),"Bullet",0);
    memset(laser,0,sizeof(Bullet));      // for safety

    laser->objtype = OBJ_BulletType;
    laser->flags = 0;
    laser->staticinfo = NULL;
    ClearNode(laser->renderlink);
    laser->currentLOD = ship->currentLOD;
    laser->cameraDistanceSquared = ship->cameraDistanceSquared;

    laser->soundType = gunstatic->gunsoundtype;
    laser->bulletType = BULLET_Laser;
    laser->owner = ship;
    laser->gunowner = gun;
    laser->target = NULL;

    laser->bulletColor = etgBulletColor[shipstatic->shiprace][laser->soundType];

    laser->bulletmass = 0.0f; //gunstatic->bulletmass;
    laser->lengthmag = 600.0f;
    laser->damage = frandombetween(defensefighterstatics->DamageReductionLow,
                                     defensefighterstatics->DamageReductionHigh);
    laser->timelived = 0.0f;
    laser->totallifetime = 100.0f;  //laser will only live for a sec anyways...
    laser->SpecialEffectFlag = 0;
    laser->traveldist = gunstatic->bulletlength;
    laser->beamtraveldist = gunstatic->bulletlength;

    //SET_MOVING_LINEARLY(laser->posinfo.isMoving);
    //laser->posinfo.haventCalculatedDist = TRUE;
    laser->DFGFieldEntryTime = 0.0f;

    matMultiplyMatByVec(&positionInWorldCoordSys,&ship->rotinfo.coordsys,&gunstatic->position);
    vecAdd(laser->posinfo.position,positionInWorldCoordSys,ship->posinfo.position);
    vecSub(laser->lengthvec, bullettotarget->posinfo.position, laser->posinfo.position);
    // heading
    tempvec = laser->lengthvec;
    vecNormalize(&tempvec);

    //matMultiplyMatByVec(&gunheadingInWorldCoordSys, &ship->rotinfo.coordsys, &tempvec);
    //laser->bulletheading = gunheadingInWorldCoordSys;
    laser->bulletheading = tempvec;
    matCreateCoordSysFromHeading(&laser->rotinfo.coordsys,&tempvec);

    vecZeroVector(laser->posinfo.velocity);

    //Laser effect...
    floatDamage = (real32)laser->damage;
    intDamage = TreatAsUdword(floatDamage);
    intVelocity = TreatAsUdword(gunstatic->bulletspeed);
    intLength = TreatAsUdword(gunstatic->bulletlength);
    //create an effect for bullet, if applicable

    etgLOD = etgGunEventTable[shipstatic->shiprace][gunstatic->gunsoundtype][EGT_GunBullet];//get pointer to bullet effect
    //etgLOD = etgGunEventTable[0][gunstatic->gunsoundtype][EGT_GunBullet];//get pointer to bullet effect
  //in future change back to proper one above...
    if (etgLOD != NULL)
    {
        if (bullettotarget != NULL)
        {
          LOD = min(ship->currentLOD, bullettotarget->currentLOD);
        }
        else
        {
          LOD = ship->currentLOD;
        }
        if (LOD >= etgLOD->nLevels)
        {
          stat = NULL;
        }
        else
        {
          stat = etgLOD->level[LOD];
        }
    }
    else
    {
      stat = NULL;
    }
#if ETG_DISABLEABLE
    if (stat != NULL && etgBulletEffectsEnabled && etgEffectsEnabled && !etgFrequencyExceeded(stat))
#else
    if (stat != NULL && etgBulletEffectsEnabled && !etgFrequencyExceeded(stat))
#endif
    {
        laser->effect = etgEffectCreate(stat, laser, NULL, NULL, NULL, 1.0f, EAF_AllButNLips, 3, intDamage, intVelocity, intLength);
//        univAddObjToRenderListIf((SpaceObj *)laser->effect,(SpaceObj *)ship);     // add to render list if parent ship is in render list
        //do length calculations :)
        ((real32 *)laser->effect->variable)[ETG_LengthVariable] =
                    fsqrt(vecMagnitudeSquared(laser->lengthvec));
    }
    else
    {
        laser->effect = NULL;                              //play no effect for this bullet
    }

//    laser->effect = NULL;               //need for render...add later?

    laser->hitEffect = etgGunEventTable[shipstatic->shiprace][bullettotarget->gunowner->gunstatic->gunsoundtype][EGT_BulletDestroyed];//get pointer to bullet effect

    if (ship->soundevent.burstHandle < 0)
    {
        soundEventBurstFire(ship, gun);
    }

    etgLOD = etgGunEventTable[shipstatic->shiprace][gunstatic->gunsoundtype][EGT_GunFire];//get pointer to bullet effect
    if (etgLOD != NULL)
    {
        LOD = ship->currentLOD;
        if (LOD >= etgLOD->nLevels)
        {
            stat = NULL;
        }
        else
        {
            stat = etgLOD->level[LOD];
        }
    }
    else
    {
        stat = NULL;
    }

#if ETG_DISABLEABLE
    if (stat != NULL && etgEffectsEnabled && etgFireEffectsEnabled && !etgFrequencyExceeded(stat))
#else
    if (stat != NULL && etgFireEffectsEnabled && !etgFrequencyExceeded(stat))
#endif
    {                                                       //if there is a gun fire effect
        newEffect = etgEffectCreate(stat, laser, NULL, NULL, NULL, 1.0f, EAF_AllButNLips, 1, intDamage);
//        univAddObjToRenderListIf((SpaceObj *)newEffect,(SpaceObj *)ship);     // add to render list if parent ship is in render list
    }
/*
//spawn bullet hitting effect
    etgLOD = etgTractorBeamEffectTable[ship->shiprace];

    //etgLOD = etgGunEventTable[shipstatic->shiprace][gunstatic->gunsoundtype][EGT_GunFire];//get pointer to bullet effect
    if (etgLOD != NULL)
    {
        LOD = ship->currentLOD;
        if (LOD >= etgLOD->nLevels)
        {
            stat = NULL;
        }
        else
        {
            stat = etgLOD->level[LOD];
        }
    }
    else
    {
        stat = NULL;
    }

#if ETG_DISABLEABLE
    if (stat != NULL && etgEffectsEnabled)
#else
    if (stat != NULL)
#endif
    {                                                       //if there is a gun fire effect
//        size = etgEffectSize(stat->nParticleBlocks);//compute size of effect
        size = stat->effectSize;
        newEffect = memAlloc(size, "DefenseFHittingEffect", 0);          //allocate the new effect

        newEffect->objtype = OBJ_EffectType;
        newEffect->flags = SOF_Rotatable | SOF_AttachVelocity | SOF_AttachPosition | SOF_AttachCoordsys;
        newEffect->staticinfo = (StaticInfo *)stat;
        ClearNode(newEffect->renderlink);
        newEffect->currentLOD = LOD;
        newEffect->cameraDistanceSquared = ship->cameraDistanceSquared;

        newEffect->timeElapsed = 0.0f;                          //brand new heavies

        floatDamage = 30.0f;
        intDamage = TreatAsUdword(floatDamage);

        newEffect->rotinfo.coordsys = bullettotarget->rotinfo.coordsys;
        newEffect->posinfo.position = bullettotarget->posinfo.position; //start at same spot as bullet
        newEffect->posinfo.velocity = bullettotarget->posinfo.velocity; //start at same spot as bullet
        etgEffectCodeStart(stat, newEffect, 1, intDamage);//get the code a-runnin'
        SET_MOVING_IMMOBILE(newEffect->posinfo.isMoving);
        newEffect->posinfo.haventCalculatedDist = TRUE;
        univUpdateObjRotInfo((SpaceObjRot *)newEffect);

//        newEffect->owner = NULL;                               // nothing owns this effect
        newEffect->owner = (Ship *) bullettotarget;
        listAddNode(&universe.SpaceObjList,&(newEffect->objlink),newEffect);
        univAddObjToRenderListIf((SpaceObj *)newEffect,(SpaceObj *)ship);     // add to render list if parent ship is in render list
    }
*/
    //Not sure If I need to add...

    listAddNode(&universe.SpaceObjList,&(laser->objlink),laser);
    listAddNode(&universe.BulletList,&(laser->bulletlink),laser);
    univAddObjToRenderListIf((SpaceObj *)laser,(SpaceObj *)ship);     // add to render list if parent ship is in render list

    newdefensestruct = memAlloc(sizeof(DefenseStruct),"DS(DefenseStruct)",Pyrophoric);
    newdefensestruct->bullet = bullettotarget;
    newdefensestruct->CoolDown = FALSE;
    newdefensestruct->CoolDownTime = 0.0f;
    newdefensestruct->LaserDead = FALSE;
    listAddNode(&spec->DefenseList,&newdefensestruct->bulletnode,newdefensestruct);
    newdefensestruct->laser = laser;



    if(bitTest(ship->flags,SOF_CloakGenField))
    {
        bitSet(ship->flags,SOF_DeCloaking);
        bitClear(ship->flags,SOF_Cloaked);
        bitClear(ship->flags,SOF_Cloaking);
    }
}
void defenseFighterAdjustLaser(Bullet *laser)
{       //calculates laser direction n' such for rendering...
    DefenseFighterSpec *spec;
 //   DefenseFighterStatics *defensefighterstatics;
    Node *bulletnode;
    DefenseStruct *defensestruct;
    Ship *ship;

    vector tempvec;
    GunStatic *gunstatic;
    Gun *gun;

    vector positionInWorldCoordSys;

    if(laser->owner == NULL)
        return;

    ship = laser->owner;

    gun = &ship->gunInfo->guns[0];
    gunstatic = gun->gunstatic;


    spec= (DefenseFighterSpec *)ship->ShipSpecifics;

//    defensefighterstatics = (DefenseFighterStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;

    bulletnode = spec->DefenseList.head;

    while (bulletnode != NULL)
    {   //as long as theres a bullet to deal with
        defensestruct = (DefenseStruct *)listGetStructOfNode(bulletnode);
        if(defensestruct->LaserDead == TRUE)
        {
            bulletnode = bulletnode->next;
            continue;
        }
        if(laser == defensestruct->laser)
        {
            dbgAssertOrIgnore(defensestruct->bullet != NULL);
            matMultiplyMatByVec(&positionInWorldCoordSys,&ship->rotinfo.coordsys,&gunstatic->position);
            vecAdd(laser->posinfo.position,positionInWorldCoordSys,ship->posinfo.position);
            vecSub(laser->lengthvec, defensestruct->bullet->posinfo.position, laser->posinfo.position);

            // heading
            tempvec = defensestruct->laser->lengthvec;
            vecNormalize(&tempvec);

            //matMultiplyMatByVec(&gunheadingInWorldCoordSys, &ship->rotinfo.coordsys, &tempvec);
            //laser->bulletheading = gunheadingInWorldCoordSys;
            defensestruct->laser->bulletheading = tempvec;
            matCreateCoordSysFromHeading(&defensestruct->laser->rotinfo.coordsys,&tempvec);
            if(defensestruct->laser->effect != NULL)
            {    //adjust length
                ((real32 *)defensestruct->laser->effect->variable)[ETG_LengthVariable] =
                    fsqrt(vecMagnitudeSquared(defensestruct->laser->lengthvec));
            }
            return;
        }
        bulletnode = bulletnode->next;
    }
    //we shouldn't get to this point :)
    //dbgMessagef("Laser Drawn doesn't exist in defense fighter records.");

    //on further reflection..if we kill the laster...but it doesn't go bye bye, we might get here...
}
void DefenseFighterHouseKeep(Ship *ship)
{
    DefenseFighterSpec *spec = (DefenseFighterSpec *)ship->ShipSpecifics;
    DefenseFighterStatics *defensefighterstatics;
    Node *bulletnode;
    Node *tempnode;
    DefenseStruct *defensestruct;
    vector seperationvector;
    vector tempvec,rot_vector;
    GunStatic *gunstatic;
    Gun *gun;

    vector positionInWorldCoordSys;
    gun = &ship->gunInfo->guns[0];
    gunstatic = gun->gunstatic;

    defensefighterstatics = (DefenseFighterStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;

    bulletnode = spec->DefenseList.head;

    while (bulletnode != NULL)
    {   //as long as theres a bullet to deal with
        defensestruct = (DefenseStruct *)listGetStructOfNode(bulletnode);

/*        if (defensestruct->bullet)
            dbgMessagef("DS: %d %f %d %f %d %d",
                        universe.univUpdateCounter,
                        defensestruct->bullet->collOptimizeDist,
                        defensestruct->laser ? 1:0,
                        defensestruct->CoolDownTime,
                        defensestruct->CoolDown ? 1:0,
                        defensestruct->LaserDead ? 1:0);
        else
            dbgMessagef("DS: %d N  %d %f %d %d",
                        universe.univUpdateCounter,
                        defensestruct->laser ? 1:0,
                        defensestruct->CoolDownTime,
                        defensestruct->CoolDown ? 1:0,
                        defensestruct->LaserDead ? 1:0);*/

        if(!defensestruct->CoolDown)
        {   //laser cannon isn't cooling down, so continue tracking
            if (defensestruct->bullet == NULL || defensestruct->bullet->damage <= 0)
            {    //bullet is already dead...don't kill it again
                defensestruct->bullet = NULL;   //destroy pointer...
                if (defensestruct->laser != NULL)
                {
                    defensestruct->laser->timelived =10000.0f; //kill laser
                }
                defensestruct->LaserDead = TRUE;    //set killed flag
                defensestruct->laser=NULL;
                defensestruct->CoolDown = TRUE;     //begin laser cooldown
                defensestruct->CoolDownTime = 0.0f;    //reset to 0 for cooldown count
                bulletnode=bulletnode->next;
                continue;
            }
            if((universe.univUpdateCounter & defensefighterstatics->DamageRate) == 0)
            {
                // Time to do damage...
                //Do damage to bullet
                defensestruct->bullet->damage = (defensestruct->bullet->damage - frandombetween(defensefighterstatics->DamageReductionLow,defensefighterstatics->DamageReductionHigh));
                if(defensestruct->bullet->damage <= 0)
                {
                    //bullet is destroyed
                    DefenseFighterDestroyedABullet(ship, defensestruct->bullet, defensestruct->laser);
                    defensestruct->bullet->damage = 0;      //cap at 0;
                    defensestruct->bullet = NULL;   //destroy pointer...
                    //dbgMessagef("Defense Fighter Destroyed A Bullet.");
                    if (defensestruct->laser != NULL)
                    {
                        defensestruct->laser->timelived =10000.0f; //kill laser
                    }
                    defensestruct->LaserDead = TRUE;    //set killed flag
                    if(defensestruct->laser->effect != NULL)
                    {
                        univRemoveObjFromRenderList((SpaceObj *) defensestruct->laser->effect);
                    }
                    defensestruct->laser=NULL;
                    defensestruct->CoolDown = TRUE;     //begin laser cooldown
                    defensestruct->CoolDownTime = 0.0f;    //reset to 0 for cooldown count
                }
            }
            if(defensestruct->laser != NULL)
            {
                //check if bullet is still in range and infront...
                if((universe.univUpdateCounter & defensefighterstatics->RangeCheckRate) == 0)
                {
                    //time to check if in front
                    vecSub(seperationvector, ship->posinfo.position, defensestruct->bullet->posinfo.position);
                    if(vecMagnitudeSquared(seperationvector) > ship->staticinfo->bulletRangeSquared[ship->tacticstype])
                    {
                        //bullet is out of range
                        defensestruct->laser->timelived =10000.0f; //kill laser
                        defensestruct->LaserDead = TRUE;    //set killed flag
                        if(defensestruct->laser->effect != NULL)
                        {
                            univRemoveObjFromRenderList((SpaceObj *) defensestruct->laser->effect);
                        }
                        defensestruct->laser=NULL;
                        //dbgMessagef("Bullet out of range.");
                        bitClear(defensestruct->bullet->SpecialEffectFlag,0x0002);
                        defensestruct->CoolDown = TRUE;     //begin laser cooldown
                        defensestruct->bullet = NULL;       //set target to NULL so it isn't referenced again!
                        defensestruct->CoolDownTime = 0.0f;    //reset to 0 for cooldown count
                    }
                    else if(!defensefighterCheckInFront(ship, defensestruct->bullet))
                    {
                        //if bullet ISN'T in front
                        defensestruct->laser->timelived =10000.0f; //kill laser
                        defensestruct->LaserDead = TRUE;    //set killed flag
                        if(defensestruct->laser->effect != NULL)
                        {
                            univRemoveObjFromRenderList((SpaceObj *) defensestruct->laser->effect);
                        }
                        defensestruct->laser=NULL;
                        //dbgMessagef("Bullet Not infront anymore...stop tracking.");
                        if(defensefighterstatics->MultipleTargettingofSingleBullet)
                        {
                            bitClear(defensestruct->bullet->SpecialEffectFlag,0x0002);
                        }
                        defensestruct->CoolDown = TRUE;     //begin laser cooldown
                        defensestruct->bullet = NULL;       //set target to NULL so it isn't referenced again!
                        defensestruct->CoolDownTime = 0.0f;    //reset to 0 for cooldown count
                    }

                }
            }
            //This code is for the sake of the visual effect which STILL won't work
            //properly!!!  So it is temperary only!
            if(defensestruct->laser != NULL)
            {   //update bullent info...for visual effect
                dbgAssertOrIgnore(defensestruct->bullet != NULL);
                matMultiplyMatByVec(&positionInWorldCoordSys,&ship->rotinfo.coordsys,&gunstatic->position);
                vecAdd(defensestruct->laser->posinfo.position,positionInWorldCoordSys,ship->posinfo.position);
                vecSub(defensestruct->laser->lengthvec, defensestruct->bullet->posinfo.position, defensestruct->laser->posinfo.position);

                // heading
                tempvec = defensestruct->laser->lengthvec;
                vecNormalize(&tempvec);

                //matMultiplyMatByVec(&gunheadingInWorldCoordSys, &ship->rotinfo.coordsys, &tempvec);
                //laser->bulletheading = gunheadingInWorldCoordSys;
                defensestruct->laser->bulletheading = tempvec;
                matCreateCoordSysFromHeading(&defensestruct->laser->rotinfo.coordsys,&tempvec);
                if(defensestruct->laser->effect != NULL)
                {    //adjust length
                    ((real32 *)defensestruct->laser->effect->variable)[ETG_LengthVariable] =
                        fsqrt(vecMagnitudeSquared(defensestruct->laser->lengthvec));
                }
            }

        }
        else
        {    //this laser cannon is cooling, so cool it
            defensestruct->CoolDownTime += universe.phystimeelapsed;
            if(defensestruct->CoolDownTime > defensefighterstatics->CoolDownTimePerLaser)
            {    //Laser Terminal has cooled down...so free it up
                tempnode = bulletnode->next;
                listDeleteNode(bulletnode);
                //dbgMessagef("Deleting defense node in CoolDown.");
                bulletnode = tempnode;
                continue;
            }
        }
        bulletnode = bulletnode->next;
    }

    if (spec->DefenseList.num == 0)
    {
        soundEventBurstStop(ship, gun);
    }

    //do special rotation if neccessary
    if(bitTest(ship->dontrotateever,1))
    {
        //matGetVectFromMatrixCol3(rot_vector,ship->rotinfo.coordsys);
        vecSet(rot_vector,100.0f,0.0f,0.0f);
        vecAddTo(ship->rotinfo.torque, rot_vector);
        vecCapVectorSloppy(&ship->rotinfo.rotspeed, defensefighterstatics->max_rot_speed );
        spec->rotate_time_counter -= universe.phystimeelapsed;
        if(spec->rotate_time_counter <= 0.0f)
        {
            bitClear(ship->dontrotateever,1);
            spec->DefenseFighterCanNowRotate = FALSE;
        }
    }
    else if (spec->DefenseFighterCanNowRotate == FALSE)
    {
        spec->rotate_time_counter += universe.phystimeelapsed;
        if(spec->rotate_time_counter >= defensefighterstatics->rotate_recover_time)
        {
            spec->DefenseFighterCanNowRotate = TRUE;
            spec->rotate_time_counter = defensefighterstatics->rotate_time;
        }

    }

}
Example #22
0
void multiDS(int n, double *x, double cc, double ce, double lmin,
             double lstart, int maxiter)
{
   int i, imin, replaced, iter = 0;
   double **xs, **xr, **xe, **xc, *fs, *fr, *fe, *fc, fsmin, frmin,
      femin, fcmin, ssize;
   FILE *fp;
   void initSimplex(int, double *, double **, double);
   void printSimplex(int, int, double **, double *);
   void findBest(int, double **, double *, int *, double *);
   void copySimplex(int, double **, double **, double *, double *);
   double simplexSize(int, double **);
   void vecAdd(int, double *, double *, double *, double);
   double dmin(int, double *);
   void mpi_assign(int);
   void mpi_distribute(int, double *);

   /* Initial size of simplex */
   ssize = lstart;

   /* Check validity of input parameters */
   if(cc <= 0.0 || cc >= 1.0) {
      printf("multiDS: contraction coefficient must be in (0,1)\n");
      exit(0);
   }

   if(ce <= 1.0) {
      printf("multiDS: expandion coefficient must be > 1\n");
      exit(0);
   }

   if(ssize < lmin) {
      printf("multiDS: starting simplex size is < minimum\n");
      printf("         give lstart > lmin\n");
      exit(0);
   }

   printf("Parameters for search:\n");
   printf("   Contraction factor     = %e\n", cc);
   printf("   Expansion   factor     = %e\n", ce);
   printf("   Starting simplex size  = %e\n", ssize);
   printf("   Minimum  simplex size  = %e\n", lmin);
   printf("   Maximum number of iter = %d\n", maxiter);

   /* Allocate memory */
   xs = (double **) calloc((n + 1), sizeof(double *));
   xr = (double **) calloc((n + 1), sizeof(double *));
   xe = (double **) calloc((n + 1), sizeof(double *));
   xc = (double **) calloc((n + 1), sizeof(double *));
   fs = (double *) calloc(n + 1, sizeof(double));
   fr = (double *) calloc(n + 1, sizeof(double));
   fe = (double *) calloc(n + 1, sizeof(double));
   fc = (double *) calloc(n + 1, sizeof(double));
   for(i = 0; i < n + 1; i++) {
      xs[i] = (double *) calloc(n, sizeof(double));
      xr[i] = (double *) calloc(n, sizeof(double));
      xe[i] = (double *) calloc(n, sizeof(double));
      xc[i] = (double *) calloc(n, sizeof(double));
   }


   /* Initialize the simplex */
   initSimplex(n, x, xs, ssize);

   /* Assign evaluations to different proc */
   mpi_assign(n);

   /* Calculate initial function values */
   /* Zeroth vertex is starting vertex, cost = 1. No need to calculate again
    * since it is already done in multiDS_driver.c */
   fs[0] = cost0;

   for(i = 1; i < n + 1; i++) {
      if(proc[i] == myproc)
         fs[i] = objFun(n, xs[i]);
   }

   /* Distribute cost functions */
   mpi_distribute(n, fs);

   printf("Initial simplex and function values:\n");
   printSimplex(0, n, xs, fs);

   /* Find best vertex and put in first position */
   findBest(n, xs, fs, &imin, &fsmin);

   if(myproc == 0)
      fp = fopen("cost.dat", "w");

   /* Main iteration loop */
   while(ssize > lmin && iter < maxiter) {
      printf("Iteration = %d\n\n", iter + 1);

      replaced = 0;
      while(!replaced && ssize > lmin) { /* inner repeat loop */

         /* rotation step */
         printf("   Rotation:\n");
         for(i = 1; i <= n; i++) {
            vecAdd(n, xs[0], xs[i], xr[i], 1.0);
            if(proc[i] == myproc)
               fr[i] = objFun(n, xr[i]);
         }
         mpi_distribute(n, fr);
         printSimplex(1, n, xr, fr);

         frmin = dmin(n, fr);
         replaced = (frmin < fs[0]) ? 1 : 0;
         if(replaced) {
            /* expansion step */
            printf("   Expansion:\n");
            for(i = 1; i <= n; i++) {
               vecAdd(n, xs[0], xs[i], xe[i], ce);
               if(proc[i] == myproc)
                  fe[i] = objFun(n, xe[i]);
            }
            mpi_distribute(n, fe);
            printSimplex(1, n, xe, fe);

            femin = dmin(n, fe);
            if(femin < frmin)
               copySimplex(n, xe, xs, fe, fs); //accept expansion
            else
               copySimplex(n, xr, xs, fr, fs); //accept rotation
         }
         else {
            /* contraction step */
            printf("   Contraction step:\n");
            for(i = 1; i <= n; i++) {
               vecAdd(n, xs[0], xs[i], xc[i], -cc);
               if(proc[i] == myproc)
                  fc[i] = objFun(n, xc[i]);
            }
            mpi_distribute(n, fc);
            printSimplex(1, n, xc, fc);

            fcmin = dmin(n, fc);
            replaced = (fcmin < fs[0]) ? 1 : 0;
            copySimplex(n, xc, xs, fc, fs); //accept contraction
         }

         /* Length of smallest edge in simplex */
         ssize = simplexSize(n, xs);

      }                         /* End of inner repeat loop */

      ++iter;

      /* Find best vertex and put in first position */
      findBest(n, xs, fs, &imin, &fsmin);

      printf("\n");
      printf("Minimum length of simplex = %12.4e\n", ssize);
      printf("Minimum function value    = %12.4e\n", fs[0]);
      printf("-------------------------------------------------\n");
      if(myproc == 0) {
         fprintf(fp, "%5d %20.10e %20.10e %5d\n", iter, fs[0], ssize, imin);
         fflush(fp);
      }
   }                            /* End of main iteration loop */
   if(myproc == 0)
      fclose(fp);

   /* Copy best vertex for output */
   for(i = 0; i < n; i++)
      x[i] = xs[0][i];

   /* Best vertex found */
   printf("Best vertex:\n");
   for(i = 0; i < n; i++)
      printf("%e ", x[i]);
   printf("\n");


   /* Free memory */
   for(i = 0; i < n + 1; i++) {
      free(xs[i]);
      free(xr[i]);
      free(xe[i]);
      free(xc[i]);
   }
   free(xs);
   free(xr);
   free(xe);
   free(xc);
   free(fs);
   free(fr);
   free(fe);
   free(fc);
}
Example #23
0
int getDoppler(GEOLOCATE_REC *g,double look,double yaw,
               double *fd, double *fdot,
               vector *out_targPos,vector *out_relVel)
{
	vector relPos, /*Vector from spacecraft to targPos.*/
		sarPos, /*Position of spacecraft*/
		targPos, /*Position of target point.*/
		relVel, /*Relative velocity vector.*/
		sarVel, /*Velocity of spacecraft*/
		targVel, /*Velocity of targPos*/
		sarAcc, /*Accelleration of spacecraft*/
		targAcc, /*Accelleration of targPos*/
		relAcc; /*Relative sarAccelleration*/
	double range,angVel=g->angularVelocity;
	sarPos=g->stVec.pos;
	sarVel=g->stVec.vel;
	relPos.x= sin(yaw);
	relPos.y=-sin(look)*cos(yaw);
	relPos.z=-cos(look)*cos(yaw);
/*c   relPos unit vector points from s/c to targPos.  Rotate into earth axes:*/
	vecMul(g->look_matrix,relPos,&relPos);
/*c   scale relPos so it reaches from s/c to targPos */
	range = calcRange(g,look,yaw);
	vecScale(&relPos,range);
	vecAdd(relPos,sarPos,&targPos);
/*c
c
c  Now we have all three vectors in earth centered coordinates:
c     sarPos = sar satellite position
c     relPos = range vector from sar to targPos
c     targPos = target position
c
c   calculate velocity vectors targVel and relVel.
c*/
	targVel.x= -angVel*targPos.y;
	targVel.y= angVel*targPos.x;
	targVel.z= 0.0;
	vecSub(targVel,sarVel,&relVel);
/*c
c  Calcuate accelerations of sar and targPos sarAcc,targAcc
c  */
	sarAcc.x=0.0;
	sarAcc.y=0.0;
/*c     sar sarAcceleration toward earth center, via
   orbital considerations (accelleration is straight down,
   at      -GxMe / h**2) */
	sarAcc.z=-g->gxMe/vecDot(sarPos,sarPos);
	vecMul(g->look_matrix,sarAcc,&sarAcc);/* !put in e.c. coordinates
c   calculate sarAcceleration of targPos on earth surface:*/
	targAcc.x=-targPos.x*angVel*angVel;
	targAcc.y=-targPos.y*angVel*angVel;
	targAcc.z=0.0;
	vecSub(targAcc,sarAcc,&relAcc);
/*c
c   calculate doppler parameters
c*/
	if (out_targPos)
		*out_targPos=targPos;
	if (out_relVel)
		*out_relVel=relVel;
	if (fd)
		*fd=-2.0/(g->lambda*range)*vecDot(relPos,relVel);
	if (fdot)
		*fdot=-2.0/(g->lambda*range)*(vecDot(relVel,relVel)+vecDot(relPos,relAcc));

        /* success */
        return 0;
}
Example #24
0
bool PhysicsWorld::Intersects(const StaticPhysicsEntity &s, const DynamicPhysicsEntity &d, Vec &outNormal, Vec &outDir)
{
	float dmin = 0, radiusSquared;

	Vec min, max, center, scale;

	min = vec(-1, -1, -1, 0);
	max = vec(1, 1, 1, 0);
	scale = vec(1, 1, 1, 0);

	Mat m, sc;

	center = entGetTransform(d.ent)->GetPosition();
	entGetTransform(s.ent)->GetMatrix(&m);
	entGetTransform(d.ent)->GetMatrix(&sc);

	// scale the unit vector and take the largest component
	// as the radius for the sphere; as long as we don't do
	// silly rotations we should be ok
	matMulVec(&scale, sc, scale);
	radiusSquared = vecMax(scale);
	radiusSquared *= radiusSquared;

	// we don't have an inv matrix of anything so instead
	// we transform everything to worldspace and do the 
	// calculations there

	// rot + scale
	matMulVec(&min, m, min);
	matMulVec(&max, m, max);

	// pos
	Vec p = entGetTransform(s.ent)->GetPosition();
	min = vecAdd(min, p);
	max = vecAdd(max, p);

	// the actual intersection test (don't test w)
	for(int i = 0; i < 3; i++)
	{
		float C = vecGetElem(center, i);

		float Bmin = vecGetElem(min, i);
		float Bmax = vecGetElem(max, i);

		if(C < Bmin)		dmin += square(C - Bmin);
		else if(C > Bmax)	dmin += square(C - Bmax);
	}

	if(dmin <= radiusSquared)
	{
		Ray r;
		r.o = center;
		r.d = vecSub(p, center);
		r.d = vecNormalize(r.d);

		float dist;
		bool hit = RayBoxIntersection(r, min, max, dist, outNormal);
		outDir = vecMul(r.d, vec(dist));

		return hit;
	}

	return false;
}
Example #25
0
int main(void)
{
    Key_val *k = NULL;
    Vec *v = NULL;
    char *s;
    char ts[] = "one";
    int i = 0;

    k = keyAdd(k, ts, "1");
    k = keyAdd(k, "two", "2");
    k = keyAdd(k, "three", "3");
    k = keyAdd(k, "four", "4");
    k = keyAdd(k, "five", "5");
    v = vecAdd(v, "ONE", k);
    //This doesn_t have to be last but k
    // must have a value. So it can_t go first.

	// You need to reset k
	k = NULL;
    k = keyAdd(k, "twenty one", "21");
    k = keyAdd(k, "twenty two", "22");
    k = keyAdd(k, "twenty three", "23");
    k = keyAdd(k, "twenty four", "24");
    v = vecAdd(v, "TWO", k);

    prV(v);

    printf("\n\n ................ \n\n");

    //Example returning key_val from the string found in vector v
	printf("Below pr(findK(v,\"ONE\"))\n");
    pr(findK(v, "ONE"));

    printf("Below pr(findK(v,\"TWO\"))\n");
    pr(findK(v, "TWO"));



    printf("\n");
    s = (char *)malloc(sizeof(char) * 80);
    strcpy(s, "twenty two");
    fprintf(stderr, "find(c,%s)=%s\n", s, find(k, s));
    modify(k,s,"New twenty two");

    k = findK(v, "ONE");
    strcpy(s, "one");
    fprintf(stderr, "find(c,%s)=%s\n", s, find(k, s));
    free(s);

    printf("\n\nExample use in a for loop.\n\n");
    for (i = 0; i < pvLength(v); ++i) {
	pr(getK(v, i));
	printf("......\n");

    }

    myfreeV(v);
    //Note myfreeV calls this
	// myfree(k);

    return 0;
}
Example #26
0
void addMonkeyResearchShipChangePosition(Ship *dockwith, Ship *ship,sdword dockindex)
{
    DockStaticPoint *dockwithstaticpoint;
    vector coneheadingInWorldCoordSysDockWith,DockWithHeading,destination,DockWithUp,destinationoffset;
    vector desiredHeading,desiredUp,conepositionInWorldCoordSysDockWith,tmpvec;
    real32 theta;
    matrix rotmatrix,tmpmat;

    ResearchShipStatics *resstatics;
    resstatics = (ResearchShipStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;


    dbgAssertOrIgnore(dockwith != NULL);    //if we're calling this there should be another reserach station available somewhere

    if(ship->shiprace == R1)
    {
        dockwithstaticpoint = &dockwith->staticinfo->dockStaticInfo->dockstaticpoints[dockindex];

        matMultiplyMatByVec(&coneheadingInWorldCoordSysDockWith,&dockwith->rotinfo.coordsys,&dockwithstaticpoint->conenormal);
        matGetVectFromMatrixCol3(DockWithHeading,dockwith->rotinfo.coordsys)


        destinationoffset.x = coneheadingInWorldCoordSysDockWith.x*resstatics->R1final_dock_distance;
        destinationoffset.y = coneheadingInWorldCoordSysDockWith.y*resstatics->R1final_dock_distance;
        destinationoffset.z = coneheadingInWorldCoordSysDockWith.z*resstatics->R1final_dock_distance;
        vecAdd(destination,dockwith->posinfo.position, destinationoffset);
        if(((ResearchShipSpec *)ship->ShipSpecifics)->pie_plate_num == 0)
        {    //ship is docking on'a'top so add upwards factor
            matGetVectFromMatrixCol1(DockWithUp,dockwith->rotinfo.coordsys);
            vecScalarMultiply(DockWithUp,DockWithUp,resstatics->R1VerticalDockDistance);
            vecAdd(destination,destination,DockWithUp);
        }

        theta = DEG_TO_RAD(60);

        matMakeRotAboutX(&rotmatrix,(real32) cos(theta),(real32) sin(theta));
        matMultiplyMatByMat(&tmpmat, &dockwith->rotinfo.coordsys, &rotmatrix);

        //share a lot of these things...later...
        ship->rotinfo.coordsys = tmpmat;
        ship->posinfo.position = destination;
    }
    else
    {
        //r2 positioning
        dockwithstaticpoint = &dockwith->staticinfo->dockStaticInfo->dockstaticpoints[dockindex];

        matMultiplyMatByVec(&coneheadingInWorldCoordSysDockWith,&dockwith->rotinfo.coordsys,&dockwithstaticpoint->conenormal);
        matMultiplyMatByVec(&conepositionInWorldCoordSysDockWith,&dockwith->rotinfo.coordsys,&dockwithstaticpoint->position);
        vecAddTo(conepositionInWorldCoordSysDockWith,dockwith->posinfo.position);
        matGetVectFromMatrixCol3(DockWithHeading,dockwith->rotinfo.coordsys)

        destinationoffset.x = coneheadingInWorldCoordSysDockWith.x*resstatics->R2DockFinalDistance;
        destinationoffset.y = coneheadingInWorldCoordSysDockWith.y*resstatics->R2DockFinalDistance;
        destinationoffset.z = coneheadingInWorldCoordSysDockWith.z*resstatics->R2DockFinalDistance;
        vecAdd(destination,conepositionInWorldCoordSysDockWith, destinationoffset);

        desiredHeading = coneheadingInWorldCoordSysDockWith;
        if(dockindex == 0)
        {
            matGetVectFromMatrixCol3(desiredUp,dockwith->rotinfo.coordsys);
        }
        else if(dockindex == 1)
        {
            matGetVectFromMatrixCol3(desiredUp,dockwith->rotinfo.coordsys);
        }
        else if(dockindex == 2)
        {
            desiredUp = DockWithHeading;
        }
        else if(dockindex == 3)
        {
            theta = DEG_TO_RAD(60);
            matMakeRotAboutZ(&rotmatrix,(real32) cos(theta),(real32) sin(theta));
            matMultiplyMatByMat(&tmpmat, &dockwith->rotinfo.coordsys, &rotmatrix);
            matGetVectFromMatrixCol1(desiredUp,tmpmat);
        }
        else if(dockindex == 4)
        {
            destinationoffset.x = coneheadingInWorldCoordSysDockWith.x*100;
            destinationoffset.y = coneheadingInWorldCoordSysDockWith.y*100;
            destinationoffset.z = coneheadingInWorldCoordSysDockWith.z*100;
            vecAdd(destination,conepositionInWorldCoordSysDockWith, destinationoffset);

            matGetVectFromMatrixCol1(desiredUp,dockwith->rotinfo.coordsys);
            vecScalarMultiply(desiredHeading,desiredHeading,-1.0f);
        }
        else
        {
            dbgAssertOrIgnore(FALSE);       //shouldget here.
        }

        vecNormalize(&desiredUp);

        matPutVectIntoMatrixCol1(desiredUp,ship->rotinfo.coordsys);
        vecCrossProduct(tmpvec,desiredHeading,desiredUp);
        matPutVectIntoMatrixCol2(tmpvec,ship->rotinfo.coordsys);
        matPutVectIntoMatrixCol3(desiredHeading,ship->rotinfo.coordsys);

        ship->posinfo.position = destination;
        ship->posinfo.velocity.x = 0.0f;
        ship->posinfo.velocity.y = 0.0f;
        ship->posinfo.velocity.z = 0.0f;
    }
}
Example #27
0
void ResearchShipHouseKeep(Ship *ship)
{
    ResearchShipSpec *spec = (ResearchShipSpec *)ship->ShipSpecifics;
    SelectCommand selection;
    vector up,destination,desiredheading,newup;
    vector univup = {0.0f,0.0f,1.0f};
    bool InParadeandMoving = FALSE;
    matrix rot_matrix,tmpmat,rotmat;
    real32 radangle;
    ResearchShipStatics *researchshipstatics;
    researchshipstatics = (ResearchShipStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;

    if(bitTest(ship->specialFlags,SPECIAL_StopForResearchDocking))
    {
        vecScalarMultiply(ship->posinfo.velocity,ship->posinfo.velocity,0.94);
        vecScalarMultiply(ship->rotinfo.rotspeed,ship->rotinfo.rotspeed,0.94);
        bitSet(ship->dontapplyforceever,1);
        bitSet(ship->dontrotateever,1);
    }
    else
    {
        bitClear(ship->dontapplyforceever,1);
        bitClear(ship->dontrotateever,1);
    }

    if(ship->flags & SOF_Slaveable)
    {
        if(ship->slaveinfo->flags & SF_MASTER)
        {
            CommandToDo *command = getShipAndItsCommand(&universe.mainCommandLayer,ship);
            if(command != NULL)
            {
                //ship may be in parade...
                if(command->ordertype.order == COMMAND_MILITARY_PARADE)
                {
                    //ship is in parade
                    CommandToDo *ashipCom = getShipAndItsCommand(&universe.mainCommandLayer,command->militaryParade->aroundShip);
                    if(ashipCom != NULL)
                    {
                        //probably shouldn't be null regardless..should be equal to command..but ohwell
                        if(ashipCom->ordertype.order == COMMAND_MOVE ||
                           ashipCom->ordertype.order == COMMAND_ATTACK ||
                           ashipCom->ordertype.order == COMMAND_SPECIAL ||
                           ashipCom->ordertype.order == COMMAND_MP_HYPERSPACING)
                        {
                            InParadeandMoving = TRUE;
                            spec->rotate_state = ROTATE_WAIT;
                        }
                    }
                //in parade
                    if(!InParadeandMoving)
                    {
                        if(bitTest(ship->specialFlags,SPECIAL_ParadeNeedTomoveCloser))
                        {
                            InParadeandMoving = TRUE;
                            spec->rotate_state = ROTATE_WAIT;
                        }
                    }
                }
            }
        }
    }
    if(ship->flags & SOF_Slaveable)
    {    //ship is slaveable
        bitSet(ship->flags,SOF_DontDrawTrails);
        ship->autostabilizeship = FALSE;        // never have univupdate autostabilize research ships
        if(ship->slaveinfo->flags & SF_MASTER)
        {    //ship is a master
            if(!InParadeandMoving)
            {
                if(ship->shiprace == R1)
                {   //ship is a race 1 MASTER research ship...
                    //i.e. it controls the motion
                    switch(spec->rotate_state)
                    {
                    case ANGLE_ESTABLISH:       //establishes the angle at which the station is supposed to rotate at
                        break;
                    case ROTATE_WAIT:           //wait to rotate
                        if(ship->slaveinfo->slaves.num >= 5)
                        {   //correct # of ships...
                            if(!ship_is_moving(ship))
                            {
                                if(!spec->prepshipforanother)
                                {   //no ships are coming to dock
                                    //do up vector tracking!
                                    //Later Calculate this vector ONCE at code start up...Let Daly do it
                                    //and get as a static value

                                    radangle = DEG_TO_RAD(researchshipstatics->RotationAngle);
                                    matMakeRotAboutX(&rotmat,(real32) cos(radangle),(real32) sin(radangle));
                                    matMultiplyMatByVec(&newup, &rotmat, &univup);
                                    //matGetVectFromMatrixCol3(desiredHeading,ship->rotinfo.coordsys);
                                    if(aitrackHeadingWithFlags(ship,&newup,0.96f,AITRACKHEADING_IGNOREUPVEC))
                                    {
                                        spec->rotate_state = ROTATE_DO;
                                        getRotatePoint(ship, &spec->rotate_point,&spec->rotate_distance);
                                    }
                                }
                            }
                            if(!spec->have_removed_from_parade)
                            {
                                spec->have_removed_from_parade = TRUE;
                                selection.numShips = 1;
                                selection.ShipPtr[0] = ship;
                                //RemoveShipsFromDoingStuff(&universe.mainCommandLayer,&selection);
                                //clHalt(&universe.mainCommandLayer,&selection);
                            }
                        }
                        break;
                    case ROTATE_STOP:
                    case ROTATE_STOP_QUICK:
                    case ROTATE_DO:
                        ship->posinfo.isMoving = ISMOVING_MOVING | ISMOVING_ROTATING;
                        make_all_slaves_moving(ship);
                        if(ship->slaveinfo->slaves.num < 5)
                        {
                            //don't rotate anymore because slaves dropped below threhold for whatever reasons!
                            spec->rotate_state = ROTATE_STOP;
                            break;
                        }
                        if(spec->prepshipforanother)
                        {   //need to prep ship for a docking ship..
                            spec->rotate_state = ROTATE_STOP;
                        }
                        else if(ship_is_moving(ship))
                        {   //ship is being moved
                            spec->rotate_state = ROTATE_STOP_QUICK;
                        }
                        else
                        {
                            spec->rotate_state = ROTATE_DO;
                        }

                        //matGetVectFromMatrixCol3(heading,ship->rotinfo.coordsys);
                        matGetVectFromMatrixCol1(up,ship->rotinfo.coordsys);
                        //vecScalarMultiply(rotate_point, heading, -250.0f);
                        //vecAdd(rotate_point,rotate_point, ship->posinfo.position);

                        switch(spec->rotate_state)
                        {
                        case ROTATE_DO:
                            if(spec->theta >= researchshipstatics->max_rotate)
                                spec->theta = researchshipstatics->max_rotate;
                            else
                                spec->theta += researchshipstatics->rotate_acelleration;
                            break;
                        case ROTATE_STOP_QUICK:
                            spec->theta *= researchshipstatics->rotate_slow;
                            spec->theta *= researchshipstatics->rotate_slow;
                        case ROTATE_STOP:
                            if(spec->theta <= 0.00001f)
                            {
                                spec->theta = 0.0f;
                                spec->rotate_state = ROTATE_WAIT;
                                break;
                            }
                            else
                                spec->theta *= researchshipstatics->rotate_slow;
                            break;
                        default:
                            dbgAssertOrIgnore(FALSE);
                            break;
                        }
                        matMakeRotAboutX(&rot_matrix,(real32) cos(spec->theta),(real32) sin(spec->theta));
                        //matMultiplyMatByMat(&tmpmat, &rot_matrix, &ship->rotinfo.coordsys);
                        matMultiplyMatByMat(&tmpmat, &ship->rotinfo.coordsys, &rot_matrix);
                        //vecSub(tmpvec, ship->posinfo.position, spec->rotate_point);
                        //dist = vecMagnitudeSquared(tmpvec);
                        //dist = fsqrt(dist);

                        matGetVectFromMatrixCol3(desiredheading,tmpmat);
                        vecScalarMultiply(destination, desiredheading, spec->rotate_distance);      //old was dist
                        vecAdd(destination,destination,spec->rotate_point);

                        ship->posinfo.position = destination;
                        ship->rotinfo.coordsys = tmpmat;
                        univUpdateObjRotInfo((SpaceObjRot *)ship);
                        break;
                    default:
                        dbgMessagef("Shouldn't Get Here...unknown Research Ship Rotate State");
                        dbgAssertOrIgnore(FALSE);
                        break;
                    }


                }
                else
                {    //Ship is an R2 Master...so rotate differently
                    switch(spec->rotate_state)
                    {
                    case ANGLE_ESTABLISH:
                        break;
                    case ROTATE_WAIT:           //wait to rotate
                        if(ship->slaveinfo->slaves.num >= 3)
                        {   //correct # of ships...
                            if(!spec->prepshipforanother && !ship_is_moving(ship))
                            {   //no ships are coming to dock
                                radangle = DEG_TO_RAD(researchshipstatics->RotationAngle);
                                matMakeRotAboutX(&rotmat,(real32) cos(radangle),(real32) sin(radangle));
                                matMultiplyMatByVec(&newup, &rotmat, &univup);
                                if(aitrackHeadingWithFlags(ship,&newup,0.96f,AITRACKHEADING_IGNOREUPVEC))
                                {
                                    spec->rotate_state = ROTATE_DO;
                                }
                            }
                            else
                            {
                                vecSet(ship->rotinfo.rotspeed,0.0f,0.0f,0.0f);
                                vecSet(ship->rotinfo.torque,0.0f,0.0f,0.0f);
                            }
                        }
                        if(ship->slaveinfo->slaves.num >= 1)
                        {   //correct # of ships...
                            if(!spec->have_removed_from_parade)
                            {
                                spec->have_removed_from_parade = TRUE;
                                selection.numShips = 1;
                                selection.ShipPtr[0] = ship;
                                //RemoveShipsFromDoingStuff(&universe.mainCommandLayer,&selection);
                                //clHalt(&universe.mainCommandLayer,&selection);
                            }
                        }
                        break;
                    case ROTATE_STOP:
                    case ROTATE_STOP_QUICK:
                    case ROTATE_DO:
                        ship->posinfo.isMoving = ISMOVING_MOVING | ISMOVING_ROTATING;
                        make_all_slaves_moving(ship);
                        if(ship->slaveinfo->slaves.num < 3)
                        {
                            //don't rotate anymore because slaves dropped below threhold for whatever reasons!
                            spec->rotate_state = ROTATE_STOP;
                            break;
                        }
                        if(spec->prepshipforanother)
                        {   //need to prep ship for a docking ship..
                            spec->rotate_state = ROTATE_STOP;
                        }
                        if(ship_is_moving(ship))
                        {   //ship is being moved
                            spec->rotate_state = ROTATE_STOP_QUICK;
                        }
                        switch(spec->rotate_state)
                        {
                        case ROTATE_DO:
                            if(spec->theta >= researchshipstatics->max_rotate)
                                spec->theta = researchshipstatics->max_rotate;
                            else
                                spec->theta += researchshipstatics->rotate_acelleration;
                            break;
                        case ROTATE_STOP_QUICK:
                            spec->theta *= researchshipstatics->rotate_slow;
                            spec->theta *= researchshipstatics->rotate_slow;
                        case ROTATE_STOP:
                            if(spec->theta <= 0.00001f)
                                {
                                spec->theta = 0.0f;
                                spec->rotate_state = ROTATE_WAIT;
                                break;
                                }
                            else
                                spec->theta *= researchshipstatics->rotate_slow;
                            break;
                        default:
                            dbgAssertOrIgnore(FALSE);
                            break;
                        }
                        matMakeRotAboutZ(&rot_matrix,(real32) cos(spec->theta),(real32) sin(spec->theta));
                        tmpmat = ship->rotinfo.coordsys;
                        matMultiplyMatByMat(&ship->rotinfo.coordsys,&tmpmat,&rot_matrix);
                        univUpdateObjRotInfo((SpaceObjRot *)ship);
                        break;
                    default:
                        dbgMessagef("Shouldn't Get Here...unknown Research Ship Rotate State");
                        dbgAssertOrIgnore(FALSE);
                        break;
                    }
                }
            }
        }
        else
        {
            vecScalarMultiply(ship->posinfo.velocity,ship->posinfo.velocity, 0.0f);
        }

    }
}
static void triangleDrawTile(float *tilebuffer, const Triangle3DSetup &t, const TriangleSetup &s, int x, int y)
{
	const Vec denom = vecRcp(vec(t.dx1 * t.dy2 - t.dy1 * t.dx2));

	const Vec DY1 = vec(t.dy1);
	const Vec DY2 = vec(t.dy2);
	const Vec DY3 = vec(t.dy3);
	const Vec DX2 = vec(t.dx2);
	const Vec DX3 = vec(t.dx3);

	const Vec X3  = vec(t.x3);
	const Vec Y3  = vec(t.y3);
	const Vec Z1  = vec(t.z1);
	const Vec Z2  = vec(t.z2);
	const Vec Z3  = vec(t.z3);

	const Vec Step = vec(0, 1, 2, 3);
	const Vec Zero = vec(0);
	const Vec One  = vec(1);
	const Vec Four = vec(4);

	float c1 = s.c1;
	float c2 = s.c2;
	float c3 = s.c3;

	for(int iy = 0; iy < tileHeight; iy++)
	{
		Vec v = vec(0, 1, 2, 3);

		Vec C1 = vec(c1);
		Vec C2 = vec(c2);
		Vec C3 = vec(c3);

		const Vec yp = vec((float)(iy + y));
		const Vec ypos = vecSub(yp, Y3);
		const Vec dxypos2 = vecMul(DX2, ypos);
		const Vec dxypos3 = vecMul(DX3, ypos);

		float fx = (float)x;
		for(int ix = 0; ix < tileWidth; ix += 4)
		{
			void * ptr = &tilebuffer[ix + iy * tileWidth];

			const Vec xp = vecAdd(vec(fx), Step);

			// Evaluate half-space equation & generate write-mask
			const Vec CX1 = vecSub(C1, vecMul(v, DY1));
			const Vec CX2 = vecSub(C2, vecMul(v, DY2));
			const Vec CX3 = vecSub(C3, vecMul(v, DY3));

			const Vec Mask1 = vecCmpGT(CX1, Zero);
			const Vec Mask2 = vecCmpGT(CX2, Zero);
			const Vec Mask3 = vecCmpGT(CX3, Zero);

			const Vec WriteMask = vecAnd(Mask1, vecAnd(Mask2, Mask3));

			// Calculate depth based on barycentric coordinates
			const Vec xpos = vecSub(xp, X3);

			const Vec dyxpos2 = vecMul(DY2, xpos);
			const Vec dyxpos3 = vecMul(DY3, xpos);

			const Vec delta2 = vecSub(dyxpos2, dxypos2);
			const Vec delta3 = vecSub(dyxpos3, dxypos3);

			const Vec t1 = vecMul(delta2, denom);
			const Vec t2 = vecMul(delta3, denom);
			const Vec t3 = vecSub(vecSub(One, t1), t2);

			const Vec tz1 = vecMul(Z1, t1);
			const Vec tz2 = vecMul(Z2, t2);
			const Vec tz3 = vecMul(Z3, t3);

			const Vec z  = vecAdd(tz1, vecAdd(tz2, tz3));

			// Depth compare
			const Vec Value			= vecLoadAligned(ptr);
			const Vec DepthCompare	= vecCmpGE(Value, z);
			const Vec Compare		= vecAnd(WriteMask, DepthCompare);
			const Vec Result		= vecSel(Value, z, Compare);

			vecStoreAligned(ptr, Result);
			v = vecAdd(v, Four);
			fx += 4;
		}

		c1 += t.dx1;
		c2 += t.dx2;
		c3 += t.dx3;
	}
}
bool MinelayerCorvetteStaticMineDrop(Ship *ship,SpaceObjRotImpTarg *target)
{
    MinelayerCorvetteStatics *minelayercorvettestatics;
    MinelayerCorvetteSpec *spec = (MinelayerCorvetteSpec *)ship->ShipSpecifics;
    sdword flag;
    GunInfo *guninfo = ship->gunInfo;
    Gun *gun0,*gun1;
    real32 time;
    sdword maxmis;

    minelayercorvettestatics = (MinelayerCorvetteStatics *) ((ShipStaticInfo *)(ship->staticinfo))->custstatinfo;
    gun0 = ((Gun *) &(ship->gunInfo->guns[0]));

    maxmis = gun0->gunstatic->maxMissiles;

    if(ship->gunInfo->numGuns > 1)
    {    //ship has 2 guns (race 1)

        gun1 = ((Gun *) &(ship->gunInfo->guns[1]));

        if(gun0->numMissiles == 0 && gun1->numMissiles == 0)
            return FALSE;

        if((universe.totaltimeelapsed - gun1->lasttimefired) < minelayercorvettestatics->gunReFireTime
           && (universe.totaltimeelapsed - gun0->lasttimefired) < minelayercorvettestatics->gunReFireTime)
        {
            return(FALSE);
        }
        maxmis += gun1->gunstatic->maxMissiles;
    }
    else
    {
        if(gun0->numMissiles == 0)
            return FALSE;

        if((universe.totaltimeelapsed - gun0->lasttimefired) < minelayercorvettestatics->gunReFireTime)
            return(FALSE);
    }


    switch(spec->MiningStatus)
    {
    case FIRST_OFF:
        //////////////////////
        //speech event for forcedropped mines
        //event num: COMM_MLVette_ForceDrop
        //use battle chatter
        if(ship->playerowner->playerIndex == universe.curPlayerIndex)
        {
            if (battleCanChatterAtThisTime(BCE_COMM_MLVette_ForceDrop, ship))
            {
                battleChatterAttempt(SOUND_EVENT_DEFAULT, BCE_COMM_MLVette_ForceDrop, ship, SOUND_EVENT_DEFAULT);
            }
        }
        /////////////////////////

        spec->MiningStatus = FIRST_OFF2;
    case FIRST_OFF2:
        if(aitrackZeroRotationAnywhere(ship))
        {
            flag = 2;
        }

        if(aitrackZeroVelocity(ship))
        {
            if(flag == 2)
            {   //we're ready for next step
                MineFormationInfo *mineformationinfo;
                aitrackForceSteadyShip(ship);           //stop movement, stop rotation
                spec->MiningStatus = BEGIN_WALL_DROP_RIGHT;
                spec->MiningSideMax = 1;
                spec->MiningSideCount = 0;
                matGetVectFromMatrixCol1(spec->formation_up,ship->rotinfo.coordsys);
                matGetVectFromMatrixCol2(spec->formation_right,ship->rotinfo.coordsys);
                vecScalarMultiply(spec->formation_up, spec->formation_up, minelayercorvettestatics->MineSpacing);
                vecScalarMultiply(spec->formation_down, spec->formation_up, -1.0f);
                vecScalarMultiply(spec->formation_right,spec->formation_right,minelayercorvettestatics->MineSpacing);
                vecScalarMultiply(spec->formation_left,spec->formation_right,-1.0f);
                matGetVectFromMatrixCol3(spec->formation_heading,ship->rotinfo.coordsys);
                vecScalarMultiply(spec->formation_heading,spec->formation_heading,-minelayercorvettestatics->MineDropDistance);

                //Create Formation Entity Here

                mineformationinfo = memAlloc(sizeof(MineFormationInfo),"MineFormationInfo",NonVolatile);
                listAddNode(&universe.MineFormationList,&(mineformationinfo->FormLink),mineformationinfo);
                listInit(&mineformationinfo->MineList);
                mineformationinfo->playerowner = ship->playerowner;
                mineformationinfo->FULL = FALSE;
                mineformationinfo->wallstate = PULSE_START;
                mineformationinfo->effect = NULL;
                spec->mineforminfo = mineformationinfo;
                time = 29.0;
                spec->mineforminfo->waittime = time;     //set wait time for each pulse

                spec->formation_number_X = 0;
                spec->formation_number_Y = 0;

                vecAdd(spec->formation_position,ship->posinfo.position,spec->formation_heading);
                spec->mineaistate = MINE_DROP_FORMATION;
                MinelayerCorvetteFire(ship,target);
                spec->MineDropNumber = 1;
            }
        }
        break;
    case BEGIN_WALL_DROP_RIGHT:
        vecAddTo(spec->formation_position,spec->formation_right);
        spec->mineaistate = MINE_DROP_FORMATION;

        MinelayerCorvetteFire(ship,target);
        spec->MineDropNumber++;
        spec->formation_number_X++;
        spec->MiningSideCount++;
        if(spec->MiningSideCount == spec->MiningSideMax)
        {
            spec->MiningSideCount = 0;
            spec->MiningStatus = BEGIN_WALL_DROP_UP;
        }
        break;
    case BEGIN_WALL_DROP_UP:
        vecAddTo(spec->formation_position,spec->formation_up);
        spec->mineaistate = MINE_DROP_FORMATION;
        MinelayerCorvetteFire(ship,target);
        spec->MineDropNumber++;
        spec->formation_number_Y++;
        spec->MiningSideCount++;
        if(spec->MiningSideCount == spec->MiningSideMax)
        {
            spec->MiningSideMax++;
            spec->MiningSideCount = 0;
            spec->MiningStatus = BEGIN_WALL_DROP_LEFT;
        }
        break;
    case BEGIN_WALL_DROP_LEFT:
        vecAddTo(spec->formation_position,spec->formation_left);
        spec->mineaistate = MINE_DROP_FORMATION;
        MinelayerCorvetteFire(ship,target);
        spec->MineDropNumber++;
        spec->formation_number_X--;
        spec->MiningSideCount++;
        if(spec->MiningSideCount == spec->MiningSideMax)
        {
            spec->MiningSideCount = 0;
            spec->MiningStatus = BEGIN_WALL_DROP_DOWN;
        }
        break;
    case BEGIN_WALL_DROP_DOWN:
        vecAddTo(spec->formation_position,spec->formation_down);
        spec->mineaistate = MINE_DROP_FORMATION;
         MinelayerCorvetteFire(ship,target);
        spec->MineDropNumber++;
        spec->formation_number_Y--;
        spec->MiningSideCount++;
        if(spec->MiningSideCount == spec->MiningSideMax)
        {
            spec->MiningSideMax++;
            spec->MiningSideCount = 0;
            spec->MiningStatus = BEGIN_WALL_DROP_RIGHT;
        }
        break;
    case DONE_WAIT:
        spec->mineaistate = MINE_DROP_ATTACK;
        return TRUE;
        break;
    }
    if(spec->MineDropNumber == minelayercorvettestatics->NumMinesInSide*minelayercorvettestatics->NumMinesInSide)
    {
        if(spec->mineforminfo != NULL)
        {
            spec->mineforminfo->FULL = TRUE;
            spec->mineforminfo = NULL;
        }
        spec->mineaistate=MINE_DROP_ATTACK;
        spec->MiningStatus = DONE_WAIT;
        spec->MineDropNumber = 0;
        return(TRUE);                               //finished Wall
    }

    return(FALSE);
}
Example #30
0
void calcAllNormals(float *normals, float *depthBuf, int width, int height, unsigned nSampleStep)
{

	//	Grid Points
	for(int j = 0; j < height; j += nSampleStep)
	for(int i = 0; i <  width; i += nSampleStep)
	{
		float fd = *(depthBuf + (i + j * width));
		if(fd > 0)
		{
			getAvgNormal(normals + 3 * (i + j * width), depthBuf, i, j, width, height, nAvgNormRad);
		}
	}

	if(nSampleStep == 1) 
	{
		return;
	}

	//	Interpolation other pixels
	for(int j = 0; j < height; j += 1)
	for(int i = 0; i <  width; i += 1)
	{
		if( (i % nSampleStep == 0) && (j % nSampleStep == 0))
		{
			continue;
		}

		float fd = *(depthBuf + (i + j * width));
		if(fd > 0)
		{
			//	1. find grid
			int nGridX0 = (i / nSampleStep) * nSampleStep;
			int nGridY0 = (j / nSampleStep) * nSampleStep;

			float fDistPercX = (i - nGridX0) * 1.f / nSampleStep;
			float fDistPercY = (j - nGridY0) * 1.f / nSampleStep;
			
			//	2. Bi-linear Interpolation
			float NullNorm[3] = {0};
			float *currNormals[4];
			currNormals[0] = normals + 3 * (nGridX0 + nGridY0 * width);

			if((i + 1) < width && (nGridX0 + nSampleStep) < width ) 
			{
				currNormals[1] = normals + 3 * (nGridX0 + nSampleStep + nGridY0 * width);
			}
			else
			{
				currNormals[1] = NullNorm;
			}

			if((j + 1)< height && (nGridY0 + nSampleStep) < height)
			{
				currNormals[2] = normals + 3 * (nGridX0 + (nGridY0 + nSampleStep) * width);
			}
			else
			{
				currNormals[2] = NullNorm;
			}

			if(	(i + 1) < width && (j + 1)< height && 
				(nGridY0 + nSampleStep) < height && 
				(nGridX0 + nSampleStep) < width )
			{
				currNormals[3] = normals + 3 * (nGridX0 + nSampleStep + (nGridY0 + nSampleStep) * width);
			}
			else
			{
				currNormals[3] = NullNorm;
			}

			float tmp[3], tmp1[3];

			float n01[3] = {0}; 
			vecScale(currNormals[0], (1 - fDistPercX), tmp);
			vecScale(currNormals[1], fDistPercX, tmp1);
			vecAdd(tmp, tmp1, n01);

			float n23[3] = {0};
			vecScale(currNormals[2], (1 - fDistPercX), tmp);
			vecScale(currNormals[3], fDistPercX, tmp1);
			vecAdd(tmp, tmp1, n23);

			float *pCurrNorm = normals + 3 * (i + j * width);
			vecScale(n01, (1 - fDistPercY), tmp);
			vecScale(n23, fDistPercY, tmp1);
			vecAdd(tmp, tmp1, pCurrNorm);
		}
	}//	for
}