Ejemplo n.º 1
0
void CPlayers::RenderHook(
	const CNetObj_Character *pPrevChar,
	const CNetObj_Character *pPlayerChar,
	const CNetObj_PlayerInfo *pPrevInfo,
	const CNetObj_PlayerInfo *pPlayerInfo,
	int ClientID
	)
{
	CNetObj_Character Prev;
	CNetObj_Character Player;
	Prev = *pPrevChar;
	Player = *pPlayerChar;

	CTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID];

	float IntraTick = Client()->IntraGameTick();

	// set size
	RenderInfo.m_Size = 64.0f;

	// use preditect players if needed
	if(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK)
	{
		if(!m_pClient->m_Snap.m_pLocalCharacter ||
			(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))
		{
		}
		else
		{
			// apply predicted results
			m_pClient->m_PredictedChar.Write07(&Player);
			m_pClient->m_PredictedPrevChar.Write07(&Prev);
			IntraTick = Client()->PredIntraGameTick();
		}
	}

	vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick);

	// draw hook
	if (Prev.m_HookState>0 && Player.m_HookState>0)
	{
		vec2 Pos = Position;
		vec2 HookPos;

		if(pPlayerChar->m_HookedPlayer != -1)
		{
			if(m_pClient->m_LocalClientID != -1 && pPlayerChar->m_HookedPlayer == m_pClient->m_LocalClientID)
			{
				if(Client()->State() == IClient::STATE_DEMOPLAYBACK) // only use prediction if needed
					HookPos = vec2(m_pClient->m_LocalCharacterPos.x, m_pClient->m_LocalCharacterPos.y);
				else
					HookPos = mix(vec2(m_pClient->m_PredictedPrevChar.m_Pos.x, m_pClient->m_PredictedPrevChar.m_Pos.y),
						vec2(m_pClient->m_PredictedChar.m_Pos.x, m_pClient->m_PredictedChar.m_Pos.y), Client()->PredIntraGameTick());
			}
			else if(m_pClient->m_LocalClientID == ClientID)
			{
				HookPos = mix(vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_X,
					m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_Y),
					vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_X,
					m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_Y),
					Client()->IntraGameTick());
			}
			else
				HookPos = mix(vec2(pPrevChar->m_HookX, pPrevChar->m_HookY), vec2(pPlayerChar->m_HookX, pPlayerChar->m_HookY), Client()->IntraGameTick());
		}
		else
			HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick);

		//~ ModAPIGraphics()->DrawLine(tu::CAssetPath::Universe(tu::CAssetPath::TYPE_LINESTYLE, MODAPI_LINESTYLE_HOOK), Position, HookPos, 1.0f, 0.0f);
	}
}
Ejemplo n.º 2
0
void CCharacter::FireWeapon()
{
	if(m_ReloadTimer != 0)
		return;

/* INFECTION MODIFICATION START ***************************************/
	if(GetClass() == PLAYERCLASS_NONE)
		return;
/* INFECTION MODIFICATION END *****************************************/

	DoWeaponSwitch();
	vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));

	bool FullAuto = false;
	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE)
		FullAuto = true;


	// check if we gonna fire
	bool WillFire = false;
	if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)
		WillFire = true;

	if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo)
		WillFire = true;

	if(!WillFire)
		return;

	// check for ammo
	if(!m_aWeapons[m_ActiveWeapon].m_Ammo)
	{
		// 125ms is a magical limit of how fast a human can click
		m_ReloadTimer = 125 * Server()->TickSpeed() / 1000;
		if(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick())
		{
			GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
			m_LastNoAmmoSound = Server()->Tick();
		}
		return;
	}

	vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f;

	switch(m_ActiveWeapon)
	{
		case WEAPON_HAMMER:
		{
/* INFECTION MODIFICATION START ***************************************/
			if(GetClass() == PLAYERCLASS_ENGINEER)
			{
				if(m_pBarrier)
				{
					GameServer()->m_World.DestroyEntity(m_pBarrier);
					m_pBarrier = 0;
				}
					
				if(m_FirstShot)
				{
					m_FirstShot = false;
					m_FirstShotCoord = m_Pos;
				}
				else if(distance(m_FirstShotCoord, m_Pos) > 10.0)
				{
					m_FirstShot = true;
					
					CBarrier *pBarrier = new CBarrier(GameWorld(), m_FirstShotCoord, m_Pos, m_pPlayer->GetCID());
					m_pBarrier = pBarrier;
					
					GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
				}
			}
			else if(GetClass() == PLAYERCLASS_SOLDIER)
			{
				if(m_pBomb)
				{
					m_pBomb->Explode();
				}
				else
				{
					CBomb *pBomb = new CBomb(GameWorld(), ProjStartPos, m_pPlayer->GetCID());
					m_pBomb = pBomb;
					
					GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);
				}
					
			}
			else if(GetClass() == PLAYERCLASS_BOOMER)
			{
				Die(m_pPlayer->GetCID(), WEAPON_WORLD);
			}
			else
			{
/* INFECTION MODIFICATION END *****************************************/
				// reset objects Hit
				m_NumObjectsHit = 0;
				GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);

				CCharacter *apEnts[MAX_CLIENTS];
				int Hits = 0;
				int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts,
															MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);

				for (int i = 0; i < Num; ++i)
				{
					CCharacter *pTarget = apEnts[i];

					if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL))
						continue;

					// set his velocity to fast upward (for now)
					if(length(pTarget->m_Pos-ProjStartPos) > 0.0f)
						GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f);
					else
						GameServer()->CreateHammerHit(ProjStartPos);

					vec2 Dir;
					if (length(pTarget->m_Pos - m_Pos) > 0.0f)
						Dir = normalize(pTarget->m_Pos - m_Pos);
					else
						Dir = vec2(0.f, -1.f);
					
/* INFECTION MODIFICATION START ***************************************/
					if(IsInfected() && pTarget->IsInfected())
					{
						pTarget->IncreaseHealth(2);
						pTarget->IncreaseArmor(2);
					}
					else
					{
						pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage,
							m_pPlayer->GetCID(), m_ActiveWeapon);
					}
/* INFECTION MODIFICATION END *****************************************/
					Hits++;
				}

				// if we Hit anything, we have to wait for the reload
				if(Hits)
					m_ReloadTimer = Server()->TickSpeed()/3;
					
/* INFECTION MODIFICATION START ***************************************/
			}
/* INFECTION MODIFICATION END *****************************************/

		} break;

		case WEAPON_GUN:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
				1, 0, 0, -1, WEAPON_GUN);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);

			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
		} break;

		case WEAPON_SHOTGUN:
		{
			int ShotSpread = 2;

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(ShotSpread*2+1);

			for(int i = -ShotSpread; i <= ShotSpread; ++i)
			{
				float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};
				float a = GetAngle(Direction);
				a += Spreading[i+2];
				float v = 1-(absolute(i)/(float)ShotSpread);
				float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v);
				CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,
					m_pPlayer->GetCID(),
					ProjStartPos,
					vec2(cosf(a), sinf(a))*Speed,
					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
					1, 0, 0, -1, WEAPON_SHOTGUN);

				// pack the Projectile and send it to the client Directly
				CNetObj_Projectile p;
				pProj->FillInfo(&p);

				for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
					Msg.AddInt(((int *)&p)[i]);
			}

			Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
		} break;

		case WEAPON_GRENADE:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
				1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);
			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);
		} break;

		case WEAPON_RIFLE:
		{
			new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());
			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
		} break;

		case WEAPON_NINJA:
		{
			// reset Hit objects
			m_NumObjectsHit = 0;

			m_Ninja.m_ActivationDir = Direction;
			m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000;
			m_Ninja.m_OldVelAmount = length(m_Core.m_Vel);

			GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE);
		} break;

	}

	m_AttackTick = Server()->Tick();

	if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited
		m_aWeapons[m_ActiveWeapon].m_Ammo--;

	if(!m_ReloadTimer)
		m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
}
Ejemplo n.º 3
0
	template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> lerp(const detail::tvec4<T>& x, const detail::tvec4<T>& y, T a){return mix(x, y, a);}							//!< \brief Returns x * (1.0 - a) + y * a, i.e., the linear blend of x and y using the floating-point value a. The value for a is not restricted to the range [0, 1]. (From GLM_GTX_compatibility)
Ejemplo n.º 4
0
/*
 * hashlittle2: return 2 32-bit hash values
 *
 * This is identical to hashlittle(), except it returns two 32-bit hash
 * values instead of just one.  This is good enough for hash table
 * lookup with 2^^64 buckets, or if you want a second hash if you're not
 * happy with the first, or if you want a probably-unique 64-bit ID for
 * the key.  *pc is better mixed than *pb, so use *pc first.  If you want
 * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
 */
void hashlittle2( 
    const void *key,       /* the key to hash */
    size_t      length,    /* length of the key */
    uint32_t   *pc,        /* IN: primary initval, OUT: primary hash */
    uint32_t   *pb)        /* IN: secondary initval, OUT: secondary hash */
{
  uint32_t a,b,c;                                          /* internal state */
  union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */

  /* Set up the internal state */
  a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc;
  c += *pb;

  u.ptr = key;
  if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
    const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
#ifdef VALGRIND
    const uint8_t  *k8;
#endif

    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      b += k[1];
      c += k[2];
      mix(a,b,c);
      length -= 12;
      k += 3;
    }

    /*----------------------------- handle the last (probably partial) block */
    /* 
     * "k[2]&0xffffff" actually reads beyond the end of the string, but
     * then masks off the part it's not allowed to read.  Because the
     * string is aligned, the masked-off tail is in the same word as the
     * rest of the string.  Every machine with memory protection I've seen
     * does it on word boundaries, so is OK with this.  But VALGRIND will
     * still catch it and complain.  The masking trick does make the hash
     * noticably faster for short strings (like English words).
     */
#ifndef VALGRIND

    switch(length)
    {
      case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
      case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
      case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
      case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
      case 8 : b+=k[1]; a+=k[0]; break;
      case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
      case 6 : b+=k[1]&0xffff; a+=k[0]; break;
      case 5 : b+=k[1]&0xff; a+=k[0]; break;
      case 4 : a+=k[0]; break;
      case 3 : a+=k[0]&0xffffff; break;
      case 2 : a+=k[0]&0xffff; break;
      case 1 : a+=k[0]&0xff; break;
      case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
    }

#else /* make valgrind happy */

    k8 = (const uint8_t *)k;
    switch(length)
    {
      case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
      case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
      case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
      case 9 : c+=k8[8];                   /* fall through */
      case 8 : b+=k[1]; a+=k[0]; break;
      case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
      case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
      case 5 : b+=k8[4];                   /* fall through */
      case 4 : a+=k[0]; break;
      case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
      case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
      case 1 : a+=k8[0]; break;
      case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
    }

#endif /* !valgrind */

  } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
    const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
    const uint8_t  *k8;

    /*--------------- all but last block: aligned reads and different mixing */
    while (length > 12)
    {
      a += k[0] + (((uint32_t)k[1])<<16);
      b += k[2] + (((uint32_t)k[3])<<16);
      c += k[4] + (((uint32_t)k[5])<<16);
      mix(a,b,c);
      length -= 12;
      k += 6;
    }

    /*----------------------------- handle the last (probably partial) block */
    k8 = (const uint8_t *)k;
    switch(length)
    {
      case 12: c+=k[4]+(((uint32_t)k[5])<<16);
               b+=k[2]+(((uint32_t)k[3])<<16);
               a+=k[0]+(((uint32_t)k[1])<<16);
               break;
      case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
      case 10: c+=k[4];
               b+=k[2]+(((uint32_t)k[3])<<16);
               a+=k[0]+(((uint32_t)k[1])<<16);
               break;
      case 9 : c+=k8[8];                      /* fall through */
      case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
               a+=k[0]+(((uint32_t)k[1])<<16);
               break;
      case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
      case 6 : b+=k[2];
               a+=k[0]+(((uint32_t)k[1])<<16);
               break;
      case 5 : b+=k8[4];                      /* fall through */
      case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
               break;
      case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
      case 2 : a+=k[0];
               break;
      case 1 : a+=k8[0];
               break;
      case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
    }

  } else {                        /* need to read the key one byte at a time */
    const uint8_t *k = (const uint8_t *)key;

    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
    while (length > 12)
    {
      a += k[0];
      a += ((uint32_t)k[1])<<8;
      a += ((uint32_t)k[2])<<16;
      a += ((uint32_t)k[3])<<24;
      b += k[4];
      b += ((uint32_t)k[5])<<8;
      b += ((uint32_t)k[6])<<16;
      b += ((uint32_t)k[7])<<24;
      c += k[8];
      c += ((uint32_t)k[9])<<8;
      c += ((uint32_t)k[10])<<16;
      c += ((uint32_t)k[11])<<24;
      mix(a,b,c);
      length -= 12;
      k += 12;
    }

    /*-------------------------------- last block: affect all 32 bits of (c) */
    switch(length)                   /* all the case statements fall through */
    {
      case 12: c+=((uint32_t)k[11])<<24;
      case 11: c+=((uint32_t)k[10])<<16;
      case 10: c+=((uint32_t)k[9])<<8;
      case 9 : c+=k[8];
      case 8 : b+=((uint32_t)k[7])<<24;
      case 7 : b+=((uint32_t)k[6])<<16;
      case 6 : b+=((uint32_t)k[5])<<8;
      case 5 : b+=k[4];
      case 4 : a+=((uint32_t)k[3])<<24;
      case 3 : a+=((uint32_t)k[2])<<16;
      case 2 : a+=((uint32_t)k[1])<<8;
      case 1 : a+=k[0];
               break;
      case 0 : *pc=c; *pb=b; return;  /* zero length strings require no mixing */
    }
  }

  final(a,b,c);
Ejemplo n.º 5
0
void randomIsaac::init( uint32_t* seed, int length )
{
	uint32_t a, b, c, d, e, f, g, h;
	a = b = c = d = e = f = g = h = 0x9e3779b9;	// the golden ratio
	aa = bb = cc = 0;

	for ( int i = 0; i < poolSize; i++ ) {
		if ( i < length ) {
			this->randomPool[i] = seed[i];
		}
		else {
			this->randomPool[i] = 0;
		}
	}

	// scramble it
	for ( int i = 0; i < 4; i++ ) {
		mix( a, b, c, d, e, f, g, h );
	}

	// fill in mm[] with messy stuff
	for ( int i = 0; i < poolSize; i += 8 ) {
		a += this->randomPool[i + 0];
		b += this->randomPool[i + 1];
		c += this->randomPool[i + 2];
		d += this->randomPool[i + 3];
		e += this->randomPool[i + 4];
		f += this->randomPool[i + 5];
		g += this->randomPool[i + 6];
		h += this->randomPool[i + 7];

		mix( a, b, c, d, e, f, g, h );
		mm[i + 0] = a;
		mm[i + 1] = b;
		mm[i + 2] = c;
		mm[i + 3] = d;
		mm[i + 4] = e;
		mm[i + 5] = f;
		mm[i + 6] = g;
		mm[i + 7] = h;
	}

	// do a second pass to make all of the seed affect all of mm
	for ( int i = 0; i < poolSize; i += 8 ) {
		a += mm[i + 0];
		b += mm[i + 1];
		c += mm[i + 2];
		d += mm[i + 3];
		e += mm[i + 4];
		f += mm[i + 5];
		g += mm[i + 6];
		h += mm[i + 7];
		mix( a, b, c, d, e, f, g, h );
		mm[i + 0] = a;
		mm[i + 1] = b;
		mm[i + 2] = c;
		mm[i + 3] = d;
		mm[i + 4] = e;
		mm[i + 5] = f;
		mm[i + 6] = g;
		mm[i + 7] = h;
	}

	// fill in the first set of results
	this->isaac();
	// prepare to use the first set of results
	this->randomPoolCount = poolSize;
}
 void main()
{
    
    vec2 blurCoordinates[20];
    
    blurCoordinates[0] = textureCoordinate + vec2(0.0, -10.0) * imageStep;
    blurCoordinates[1] = textureCoordinate + vec2(5.0, -8.0) * imageStep;
    blurCoordinates[2] = textureCoordinate + vec2(8.0, -5.0) * imageStep;
    blurCoordinates[3] = textureCoordinate + vec2(10.0, 0.0) * imageStep;
    blurCoordinates[4] = textureCoordinate + vec2(8.0, 5.0) * imageStep;
    blurCoordinates[5] = textureCoordinate + vec2(5.0, 8.0) * imageStep;
    blurCoordinates[6] = textureCoordinate + vec2(0.0, 10.0) * imageStep;
    blurCoordinates[7] = textureCoordinate + vec2(-5.0, 8.0) * imageStep;
    blurCoordinates[8] = textureCoordinate + vec2(-8.0, 5.0) * imageStep;
    blurCoordinates[9] = textureCoordinate + vec2(-10.0, 0.0) * imageStep;
    blurCoordinates[10] = textureCoordinate + vec2(-8.0, -5.0) * imageStep;
    blurCoordinates[11] = textureCoordinate + vec2(-5.0, -8.0) * imageStep;
    blurCoordinates[12] = textureCoordinate + vec2(0.0, -6.0) * imageStep;
    blurCoordinates[13] = textureCoordinate + vec2(-4.0, -4.0) * imageStep;
    blurCoordinates[14] = textureCoordinate + vec2(-6.0, 0.0) * imageStep;
    blurCoordinates[15] = textureCoordinate + vec2(-4.0, 4.0) * imageStep;
    blurCoordinates[16] = textureCoordinate + vec2(0.0, 6.0) * imageStep;
    blurCoordinates[17] = textureCoordinate + vec2(4.0, 4.0) * imageStep;
    blurCoordinates[18] = textureCoordinate + vec2(6.0, 0.0) * imageStep;
    blurCoordinates[19] = textureCoordinate + vec2(4.0, -4.0) * imageStep;
    
    vec3 centralColor = texture2D(inputImageTexture, textureCoordinate).rgb;
    
    float sampleColor = centralColor.g * 24.0;
    
    sampleColor += texture2D(inputImageTexture, blurCoordinates[0]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[1]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[2]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[3]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[4]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[5]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[6]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[7]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[8]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[9]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[10]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[11]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[12]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[13]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[14]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[15]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[16]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[17]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[18]).g;
    sampleColor += texture2D(inputImageTexture, blurCoordinates[19]).g;
    
    sampleColor = sampleColor/44.0;
    
    float dis = centralColor.g - sampleColor + 0.5;
    
    if(dis <= 0.5)
    {
        dis = dis * dis * 2.0;
    }
    else
    {
        dis = 1.0 - ((1.0 - dis)*(1.0 - dis) * 2.0);
    }
    
    if(dis <= 0.5)
    {
        dis = dis * dis * 2.0;
    }
    else
    {
        dis = 1.0 - ((1.0 - dis)*(1.0 - dis) * 2.0);
    }
    
    if(dis <= 0.5)
    {
        dis = dis * dis * 2.0;
    }
    else
    {
        dis = 1.0 - ((1.0 - dis)*(1.0 - dis) * 2.0);
    }
    
    if(dis <= 0.5)
    {
        dis = dis * dis * 2.0;
    }
    else
    {
        dis = 1.0 - ((1.0 - dis)*(1.0 - dis) * 2.0);
    }
    
    if(dis <= 0.5)
    {
        dis = dis * dis * 2.0;
    }
    else
    {
        dis = 1.0 - ((1.0 - dis)*(1.0 - dis) * 2.0);
    }
    
    vec3 result = centralColor * 1.065 - dis * 0.065;
    
    float hue = dot(result, vec3(0.299,0.587,0.114)) - 0.3;
    
    hue = pow(clamp(hue, 0.0, 1.0), 0.3);
    
    result = centralColor * (1.0 - hue) + result * hue;
    result = (result - 0.8) * 1.06 + 0.8;
    
    result = pow(result, vec3(0.75));
    
    result = mix(centralColor, result, intensity);
    
    gl_FragColor = vec4(result, 1.0);
}
Ejemplo n.º 7
0
void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID)
{

	// get positions
	float Curvature = 0;
	float Speed = 0;
	if(pCurrent->m_Type == WEAPON_GRENADE)
	{
		Curvature = m_pClient->m_Tuning.m_GrenadeCurvature;
		Speed = m_pClient->m_Tuning.m_GrenadeSpeed;
	}
	else if(pCurrent->m_Type == WEAPON_SHOTGUN)
	{
		Curvature = m_pClient->m_Tuning.m_ShotgunCurvature;
		Speed = m_pClient->m_Tuning.m_ShotgunSpeed;
	}
	else if(pCurrent->m_Type == WEAPON_GUN)
	{
		Curvature = m_pClient->m_Tuning.m_GunCurvature;
		Speed = m_pClient->m_Tuning.m_GunSpeed;
	}

	float Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime();
	if(Ct < 0)
		return; // projectile havn't been shot yet
		
	vec2 StartPos(pCurrent->m_X, pCurrent->m_Y);
	vec2 StartVel(pCurrent->m_VelX/100.0f, pCurrent->m_VelY/100.0f);
	vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct);
	vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct-0.001f);


	Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
	Graphics()->QuadsBegin();
	
	RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Type, 0, NUM_WEAPONS-1)].m_pSpriteProj);
	vec2 Vel = Pos-PrevPos;
	//vec2 pos = mix(vec2(prev->x, prev->y), vec2(current->x, current->y), Client()->IntraGameTick());
	

	// add particle for this projectile
	if(pCurrent->m_Type == WEAPON_GRENADE)
	{
		m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1);
		m_pClient->m_pFlow->Add(Pos, Vel*1000*Client()->FrameTime(), 10.0f);
		
		if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
		{
			const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
			static float Time = 0;
			static float LastLocalTime = Client()->LocalTime();
		
			if(!pInfo->m_Paused)
				Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed;
			
			Graphics()->QuadsSetRotation(Time*pi*2*2 + ItemID);
			
			LastLocalTime = Client()->LocalTime();
		}
		else
			Graphics()->QuadsSetRotation(Client()->LocalTime()*pi*2*2 + ItemID);
	}
	else
	{
		m_pClient->m_pEffects->BulletTrail(Pos);
		m_pClient->m_pFlow->Add(Pos, Vel*1000*Client()->FrameTime(), 10.0f);

		if(length(Vel) > 0.00001f)
			Graphics()->QuadsSetRotation(GetAngle(Vel));
		else
			Graphics()->QuadsSetRotation(0);

	}

	IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 32, 32);
	Graphics()->QuadsDraw(&QuadItem, 1);

	//--- Antiping
	// Draw shadows of grenades
	bool LocalPlayerInGame = 
		m_pClient->m_aClients[m_pClient->m_Snap.m_LocalCid].m_Team != -1;

	if(g_Config.m_AntiPing && pCurrent->m_Type == WEAPON_GRENADE && LocalPlayerInGame)
	{
		// Calculate average prediction offset, because client_predtick() gets varial values :(((
		// Must be there is a normal way to realize it, but I'm too lazy to find it. ^)
		if (m_pClient->m_Average_Prediction_Offset == -1)
		{
			int Offset = Client()->PredGameTick() - Client()->GameTick();
			m_pClient->m_Prediction_Offset_Summ += Offset;
			m_pClient->m_Prediction_Offset_Count++;

			if (m_pClient->m_Prediction_Offset_Count >= 100)
			{
				m_pClient->m_Average_Prediction_Offset = 
					round((float)m_pClient->m_Prediction_Offset_Summ / m_pClient->m_Prediction_Offset_Count);
			}
		}		

		// Draw shadow only if grenade directed to local player
		CNetObj_CharacterCore& CurChar = m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_LocalCid].m_Cur;
		CNetObj_CharacterCore& PrevChar = m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_LocalCid].m_Prev;
		vec2 ServerPos = mix(vec2(PrevChar.m_X, PrevChar.m_Y), vec2(CurChar.m_X, CurChar.m_Y), Client()->IntraGameTick());

		float d1 = distance(Pos, ServerPos);
		float d2 = distance(PrevPos, ServerPos);
		if (d1 < 0) d1 *= -1;
		if (d2 < 0) d2 *= -1;
		bool GrenadeIsDirectedToLocalPlayer = d1 < d2;

		if (m_pClient->m_Average_Prediction_Offset != -1 && GrenadeIsDirectedToLocalPlayer)
		{
			int PredictedTick = Client()->PrevGameTick() + m_pClient->m_Average_Prediction_Offset;
			float PredictedCt = (PredictedTick - pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime();
		
			if (PredictedCt >= 0)
			{
				int shadow_type = WEAPON_GUN; // Pistol bullet sprite is used for marker of shadow. TODO: use something custom.
				RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(shadow_type, 0, NUM_WEAPONS-1)].m_pSpriteProj);
				
				vec2 PredictedPos = CalcPos(StartPos, StartVel, Curvature, Speed, PredictedCt);
				
				IGraphics::CQuadItem QuadItem(PredictedPos.x, PredictedPos.y, 32, 32);
				Graphics()->QuadsDraw(&QuadItem, 1);
			}
		}
	}
	//---

	Graphics()->QuadsSetRotation(0);
	Graphics()->QuadsEnd();
}
Ejemplo n.º 8
0
void TransferFunctionKey::Interpolate( TransferFunctionKey & keyA, TransferFunctionKey & keyB, double ratio )
{
    // Interpolate color function
    m_colorFunc->RemoveAllPoints();
    int keyASize = keyA.m_colorFunc->GetSize();
    int keyBSize = keyB.m_colorFunc->GetSize();
    vtkColorTransferFunction * colA = keyA.m_colorFunc.GetPointer();
    vtkColorTransferFunction * colB = keyB.m_colorFunc.GetPointer();
    for( int i = 0; i < keyASize || i < keyBSize; ++i )
    {
        if( i < keyASize && i < keyBSize )
        {
            double nodeA[6];
            colA->GetNodeValue( i, nodeA );
            double nodeB[6];
            colB->GetNodeValue( i, nodeB );
            double interpolated[6];
            for( int j = 0; j < 6; ++j )
            {
                interpolated[j] = mix( nodeA[j], nodeB[j], ratio );
            }
            m_colorFunc->AddRGBPoint( interpolated[0], interpolated[1], interpolated[2], interpolated[3], interpolated[4], interpolated[5] );
        }
        else if( i < keyASize )
        {
            double nodeA[6];
            colA->GetNodeValue( i, nodeA );
            m_colorFunc->AddRGBPoint( nodeA[0], nodeA[1], nodeA[2], nodeA[3], nodeA[4], nodeA[5] );
        }
        else
        {
            double nodeB[6];
            colB->GetNodeValue( i, nodeB );
            m_colorFunc->AddRGBPoint( nodeB[0], nodeB[1], nodeB[2], nodeB[3], nodeB[4], nodeB[5] );
        }
    }

    // Interpolate opacity function
    m_opacityFunc->RemoveAllPoints();
    keyASize = keyA.m_opacityFunc->GetSize();
    keyBSize = keyB.m_opacityFunc->GetSize();
    vtkPiecewiseFunction * opaA = keyA.m_opacityFunc;
    vtkPiecewiseFunction * opaB = keyB.m_opacityFunc;
    for( int i = 0; i < keyASize || i < keyBSize; ++i )
    {
        if( i < keyASize && i < keyBSize )
        {
            double nodeA[4];
            opaA->GetNodeValue( i, nodeA );
            double nodeB[4];
            opaB->GetNodeValue( i, nodeB );
            double interp[4];
            for( int j = 0; j < 4; ++j )
                interp[j] = mix( nodeA[j], nodeB[j], ratio );
            m_opacityFunc->AddPoint( interp[0], interp[1], interp[2], interp[3] );
        }
        else if( i < keyASize )
        {
            double nodeA[4];
            opaA->GetNodeValue( i, nodeA );
            m_opacityFunc->AddPoint( nodeA[0], nodeA[1], nodeA[2], nodeA[3] );
        }
        else
        {
            double nodeB[4];
            opaB->GetNodeValue( i, nodeB );
            m_opacityFunc->AddPoint( nodeB[0], nodeB[1], nodeB[2], nodeB[3] );
        }
    }
}
Ejemplo n.º 9
0
		void main()\
		{\
			gl_FragColor.rgb = (gl_Color *\
				mix( texture2D(first, gl_TexCoord[0].xy / (2 * zoomFactor)), texture2D(second, gl_TexCoord[0].xy ), amount )).rgb;\
			gl_FragColor.a = texture2D(mask, gl_TexCoord[0].xy).a;\
		}";
Ejemplo n.º 10
0
mxArray *get_polarity(Miscellaneous *miscell, PMap *predMap, Node *phi)
{
    /* Peer reviewed on 2013.07.22 by Dokhanchi, Adel */
    const char *fields[] = {"polarity", "index"};
    mxArray *tmp, *Array;
	/*mwSize *dims;*/
    mwSize dims;
	double *pr;
	int temp_pol = 0;
	Polarity *p;
	int i = 0,ii;
	int iii=0;								/* used for check the index for subformula*/
	int jjj=0;								/* length-1 of the subformula array */
	int *qi;
	int temp = 1;
#define subMax 200							/*	biggest number of iterations the subformula could store*/
	Node *subformula[subMax];				/* subformula array as a cross-reference for the phi*/

	/* Initialize some variables for BFS */
	queue q;
	queue *Q = &q;
	init_queue(Q);							/*initial the queue*/
	qi = &temp;
	/*----------------------------------*/

	p = (Polarity *)emalloc(sizeof(Polarity));
	p->polar = UNDEFINED_POLAR;
	tmp = mxCreateStructMatrix(1, 1, 2, fields);

	/*-----BFS for formula--------------*/
	jjj = BreadthFirstTraversal(Q,phi,subformula,qi);
		for(iii=1; iii<jjj; iii++)			/*	check the index for subformula*/
		{
			if(iii != subformula[iii]->index)
				mexErrMsgTxt("mx_dp_taliro: subformula not in right index!");
		}


	make_predicate_list(miscell, p);

/* predicate list*/
	pr = mxCalloc(miscell->dp_taliro_param.nPred, sizeof(double));
	/*dims = &(miscell->dp_taliro_param.nPred);*/
    dims = (mwSize)(miscell->dp_taliro_param.nPred);
	Array = mxCreateDoubleMatrix (1, dims, mxREAL);
	for(i = 0;i<miscell->dp_taliro_param.nPred;i++)
	{
		pr[i] = miscell->pList.pindex[i];
		if(pr[i] == -1)
		{
			pr[i] = 0;
		}
	}
	mxSetPr(Array,pr);
/* predicate list ends*/
	/* polarity calculation*/
	i = jjj;
	while(i>0)
	{
		switch (subformula[i]->ntyp)
		{
			case TRUE:
				subformula[i]->pol = UNDEFINED_POLAR;
				break;	
			case FALSE:
				subformula[i]->pol = UNDEFINED_POLAR;
				break;	
			case VALUE:
				subformula[i]->pol = UNDEFINED_POLAR;
				break;	
			case PREDICATE:
              		/* match predicate index*/
        		for(ii = 0; ii < miscell->dp_taliro_param.nPred; ii++)
                {
                    if(miscell->predMap[ii].str != NULL)
                    {
                        if(strcmp(subformula[i]->sym->name,predMap[ii].str)==0)
                        {
                            if(predMap[ii].parameter!=NULL){
                                subformula[i]->pol = POSITIVE_POLAR;   
                            }
                            else{
                   				subformula[i]->pol = UNDEFINED_POLAR;
                           }
                    	}
                    }
                }
				break;
			case NOT:
				subformula[i]->pol = flip(subformula[i]->lft->pol);
				/*p->polar = flip(p->polar);*/
				break;
			case AND:
				subformula[i]->pol = mix(subformula[i]->lft->pol, subformula[i]->rgt->pol);
				break;
			case OR:
				subformula[i]->pol = mix(subformula[i]->lft->pol, subformula[i]->rgt->pol);
				break;
			case NEXT:
				subformula[i]->pol = subformula[i]->lft->pol;
				break;
			case WEAKNEXT:
				subformula[i]->pol = subformula[i]->lft->pol;
				break;
			case ALWAYS:
				if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 0)
				{
					subformula[i]->pol = pos(subformula[i]->rgt->pol);
				}
				else if(subformula[i]->time.l_par == 0 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = neg(subformula[i]->rgt->pol);
				}
				else if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = MIXED_POLAR;
				}
				else
				{
					subformula[i]->pol = subformula[i]->rgt->pol;
				}
				break;
			case EVENTUALLY:
				if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 0)
				{
					subformula[i]->pol = neg(subformula[i]->rgt->pol);
				}
				else if(subformula[i]->time.l_par == 0 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = pos(subformula[i]->rgt->pol);
				}
				else if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = MIXED_POLAR;
				}
				else
				{
					subformula[i]->pol = subformula[i]->rgt->pol;
				}
				break;
			case U_OPER:
				if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 0)
				{
					temp_pol = NEGATIVE_POLAR;
					subformula[i]->pol = mix(temp_pol,mix(subformula[i]->lft->pol,subformula[i]->rgt->pol));
				}
				else if(subformula[i]->time.l_par == 0 && subformula[i]->time.u_par == 1)
				{
					temp_pol = POSITIVE_POLAR;
					subformula[i]->pol = mix(temp_pol,mix(subformula[i]->lft->pol,subformula[i]->rgt->pol));
				}
				else if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = MIXED_POLAR;
				}
				else
				{
					subformula[i]->pol = mix(subformula[i]->lft->pol,subformula[i]->rgt->pol);
				}
				break;
			case V_OPER:
				if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 0)
				{
/* 					temp_pol = POSITIVE_POLAR;
 					subformula[i]->pol = mix(temp_pol,mix(subformula[i]->lft->pol,subformula[i]->rgt->pol));*/
					temp_pol = NEGATIVE_POLAR;
					subformula[i]->pol = flip(mix(temp_pol,mix(flip(subformula[i]->lft->pol),flip(subformula[i]->rgt->pol))));
				}
				else if(subformula[i]->time.l_par == 0 && subformula[i]->time.u_par == 1)
				{
/* 					temp_pol = NEGATIVE_POLAR;
 					subformula[i]->pol = mix(temp_pol,mix(subformula[i]->lft->pol,subformula[i]->rgt->pol));*/
					temp_pol = POSITIVE_POLAR;
					subformula[i]->pol = flip(mix(temp_pol,mix(flip(subformula[i]->lft->pol),flip(subformula[i]->rgt->pol))));
				}
				else if(subformula[i]->time.l_par == 1 && subformula[i]->time.u_par == 1)
				{
					subformula[i]->pol = MIXED_POLAR;
				}
				else
				{
					subformula[i]->pol = mix(subformula[i]->lft->pol,subformula[i]->rgt->pol);
				}
				break;
			default:
				break;
		}
	i--;
	}
	/* polarity calculation ends*/


	mxSetField(tmp, 0, "polarity", mxCreateDoubleScalar(subformula[1]->pol));
	mxSetField(tmp, 0, "index", Array);

	return (tmp);
}
Ejemplo n.º 11
0
// main function of verifyBamID
int execute(int argc, char** argv) {
  printf("verifyBamID %s -- verify identity and purity of sequence data\n"
	 "(c) 2010-2014 Hyun Min Kang, Goo Jun, and Goncalo Abecasis\n\n", VERSION);

  VerifyBamIDArgs args;
  ParameterList pl;

  BEGIN_LONG_PARAMETERS(longParameters)
    LONG_PARAMETER_GROUP("Input Files")
    LONG_STRINGPARAMETER("vcf",&args.sVcfFile)
    LONG_STRINGPARAMETER("bam",&args.sBamFile)
    LONG_STRINGPARAMETER("subset",&args.sSubsetInds)
    LONG_STRINGPARAMETER("smID",&args.sSMID)

    LONG_PARAMETER_GROUP("VCF analysis options")
    LONG_DOUBLEPARAMETER("genoError",&args.genoError)
    LONG_DOUBLEPARAMETER("minAF",&args.minAF)
    LONG_DOUBLEPARAMETER("minCallRate",&args.minCallRate)

    LONG_PARAMETER_GROUP("Individuals to compare with chip data")
    EXCLUSIVE_PARAMETER("site",&args.bSiteOnly)
    EXCLUSIVE_PARAMETER("self",&args.bSelfOnly)
    EXCLUSIVE_PARAMETER("best",&args.bFindBest)

    LONG_PARAMETER_GROUP("Chip-free optimization options")
    EXCLUSIVE_PARAMETER("free-none",&args.bFreeNone)
    EXCLUSIVE_PARAMETER("free-mix",&args.bFreeMixOnly)
    EXCLUSIVE_PARAMETER("free-refBias",&args.bFreeRefBiasOnly)
    EXCLUSIVE_PARAMETER("free-full",&args.bFreeFull)

    LONG_PARAMETER_GROUP("With-chip optimization options")
    EXCLUSIVE_PARAMETER("chip-none",&args.bChipNone)
    EXCLUSIVE_PARAMETER("chip-mix",&args.bChipMixOnly)
    EXCLUSIVE_PARAMETER("chip-refBias",&args.bChipRefBiasOnly)
    EXCLUSIVE_PARAMETER("chip-full",&args.bChipFull)

    LONG_PARAMETER_GROUP("BAM analysis options")
    LONG_PARAMETER("ignoreRG",&args.bIgnoreRG)
    LONG_PARAMETER("ignoreOverlapPair",&args.bIgnoreOverlapPair)
    LONG_PARAMETER("noEOF",&args.bNoEOF)
    LONG_PARAMETER("precise",&args.bPrecise)
    LONG_INTPARAMETER("minMapQ",&args.minMapQ)
    LONG_INTPARAMETER("maxDepth",&args.maxDepth)
    LONG_INTPARAMETER("minQ",&args.minQ)
    LONG_INTPARAMETER("maxQ",&args.maxQ)
    LONG_DOUBLEPARAMETER("grid",&args.grid)

    LONG_PARAMETER_GROUP("Modeling Reference Bias")
    LONG_DOUBLEPARAMETER("refRef",&args.pRefRef)
    LONG_DOUBLEPARAMETER("refHet",&args.pRefHet)
    LONG_DOUBLEPARAMETER("refAlt",&args.pRefAlt)

    LONG_PARAMETER_GROUP("Output options")
    LONG_STRINGPARAMETER("out",&args.sOutFile)
    LONG_PARAMETER("verbose",&args.bVerbose)
    LONG_PHONEHOME(VERSION)
  END_LONG_PARAMETERS();

  pl.Add(new LongParameters("Available Options",longParameters));
  pl.Read(argc, argv);
  pl.Status();

  // check the validity of input files
  if ( args.sVcfFile.IsEmpty() ) {
    error("--vcf [vcf file] required");
  }

  if ( args.sBamFile.IsEmpty() ) {
    error("--bam [bam file] is required");
  }

  if ( args.sOutFile.IsEmpty() ) {
    error("--out [output prefix] is required");
  }
  Logger::gLogger = new Logger((args.sOutFile + ".log").c_str(), args.bVerbose);

  if ( ! ( args.bSiteOnly || args.bSelfOnly || args.bFindBest ) ) {
    warning("--self option was autotomatically turned on by default. Specify --best option if you wanted to check across all possible samples in the VCF");
    args.bSelfOnly = true;
  }

  if ( ( args.maxDepth > 20 ) && ( !args.bPrecise ) ) {
    warning("--precise option is not turned on at --maxDepth %d : may be prone to precision errors",args.maxDepth);
  }

  if ( ( args.bChipRefBiasOnly ) && ( !args.bSelfOnly ) ) {
    error("--self must be set for --chip-refBias to work. Skipping..");
  }

  // check timestamp
  time_t t;
  time(&t);
  Logger::gLogger->writeLog("Analysis started on %s",ctime(&t));

  // load arguments
  VerifyBamID vbid(&args);

  // load input VCF and BAM files
  Logger::gLogger->writeLog("Opening Input Files");
  vbid.loadFiles(args.sBamFile.c_str(), args.sVcfFile.c_str());

  // Check which genotype-free method is used
  if ( args.bFreeNone ) {  // if no genotype-free mode is tested. skip it
    // do nothing for genotype-free estimation
    Logger::gLogger->writeLog("Skipping chip-free estimation of sample mixture");
  }
  else if ( args.bFreeMixOnly ) { // only mixture is estimated.
    // genotype-free method
    Logger::gLogger->writeLog("Performing chip-free estimation of sample mixture at fixed reference bias parameters (%lf, %lf, %lf)",args.pRefRef,args.pRefHet,args.pRefAlt);

    // scan across multiple readgroups
    for(int rg=-1; rg < vbid.nRGs - (int)args.bIgnoreRG; ++rg) {
      VerifyBamID::mixLLK mix(&vbid);
      mix.OptimizeLLK(rg);
      Logger::gLogger->writeLog("Optimal per-sample fMix = %lf, LLK0 = %lf, LLK1 = %lf\n",mix.fMix,mix.llk0,mix.llk1);
      vbid.mixOut.llk0s[rg+1] = mix.llk0;
      vbid.mixOut.llk1s[rg+1] = mix.llk1;
      vbid.mixOut.fMixs[rg+1] = mix.fMix;
    }

    //vbid.mixRefHet = 0.5;
    //vbid.mixRefAlt = 0.00;
  }
  else if ( args.bFreeRefBiasOnly ) {
    Logger::gLogger->writeLog("Performing chip-free estimation of reference-bias without sample mixture");
    for(int rg=-1; rg < vbid.nRGs - (int)args.bIgnoreRG; ++rg) {
      VerifyBamID::refBiasMixLLKFunc myFunc(&vbid, rg);
      AmoebaMinimizer myMinimizer;
      Vector startingPoint(2);
      startingPoint[0] = 0;      // pRefHet = 0.5
      startingPoint[1] = -4.595; // pRefAlt = 0.01
      myMinimizer.func = &myFunc;
      myMinimizer.Reset(2);
      myMinimizer.point = startingPoint;
      myMinimizer.Minimize(1e-6);
      double pRefHet = VerifyBamID::invLogit(myMinimizer.point[0]);
      double pRefAlt = VerifyBamID::invLogit(myMinimizer.point[1]);
      Logger::gLogger->writeLog("Reference Bias Estimated as ( Pr[refBase|HET] = %lf, Pr[refBase|ALT] = %lf) with LLK = %lf at readGroup %d",pRefHet,pRefAlt,myMinimizer.fmin,rg);
      //vbid.setRefBiasParams(1.0, pRefHet, pRefAlt);

      vbid.mixOut.llk0s[rg+1] = myFunc.llk0;
      vbid.mixOut.llk1s[rg+1] = myFunc.llk1;
      vbid.mixOut.refHets[rg+1] = myFunc.pRefHet;
      vbid.mixOut.refAlts[rg+1] = myFunc.pRefAlt;
    }
  }
  else if ( args.bFreeFull ) {
    Logger::gLogger->writeLog("Performing chip-free estimation of reference-bias and sample mixture together");
    for(int rg = -1; rg < vbid.nRGs - args.bIgnoreRG; ++rg) {
      VerifyBamID::fullMixLLKFunc myFunc(&vbid, rg);
      AmoebaMinimizer myMinimizer;
      Vector startingPoint(3);
      startingPoint[0] = -3.91;  // start with fMix = 0.01
      startingPoint[1] = 0;      // pRefHet = 0.5
      startingPoint[2] = -4.595; // pRefAlt = 0.01
      myMinimizer.func = &myFunc;
      myMinimizer.Reset(3);
      myMinimizer.point = startingPoint;
      myMinimizer.Minimize(1e-6);
      double fMix = VerifyBamID::invLogit(myMinimizer.point[0]);
      if ( fMix > 0.5 ) 
	fMix = 1.-fMix;
      double pRefHet = VerifyBamID::invLogit(myMinimizer.point[1]);
      double pRefAlt = VerifyBamID::invLogit(myMinimizer.point[2]);
      Logger::gLogger->writeLog("Optimal per-sample fMix = %lf\n",fMix);
      Logger::gLogger->writeLog("Reference Bias Estimated as ( Pr[refBase|HET] = %lf, Pr[refBase|ALT] = %lf) with LLK = %lf",pRefHet,pRefAlt,myMinimizer.fmin);
      //vbid.setRefBiasParams(1.0, pRefHet, pRefAlt);

      vbid.mixOut.llk0s[rg+1] = myFunc.llk0;
      vbid.mixOut.llk1s[rg+1] = myFunc.llk1;
      vbid.mixOut.fMixs[rg+1] = myFunc.fMix;
      vbid.mixOut.refHets[rg+1] = myFunc.pRefHet;
      vbid.mixOut.refAlts[rg+1] = myFunc.pRefAlt;
    }
  }
  Logger::gLogger->writeLog("calculating depth distribution");  
  vbid.calculateDepthDistribution(args.maxDepth, vbid.mixOut);

  Logger::gLogger->writeLog("finished calculating depth distribution");  

  std::vector<int> bestInds(vbid.nRGs+1,-1);
  std::vector<int> selfInds(vbid.nRGs+1,-1);

  if ( args.bChipNone ) {
    // do nothing
    Logger::gLogger->writeLog("Skipping with-chip estimation of sample mixture");
  }
  else if ( args.bChipMixOnly ) {
    Logger::gLogger->writeLog("Performing with-chip estimation of sample mixture at fixed reference bias parameter (%lf, %lf, %lf)",args.pRefRef,args.pRefHet,args.pRefAlt);
    
    for(int rg=-1; rg < (vbid.nRGs - (int)args.bIgnoreRG); ++rg) {
      double maxIBD = -1;
      VerifyBamID::ibdLLK ibd(&vbid);
      for(int i=0; i < (int)vbid.pGenotypes->indids.size(); ++i) {
	double fIBD = ibd.OptimizeLLK(i, rg);
	Logger::gLogger->writeLog("Comparing with individual %s.. Optimal fIBD = %lf, LLK0 = %lf, LLK1 = %lf for readgroup %d",vbid.pGenotypes->indids[i].c_str(),fIBD, ibd.llk0, ibd.llk1, rg);
	if ( maxIBD < fIBD ) {
	  bestInds[rg+1] = i;
	  vbid.bestOut.llk0s[rg+1] = ibd.llk0;
	  vbid.bestOut.llk1s[rg+1] = ibd.llk1;
	  vbid.bestOut.fMixs[rg+1] = 1-ibd.fIBD;
	  maxIBD = ibd.fIBD;
	}

	if ( ( (rg < 0) && (vbid.pPile->sBamSMID == vbid.pGenotypes->indids[i] ) ) || ( ( rg >= 0 ) && ( vbid.pPile->vsSMIDs[rg] == vbid.pGenotypes->indids[i]) ) ) {
	  selfInds[rg+1] = i;
	  vbid.selfOut.llk0s[rg+1] = ibd.llk0;
	  vbid.selfOut.llk1s[rg+1] = ibd.llk1;
	  vbid.selfOut.fMixs[rg+1] = 1-ibd.fIBD;
	}
      }

      if ( bestInds[rg+1] >= 0 ) {
	Logger::gLogger->writeLog("Best Matching Individual is %s with IBD = %lf",vbid.pGenotypes->indids[bestInds[rg+1]].c_str(),maxIBD);
	vbid.calculateDepthByGenotype(bestInds[rg+1],rg,vbid.bestOut);
      }

      if ( selfInds[rg+1] >= 0 ) {
	Logger::gLogger->writeLog("Self Individual is %s with IBD = %lf",vbid.pGenotypes->indids[selfInds[rg+1]].c_str(),vbid.selfOut.fMixs[rg+1]);
	vbid.calculateDepthByGenotype(selfInds[rg+1],rg,vbid.selfOut);
      }
    }
  }
  else if ( args.bChipRefBiasOnly ) {
    Logger::gLogger->writeLog("Performing with-chip estimation of reference-bias without sample mixture");
    if ( args.bSelfOnly ) {
      for(int rg=-1; rg < (vbid.nRGs - (int)args.bIgnoreRG); ++rg) {
	VerifyBamID::refBiasIbdLLKFunc myFunc(&vbid, rg);
	AmoebaMinimizer myMinimizer;
	Vector startingPoint(2);
	startingPoint[0] = 0;      // pRefHet = 0.5
	startingPoint[1] = -4.595; // pRefAlt = 0.01
	myMinimizer.func = &myFunc;
	myMinimizer.Reset(2);
	myMinimizer.point = startingPoint;
	myMinimizer.Minimize(1e-6);
	double pRefHet = VerifyBamID::invLogit(myMinimizer.point[0]);
	double pRefAlt = VerifyBamID::invLogit(myMinimizer.point[1]);
	Logger::gLogger->writeLog("Reference Bias Estimated as ( Pr[refBase|HET] = %lf, Pr[refBase|ALT] = %lf) with LLK = %lf",pRefHet,pRefAlt,myMinimizer.fmin);
	//vbid.setRefBiasParams(1.0, pRefHet, pRefAlt);

	vbid.selfOut.llk0s[rg+1] = myFunc.llk0;
	vbid.selfOut.llk1s[rg+1] = myFunc.llk1;
	vbid.selfOut.refHets[rg+1] = myFunc.pRefHet;
	vbid.selfOut.refAlts[rg+1] = myFunc.pRefAlt;
	vbid.calculateDepthByGenotype(0,rg,vbid.selfOut);
      }
    }
    else {
      Logger::gLogger->warning("--self must be set for --chip-refBias to work. Skipping..");
    }
  }
  else if ( args.bChipFull ) {
    Logger::gLogger->writeLog("Performing with-chip estimation of reference-bias and sample mixture together");
    for(int rg=-1; rg < (vbid.nRGs - (int)args.bIgnoreRG); ++rg) {
      double maxIBD = -1;

      for(int i=0; i < (int)vbid.pGenotypes->indids.size(); ++i) {
	VerifyBamID::fullIbdLLKFunc myFunc(&vbid,i,rg);
	AmoebaMinimizer myMinimizer;
	Vector startingPoint(3);
	startingPoint[0] = 3.91;  // start with fIBD = 0.99
	startingPoint[1] = 0;      // pRefHet = 0.5
	startingPoint[2] = -4.595; // pRefAlt = 0.01
	myMinimizer.func = &myFunc;

	myFunc.indIdx = i;
	myMinimizer.Reset(3);
	myMinimizer.point = startingPoint;
	myMinimizer.Minimize(1e-6);
	double fIBD = VerifyBamID::invLogit(myMinimizer.point[0]);
	double pRefHet = VerifyBamID::invLogit(myMinimizer.point[1]);
	double pRefAlt = VerifyBamID::invLogit(myMinimizer.point[2]);

	Logger::gLogger->writeLog("Comparing with individual %s.. Optimal fIBD = %lf, LLK0 = %lf, LLK1 = %lf for readgroup %d",vbid.pGenotypes->indids[i].c_str(), fIBD, myFunc.llk0, myFunc.llk1, rg);
	//Logger::gLogger->writeLog("Optimal per-sample fIBD = %lf, ",fIBD);
	Logger::gLogger->writeLog("Reference Bias Estimated as ( Pr[refBase|HET] = %lf, Pr[refBase|ALT] = %lf ) with LLK = %lf",pRefHet,pRefAlt,myMinimizer.fmin);
	if ( maxIBD < fIBD ) {
	  bestInds[rg+1] = i;
	  maxIBD = fIBD;
	  vbid.bestOut.llk0s[rg+1] = myFunc.llk0;
	  vbid.bestOut.llk1s[rg+1] = myFunc.llk1;
	  vbid.bestOut.fMixs[rg+1] = 1.-myFunc.fIBD;
	  vbid.bestOut.refHets[rg+1] = myFunc.pRefHet;
	  vbid.bestOut.refAlts[rg+1] = myFunc.pRefAlt;
	}

	if ( ( (rg < 0) && (vbid.pPile->sBamSMID == vbid.pGenotypes->indids[i] ) ) || ( ( rg >= 0 ) && ( vbid.pPile->vsSMIDs[rg] == vbid.pGenotypes->indids[i]) ) ) {
	  selfInds[rg+1] = i;
	  vbid.selfOut.llk0s[rg+1] = myFunc.llk0;
	  vbid.selfOut.llk1s[rg+1] = myFunc.llk1;
	  vbid.selfOut.fMixs[rg+1] = 1.-myFunc.fIBD;
	  vbid.selfOut.refHets[rg+1] = myFunc.pRefHet;
	  vbid.selfOut.refAlts[rg+1] = myFunc.pRefAlt;
	  vbid.calculateDepthByGenotype(i, rg, vbid.selfOut);
	}
      }
      //vbid.setRefBiasParams(1.0, pRefHet, pRefAlt);
      if ( bestInds[rg+1] >= 0 ) {
	Logger::gLogger->writeLog("Best Matching Individual is %s with IBD = %lf",vbid.pGenotypes->indids[bestInds[rg+1]].c_str(),maxIBD);
	vbid.calculateDepthByGenotype(bestInds[rg+1], rg, vbid.bestOut);
      }

      if ( selfInds[rg+1] >= 0 ) {
	Logger::gLogger->writeLog("Self Individual is %s with IBD = %lf",vbid.pGenotypes->indids[selfInds[rg+1]].c_str(),vbid.selfOut.fMixs[rg+1]);
	vbid.calculateDepthByGenotype(selfInds[rg+1],rg,vbid.selfOut);
      }
    }
  }

  // PRINT OUTPUT FILE - ".selfSM"
  // [SEQ_ID]  : SAMPLE ID in the sequence file
  // [CHIP_ID] : SAMPLE ID in the chip file (NA if not available)
  // [#SNPS] : Number of markers evaluated
  // [#READS]   : Number of reads evaluated
  // [AVG_DP]   : Mean depth
  // [FREEMIX]  : Chip-free estimated alpha (% MIX in 0-1 scale), NA if unavailable
  // [FREELK1]  : Chip-free log-likelihood at estimated alpha
  // [FREELK0]  : Chip-free log-likelihood at 0% contamination
  // [CHIPIBD]  : With-chip estimated alpha (% MIX in 0-1 scale)
  // [CHIPLK1]  : With-chip log-likelihood at estimated alpha
  // [CHIPLK0]  : With-chip log-likelihood at 0% contamination
  // [DPREF]    : Depth at reference site in the chip
  // [RDPHET]   : Relative depth at HET site in the chip
  // [RDPALT]   : Relative depth at HOMALT site in the chip
  // [FREE_RF]  : Pr(Ref|Ref) site estimated without chip data
  // [FREE_RH]  : Pr(Ref|Het) site estimated without chip data
  // [FREE_RA]  : Pr(Ref|Alt) site estimated without chip data
  // [CHIP_RF]  : Pr(Ref|Ref) site estimated with chip data
  // [CHIP_RH]  : Pr(Ref|Het) site estimated with chip data
  // [CHIP_RA]  : Pr(Ref|Alt) site estimated with chip data
  // [DPREF]    : Depth at reference alleles
  // [RDPHET]   : Relative depth at heterozygous alleles
  // [RDPALT]   : Relative depth at hom-alt alleles

  String selfSMFN = args.sOutFile + ".selfSM";
  String bestSMFN = args.sOutFile + ".bestSM";
  String selfRGFN = args.sOutFile + ".selfRG";
  String bestRGFN = args.sOutFile + ".bestRG";
  String dpSMFN = args.sOutFile + ".depthSM";
  String dpRGFN = args.sOutFile + ".depthRG";

  IFILE selfSMF = ifopen(selfSMFN,"wb");
  IFILE bestSMF = (args.bFindBest ? ifopen(bestSMFN,"wb") : NULL);
  IFILE selfRGF = (args.bIgnoreRG ? NULL : ifopen(selfRGFN,"wb"));
  IFILE bestRGF = (args.bFindBest && !args.bIgnoreRG) ? ifopen(bestRGFN,"wb") : NULL;

  IFILE dpSMF = ifopen(dpSMFN,"wb");
  IFILE dpRGF = (args.bIgnoreRG ? NULL : ifopen(dpRGFN,"wb"));
  if ( selfSMF == NULL ) {
    Logger::gLogger->error("Cannot write to %s",selfSMF);
  }
  if ( args.bFindBest && ( bestSMF == NULL ) ) {
    Logger::gLogger->error("Cannot write to %s",bestSMF);
  }
  if ( dpSMF == NULL ) {
    Logger::gLogger->error("Cannot write to %s",dpSMF);
  }

  ifprintf(dpSMF,"#RG\tDEPTH\t#SNPs\t%%SNPs\t%%CUMUL\n");
  int nCumMarkers = 0;
  for(int i=args.maxDepth; i >= 0; --i) {
    nCumMarkers += vbid.mixOut.depths[i];
    ifprintf(dpSMF,"ALL\t%d\t%d\t%.5lf\t%.5lf\n",i, vbid.mixOut.depths[i],(double) vbid.mixOut.depths[i]/(double)vbid.nMarkers,(double)nCumMarkers/(double)vbid.nMarkers);
  }
  ifclose(dpSMF);


  if ( dpRGF != NULL ) {
    ifprintf(dpRGF,"#RG\tDEPTH\t#SNPs\t%%SNPs\t%%CUMUL\n");
    for(int rg=0; rg < (vbid.nRGs - (int)args.bIgnoreRG); ++rg) {
      const char* rgID = vbid.pPile->vsRGIDs[rg].c_str();

      int nMarkers = 0;
      for(int i=args.maxDepth; i >= 0; --i) {
	nMarkers += vbid.mixOut.depths[(rg+1)*(args.maxDepth+1) + i];
      }

      nCumMarkers = 0;
      for(int i=args.maxDepth; i >= 0; --i) {
	int d = vbid.mixOut.depths[(rg+1)*(args.maxDepth+1) + i];
	nCumMarkers += d;
	ifprintf(dpRGF,"%s\t%d\t%d\t%.5lf\t%.5lf\n",rgID,i,d,(double)d/(double)vbid.nMarkers,(double)nCumMarkers/(double)nMarkers);
      }
    }
    ifclose(dpRGF);
  }

  const char* headers[] = {"#SEQ_ID","RG","CHIP_ID","#SNPS","#READS","AVG_DP","FREEMIX","FREELK1","FREELK0","FREE_RH","FREE_RA","CHIPMIX","CHIPLK1","CHIPLK0","CHIP_RH","CHIP_RA","DPREF","RDPHET","RDPALT"};
  int nheaders = sizeof(headers)/sizeof(headers[0]);

  for(int i=0; i < nheaders; ++i) { ifprintf(selfSMF,"%s%s",i>0 ? "\t" : "",headers[i]); }
  ifprintf(selfSMF,"\n");
  ifprintf(selfSMF,"%s\tALL",vbid.pPile->sBamSMID.c_str());
  ifprintf(selfSMF,"\t%s",selfInds[0] >= 0 ? vbid.pGenotypes->indids[selfInds[0]].c_str() : "NA");
  ifprintf(selfSMF,"\t%d\t%d\t%.2lf",vbid.nMarkers,vbid.mixOut.numReads[0],(double)vbid.mixOut.numReads[0]/(double)vbid.nMarkers);
  if ( args.bFreeNone ) { ifprintf(selfSMF,"\tNA\tNA\tNA\tNA\tNA"); }
  else if ( args.bFreeMixOnly ) { ifprintf(selfSMF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA",vbid.mixOut.fMixs[0],vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0]); }
  else if ( args.bFreeRefBiasOnly ) { ifprintf(selfSMF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0],vbid.mixOut.refHets[0],vbid.mixOut.refAlts[0]); }
  else if ( args.bFreeFull ) { ifprintf(selfSMF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.fMixs[0],vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0],vbid.mixOut.refHets[0],vbid.mixOut.refAlts[0]); }
  else { error("Invalid option in handling bFree"); }

  if ( args.bChipNone || bestInds[0] < 0 ) { ifprintf(selfSMF,"\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA"); }
  else if ( args.bChipMixOnly ) { ifprintf(selfSMF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA\t%.3lf\t%.4lf\t%.4lf",vbid.selfOut.fMixs[0],vbid.selfOut.llk1s[0],vbid.selfOut.llk0s[0],(double)vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[1], (double)vbid.selfOut.numReads[2]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[2], (double)vbid.selfOut.numReads[3]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[3]); }
  else if ( args.bChipMixOnly ) { ifprintf(selfSMF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf",vbid.selfOut.llk1s[0], vbid.selfOut.llk0s[0], vbid.selfOut.refHets[0], vbid.selfOut.refAlts[0], (double)vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[1], (double)vbid.selfOut.numReads[2]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[2], (double)vbid.selfOut.numReads[3]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[3]); }
  else if ( args.bChipFull ) { ifprintf(selfSMF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf", vbid.selfOut.fMixs[0], vbid.selfOut.llk1s[0], vbid.selfOut.llk0s[0], vbid.selfOut.refHets[0], vbid.selfOut.refAlts[0], (double)vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[1], (double)vbid.selfOut.numReads[2]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[2], (double)vbid.selfOut.numReads[3]*vbid.selfOut.numGenos[1]/vbid.selfOut.numReads[1]/vbid.selfOut.numGenos[3]); }
  else { error("Invalid option in handling bChip"); }
  ifprintf(selfSMF,"\n");
  ifclose(selfSMF);

  if ( bestSMF != NULL ) {
    for(int i=0; i < nheaders; ++i) { ifprintf(bestSMF,"%s%s",i>0 ? "\t" : "",headers[i]); }
    ifprintf(bestSMF,"\n");
    ifprintf(bestSMF,"%s\tALL",vbid.pPile->sBamSMID.c_str());
    ifprintf(bestSMF,"\t%s",bestInds[0] >= 0 ? vbid.pGenotypes->indids[bestInds[0]].c_str() : "NA");
    ifprintf(bestSMF,"\t%d\t%d\t%.2lf",vbid.nMarkers,vbid.mixOut.numReads[0],(double)vbid.mixOut.numReads[0]/(double)vbid.nMarkers);
    if ( args.bFreeNone ) { ifprintf(bestSMF,"\tNA\tNA\tNA\tNA\tNA"); }
    else if ( args.bFreeMixOnly ) { ifprintf(bestSMF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA",vbid.mixOut.fMixs[0],vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0]); }
    else if ( args.bFreeRefBiasOnly ) { ifprintf(bestSMF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0],vbid.mixOut.refHets[0],vbid.mixOut.refAlts[0]); }
    else if ( args.bFreeFull ) { ifprintf(bestSMF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.fMixs[0],vbid.mixOut.llk1s[0],vbid.mixOut.llk0s[0],vbid.mixOut.refHets[0],vbid.mixOut.refAlts[0]); }
    else { error("Invalid option in handling bFree"); }
    
    if ( args.bChipNone || bestInds[0] < 0 ) { ifprintf(bestSMF,"\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA"); }
    else if ( args.bChipMixOnly ) { ifprintf(bestSMF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA\t%.3lf\t%.4lf\t%.4lf",vbid.bestOut.fMixs[0],vbid.bestOut.llk1s[0],vbid.bestOut.llk0s[0],(double)vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[1], (double)vbid.bestOut.numReads[2]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[2], (double)vbid.bestOut.numReads[3]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[3]); }
    else if ( args.bChipMixOnly ) { ifprintf(bestSMF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf",vbid.bestOut.llk1s[0], vbid.bestOut.llk0s[0], vbid.bestOut.refHets[0], vbid.bestOut.refAlts[0], (double)vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[1], (double)vbid.bestOut.numReads[2]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[2], (double)vbid.bestOut.numReads[3]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[3]); }
    else if ( args.bChipFull ) { ifprintf(bestSMF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf", vbid.bestOut.fMixs[0], vbid.bestOut.llk1s[0], vbid.bestOut.llk0s[0], vbid.bestOut.refHets[0], vbid.bestOut.refAlts[0], (double)vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[1], (double)vbid.bestOut.numReads[2]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[2], (double)vbid.bestOut.numReads[3]*vbid.bestOut.numGenos[1]/vbid.bestOut.numReads[1]/vbid.bestOut.numGenos[3]); }
    else { error("Invalid option in handling bChip"); }
    ifprintf(bestSMF,"\n");
    ifclose(bestSMF);
  }

  if ( selfRGF != NULL ) {
    for(int i=0; i < nheaders; ++i) { ifprintf(selfRGF,"%s%s",i>0 ? "\t" : "",headers[i]); }
    ifprintf(selfRGF,"\n");
    for(int rg=0; rg < vbid.nRGs; ++rg) {
      ifprintf(selfRGF,"%s\t%s",vbid.pPile->sBamSMID.c_str(),vbid.pPile->vsRGIDs[rg].c_str());
      ifprintf(selfRGF,"\t%s",bestInds[rg] >= 0 ? vbid.pGenotypes->indids[bestInds[rg]].c_str() : "NA");
      ifprintf(selfRGF,"\t%d\t%d\t%.2lf",vbid.nMarkers,vbid.mixOut.numReads[(rg+1)*4],(double)vbid.mixOut.numReads[(rg+1)*4]/(double)vbid.mixOut.numGenos[(rg+1)*4]);
      if ( args.bFreeNone ) { ifprintf(selfRGF,"\tNA\tNA\tNA\tNA\tNA"); }
      else if ( args.bFreeMixOnly ) { ifprintf(selfRGF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA",vbid.mixOut.fMixs[rg+1],vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1]); }
      else if ( args.bFreeRefBiasOnly ) { ifprintf(selfRGF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1],vbid.mixOut.refHets[rg+1],vbid.mixOut.refAlts[rg+1]); }
      else if ( args.bFreeFull ) { ifprintf(selfRGF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.fMixs[rg+1],vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1],vbid.mixOut.refHets[rg+1],vbid.mixOut.refAlts[rg+1]); }
      else { error("Invalid option in handling bFree"); }
      
      if ( args.bChipNone || bestInds[0] < 0 ) { ifprintf(selfRGF,"\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA"); }
      else if ( args.bChipMixOnly ) { ifprintf(selfRGF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA\t%.3lf\t%.4lf\t%.4lf",vbid.selfOut.fMixs[rg+1], vbid.selfOut.llk1s[rg+1], vbid.selfOut.llk0s[rg+1], (double)vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+1], (double)vbid.selfOut.numReads[(rg+1)*4+2]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+2], (double)vbid.selfOut.numReads[(rg+1)*4+3]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+3]); }
      else if ( args.bChipMixOnly ) { ifprintf(selfRGF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf",vbid.selfOut.llk1s[rg+1], vbid.selfOut.llk0s[rg+1], vbid.selfOut.refHets[rg+1], vbid.selfOut.refAlts[rg+1], (double)vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+1], (double)vbid.selfOut.numReads[(rg+1)*4+2]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4]/vbid.selfOut.numGenos[(rg+1)*4+2], (double)vbid.selfOut.numReads[(rg+1)*4+3]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+3]); }
      else if ( args.bChipFull ) { ifprintf(selfRGF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf", vbid.selfOut.fMixs[rg+1], vbid.selfOut.llk1s[rg+1], vbid.selfOut.llk0s[rg+1], vbid.selfOut.refHets[rg+1], vbid.selfOut.refAlts[rg+1], (double)vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+1], (double)vbid.selfOut.numReads[(rg+1)*4+2]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+2], (double)vbid.selfOut.numReads[(rg+1)*4+3]*vbid.selfOut.numGenos[(rg+1)*4+1]/vbid.selfOut.numReads[(rg+1)*4+1]/vbid.selfOut.numGenos[(rg+1)*4+3]); }
      else { error("Invalid option in handling bChip"); }
      ifprintf(selfRGF,"\n");
    }
    ifclose(selfRGF);
  }

  if ( bestRGF != NULL ) {
    for(int i=0; i < nheaders; ++i) { ifprintf(bestRGF,"%s%s",i>0 ? "\t" : "",headers[i]); }
    ifprintf(bestRGF,"\n");
    for(int rg=0; rg < vbid.nRGs; ++rg) {
      ifprintf(bestRGF,"%s\t%s",vbid.pPile->sBamSMID.c_str(),vbid.pPile->vsRGIDs[rg].c_str());
      ifprintf(bestRGF,"\t%s",bestInds[rg] >= 0 ? vbid.pGenotypes->indids[bestInds[rg]].c_str() : "NA");
      ifprintf(bestRGF,"\t%d\t%d\t%.2lf",vbid.nMarkers,vbid.mixOut.numReads[(rg+1)*4],(double)vbid.mixOut.numReads[(rg+1)*4]/(double)vbid.mixOut.numGenos[(rg+1)*4]);
      if ( args.bFreeNone ) { ifprintf(bestRGF,"\tNA\tNA\tNA\tNA\tNA"); }
      else if ( args.bFreeMixOnly ) { ifprintf(bestRGF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA",vbid.mixOut.fMixs[rg+1],vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1]); }
      else if ( args.bFreeRefBiasOnly ) { ifprintf(bestRGF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1],vbid.mixOut.refHets[rg+1],vbid.mixOut.refAlts[rg+1]); }
      else if ( args.bFreeFull ) { ifprintf(bestRGF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf",vbid.mixOut.fMixs[rg+1],vbid.mixOut.llk1s[rg+1],vbid.mixOut.llk0s[rg+1],vbid.mixOut.refHets[rg+1],vbid.mixOut.refAlts[rg+1]); }
      else { error("Invalid option in handling bFree"); }
      
      if ( args.bChipNone || bestInds[0] < 0 ) { ifprintf(bestRGF,"\tNA\tNA\tNA\tNA\tNA\tNA\tNA\tNA"); }
      else if ( args.bChipMixOnly ) { ifprintf(bestRGF,"\t%.5lf\t%.2lf\t%.2lf\tNA\tNA\t%.3lf\t%.4lf\t%.4lf",vbid.bestOut.fMixs[rg+1], vbid.bestOut.llk1s[rg+1], vbid.bestOut.llk0s[rg+1], (double)vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+1], (double)vbid.bestOut.numReads[(rg+1)*4+2]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+2], (double)vbid.bestOut.numReads[(rg+1)*4+3]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+3]); }
      else if ( args.bChipMixOnly ) { ifprintf(bestRGF,"\tNA\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf",vbid.bestOut.llk1s[rg+1], vbid.bestOut.llk0s[rg+1], vbid.bestOut.refHets[rg+1], vbid.bestOut.refAlts[rg+1], (double)vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+1], (double)vbid.bestOut.numReads[(rg+1)*4+2]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4]/vbid.bestOut.numGenos[(rg+1)*4+2], (double)vbid.bestOut.numReads[(rg+1)*4+3]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+3]); }
      else if ( args.bChipFull ) { ifprintf(bestRGF,"\t%.5lf\t%.2lf\t%.2lf\t%.5lf\t%.5lf\t%.3lf\t%.4lf\t%.4lf", vbid.bestOut.fMixs[rg+1], vbid.bestOut.llk1s[rg+1], vbid.bestOut.llk0s[rg+1], vbid.bestOut.refHets[rg+1], vbid.bestOut.refAlts[rg+1], (double)vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+1], (double)vbid.bestOut.numReads[(rg+1)*4+2]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+2], (double)vbid.bestOut.numReads[(rg+1)*4+3]*vbid.bestOut.numGenos[(rg+1)*4+1]/vbid.bestOut.numReads[(rg+1)*4+1]/vbid.bestOut.numGenos[(rg+1)*4+3]); }
      else { error("Invalid option in handling bChip"); }
      ifprintf(bestRGF,"\n");
    }
    ifclose(bestRGF);
  }
  
  time(&t);
  Logger::gLogger->writeLog("Analysis finished on %s",ctime(&t));

  return 0;
}
Ejemplo n.º 12
0
void PLAYERS::render_player(
	const NETOBJ_CHARACTER *prev_char,
	const NETOBJ_CHARACTER *player_char,
	const NETOBJ_PLAYER_INFO *prev_info,
	const NETOBJ_PLAYER_INFO *player_info
	)
{
	NETOBJ_CHARACTER prev;
	NETOBJ_CHARACTER player;
	prev = *prev_char;
	player = *player_char;

	NETOBJ_PLAYER_INFO info = *player_info;
	TEE_RENDER_INFO render_info = gameclient.clients[info.cid].render_info;

	// check for teamplay modes
	bool is_teamplay = false;
	bool new_tick = gameclient.new_tick;
	if(gameclient.snap.gameobj)
		is_teamplay = (gameclient.snap.gameobj->flags&GAMEFLAG_TEAMS) != 0;

	// check for ninja	
	if (player.weapon == WEAPON_NINJA)
	{
		// change the skin for the player to the ninja
		int skin = gameclient.skins->find("x_ninja");
		if(skin != -1)
		{
			if(is_teamplay)
				render_info.texture = gameclient.skins->get(skin)->color_texture;
			else
			{
				render_info.texture = gameclient.skins->get(skin)->org_texture;
				render_info.color_body = vec4(1,1,1,1);
				render_info.color_feet = vec4(1,1,1,1);
			}
		}	
	}
	
	// set size
	render_info.size = 64.0f;

	float intratick = client_intratick();
	
	if(player.health < 0) // dont render dead players
		return;

	float angle = mix((float)prev.angle, (float)player.angle, intratick)/256.0f;
	
	//float angle = 0;
	
	if(info.local && client_state() != CLIENTSTATE_DEMOPLAYBACK)
	{
		// just use the direct input if it's local player we are rendering
		angle = get_angle(gameclient.controls->mouse_pos);
	}
	else
	{
		/*
		float mixspeed = client_frametime()*2.5f;
		if(player.attacktick != prev.attacktick) // shooting boosts the mixing speed
			mixspeed *= 15.0f;
		
		// move the delta on a constant speed on a x^2 curve
		float current = gameclient.clients[info.cid].angle;
		float target = player.angle/256.0f;
		float delta = angular_distance(current, target);
		float sign = delta < 0 ? -1 : 1;
		float new_delta = delta - 2*mixspeed*sqrt(delta*sign)*sign + mixspeed*mixspeed;
		
		// make sure that it doesn't vibrate when it's still
		if(fabs(delta) < 2/256.0f)
			angle = target;
		else
			angle = angular_approach(current, target, fabs(delta-new_delta));

		gameclient.clients[info.cid].angle = angle;*/
	}
	
	// use preditect players if needed
	if(info.local && config.cl_predict && client_state() != CLIENTSTATE_DEMOPLAYBACK)
	{
		if(!gameclient.snap.local_character || (gameclient.snap.local_character->health < 0) || (gameclient.snap.gameobj && gameclient.snap.gameobj->game_over))
		{
		}
		else
		{
			// apply predicted results
			gameclient.predicted_char.write(&player);
			gameclient.predicted_prev_char.write(&prev);
			intratick = client_predintratick();
			new_tick = gameclient.new_predicted_tick;
		}
	}
	
	vec2 direction = get_direction((int)(angle*256.0f));
	vec2 position = mix(vec2(prev.x, prev.y), vec2(player.x, player.y), intratick);
	vec2 vel = mix(vec2(prev.vx/256.0f, prev.vy/256.0f), vec2(player.vx/256.0f, player.vy/256.0f), intratick);
	
	gameclient.flow->add(position, vel*100.0f, 10.0f);
	
	render_info.got_airjump = player.jumped&2?0:1;
	
	
	// detect events
	if(new_tick)
	{
		// detect air jump
		if(!render_info.got_airjump && !(prev.jumped&2))
			gameclient.effects->air_jump(position);
	}

	if(prev.health < 0) // Don't flicker from previous position
		position = vec2(player.x, player.y);

	bool stationary = player.vx <= 1 && player.vx >= -1;
	bool inair = col_check_point(player.x, player.y+16) == 0;
	bool want_other_dir = (player.direction == -1 && vel.x > 0) || (player.direction == 1 && vel.x < 0);

	// evaluate animation
	float walk_time = fmod(position.x, 100.0f)/100.0f;
	ANIMSTATE state;
	state.set(&data->animations[ANIM_BASE], 0);

	if(inair)
		state.add(&data->animations[ANIM_INAIR], 0, 1.0f); // TODO: some sort of time here
	else if(stationary)
		state.add(&data->animations[ANIM_IDLE], 0, 1.0f); // TODO: some sort of time here
	else if(!want_other_dir)
		state.add(&data->animations[ANIM_WALK], walk_time, 1.0f);

	if (player.weapon == WEAPON_HAMMER)
	{
		float ct = (client_prevtick()-player.attacktick)/(float)SERVER_TICK_SPEED + client_ticktime();
		state.add(&data->animations[ANIM_HAMMER_SWING], clamp(ct*5.0f,0.0f,1.0f), 1.0f);
	}
	if (player.weapon == WEAPON_NINJA)
	{
		float ct = (client_prevtick()-player.attacktick)/(float)SERVER_TICK_SPEED + client_ticktime();
		state.add(&data->animations[ANIM_NINJA_SWING], clamp(ct*2.0f,0.0f,1.0f), 1.0f);
	}
	
	// do skidding
	if(!inair && want_other_dir && length(vel*50) > 500.0f)
	{
		static int64 skid_sound_time = 0;
		if(time_get()-skid_sound_time > time_freq()/10)
		{
			gameclient.sounds->play(SOUNDS::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, position);
			skid_sound_time = time_get();
		}
		
		gameclient.effects->skidtrail(
			position+vec2(-player.direction*6,12),
			vec2(-player.direction*100*length(vel),-50)
		);
	}

	// draw hook
	if (prev.hook_state>0 && player.hook_state>0)
	{
		gfx_texture_set(data->images[IMAGE_GAME].id);
		gfx_quads_begin();
		//gfx_quads_begin();

		vec2 pos = position;
		vec2 hook_pos;
		
		if(player_char->hooked_player != -1)
		{
			if(gameclient.snap.local_info && player_char->hooked_player == gameclient.snap.local_info->cid)
			{
				hook_pos = mix(vec2(gameclient.predicted_prev_char.pos.x, gameclient.predicted_prev_char.pos.y),
					vec2(gameclient.predicted_char.pos.x, gameclient.predicted_char.pos.y), client_predintratick());
			}
			else
				hook_pos = mix(vec2(prev_char->hook_x, prev_char->hook_y), vec2(player_char->hook_x, player_char->hook_y), client_intratick());
		}
		else
			hook_pos = mix(vec2(prev.hook_x, prev.hook_y), vec2(player.hook_x, player.hook_y), intratick);

		float d = distance(pos, hook_pos);
		vec2 dir = normalize(pos-hook_pos);

		gfx_quads_setrotation(get_angle(dir)+pi);

		// render head
		select_sprite(SPRITE_HOOK_HEAD);
		gfx_quads_draw(hook_pos.x, hook_pos.y, 24,16);

		// render chain
		select_sprite(SPRITE_HOOK_CHAIN);
		int i = 0;
		for(float f = 24; f < d && i < 1024; f += 24, i++)
		{
			vec2 p = hook_pos + dir*f;
			gfx_quads_draw(p.x, p.y,24,16);
		}

		gfx_quads_setrotation(0);
		gfx_quads_end();

		render_hand(&render_info, position, normalize(hook_pos-pos), -pi/2, vec2(20, 0));
	}

	// draw gun
	{
		gfx_texture_set(data->images[IMAGE_GAME].id);
		gfx_quads_begin();
		gfx_quads_setrotation(state.attach.angle*pi*2+angle);

		// normal weapons
		int iw = clamp(player.weapon, 0, NUM_WEAPONS-1);
		select_sprite(data->weapons.id[iw].sprite_body, direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0);

		vec2 dir = direction;
		float recoil = 0.0f;
		vec2 p;
		if (player.weapon == WEAPON_HAMMER)
		{
			// Static position for hammer
			p = position + vec2(state.attach.x, state.attach.y);
			p.y += data->weapons.id[iw].offsety;
			// if attack is under way, bash stuffs
			if(direction.x < 0)
			{
				gfx_quads_setrotation(-pi/2-state.attach.angle*pi*2);
				p.x -= data->weapons.id[iw].offsetx;
			}
			else
			{
				gfx_quads_setrotation(-pi/2+state.attach.angle*pi*2);
			}
			draw_sprite(p.x, p.y, data->weapons.id[iw].visual_size);
		}
		else if (player.weapon == WEAPON_NINJA)
		{
			p = position;
			p.y += data->weapons.id[iw].offsety;

			if(direction.x < 0)
			{
				gfx_quads_setrotation(-pi/2-state.attach.angle*pi*2);
				p.x -= data->weapons.id[iw].offsetx;
				gameclient.effects->powerupshine(p+vec2(32,0), vec2(32,12));
			}
			else
			{
				gfx_quads_setrotation(-pi/2+state.attach.angle*pi*2);
				gameclient.effects->powerupshine(p-vec2(32,0), vec2(32,12));
			}
			draw_sprite(p.x, p.y, data->weapons.id[iw].visual_size);

			// HADOKEN
			if ((client_tick()-player.attacktick) <= (SERVER_TICK_SPEED / 6) && data->weapons.id[iw].num_sprite_muzzles)
			{
				int itex = rand() % data->weapons.id[iw].num_sprite_muzzles;
				float alpha = 1.0f;
				if (alpha > 0.0f && data->weapons.id[iw].sprite_muzzles[itex])
				{
					vec2 dir = vec2(player_char->x,player_char->y) - vec2(prev_char->x, prev_char->y);
					dir = normalize(dir);
					float hadokenangle = get_angle(dir);
					gfx_quads_setrotation(hadokenangle);
					//float offsety = -data->weapons[iw].muzzleoffsety;
					select_sprite(data->weapons.id[iw].sprite_muzzles[itex], 0);
					vec2 diry(-dir.y,dir.x);
					p = position;
					float offsetx = data->weapons.id[iw].muzzleoffsetx;
					p -= dir * offsetx;
					draw_sprite(p.x, p.y, 160.0f);
				}
			}
		}
		else
		{
			// TODO: should be an animation
			recoil = 0;
			float a = (client_tick()-player.attacktick+intratick)/5.0f;
			if(a < 1)
				recoil = sinf(a*pi);
			p = position + dir * data->weapons.id[iw].offsetx - dir*recoil*10.0f;
			p.y += data->weapons.id[iw].offsety;
			draw_sprite(p.x, p.y, data->weapons.id[iw].visual_size);
		}

		if (player.weapon == WEAPON_GUN || player.weapon == WEAPON_SHOTGUN)
		{
			// check if we're firing stuff
			if(data->weapons.id[iw].num_sprite_muzzles)//prev.attackticks)
			{
				float alpha = 0.0f;
				int phase1tick = (client_tick() - player.attacktick);
				if (phase1tick < (data->weapons.id[iw].muzzleduration + 3))
				{
					float t = ((((float)phase1tick) + intratick)/(float)data->weapons.id[iw].muzzleduration);
					alpha = LERP(2.0, 0.0f, min(1.0f,max(0.0f,t)));
				}

				int itex = rand() % data->weapons.id[iw].num_sprite_muzzles;
				if (alpha > 0.0f && data->weapons.id[iw].sprite_muzzles[itex])
				{
					float offsety = -data->weapons.id[iw].muzzleoffsety;
					select_sprite(data->weapons.id[iw].sprite_muzzles[itex], direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0);
					if(direction.x < 0)
						offsety = -offsety;

					vec2 diry(-dir.y,dir.x);
					vec2 muzzlepos = p + dir * data->weapons.id[iw].muzzleoffsetx + diry * offsety;

					draw_sprite(muzzlepos.x, muzzlepos.y, data->weapons.id[iw].visual_size);
				}
			}
		}
		gfx_quads_end();

		switch (player.weapon)
		{
			case WEAPON_GUN: render_hand(&render_info, p, direction, -3*pi/4, vec2(-15, 4)); break;
			case WEAPON_SHOTGUN: render_hand(&render_info, p, direction, -pi/2, vec2(-5, 4)); break;
			case WEAPON_GRENADE: render_hand(&render_info, p, direction, -pi/2, vec2(-4, 7)); break;
		}

	}

	// render the "shadow" tee
	if(info.local && config.debug)
	{
		vec2 ghost_position = mix(vec2(prev_char->x, prev_char->y), vec2(player_char->x, player_char->y), client_intratick());
		TEE_RENDER_INFO ghost = render_info;
		ghost.color_body.a = 0.5f;
		ghost.color_feet.a = 0.5f;
		render_tee(&state, &ghost, player.emote, direction, ghost_position); // render ghost
	}

	render_info.size = 64.0f; // force some settings
	render_info.color_body.a = 1.0f;
	render_info.color_feet.a = 1.0f;
	render_tee(&state, &render_info, player.emote, direction, position);

	if(player.player_state == PLAYERSTATE_CHATTING)
	{
		gfx_texture_set(data->images[IMAGE_EMOTICONS].id);
		gfx_quads_begin();
		select_sprite(SPRITE_DOTDOT);
		gfx_quads_draw(position.x + 24, position.y - 40, 64,64);
		gfx_quads_end();
	}

	if (gameclient.clients[info.cid].emoticon_start != -1 && gameclient.clients[info.cid].emoticon_start + 2 * client_tickspeed() > client_tick())
	{
		gfx_texture_set(data->images[IMAGE_EMOTICONS].id);
		gfx_quads_begin();

		int since_start = client_tick() - gameclient.clients[info.cid].emoticon_start;
		int from_end = gameclient.clients[info.cid].emoticon_start + 2 * client_tickspeed() - client_tick();

		float a = 1;

		if (from_end < client_tickspeed() / 5)
			a = from_end / (client_tickspeed() / 5.0);

		float h = 1;
		if (since_start < client_tickspeed() / 10)
			h = since_start / (client_tickspeed() / 10.0);

		float wiggle = 0;
		if (since_start < client_tickspeed() / 5)
			wiggle = since_start / (client_tickspeed() / 5.0);

		float wiggle_angle = sin(5*wiggle);

		gfx_quads_setrotation(pi/6*wiggle_angle);

		gfx_setcolor(1.0f,1.0f,1.0f,a);
		// client_datas::emoticon is an offset from the first emoticon
		select_sprite(SPRITE_OOP + gameclient.clients[info.cid].emoticon);
		gfx_quads_draw(position.x, position.y - 23 - 32*h, 64, 64*h);
		gfx_quads_end();
	}
}
Ejemplo n.º 13
0
uint8_t chroma_mix (uint8_t c1, uint8_t c2, uint8_t per) {
	return mix(c1,c2,per,128);
}
Ejemplo n.º 14
0
uint8_t luma_mix (uint8_t c1, uint8_t c2, uint8_t per) {
	return mix(c1,c2,per,16);
}
Ejemplo n.º 15
0
void mixtureKEpsilon<BasicTurbulenceModel>::correct()
{
    const transportModel& gas = this->transport();
    const twoPhaseSystem& fluid = gas.fluid();

    // Only solve the mixture turbulence for the gas-phase
    if (&gas != &fluid.phase1())
    {
        // This is the liquid phase but check the model for the gas-phase
        // is consistent
        this->liquidTurbulence();

        return;
    }

    if (!this->turbulence_)
    {
        return;
    }

    // Initialise the mixture fields if they have not yet been constructed
    initMixtureFields();

    // Local references to gas-phase properties
    const surfaceScalarField& phig = this->phi_;
    const volVectorField& Ug = this->U_;
    const volScalarField& alphag = this->alpha_;
    volScalarField& kg = this->k_;
    volScalarField& epsilong = this->epsilon_;
    volScalarField& nutg = this->nut_;

    // Local references to liquid-phase properties
    mixtureKEpsilon<BasicTurbulenceModel>& liquidTurbulence =
        this->liquidTurbulence();
    const surfaceScalarField& phil = liquidTurbulence.phi_;
    const volVectorField& Ul = liquidTurbulence.U_;
    const volScalarField& alphal = liquidTurbulence.alpha_;
    volScalarField& kl = liquidTurbulence.k_;
    volScalarField& epsilonl = liquidTurbulence.epsilon_;
    volScalarField& nutl = liquidTurbulence.nut_;

    // Local references to mixture properties
    volScalarField& rhom = rhom_();
    volScalarField& km = km_();
    volScalarField& epsilonm = epsilonm_();

    eddyViscosity<RASModel<BasicTurbulenceModel> >::correct();

    // Update the effective mixture density
    rhom = this->rhom();

    // Mixture flux
    surfaceScalarField phim("phim", mixFlux(phil, phig));

    // Mixture velocity divergence
    volScalarField divUm
    (
        mixU
        (
            fvc::div(fvc::absolute(phil, Ul)),
            fvc::div(fvc::absolute(phig, Ug))
        )
    );

    tmp<volScalarField> Gc;
    {
        tmp<volTensorField> tgradUl = fvc::grad(Ul);
        Gc = tmp<volScalarField>
        (
            new volScalarField
            (
                this->GName(),
                nutl*(tgradUl() && dev(twoSymm(tgradUl())))
            )
        );
        tgradUl.clear();

        // Update k, epsilon and G at the wall
        kl.boundaryField().updateCoeffs();
        epsilonl.boundaryField().updateCoeffs();

        Gc().checkOut();
    }

    tmp<volScalarField> Gd;
    {
        tmp<volTensorField> tgradUg = fvc::grad(Ug);
        Gd = tmp<volScalarField>
        (
            new volScalarField
            (
                this->GName(),
                nutg*(tgradUg() && dev(twoSymm(tgradUg())))
            )
        );
        tgradUg.clear();

        // Update k, epsilon and G at the wall
        kg.boundaryField().updateCoeffs();
        epsilong.boundaryField().updateCoeffs();

        Gd().checkOut();
    }

    // Mixture turbulence generation
    volScalarField Gm(mix(Gc, Gd));

    // Mixture turbulence viscosity
    volScalarField nutm(mixU(nutl, nutg));

    // Update the mixture k and epsilon boundary conditions
    km == mix(kl, kg);
    bound(km, this->kMin_);
    epsilonm == mix(epsilonl, epsilong);
    bound(epsilonm, this->epsilonMin_);

    // Dissipation equation
    tmp<fvScalarMatrix> epsEqn
    (
        fvm::ddt(rhom, epsilonm)
      + fvm::div(phim, epsilonm)
      - fvm::Sp(fvc::ddt(rhom) + fvc::div(phim), epsilonm)
      - fvm::laplacian(DepsilonEff(rhom*nutm), epsilonm)
     ==
        C1_*rhom*Gm*epsilonm/km
      - fvm::SuSp(((2.0/3.0)*C1_)*rhom*divUm, epsilonm)
      - fvm::Sp(C2_*rhom*epsilonm/km, epsilonm)
      + epsilonSource()
    );

    epsEqn().relax();

    epsEqn().boundaryManipulate(epsilonm.boundaryField());

    solve(epsEqn);
    bound(epsilonm, this->epsilonMin_);


    // Turbulent kinetic energy equation
    tmp<fvScalarMatrix> kmEqn
    (
        fvm::ddt(rhom, km)
      + fvm::div(phim, km)
      - fvm::Sp(fvc::ddt(rhom) + fvc::div(phim), km)
      - fvm::laplacian(DkEff(rhom*nutm), km)
     ==
        rhom*Gm
      - fvm::SuSp((2.0/3.0)*rhom*divUm, km)
      - fvm::Sp(rhom*epsilonm/km, km)
      + kSource()
    );

    kmEqn().relax();
    solve(kmEqn);
    bound(km, this->kMin_);
    km.correctBoundaryConditions();

    volScalarField Cc2(rhom/(alphal*rholEff() + alphag*rhogEff()*Ct2_()));
    kl = Cc2*km;
    kl.correctBoundaryConditions();
    epsilonl = Cc2*epsilonm;
    epsilonl.correctBoundaryConditions();
    liquidTurbulence.correctNut();

    Ct2_() = Ct2();
    kg = Ct2_()*kl;
    kg.correctBoundaryConditions();
    epsilong = Ct2_()*epsilonl;
    epsilong.correctBoundaryConditions();
    nutg = Ct2_()*(liquidTurbulence.nu()/this->nu())*nutl;
}
Ejemplo n.º 16
0
		void main()\
		{\
			gl_FragColor = (gl_Color == highlightColor ? highlight(gl_Color) : gl_Color) *\
				mix( texture2D(first, gl_TexCoord[0].xy / (2 * zoomFactor)), texture2D(second, gl_TexCoord[0].xy ), amount );\
		}";
Ejemplo n.º 17
0
static uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
{
	uint32_t a,b,c;
	union { const void *ptr; size_t i; } u;

	/* Set up the internal state */
	a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;

	u.ptr = key;
	if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
		const uint32_t *k = (const uint32_t *)key;

		while (length > 12) {
			a += k[0];
			b += k[1];
			c += k[2];
			mix(a,b,c);
			length -= 12;
			k += 3;
		}

#ifndef VALGRIND
		switch (length) {

		case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
		case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
		case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
		case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
		case 8 : b+=k[1]; a+=k[0]; break;
		case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
		case 6 : b+=k[1]&0xffff; a+=k[0]; break;
		case 5 : b+=k[1]&0xff; a+=k[0]; break;
		case 4 : a+=k[0]; break;
		case 3 : a+=k[0]&0xffffff; break;
		case 2 : a+=k[0]&0xffff; break;
		case 1 : a+=k[0]&0xff; break;
		case 0 : return c;
		}

#else /* make valgrind happy */

		const uint8_t  *k8 = (const uint8_t *)k;
		switch (length) {

		case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
		case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
		case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
		case 9 : c+=k8[8];                   /* fall through */
		case 8 : b+=k[1]; a+=k[0]; break;
		case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
		case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
		case 5 : b+=k8[4];                   /* fall through */
		case 4 : a+=k[0]; break;
		case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
		case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
		case 1 : a+=k8[0]; break;
		case 0 : return c;
		}

#endif /* !valgrind */

	}
	else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
		const uint16_t *k = (const uint16_t *)key;
		const uint8_t  *k8;

		while (length > 12) {
			a += k[0] + (((uint32_t)k[1])<<16);
			b += k[2] + (((uint32_t)k[3])<<16);
			c += k[4] + (((uint32_t)k[5])<<16);
			mix(a,b,c);
			length -= 12;
			k += 6;
		}

		k8 = (const uint8_t *)k;

		switch (length) {

		case 12: c+=k[4]+(((uint32_t)k[5])<<16);
			b+=k[2]+(((uint32_t)k[3])<<16);
			a+=k[0]+(((uint32_t)k[1])<<16);
			break;
		case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
		case 10: c+=k[4];
			b+=k[2]+(((uint32_t)k[3])<<16);
			a+=k[0]+(((uint32_t)k[1])<<16);
			break;
		case 9 : c+=k8[8];                      /* fall through */
		case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
			a+=k[0]+(((uint32_t)k[1])<<16);
			break;
		case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
		case 6 : b+=k[2];
			a+=k[0]+(((uint32_t)k[1])<<16);
			break;
		case 5 : b+=k8[4];                      /* fall through */
		case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
			break;
		case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
		case 2 : a+=k[0];
			break;
		case 1 : a+=k8[0];
			break;
		case 0 : return c;
		}
	}
	else {
		const uint8_t *k = (const uint8_t *)key;

		while (length > 12) {
			a += k[0];
			a += ((uint32_t)k[1])<<8;
			a += ((uint32_t)k[2])<<16;
			a += ((uint32_t)k[3])<<24;
			b += k[4];
			b += ((uint32_t)k[5])<<8;
			b += ((uint32_t)k[6])<<16;
			b += ((uint32_t)k[7])<<24;
			c += k[8];
			c += ((uint32_t)k[9])<<8;
			c += ((uint32_t)k[10])<<16;
			c += ((uint32_t)k[11])<<24;
			mix(a,b,c);
			length -= 12;
			k += 12;
		}

		/* all the case statements fall through */
		switch (length) {

		case 12: c+=((uint32_t)k[11])<<24;
		case 11: c+=((uint32_t)k[10])<<16;
		case 10: c+=((uint32_t)k[9])<<8;
		case 9 : c+=k[8];
		case 8 : b+=((uint32_t)k[7])<<24;
		case 7 : b+=((uint32_t)k[6])<<16;
		case 6 : b+=((uint32_t)k[5])<<8;
		case 5 : b+=k[4];
		case 4 : a+=((uint32_t)k[3])<<24;
		case 3 : a+=((uint32_t)k[2])<<16;
		case 2 : a+=((uint32_t)k[1])<<8;
		case 1 : a+=k[0];
			break;
		case 0 : return c;
		}
	}

	final(a,b,c);
Ejemplo n.º 18
0
unsigned long Bignum::hash()
{
  return mix(mpz_sgn(_z), mpz_get_ui(_z));
}
Ejemplo n.º 19
0
void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent)
{
	Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
	Graphics()->QuadsBegin();
	vec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick());
	float Angle = 0.0f;
	float Size = 64.0f;
	if (pCurrent->m_Type == POWERUP_WEAPON)
	{
		Angle = 0; //-pi/6;//-0.25f * pi * 2.0f;
		RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Subtype, 0, NUM_WEAPONS-1)].m_pSpriteBody);
		Size = g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Subtype, 0, NUM_WEAPONS-1)].m_VisualSize;
		if(g_Config.m_ClEffectsWeapontrail)
		{
			if(pCurrent->m_Subtype == 2)
				m_pClient->m_pEffects->PowerupShine(Pos, vec2(64,32),vec4(0.25f,1,0.25f,1));
			else if(pCurrent->m_Subtype == 3)
				m_pClient->m_pEffects->PowerupShine(Pos, vec2(64,32),vec4(1,0.4f,0.4f,1));
			else if(pCurrent->m_Subtype == 4)
				m_pClient->m_pEffects->PowerupShine(Pos, vec2(64,32),vec4(0.3232f,0.03232f,1,1));
		}
	
	}
	else
	{
		const int c[] = {
			SPRITE_PICKUP_HEALTH,
			SPRITE_PICKUP_ARMOR,
			SPRITE_PICKUP_WEAPON,
			SPRITE_PICKUP_NINJA
			};
		RenderTools()->SelectSprite(c[pCurrent->m_Type]);

		if(c[pCurrent->m_Type] == SPRITE_PICKUP_NINJA)
		{
			m_pClient->m_pEffects->PowerupShine(Pos, vec2(96,18));
			Size *= 2.0f;
			Pos.x -= 10.0f;
		}
	}

	Graphics()->QuadsSetRotation(Angle);

	float Offset = Pos.y/32.0f + Pos.x/32.0f;
	if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
	{
		const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
		static float Time = 0;
		static float LastLocalTime = Client()->LocalTime();
		
		if(!pInfo->m_Paused)
			Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed;
			
		Pos.x += cosf(Time*2.0f+Offset)*2.5f;
		Pos.y += sinf(Time*2.0f+Offset)*2.5f;
		
		LastLocalTime = Client()->LocalTime();
	}
	else
	{
		Pos.x += cosf(Client()->LocalTime()*2.0f+Offset)*2.5f;
		Pos.y += sinf(Client()->LocalTime()*2.0f+Offset)*2.5f;
	}
	RenderTools()->DrawSprite(Pos.x, Pos.y, Size);
	Graphics()->QuadsEnd();
}
Ejemplo n.º 20
0
uint32_t
hash_func(const uint8_t *k, uint32_t length, uint32_t initval)
{
    uint32_t a, b, c, len;

    /* Set up the internal state */
    len = length;
    a = b = 0x9e3779b9;      /* the golden ratio; an arbitrary value */
    c = initval;             /* the previous hash value */

    /*---------------------------------------- handle most of the key */
    while (len >= 12)
    {
        a += (k[0] + ((uint32_t) k[1] << 8)
              + ((uint32_t) k[2] << 16)
              + ((uint32_t) k[3] << 24));
        b += (k[4] + ((uint32_t) k[5] << 8)
              + ((uint32_t) k[6] << 16)
              + ((uint32_t) k[7] << 24));
        c += (k[8] + ((uint32_t) k[9] << 8)
              + ((uint32_t) k[10] << 16)
              + ((uint32_t) k[11] << 24));
        mix(a, b, c);
        k += 12;
        len -= 12;
    }

    /*------------------------------------- handle the last 11 bytes */
    c += length;
    switch (len)            /* all the case statements fall through */
    {
        case 11:
            c += ((uint32_t) k[10] << 24);

        case 10:
            c += ((uint32_t) k[9] << 16);

        case 9:
            c += ((uint32_t) k[8] << 8);

        /* the first byte of c is reserved for the length */
        case 8:
            b += ((uint32_t) k[7] << 24);

        case 7:
            b += ((uint32_t) k[6] << 16);

        case 6:
            b += ((uint32_t) k[5] << 8);

        case 5:
            b += k[4];

        case 4:
            a += ((uint32_t) k[3] << 24);

        case 3:
            a += ((uint32_t) k[2] << 16);

        case 2:
            a += ((uint32_t) k[1] << 8);

        case 1:
            a += k[0];
            /* case 0: nothing left to add */
    }
    mix(a, b, c);
    /*-------------------------------------- report the result */
    return c;
}
Ejemplo n.º 21
0
vec3 mix(const vec3& a, const vec3& b, const vec3& x) {
  return vec3(mix(a[0], b[0], x[0]),
              mix(a[1], b[1], x[1]),
              mix(a[2], b[2], x[2]));
}
Ejemplo n.º 22
0
static bool RT_play_voice(Data *data, Voice *voice, int num_frames_to_produce, float **outputs){
  int startpos = voice->delta_pos_at_start;
  int endpos = voice->delta_pos_at_end;

  if(startpos>=0)
    voice->delta_pos_at_start = 0;
  if(endpos>=0)
    voice->delta_pos_at_end = -1;

  if(endpos>=0 && endpos<startpos) // Should not happen. Test for it just in case. It's a bit messy when notes are generated by the keyboard, player and other places at the same time.
    {
      printf("Oops. Endpos: %d. startpos: %d\n",endpos,startpos);
      return false;
    }

  float resampled_data[num_frames_to_produce-startpos];
  int frames_created_by_resampler = RT_get_resampled_data(data,voice,resampled_data,num_frames_to_produce-startpos);
  //printf("Frames created by resampler: %d\n",frames_created_by_resampler);
  //printf("peak: %f\n",get_peak(resampled_data,frames_created_by_resampler));

  int frames_created_by_envelope;

  float *adsr_sound_data[1]={&resampled_data[0]};

  if(endpos>=0){
    int pre_release_len = endpos-startpos;

    //printf("********** endpos>0: %d. prelen: %d, frames_created_by_resampler: %d\n",endpos,prelen,frames_created_by_resampler);

    if(frames_created_by_resampler <= pre_release_len){ // i.e. we reached the end of sound before beginning to release the ADSR envelope.

      frames_created_by_envelope = ADSR_apply(voice->adsr, adsr_sound_data, 1, frames_created_by_resampler);

    }else{
      frames_created_by_envelope = ADSR_apply(voice->adsr, adsr_sound_data, 1, pre_release_len);

      //printf("************************ Calling adsr release\n");
      ADSR_release(voice->adsr);

      int post_release_len = frames_created_by_resampler - frames_created_by_envelope;
      adsr_sound_data[0] = &resampled_data[frames_created_by_envelope];        
      frames_created_by_envelope += ADSR_apply(voice->adsr, adsr_sound_data, 1, post_release_len);
    }

  }else{

    frames_created_by_envelope = ADSR_apply(voice->adsr, adsr_sound_data, 1, frames_created_by_resampler);
    //printf("Frames created by envelope: %d, peak: %f\n",frames_created_by_envelope,get_peak(resampled_data,frames_created_by_envelope));
    //printf("peak: %f\n",get_peak(resampled_data,frames_created_by_resampler));
  }

  //float peak_in = get_peak(resampled_data,frames_created_by_envelope);

  const Sample *sample = voice->sample;

#define mix(input_channel, output_channel) do{                          \
    float panval = voice->pan.vals[input_channel][output_channel];      \
    if(panval>0.0f){                                                    \
      float *out          = outputs[output_channel] + startpos;         \
      float  start_volume = voice->start_volume*panval;                 \
      float  end_volume   = voice->end_volume*panval;                   \
      SMOOTH_mix_sounds_raw(out, resampled_data, frames_created_by_envelope, start_volume, end_volume); \
    }                                                                   \
  }while(0)

  if(sample->ch == -1){
    mix(0,0);
    mix(0,1);
  }else{
    mix(sample->ch,0);
    mix(sample->ch,1);
  }

  //printf("peak in/out: %.3f - %.3f\n",peak_in,get_peak(outputs[0], num_frames_to_produce));

  voice->start_volume = voice->end_volume;
  voice->start_pitch = voice->end_pitch;

  if(startpos+frames_created_by_envelope < num_frames_to_produce)
    return true;
  else
    return false;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
    vector<HeuristicChooseReversal *> hcr_seq;

    /* Set random seed */
    unsigned long seed = mix(clock(), time(NULL), getpid());

    /* Set random seed */
    srand(seed);

    /* Exact Unitaty Parameters */
    ofstream fout;

    /* Time results */
    timestamp_t time_begin;
    timestamp_t time_end;
    time_begin = get_timestamp();

    /* Log result file */
    ostream *logOut = NULL;
    ostream *logTime = NULL;

    /* Check essential parameters */
    // TODO: start to use parameter names instead of parameter sequence, ex: -p 1,2,4...
    if (argc < 7) {
        printf("Usage:\n");
        printf("lwr_test_metaheuristic permutation number_of_iteration inversion_limit frame_limit is_signed cost_function {-r=[[...]]}.\n\n");
        printf("Parameters description:\n");
        printf(" 1. permutation: the input permutation.\n\n");
        printf(" 2. number_of_iteration: number of iterations that will\n");
            printf("be performed by the Metaheuristic.\n\n");
        printf(" 3. inversion_limit: limit (upper bound) for the number of inversions\n");
            printf("that will be selected at each iteration of the heuristic for building solutions.\n\n");
        printf(" 4. frame_limit: percentege (in the interval (0,100]) of frames that \n");
            printf("will be selected at each iteration of the Metaheuristic.\n\n");
        printf(" 5. is_signed: 1 if the input permutation is signed, 0 otherwise.\n\n");
        printf(" 6. cost_function: 1 for linear function, 2 for quadratic function and 3 logaritmic function.\n\n");
        printf(" 7. -r=[[...]]: Optional parameter to give a seed solution as a input parameter\n");

        return 0;
    }

    /* Seed result */
    Result seed_result;

    /* Permutation parameters */
    parameter perm_param;

    /* Exact Unitary parameters */
    parameter exactP;

    /* Improve parameters */

    parameter improveP;

    /* ChooseHeuristic parameters*/
    parameter hcrP;

    /* list of solvers for choose reversals */
    vector<Solver *> solver_hcr;

    string intervalMethod = "WINDOW";
    string heuristicReversalsName = "BenefitLoss";

    /* -------------------Read the parameters  From terminal----------------- */

    int p_read = 1;

    // Read the permutation's sequence
    vector<ll> perm_seq = read_seq(argv[p_read++]);

    int num_it;
    sscanf(argv[p_read++], "%d", &num_it);

    int inv_limit;
    sscanf(argv[p_read++], "%d", &inv_limit);

    double frame_limit;
    sscanf(argv[p_read++], "%lf", &frame_limit);

    int is_signed;
    sscanf(argv[p_read++], "%d", &is_signed);

    int cost_function;
    sscanf(argv[p_read++], "%d", &cost_function);

    /* Construct the permutation */
    if (is_signed) {
        perm_param = getSignedParameters();
    } else {
        perm_param = getUnsignedGraspParameters();
    }
    Permutation perm = Permutation(perm_param, perm_seq);
    // makes a copy from the original input permutation and set the normal mode
    Permutation perm_orig = perm;

    // Look for a input solution
    Result input_seed_result;
    bool has_input_seed_result = false;
    if (p_read < argc) {
        string solution = string(argv[p_read++]);
        if (solution.substr(0, 2) == "-r") {
            // in this caseheuristicName is supposed to be like -r=[[...]]
            string str_result = solution.substr(3);
	    // Alterado por Ulisses
            input_seed_result = Util::getResultFromStr(str_result.c_str(), cost_function);
            has_input_seed_result = true;

            Permutation perm_copy = perm;
            bool valid = Solver::validateResult(perm_copy, input_seed_result, cout);
            if (!valid) {
                cout<<"Invalid input solution."<<endl;
                exit(1);
            }
        }
    }


    /* -------------Check if the permutation is already sorted--------------- */
    if (perm.isSorted(1, perm.size())) {
        Result::printResult(seed_result, cout);
        cout<<endl;
        return 0;
    }

    /* ----------------------- Set Default Parameters ----------------------- */
 
    parameter default_parameters = getDefaultParameters();

    /* Set the output for results logging */
    if (p_read < argc) {
        logOut = new ofstream(argv[p_read++], std::ofstream::out|ofstream::app);
    }
    if (p_read < argc) {
        logTime = new ofstream(argv[p_read++], std::ofstream::out|ofstream::app);
    }

    /* Look for Parameters */
    string type;
    parameter::iterator it;
    for (it = default_parameters.begin(); it != default_parameters.end(); it++) {
        pair<string, string> p = getParameterPair(it->F);
        string type = p.F;
        string name = p.S;
        double value = it->S;
        // get Num selected rev
        if (type == "HCR") {
            hcrP[name] = value;
        } else if (type == "IMP") {
            improveP[name] = value;
        } else if (type == "BUILD_SOLUTION") {
            exactP[name] = value;
        }
        p_read++;
    }
    /* Look for the unsigned mode */
    improveP["UNSIGNED"] = !is_signed;

    /* Create log file */
    //ofstream log_out("log_test_signed.txt",ios_base::app);

    /* ----------------------Set Parameters from terminal---------------------- */
    hcrP["COST_FUNCTION"]  = cost_function;
    improveP["COST_FUNCTION"]  = cost_function;
    exactP["COST_FUNCTION"]  = cost_function;

    improveP["NUM_ROUND"] = num_it;
    exactP["NUM_SELECTED_REV"] = inv_limit;

    if (frame_limit <= 0 || frame_limit > 100) {
        cerr<<"Error: frame_limit must be in the interval (0, 100]"<<endl;
        exit(1);
    }
    improveP["ROLETTE_PERCENT_DISCARD"] = (100.0 - frame_limit);


    /*---------------- Build the Choosen reversal Heuristic -------------------*/
    hcr_seq = build_hcr_seq(
      intervalMethod,
      improveP,
      hcrP,
      exactP,
      heuristicReversalsName
    );
    if (improveP["EXACT_UNITATY_LS"]) {
        solver_hcr.push_back(new ExactUnitary(exactP, hcr_seq));
    } else if (improveP["GRASP_HEURISTIC_LS"]) {
        solver_hcr.push_back(new GRASPHeuristic(exactP, hcr_seq));
    }


    /*---------------------- Build The seed solution -------------------------*/
    if (has_input_seed_result) {
        seed_result = input_seed_result;
    } else if (is_signed){
      // Alterado por Ulisses
      seed_result = sortByGRIMM(perm, true, cost_function);
    } else {
      seed_result = sortByGRIMMUnsigned(perm, NUM_IT_GRIMM_UNSIGNED, true, cost_function);
    }
        

    /*--------------------- Build Improvement Metaheuristic ------------------*/
    ImproveReversals * ir = new ImproveReversals(
        solver_hcr,
        intervalMethod,
        improveP,
        logOut
    );

    /*-------------------------- Try improve the result ----------------------*/
    Result r_improved = tryImprove(
        seed_result,
        ir,
        perm_orig,
	cost_function
     );


    /*----------------------- Validate result --------------------------------*/
    bool valid = Solver::validateResult(perm_orig, r_improved, cout);

    Result seedR = seed_result;
    //seedR.reversals = seed_result;
    seedR = Solver::calcTotalCost(seedR, cost_function);


    /*------------------------- Print the result -----------------------------*/
    if (valid) {
        Result::printResult(r_improved, cout);
        cout<<endl;
    } else {
        cout<<"ERROR";
        return 1;
    }

    /*------------------------- Print time -----------------------------------*/
    time_end = get_timestamp();
    double time_sec = get_interval_time(time_begin, time_end);

    if (logTime != NULL)
        *(logTime)<<time_sec<<endl;

    /* Clean all resources */
    for (size_t i = 0; i < solver_hcr.size(); i++) {
        delete solver_hcr[i];
    }
    solver_hcr.clear();
    if (logOut != NULL)
        delete logOut;
    delete ir;
    cleanResources();

    return valid;
}
Ejemplo n.º 24
0
void Particle::initBuffers(){
  nParticles = 10000;
  
  //generate buffers
  GLuint vboHandles[2];
  glGenBuffers(2, vboHandles);
  initVelBufferHandle = vboHandles[0];
  startTimeBufferHandle = vboHandles[1];
  
  // set the initial velocity data
  vec3 v(0.0f);
  
  float velocity, theta, phi;
  GLfloat *datai = new GLfloat[nParticles * 3];
  
  for(unsigned int i = 0; i < nParticles; i ++) {
    theta = mix(0.0f, (float)M_PI / 6.0f, randFloat());
    phi = mix(0.0f, (float)M_PI * 2, randFloat());
    v.x = sinf(theta) * cosf(phi);
    v.y = cosf(theta);
    v.z = sinf(theta) * sinf(phi);
  
    velocity = mix(0.25f, 0.5f, randFloat());
    v = v * velocity;
    datai[3 * i] = v.x;
    datai[3 * i + 1] = v.y;
    datai[3 * i + 2] = v.z;
  }
  
  //set the start time data
  float *datas = new GLfloat[nParticles];
  float time = 0.0f, rate = 0.0005f;
  for(unsigned int i = 0; i < nParticles; i ++) {
    datas[i] = time;
    time += rate;
  }
  
  //allocate space for init velocity buffer
  glBindBuffer(GL_ARRAY_BUFFER, initVelBufferHandle);
  glBufferData(GL_ARRAY_BUFFER, nParticles * 3 * sizeof(GLfloat), datai, GL_STATIC_DRAW);
  
  
  
  //allocate space for start time buffer
  glBindBuffer(GL_ARRAY_BUFFER, startTimeBufferHandle);
  glBufferData(GL_ARRAY_BUFFER, nParticles * sizeof(GLfloat), datas, GL_STATIC_DRAW);
  
  //attach vbo to vao
  glGenVertexArrays(1, &vaoHandle);
  glBindVertexArray(vaoHandle);
  
  glEnableVertexAttribArray(0);
  glEnableVertexAttribArray(1);
  
  glBindBuffer(GL_ARRAY_BUFFER, initVelBufferHandle);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
  
  glBindBuffer(GL_ARRAY_BUFFER, startTimeBufferHandle);
  glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
  
}
Ejemplo n.º 25
0
		static texel_type call(texture_type const & Texture, fetch_type Fetch, samplecoord_type const & SampleCoordWrap, size_type Layer, size_type Face, interpolate_type Level, texel_type const & BorderColor)
		{
			texel_type const MinTexel = linear<Dimension, texture_type, interpolate_type, samplecoord_type, fetch_type, texel_type, is_float, support_border>::call(Texture, Fetch, SampleCoordWrap, Layer, Face, floor(Level), BorderColor);
			texel_type const MaxTexel = linear<Dimension, texture_type, interpolate_type, samplecoord_type, fetch_type, texel_type, is_float, support_border>::call(Texture, Fetch, SampleCoordWrap, Layer, Face, ceil(Level), BorderColor);
			return mix(MinTexel, MaxTexel, fract(Level));
		}
Ejemplo n.º 26
0
void Ship::update () {
    vec3 dv = orientation * vec3 (0, 0, 1);
    vec3 up = orientation * vec3 (0, 1, 0);
    vec3 rt = orientation * vec3 (1, 0, 0);

    float dt = engine.delta * 0.001;

    float speedFactor = length (velocity) > 0 ?
                (3.0-dot (normalize (velocity), normalize (dv))) / 2.0 : 1.0;

    if (throttle) {
        // TODO: add point lights from throttle
        velocity += dv * dt * speedFactor * 10.f;
        throttleParticles->addParticles (position-0.4f*dv,
                                 velocity-2.0f*dv, 2);
        throttleParticles->addParticles (position-0.4f*dv-0.06f*up+0.22f*rt,
                                 velocity-2.0f*dv, 2);
        throttleParticles->addParticles (position-0.4f*dv-0.06f*up-0.22f*rt,
                                 velocity-2.0f*dv, 2);
        throttleTime += dt * 0.1f;
    } else {
        throttleTime *= 0.98;
    }
    throttleParticles->setParticlesColor (mix (vec3(1,0.5,0.1), vec3(0.1, 0.5, 1), throttleTime));

    if (fire && !fireStopping && (fireTime < 8)) {
        fireTime += 8;
        for (int i = 0; i < 4; ++i) {
        fireParticles->addParticles (position + 0.12f*up + 0.2f*rt - 0.3f*i*dv,
                                     velocity + speedFactor * 100.f*dv, 1);
        fireParticles->addParticles (position + 0.12f*up - 0.2f*rt - 0.3f*i*dv,
                                     velocity + speedFactor * 100.f*dv, 1);
        }
    } else {
        fireStopping = fireTime > 0;
        if (fireStopping) fireTime -= dt * 100;
    }

    vector<asteroid> &asts = ast->getAsteroids ();
    for (auto &a : asts) {
        if (length (a.position-position) <= shipSize+a.radius*1.1f) {
            a.stamina -= length(velocity) / a.radius;
            velocity =  position - a.position;
            engine.switchGameState = true;
            explode ();
            thread ([&](){
                sleep(2);
                engine.gameState = GAME_OVER_MENU;
                engine.switchGameState = false;
            }).detach();
        }
    }

    position += velocity * dt;

    for (auto &p : fireParticles->getParticles ()) {
        if (p.lifeTime < 10) {
            for (auto &a : asts) {
                if (length(a.position-p.position) <= length(p.velocity*dt)+a.radius) {
                    a.stamina -= 0.2/a.radius;
                    p.lifeTime = 1000;
                }
            }
        }
    }
}
Ejemplo n.º 27
0
void CBlood::RenderGroup(int Group)
{
	// render acid layer to screen
	if (Group == GROUP_ACIDLAYER)
	{
		if (!g_Config.m_GfxMultiBuffering)
			return;

		CUIRect Screen;
		Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h);
		
		Graphics()->MapScreen(0,0,Graphics()->ScreenWidth(),Graphics()->ScreenHeight());
		
		Graphics()->RenderToScreen();
		Graphics()->BlendNormal();
			
		// blood
		Graphics()->ShaderBegin(SHADER_ACID, CustomStuff()->m_SawbladeAngle*0.1f);
		Graphics()->TextureSet(-2, RENDERBUFFER_ACID);

		Graphics()->QuadsBegin();
		Graphics()->QuadsSetRotation(0);
		Graphics()->SetColor(0.0f, 1.0f, 0, 0.8f);
		
		{
			IGraphics::CQuadItem QuadItem(Graphics()->ScreenWidth() / 2, Graphics()->ScreenHeight() / 2, Graphics()->ScreenWidth(), -Graphics()->ScreenHeight());
			Graphics()->QuadsDraw(&QuadItem, 1);
		}
		
		Graphics()->QuadsEnd();
		Graphics()->ShaderEnd();
		

		// reset the screen like it was before
		Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);
		
		return;
	}
	
	
	// render particles to texture buffers
	if (g_Config.m_GfxMultiBuffering)
	{
		if (Group == GROUP_BLOOD)
			Graphics()->RenderToTexture(RENDERBUFFER_BLOOD);
		else if (Group == GROUP_ACID)
			Graphics()->RenderToTexture(RENDERBUFFER_ACID);
	
		Graphics()->BlendAdditive();
		Graphics()->TextureSet(g_pData->m_aImages[IMAGE_LIGHTS].m_Id);
		Graphics()->QuadsBegin();

		int i = m_aFirstPart[Group];
		while(i != -1)
		{
			float a = m_aBlood[i].m_Life / m_aBlood[i].m_LifeSpan;
			vec2 p = m_aBlood[i].m_Pos;
			float Size = mix(m_aBlood[i].m_StartSize, m_aBlood[i].m_EndSize, a);

			Graphics()->QuadsSetRotation(m_aBlood[i].m_Rot);

			Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);

			IGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size*0.7f);
			Graphics()->QuadsDraw(&QuadItem, 1);

			i = m_aBlood[i].m_NextPart;
		}
		
		Graphics()->QuadsEnd();
		Graphics()->BlendNormal();
	}
	
	// ...or render particles to screen
	else if (Group == GROUP_BLOOD)
	{
		Graphics()->BlendNormal();
		Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GORE].m_Id);
		
		Graphics()->QuadsBegin();

		int i = m_aFirstPart[Group];
		while(i != -1)
		{
			RenderTools()->SelectSprite(m_aBlood[i].m_Spr);
			float a = m_aBlood[i].m_Life / m_aBlood[i].m_LifeSpan;
			vec2 p = m_aBlood[i].m_Pos;
			float Size = mix(m_aBlood[i].m_StartSize, m_aBlood[i].m_EndSize, a);

			Graphics()->QuadsSetRotation(m_aBlood[i].m_Rot);
			
			Graphics()->SetColor(
				m_aBlood[i].m_Color.r,
				m_aBlood[i].m_Color.g,
				m_aBlood[i].m_Color.b,
				1.2f-a);

			IGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size / 2.0f);
			Graphics()->QuadsDraw(&QuadItem, 1);

			i = m_aBlood[i].m_NextPart;
		}
		Graphics()->QuadsEnd();
	}
}
Ejemplo n.º 28
0
void mixtureKEpsilon<BasicTurbulenceModel>::initMixtureFields()
{
    if (rhom_.valid()) return;

    // Local references to gas-phase properties
    const volScalarField& kg = this->k_;
    const volScalarField& epsilong = this->epsilon_;

    // Local references to liquid-phase properties
    mixtureKEpsilon<BasicTurbulenceModel>& turbc = this->liquidTurbulence();
    const volScalarField& kl = turbc.k_;
    const volScalarField& epsilonl = turbc.epsilon_;

    Ct2_.set
    (
        new volScalarField
        (
            IOobject
            (
                "Ct2",
                this->runTime_.timeName(),
                this->mesh_,
                IOobject::READ_IF_PRESENT,
                IOobject::AUTO_WRITE
            ),
            Ct2()
        )
    );

    rhom_.set
    (
        new volScalarField
        (
            IOobject
            (
                "rhom",
                this->runTime_.timeName(),
                this->mesh_,
                IOobject::READ_IF_PRESENT,
                IOobject::AUTO_WRITE
            ),
            rhom()
        )
    );

    km_.set
    (
        new volScalarField
        (
            IOobject
            (
                "km",
                this->runTime_.timeName(),
                this->mesh_,
                IOobject::READ_IF_PRESENT,
                IOobject::AUTO_WRITE
            ),
            mix(kl, kg),
            kl.boundaryField().types()
        )
    );
    correctInletOutlet(km_(), kl);

    epsilonm_.set
    (
        new volScalarField
        (
            IOobject
            (
                "epsilonm",
                this->runTime_.timeName(),
                this->mesh_,
                IOobject::READ_IF_PRESENT,
                IOobject::AUTO_WRITE
            ),
            mix(epsilonl, epsilong),
            epsilonBoundaryTypes(epsilonl)
        )
    );
    correctInletOutlet(epsilonm_(), epsilonl);
}
Ejemplo n.º 29
0
	template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> lerp(const detail::tvec3<T>& x, const detail::tvec3<T>& y, const detail::tvec3<T>& a){return mix(x, y, a);}	//!< \brief Returns the component-wise result of x * (1.0 - a) + y * a, i.e., the linear blend of x and y using vector a. The value for a is not restricted to the range [0, 1]. (From GLM_GTX_compatibility)
Ejemplo n.º 30
0
void CPlayers::RenderPlayer(
	const CNetObj_Character *pPrevChar,
	const CNetObj_Character *pPlayerChar,
	const CNetObj_PlayerInfo *pPrevInfo,
	const CNetObj_PlayerInfo *pPlayerInfo,
	int ClientID
	)
{
	CNetObj_Character Prev;
	CNetObj_Character Player;
	Prev = *pPrevChar;
	Player = *pPlayerChar;

	CNetObj_PlayerInfo pInfo = *pPlayerInfo;
	CTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID];

	// set size
	RenderInfo.m_Size = 64.0f;

	float IntraTick = Client()->IntraGameTick();

	if(Prev.m_Angle < pi*-128 && Player.m_Angle > pi*128)
		Prev.m_Angle += 2*pi*256;
	else if(Prev.m_Angle > pi*128 && Player.m_Angle < pi*-128)
		Player.m_Angle += 2*pi*256;
	float Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f;

	//float angle = 0;

	if(m_pClient->m_LocalClientID == ClientID && Client()->State() != IClient::STATE_DEMOPLAYBACK)
	{
		// just use the direct input if it's local player we are rendering
		Angle = angle(m_pClient->m_pControls->m_MousePos);
	}

	// use preditect players if needed
	if(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK)
	{
		if(!m_pClient->m_Snap.m_pLocalCharacter ||
			(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))
		{
		}
		else
		{
			// apply predicted results
			m_pClient->m_PredictedChar.Write07(&Player);
			m_pClient->m_PredictedPrevChar.Write07(&Prev);
			IntraTick = Client()->PredIntraGameTick();
		}
	}

	vec2 MotionDir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y);
	vec2 AimDir = direction(Angle);
	vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick);
	vec2 Vel = mix(vec2(Prev.m_VelX/256.0f, Prev.m_VelY/256.0f), vec2(Player.m_VelX/256.0f, Player.m_VelY/256.0f), IntraTick);
	
	m_pClient->m_pFlow->Add(Position, Vel*100.0f, 10.0f);

	bool GotAirJump = Player.m_Jumped&2?0:1;

	bool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1;
	bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16);
	bool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0);
	
	tu::CSkeletonRenderer SkeletonRenderer(TUKernel());
	SkeletonRenderer.SetAim(AimDir);
	SkeletonRenderer.SetMotion(MotionDir);
	
	const tu::CAsset_CharacterPart* pCharacterPart[6];
	tu::CAssetPath CharacterPath;
	for(int i=0; i<6; i++)
	{
		pCharacterPart[i] = TUKernel()->AssetsManager()->GetAsset<tu::CAsset_CharacterPart>(RenderInfo.m_aCharacterParts[i]);
		if(pCharacterPart[i])
		{
			SkeletonRenderer.AddSkinWithSkeleton(pCharacterPart[i]->GetSkeletonSkinPath(), RenderInfo.m_aColors[i]);
			if(CharacterPath.IsNull())
				CharacterPath = pCharacterPart[i]->GetCharacterPath();
		}
	}
	
	// Skin
	const tu::CAsset_Character* pCharacter = TUKernel()->AssetsManager()->GetAsset<tu::CAsset_Character>(CharacterPath);
	if(pCharacter)
	{
		if(InAir)
		{
			if(!GotAirJump && g_Config.m_ClAirjumpindicator)
			{
				SkeletonRenderer.ApplyAnimation(pCharacter->GetUncontrolledJumpPath(), 0.0f);
			}
			else
			{
				SkeletonRenderer.ApplyAnimation(pCharacter->GetControlledJumpPath(), 0.0f);
			}
		}
		else if(Stationary)
		{
			SkeletonRenderer.ApplyAnimation(pCharacter->GetIdlePath(), 0.0f);
		}
		else if(!WantOtherDir)
		{
			const float WalkTimeMagic = 100.0f;
			float WalkTime =
				((Position.x >= 0)
					? fmod(Position.x, WalkTimeMagic)
					: WalkTimeMagic - fmod(-Position.x, WalkTimeMagic))
				/ WalkTimeMagic;
			
			SkeletonRenderer.ApplyAnimation(pCharacter->GetWalkPath(), WalkTime);
		}
	}
	
	// Weapon
	static float s_LastGameTickTime = Client()->GameTickTime();
	if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
		s_LastGameTickTime = Client()->GameTickTime();
	
	float WeaponTime = clamp(5.0f*((Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime), 0.0f, 1.0f);
	switch(Player.m_Weapon)
	{
		case WEAPON_HAMMER:
			SkeletonRenderer.AddSkinWithSkeleton(tu::CAssetPath::Universe(tu::CAssetPath::TYPE_SKELETONSKIN, tu::SKELETONSKIN_HAMMER), vec4(1.0, 1.0, 1.0, 1.0));
			SkeletonRenderer.ApplyAnimation(tu::CAssetPath::Universe(tu::CAssetPath::TYPE_SKELETONANIMATION, tu::SKELETONANIMATION_HAMMERATTACK), WeaponTime);
			break;
	}
	
	// do skidding
	if(!InAir && WantOtherDir && length(Vel*50) > 500.0f)
	{
		static int64 SkidSoundTime = 0;
		if(time_get()-SkidSoundTime > time_freq()/10)
		{
			m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position);
			SkidSoundTime = time_get();
		}

		m_pClient->m_pEffects->SkidTrail(
			Position+vec2(-Player.m_Direction*6,12),
			vec2(-Player.m_Direction*100*length(Vel),-50)
		);
	}
	
	SkeletonRenderer.Finalize();
	SkeletonRenderer.RenderSkins(Position, 1.0);
	
	if(pInfo.m_PlayerFlags&PLAYERFLAG_CHATTING)
	{
		Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);
		Graphics()->QuadsBegin();
		RenderTools()->SelectSprite(SPRITE_DOTDOT);
		IGraphics::CQuadItem QuadItem(Position.x + 24, Position.y - 40, 64,64);
		Graphics()->QuadsDraw(&QuadItem, 1);
		Graphics()->QuadsEnd();
	}
	if (m_pClient->m_aClients[ClientID].m_EmoticonStart != -1 && m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() > Client()->GameTick())
	{
		Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);
		Graphics()->QuadsBegin();

		int SinceStart = Client()->GameTick() - m_pClient->m_aClients[ClientID].m_EmoticonStart;
		int FromEnd = m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() - Client()->GameTick();

		float a = 1;

		if (FromEnd < Client()->GameTickSpeed() / 5)
			a = FromEnd / (Client()->GameTickSpeed() / 5.0);

		float h = 1;
		if (SinceStart < Client()->GameTickSpeed() / 10)
			h = SinceStart / (Client()->GameTickSpeed() / 10.0);

		float Wiggle = 0;
		if (SinceStart < Client()->GameTickSpeed() / 5)
			Wiggle = SinceStart / (Client()->GameTickSpeed() / 5.0);

		float WiggleAngle = sinf(5*Wiggle);

		Graphics()->QuadsSetRotation(pi/6*WiggleAngle);

		Graphics()->SetColor(1.0f,1.0f,1.0f,a);
		// client_datas::emoticon is an offset from the first emoticon
		RenderTools()->SelectSprite(SPRITE_OOP + m_pClient->m_aClients[ClientID].m_Emoticon);
		IGraphics::CQuadItem QuadItem(Position.x, Position.y - 23 - 32*h, 64, 64*h);
		Graphics()->QuadsDraw(&QuadItem, 1);
		Graphics()->QuadsEnd();
	}
}