Пример #1
0
Sphere::Sphere(GLfloat _x, GLfloat _y, GLfloat _z, GLfloat _radius, GLfloat _r, GLfloat _g, GLfloat _b) {
	x = _x;
	y = _y;
	z = _z;
	radius = _radius;

	float speedCap = 0.05;
	vx = randomFloat(-speedCap, speedCap);
	vy = randomFloat(-speedCap, speedCap);
	vz = randomFloat(-speedCap, speedCap);

	if (_r == -1) {
		color[0] = randomFloat(0.0, 1.0);
		color[1] = randomFloat(0.0, 1.0);
		color[2] = randomFloat(0.0, 1.0);
	} else {
		color[0] = _r;
		color[1] = _g;
		color[2] = _b;
	}

	color[3] = 1.0f;
}
Пример #2
0
float randomMass() { return randomFloat(mass_min, mass_max); }
Пример #3
0
double RobertaFunctions::arrRand(int len, double arr[]) {
  int arrayInd = len * (randomFloat()*100)/100;
  return arr[arrayInd - 1];
}
Пример #4
0
float Random::randomInRange(float min, float max){
	return randomFloat() * (max - min + 1) + min;
}
Пример #5
0
std::vector<std::vector<Phase>> initializeBossPhases(World &world, Boss &boss)
{
    std::vector<std::vector<Phase>> data(Boss::TypeCount);

    // Welcome to one of the most un-readable code I've ever made :

    // Boss1 Phase1
    Phase b1p1(world, boss, sf::seconds(5.f));
    b1p1.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        Player* player = world.getPlayerEntity();
        //world.shakeCameraFor(0.3f);
        boss.unsensible();
        if((b.getPosition().x-player->getPosition().x) > 40) {
            boss.move(Entity::Left);
        } else if((b.getPosition().x-player->getPosition().x) < 40) {
            boss.move(Entity::Right);
        } else {
            //boss.knock();
        }
    });
    data[Boss::Boss1].push_back(b1p1);
    // Boss1 Phase2
    Phase b1p2(world, boss, sf::seconds(3.f));
    b1p2.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        b.sensible();
    });
    data[Boss::Boss1].push_back(b1p2);
    // Boss1 Phase3
    Phase b1p3(world, boss, sf::seconds(1.f));
    b1p3.addSkill(sf::seconds(0.9f), [&](Boss& b, sf::Time dt){
        if(randomInt(0,5) == 1) world.addMedkit(sf::Vector2f(randomFloat(10, 1270), 20));
    });
    data[Boss::Boss1].push_back(b1p3);
    // Boss1 Phase4
    Phase b1p4(world, boss, sf::seconds(1.f));
    b1p4.addSkill(sf::seconds(0.9f), [&](Boss& b, sf::Time dt){
        Player* player = world.getPlayerEntity();
        auto pos = player->getPosition();
        //world.addZombie(sf::Vector2f(pos.x, 100.f));
        //world.addZombie(sf::Vector2f(pos.x+50.f, 100.f));
        world.addZombie(sf::Vector2f(randomFloat(10, 1270), 100.f));
        b.playLocalSound(world.getCommandQueue(), Sounds::Boss1AddPop);
    });
    data[Boss::Boss1].push_back(b1p4);

    //////////////////////////////////////////////

    /*// Boss2 Phase2
    Phase b2p2(world, boss, sf::seconds(2.f));
    b2p2.addSkill(sf::seconds(0.90f), [&](Boss&, sf::Time){
    });
    data[Entity::Boss2].push_back(b2p2);
    // Boss2 Phase1
    Phase b2p1(world, boss, sf::seconds(1.2f));
    b2p1.addSkill(sf::seconds(0.5f), [&](Boss& b, sf::Time){
        PlayerEntity* player = world.player();
        if((b.getPosition().x-player->getPosition().x) > 0) {
            world.addCreature(2, 50.f);
        } else {
            world.addCreature(2, -50.f);
        }
    });
    data[Entity::Boss2].push_back(b2p1);
    // Boss2 Phase2
    data[Entity::Boss2].push_back(b2p2);
    data[Entity::Boss2].push_back(b2p1);
    data[Entity::Boss2].push_back(b2p2);
    data[Entity::Boss2].push_back(b2p1);
    // Boss1 Phase4
    Phase b2p3(world, boss, sf::seconds(0.f));
    b2p3.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time dt){
        PlayerEntity* player = world.player();
        if(b.getPosition().x < 512) {
            for(unsigned int i = 0; i < 5; ++i)
            {
                world.addCreature(2, 50.f + i*32.f);
            }
            world.addCreature(1, 380.f);
        } else {
            for(unsigned int i = 0; i < 5; ++i)
            {
                world.addCreature(2, -50.f - i*32.f);
            }
            world.addCreature(1, -380.f);
        }
    });
    data[Entity::Boss2].push_back(b2p3);
    // Boss2 Phase4
    Phase b2p4(world, boss, sf::seconds(4.f));
    b2p4.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        PlayerEntity* player = world.player();
        if((b.getPosition().x-player->getPosition().x) > 0) {
            boss.move(Entity::Left);
        } else {
            boss.move(Entity::Right);
        }
    });
    data[Entity::Boss2].push_back(b2p4);
    // Boss2 Phase5
    Phase b2p5(world, boss, sf::seconds(2.f));
    b2p5.addSkill(sf::seconds(0.90f), [&](Boss& b, sf::Time){
        b.knock();
    });
    data[Entity::Boss2].push_back(b2p5);
    // Boss2 Phase6
    Phase b2p6(world, boss, sf::seconds(0.0f));
    b2p6.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        PlayerEntity* player = world.player();
        if((b.getPosition().x-player->getPosition().x) > 0) {
            world.addCreature(3, 50.f);
        } else {
            world.addCreature(3, -50.f);
        }
    });
    data[Entity::Boss2].push_back(b2p6);
    // Boss2 Phase7
    Phase b2p7(world, boss, sf::seconds(4.1f));
    b2p7.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        PlayerEntity* player = world.player();
        if((b.getPosition().x-player->getPosition().x) > 0) {
            boss.move(Entity::Right);
        } else {
            boss.move(Entity::Left);
        }
    });
    data[Entity::Boss2].push_back(b2p7);

    //////////////////////////////////////////////

    // Boss3 Phase1
    Phase b3p1(world, boss, sf::seconds(0.6f));
    b3p1.addSkill(sf::seconds(0.5f), [&](Boss& b, sf::Time){
        for(unsigned int i = 0; i < 6; ++i)
        {
            world.addCreature(3, 50.f + 150.f*i);
            world.addCreature(3, -50.f - 150.f*i);
        }
    });
    data[Entity::Boss3].push_back(b3p1);
    Phase b3p2(world, boss, sf::seconds(5.f));
    b3p2.addSkill(sf::seconds(0.90f), [&](Boss& b, sf::Time){b.knock();});
    data[Entity::Boss3].push_back(b3p2);
    // Boss1 Phase1
    Phase b3p3(world, boss, sf::seconds(5.f));
    b3p3.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        PlayerEntity* player = world.player();
        world.shakeCameraFor(0.3f);
        if((b.getPosition().x-player->getPosition().x) > 0) {
            boss.move(Entity::Left);
        } else {
            boss.move(Entity::Right);
        }
    });
    data[Entity::Boss3].push_back(b3p3);
    data[Entity::Boss3].push_back(b3p1);
    // Boss1 Phase4
    Phase b3p4(world, boss, sf::seconds(3.f));
    b3p4.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time){
        b.knock();
    });
    data[Entity::Boss3].push_back(b3p4);
    // Boss3 Phase5
    Phase b3p5(world, boss, sf::seconds(2.f));
    b3p5.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time dt){
        b.setPosition(sf::Vector2f(b.getPosition().x, b.getPosition().y-500*dt.asSeconds()));
    });
    data[Entity::Boss3].push_back(b3p5);
    data[Entity::Boss3].push_back(b3p2);
    // Boss3 Phase6
    Phase b3p6(world, boss, sf::seconds(0.0f));
    b3p6.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time dt){
        PlayerEntity* player = world.player();
        b.setPosition(sf::Vector2f(player->getPosition().x, -160));
        world.addCreature(1, 50);
    });
    data[Entity::Boss3].push_back(b3p6);
    Phase b3p6bis(world, boss, sf::seconds(1.5f));
    b3p6bis.addSkill(sf::seconds(0.90f), [&](Boss& b, sf::Time){b.knock();});
    data[Entity::Boss3].push_back(b3p6bis);
    // Boss3 Phase7
    Phase b3p7(world, boss, sf::seconds(1.3f));
    b3p7.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time dt){
        if(b.getPosition().y < 512-105)
        {
            b.setPosition(sf::Vector2f(b.getPosition().x, b.getPosition().y+500*dt.asSeconds()));
        }
        else
        {
            world.shakeCamera();
            b.playLocalSound(world.getCommandQueue(), Sounds::BossCrush);
        }
    });
    data[Entity::Boss3].push_back(b3p7);
    data[Entity::Boss3].push_back(b3p1);
    // Boss3 Phase8
    data[Entity::Boss3].push_back(b3p5);
    data[Entity::Boss3].push_back(b3p6);
    data[Entity::Boss3].push_back(b3p6bis);
    data[Entity::Boss3].push_back(b3p7);
    data[Entity::Boss3].push_back(b3p1);
    data[Entity::Boss3].push_back(b3p5);
    // Boss3 Phase9
    Phase b3p9(world, boss, sf::seconds(1.5f));
    b3p9.addSkill(sf::seconds(0.f), [&](Boss& b, sf::Time dt){
        b.setPosition(1024+160, 512-105);
    });
    data[Entity::Boss3].push_back(b3p9);*/

    return data;
}
Пример #6
0
void DimensionReduction::apply(Window im, int dimensions) {
    assert(dimensions < im.channels && dimensions > 0, 
           "dimensions must be greater than zero and less than the current number of channels\n");

    // get some statistics (mostly for the covariance matrix)
    Stats stats(im);

    // we're going to find the leading eigenvectors of the covariance matrix and
    // use them as the basis for our subspace
    vector<float> subspace(dimensions * im.channels), newsubspace(dimensions * im.channels);

    for (int i = 0; i < dimensions * im.channels; i++) subspace[i] = randomFloat(0, 1);

    float delta = 1;
    while (delta > 0.00001) {
        // multiply the subspace by the covariance matrix
        for (int d = 0; d < dimensions; d++) {
            for (int c1 = 0; c1 < im.channels; c1++) {
                newsubspace[d * im.channels + c1] = 0;
                for (int c2 = 0; c2 < im.channels; c2++) {
                    newsubspace[d * im.channels + c1] += (float)(subspace[d * im.channels + c2] * stats.covariance(c1, c2));
                }
            }
        }

        // orthonormalize it with gram-schmidt
        for (int d = 0; d < dimensions; d++) {
            // first subtract it's component in the direction of all earlier vectors
            for (int d2 = 0; d2 < d; d2++) {
                float dot = 0;
                for (int c = 0; c < im.channels; c++) {
                    dot += newsubspace[d * im.channels + c] * newsubspace[d2 * im.channels + c];
                }
                for (int c = 0; c < im.channels; c++) {
                    newsubspace[d * im.channels + c] -= dot * newsubspace[d2 * im.channels + c];
                }                
            }
            // then normalize it
            float sum = 0;
            for (int c = 0; c < im.channels; c++) {
                float val = newsubspace[d * im.channels + c];
                sum += val * val;
            }
            float factor = 1.0f / sqrt(sum);
            for (int c = 0; c < im.channels; c++) {
                newsubspace[d * im.channels + c] *= factor;
            }
            // if the sum is negative, flip it
            sum = 0;
            for (int c = 0; c < im.channels; c++) {
                sum += newsubspace[d * im.channels + c];
            }
            if (sum < -0.01) {
                for (int c = 0; c < im.channels; c++) {
                    newsubspace[d * im.channels + c] *= -1;
                }                
            }
        }

        // check to see how much changed
        delta = 0;
        for (int d = 0; d < dimensions; d++) {
            for (int c = 0; c < im.channels; c++) {
                float diff = newsubspace[d * im.channels + c] - subspace[d * im.channels + c];
                delta += diff * diff;
            }
        }

        newsubspace.swap(subspace);
    }

    // now project the image onto the subspace

    vector<float> output(im.channels);
    for (int t = 0; t < im.frames; t++) {
        for (int y = 0; y < im.height; y++) {
            for (int x = 0; x < im.width; x++) {
                for (int c = 0; c < im.channels; c++) output[c] = 0;
                // project this pixel onto each vector, and add the results
                for (int d = 0; d < dimensions; d++) {
                    float dot = 0;
                    for (int c = 0; c < im.channels; c++) {
                        dot += im(x, y, t)[c] * subspace[d * im.channels + c];                        
                    }
                    for (int c = 0; c < im.channels; c++) {
                        output[c] += dot * subspace[d * im.channels + c];
                    }
                }
                for (int c = 0; c < im.channels; c++) im(x, y, t)[c] = output[c];
            }
        }
    }

    // display the subspace for debugging
    printf("Basis chosen:\n");
    for (int c = 0; c < im.channels; c++) {
        for (int d = 0; d < dimensions; d++) {
            printf("%f \t", newsubspace[d * im.channels + c]);
        }
        printf("\n");
    }        



}
Пример #7
0
TEST( AudioEngine, TempoUpdate )
{
    AudioEngine::test_program = 1; // help mocked OpenSL IO identify which test is running

    // prepare engine environment

    float oldTempo = randomFloat( 40.0f,  199.0f );
    float newTempo = randomFloat( 120.0f, 300.0f );

    SequencerController* controller = new SequencerController();
    controller->prepare( 240, 48000, oldTempo, 4, 4 );
    controller->setTempoNow( oldTempo, 4, 4 ); // ensure tempo is applied immediately
    controller->rewind();

    int oldSPBar  = AudioEngine::samples_per_bar;
    int oldSPBeat = AudioEngine::samples_per_beat;
    int oldSPStep = AudioEngine::samples_per_step;
    int oldMaxBP  = AudioEngine::max_buffer_position = randomInt( 11025, 8820  );

    EXPECT_EQ( oldTempo, controller->getTempo() )
        << "expected tempo to be set prior to engine start";

    // request new tempo via controller

    controller->setTempo( newTempo, 12, 8 );

    EXPECT_EQ( oldTempo, controller->getTempo() )
        << "expected tempo at the old value to be set prior to engine start";

    EXPECT_EQ( 4, controller->getTimeSigBeatAmount() )
        << "expected time signature to be at the old value prior to the engine start";

    EXPECT_EQ( 4, controller->getTimeSigBeatUnit() )
        << "expected time signature to be at the old value prior to the engine start";

    AudioEngine::start();
    //usleep( 50 ); // tempo update is executed after the engine is halted by the OpenSL mock

    // assert results

    EXPECT_EQ( newTempo, controller->getTempo() )
        << "expected engine to have updated the tempo during a single iteration of its render cycle";

    EXPECT_EQ( 12, controller->getTimeSigBeatAmount() )
        << "expected engine to have updated the time signature during a single iteration of its render cycle";

    EXPECT_EQ( 8, controller->getTimeSigBeatUnit() )
        << "expected engine to have updated the time signature during a single iteration of its render cycle";

    ASSERT_FALSE( AudioEngine::max_buffer_position == oldMaxBP )
        << "expected engine to have updated its max buffer position after tempo change";

    ASSERT_FALSE( AudioEngine::samples_per_bar == oldSPBar )
        << "expected engine to have updated its samples per bar value after tempo change";

    ASSERT_FALSE( AudioEngine::samples_per_beat == oldSPBeat )
        << "expected engine to have updated its samples per beat value after tempo change";

    ASSERT_FALSE( AudioEngine::samples_per_step == oldSPStep )
        << "expected engine to have updated its samples per step value after tempo change";

    EXPECT_EQ( 2, AudioEngine::test_program )
        << "expected program to have incremented";

    delete controller;
}
Пример #8
0
// TO DO  - Base on waypoint danger
// base on base point -- if already have attack point and base point -- less focus on base point
int CTFObjectiveResource::getRandomValidPointForTeam ( int team, ePointAttackDefend_s type)
{
	TF2PointProb_t *arr = NULL;
	vector<int> points;
	int iotherteam;

	float fTotal = 0.0f;

	if (( team < 2 ) || ( team > 3 ))
		return 0;

	if ( m_iNumControlPoints == NULL )
		return 0;

	iotherteam = (team==2)?3:2;

	arr = m_ValidPoints[team-2][type];

	for ( int i = 0; i < *m_iNumControlPoints; i ++ )
	{
		if ( arr[i].bValid == true )
		{
			points.push_back(i);

			if ( type == TF2_POINT_ATTACK ) 
			{
				if (GetCappingTeam(i) == team)
					arr[i].fProbMultiplier = 3.0f;
				else if ((getLastCaptureTime(i) + 10.0f) > gpGlobals->curtime )
					arr[i].fProbMultiplier = 2.0f;
			}
			else
			{
				if (GetCappingTeam(i) == iotherteam)
				{
					int numplayers = GetNumPlayersInArea(i,iotherteam);

					// IF this is not base point and a lot of players are here, reduce probability of defending
					if ( (i != GetBaseControlPointForTeam(team)) && (numplayers > 1)  )
					{
						arr[i].fProbMultiplier = 1.0f - ((float)numplayers/(gpGlobals->maxClients/4));

						if ( arr[i].fProbMultiplier <= 0.0f )
							arr[i].fProbMultiplier = 0.1f;
					}
					else // Otherwise there aren't any playres on or is base and has been attacked recently
						arr[i].fProbMultiplier = 4.0f;
				}
				else if ((getLastCaptureTime(i) + 10.0f) > gpGlobals->curtime )
					arr[i].fProbMultiplier = 2.0f;
			}

			fTotal += arr[i].fProb*arr[i].fProbMultiplier;
		}
	}

	float fRand = randomFloat(0.0f,fTotal);

	fTotal = 0.0f;

	for ( unsigned int i = 0; i < points.size(); i ++ )
	{
		int index = points[i];

		fTotal += arr[index].fProb*arr[index].fProbMultiplier;

		if ( fTotal > fRand )
		{
			return m_IndexToWaypointAreaTranslation[index];
		}
	}

	// no points
	return 0;
}
Пример #9
0
void tree::fractalTree(int count, Vertex zero, Vertex one, float angleRight, float angleLeft)
{
	count--;
	if (count > 0) {
		vec4 Zero(zero.coords[0], zero.coords[1],zero.coords[2],1);
		vec4 One(one.coords[0], one.coords[1], one.coords[2],1);

		vec4 Scale = (One - Zero);
		Scale = Scale * 0.8f;
		//float randValue = randomFloat(-rand, rand);
		//float alpha = ((angleRight + randValue)*3.14 / 180);
		////mat3x3 rotMatrix(cos(alpha), sin(alpha), -sin(alpha), cos(alpha));
		//mat3x3 rotMatrixX(1, 0, 0, 0, cos(alpha), sin(alpha), 0, -sin(alpha), cos(alpha));
		//float randValue2 = randomFloat(-rand, rand);
		//float beta = ((angleRight + randValue2)*3.14 / 180);
		//mat3x3 rotMatrixZ(cos(beta), sin(beta), 0, -sin(beta), cos(beta), 0, 0, 0, 1);
		//vec3 Answer = (Scale * rotMatrixZ)*rotMatrixX;
		mat4 rotMatrix = mat4(1);
		rotMatrix = rotate(rotMatrix, randomFloat((-angleRight), angleRight)*3.14f/180.0f, vec3(0, 1, 0));
		rotMatrix = rotate(rotMatrix, randomFloat((-angleRight), angleRight)*3.14f / 180.0f, vec3(0, 0, 1));
		rotMatrix = rotate(rotMatrix, randomFloat((-angleRight), angleRight)*3.14f / 180.0f, vec3(1, 0, 0));
		vec4 Answer = rotMatrix * Scale;
		Answer = Answer + One;

		branches[branchesIterator].zero = one;
		branches[branchesIterator].zero.colors[0] = 0.3f;
		branches[branchesIterator].zero.colors[1] = 0.1f;
		branches[branchesIterator].one.coords[0] = Answer.x;
		branches[branchesIterator].one.coords[1] = Answer.y;
		branches[branchesIterator].one.coords[2] = Answer.z;
		branches[branchesIterator].one.coords[3] = 1;
		branches[branchesIterator].one.coords[3] = 1;
		branches[branchesIterator].one.colors[0] = 0.3f;
		branches[branchesIterator].one.colors[1] = 0.1f;
		if (count == 1)
			branches[branchesIterator].end = true;
		else
			branches[branchesIterator].end = false;
		branchesIterator++;
		depth.push_back(count);
		fractalTree(count, branches[branchesIterator - 1].zero, branches[branchesIterator - 1].one, angleRight, angleLeft);

		////////////////////////////////////////////////

		Zero = vec4(zero.coords[0], zero.coords[1], zero.coords[2],1);
		One = vec4(one.coords[0], one.coords[1], one.coords[2],1);

		Scale = One - Zero;
		Scale = Scale * 0.8f;
		/*randValue = randomFloat(-rand, rand);
		alpha = ((angleLeft +randValue)*3.14 / 180)*-1;
		rotMatrixX = mat3x3(1, 0, 0, 0, cos(alpha), sin(alpha), 0, -sin(alpha), cos(alpha));
		randValue2 = randomFloat(-rand, rand);
		beta = ((angleLeft + randValue2)*3.14 / 180)*-1;
		rotMatrixZ = mat3x3(cos(beta), sin(beta), 0, -sin(beta), cos(beta), 0, 0, 0, 1);
		Answer = (Scale * rotMatrixZ)*rotMatrixX;*/

		rotMatrix = mat4(1);
		rotMatrix = rotate(rotMatrix, (randomFloat((-angleLeft), angleLeft)*3.14f/180.0f), vec3(0, 1, 0));
		rotMatrix = rotate(rotMatrix, randomFloat((-angleLeft), angleLeft)*3.14f / 180.0f, vec3(0, 0, 1));
		rotMatrix = rotate(rotMatrix, randomFloat((-angleLeft), angleLeft)*3.14f / 180.0f, vec3(1, 0, 0));

		Answer = rotMatrix * Scale;
		Answer = Answer + One;

		branches[branchesIterator].zero = one;
		branches[branchesIterator].zero.colors[0] = 0.3f;
		branches[branchesIterator].zero.colors[1] = 0.1f;
		branches[branchesIterator].one.coords[0] = Answer.x;
		branches[branchesIterator].one.coords[1] = Answer.y;
		branches[branchesIterator].one.coords[2] = Answer.z;
		branches[branchesIterator].one.coords[3] = 1;
		branches[branchesIterator].one.coords[3] = 1;
		branches[branchesIterator].one.colors[0] = 0.3f;
		branches[branchesIterator].one.colors[1] = 0.1f;
		if (count == 1)
			branches[branchesIterator].end = true;
		else
			branches[branchesIterator].end = false;
		branchesIterator++;
		depth.push_back(count);
		fractalTree(count, branches[branchesIterator - 1].zero, branches[branchesIterator - 1].one, angleRight,angleLeft);
	}
}
Vector2D ParticalEffect::RandomUnitVectorHalf() {
    float angle = (TWO_PI/2.0f) * randomFloat();
    return Vector2D( cos(angle), sin(angle) );
}
Vector2D ParticalEffect::RandomUnitVector() {
    float angle = TWO_PI * randomFloat();
    return Vector2D( cos(angle), sin(angle) );
}
float ParticalEffect::randomInRange(float min, float max) {
    return randomFloat() * (max - min + 1) + min;
}
//Returns the average velocity of particles produced by the fountain.
cVec3 Explosion::CurVelocity() {
	//return cVec3(0.0f, -3 * cos(mfAngle) , 3 * cos(mfAngle));
	return cVec3(0.5f * randomFloat() - 0.25f, 1.f * randomFloat() + 1.f, 0.5f * randomFloat() - 0.25f);
}
Пример #14
0
float BaseUtils::randomAngle(float from, float to) {
	while (to < from) {
		to += 360;
	}
	return normalizeAngle(randomFloat(from, to));
}
void initWeights(Neuron* neuron) {
	for (int i = 0; i <= N; i++)
		neuron->w[i] = randomFloat();
}
Пример #16
0
 glm::vec2 Randomness::randomUnitVector()
{
	float angle = TWO_PI * randomFloat();
	return glm::vec2(cos(angle), sin(angle));
}
Пример #17
0
 float Randomness::randomInRange(float min, float max)
{
	return (randomFloat()*(max-min)+min);
}
Пример #18
0
//--------------------------------------------------------------
void ofApp::setup(){
    
    sliderArea = ofRectangle(0, 0, ofGetWindowWidth() / 2, ofGetWindowHeight());
    
    ///////////////////////////////
    //      Audio Stuff
    ///////////////////////////////
    
    const int NUM_STEPS = 8;
    
    // synth paramters are like instance variables -- they're values you can set later, by
    // cally synth.setParameter()
    ControlGenerator bpm = synth.addParameter("tempo",100).min(50).max(300);
    ControlGenerator transpose = synth.addParameter("transpose", 0).min(-6).max(6);
    
    // ControlMetro generates a "trigger" message at a given bpm. We multiply it by four because we
    // want four 16th notes for every beat
    ControlGenerator metro = ControlMetro().bpm(4 * bpm);
    
    // ControlStepper increments a value every time it's triggered, and then starts at the beginning again
    // Here, we're using it to move forward in the sequence
    ControlGenerator step = ControlStepper().end(NUM_STEPS).trigger(metro);
    
    // ControlSwitcher holds a list of ControlGenerators, and routes whichever one the inputIndex is pointing
    // to to its output.
    ControlSwitcher pitches = ControlSwitcher().inputIndex(step);
    ControlSwitcher cutoffs = ControlSwitcher().inputIndex(step);
    ControlSwitcher glides = ControlSwitcher().inputIndex(step);
    
    // stick a bunch of random values into the pitch and cutoff lists
    for(int i = 0; i < NUM_STEPS; i++){
        ControlGenerator pitchForThisStep = synth.addParameter("step" + to_string(i) + "Pitch", randomFloat(10, 80)).min(10).max(80);
        pitches.addInput(pitchForThisStep);
        
        ControlGenerator cutoff = synth.addParameter("step" + to_string(i) + "Cutoff", 500).min(30).max(1500);
        cutoffs.addInput(cutoff);
        
        ControlGenerator glide = synth.addParameter("step" + to_string(i) + "Glide", 0).min(0).max(0.1);
        glides.addInput(glide);
        
    }
    
    // Define a scale according to steps in a 12-note octave. This is a pentatonic scale. Like using
    // just the black keys on a piano
    vector<float> scale;
    scale.push_back(0);
    scale.push_back(2);
    scale.push_back(3);
    scale.push_back(5);
    scale.push_back(7);
    scale.push_back(10);
    
    // ControlSnapToScale snaps a float value to the nearest scale value, no matter what octave its in
    ControlGenerator midiNote = transpose + ControlSnapToScale().setScale(scale).input(pitches);
    
    ControlGenerator frequencyInHertz = ControlMidiToFreq().input(midiNote);
    
    // now that we've done all that, we have a frequency signal that's changing 4x per beat
    Generator tone = RectWave().freq( frequencyInHertz.smoothed().length(glides) );
    
    // create an amplitude signal with an ADSR envelope, and scale it down a little so it's not scary loud
    Generator amplitude = ADSR(0.01, 0.1, 0,0).trigger(metro) * 0.3;
    
    // create a filter, and feed the cutoff sequence in to it
    LPF24 filter =  LPF24().cutoff(cutoffs).Q(0.1);
    filter.input(tone * amplitude);
    
    // rout the output of the filter to the synth's main output
    synth.setOutputGen( filter );
    
    // build a slider for each parameter
    vector<ControlParameter> synthParameters = synth.getParameters();
    for(int i = 0; i < synthParameters.size(); i++){
        sliders.push_back(ParameterSlider(synthParameters.at(i)));
    }
    
    
    auto _devices = soundStream.getDeviceList();
    ofSoundStreamSettings _settings;
    if (!_devices.empty()) {
        _settings.setOutDevice(_devices[1]);
    }
    _settings.setOutListener(this);
    _settings.bufferSize = 512;
    _settings.sampleRate = 44100;
    _settings.numInputChannels = 0;
    _settings.numOutputChannels = 2;
    soundStream.setup(_settings);
    
}
Пример #19
0
SimdVector3 randomPosition( const SimdPoint3& minPoint, const SimdPoint3& maxPoint )
{
	return SimdVector3( randomFloat( minPoint.getX(), maxPoint.getX() ),
		randomFloat( minPoint.getY(), maxPoint.getY() ),
		randomFloat( minPoint.getZ(), maxPoint.getZ() ) );
}
Пример #20
0
int main()
{
	// seeding random
	srand(static_cast<unsigned int>(time(nullptr)));

	// creating window
	sf::RenderWindow window(sf::VideoMode(1000, 1000), "genlines");
	window.setVerticalSyncEnabled(true);

	// centering 2D camera
	window.setView(sf::View(sf::FloatRect(-500, -500, 1000, 1000)));

	// creating manager
	EvolutionManager manager(sf::Vector2f(200.0f, -250.0f), sf::Vector2f(-250.0f, -250.0f));
	std::vector<Line> lines = manager.getCurrentGeneration();

	// creating circle around target point
	sf::CircleShape area;
	area.setOutlineThickness(1.0f);
	area.setOutlineColor(sf::Color::Red);
	area.setFillColor(sf::Color::Black);
	area.setRadius(50.0f);
	area.setPosition(manager.getTarget() - sf::Vector2f(50.0f, 50.0f));

	// starting main application looop
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
			case sf::Event::Closed:
				window.close();
				break;

			case sf::Event::KeyPressed:
				if (event.key.code == sf::Keyboard::Key::Escape) {
					window.close();
				}
				else if (event.key.code == sf::Keyboard::Key::Space) {
					lines = manager.nextGeneration();
				}
				else if (event.key.code == sf::Keyboard::Key::R) {
					manager = EvolutionManager(sf::Vector2f(randomFloat(-400.0f, 400.0f), randomFloat(-400.0f, 400.0f)),
											   sf::Vector2f(randomFloat(-400.0f, 400.0f), randomFloat(-400.0f, 400.0f)));
					lines = manager.getCurrentGeneration();
					area.setPosition(manager.getTarget() - sf::Vector2f(50.0f, 50.0f));
				}
				break;

			default:
				break;
			}
		}

		window.clear();

		// drawing sphere
		window.draw(area);

		// drawing lines
		for (Line& line : lines) {
			window.draw(line);
		}

		window.display();
	}

	return 0;
}
Пример #21
0
void KMeans::apply(Window im, int clusters) {
    assert(clusters > 1, "must have at least one cluster\n");

    vector< vector<float> > cluster, newCluster;
    vector<int> newClusterMembers(clusters);

    for (int c = 0; c < im.channels; c++) {
        cluster.push_back(vector<float>(clusters, 0));
        newCluster.push_back(vector<float>(clusters, 0));
    }

    // initialize the clusters to randomly selected pixels
    for (int i = 0; i < clusters; i++) {
        float *pixel = im(randomInt(0, im.width-1), randomInt(0, im.height-1), randomInt(0, im.frames-1));
        for (int c = 0; c < im.channels; c++) {
            cluster[c][i] = pixel[c] + randomFloat(-0.0001f, 0.0001f);
        }
    }

    while (1) {
        // wipe the newCluster
        for (int i = 0; i < clusters; i++) {
            newClusterMembers[i] = 0;
            for (int c = 0; c < im.channels; c++) {           
                newCluster[c][i] = 0;
            }
        }

        for (int t = 0; t < im.frames; t++) {
            for (int y = 0; y < im.height; y++) {
                for (int x = 0; x < im.width; x++) {
                    float *pixel = im(x, y, t);
                    // assign this pixel to a cluster
                    int bestCluster = 0;
                    float bestDistance = 1e10;
                    for (int i = 0; i < clusters; i++) {
                        float distance = 0;
                        for (int c = 0; c < im.channels; c++) {
                            float d = cluster[c][i] - pixel[c];
                            distance += d*d;
                        }
                        if (distance < bestDistance) {
                            bestCluster = i;
                            bestDistance = distance;
                        }
                    }

                    for (int c = 0; c < im.channels; c++) {
                        newCluster[c][bestCluster] += pixel[c];
                    }
                    newClusterMembers[bestCluster]++;
                }
            }
        }

        // normalize the new clusters (reset any zero ones to random)
        for (int i = 0; i < clusters; i++) {
            if (newClusterMembers[i] == 0) {
                float *pixel = im(randomInt(0, im.width-1),
                                         randomInt(0, im.height-1),
                                         randomInt(0, im.frames-1));
                for (int c = 0; c < im.channels; c++) {
                    newCluster[c][i] = pixel[c] + randomFloat(-0.0001f, 0.0001f);
                }
            } else {
                for (int c = 0; c < im.channels; c++) {
                    newCluster[c][i] /= newClusterMembers[i];
                }
            }
        }

        // break if the clusters are unchanged
        if (cluster == newCluster) break;

        // swap over the pointers
        cluster.swap(newCluster);
    }

    // now color each pixel according to the closest cluster
    for (int t = 0; t < im.frames; t++) {
        for (int y = 0; y < im.height; y++) {
            for (int x = 0; x < im.width; x++) {
                float *pixel = im(x, y, t);
                // assign this pixel to a cluster
                int bestCluster = 0;
                float bestDistance = 1e10;
                for (int i = 0; i < clusters; i++) {
                    float distance = 0;
                    for (int c = 0; c < im.channels; c++) {
                        float d = cluster[c][i] - pixel[c];
                        distance += d*d;
                    }
                    if (distance < bestDistance) {
                        bestCluster = i;
                        bestDistance = distance;
                    }
                }

                for (int c = 0; c < im.channels; c++) {
                    pixel[c] = cluster[c][bestCluster];
                }
            }
        }
    }    
}
void mutacao(Individuo* ind){

	float mutVal;
	
	//Probabilidade de ataque
	if (randomFloat(0,1) < MUT_RATE){
		mutVal = randomFloat(-DELTA_PROB, DELTA_PROB);
		ind->setProbAtk(ind->getProbAtk() + mutVal);
	}

	//Velocidade de ataque
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_VEL_ATK, DELTA_VEL_ATK);
		ind->setVelAtk(ind->getVelAtk() + mutVal);
	}

	//Velocidade de esquiva
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_VEL_DEF, DELTA_VEL_DEF);
		ind->setVelDef(ind->getVelDef() + mutVal);
	}

	//Tempo de ataque
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_T_ATK, DELTA_T_ATK);
		ind->setTAtk(ind->getTAtk() + mutVal);
	}

	//Tempo de defesa
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_T_DEF, DELTA_T_DEF);
		ind->setTDef(ind->getTDef() + mutVal);
	}

	//Torque
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_TORQUE, DELTA_TORQUE);
		ind->setTorque(ind->getTorque() + mutVal);
	}

	//Peso
	if (randomFloat(0, 1) < MUT_RATE) {
		mutVal = randomFloat(-DELTA_WEIGHT, DELTA_WEIGHT);
		ind->setWeight(ind->getWeight() + mutVal);
	}

	
}
Пример #23
0
void Grenade::think(const double elapsedTime)
{
	//Run entity think routines.
	Entity::think(elapsedTime);

	//Check if Grenade lifetime is over.
	if(mLifeTimer.getElapsedTime() > ttl)
	{
		game->getEntityManager()->add(New Explosion(mPosition,3.0f));
		setShouldDelete(true);
	}

	mVelocity.Y -= 0.001;

	if(mPosition.Y < -1.f)
	{
		mVelocity.Y = -mVelocity.Y;
		mVelocity.Y *= GRENADE_DAMPING;

		//if(abs(mVelocity.Y) > 0.01f)
			//game->getSoundEngine()->play3DSound(game->getResourceManager()->get("squishsound"), mPosition, 3.0, randomFloat(0.75,1.25));

		if(rotator < 0)
		{
			rotator += 5;

			if(rotator > 0)
			{
				rotator = 0;
			}
		}
		else if(rotator > 0)
		{
			rotator -= 5;

			if(rotator < 0)
				rotator = 0;
		}

		game->getSoundEngine()->play3DSound(game->getResourceManager()->get("grenade_clink"), mPosition, 0.8f, randomFloat(0.75,1.25));
	}

	if(game->getCurrentMap()->getTile(int(mPosition.X + mVelocity.X), int(mPosition.Z)).type == TYPE_WALL)
	{
		mVelocity.X = -mVelocity.X;

		mVelocity *= GRENADE_DAMPING;

		game->getSoundEngine()->play3DSound(game->getResourceManager()->get("grenade_clink"), mPosition, 0.8f, randomFloat(0.75,1.25));

	}
	if(game->getCurrentMap()->getTile(int(mPosition.X), int(mPosition.Z + mVelocity.Z)).type == TYPE_WALL)
	{
		mVelocity.Z = -mVelocity.Z;

		mVelocity *= GRENADE_DAMPING;

		game->getSoundEngine()->play3DSound(game->getResourceManager()->get("grenade_clink"), mPosition, 0.8f, randomFloat(0.75,1.25));
	}

	//Add velocity to current position.
	mPosition += mVelocity;

	mpAnim->setRotation(mpAnim->getRotation() + rotator);

	if(mVoice)
		mVoice->setPosition(mPosition);
}
Пример #24
0
int main()
{
//vars
	int x = 800;
	int y = 600;
	int framerate = 60;

	const enum modes{BALLS, TRIS, BOXES, ALL};
	int mode;

	const int balls = 0;
	const int triangles = 10;
	const int boxes = 10;
	
	BouncingObject* shapes[balls + triangles + boxes];
	CollisionDetection col;

	//////
	sf::ConvexShape box(4);
	box.setPointCount(4);
	box.setPosition(sf::Vector2f(x - 10, y - 10));
	box.setPoint(0, sf::Vector2f(-10, -10));
	box.setPoint(1, sf::Vector2f(10, -10));
	box.setPoint(2, sf::Vector2f(10, 10));
	box.setPoint(3, sf::Vector2f(-10, 10));
	box.setFillColor(sf::Color(160, 20, 40, 128));
	//////

// Create the main window
sf::RenderWindow window(sf::VideoMode(x, y, 32), "BOUNCING SHAPES");
window.setFramerateLimit(framerate);
srand(time(NULL));

mode = modes::ALL;

int total = 0;

if (mode == modes::BALLS || mode == modes::ALL)
{
	int j;
	for (j = total; j < total + balls; j++)
	{
		shapes[j] = new BouncingBall(16, Vector2f(randomFloat(x - 16, 1, false), randomFloat(y - 16, 1, false)), randomColor());
		shapes[j]->impulse(Vector2f(randomFloat(8, 1, true), randomFloat(8, 1, true)));
		shapes[j]->setRotate(false);
	}
	total += j;
}

if (mode == modes::TRIS || mode == modes::ALL)
{	
	int j = total;
	for (j; j < total + triangles; j++)
	{

		//shapes[j] = new BouncingTriangle(32, Vector2f(0,0), randomColor());
		//shapes[j] = new BouncingTriangle(32, Vector2f(x / 4 , y / 4), randomColor());

		shapes[j] = new BouncingTriangle(16, Vector2f(randomFloat(x - 16, 1, false), randomFloat(y - 16, 1, false)), randomColor());
		shapes[j]->impulse(Vector2f(randomFloat(80, 1, true), randomFloat(80, 1, true)));
		shapes[j]->spin(randomFloat(8, 1, true));
	}
	total += j - total;
}

if (mode == modes::BOXES || mode == modes::ALL)
{
	int j = total;
	for (j; j < total + boxes; j++)
	{
		shapes[j] = new BouncingRectangle(16, Vector2f(randomFloat(x - 16, 1, false), randomFloat(y - 16, 1, false)), randomColor());
		shapes[j]->impulse(Vector2f(randomFloat(8, 1, true), randomFloat(8, 1, true)));
		shapes[j]->spin(randomFloat(8, 1, true));
	}
	total += j - total;
}

// Start game loop
while (window.isOpen())
{
	// Process events
	sf::Event Event;
	while (window.pollEvent(Event))
	{
		// Close window : exit
		if (Event.type == sf::Event::Closed)
		window.close();
		// Escape key : exit
		if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape))
			window.close();
		if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Num1))
			shapes[0]->setPosition(sf::Vector2f(sf::Mouse().getPosition(window)));
		if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Num2))
			shapes[1]->setPosition(sf::Vector2f(sf::Mouse().getPosition(window)));
		
	}

	//Declare looping vars
	int i, j;

	//update items
	for (i = 0; i < total; i++)
	{
		shapes[i]->update(0.05, x, y); 		
	}

	//check collisions
	for (i = 0; i < total - 1; i++)
	{
		bool collision = false;
		for (j = i + 1; j < total; j++)
		{
			if (col.CheckBoundingSphere(shapes[i]->getPosition(), shapes[j]->getPosition(), shapes[i]->getRadius(), shapes[j]->getRadius()))
			{
				if (col.CheckCollisionSAT(*shapes[i], *shapes[j]))
				{
					shapes[i]->bounceOther(shapes[j]->getPosition());
					shapes[j]->bounceOther(shapes[i]->getPosition());
				}
			}
		}
	}

	//prepare frame
	window.clear();

	//draw frame items	
	for (int i = 0; i < total; i++)
	{
		//shapes[i]->draw(window);
		window.draw(shapes[i]->getShape());
		//window.setTitle("" + sf::Mouse().getPosition(window).x + ", " + sf::Mouse().getPosition(window).x);
	}

	// Finally, display rendered frame on screen
	window.display();
	
	} //loop back for next frame
	return EXIT_SUCCESS;
}
Пример #25
0
Vector2D Random::RandomUnitVectorHalf() { 
	float angle = (TWO_PI/6.0f) * randomFloat(); 
	return Vector2D( cos(angle), sin(angle) ); 
}
Пример #26
0
void drawObj(GLenum mode) {
    vector<Group*> groups = mesh->getGroups();
    for (auto g : groups) {
        Group *group = g;
        if (group->getFaces().size() == 0) {
            continue;
        }
        
        Material *material = group->getMaterial();
        if (material != nullptr) {
            if (material->hasTexture()) {
                glBindTexture(GL_TEXTURE_2D, textures->getIds()[material->getTexnum()]);
            }
        }
        
        setLightingForGroup(group);
        
        if (mode == GL_SELECT) {
            glLoadName(group->getId());
        }
        
        float alpha = group->isVisible() ? 1 : 0.2;
        
        
        vector<Face*> faces = group->getFaces();
        for (auto f : faces) {
            if (useRandomColors && (material == nullptr || !material->hasTexture())) {
                glColor4f(randomFloat(), randomFloat(), randomFloat(), alpha);
            } else {
                glColor4f(0.5, 0.5, 0.5, alpha);
            }
            
            Face* face = f;
            vector<int> verticesIndexes = face->getVertices();
            vector<int> normalsIndexes = face->getNormalsIndexes();
            vector<int> texturesIndexes = face->getTextureIndexes();
 
            u_long size = verticesIndexes.size();
            if (size == 3) {
                glBegin(GL_TRIANGLES);
            } else if (size == 4) {
                glBegin(GL_QUADS);
            } else {
                glBegin(GL_POLYGON);
            }
            
            for (int i = 0; i < verticesIndexes.size(); i++) {
                // normal
                int normalIndex = normalsIndexes.at(i);
                if (normalIndex >= 0) {
                    Vertex *normal = mesh->getNormals().at(normalIndex - 1); // -1 porque OBJ são 1-indexed
                    glNormal3f(normal->getX(), normal->getY(), normal->getZ());
                }
                
                // texture mapping
                int textureIndex = texturesIndexes.at(i);
                if (textureIndex >= 0) {
                    TextureMapping *textureMapping = mesh->getTextureMappings().at(textureIndex - 1); // -1 porque OBJ são 1-indexed
                    glTexCoord2f(textureMapping->getU(), textureMapping->getV());
                }
                
                // vertex
                int vertexIndex = verticesIndexes.at(i);
                Vertex *vertex = mesh->getVertices().at(vertexIndex - 1); // -1 porque OBJ são 1-indexed
                glVertex3d(vertex->getX(), vertex->getY(), vertex->getZ());
            }
            
            glEnd();
        }
    }
}
Пример #27
0
Vector2D Random::RandomUnitVector() { 
	float angle = TWO_PI * randomFloat(); 
	return Vector2D( cos(angle), sin(angle) ); 
}
Пример #28
0
void SpecialActions::update(SpecialActionsOutput& specialActionsOutput)
{
  if(!motionNetData.nodeArray)
  {
    specialActionsOutput.angles.fill(0);
    specialActionsOutput.stiffnessData.stiffnesses.fill(0);
    return;
  }

  float speedFactor = 1.0f;
  MODIFY("parameters:SpecialActions:speedFactor", speedFactor);
  if(theMotionSelection.specialActionMode != MotionSelection::deactive)
  {
    specialActionsOutput.isLeavingPossible = true;
    if(dataRepetitionCounter <= 0)
    {
      if(!wasActive)
      {
        //entered from external motion
        currentNode = 0;
        for(int i = 0; i < Joints::numOfJoints; ++i)
          lastRequest.angles[i] = theJointAngles.angles[i];
        lastSpecialAction = SpecialActionRequest::numOfSpecialActionIDs;
      }

      // this is need when a special actions gets executed directly after another without
      // switching to a different motion for interpolating the stiffness
      if(wasEndOfSpecialAction)
      {
        specialActionsOutput.stiffnessData.resetToDefault();
        if(!mirror)
          lastStiffnessRequest = currentStiffnessRequest;
        else
          lastStiffnessRequest.mirror(currentStiffnessRequest);
        currentStiffnessRequest.resetToDefault();
      }
      wasEndOfSpecialAction = false;
      // search next data, leave on transition to external motion
      if(!getNextData(theMotionSelection.specialActionRequest, specialActionsOutput))
      {
        wasActive = true;
        wasEndOfSpecialAction = true;
        specialActionsOutput.odometryOffset = Pose2f();
        return;
      }
    }
    else
    {
      dataRepetitionCounter -= int(theFrameInfo.cycleTime * 1000 * speedFactor);
      stiffnessInterpolationCounter -= int(theFrameInfo.cycleTime * 1000 * speedFactor);
    }

    //set current joint values
    calculateJointRequest(specialActionsOutput);

    //odometry update
    if(currentInfo.type == SpecialActionInfo::homogeneous || currentInfo.type == SpecialActionInfo::once)
      if(mirror)
        specialActionsOutput.odometryOffset = Pose2f(-currentInfo.odometryOffset.rotation, currentInfo.odometryOffset.translation.x(), -currentInfo.odometryOffset.translation.y());
      else
        specialActionsOutput.odometryOffset = currentInfo.odometryOffset;
    else
      specialActionsOutput.odometryOffset = Pose2f();
    if(currentInfo.type == SpecialActionInfo::once)
      currentInfo.type = SpecialActionInfo::none;

    //store value if current data line finished
    if(dataRepetitionCounter <= 0)
    {
      if(!mirror)
        lastRequest = currentRequest;
      else
        lastRequest.mirror(currentRequest);
    }
    specialActionsOutput.isLeavingPossible = false;
    if(deShakeMode)
      for(int i = Joints::lShoulderPitch; i <= Joints::rElbowRoll; ++i)
        if(randomFloat() < 0.25)
          specialActionsOutput.angles[i] = JointAngles::off;
  }
  wasActive = theMotionSelection.specialActionMode != MotionSelection::deactive;
}
Пример #29
0
void CBotGAValues :: addRnd()
{
	m_theValues.push_back(randomFloat(0,1));
}
Пример #30
0
float randomFloatMax(float max) {
  return max * randomFloat();
};