| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229 |
- #include "Game.h"
- #include <Logging.h>
- #include "AsynchronCall.h"
- #include "Chat.h"
- #include "Dimension.h"
- #include "Entity.h"
- #include "ItemEntity.h"
- #include "JsonUtils.h"
- #include "MultiblockTree.h"
- #include "NetworkMessage.h"
- #include "NoBlock.h"
- #include "Player.h"
- #include "PlayerHand.h"
- #include "PlayerRegister.h"
- #include "Quest.h"
- #include "RecipieLoader.h"
- #include "Server.h"
- #include "TickOrganizer.h"
- #include "UIController.h"
- #include "WorldGenerator.h"
- #include "WorldLoader.h"
- #include "Zeit.h"
- using namespace Framework;
- Framework::ConsoleHandler* Game::consoleHandler = 0;
- Framework::InputLine* Game::consoleInput = 0;
- Game::Game(Framework::Text name, Framework::Text worldsDir)
- : Thread(),
- name(name),
- typeRegistry(new TypeRegistry()),
- blockTypeNameFactory(new BlockTypeNameFactory()),
- itemTypeNameFactory(new ItemTypeNameFactory()),
- dimensions(new RCArray<Dimension>()),
- clients(new RCArray<GameClient>()),
- questManager(new QuestManager()),
- ticker(new TickOrganizer()),
- path((const char*)(worldsDir + "/" + name)),
- stop(0),
- tickId(0),
- nextEntityId(0),
- generator(0),
- loader(0),
- recipies(new RecipieLoader()),
- chat(0),
- playerRegister(new PlayerRegister(path)),
- uiController(new UIController()),
- totalTickTime(0),
- tickCounter(0),
- averageTickTime(0),
- ticksPerSecond(0),
- totalTime(0),
- blockTypes(0),
- blockTypeCount(0),
- itemTypes(0),
- itemTypeCount(0),
- entityTypes(0),
- entityTypeCount(0),
- multiblockStructureTypes(0),
- multiblockStructureTypeCount(0)
- {
- typeRegistry->registerType(
- BlockTypeNameFactory::TYPE_ID, blockTypeNameFactory);
- typeRegistry->registerType(
- ItemTypeNameFactory::TYPE_ID, itemTypeNameFactory);
- if (!DateiExistiert(path)) DateiPfadErstellen(path + "/");
- Datei d;
- d.setDatei(path + "/eid");
- if (d.existiert())
- {
- d.open(Datei::Style::lesen);
- d.lese((char*)&nextEntityId, 4);
- d.close();
- }
- start();
- }
- Game::~Game()
- {
- dimensions->release();
- clients->release();
- generator->release();
- loader->release();
- chat->release();
- playerRegister->release();
- typeRegistry->release();
- uiController->release();
- recipies->release();
- for (int i = 0; i < blockTypeCount; i++)
- {
- if (blockTypes[i]) blockTypes[i]->release();
- }
- delete[] blockTypes;
- for (int i = 0; i < itemTypeCount; i++)
- {
- if (itemTypes[i]) itemTypes[i]->release();
- }
- delete[] itemTypes;
- for (int i = 0; i < entityTypeCount; i++)
- {
- if (entityTypes[i]) entityTypes[i]->release();
- }
- delete[] entityTypes;
- for (int i = 0; i < multiblockStructureTypeCount; i++)
- {
- if (multiblockStructureTypes[i]) multiblockStructureTypes[i]->release();
- }
- delete[] multiblockStructureTypes;
- }
- void Game::initialize()
- {
- // TODO load mods libraries
- // load block types
- Framework::Logging::info() << "Loading block types";
- Framework::Array<BlockType*> blockTypeArray;
- Framework::Validator::DataValidator* validator
- = Framework::Validator::DataValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
- ->removeInvalidEntries()
- ->finishArray();
- loadAllJsonsFromDirectory("data/blocks",
- [this, &blockTypeArray, validator](
- Framework::JSON::JSONValue* zValue, Framework::Text path) {
- Framework::RCArray<Framework::Validator::ValidationResult>
- validationResults;
- Framework::JSON::JSONValue* validParts
- = validator->getValidParts(zValue, &validationResults);
- for (Framework::Validator::ValidationResult* result :
- validationResults)
- {
- Framework::Logging::error() << result->getInvalidInfo();
- }
- if (validParts)
- {
- for (Framework::JSON::JSONValue* value : *validParts->asArray())
- {
- BlockType* blockType
- = typeRegistry->fromJson<BlockType>(value);
- if (blockType)
- {
- blockTypeArray.add(blockType);
- }
- }
- validParts->release();
- }
- });
- validator->release();
- Framework::Logging::info() << "Loaded " << blockTypeArray.getEintragAnzahl()
- << " block types from data/blocks";
- blockTypes = new BlockType*[2 + blockTypeArray.getEintragAnzahl()];
- blockTypes[0] = new NoBlockBlockType(
- dynamic_cast<Block*>(NoBlock::INSTANCE.getThis()),
- "__not_yet_generated");
- blockTypes[1] = new NoBlockBlockType(
- dynamic_cast<Block*>(AirBlock::INSTANCE.getThis()), "Air");
- blockTypeCount = 2;
- for (BlockType* blockType : blockTypeArray)
- {
- blockTypes[blockTypeCount++] = blockType;
- }
- Framework::RCArray<Framework::Text>* blockTypeNames
- = new Framework::RCArray<Framework::Text>();
- for (int i = 0; i < blockTypeCount; i++)
- {
- blockTypeNames->add(new Framework::Text(blockTypes[i]->getName()));
- blockTypes[i]->setTypeId(i);
- }
- blockTypeNameFactory->setBlockTypeNames(blockTypeNames);
- Framework::Logging::info() << "Loading item types";
- Framework::Array<ItemType*> itemTypeArray;
- validator
- = Framework::Validator::DataValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
- ->removeInvalidEntries()
- ->finishArray();
- loadAllJsonsFromDirectory("data/items",
- [this, &itemTypeArray, validator](
- Framework::JSON::JSONValue* zValue, Framework::Text path) {
- Framework::RCArray<Framework::Validator::ValidationResult>
- validationResults;
- Framework::JSON::JSONValue* validParts
- = validator->getValidParts(zValue, &validationResults);
- for (Framework::Validator::ValidationResult* result :
- validationResults)
- {
- Framework::Logging::error() << result->getInvalidInfo();
- }
- if (validParts)
- {
- for (Framework::JSON::JSONValue* value : *validParts->asArray())
- {
- ItemType* itemType
- = typeRegistry->fromJson<ItemType>(value);
- if (itemType)
- {
- itemTypeArray.add(itemType);
- }
- }
- validParts->release();
- }
- });
- validator->release();
- Framework::Logging::info() << "Loaded " << itemTypeArray.getEintragAnzahl()
- << " item types from data/items";
- itemTypes
- = new ItemType*[blockTypeCount + itemTypeArray.getEintragAnzahl()];
- itemTypes[0] = new PlayerHandItemType();
- itemTypeCount = 1;
- for (int i = 0; i < blockTypeCount; i++)
- {
- ItemType* itemType = blockTypes[i]->createItemType();
- if (itemType)
- {
- itemTypes[itemTypeCount++] = itemType;
- }
- }
- for (ItemType* itemType : itemTypeArray)
- {
- itemTypes[itemTypeCount++] = itemType;
- }
- Framework::RCArray<Framework::Text>* itemTypeNames
- = new Framework::RCArray<Framework::Text>();
- for (int i = 0; i < itemTypeCount; i++)
- {
- itemTypes[i]->setTypeId(i);
- itemTypeNames->add(new Framework::Text(itemTypes[i]->getName()));
- }
- itemTypeNameFactory->setItemTypeNames(itemTypeNames);
- Framework::Logging::info() << "Loading entity types";
- Framework::Array<EntityType*> entityTypeArray;
- /*validator
- = Framework::JSON::Validator::JSONValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
- ->removeInvalidEntries()
- ->finishArray();
- loadAllJsonsFromDirectory("data/entities",
- [this, &entityTypeArray, validator](
- Framework::JSON::JSONValue* zValue, Framework::Text path) {
- Framework::RCArray<Framework::JSON::Validator::JSONValidationResult>
- validationResults;
- Framework::JSON::JSONValue* validParts
- = validator->getValidParts(zValue, &validationResults);
- for (Framework::JSON::Validator::JSONValidationResult* result :
- validationResults)
- {
- result->printInvalidInfo();
- }
- if (validParts)
- {
- for (Framework::JSON::JSONValue* value : *validParts->asArray())
- {
- EntityType* entityType
- = typeRegistry->fromJson<EntityType>(value);
- if (entityType)
- {
- entityTypeArray.add(entityType);
- }
- }
- validParts->release();
- }
- });
- validator->release();*/
- Framework::Logging::info()
- << "Loaded " << entityTypeArray.getEintragAnzahl()
- << " entity types from data/entities";
- entityTypes = new EntityType*[2 + entityTypeArray.getEintragAnzahl()];
- entityTypes[0] = new PlayerEntityType();
- entityTypes[1] = new ItemEntityType();
- entityTypeCount = 2;
- for (EntityType* entityType : entityTypeArray)
- {
- entityTypes[entityTypeCount++] = entityType;
- }
- for (int i = 0; i < entityTypeCount; i++)
- {
- entityTypes[i]->setTypeId(i);
- }
- // initialize loaded types
- bool allInitialized = false;
- while (!allInitialized)
- {
- allInitialized = true;
- for (int i = 0; i < blockTypeCount; i++)
- {
- if (blockTypes[i] && !blockTypes[i]->initialize(this))
- {
- Framework::Logging::error()
- << "Could not initialize Block Type '"
- << blockTypes[i]->getName() << "'.";
- blockTypes[i]->release();
- blockTypes[i] = 0;
- allInitialized = false;
- }
- }
- }
- allInitialized = false;
- while (!allInitialized)
- {
- allInitialized = true;
- for (int i = 0; i < itemTypeCount; i++)
- {
- if (itemTypes[i] && !itemTypes[i]->initialize(this))
- {
- Framework::Logging::error()
- << "Could not initialize Item Type '"
- << itemTypes[i]->getName() << "'.";
- itemTypes[i]->release();
- itemTypes[i] = 0;
- allInitialized = false;
- }
- }
- }
- allInitialized = false;
- while (!allInitialized)
- {
- allInitialized = true;
- for (int i = 0; i < entityTypeCount; i++)
- {
- if (entityTypes[i] && !entityTypes[i]->initialize(this))
- {
- Framework::Logging::error()
- << "Could not initialize Entity Type '"
- << entityTypes[i]->getName() << "'.";
- entityTypes[i]->release();
- entityTypes[i] = 0;
- allInitialized = false;
- }
- }
- }
- for (int i = 0; i < blockTypeCount; i++)
- {
- if (blockTypes[i])
- {
- blockTypes[i]->initializeDefault();
- }
- }
- multiblockStructureTypes = new MultiblockStructureType*[1];
- multiblockStructureTypes[0] = new MultiblockTreeStructureType();
- multiblockStructureTypeCount = 1;
- // save syntax info
- Framework::DateiRemove("data/syntax");
- // typeRegistry->writeSyntaxInfo("data/syntax");
- validator
- = Framework::Validator::DataValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
- ->finishArray();
- Framework::JSON::JSONObject* schema = validator->getJsonSchema();
- Framework::Datei syntaxFile;
- syntaxFile.setDatei("data/syntax/schema/blocks.json");
- syntaxFile.erstellen();
- syntaxFile.open(Framework::Datei::Style::schreiben);
- syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
- syntaxFile.close();
- schema->release();
- validator->release();
- validator
- = Framework::Validator::DataValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
- ->finishArray();
- schema = validator->getJsonSchema();
- syntaxFile.setDatei("data/syntax/schema/items.json");
- syntaxFile.erstellen();
- syntaxFile.open(Framework::Datei::Style::schreiben);
- syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
- syntaxFile.close();
- schema->release();
- validator->release();
- validator
- = Framework::Validator::DataValidator::buildForArray()
- ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
- ->finishArray();
- schema = validator->getJsonSchema();
- syntaxFile.setDatei("data/syntax/schema/entities.json");
- syntaxFile.erstellen();
- syntaxFile.open(Framework::Datei::Style::schreiben);
- syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
- syntaxFile.close();
- schema->release();
- validator->release();
- // initialize world generator and world loader
- int seed = 0;
- int index = 0;
- for (const char* n = name; *n; n++)
- seed += (int)pow((float)*n * 31, (float)++index);
- generator = new WorldGenerator(seed);
- loader = new WorldLoader();
- // load recipies
- recipies->loadRecipies("data");
- // initialize chat
- chat = new Chat();
- // load quests
- questManager->loadQuests();
- }
- void Game::thread()
- {
- ZeitMesser waitForLock;
- ZeitMesser removeOldClients;
- ZeitMesser tickEntities;
- ZeitMesser worldUpdates;
- ZeitMesser clientReply;
- ZeitMesser removeOldChunks;
- ZeitMesser m;
- ZeitMesser total;
- total.messungStart();
- double tickTime = 0;
- double sleepTime = 0;
- int nextTimeSync = MAX_TICKS_PER_SECOND;
- while (!stop)
- {
- m.messungStart();
- ticker->nextTick();
- actionsCs.lock();
- while (actions.getEintragAnzahl() > 0)
- {
- actions.get(0)();
- actions.remove(0);
- }
- actionsCs.unlock();
- Array<int> removed;
- double waitTotal = 0;
- waitForLock.messungStart();
- cs.lock();
- waitForLock.messungEnde();
- waitTotal += waitForLock.getSekunden();
- removeOldClients.messungStart();
- int index = 0;
- nextTimeSync--;
- for (auto player : *clients)
- {
- if (!player->isOnline())
- {
- uiController->removePlayerDialogs(player->zEntity()->getId());
- chat->removeObserver(player->zEntity()->getId());
- chat->broadcastMessage(
- Framework::Text(player->zEntity()->getName())
- + " left the game.",
- Chat::CHANNEL_INFO);
- Datei pFile;
- pFile.setDatei(path + "/player/"
- + getPlayerId(player->zEntity()->getName()));
- pFile.erstellen();
- if (pFile.open(Datei::Style::schreiben))
- zEntityType(EntityTypeEnum::PLAYER)
- ->saveEntity(player->zEntity(), &pFile);
- pFile.close();
- removed.add(index, 0);
- Dimension* dim
- = zDimension(player->zEntity()->getDimensionId());
- dim->removeSubscriptions(player->zEntity());
- Chunk* chunk = dim->zChunk(
- getChunkCenter((int)player->zEntity()->getLocation().x,
- (int)player->zEntity()->getLocation().y));
- if (chunk)
- {
- chunk->onEntityLeaves(player->zEntity(), 0);
- }
- dim->removeEntity(player->zEntity()->getId());
- }
- else
- {
- if (nextTimeSync <= 0 && player->zEntity())
- {
- Dimension* zDim
- = zDimension(player->zEntity()->getDimensionId());
- if (zDim)
- {
- NetworkMessage* msg = new NetworkMessage();
- msg->syncTime(zDim->getCurrentDayTime(),
- zDim->getNightDuration(),
- zDim->getNightTransitionDuration(),
- zDim->getDayDuration());
- player->sendResponse(msg);
- }
- }
- }
- index++;
- }
- if (nextTimeSync <= 0)
- {
- consoleHandler->print();
- nextTimeSync = MAX_TICKS_PER_SECOND;
- }
- for (auto i : removed)
- clients->remove(i);
- removeOldClients.messungEnde();
- cs.unlock();
- tickEntities.messungStart();
- for (auto dim : *dimensions)
- dim->tickEntities();
- tickEntities.messungEnde();
- waitForLock.messungStart();
- cs.lock();
- waitForLock.messungEnde();
- waitTotal += waitForLock.getSekunden();
- worldUpdates.messungStart();
- worldUpdates.messungEnde();
- cs.unlock();
- clientReply.messungStart();
- for (auto client : *clients)
- client->reply();
- clientReply.messungEnde();
- waitForLock.messungStart();
- cs.lock();
- waitForLock.messungEnde();
- waitTotal += waitForLock.getSekunden();
- removeOldChunks.messungStart();
- for (auto dim : *dimensions)
- dim->removeOldChunks();
- removeOldChunks.messungEnde();
- cs.unlock();
- m.messungEnde();
- double sec = m.getSekunden();
- tickCounter++;
- totalTickTime += sec;
- sleepTime += 1.0 / MAX_TICKS_PER_SECOND - tickTime;
- if (sleepTime > 0)
- {
- Sleep((int)(sleepTime * 1000));
- }
- total.messungEnde();
- total.messungStart();
- tickTime = total.getSekunden();
- totalTime += tickTime;
- if (totalTime >= 1)
- {
- averageTickTime = totalTickTime / tickCounter;
- ticksPerSecond = tickCounter;
- totalTickTime = 0;
- tickCounter = 0;
- totalTime = 0;
- }
- else if (sec > 1)
- {
- Framework::Logging::warning()
- << "tick needed " << sec
- << " seconds. The game will run sower then normal.\n";
- Framework::Logging::trace()
- << "waiting: " << waitTotal
- << "\nremoveOldClients: " << removeOldClients.getSekunden()
- << "\ntickEntities:" << tickEntities.getSekunden()
- << "\nworldUpdates: " << worldUpdates.getSekunden()
- << "\nclientReply: " << clientReply.getSekunden()
- << "\nremoveOldChunks:" << removeOldChunks.getSekunden();
- }
- }
- save();
- generator->exitAndWait();
- loader->exitAndWait();
- ticker->exitAndWait();
- for (Dimension* dim : *dimensions)
- dim->requestStopAndWait();
- Framework::Logging::info() << "Game thread exited";
- }
- void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
- {
- char type;
- zRequest->lese(&type, 1);
- NetworkMessage* response = new NetworkMessage();
- switch (type)
- {
- case 1: // world
- {
- Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
- if (!dim)
- {
- dim = generator->createDimension(
- zOrigin->zEntity()->getDimensionId());
- if (!dim)
- {
- Framework::Logging::error()
- << "could not create dimension "
- << zOrigin->zEntity()->getDimensionId()
- << ". No Factory was provided.";
- return;
- }
- addDimension(dim);
- }
- dim->api(zRequest, response, zOrigin->zEntity());
- break;
- }
- case 2: // player
- zOrigin->zEntity()->playerApi(zRequest, response);
- break;
- case 3: // entity
- {
- int id;
- zRequest->lese((char*)&id, 4);
- for (Dimension* dim : *dimensions)
- {
- Entity* entity = dim->zEntity(id);
- if (entity)
- {
- entity->api(zRequest, response, zOrigin->zEntity());
- break;
- }
- }
- break;
- }
- case 4:
- { // inventory
- bool isEntity;
- zRequest->lese((char*)&isEntity, 1);
- Inventory* target;
- if (isEntity)
- {
- int id;
- zRequest->lese((char*)&id, 4);
- target = zEntity(id);
- }
- else
- {
- int dim;
- Vec3<int> pos;
- zRequest->lese((char*)&dim, 4);
- zRequest->lese((char*)&pos.x, 4);
- zRequest->lese((char*)&pos.y, 4);
- zRequest->lese((char*)&pos.z, 4);
- target = zBlockAt(pos, dim, 0);
- }
- if (target)
- target->inventoryApi(zRequest, response, zOrigin->zEntity());
- break;
- }
- case 5:
- { // crafting uiml request
- int id;
- zRequest->lese((char*)&id, 4);
- Text uiml = recipies->getCrafingUIML(id);
- Text dialogId = "crafting_";
- dialogId += id;
- uiController->addDialog(new UIDialog(dialogId,
- zOrigin->zEntity()->getId(),
- new Framework::XML::Element(uiml)));
- break;
- }
- case 6:
- { // chat message
- chat->chatApi(zRequest, zOrigin->zEntity(), response);
- break;
- }
- case 7: // other dimension
- {
- int dimensionId;
- zRequest->lese((char*)&dimensionId, 4);
- Dimension* dim = zDimension(dimensionId);
- if (dim)
- {
- dim->api(zRequest, response, zOrigin->zEntity());
- }
- break;
- }
- case 8: // ui message
- {
- uiController->api(zRequest, response, zOrigin->zEntity());
- break;
- }
- default:
- Framework::Logging::warning()
- << "received unknown api request in game with type " << (int)type;
- }
- if (!response->isEmpty())
- {
- if (response->isBroadcast())
- broadcastMessage(response);
- else
- zOrigin->sendResponse(response);
- }
- else
- {
- response->release();
- }
- }
- void Game::updateLightning(int dimensionId, Vec3<int> location)
- {
- Dimension* zDim = zDimension(dimensionId);
- if (zDim) zDim->updateLightning(location);
- }
- void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
- {
- Dimension* zDim = zDimension(dimensionId);
- if (zDim) zDim->updateLightningWithoutWait(location);
- }
- void Game::broadcastMessage(NetworkMessage* response)
- {
- for (auto client : *clients)
- client->sendResponse(
- dynamic_cast<NetworkMessage*>(response->getThis()));
- response->release();
- }
- void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
- {
- for (auto client : *clients)
- {
- if (client->zEntity()->getId() == zTargetPlayer->getId())
- {
- client->sendResponse(response);
- return;
- }
- }
- response->release();
- }
- bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
- {
- if (playerRegister->checkSecret(name, secret))
- return 1;
- else
- {
- Framework::Logging::warning()
- << "player " << name.getText()
- << " tryed to connect with an invalid secret.";
- return 0;
- }
- }
- bool Game::existsPlayer(Framework::Text name)
- {
- return playerRegister->hasPlayer(name);
- }
- Framework::Text Game::createPlayer(Framework::Text name)
- {
- return playerRegister->addPlayer(name);
- }
- GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
- {
- cs.lock();
- int id = playerRegister->getPlayerId(name);
- Datei pFile;
- pFile.setDatei(path + "/player/" + id);
- Player* player;
- bool isNew = 0;
- if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
- {
- player = (Player*)zEntityType(EntityTypeEnum::PLAYER)
- ->createEntityAt(
- Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
- player->setName(name);
- isNew = 1;
- }
- else
- {
- player
- = (Player*)zEntityType(EntityTypeEnum::PLAYER)->loadEntity(&pFile);
- pFile.close();
- }
- if (player->getId() >= nextEntityId)
- {
- nextEntityId = player->getId() + 1;
- }
- GameClient* gameClient = new GameClient(player, client);
- gameClient->sendTypes();
- clients->add(gameClient);
- if (!zDimension(player->getDimensionId()))
- {
- Dimension* dim = generator->createDimension(player->getDimensionId());
- if (!dim)
- {
- Framework::Logging::error() << "could not create dimension "
- << (int)player->getDimensionId()
- << ". No Factory was provided.";
- return 0;
- }
- NetworkMessage* msg = new NetworkMessage();
- msg->syncTime(dim->getCurrentDayTime(),
- dim->getNightDuration(),
- dim->getNightTransitionDuration(),
- dim->getDayDuration());
- gameClient->sendResponse(msg);
- this->addDimension(dim);
- }
- // subscribe the new player as an observer of the new chunk
- Dimension* dim = zDimension(player->getDimensionId());
- InMemoryBuffer* buffer = new InMemoryBuffer();
- buffer->schreibe("\0", 1);
- Punkt center = getChunkCenter(
- (int)player->getPosition().x, (int)player->getPosition().y);
- buffer->schreibe((char*)¢er.x, 4);
- buffer->schreibe((char*)¢er.y, 4);
- buffer->schreibe("\0", 1);
- dim->api(buffer, 0, player);
- buffer->release();
- while (isNew
- && !dim->zChunk(getChunkCenter(
- (int)player->getPosition().x, (int)player->getPosition().y)))
- {
- cs.unlock();
- Sleep(1000);
- cs.lock();
- }
- if (isNew)
- {
- Either<Block*, int> b = BlockTypeEnum::AIR;
- int h = WORLD_HEIGHT;
- while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
- || (b.isB() && zBlockType(b)->zDefault()->isPassable()))
- && h > 0)
- b = zBlockAt({(int)player->getPosition().x,
- (int)player->getPosition().y,
- --h},
- player->getDimensionId(),
- 0);
- player->setPosition(
- {player->getPosition().x, player->getPosition().y, (float)h + 2.f});
- }
- Dimension* zDim = zDimension(player->getDimensionId());
- if (zDim)
- {
- zDim->addEntity(player);
- }
- else
- {
- Framework::Logging::error()
- << "could not add player to dimension "
- << (int)player->getDimensionId() << ". Dimension not loaded.";
- player->release();
- }
- chat->addObserver(gameClient->zEntity()->getId());
- chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
- cs.unlock();
- return dynamic_cast<GameClient*>(gameClient->getThis());
- }
- bool Game::isChunkLoaded(int x, int y, int dimension) const
- {
- Dimension* dim = zDimension(dimension);
- return (dim && dim->hasChunck(x, y));
- }
- bool Game::doesChunkExist(int x, int y, int dimension)
- {
- cs.lock();
- bool result = isChunkLoaded(x, y, dimension)
- || loader->existsChunk(x, y, dimension);
- cs.unlock();
- return result;
- }
- void Game::blockTargetChanged(Block* zBlock)
- {
- for (GameClient* client : *this->clients)
- {
- if (client->zEntity()->zTarget()
- && client->zEntity()->zTarget()->isBlock(
- zBlock->getPos(), NO_DIRECTION))
- {
- client->zEntity()->onTargetChange();
- }
- }
- }
- void Game::entityTargetChanged(Entity* zEntity)
- {
- for (GameClient* client : *this->clients)
- {
- if (client->zEntity()->zTarget()
- && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
- {
- client->zEntity()->onTargetChange();
- }
- }
- }
- void Game::spawnItem(
- Framework::Vec3<float> location, int dimensionId, Item* stack)
- {
- spawnItem(location, dimensionId, new ItemStack(stack, 1));
- }
- void Game::spawnItem(
- Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
- {
- ItemEntity* itemEntity
- = (ItemEntity*)zEntityType(EntityTypeEnum::ITEM)
- ->createEntity(
- location, dimensionId, Game::INSTANCE->getNextEntityId());
- itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
- stack->release();
- Dimension* dim = zDimension(dimensionId);
- if (dim)
- {
- dim->addEntity(itemEntity);
- }
- else
- {
- Framework::Logging::error()
- << "could not spawn item entity in dimension " << dimensionId
- << ". Dimension not loaded.";
- itemEntity->release();
- return;
- }
- }
- Framework::Either<Block*, int> Game::zBlockAt(
- Framework::Vec3<int> location, int dimension, OUT Chunk** zChunk) const
- {
- Dimension* dim = zDimension(dimension);
- if (dim) return dim->zBlock(location, zChunk);
- return 0;
- }
- Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
- {
- Dimension* dim = zDimension(dimension);
- if (dim) return dim->zRealBlockInstance(location);
- return 0;
- }
- const Block* Game::zConstBlock(Framework::Vec3<int> location, int dimension)
- {
- Dimension* dim = zDimension(dimension);
- if (dim) return dim->zBlockOrDefault(location);
- return 0;
- }
- int Game::getBlockType(Framework::Vec3<int> location, int dimension)
- {
- Dimension* dim = zDimension(dimension);
- if (dim) return dim->getBlockType(location);
- return 0;
- }
- Dimension* Game::zDimension(int id) const
- {
- for (auto dim : *dimensions)
- {
- if (dim->getDimensionId() == id) return dim;
- }
- return 0;
- }
- Framework::Punkt Game::getChunkCenter(int x, int y)
- {
- return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
- + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
- ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
- + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
- }
- Area Game::getChunckArea(Punkt center) const
- {
- return {center.x - CHUNK_SIZE / 2,
- center.y - CHUNK_SIZE / 2,
- center.x + CHUNK_SIZE / 2 - 1,
- center.y + CHUNK_SIZE / 2 - 1,
- 0};
- }
- Framework::Text Game::getWorldDirectory() const
- {
- return path;
- }
- void Game::requestArea(Area area)
- {
- generator->requestGeneration(area);
- loader->requestLoading(area);
- }
- void Game::save() const
- {
- questManager->saveQuests();
- Datei d;
- d.setDatei(path + "/eid");
- d.open(Datei::Style::schreiben);
- d.schreibe((char*)&nextEntityId, 4);
- d.close();
- playerRegister->save();
- for (auto dim : *dimensions)
- dim->save(path);
- chat->save();
- Framework::Logging::info() << "Game was saved";
- }
- void Game::requestStop()
- {
- stop = 1;
- warteAufThread(1000000);
- }
- void Game::addDimension(Dimension* d)
- {
- dimensions->add(d);
- }
- int Game::getNextEntityId()
- {
- cs.lock();
- int result = nextEntityId++;
- cs.unlock();
- return result;
- }
- WorldGenerator* Game::zGenerator() const
- {
- return generator;
- }
- Game* Game::INSTANCE = 0;
- void Game::initialize(Framework::Text name, Framework::Text worldsDir)
- {
- if (!Game::INSTANCE)
- {
- Game::INSTANCE = new Game(name, worldsDir);
- Game::INSTANCE->initialize();
- }
- }
- Entity* Game::zEntity(int id, int dimensionId) const
- {
- Dimension* d = zDimension(dimensionId);
- if (d) return d->zEntity(id);
- return 0;
- }
- Entity* Game::zEntity(int id) const
- {
- for (Dimension* d : *dimensions)
- {
- Entity* e = d->zEntity(id);
- if (e) return e;
- }
- // for new players that are currently loading
- for (GameClient* client : *clients)
- {
- if (client->zEntity()->getId() == id)
- {
- return client->zEntity();
- }
- }
- return 0;
- }
- Entity* Game::zNearestEntity(int dimensionId,
- Framework::Vec3<float> pos,
- std::function<bool(Entity*)> filter)
- {
- Dimension* d = zDimension(dimensionId);
- if (!d) return 0;
- return d->zNearestEntity(pos, filter);
- }
- RecipieLoader* Game::zRecipies() const
- {
- return recipies;
- }
- void Game::doLater(std::function<void()> action)
- {
- actionsCs.lock();
- actions.add(action);
- actionsCs.unlock();
- }
- TickOrganizer* Game::zTickOrganizer() const
- {
- return ticker;
- }
- Chat* Game::zChat() const
- {
- return chat;
- }
- Player* Game::zPlayerByName(const char* name) const
- {
- for (GameClient* client : *clients)
- {
- if (strcmp(client->zEntity()->getName(), name) == 0)
- {
- return client->zEntity();
- }
- }
- return 0;
- }
- void Game::listPlayerNames(Framework::RCArray<Framework::Text>& names)
- {
- for (GameClient* client : *clients)
- {
- names.add(new Framework::Text(client->zEntity()->getName()));
- }
- }
- TypeRegistry* Game::zTypeRegistry() const
- {
- return typeRegistry;
- }
- int Game::getPlayerId(const char* name) const
- {
- return playerRegister->getPlayerId(name);
- }
- QuestManager* Game::zQuestManager() const
- {
- return questManager;
- }
- UIController* Game::zUIController() const
- {
- return uiController;
- }
- double Game::getAverageTickTime() const
- {
- return averageTickTime;
- }
- int Game::getTicksPerSecond() const
- {
- return ticksPerSecond;
- }
- int Game::getPlayerCount() const
- {
- return clients->getEintragAnzahl();
- }
- int Game::getChunkCount() const
- {
- int result = 0;
- for (Dimension* dim : *dimensions)
- {
- result += dim->getChunkCount();
- }
- return result;
- }
- const BlockType* Game::zBlockType(int id) const
- {
- return blockTypes[id];
- }
- const ItemType* Game::zItemType(int id) const
- {
- return itemTypes[id];
- }
- const EntityType* Game::zEntityType(int id) const
- {
- return entityTypes[id];
- }
- int Game::getEntityTypeId(const char* name) const
- {
- for (int i = 0; i < entityTypeCount; i++)
- {
- if (entityTypes[i]
- && Framework::Text(entityTypes[i]->getName()).istGleich(name))
- {
- return i;
- }
- }
- Framework::Logging::warning()
- << "no entity type with name '" << name << "' found.";
- return -1;
- }
- int Game::getBlockTypeId(const char* name) const
- {
- for (int i = 0; i < blockTypeCount; i++)
- {
- if (blockTypes[i]
- && Framework::Text(blockTypes[i]->getName()).istGleich(name))
- {
- return i;
- }
- }
- Framework::Logging::warning()
- << "no block type with name '" << name << "' found.";
- return -1;
- }
- int Game::getItemTypeId(const char* name) const
- {
- for (int i = 0; i < itemTypeCount; i++)
- {
- if (itemTypes[i]
- && Framework::Text(itemTypes[i]->getName()).istGleich(name))
- {
- return i;
- }
- }
- Framework::Logging::warning()
- << "no item type with name '" << name << "' found.";
- return -1;
- }
- int Game::getBlockTypeCount() const
- {
- return blockTypeCount;
- }
- int Game::getItemTypeCount() const
- {
- return itemTypeCount;
- }
- int Game::getEntityTypeCount() const
- {
- return entityTypeCount;
- }
- const MultiblockStructureType* Game::zMultiblockStructureType(int id) const
- {
- return multiblockStructureTypes[id];
- }
- int Game::getMultiblockStructureTypeCount() const
- {
- return multiblockStructureTypeCount;
- }
|