Ir para conteúdo
  • Cadastre-se

OTClient Adicionando barra de carregamento nas criaturas


Posts Recomendados

 

Descrição: Com estas alterações nas sources do servidor e do OTC você conseguirá adicionar ao jogo uma barra de carregamento nas criaturas do jogo. Esta barra é personalizável e pode ser utilizada de diversas formas em diferentes scripts.

separador.png

Server sources.

No arquivo game.h

Abaixo de:

Spoiler



bool reload(ReloadTypes_t reloadType);

 

Adicione:

Spoiler



void startProgressbar(Creature* creature, uint32_t duration, bool ltr = true);

 

 

No arquivo game.cpp

Adicione:

Spoiler




void Game::startProgressbar(Creature* creature, uint32_t duration, bool ltr)
{
    SpectatorVec spectators;
    map.getSpectators(spectators, creature->getPosition(), false, true);
    for (Creature* spectator : spectators) {
        if (Player* tmpPlayer = spectator->getPlayer()) {
            tmpPlayer->sendProgressbar(creature->getID(), duration, ltr);
        }
    }
}

 

 

No arquivo luascript.h

Abaixo de:

Spoiler



static int luaCreatureGetZone(lua_State* L);

 

Adicione:

Spoiler



static int luaCreatureSetProgressbar(lua_State* L);

 

 

No arquivo luascript.cpp

Abaixo de:

Spoiler



	registerMethod("Creature", "getZone", LuaScriptInterface::luaCreatureGetZone)

 

Adicione:

Spoiler

 




	registerMethod("Creature", "sendProgressbar", LuaScriptInterface::luaCreatureSetProgressbar);

Abaixo de:

Spoiler

 





int LuaScriptInterface::luaCreatureGetZone(lua_State* L)
{
	// creature:getZone()
	Creature* creature = getUserdata<Creature>(L, 1);
	if (creature) {
		lua_pushnumber(L, creature->getZone());
	} else {
		lua_pushnil(L);
	}
	return 1;
}

Adicione:

Spoiler




int LuaScriptInterface::luaCreatureSetProgressbar(lua_State* L)
{
    // creature:sendProgressbar(duration, leftToRight)
    Creature* creature = getUserdata<Creature>(L, 1);
    uint32_t duration = getNumber<uint32_t>(L, 2);
    bool ltr = getBoolean(L, 3);
    if (creature) {
        g_game.startProgressbar(creature, duration, ltr);
        pushBoolean(L, true);
    }
    else {
        lua_pushnil(L);
    }

    return 1;
}

 

 

No arquivo player.h

Abaixo de:

Spoiler




		void sendNetworkMessage(const NetworkMessage& message) {
			if (client) {
				client->writeToOutputBuffer(message);
			}
		}

 

Adicione:

Spoiler




		void sendProgressbar(uint32_t id, uint32_t duration, bool ltr = true) {
            if (client) {
                client->sendProgressbar(id, duration, ltr);
            }
        }

 

 

No arquivo protocolgame.h

Abaixo de:

Spoiler



void sendModalWindow(const ModalWindow& modalWindow);

 

Adicione:

Spoiler



void sendProgressbar(uint32_t id, uint32_t duration, bool ltr = true);

 

 

No arquivo protocolgame.cpp

No final do arquivo adicione:

Spoiler




void ProtocolGame::sendProgressbar(uint32_t id, uint32_t duration, bool ltr)
{
    NetworkMessage msg;
    msg.addByte(0x3b);
    msg.add<uint32_t>(id);
    msg.add<uint32_t>(duration);
    msg.addByte(ltr);
    writeToOutputBuffer(msg);
}

 

 

Client sources.

No arquivo protocolcodes.cpp

Abaixo de:

Spoiler



        GameServerExtendedOpcode            = 50,

 

Adicione:

Spoiler



		GameServerProgressBar               = 59,

 

 

No arquivo protocolgame.h

Abaixo de:

Spoiler



    void parseChangeMapAwareRange(const InputMessagePtr& msg);

 

Adicione:

Spoiler



	void parseProgressBar(const InputMessagePtr& msg);

 

 

No arquivo protocolgameparse.cpp

Abaixo de:

Spoiler



            case Proto::GameServerChangeMapAwareRange:
                parseChangeMapAwareRange(msg);
                break;

 

Adicione:

Spoiler




			case Proto::GameServerProgressBar:
                parseProgressBar(msg);
                break;

 

Abaixo de:

Spoiler




void ProtocolGame::parseChangeMapAwareRange(const InputMessagePtr& msg)
{
    int xrange = msg->getU8();
    int yrange = msg->getU8();

    AwareRange range;
    range.left = xrange/2 - ((xrange+1) % 2);
    range.right = xrange/2;
    range.top = yrange/2 - ((yrange+1) % 2);
    range.bottom = yrange/2;

    g_map.setAwareRange(range);
    g_lua.callGlobalField("g_game", "onMapChangeAwareRange", xrange, yrange);
}

 

Adicione:

Spoiler

 





void ProtocolGame::parseProgressBar(const InputMessagePtr& msg)
{
    uint32 id = msg->getU32();
    uint32 duration = msg->getU32();
    bool ltr = msg->getU8();
    CreaturePtr creature = g_map.getCreatureById(id);
    if (creature)
        creature->setProgressBar(duration, ltr);
    else
        g_logger.traceError(stdext::format("could not get creature with id %d", id));
}

 

No arquivo creature.h

Abaixo de:

Spoiler




    virtual void onPositionChange(const Position& newPos, const Position& oldPos);
    virtual void onAppear();
    virtual void onDisappear();
    virtual void onDeath();

 

Adicione:

Spoiler




    // progress bar
    uint8 getProgressBarPercent() { return m_progressBarPercent; }
    void setProgressBar(uint32 duration, bool ltr);
    void updateProgressBar(uint32 duration, bool ltr);

 

Abaixo de:

Spoiler

 





    // jump related
    float m_jumpHeight;
    float m_jumpDuration;
    PointF m_jumpOffset;
    Timer m_jumpTimer;

Adicione:

Spoiler

 





    // progress bar
    uint8 m_progressBarPercent;
    ScheduledEventPtr m_progressBarUpdateEvent;
    Timer m_progressBarTimer;

 

No arquivo creature.cpp

Abaixo de:

Spoiler

 





    m_outfitColor = Color::white;

Adicione:

Spoiler




	m_progressBarPercent = 0;
    m_progressBarUpdateEvent = nullptr;

 

Substitua o código abaixo:

 

Spoiler




    // draw
    if(g_game.getFeature(Otc::GameBlueNpcNameColor) && isNpc() && m_healthPercent == 100 && !useGray)
        fillColor = Color(0x66, 0xcc, 0xff);

    if(drawFlags & Otc::DrawBars && (!isNpc() || !g_game.getFeature(Otc::GameHideNpcNames))) {
        g_painter->setColor(Color::black);
        g_painter->drawFilledRect(backgroundRect);

        g_painter->setColor(fillColor);
        g_painter->drawFilledRect(healthRect);

        if(drawFlags & Otc::DrawManaBar && isLocalPlayer()) {
            LocalPlayerPtr player = g_game.getLocalPlayer();
            if(player) {
                backgroundRect.moveTop(backgroundRect.bottom());

                g_painter->setColor(Color::black);
                g_painter->drawFilledRect(backgroundRect);

                Rect manaRect = backgroundRect.expanded(-1);
                double maxMana = player->getMaxMana();
                if(maxMana == 0) {
                    manaRect.setWidth(25);
                } else {
                    manaRect.setWidth(player->getMana() / (maxMana * 1.0) * 25);
                }

                g_painter->setColor(Color::blue);
                g_painter->drawFilledRect(manaRect);
            }
        }
    }

 

Por este código:

Spoiler




    // draw
    if(g_game.getFeature(Otc::GameBlueNpcNameColor) && isNpc() && m_healthPercent == 100 && !useGray)
        fillColor = Color(0x66, 0xcc, 0xff);

    if(drawFlags & Otc::DrawBars && (!isNpc() || !g_game.getFeature(Otc::GameHideNpcNames))) {
        g_painter->setColor(Color::black);
        g_painter->drawFilledRect(backgroundRect);

        g_painter->setColor(fillColor);
        g_painter->drawFilledRect(healthRect);

        if(drawFlags & Otc::DrawManaBar && isLocalPlayer()) {
            LocalPlayerPtr player = g_game.getLocalPlayer();
            if(player) {
                backgroundRect.moveTop(backgroundRect.bottom());

                g_painter->setColor(Color::black);
                g_painter->drawFilledRect(backgroundRect);

                Rect manaRect = backgroundRect.expanded(-1);
                double maxMana = player->getMaxMana();
                if(maxMana == 0) {
                    manaRect.setWidth(25);
                } else {
                    manaRect.setWidth(player->getMana() / (maxMana * 1.0) * 25);
                }

                g_painter->setColor(Color::blue);
                g_painter->drawFilledRect(manaRect);
            }
        }
		
		if (getProgressBarPercent()) {
            backgroundRect.moveTop(backgroundRect.bottom());

			g_painter->setColor(Color::black);
            g_painter->drawFilledRect(backgroundRect);
            //g_drawQueue->addFilledRect(backgroundRect, Color::black);

            Rect progressBarRect = backgroundRect.expanded(-1);
            double maxBar = 100;
            progressBarRect.setWidth(getProgressBarPercent() / (maxBar * 1.0) * 25);

			g_painter->setColor(Color::white);
            g_painter->drawFilledRect(progressBarRect);
            //g_drawQueue->addFilledRect(progressBarRect, Color::white);
		}
    }

 

 

E ainda no arquivo creature.cpp no final da página adicione:

Spoiler




void Creature::setProgressBar(uint32 duration, bool ltr)
{
    if (m_progressBarUpdateEvent) {
        m_progressBarUpdateEvent->cancel();
        m_progressBarUpdateEvent = nullptr;
    }

    if (duration > 0) {
        m_progressBarTimer.restart();
        updateProgressBar(duration, ltr);
    } else
        m_progressBarPercent = 0;

    callLuaField("onProgressBarStart", duration, ltr);
}

void Creature::updateProgressBar(uint32 duration, bool ltr)
{
    if (m_progressBarTimer.ticksElapsed() < duration) {
        if (ltr)
            m_progressBarPercent = abs(m_progressBarTimer.ticksElapsed() / static_cast<double>(duration) * 100);
        else
            m_progressBarPercent = abs((m_progressBarTimer.ticksElapsed() / static_cast<double>(duration) * 100) - 100);

        auto self = static_self_cast<Creature>();
        m_progressBarUpdateEvent = g_dispatcher.scheduleEvent([=] {
            self->updateProgressBar(duration, ltr);
        }, 50);
    } else {
        m_progressBarPercent = 0;
    }
    callLuaField("onProgressBarUpdate", m_progressBarPercent, duration, ltr);
}

 

 

 

Fim! Estas são todas as alterações! 

separador.png

Créditos:

EddyHavoc

Flatlander

Kondrah
Oen432

 

Editado por EddyHavoc (veja o histórico de edições)
Link para o post
Compartilhar em outros sites
  • 4 months later...

Muito dahora este tutorial Eddy, apenas lembrando que o mesmo foi feito pelo oen432, o mesmo pode ser visto no fórum gringo.

O Kondrah apenas adicionou o suporte pra ele no otcv8 2.6.

# Regras Gerais - TibiaKing.com #
Contato: [email protected]
Não respondo dúvidas via MP.


1C2tu.png4Tlqo.png1C2tu.png


 

Link para o post
Compartilhar em outros sites
3 horas atrás, Augusto disse:

Muito dahora este tutorial Eddy, apenas lembrando que o mesmo foi feito pelo oen432, o mesmo pode ser visto no fórum gringo.

O Kondrah apenas adicionou o suporte pra ele no otcv8 2.6.

 

Valeu pelo comentário @Augusto o Oen432 é um Monstro no OTC! Acredito que ele e o Reddington são atualmente os melhores na área. Adicionei os créditos a postagem. Muito obrigado por avisar.

Link para o post
Compartilhar em outros sites

Participe da conversa

Você pode postar agora e se cadastrar mais tarde. Se você tem uma conta, faça o login para postar com sua conta.

Visitante
Responder

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emojis são permitidos.

×   Seu link foi automaticamente incorporado.   Mostrar como link

×   Seu conteúdo anterior foi restaurado.   Limpar o editor

×   Não é possível colar imagens diretamente. Carregar ou inserir imagens do URL.

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

  • Conteúdo Similar

    • Por Kiman174
      GRIMHAVEN SEASON 4
      LAUNCHING APRIL 18TH 19:00 CEST
       
      Join our community and stay up to date:
      Official Discord Server
       
       
       
       
       
      Step into a world where passion meets innovation—welcome to Grimhaven MMORPG! Born from a heartfelt passion project, Grimhaven has evolved into an extraordinary realm where every pixel on our meticulously crafted Real Map tells a story. Leveraging the classic legacy of version 8.6 and elevated by inventive custom content, our server transcends traditional gameplay, inviting you into a living, breathing adventure at every turn.
       
       
      Explore sprawling landscapes, battle formidable foes, and uncover hidden lore as you journey through environments that blend classic mechanics with innovative systems. Every corner of Grimhaven pulses with life and mystery, inviting you to forge alliances, challenge epic quests, and redefine what you thought possible in an open Tibia server. With each update, our dedicated team pushes the envelope, ensuring that every raid, dungeon, and social encounter feels fresh and electrifying.
       
       
      Whether you're a seasoned adventurer or new to the realm, Grimhaven offers a thrilling escape into a world where the spirit of discovery and the thrill of combat come together in perfect harmony. Embrace the extraordinary—your adventure begins now in Grimhaven MMORPG!
       
       
      What Makes Grimhaven Stand Out?
       
      With over thousands of hours of development and 4000+ commits, Grimhaven stands out with its unique blend of classic and innovative MMORPG features. Built on an authentic Real Map with 8.6 mechanics and expanded with carefully designed custom content, the experience is unmatched. The server offers rates starting from 12x, stunning HD visuals, and intricately scripted quests that immerse you in a dynamic narrative. From challenging custom raid bosses to a refined item system inspired by classic action RPGs, every element is thoughtfully crafted to deliver an engaging and ever-evolving adventure, all backed by a dedicated team ensuring a top-tier gaming experience.
       
       
       
      Custom Zones :
      Explore meticulously designed zones that promise unique challenges and unparalleled rewards.
       

       
       
       
      Unique Randomly Generated Dungeons :
      As if that's not enough, brace yourselves for our unique dungeons. Each one is randomly generated, ensuring that no adventure is ever the same. The thrill of exploring the unknown awaits you in every twist and turn.
       


       

       
       


       
       
       
      Scripted and Mechanically Challenging Quests:
      Immerse yourself in intricately designed quests that push your strategic prowess and combat skills, all brought to life by the remarkable creativity of our quest designer and mapper.
       

       

       


       
       
      Mighty Bosses:
      Confront colossal adversaries, each boasting unique abilities and intricate mechanics that challenge your tactics and teamwork, turning every encounter into an unforgettable battle.
       


       
       
       
      Ancient and Mythic Monsters:
      Encounter legendary beasts, ancient guardians, and mythical creatures that not only test your skills and courage but also offer tougher challenges, richer loot drops, and enhanced experience rewards.
       

       
       
       
      Magical Attributes & Crafting:
      Discover a world of enchantment where magical items not only have a chance to drop in the wild, but can also be expertly crafted to bestow unique and powerful attributes on your gear.
       
       

       

       
       
       
      Custom Events :
      We keep the excitement rolling with unique, server-wide events that'll keep you on the edge of your seat. Expect the unexpected!
       
       



       
       
       
      This glimpse barely scratches the surface—there's a TON more content that would overwhelm this thread! To dive even deeper, visit our official wiki at Grimhaven Wiki (https://wiki.grimhaven.net) and create your account today at Latestnews - Grimhaven (https://www.grimhaven.net/) .   
       
      Gear up for an unforgettable adventure starting April 18th 19:00 CEST.
      Dive into a realm of epic rewards, heart-pounding quests, and intense PVP battles where you'll test your skills against others.
      Join a vibrant community of adventurers, embrace the thrill of discovery, and answer the call to glory on the battlefield!
    • Por yezzin
      FALA RAPAZIADA CANSADOS DE JOGAR EM SERVIDORES QUE FECHAM TODA HORA E ADM'S QUE NÃO LIGAM PARA O GAME?
      APRESENTO NTO STORM.

      ⚡NTO STORM⚡
       
       💖Versão 8.60 com OLD e OTC
       💖Task system;
       💖Saga system;
      💖 Outfit/skin system;
       💖Raridade system;
       💖Elo/Kage system;
       💖buff/Aura system;
      💖 Market system;
      💖 Autoloot system;
      💖 Mapa 100% proprio e novinho;
       💖Diversas quest de todos os niveis;
      💖 Vocaçao do dia;
       💖Cast System;
       💖Shop no Game
       💖Mercado Negro;
      💖Upgrade Set;
      💖Refinamento de Armas e Shields;
       💖Evento(castle,Guild castle, eventos, task, bonus, sorteios!
       
      https://discord.gg/un9uewM3Ds
      VOA !!
    • Por OT Archive
      OTClient Redemption (mehah) para navegadores
      Em nome da OTServList Brasil e do OT Archive, adaptei o OTClient Redemption para rodar em navegadores web.
       
       
      Source: https://github.com/mehah/otclient/pull/894 Guia de compilação e uso: https://github.com/OTArchive/otclient/wiki/Guia-‐-OTClient-Redemption-Web Demo sem assets: https://demo.otarchive.com Versão modular: https://webclient.otarchive.com Vídeo demonstrando o client se conectando a um servidor:  


       
       
      Em caso de dúvidas sobre o client web ou sobre servidores com suporte a websockets, por favor poste aqui.
       
      Disponibilizou um client web para seu servidor? Me avise para que eu inclua seu OT na categoria Web na OTServList Brasil, com um botão "Jogar Agora".
    • Por Heyron
      Elysia OT (Global Full 8.60)   IP: elysiaot-global.servegame.com   ✔︎ Login pelo Account Manager 1/1, não temos site. ✔︎ Login zerado é Cast System.   XP (Rates): Stages = Sim Experience = 50.0 Skill = 15.0 Magic = 5.0 Loot = 1.0 Spawn = 1.0 Protection Level: 30   ✔︎ Sem itens VIP. ✔︎ Premiação ao upar nível 20, 50 e 80. ✔︎ Itens iniciais por vocação. ✔︎ Free Bless até o level 50. ✔︎ Danos de spells balanceados. ✔︎ Sem fast attack ou ataque rápido (padrão 2seg). ✔︎ Sem itens infinitos, exceto munição de Paladin.           Jogue agora!   IP: elysiaot-global.servegame.com Versão: 8.60      
    • Por chateadoagr
      Bem-vindo ao Genesis Online Tibia (GOT), um mundo onde a civilização foi devastada por um apocalipse zumbi. Inspirado em referências como The Walking Dead e Resident Evil, o GOT desafia você a sobreviver em meio ao caos, enfrentando hordas de mortos-vivos, explorando ruínas perigosas e formando alianças estratégicas. Embarque nesta jornada épica de sobrevivência e descoberta, onde cada escolha molda seu destino em um cenário hostil repleto de desafios e perigos iminentes.
       
       
      Adentre o universo de Genesis Online Tibia (GOT), um jogo repleto de sistemas inovadores e emocionantes. Equipe-se com um vasto arsenal de armas para enfrentar as ameaças do apocalipse zumbi, enquanto o sistema autoloot simplifica suas conquistas. Desenvolva seu personagem através de um sistema de upgrade único, aprimorando habilidades e atributos para enfrentar desafios cada vez mais formidáveis.
       
      Explore um mundo imersivo onde o som desempenha um papel crucial, criando uma atmosfera envolvente e realista. Vasculhe cada canto em busca de recursos vitais, desvendando segredos e tesouros ocultos. Siga uma cativante história através de missões que expandem o enredo, revelando os mistérios por trás do apocalipse e oferecendo recompensas valiosas.
       
      Em Genesis Online Tibia, a jornada pela sobrevivência é repleta de ação, estratégia e emoção, convidando você a se aventurar em um mundo onde cada decisão molda seu destino e determina sua capacidade de enfrentar os desafios que aguardam.

      Em breve imagens do servidor!
       
       
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo