diff options
Diffstat (limited to 'Minecraft.World')
147 files changed, 1768 insertions, 2198 deletions
diff --git a/Minecraft.World/AABB.cpp b/Minecraft.World/AABB.cpp index 8bc8e140..f8e13497 100644 --- a/Minecraft.World/AABB.cpp +++ b/Minecraft.World/AABB.cpp @@ -47,20 +47,20 @@ void AABB::ReleaseThreadStorage() delete tls; } -AABB *AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, double z1) { return new AABB(x0, y0, z0, x1, y1, z1); } -void AABB::clearPool() +void AABB::clearPool() { } -void AABB::resetPool() +void AABB::resetPool() { } -AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, double z1) { ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); AABB *thisAABB = &tls->pool[tls->poolPointer]; @@ -69,7 +69,7 @@ AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, doubl return thisAABB; } -AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) +AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) { this->x0 = x0; this->y0 = y0; @@ -80,7 +80,7 @@ AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) } -AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1) { this->x0 = x0; this->y0 = y0; @@ -91,7 +91,7 @@ AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1 return this; } -AABB *AABB::expand(double xa, double ya, double za) +AABB *AABB::expand(double xa, double ya, double za) { double _x0 = x0; double _y0 = y0; @@ -112,7 +112,7 @@ AABB *AABB::expand(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::grow(double xa, double ya, double za) +AABB *AABB::grow(double xa, double ya, double za) { double _x0 = x0 - xa; double _y0 = y0 - ya; @@ -136,22 +136,22 @@ AABB *AABB::minmax(AABB *other) return newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::cloneMove(double xa, double ya, double za) +AABB *AABB::cloneMove(double xa, double ya, double za) { return AABB::newTemp(x0 + xa, y0 + ya, z0 + za, x1 + xa, y1 + ya, z1 + za); } -double AABB::clipXCollide(AABB *c, double xa) +double AABB::clipXCollide(AABB *c, double xa) { if (c->y1 <= y0 || c->y0 >= y1) return xa; if (c->z1 <= z0 || c->z0 >= z1) return xa; - if (xa > 0 && c->x1 <= x0) + if (xa > 0 && c->x1 <= x0) { double max = x0 - c->x1; if (max < xa) xa = max; } - if (xa < 0 && c->x0 >= x1) + if (xa < 0 && c->x0 >= x1) { double max = x1 - c->x0; if (max > xa) xa = max; @@ -165,12 +165,12 @@ double AABB::clipYCollide(AABB *c, double ya) if (c->x1 <= x0 || c->x0 >= x1) return ya; if (c->z1 <= z0 || c->z0 >= z1) return ya; - if (ya > 0 && c->y1 <= y0) + if (ya > 0 && c->y1 <= y0) { double max = y0 - c->y1; if (max < ya) ya = max; } - if (ya < 0 && c->y0 >= y1) + if (ya < 0 && c->y0 >= y1) { double max = y1 - c->y0; if (max > ya) ya = max; @@ -179,17 +179,17 @@ double AABB::clipYCollide(AABB *c, double ya) return ya; } -double AABB::clipZCollide(AABB *c, double za) +double AABB::clipZCollide(AABB *c, double za) { if (c->x1 <= x0 || c->x0 >= x1) return za; if (c->y1 <= y0 || c->y0 >= y1) return za; - if (za > 0 && c->z1 <= z0) + if (za > 0 && c->z1 <= z0) { double max = z0 - c->z1; if (max < za) za = max; } - if (za < 0 && c->z0 >= z1) + if (za < 0 && c->z0 >= z1) { double max = z1 - c->z0; if (max > za) za = max; @@ -198,7 +198,7 @@ double AABB::clipZCollide(AABB *c, double za) return za; } -bool AABB::intersects(AABB *c) +bool AABB::intersects(AABB *c) { if (c->x1 <= x0 || c->x0 >= x1) return false; if (c->y1 <= y0 || c->y0 >= y1) return false; @@ -206,7 +206,7 @@ bool AABB::intersects(AABB *c) return true; } -bool AABB::intersectsInner(AABB *c) +bool AABB::intersectsInner(AABB *c) { if (c->x1 < x0 || c->x0 > x1) return false; if (c->y1 < y0 || c->y0 > y1) return false; @@ -214,7 +214,7 @@ bool AABB::intersectsInner(AABB *c) return true; } -AABB *AABB::move(double xa, double ya, double za) +AABB *AABB::move(double xa, double ya, double za) { x0 += xa; y0 += ya; @@ -225,7 +225,7 @@ AABB *AABB::move(double xa, double ya, double za) return this; } -bool AABB::intersects(double x02, double y02, double z02, double x12, double y12, double z12) +bool AABB::intersects(double x02, double y02, double z02, double x12, double y12, double z12) { if (x12 <= x0 || x02 >= x1) return false; if (y12 <= y0 || y02 >= y1) return false; @@ -233,7 +233,7 @@ bool AABB::intersects(double x02, double y02, double z02, double x12, double y12 return true; } -bool AABB::contains(Vec3 *p) +bool AABB::contains(Vec3 *p) { if (p->x <= x0 || p->x >= x1) return false; if (p->y <= y0 || p->y >= y1) return false; @@ -242,7 +242,7 @@ bool AABB::contains(Vec3 *p) } // 4J Added -bool AABB::containsIncludingLowerBound(Vec3 *p) +bool AABB::containsIncludingLowerBound(Vec3 *p) { if (p->x < x0 || p->x >= x1) return false; if (p->y < y0 || p->y >= y1) return false; @@ -250,7 +250,7 @@ bool AABB::containsIncludingLowerBound(Vec3 *p) return true; } -double AABB::getSize() +double AABB::getSize() { double xs = x1 - x0; double ys = y1 - y0; @@ -258,7 +258,7 @@ double AABB::getSize() return (xs + ys + zs) / 3.0f; } -AABB *AABB::shrink(double xa, double ya, double za) +AABB *AABB::shrink(double xa, double ya, double za) { double _x0 = x0 + xa; double _y0 = y0 + ya; @@ -270,12 +270,12 @@ AABB *AABB::shrink(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::copy() +AABB *AABB::copy() { return AABB::newTemp(x0, y0, z0, x1, y1, z1); } -HitResult *AABB::clip(Vec3 *a, Vec3 *b) +HitResult *AABB::clip(Vec3 *a, Vec3 *b) { Vec3 *xh0 = a->clipX(b, x0); Vec3 *xh1 = a->clipX(b, x1); @@ -317,26 +317,26 @@ HitResult *AABB::clip(Vec3 *a, Vec3 *b) } -bool AABB::containsX(Vec3 *v) +bool AABB::containsX(Vec3 *v) { if (v == NULL) return false; return v->y >= y0 && v->y <= y1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsY(Vec3 *v) +bool AABB::containsY(Vec3 *v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsZ(Vec3 *v) +bool AABB::containsZ(Vec3 *v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->y >= y0 && v->y <= y1; } -void AABB::set(AABB *b) +void AABB::set(AABB *b) { x0 = b->x0; y0 = b->y0; @@ -346,9 +346,9 @@ void AABB::set(AABB *b) z1 = b->z1; } -wstring AABB::toString() +wstring AABB::toString() { - return L"box[" + _toString<double>(x0) + L", " + _toString<double>(y0) + L", " + _toString<double>(z0) + L" -> " + - _toString<double>(x1) + L", " + _toString<double>(y1) + L", " + _toString<double>(z1) + L"]"; + return L"box[" + std::to_wstring(x0) + L", " + std::to_wstring(y0) + L", " + std::to_wstring(z0) + L" -> " + + std::to_wstring(x1) + L", " + std::to_wstring(y1) + L", " + std::to_wstring(z1) + L"]"; } diff --git a/Minecraft.World/AbstractContainerMenu.cpp b/Minecraft.World/AbstractContainerMenu.cpp index 082e8008..57b0b177 100644 --- a/Minecraft.World/AbstractContainerMenu.cpp +++ b/Minecraft.World/AbstractContainerMenu.cpp @@ -48,27 +48,25 @@ void AbstractContainerMenu::addSlotListener(ContainerListener *listener) void AbstractContainerMenu::removeSlotListener(ContainerListener *listener) { - AUTO_VAR(it, std::find(containerListeners.begin(), containerListeners.end(), listener) ); + auto it = std::find(containerListeners.begin(), containerListeners.end(), listener); if(it != containerListeners.end()) containerListeners.erase(it); } vector<shared_ptr<ItemInstance> > *AbstractContainerMenu::getItems() { vector<shared_ptr<ItemInstance> > *items = new vector<shared_ptr<ItemInstance> >(); - AUTO_VAR(itEnd, slots.end()); - for (AUTO_VAR(it, slots.begin()); it != itEnd; it++) + for ( Slot* it : slots ) { - items->push_back((*it)->getItem()); + items->push_back(it->getItem()); } return items; } void AbstractContainerMenu::sendData(int id, int value) { - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + for ( auto& it : containerListeners ) { - (*it)->setContainerData(this, id, value); + it->setContainerData(this, id, value); } } @@ -86,10 +84,9 @@ void AbstractContainerMenu::broadcastChanges() lastSlots[i] = expected; m_bNeedsRendered = true; - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + for ( auto& it : containerListeners ) { - (*it)->slotChanged(this, i, expected); + it->slotChanged(this, i, expected); } } } @@ -122,10 +119,8 @@ bool AbstractContainerMenu::clickMenuButton(shared_ptr<Player> player, int butto Slot *AbstractContainerMenu::getSlotFor(shared_ptr<Container> c, int index) { - AUTO_VAR(itEnd, slots.end()); - for (AUTO_VAR(it, slots.begin()); it != itEnd; it++) + for ( Slot *slot : slots ) { - Slot *slot = *it; //slots->at(i); if (slot->isAt(c, index)) { return slot; @@ -197,10 +192,9 @@ shared_ptr<ItemInstance> AbstractContainerMenu::clicked(int slotIndex, int butto shared_ptr<ItemInstance> source = inventory->getCarried()->copy(); int remaining = inventory->getCarried()->count; - for(AUTO_VAR(it, quickcraftSlots.begin()); it != quickcraftSlots.end(); ++it) + for ( Slot *slot : quickcraftSlots ) { - Slot *slot = *it; - if (slot != NULL && canItemQuickReplace(slot, inventory->getCarried(), true) && slot->mayPlace(inventory->getCarried()) && inventory->getCarried()->count >= quickcraftSlots.size() && canDragTo(slot)) + if (slot != nullptr && canItemQuickReplace(slot, inventory->getCarried(), true) && slot->mayPlace(inventory->getCarried()) && inventory->getCarried()->count >= quickcraftSlots.size() && canDragTo(slot)) { shared_ptr<ItemInstance> copy = source->copy(); int carry = slot->hasItem() ? slot->getItem()->count : 0; @@ -582,7 +576,7 @@ void AbstractContainerMenu::setSynched(shared_ptr<Player> player, bool synched) { if (synched) { - AUTO_VAR(it, unSynchedPlayers.find(player)); + auto it = unSynchedPlayers.find(player); if(it != unSynchedPlayers.end()) unSynchedPlayers.erase( it ); } diff --git a/Minecraft.World/Animal.cpp b/Minecraft.World/Animal.cpp index 31de7d75..ecda8fc5 100644 --- a/Minecraft.World/Animal.cpp +++ b/Minecraft.World/Animal.cpp @@ -229,51 +229,58 @@ shared_ptr<Entity> Animal::findAttackTarget() if (getInLoveValue() > 0) { vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others->size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (p != shared_from_this() && p->getInLoveValue() > 0) + for (auto& it : *others) { - delete others; - return p; + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if (p != shared_from_this() && p->getInLoveValue() > 0) + { + delete others; + return p; + } } + delete others; } - delete others; } else { if (getAge() == 0) { vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), bb->grow(r, r, r)); - //for (int i = 0; i < players.size(); i++) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) + if ( players ) { - setDespawnProtected(); - - shared_ptr<Player> p = dynamic_pointer_cast<Player>(*it); - if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) + for (auto& it : *players) { - delete players; - return p; + setDespawnProtected(); + + shared_ptr<Player> p = dynamic_pointer_cast<Player>(it); + if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) + { + delete players; + return p; + } } + delete players; } - delete players; } else if (getAge() > 0) { vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others.size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (p != shared_from_this() && p->getAge() < 0) + for (auto& it : *others) { - delete others; - return p; + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if (p != shared_from_this() && p->getAge() < 0) + { + delete others; + return p; + } } + delete others; } - delete others; } } return nullptr; diff --git a/Minecraft.World/AnvilMenu.cpp b/Minecraft.World/AnvilMenu.cpp index 2ef00e3e..83d38142 100644 --- a/Minecraft.World/AnvilMenu.cpp +++ b/Minecraft.World/AnvilMenu.cpp @@ -134,64 +134,67 @@ void AnvilMenu::createResult() unordered_map<int, int> *additionalEnchantments = EnchantmentHelper::getEnchantments(addition); - for(AUTO_VAR(it, additionalEnchantments->begin()); it != additionalEnchantments->end(); ++it) + if ( additionalEnchantments ) { - int id = it->first; - Enchantment *enchantment = Enchantment::enchantments[id]; - AUTO_VAR(localIt, enchantments->find(id)); - int current = localIt != enchantments->end() ? localIt->second : 0; - int level = it->second; - level = (current == level) ? level += 1 : max(level, current); - int extra = level - current; - bool compatible = enchantment->canEnchant(input); - - if (player->abilities.instabuild || input->id == EnchantedBookItem::enchantedBook_Id) compatible = true; - - for(AUTO_VAR(it2, enchantments->begin()); it2 != enchantments->end(); ++it2) + for (const auto& it : *additionalEnchantments) { - int other = it2->first; - if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) + int id = it.first; + Enchantment* enchantment = Enchantment::enchantments[id]; + auto localIt = enchantments->find(id); + int current = localIt != enchantments->end() ? localIt->second : 0; + int level = it.second; + level = (current == level) ? level += 1 : std::max<int>(level, current); + int extra = level - current; + bool compatible = enchantment->canEnchant(input); + + if (player->abilities.instabuild || input->id == EnchantedBookItem::enchantedBook_Id) compatible = true; + + for (auto& it2 : *enchantments) { - compatible = false; - - price += extra; - if (DEBUG_COST) + int other = it2.first; + if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) { - app.DebugPrintf("Enchantment incompatibility fee; price is now %d (went up by %d)\n", price, extra); + compatible = false; + + price += extra; + if (DEBUG_COST) + { + app.DebugPrintf("Enchantment incompatibility fee; price is now %d (went up by %d)\n", price, extra); + } } } - } - if (!compatible) continue; - if (level > enchantment->getMaxLevel()) level = enchantment->getMaxLevel(); - (*enchantments)[id] = level; - int fee = 0; + if (!compatible) continue; + if (level > enchantment->getMaxLevel()) level = enchantment->getMaxLevel(); + (*enchantments)[id] = level; + int fee = 0; - switch (enchantment->getFrequency()) - { - case Enchantment::FREQ_COMMON: - fee = 1; - break; - case Enchantment::FREQ_UNCOMMON: - fee = 2; - break; - case Enchantment::FREQ_RARE: - fee = 4; - break; - case Enchantment::FREQ_VERY_RARE: - fee = 8; - break; - } + switch (enchantment->getFrequency()) + { + case Enchantment::FREQ_COMMON: + fee = 1; + break; + case Enchantment::FREQ_UNCOMMON: + fee = 2; + break; + case Enchantment::FREQ_RARE: + fee = 4; + break; + case Enchantment::FREQ_VERY_RARE: + fee = 8; + break; + } - if (usingBook) fee = max(1, fee / 2); + if (usingBook) fee = max(1, fee / 2); - price += fee * extra; - if (DEBUG_COST) - { - app.DebugPrintf("Enchantment increase fee; price is now %d (went up by %d)\n", price, fee*extra); + price += fee * extra; + if (DEBUG_COST) + { + app.DebugPrintf("Enchantment increase fee; price is now %d (went up by %d)\n", price, fee * extra); + } } + delete additionalEnchantments; } - delete additionalEnchantments; } } @@ -233,11 +236,11 @@ void AnvilMenu::createResult() } int count = 0; - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for( const auto& it : *enchantments ) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - int level = it->second; + int level = it.second; int fee = 0; count++; @@ -258,7 +261,7 @@ void AnvilMenu::createResult() break; } - if (usingBook) fee = max(1, fee / 2); + if (usingBook) fee = std::max<int>(1, fee / 2); tax += count + level * fee; if (DEBUG_COST) diff --git a/Minecraft.World/ArmorDyeRecipe.cpp b/Minecraft.World/ArmorDyeRecipe.cpp index 0f9c8955..c2f681fa 100644 --- a/Minecraft.World/ArmorDyeRecipe.cpp +++ b/Minecraft.World/ArmorDyeRecipe.cpp @@ -173,15 +173,11 @@ void ArmorDyeRecipe::requires(INGREDIENTS_REQUIRED *pIngReq) ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); #if 0 - AUTO_VAR(citEnd, ingredients->end()); - - for (vector<ItemInstance *>::const_iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( ItemInstance *expected : *ingredients ) { - ItemInstance *expected = *ingredient; - if (expected!=NULL) { - int iAuxVal = (*ingredient)->getAuxValue(); + int iAuxVal = expected->getAuxValue(); TempIngReq.uiGridA[iCount++]=expected->id | iAuxVal<<24; // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them in a 2x2 crafting screen if(iCount==2) iCount=3; diff --git a/Minecraft.World/Arrow.cpp b/Minecraft.World/Arrow.cpp index 743f966b..ab942aac 100644 --- a/Minecraft.World/Arrow.cpp +++ b/Minecraft.World/Arrow.cpp @@ -249,10 +249,8 @@ void Arrow::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for ( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects->at(i); if (!e->isPickable() || (e == owner && flightTime < 5)) continue; float rr = 0.3f; diff --git a/Minecraft.World/BaseAttributeMap.cpp b/Minecraft.World/BaseAttributeMap.cpp index 5a920f24..8fb1b1f1 100644 --- a/Minecraft.World/BaseAttributeMap.cpp +++ b/Minecraft.World/BaseAttributeMap.cpp @@ -4,9 +4,9 @@ BaseAttributeMap::~BaseAttributeMap() { - for(AUTO_VAR(it,attributesById.begin()); it != attributesById.end(); ++it) + for( auto& it : attributesById ) { - delete it->second; + delete it.second; } } @@ -17,7 +17,7 @@ AttributeInstance *BaseAttributeMap::getInstance(Attribute *attribute) AttributeInstance *BaseAttributeMap::getInstance(eATTRIBUTE_ID id) { - AUTO_VAR(it,attributesById.find(id)); + auto it = attributesById.find(id); if(it != attributesById.end()) { return it->second; @@ -30,9 +30,9 @@ AttributeInstance *BaseAttributeMap::getInstance(eATTRIBUTE_ID id) void BaseAttributeMap::getAttributes(vector<AttributeInstance *>& atts) { - for(AUTO_VAR(it,attributesById.begin()); it != attributesById.end(); ++it) + for( auto& it : attributesById ) { - atts.push_back(it->second); + atts.push_back(it.second); } } @@ -43,40 +43,44 @@ void BaseAttributeMap::onAttributeModified(ModifiableAttributeInstance *attribut void BaseAttributeMap::removeItemModifiers(shared_ptr<ItemInstance> item) { attrAttrModMap *modifiers = item->getAttributeModifiers(); - - for(AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + if ( modifiers ) { - AttributeInstance *attribute = getInstance(it->first); - AttributeModifier *modifier = it->second; - - if (attribute != NULL) + for (auto& it : *modifiers) { - attribute->removeModifier(modifier); + AttributeInstance* attribute = getInstance(it.first); + AttributeModifier* modifier = it.second; + + if (attribute != NULL) + { + attribute->removeModifier(modifier); + } + + delete modifier; } - delete modifier; + delete modifiers; } - - delete modifiers; } void BaseAttributeMap::addItemModifiers(shared_ptr<ItemInstance> item) { attrAttrModMap *modifiers = item->getAttributeModifiers(); - - for(AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + if ( modifiers ) { - AttributeInstance *attribute = getInstance(it->first); - AttributeModifier *modifier = it->second; - - if (attribute != NULL) + for (auto& it : *modifiers) { - attribute->removeModifier(modifier); - attribute->addModifier(new AttributeModifier(*modifier)); + AttributeInstance* attribute = getInstance(it.first); + AttributeModifier* modifier = it.second; + + if (attribute != NULL) + { + attribute->removeModifier(modifier); + attribute->addModifier(new AttributeModifier(*modifier)); + } + + delete modifier; } - - delete modifier; - } - delete modifiers; + delete modifiers; + } } diff --git a/Minecraft.World/BaseMobSpawner.cpp b/Minecraft.World/BaseMobSpawner.cpp index 887177ed..0e37e444 100644 --- a/Minecraft.World/BaseMobSpawner.cpp +++ b/Minecraft.World/BaseMobSpawner.cpp @@ -27,9 +27,9 @@ BaseMobSpawner::~BaseMobSpawner() { if(spawnPotentials) { - for(AUTO_VAR(it,spawnPotentials->begin()); it != spawnPotentials->end(); ++it) + for( auto& it : *spawnPotentials ) { - delete *it; + delete it; } delete spawnPotentials; } @@ -137,12 +137,14 @@ shared_ptr<Entity> BaseMobSpawner::loadDataAndAddEntity(shared_ptr<Entity> entit entity->save(data); vector<Tag *> *tags = getNextSpawnData()->tag->getAllTags(); - for (AUTO_VAR(it, tags->begin()); it != tags->end(); ++it) + if ( tags ) { - Tag *tag = *it; - data->put(tag->getName(), tag->copy()); + for (auto& tag : *tags) + { + data->put(tag->getName(), tag->copy()); + } + delete tags; } - delete tags; entity->load(data); if (entity->level != NULL) entity->level->addEntity(entity); @@ -159,12 +161,14 @@ shared_ptr<Entity> BaseMobSpawner::loadDataAndAddEntity(shared_ptr<Entity> entit mount->save(mountData); vector<Tag *> *ridingTags = ridingTag->getAllTags(); - for (AUTO_VAR(it, ridingTags->begin()); it != ridingTags->end(); ++it) + if ( ridingTags ) { - Tag *tag = *it; - mountData->put(tag->getName(), tag->copy()); + for (auto& tag : *ridingTags) + { + mountData->put(tag->getName(), tag->copy()); + } + delete ridingTags; } - delete ridingTags; mount->load(mountData); mount->moveTo(rider->x, rider->y, rider->z, rider->yRot, rider->xRot); @@ -274,11 +278,10 @@ void BaseMobSpawner::save(CompoundTag *tag) { ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); - if (spawnPotentials != NULL && spawnPotentials->size() > 0) + if (spawnPotentials && spawnPotentials->size() > 0) { - for (AUTO_VAR(it, spawnPotentials->begin()); it != spawnPotentials->end(); ++it) + for ( auto& data : *spawnPotentials ) { - SpawnData *data = *it; list->add(data->save()); } } diff --git a/Minecraft.World/BaseRailTile.cpp b/Minecraft.World/BaseRailTile.cpp index 8ec23fd6..db854bb3 100644 --- a/Minecraft.World/BaseRailTile.cpp +++ b/Minecraft.World/BaseRailTile.cpp @@ -142,10 +142,8 @@ bool BaseRailTile::Rail::connectsTo(Rail *rail) { if(m_bValidRail) { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( const auto& p : connections ) { - TilePos *p = *it; //connections[i]; if (p->x == rail->x && p->z == rail->z) { return true; @@ -159,10 +157,8 @@ bool BaseRailTile::Rail::hasConnection(int x, int y, int z) { if(m_bValidRail) { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( const auto& p : connections ) { - TilePos *p = *it; //connections[i]; if (p->x == x && p->z == z) { return true; @@ -332,10 +328,9 @@ void BaseRailTile::Rail::place(bool hasSignal, bool first) { level->setData(x, y, z, data, Tile::UPDATE_ALL); - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( auto& it : connections ) { - Rail *neighbor = getRail(*it); + Rail *neighbor = getRail(it); if (neighbor == NULL) continue; neighbor->removeSoftConnections(); diff --git a/Minecraft.World/BeaconTileEntity.cpp b/Minecraft.World/BeaconTileEntity.cpp index 9cfb0d67..d80eb906 100644 --- a/Minecraft.World/BeaconTileEntity.cpp +++ b/Minecraft.World/BeaconTileEntity.cpp @@ -80,21 +80,26 @@ void BeaconTileEntity::applyEffects() AABB *bb = AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(range, range, range); bb->y1 = level->getMaxBuildHeight(); vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), bb); - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if ( players ) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - player->addEffect(new MobEffectInstance(primaryPower, SharedConstants::TICKS_PER_SECOND * 9, baseAmp, true)); - } + for (auto& it : *players) + { + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + if ( player ) + player->addEffect(new MobEffectInstance(primaryPower, SharedConstants::TICKS_PER_SECOND * 9, baseAmp, true)); + } - if (levels >= 4 && primaryPower != secondaryPower && secondaryPower > 0) - { - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if (levels >= 4 && primaryPower != secondaryPower && secondaryPower > 0) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - player->addEffect(new MobEffectInstance(secondaryPower, SharedConstants::TICKS_PER_SECOND * 9, 0, true)); + for ( auto& it : *players ) + { + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + if ( player ) + player->addEffect(new MobEffectInstance(secondaryPower, SharedConstants::TICKS_PER_SECOND * 9, 0, true)); + } } + delete players; } - delete players; } } diff --git a/Minecraft.World/BedTile.cpp b/Minecraft.World/BedTile.cpp index 2023e23f..039943bd 100644 --- a/Minecraft.World/BedTile.cpp +++ b/Minecraft.World/BedTile.cpp @@ -108,10 +108,8 @@ bool BedTile::use(Level *level, int x, int y, int z, shared_ptr<Player> player, if (isOccupied(data)) { shared_ptr<Player> sleepingPlayer = nullptr; - AUTO_VAR(itEnd, level->players.end()); - for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++ ) + for ( auto& p : level->players ) { - shared_ptr<Player> p = *it; if (p->isSleeping()) { Pos pos = p->bedPosition; diff --git a/Minecraft.World/BehaviorRegistry.cpp b/Minecraft.World/BehaviorRegistry.cpp index 8689f129..5c314ad0 100644 --- a/Minecraft.World/BehaviorRegistry.cpp +++ b/Minecraft.World/BehaviorRegistry.cpp @@ -9,9 +9,9 @@ BehaviorRegistry::BehaviorRegistry(DispenseItemBehavior *defaultValue) BehaviorRegistry::~BehaviorRegistry() { - for(AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) + for( auto& it : storage ) { - delete it->second; + delete it.second; } delete defaultBehavior; @@ -19,7 +19,7 @@ BehaviorRegistry::~BehaviorRegistry() DispenseItemBehavior *BehaviorRegistry::get(Item *key) { - AUTO_VAR(it, storage.find(key)); + auto it = storage.find(key); return (it == storage.end()) ? defaultBehavior : it->second; } diff --git a/Minecraft.World/BiomeCache.cpp b/Minecraft.World/BiomeCache.cpp index 0d9c017c..b93ce32e 100644 --- a/Minecraft.World/BiomeCache.cpp +++ b/Minecraft.World/BiomeCache.cpp @@ -72,9 +72,9 @@ BiomeCache::~BiomeCache() // 4J Stu - Delete source? // delete source; - for(AUTO_VAR(it, all.begin()); it != all.end(); ++it) + for( auto& it : all ) { - delete (*it); + delete it; } DeleteCriticalSection(&m_CS); } @@ -86,7 +86,7 @@ BiomeCache::Block *BiomeCache::getBlockAt(int x, int z) x >>= ZONE_SIZE_BITS; z >>= ZONE_SIZE_BITS; __int64 slot = (((__int64) x) & 0xffffffffl) | ((((__int64) z) & 0xffffffffl) << 32l); - AUTO_VAR(it, cached.find(slot)); + auto it = cached.find(slot); Block *block = NULL; if (it == cached.end()) { @@ -130,7 +130,7 @@ void BiomeCache::update() { lastUpdateTime = now; - for (AUTO_VAR(it, all.begin()); it != all.end();) + for (auto it = all.begin(); it != all.end();) { Block *block = *it; __int64 time = now - block->lastUse; diff --git a/Minecraft.World/Boat.cpp b/Minecraft.World/Boat.cpp index c0c6a2cf..e39bd7f3 100644 --- a/Minecraft.World/Boat.cpp +++ b/Minecraft.World/Boat.cpp @@ -405,13 +405,12 @@ void Boat::tick() if(level->isClientSide) return; vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) + if (entities && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + auto riderPtr = rider.lock(); + for ( auto& e : *entities ) { - shared_ptr<Entity> e = (*it); // entities->at(i); - if (e != rider.lock() && e->isPushable() && e->GetType() == eTYPE_BOAT) + if (e != riderPtr && e->isPushable() && e->GetType() == eTYPE_BOAT) { e->push(shared_from_this()); } diff --git a/Minecraft.World/BoatItem.cpp b/Minecraft.World/BoatItem.cpp index d5628f09..d2bb75b5 100644 --- a/Minecraft.World/BoatItem.cpp +++ b/Minecraft.World/BoatItem.cpp @@ -81,10 +81,9 @@ shared_ptr<ItemInstance> BoatItem::use(shared_ptr<ItemInstance> itemInstance, Le bool hitEntity = false; float overlap = 1; vector<shared_ptr<Entity> > *objects = level->getEntities(player, player->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); - //for (int i = 0; i < objects.size(); i++) { - for(AUTO_VAR(it, objects->begin()); it != objects->end(); ++it) + + for( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects.get(i); if (!e->isPickable()) continue; float rr = e->getPickRadius(); diff --git a/Minecraft.World/BoundingBox.cpp b/Minecraft.World/BoundingBox.cpp index 24972bf9..74dba470 100644 --- a/Minecraft.World/BoundingBox.cpp +++ b/Minecraft.World/BoundingBox.cpp @@ -175,7 +175,7 @@ int BoundingBox::getZCenter() wstring BoundingBox::toString() { - return L"(" + _toString<int>(x0) + L", " + _toString<int>(y0) + L", " + _toString<int>(z0) + L"; " + _toString<int>(x1) + L", " + _toString<int>(y1) + L", " + _toString<int>(z1) + L")"; + return L"(" + std::to_wstring(x0) + L", " + std::to_wstring(y0) + L", " + std::to_wstring(z0) + L"; " + std::to_wstring(x1) + L", " + std::to_wstring(y1) + L", " + std::to_wstring(z1) + L")"; } IntArrayTag *BoundingBox::createTag(const wstring &name) diff --git a/Minecraft.World/BreedGoal.cpp b/Minecraft.World/BreedGoal.cpp index ce2d8fff..1c46fd90 100644 --- a/Minecraft.World/BreedGoal.cpp +++ b/Minecraft.World/BreedGoal.cpp @@ -53,16 +53,19 @@ shared_ptr<Animal> BreedGoal::getFreePartner() vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*animal), animal->bb->grow(r, r, r)); double dist = Double::MAX_VALUE; shared_ptr<Animal> partner = nullptr; - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (animal->canMate(p) && animal->distanceToSqr(p) < dist) + for ( auto& it : *others ) { - partner = p; - dist = animal->distanceToSqr(p); + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if ( p && animal->canMate(p) && animal->distanceToSqr(p) < dist) + { + partner = p; + dist = animal->distanceToSqr(p); + } } + delete others; } - delete others; return partner; } diff --git a/Minecraft.World/BrewingStandMenu.cpp b/Minecraft.World/BrewingStandMenu.cpp index eaf78329..4f9e2ac3 100644 --- a/Minecraft.World/BrewingStandMenu.cpp +++ b/Minecraft.World/BrewingStandMenu.cpp @@ -40,10 +40,8 @@ void BrewingStandMenu::broadcastChanges() { AbstractContainerMenu::broadcastChanges(); - //for (int i = 0; i < containerListeners->size(); i++) - for(AUTO_VAR(it, containerListeners.begin()); it != containerListeners.end(); ++it) + for( auto& listener : containerListeners ) { - ContainerListener *listener = *it; //containerListeners.at(i); if (tc != brewingStand->getBrewTime()) { listener->setContainerData(this, 0, brewingStand->getBrewTime()); diff --git a/Minecraft.World/C4JThread.cpp b/Minecraft.World/C4JThread.cpp index 4b9760c1..d0794f06 100644 --- a/Minecraft.World/C4JThread.cpp +++ b/Minecraft.World/C4JThread.cpp @@ -183,7 +183,7 @@ C4JThread::~C4JThread() EnterCriticalSection(&ms_threadListCS); - for( AUTO_VAR(it,ms_threadList.begin()); it != ms_threadList.end(); it++ ) + for (auto it = ms_threadList.begin(); it != ms_threadList.end(); it++) { if( (*it) == this ) { diff --git a/Minecraft.World/CarrotTile.cpp b/Minecraft.World/CarrotTile.cpp index 677ab78a..8841e199 100644 --- a/Minecraft.World/CarrotTile.cpp +++ b/Minecraft.World/CarrotTile.cpp @@ -37,6 +37,6 @@ void CarrotTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < 4; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString(i)); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i)); } }
\ No newline at end of file diff --git a/Minecraft.World/CaveFeature.cpp b/Minecraft.World/CaveFeature.cpp index 698ee3da..adb5d446 100644 --- a/Minecraft.World/CaveFeature.cpp +++ b/Minecraft.World/CaveFeature.cpp @@ -70,17 +70,13 @@ bool CaveFeature::place(Level *level, Random *random, int x, int y, int z) } } - AUTO_VAR(itEnd, toRemove.end()); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) + for ( auto& p : toRemove ) { - TilePos *p = *it; //toRemove[i]; level->setTileAndData(p->x, p->y, p->z, 0, 0, Tile::UPDATE_CLIENTS); } - itEnd = toRemove.end(); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) + for ( auto& p : toRemove ) { - TilePos *p = *it; //toRemove[i]; if (level->getTile(p->x, p->y - 1, p->z) == Tile::dirt_Id && level->getDaytimeRawBrightness(p->x, p->y, p->z) > 8) { level->setTileAndData(p->x, p->y - 1, p->z, Tile::grass_Id, 0, Tile::UPDATE_CLIENTS); diff --git a/Minecraft.World/ChestTile.cpp b/Minecraft.World/ChestTile.cpp index a4894c86..11178b8a 100644 --- a/Minecraft.World/ChestTile.cpp +++ b/Minecraft.World/ChestTile.cpp @@ -337,16 +337,19 @@ int ChestTile::getDirectSignal(LevelSource *level, int x, int y, int z, int dir) bool ChestTile::isCatSittingOnChest(Level *level, int x, int y, int z) { vector<shared_ptr<Entity> > *entities = level->getEntitiesOfClass(typeid(Ocelot), AABB::newTemp(x, y + 1, z, x + 1, y + 2, z + 1)); - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - shared_ptr<Ocelot> ocelot = dynamic_pointer_cast<Ocelot>(*it); - if(ocelot->isSitting()) + for (auto& it : *entities) { - delete entities; - return true; + shared_ptr<Ocelot> ocelot = dynamic_pointer_cast<Ocelot>(it); + if ( ocelot && ocelot->isSitting()) + { + delete entities; + return true; + } } + delete entities; } - delete entities; return false; } diff --git a/Minecraft.World/ChestTileEntity.cpp b/Minecraft.World/ChestTileEntity.cpp index fded7d28..b8f323f4 100644 --- a/Minecraft.World/ChestTileEntity.cpp +++ b/Minecraft.World/ChestTileEntity.cpp @@ -271,23 +271,26 @@ void ChestTileEntity::tick() float range = 5; vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), AABB::newTemp(x - range, y - range, z - range, x + 1 + range, y + 1 + range, z + 1 + range)); - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if ( players ) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - - ContainerMenu *containerMenu = dynamic_cast<ContainerMenu*>(player->containerMenu); - if (containerMenu != NULL) + for (auto& it : *players) { - shared_ptr<Container> container = containerMenu->getContainer(); - shared_ptr<Container> thisContainer = dynamic_pointer_cast<Container>(shared_from_this()); - shared_ptr<CompoundContainer> compoundContainer = dynamic_pointer_cast<CompoundContainer>( container ); - if ( (container == thisContainer) || (compoundContainer != NULL && compoundContainer->contains(thisContainer)) ) + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + + ContainerMenu* containerMenu = dynamic_cast<ContainerMenu*>(player->containerMenu); + if (containerMenu) { - openCount++; + shared_ptr<Container> container = containerMenu->getContainer(); + shared_ptr<Container> thisContainer = dynamic_pointer_cast<Container>(shared_from_this()); + shared_ptr<CompoundContainer> compoundContainer = dynamic_pointer_cast<CompoundContainer>(container); + if ((container == thisContainer) || (compoundContainer != NULL && compoundContainer->contains(thisContainer))) + { + openCount++; + } } } + delete players; } - delete players; } oOpenness = openness; diff --git a/Minecraft.World/ChunkPos.cpp b/Minecraft.World/ChunkPos.cpp index 3f9674a7..ff1c34f0 100644 --- a/Minecraft.World/ChunkPos.cpp +++ b/Minecraft.World/ChunkPos.cpp @@ -53,14 +53,14 @@ int ChunkPos::getMiddleBlockZ() return ( z << 4 ) + 8; } -TilePos ChunkPos::getMiddleBlockPosition(int y) +TilePos ChunkPos::getMiddleBlockPosition(int y) { return TilePos(getMiddleBlockX(), y, getMiddleBlockZ()); } wstring ChunkPos::toString() { - return L"[" + _toString<int>(x) + L", " + _toString<int>(z) + L"]"; + return L"[" + std::to_wstring(x) + L", " + std::to_wstring(z) + L"]"; } __int64 ChunkPos::hash_fnct(const ChunkPos &k) diff --git a/Minecraft.World/Class.h b/Minecraft.World/Class.h index 31fc4dad..25802c3f 100644 --- a/Minecraft.World/Class.h +++ b/Minecraft.World/Class.h @@ -371,9 +371,9 @@ public: m_parents.push_back(id); - for (AUTO_VAR(itr, parent->m_parents.begin()); itr != parent->m_parents.end(); itr++) + for ( auto& it : parent->m_parents ) { - m_parents.push_back(*itr); + m_parents.push_back(it); } return this; diff --git a/Minecraft.World/ClothTile.cpp b/Minecraft.World/ClothTile.cpp index 70ba4837..8c18b01c 100644 --- a/Minecraft.World/ClothTile.cpp +++ b/Minecraft.World/ClothTile.cpp @@ -33,6 +33,6 @@ void ClothTile::registerIcons(IconRegister *iconRegister) for (int i = 0; i < 16; i++) { - icons[i] = iconRegister->registerIcon(L"cloth_" + _toString(i) ); + icons[i] = iconRegister->registerIcon(L"cloth_" + std::to_wstring(i) ); } }
\ No newline at end of file diff --git a/Minecraft.World/CombatTracker.cpp b/Minecraft.World/CombatTracker.cpp index 77aac68a..2d35913c 100644 --- a/Minecraft.World/CombatTracker.cpp +++ b/Minecraft.World/CombatTracker.cpp @@ -13,9 +13,9 @@ CombatTracker::CombatTracker(LivingEntity *mob) CombatTracker::~CombatTracker() { - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( auto& it : entries ) { - delete (*it); + delete it; } } @@ -138,9 +138,8 @@ shared_ptr<LivingEntity> CombatTracker::getKiller() float bestMobDamage = 0; float bestPlayerDamage = 0; - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( CombatEntry *entry : entries ) { - CombatEntry *entry = *it; if ( entry->getSource() != NULL && entry->getSource()->getEntity() != NULL && entry->getSource()->getEntity()->instanceof(eTYPE_PLAYER) && (bestPlayer == NULL || entry->getDamage() > bestPlayerDamage)) { bestPlayerDamage = entry->getDamage(); @@ -241,9 +240,9 @@ void CombatTracker::recheckStatus() if (takingDamage && mob->tickCount - lastDamageTime > reset) { - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( auto& it : entries ) { - delete (*it); + delete it; } entries.clear(); takingDamage = false; diff --git a/Minecraft.World/CommandDispatcher.cpp b/Minecraft.World/CommandDispatcher.cpp index 545063db..45b3f5fe 100644 --- a/Minecraft.World/CommandDispatcher.cpp +++ b/Minecraft.World/CommandDispatcher.cpp @@ -4,7 +4,7 @@ int CommandDispatcher::performCommand(shared_ptr<CommandSender> sender, EGameCommand command, byteArray commandData) { - AUTO_VAR(it, commandsById.find(command)); + auto it = commandsById.find(command); if(it != commandsById.end()) { diff --git a/Minecraft.World/CompoundTag.h b/Minecraft.World/CompoundTag.h index 29d35041..f3a711d2 100644 --- a/Minecraft.World/CompoundTag.h +++ b/Minecraft.World/CompoundTag.h @@ -22,10 +22,9 @@ public: void write(DataOutput *dos) { - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<wstring, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& tag : tags ) { - Tag::writeNamedTag(it->second, dos); + Tag::writeNamedTag(tag.second, dos); } dos->writeByte(Tag::TAG_End); } @@ -55,10 +54,9 @@ public: // 4J - was return tags.values(); vector<Tag *> *ret = new vector<Tag *>; - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<wstring, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& tag : tags ) { - ret->push_back(it->second); + ret->push_back(tag.second); } return ret; } @@ -130,7 +128,7 @@ public: Tag *get(const wstring &name) { - AUTO_VAR(it, tags.find(name)); + auto it = tags.find(name); if(it != tags.end()) return it->second; return NULL; } @@ -213,7 +211,7 @@ public: void remove(const wstring &name) { - AUTO_VAR(it, tags.find(name)); + auto it = tags.find(name); if(it != tags.end()) tags.erase(it); //tags.remove(name); } @@ -222,7 +220,7 @@ public: { static const int bufSize = 32; static wchar_t buf[bufSize]; - swprintf(buf,bufSize,L"%d entries",tags.size()); + swprintf(buf,bufSize,L"%zu entries",tags.size()); return wstring( buf ); } @@ -236,10 +234,9 @@ public: strcpy( newPrefix, prefix); strcat( newPrefix, " "); - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<string, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& it : tags ) { - it->second->print(newPrefix, out); + it.second->print(newPrefix, out); } delete[] newPrefix; out << prefix << "}" << endl; @@ -253,10 +250,9 @@ public: virtual ~CompoundTag() { - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& tag : tags ) { - delete it->second; + delete tag.second; } } @@ -264,10 +260,9 @@ public: { CompoundTag *tag = new CompoundTag(getName()); - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& it : tags ) { - tag->put((wchar_t *)it->first.c_str(), it->second->copy()); + tag->put((wchar_t *)it.first.c_str(), it.second->copy()); } return tag; } @@ -281,11 +276,10 @@ public: if(tags.size() == o->tags.size()) { bool equal = true; - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& it : tags ) { - AUTO_VAR(itFind, o->tags.find(it->first)); - if(itFind == o->tags.end() || !it->second->equals(itFind->second) ) + auto itFind = o->tags.find(it.first); + if(itFind == o->tags.end() || !it.second->equals(itFind->second) ) { equal = false; break; diff --git a/Minecraft.World/ConsoleSaveFileConverter.cpp b/Minecraft.World/ConsoleSaveFileConverter.cpp index 16b025a5..21de3cbe 100644 --- a/Minecraft.World/ConsoleSaveFileConverter.cpp +++ b/Minecraft.World/ConsoleSaveFileConverter.cpp @@ -273,27 +273,29 @@ void ConsoleSaveFileConverter::ConvertSave(ConsoleSaveFile *sourceSave, ConsoleS // 4J Stu - Old version that just changes the compression of chunks, not usable for XboxOne style split saves or compressed tile formats // Process region files vector<FileEntry *> *allFilesInSave = sourceSave->getFilesWithPrefix(wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) + if ( allFilesInSave ) { - FileEntry *fe = *it; - if( fe != sourceLdatFe ) + for ( FileEntry* fe : *allFilesInSave ) { - wstring fName( fe->data.filename ); - wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) + if (fe != sourceLdatFe) { + wstring fName(fe->data.filename); + wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0) + { #ifndef _CONTENT_PACKAGE - wprintf(L"Processing a region file: %s\n", fe->data.filename); + wprintf(L"Processing a region file: %s\n", fe->data.filename); #endif - ProcessStandardRegionFile(sourceSave, File(fe->data.filename), targetSave, File(fe->data.filename) ); - } - else - { + ProcessStandardRegionFile(sourceSave, File(fe->data.filename), targetSave, File(fe->data.filename)); + } + else + { #ifndef _CONTENT_PACKAGE - wprintf(L"%s is not a region file, ignoring\n", fe->data.filename); + wprintf(L"%s is not a region file, ignoring\n", fe->data.filename); #endif + } } } - } #endif + } }
\ No newline at end of file diff --git a/Minecraft.World/ConsoleSaveFileOriginal.cpp b/Minecraft.World/ConsoleSaveFileOriginal.cpp index 8e6f58c6..3a2b5ef1 100644 --- a/Minecraft.World/ConsoleSaveFileOriginal.cpp +++ b/Minecraft.World/ConsoleSaveFileOriginal.cpp @@ -1043,19 +1043,21 @@ void ConsoleSaveFileOriginal::ConvertToLocalPlatform() } // convert each of the region files to the local platform vector<FileEntry *> *allFilesInSave = getFilesWithPrefix(wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) + if ( allFilesInSave ) { - FileEntry *fe = *it; - wstring fName( fe->data.filename ); - wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) + for (FileEntry* fe : *allFilesInSave) { - app.DebugPrintf("Processing a region file: %ls\n",fName.c_str()); - ConvertRegionFile(File(fe->data.filename) ); - } - else - { - app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); + wstring fName(fe->data.filename); + wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0) + { + app.DebugPrintf("Processing a region file: %ls\n", fName.c_str()); + ConvertRegionFile(File(fe->data.filename)); + } + else + { + app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); + } } } diff --git a/Minecraft.World/CropTile.cpp b/Minecraft.World/CropTile.cpp index 29c5b1c9..0df71924 100644 --- a/Minecraft.World/CropTile.cpp +++ b/Minecraft.World/CropTile.cpp @@ -167,6 +167,6 @@ void CropTile::registerIcons(IconRegister *iconRegister) for (int i = 0; i < 8; i++) { - icons[i] = iconRegister->registerIcon(L"crops_" + _toString(i)); + icons[i] = iconRegister->registerIcon(L"crops_" + std::to_wstring(i)); } }
\ No newline at end of file diff --git a/Minecraft.World/DirectoryLevelStorage.cpp b/Minecraft.World/DirectoryLevelStorage.cpp index ba9bec6a..facd949a 100644 --- a/Minecraft.World/DirectoryLevelStorage.cpp +++ b/Minecraft.World/DirectoryLevelStorage.cpp @@ -121,7 +121,7 @@ bool DirectoryLevelStorage::PlayerMappings::getMapping(int &id, int centreX, int //__int64 xShifted = xMasked << 5; //app.DebugPrintf("xShifted = %d (0x%016x), zShifted = %I64d (0x%016llx)\n", xShifted, xShifted, zShifted, zShifted); __int64 index = ( ((__int64)(centreZ & 0x1FFFFFFF)) << 34) | ( ((__int64)(centreX & 0x1FFFFFFF)) << 5) | ( (scale & 0x7) << 2) | (dimension & 0x3); - AUTO_VAR(it,m_mappings.find(index)); + auto it = m_mappings.find(index); if(it != m_mappings.end()) { id = it->second; @@ -138,11 +138,11 @@ bool DirectoryLevelStorage::PlayerMappings::getMapping(int &id, int centreX, int void DirectoryLevelStorage::PlayerMappings::writeMappings(DataOutputStream *dos) { dos->writeInt(m_mappings.size()); - for(AUTO_VAR(it, m_mappings.begin()); it != m_mappings.end(); ++it) + for ( auto& it : m_mappings ) { - app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it->first, it->first, it->second); - dos->writeLong(it->first); - dos->writeInt(it->second); + app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it.first, it.first, it.second); + dos->writeLong(it.first); + dos->writeInt(it.second); } } @@ -174,9 +174,9 @@ DirectoryLevelStorage::~DirectoryLevelStorage() { delete m_saveFile; - for(AUTO_VAR(it,m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) + for( auto& it : m_cachedSaveData ) { - delete it->second; + delete it.second; } #ifdef _LARGE_WORLDS @@ -233,7 +233,7 @@ ChunkStorage *DirectoryLevelStorage::createChunkStorage(Dimension *dimension) return new OldChunkStorage(dir, true); } -LevelData *DirectoryLevelStorage::prepareLevel() +LevelData *DirectoryLevelStorage::prepareLevel() { // 4J Stu Added #ifdef _LARGE_WORLDS @@ -295,7 +295,7 @@ LevelData *DirectoryLevelStorage::prepareLevel() #else if(getSaveFile()->getSaveVersion() < END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) - { + { MapDataMappings_old oldMapDataMappings; getSaveFile()->readFile( fileEntry, &oldMapDataMappings, // data buffer @@ -334,7 +334,7 @@ LevelData *DirectoryLevelStorage::prepareLevel() ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); - if ( m_saveFile->doesFileExist( dataFile ) ) + if ( m_saveFile->doesFileExist( dataFile ) ) { ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, dataFile); CompoundTag *root = NbtIo::readCompressed(&fis); @@ -398,7 +398,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) #elif defined(_DURANGO) ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + player->getXuid().toString() + L".dat" ); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( player->getXuid() ) + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + std::to_wstring( player->getXuid() ) + L".dat" ); #endif // If saves are disabled (e.g. because we are writing the save buffer to disk) then cache this player data if(StorageManager.GetSaveDisabled()) @@ -406,7 +406,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) ByteArrayOutputStream *bos = new ByteArrayOutputStream(); NbtIo::writeCompressed(tag,bos); - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + auto it = m_cachedSaveData.find(realFile.getName()); if(it != m_cachedSaveData.end() ) { delete it->second; @@ -429,7 +429,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) } // 4J Changed return val to bool to check if new player or loaded player -CompoundTag *DirectoryLevelStorage::load(shared_ptr<Player> player) +CompoundTag *DirectoryLevelStorage::load(shared_ptr<Player> player) { CompoundTag *tag = loadPlayerDataTag( player->getXuid() ); if (tag != NULL) @@ -447,9 +447,9 @@ CompoundTag *DirectoryLevelStorage::loadPlayerDataTag(PlayerUID xuid) #elif defined(_DURANGO) ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + xuid.toString() + L".dat" ); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( xuid ) + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + std::to_wstring( xuid ) + L".dat" ); #endif - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + auto it = m_cachedSaveData.find(realFile.getName()); if(it != m_cachedSaveData.end() ) { ByteArrayOutputStream *bos = it->second; @@ -496,7 +496,7 @@ void DirectoryLevelStorage::clearOldPlayerFiles() m_saveFile->deleteFile( playerFiles->at(i) ); } } - else + else #endif if( playerFiles->size() > MAX_PLAYER_DATA_SAVES ) { @@ -520,12 +520,12 @@ void DirectoryLevelStorage::clearOldPlayerFiles() } } -PlayerIO *DirectoryLevelStorage::getPlayerIO() +PlayerIO *DirectoryLevelStorage::getPlayerIO() { return this; } -void DirectoryLevelStorage::closeAll() +void DirectoryLevelStorage::closeAll() { } @@ -567,11 +567,10 @@ void DirectoryLevelStorage::resetNetherPlayerPositions() vector<FileEntry *> *playerFiles = m_saveFile->getFilesWithPrefix( playerDir.getName() ); #endif - if( playerFiles != NULL ) + if ( playerFiles ) { - for( AUTO_VAR(it, playerFiles->begin()); it != playerFiles->end(); ++it) + for ( FileEntry * realFile : *playerFiles ) { - FileEntry * realFile = *it; ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, realFile); CompoundTag *tag = NbtIo::readCompressed(&fis); if (tag != NULL) @@ -579,7 +578,7 @@ void DirectoryLevelStorage::resetNetherPlayerPositions() // If the player is in the nether, set their y position above the top of the nether // This will force the player to be spawned in a valid position in the overworld when they are loaded if(tag->contains(L"Dimension") && tag->getInt(L"Dimension") == LevelData::DIMENSION_NETHER && tag->contains(L"Pos")) - { + { ListTag<DoubleTag> *pos = (ListTag<DoubleTag> *) tag->getList(L"Pos"); pos->get(1)->data = DBL_MAX; @@ -600,7 +599,7 @@ int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int bool foundMapping = false; #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { foundMapping = it->second.getMapping(mapId, centreXC, centreZC, dimension, scale); @@ -647,12 +646,12 @@ int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int m_saveableMapDataMappings.setMapping(mapId, xuid, dimension); // If we had an old map file for a mapping that is no longer valid, delete it - std::wstring id = wstring( L"map_" ) + _toString(mapId); + std::wstring id = wstring( L"map_" ) + std::to_wstring(mapId); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) { - AUTO_VAR(it, find(m_mapFilesToDelete.begin(), m_mapFilesToDelete.end(), mapId)); + auto it = find(m_mapFilesToDelete.begin(), m_mapFilesToDelete.end(), mapId); if(it != m_mapFilesToDelete.end()) m_mapFilesToDelete.erase(it); m_saveFile->deleteFile( m_saveFile->createFile(file) ); @@ -683,15 +682,15 @@ void DirectoryLevelStorage::saveMapIdLookup() DataOutputStream dos(&baos); dos.writeInt(m_playerMappings.size()); app.DebugPrintf("Saving %d mappings\n", m_playerMappings.size()); - for(AUTO_VAR(it,m_playerMappings.begin()); it != m_playerMappings.end(); ++it) + for ( auto& it : m_playerMappings ) { #ifdef _WINDOWS64 - app.DebugPrintf(" -- %d\n", it->first); + app.DebugPrintf(" -- %d\n", it.first); #else - app.DebugPrintf(" -- %ls\n", it->first.toString().c_str()); + app.DebugPrintf(" -- %ls\n", it.first.toString().c_str()); #endif - dos.writePlayerUID(it->first); - it->second.writeMappings(&dos); + dos.writePlayerUID(it.first); + it.second.writeMappings(&dos); } dos.write(m_usedMappings); m_saveFile->writeFile( fileEntry, @@ -713,10 +712,10 @@ void DirectoryLevelStorage::saveMapIdLookup() void DirectoryLevelStorage::dontSaveMapMappingForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) + for (auto itMap = it->second.m_mappings.begin(); itMap != it->second.m_mappings.end(); ++itMap) { int index = itMap->second / 8; int offset = itMap->second % 8; @@ -744,12 +743,12 @@ void DirectoryLevelStorage::deleteMapFilesForPlayer(shared_ptr<Player> player) void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) + for (auto itMap = it->second.m_mappings.begin(); itMap != it->second.m_mappings.end(); ++itMap) { - std::wstring id = wstring( L"map_" ) + _toString(itMap->second); + std::wstring id = wstring( L"map_" ) + std::to_wstring(itMap->second); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) @@ -773,7 +772,7 @@ void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) { changed = true; - std::wstring id = wstring( L"map_" ) + _toString(i); + std::wstring id = wstring( L"map_" ) + std::to_wstring(i); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) @@ -795,22 +794,22 @@ void DirectoryLevelStorage::saveAllCachedData() if(StorageManager.GetSaveDisabled() ) return; // Save any files that were saved while saving was disabled - for(AUTO_VAR(it, m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) + for ( auto& it : m_cachedSaveData ) { - ByteArrayOutputStream *bos = it->second; + ByteArrayOutputStream *bos = it.second; - ConsoleSavePath realFile = ConsoleSavePath( it->first ); + ConsoleSavePath realFile = ConsoleSavePath( it.first ); ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, realFile ); - app.DebugPrintf("Actually writing cached file %ls\n",it->first.c_str() ); + app.DebugPrintf("Actually writing cached file %ls\n",it.first.c_str() ); fos.write(bos->buf, 0, bos->size() ); delete bos; } m_cachedSaveData.clear(); - for(AUTO_VAR(it, m_mapFilesToDelete.begin()); it != m_mapFilesToDelete.end(); ++it) + for (auto& it : m_mapFilesToDelete ) { - std::wstring id = wstring( L"map_" ) + _toString(*it); + std::wstring id = wstring( L"map_" ) + std::to_wstring(it); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) { diff --git a/Minecraft.World/DirectoryLevelStorageSource.cpp b/Minecraft.World/DirectoryLevelStorageSource.cpp index b4beb8b5..e229232b 100644 --- a/Minecraft.World/DirectoryLevelStorageSource.cpp +++ b/Minecraft.World/DirectoryLevelStorageSource.cpp @@ -27,12 +27,12 @@ vector<LevelSummary *> *DirectoryLevelStorageSource::getLevelList() // 4J Stu - We don't use directory list with the Xbox save locations vector<LevelSummary *> *levels = new vector<LevelSummary *>; #if 0 - for (int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { - wstring levelId = wstring(L"World").append( _toString( (i+1) ) ); + wstring levelId = wstring(L"World").append( std::to_wstring( (i+1) ) ); LevelData *levelData = getDataTagFor(saveFile, levelId); - if (levelData != NULL) + if (levelData != NULL) { levels->push_back(new LevelSummary(levelId, L"", levelData->getLastPlayed(), levelData->getSizeOnDisk(), levelData.getGameType(), false, levelData->isHardcore())); } @@ -45,7 +45,7 @@ void DirectoryLevelStorageSource::clearAll() { } -LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, const wstring& levelId) +LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, const wstring& levelId) { //File dataFile(dir, L"level.dat"); ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); @@ -63,12 +63,12 @@ LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, } void DirectoryLevelStorageSource::renameLevel(const wstring& levelId, const wstring& newLevelName) -{ +{ ConsoleSaveFileOriginal tempSave(levelId); //File dataFile = File(dir, L"level.dat"); ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); - if ( tempSave.doesFileExist( dataFile ) ) + if ( tempSave.doesFileExist( dataFile ) ) { ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(&tempSave, dataFile); CompoundTag *root = NbtIo::readCompressed(&fis); @@ -80,7 +80,7 @@ void DirectoryLevelStorageSource::renameLevel(const wstring& levelId, const wstr } } -bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) +bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) { // 4J Jev, removed try/catch. @@ -95,7 +95,7 @@ bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) return true; } -void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) +void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) { File dir = File(baseDir, levelId); if (!dir.exists()) return; @@ -106,15 +106,16 @@ void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) void DirectoryLevelStorageSource::deleteRecursive(vector<File *> *files) { - AUTO_VAR(itEnd, files->end()); - for (AUTO_VAR(it, files->begin()); it != itEnd; it++) + if ( files ) { - File *file = *it; - if (file->isDirectory()) + for (File* file : *files) { - deleteRecursive(file->listFiles()); + if (file->isDirectory()) + { + deleteRecursive(file->listFiles()); + } + file->_delete(); } - file->_delete(); } } @@ -133,7 +134,7 @@ bool DirectoryLevelStorageSource::requiresConversion(ConsoleSaveFile *saveFile, return false; } -bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const wstring& levelId, ProgressListener *progress) +bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const wstring& levelId, ProgressListener *progress) { return false; } diff --git a/Minecraft.World/DragonFireball.cpp b/Minecraft.World/DragonFireball.cpp index 32524592..335b345f 100644 --- a/Minecraft.World/DragonFireball.cpp +++ b/Minecraft.World/DragonFireball.cpp @@ -33,27 +33,27 @@ void DragonFireball::onHit(HitResult *res) { AABB *aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); vector<shared_ptr<Entity> > *entitiesOfClass = level->getEntitiesOfClass(typeid(LivingEntity), aoe); - - if (entitiesOfClass != NULL && !entitiesOfClass->empty()) + if ( entitiesOfClass ) { - //for (Entity e : entitiesOfClass) - for( AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) + if (!entitiesOfClass->empty()) { - //shared_ptr<Entity> e = *it; - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - double dist = distanceToSqr(e); - if (dist < SPLASH_RANGE_SQ) + for (auto& it : *entitiesOfClass) { - double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); - if (e == res->entity) + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + double dist = distanceToSqr(e); + if (dist < SPLASH_RANGE_SQ) { - scale = 1; + double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); + if (e == res->entity) + { + scale = 1; + } + e->hurt(DamageSource::dragonbreath, 8 * scale); } - e->hurt(DamageSource::dragonbreath, 8*scale); } } + delete entitiesOfClass; } - delete entitiesOfClass; level->levelEvent(LevelEvent::ENDERDRAGON_FIREBALL_SPLASH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), 0); remove(); diff --git a/Minecraft.World/EnchantmentHelper.cpp b/Minecraft.World/EnchantmentHelper.cpp index da784d5a..7abc9856 100644 --- a/Minecraft.World/EnchantmentHelper.cpp +++ b/Minecraft.World/EnchantmentHelper.cpp @@ -57,19 +57,19 @@ void EnchantmentHelper::setEnchantments(unordered_map<int, int> *enchantments, s ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); //for (int id : enchantments.keySet()) - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for ( const auto& it : *enchantments ) { - int id = it->first; + int id = it.first; CompoundTag *tag = new CompoundTag(); tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_ID, (short) id); - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short)(int)it->second); + tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short)(int)it.second); list->add(tag); if (item->id == Item::enchantedBook_Id) { - Item::enchantedBook->addEnchantment(item, new EnchantmentInstance(id, it->second)); + Item::enchantedBook->addEnchantment(item, new EnchantmentInstance(id, it.second)); } } @@ -301,20 +301,22 @@ shared_ptr<ItemInstance> EnchantmentHelper::enchantItem(Random *random, shared_p if (isBook) itemInstance->id = Item::enchantedBook_Id; - if (newEnchantment != NULL) + if ( newEnchantment ) { - for(AUTO_VAR(it, newEnchantment->begin()); it != newEnchantment->end(); ++it) + for ( EnchantmentInstance *e : *newEnchantment ) { - EnchantmentInstance *e = *it; - if (isBook) + if ( e ) { - Item::enchantedBook->addEnchantment(itemInstance, e); - } - else - { - itemInstance->enchant(e->enchantment, e->level); + if (isBook) + { + Item::enchantedBook->addEnchantment(itemInstance, e); + } + else + { + itemInstance->enchant(e->enchantment, e->level); + } + delete e; } - delete e; } delete newEnchantment; } @@ -355,17 +357,17 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand vector<EnchantmentInstance *> *results = NULL; unordered_map<int, EnchantmentInstance *> *availableEnchantments = getAvailableEnchantmentResults(realValue, itemInstance); - if (availableEnchantments != NULL && !availableEnchantments->empty()) + if (availableEnchantments && !availableEnchantments->empty()) { vector<WeighedRandomItem *> values; - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for( auto& it : *availableEnchantments ) { - values.push_back(it->second); + values.push_back(it.second); } EnchantmentInstance *instance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); values.clear(); - if (instance != NULL) + if (instance) { results = new vector<EnchantmentInstance *>(); results->push_back( instance->copy() ); // 4J Stu - Inserting a copy so we can clear memory from the availableEnchantments collection @@ -377,14 +379,12 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand // remove incompatible enchantments from previous result //final Iterator<Integer> mapIter = availableEnchantments.keySet().iterator(); //while (mapIter.hasNext()) - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end();) + for (auto it = availableEnchantments->begin(); it != availableEnchantments->end();) { int nextEnchantment = it->first;//mapIter.next(); bool valid = true; - //for (EnchantmentInstance *current : results) - for(AUTO_VAR(resIt, results->begin()); resIt != results->end(); ++resIt) + for ( const EnchantmentInstance *current : *results ) { - EnchantmentInstance *current = *resIt; if (!current->enchantment->isCompatibleWith(Enchantment::enchantments[nextEnchantment])) { valid = false; @@ -405,9 +405,9 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand if (!availableEnchantments->empty()) { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for (auto& it : *availableEnchantments ) { - values.push_back(it->second); + values.push_back(it.second); } EnchantmentInstance *nextInstance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); values.clear(); @@ -418,11 +418,11 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand } } } - if(availableEnchantments != NULL) + if( availableEnchantments ) { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for (auto& it : *availableEnchantments ) { - delete it->second; + delete it.second; } delete availableEnchantments; } @@ -460,7 +460,7 @@ unordered_map<int, EnchantmentInstance *> *EnchantmentHelper::getAvailableEnchan { results = new unordered_map<int, EnchantmentInstance *>(); } - AUTO_VAR(it, results->find(e->id)); + auto it = results->find(e->id); if(it != results->end()) { delete it->second; diff --git a/Minecraft.World/EnderCrystal.cpp b/Minecraft.World/EnderCrystal.cpp index 78e00419..5e7a9edb 100644 --- a/Minecraft.World/EnderCrystal.cpp +++ b/Minecraft.World/EnderCrystal.cpp @@ -110,12 +110,10 @@ bool EnderCrystal::hurt(DamageSource *source, float damage) vector<shared_ptr<Entity> > entities = level->getAllEntities(); shared_ptr<EnderDragon> dragon = nullptr; - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for ( auto& e : entities ) { - shared_ptr<Entity> e = *it; //entities->at(i); dragon = dynamic_pointer_cast<EnderDragon>(e); - if(dragon != NULL) + if ( dragon ) { dragon->handleCrystalDestroyed(source); break; diff --git a/Minecraft.World/EnderDragon.cpp b/Minecraft.World/EnderDragon.cpp index 2dc0c434..e1dea172 100644 --- a/Minecraft.World/EnderDragon.cpp +++ b/Minecraft.World/EnderDragon.cpp @@ -444,13 +444,16 @@ void EnderDragon::aiStep() { vector<shared_ptr<Entity> > *targets = level->getEntities(shared_from_this(), m_acidArea); - for( AUTO_VAR(it, targets->begin() ); it != targets->end(); ++it) + if ( targets ) { - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) ) + for (auto& it : *targets ) { - //app.DebugPrintf("Attacking entity with acid\n"); - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - e->hurt(DamageSource::dragonbreath, 2); + if ( it->instanceof(eTYPE_LIVINGENTITY)) + { + //app.DebugPrintf("Attacking entity with acid\n"); + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + e->hurt(DamageSource::dragonbreath, 2); + } } } } @@ -796,24 +799,23 @@ void EnderDragon::checkCrystals() { float maxDist = 32; vector<shared_ptr<Entity> > *crystals = level->getEntitiesOfClass(typeid(EnderCrystal), bb->grow(maxDist, maxDist, maxDist)); - - shared_ptr<EnderCrystal> crystal = nullptr; - double nearest = Double::MAX_VALUE; - //for (Entity ec : crystals) - for(AUTO_VAR(it, crystals->begin()); it != crystals->end(); ++it) + if ( crystals ) { - shared_ptr<EnderCrystal> ec = dynamic_pointer_cast<EnderCrystal>( *it ); - double dist = ec->distanceToSqr(shared_from_this() ); - if (dist < nearest) + shared_ptr<EnderCrystal> crystal = nullptr; + double nearest = Double::MAX_VALUE; + for (auto& it : *crystals ) { - nearest = dist; - crystal = ec; + shared_ptr<EnderCrystal> ec = dynamic_pointer_cast<EnderCrystal>(it); + double dist = ec->distanceToSqr(shared_from_this()); + if (dist < nearest) + { + nearest = dist; + crystal = ec; + } } + delete crystals; + nearestCrystal = crystal; } - delete crystals; - - - nearestCrystal = crystal; } } @@ -839,33 +841,39 @@ void EnderDragon::knockBack(vector<shared_ptr<Entity> > *entities) // double ym = (body.bb.y0 + body.bb.y1) / 2; double zm = (body->bb->z0 + body->bb->z1) / 2; - //for (Entity e : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) )//(e instanceof Mob) + for ( auto& it : *entities ) { - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - double xd = e->x - xm; - double zd = e->z - zm; - double dd = xd * xd + zd * zd; - e->push(xd / dd * 4, 0.2f, zd / dd * 4); + if (it->instanceof(eTYPE_LIVINGENTITY)) + { + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + double xd = e->x - xm; + double zd = e->z - zm; + double dd = xd * xd + zd * zd; + e->push(xd / dd * 4, 0.2f, zd / dd * 4); + } } } } void EnderDragon::hurt(vector<shared_ptr<Entity> > *entities) { - //for (int i = 0; i < entities->size(); i++) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) ) //(e instanceof Mob) + for ( auto& it : *entities ) { - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it );//entities.get(i); - DamageSource *damageSource = DamageSource::mobAttack( dynamic_pointer_cast<LivingEntity>( shared_from_this() )); - e->hurt(damageSource, 10); - delete damageSource; + + if ( it->instanceof(eTYPE_LIVINGENTITY)) + { + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + DamageSource* damageSource = DamageSource::mobAttack(dynamic_pointer_cast<LivingEntity>(shared_from_this())); + if ( damageSource ) + { + e->hurt(damageSource, 10); + delete damageSource; + } + } } } } diff --git a/Minecraft.World/Entity.cpp b/Minecraft.World/Entity.cpp index cfae1772..e8233140 100644 --- a/Minecraft.World/Entity.cpp +++ b/Minecraft.World/Entity.cpp @@ -753,9 +753,6 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - AABBList *aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za), noEntityCubes, true); - // LAND FIRST, then x and z - AUTO_VAR(itEndAABB, aABBs->end()); - // 4J Stu - Particles (and possibly other entities) don't have xChunk and zChunk set, so calculate the chunk instead int xc = Mth::floor(x / 16); int zc = Mth::floor(z / 16); @@ -763,8 +760,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - { // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -775,9 +772,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - bool og = onGround || (yaOrg != ya && yaOrg < 0); - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); + for ( auto& it : *aABBs ) + xa = it->clipXCollide(bb, xa); bb->move(xa, 0, 0); @@ -786,9 +782,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - xa = ya = za = 0; } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); + for ( auto& it : *aABBs ) + za = it->clipZCollide(bb, za); bb->move(0, 0, za); if (!slide && zaOrg != za) @@ -812,15 +807,12 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - // so we'd better include cubes under our feet in this list of things we might possibly collide with aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za)->expand(0,-ya,0),false,true); - // LAND FIRST, then x and z - itEndAABB = aABBs->end(); - if(!level->isClientSide || level->reallyHasChunk(xc, zc)) { // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -830,9 +822,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); + for ( auto& it : *aABBs ) + xa = it->clipXCollide(bb, xa); bb->move(xa, 0, 0); if (!slide && xaOrg != xa) @@ -840,9 +831,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - xa = ya = za = 0; } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); + for ( auto& it : *aABBs ) + za = it->clipZCollide(bb, za); bb->move(0, 0, za); if (!slide && zaOrg != za) @@ -859,9 +849,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - { ya = -footSize; // LAND FIRST, then x and z - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -1667,14 +1656,12 @@ void Entity::lerpTo(double x, double y, double z, float yRot, float xRot, int st if( GetType() != eTYPE_ARROW ) { AABBList *collisions = level->getCubes(shared_from_this(), bb->shrink(1 / 32.0, 0, 1 / 32.0)); - if (!collisions->empty()) + if ( collisions && !collisions->empty()) { double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) + for ( const AABB *ab : *collisions ) { - AABB *ab = *it; //collisions->at(i); - if (ab->y1 > yTop) yTop = ab->y1; + if ( ab && ab->y1 > yTop) yTop = ab->y1; } y += yTop - bb->y0; @@ -1942,7 +1929,7 @@ wstring Entity::getAName() #ifdef _DEBUG wstring id = EntityIO::getEncodeId(shared_from_this()); if (id.empty()) id = L"generic"; - return L"entity." + id + _toString(entityId); + return L"entity." + id + std::to_wstring(entityId); #else return L""; #endif diff --git a/Minecraft.World/EntityHorse.cpp b/Minecraft.World/EntityHorse.cpp index d7250087..90c2a6b9 100644 --- a/Minecraft.World/EntityHorse.cpp +++ b/Minecraft.World/EntityHorse.cpp @@ -440,7 +440,7 @@ void EntityHorse::causeFallDamage(float fallDistance) /** * Different inventory sizes depending on the kind of horse -* +* * @return */ int EntityHorse::getInventorySize() @@ -523,9 +523,8 @@ shared_ptr<EntityHorse> EntityHorse::getClosestMommy(shared_ptr<Entity> baby, do shared_ptr<Entity> mommy = nullptr; vector<shared_ptr<Entity> > *list = level->getEntities(baby, baby->bb->expand(searchRadius, searchRadius, searchRadius), PARENT_HORSE_SELECTOR); - for(AUTO_VAR(it,list->begin()); it != list->end(); ++it) + for( auto& horse : *list ) { - shared_ptr<Entity> horse = *it; double distanceSquared = horse->distanceToSqr(baby->x, baby->y, baby->z); if (distanceSquared < closestDistance) @@ -767,7 +766,7 @@ void EntityHorse::rebuildLayeredTextureInfo() else { layerTextureLayers[0] = -1; - layerTextureHashName += L"_" + _toString<int>(type) + L"_"; + layerTextureHashName += L"_" + std::to_wstring(type) + L"_"; armorIndex = 1; } @@ -1036,7 +1035,7 @@ bool EntityHorse::canWearArmor() /** * able to carry bags -* +* * @return */ bool EntityHorse::canWearBags() @@ -1065,7 +1064,7 @@ bool EntityHorse::isPureBreed() /** * Is this an Undead Horse? -* +* * @return */ bool EntityHorse::isUndead() @@ -1675,7 +1674,7 @@ MobGroupData *EntityHorse::finalizeMobSpawn(MobGroupData *groupData, int extraDa setAge(AgableMob::BABY_START_AGE); } - if (type == TYPE_SKELETON || type == TYPE_UNDEAD) + if (type == TYPE_SKELETON || type == TYPE_UNDEAD) { getAttribute(SharedMonsterAttributes::MAX_HEALTH)->setBaseValue(15); getAttribute(SharedMonsterAttributes::MOVEMENT_SPEED)->setBaseValue(0.2f); @@ -1791,7 +1790,7 @@ void EntityHorse::positionRider() float height = .15f * standAnimO; rider.lock()->setPos(x + dist * sin, y + getRideHeight() + rider.lock()->getRidingHeight() + height, z - dist * cos); - + if ( rider.lock()->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> livingRider = dynamic_pointer_cast<LivingEntity>(rider.lock()); diff --git a/Minecraft.World/EntityIO.cpp b/Minecraft.World/EntityIO.cpp index 4532e8dd..086015dc 100644 --- a/Minecraft.World/EntityIO.cpp +++ b/Minecraft.World/EntityIO.cpp @@ -131,7 +131,7 @@ shared_ptr<Entity> EntityIO::newEntity(const wstring& id, Level *level) { shared_ptr<Entity> entity; - AUTO_VAR(it, idCreateMap->find(id)); + auto it = idCreateMap->find(id); if(it != idCreateMap->end() ) { entityCreateFn create = it->second; @@ -169,7 +169,7 @@ shared_ptr<Entity> EntityIO::loadStatic(CompoundTag *tag, Level *level) tag->remove(L"Type"); } - AUTO_VAR(it, idCreateMap->find(tag->getString(L"id"))); + auto it = idCreateMap->find(tag->getString(L"id")); if(it != idCreateMap->end() ) { entityCreateFn create = it->second; @@ -197,7 +197,7 @@ shared_ptr<Entity> EntityIO::newById(int id, Level *level) { shared_ptr<Entity> entity; - AUTO_VAR(it, numCreateMap->find(id)); + auto it = numCreateMap->find(id); if(it != numCreateMap->end() ) { entityCreateFn create = it->second; @@ -222,10 +222,10 @@ shared_ptr<Entity> EntityIO::newByEnumType(eINSTANCEOF eType, Level *level) { shared_ptr<Entity> entity; - unordered_map<eINSTANCEOF, int, eINSTANCEOFKeyHash, eINSTANCEOFKeyEq>::iterator it = classNumMap->find( eType ); + auto it = classNumMap->find( eType ); if( it != classNumMap->end() ) { - AUTO_VAR(it2, numCreateMap->find(it->second)); + auto it2 = numCreateMap->find(it->second); if(it2 != numCreateMap->end() ) { entityCreateFn create = it2->second; @@ -257,7 +257,7 @@ wstring EntityIO::getEncodeId(shared_ptr<Entity> entity) int EntityIO::getId(const wstring &encodeId) { - AUTO_VAR(it, idNumMap->find(encodeId)); + auto it = idNumMap->find(encodeId); if (it == idNumMap->end()) { // defaults to pig... @@ -274,7 +274,7 @@ wstring EntityIO::getEncodeId(int entityIoValue) //return classIdMap.get(class1); //} - AUTO_VAR(it, numClassMap->find(entityIoValue)); + auto it = numClassMap->find(entityIoValue); if(it != numClassMap->end() ) { unordered_map<eINSTANCEOF, wstring, eINSTANCEOFKeyHash, eINSTANCEOFKeyEq>::iterator classIdIt = classIdMap->find( it->second ); @@ -291,7 +291,7 @@ int EntityIO::getNameId(int entityIoValue) { int id = -1; - AUTO_VAR(it, idsSpawnableInCreative.find(entityIoValue)); + auto it = idsSpawnableInCreative.find(entityIoValue); if(it != idsSpawnableInCreative.end()) { id = it->second->nameId; @@ -302,7 +302,7 @@ int EntityIO::getNameId(int entityIoValue) eINSTANCEOF EntityIO::getType(const wstring &idString) { - AUTO_VAR(it, numClassMap->find(getId(idString))); + auto it = numClassMap->find(getId(idString)); if(it != numClassMap->end() ) { return it->second; @@ -312,7 +312,7 @@ eINSTANCEOF EntityIO::getType(const wstring &idString) eINSTANCEOF EntityIO::getClass(int id) { - AUTO_VAR(it, numClassMap->find(id)); + auto it = numClassMap->find(id); if(it != numClassMap->end() ) { return it->second; diff --git a/Minecraft.World/ExplodePacket.cpp b/Minecraft.World/ExplodePacket.cpp index aec5b261..30d09e46 100644 --- a/Minecraft.World/ExplodePacket.cpp +++ b/Minecraft.World/ExplodePacket.cpp @@ -27,16 +27,12 @@ ExplodePacket::ExplodePacket(double x, double y, double z, float r, unordered_se this->r = r; m_bKnockbackOnly = knockBackOnly; - if(toBlow != NULL) + if(toBlow != nullptr) { this->toBlow.assign(toBlow->begin(),toBlow->end()); - //for( AUTO_VAR(it, toBlow->begin()); it != toBlow->end(); it++ ) - //{ - // this->toBlow.push_back(*it); - //} } - if (knockback != NULL) + if (knockback != nullptr) { knockbackX = (float) knockback->x; knockbackY = (float) knockback->y; @@ -89,13 +85,8 @@ void ExplodePacket::write(DataOutputStream *dos) //throws IOException int yp = (int)y; int zp = (int)z; - //(Myset::const_iterator it = c1.begin(); - //it != c1.end(); ++it) - - for( AUTO_VAR(it, toBlow.begin()); it != toBlow.end(); it++ ) + for ( const TilePos& tp : toBlow ) { - TilePos tp = *it; - int xx = tp.x-xp; int yy = tp.y-yp; int zz = tp.z-zp; diff --git a/Minecraft.World/Explosion.cpp b/Minecraft.World/Explosion.cpp index 028ad673..ab305a02 100644 --- a/Minecraft.World/Explosion.cpp +++ b/Minecraft.World/Explosion.cpp @@ -29,9 +29,9 @@ Explosion::Explosion(Level *level, shared_ptr<Entity> source, double x, double y Explosion::~Explosion() { delete random; - for(AUTO_VAR(it, hitPlayers.begin()); it != hitPlayers.end(); ++it) + for( auto& it : hitPlayers ) { - delete it->second; + delete it.second; } } @@ -105,17 +105,14 @@ void Explosion::explode() vector<shared_ptr<Entity> > entities(levelEntities->begin(), levelEntities->end() ); Vec3 *center = Vec3::newTemp(x, y, z); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for ( auto& e : entities ) { - shared_ptr<Entity> e = *it; //entities->at(i); - // 4J Stu - If the entity is not in a block that would be blown up, then they should not be damaged // Fix for #46606 - TU5: Content: Gameplay: The player can be damaged and killed by explosions behind obsidian walls bool canDamage = false; - for(AUTO_VAR(it2, toBlow.begin()); it2 != toBlow.end(); ++it2) + for ( auto& it2 : toBlow ) { - if(e->bb->intersects(it2->x,it2->y,it2->z,it2->x + 1,it2->y + 1,it2->z + 1)) + if(e->bb->intersects(it2.x,it2.y,it2.z,it2.x + 1,it2.y + 1,it2.z + 1)) { canDamage = true; break; @@ -192,7 +189,7 @@ void Explosion::finalizeExplosion(bool generateParticles, vector<TilePos> *toBlo if( fraction == 0 ) fraction = 1; size_t j = toBlowArray->size() - 1; //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) + for (auto it = toBlowArray->rbegin(); it != toBlowArray->rend(); ++it) { TilePos *tp = &(*it); //&toBlowArray->at(j); int xt = tp->x; @@ -249,8 +246,7 @@ void Explosion::finalizeExplosion(bool generateParticles, vector<TilePos> *toBlo if (fire) { - //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) + for (auto it = toBlowArray->rbegin(); it != toBlowArray->rend(); ++it) { TilePos *tp = &(*it); //&toBlowArray->at(j); int xt = tp->x; @@ -276,7 +272,7 @@ Explosion::playerVec3Map *Explosion::getHitPlayers() Vec3 *Explosion::getHitPlayerKnockback( shared_ptr<Player> player ) { - AUTO_VAR(it, hitPlayers.find(player)); + auto it = hitPlayers.find(player); if(it == hitPlayers.end() ) return Vec3::newTemp(0.0,0.0,0.0); diff --git a/Minecraft.World/FallingTile.cpp b/Minecraft.World/FallingTile.cpp index 28248014..c0eb7d22 100644 --- a/Minecraft.World/FallingTile.cpp +++ b/Minecraft.World/FallingTile.cpp @@ -145,13 +145,15 @@ void FallingTile::tick() CompoundTag *swap = new CompoundTag(); tileEntity->save(swap); vector<Tag *> *allTags = tileData->getAllTags(); - for(AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) + if ( allTags ) { - Tag *tag = *it; - if (tag->getName().compare(L"x") == 0 || tag->getName().compare(L"y") == 0 || tag->getName().compare(L"z") == 0) continue; - swap->put(tag->getName(), tag->copy()); + for ( Tag* tag : *allTags ) + { + if (tag->getName().compare(L"x") == 0 || tag->getName().compare(L"y") == 0 || tag->getName().compare(L"z") == 0) continue; + swap->put(tag->getName(), tag->copy()); + } + delete allTags; } - delete allTags; tileEntity->load(swap); tileEntity->setChanged(); } @@ -181,12 +183,14 @@ void FallingTile::causeFallDamage(float distance) // 4J: Copy vector since it might be modified when we hurt the entities (invalidating our iterator) vector<shared_ptr<Entity> > *entities = new vector<shared_ptr<Entity> >(*level->getEntities(shared_from_this(), bb)); DamageSource *source = tile == Tile::anvil_Id ? DamageSource::anvil : DamageSource::fallingBlock; - //for (Entity entity : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( source ) { - (*it)->hurt(source, min(Mth::floor(dmg * fallDamageAmount), fallDamageMax)); + for (auto& it : *entities) + { + it->hurt(source, static_cast<float>(std::min<int>(Mth::floor(dmg * fallDamageAmount), fallDamageMax))); + } + delete entities; } - delete entities; if (tile == Tile::anvil_Id && random->nextFloat() < 0.05f + (dmg * 0.05)) { diff --git a/Minecraft.World/File.cpp b/Minecraft.World/File.cpp index 21bc3021..82e593dc 100644 --- a/Minecraft.World/File.cpp +++ b/Minecraft.World/File.cpp @@ -152,17 +152,16 @@ bool File::mkdirs() const std::vector<std::wstring> path = stringSplit( m_abstractPathName, pathSeparator ); std::wstring pathToHere = L""; - AUTO_VAR(itEnd, path.end()); - for( AUTO_VAR(it, path.begin()); it != itEnd; it++ ) + for( auto& it : path ) { // If this member of the vector is the root then just skip to the next - if( pathRoot.compare( *it ) == 0 ) + if( pathRoot.compare(it) == 0 ) { - pathToHere = *it; + pathToHere = it; continue; } - pathToHere = pathToHere + pathSeparator + *it; + pathToHere = pathToHere + pathSeparator + it; // if not exists #ifdef _UNICODE diff --git a/Minecraft.World/FileHeader.cpp b/Minecraft.World/FileHeader.cpp index 35f7b02d..0a47e043 100644 --- a/Minecraft.World/FileHeader.cpp +++ b/Minecraft.World/FileHeader.cpp @@ -53,7 +53,7 @@ void FileHeader::RemoveFile( FileEntry *file ) AdjustStartOffsets(file, file->getFileSize(), true); - AUTO_VAR(it, find(fileTable.begin(), fileTable.end(),file)); + auto it = find(fileTable.begin(), fileTable.end(), file); if( it < fileTable.end() ) { diff --git a/Minecraft.World/Fireball.cpp b/Minecraft.World/Fireball.cpp index 1d9fbdda..2a538b06 100644 --- a/Minecraft.World/Fireball.cpp +++ b/Minecraft.World/Fireball.cpp @@ -200,11 +200,9 @@ void Fireball::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for ( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects->at(i); - if (!e->isPickable() || (e->is(owner) )) continue; //4J Stu - Never collide with the owner (Enderdragon) // && flightTime < 25)) continue; + if ( e == nullptr || !e->isPickable() || (e->is(owner) )) continue; //4J Stu - Never collide with the owner (Enderdragon) // && flightTime < 25)) continue; float rr = 0.3f; AABB *bb = e->bb->grow(rr, rr, rr); diff --git a/Minecraft.World/FireworksItem.cpp b/Minecraft.World/FireworksItem.cpp index 045ea130..f81b4588 100644 --- a/Minecraft.World/FireworksItem.cpp +++ b/Minecraft.World/FireworksItem.cpp @@ -52,7 +52,7 @@ void FireworksItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, share } if (fireTag->contains(TAG_FLIGHT)) { - lines->push_back(wstring(app.GetString(IDS_ITEM_FIREWORKS_FLIGHT)) + L" " + _toString<int>((fireTag->getByte(TAG_FLIGHT)))); + lines->push_back(wstring(app.GetString(IDS_ITEM_FIREWORKS_FLIGHT)) + L" " + std::to_wstring((fireTag->getByte(TAG_FLIGHT)))); } ListTag<CompoundTag> *explosions = (ListTag<CompoundTag> *) fireTag->getList(TAG_EXPLOSIONS); diff --git a/Minecraft.World/FishingHook.cpp b/Minecraft.World/FishingHook.cpp index 3e627af2..e38a64b6 100644 --- a/Minecraft.World/FishingHook.cpp +++ b/Minecraft.World/FishingHook.cpp @@ -233,8 +233,7 @@ void FishingHook::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for (auto it = objects->begin(); it != objects->end(); it++) { shared_ptr<Entity> e = *it; // objects->at(i); if (!e->isPickable() || (e == owner && flightTime < 5)) continue; diff --git a/Minecraft.World/FlatGeneratorInfo.cpp b/Minecraft.World/FlatGeneratorInfo.cpp index 9df19693..dfd4cb66 100644 --- a/Minecraft.World/FlatGeneratorInfo.cpp +++ b/Minecraft.World/FlatGeneratorInfo.cpp @@ -20,9 +20,9 @@ FlatGeneratorInfo::FlatGeneratorInfo() FlatGeneratorInfo::~FlatGeneratorInfo() { - for(AUTO_VAR(it, layers.begin()); it != layers.end(); ++it) + for(auto& layer : layers) { - delete *it; + delete layer; } } @@ -50,9 +50,8 @@ void FlatGeneratorInfo::updateLayers() { int y = 0; - for(AUTO_VAR(it, layers.begin()); it != layers.end(); ++it) + for(auto& layer : layers) { - FlatLayerInfo *layer = *it; layer->setStart(y); y += layer->getHeight(); } @@ -113,7 +112,7 @@ wstring FlatGeneratorInfo::toString() #endif } -FlatLayerInfo *FlatGeneratorInfo::getLayerFromString(const wstring &input, int yOffset) +FlatLayerInfo *FlatGeneratorInfo::getLayerFromString(const wstring &input, int yOffset) { return NULL; #if 0 @@ -159,9 +158,9 @@ vector<FlatLayerInfo *> *FlatGeneratorInfo::getLayersFromString(const wstring &i int yOffset = 0; - for(AUTO_VAR(it, depths.begin()); it != depths.end(); ++it) + for(auto& depth : depths) { - FlatLayerInfo *layer = getLayerFromString(*it, yOffset); + FlatLayerInfo *layer = getLayerFromString(depth, yOffset); if (layer == NULL) return NULL; result->push_back(layer); yOffset += layer->getHeight(); @@ -203,8 +202,8 @@ FlatGeneratorInfo *FlatGeneratorInfo::fromValue(const wstring &input) { std::vector<std::wstring> structures = stringSplit(parts[index++], L','); - for(AUTO_VAR(it, structures.begin()); it != structures.end(); ++it) - { + for (auto it = structures.begin(); it != structures.end(); ++it) + { std::vector<std::wstring> separated = stringSplit(parts[index++], L"\\("); unordered_map<wstring, wstring> structureOptions; diff --git a/Minecraft.World/FlatLayerInfo.cpp b/Minecraft.World/FlatLayerInfo.cpp index 4a4d79dd..331717e2 100644 --- a/Minecraft.World/FlatLayerInfo.cpp +++ b/Minecraft.World/FlatLayerInfo.cpp @@ -63,15 +63,15 @@ void FlatLayerInfo::setStart(int start) wstring FlatLayerInfo::toString() { - wstring result = _toString<int>(id); + wstring result = std::to_wstring(id); if (height > 1) { - result = _toString<int>(height) + L"x" + result; + result = std::to_wstring(height) + L"x" + result; } if (data > 0) { - result += L":" + _toString<int>(data); + result += L":" + std::to_wstring(data); } return result; diff --git a/Minecraft.World/FollowParentGoal.cpp b/Minecraft.World/FollowParentGoal.cpp index 61c5614a..8983590a 100644 --- a/Minecraft.World/FollowParentGoal.cpp +++ b/Minecraft.World/FollowParentGoal.cpp @@ -22,9 +22,9 @@ bool FollowParentGoal::canUse() shared_ptr<Animal> closest = nullptr; double closestDistSqr = Double::MAX_VALUE; - for(AUTO_VAR(it, parents->begin()); it != parents->end(); ++it) + for(auto& it : *parents) { - shared_ptr<Animal> parent = dynamic_pointer_cast<Animal>(*it); + shared_ptr<Animal> parent = dynamic_pointer_cast<Animal>(it); if (parent->getAge() < 0) continue; double distSqr = animal->distanceToSqr(parent); if (distSqr > closestDistSqr) continue; diff --git a/Minecraft.World/FurnaceMenu.cpp b/Minecraft.World/FurnaceMenu.cpp index 2a6ebc63..f67d6388 100644 --- a/Minecraft.World/FurnaceMenu.cpp +++ b/Minecraft.World/FurnaceMenu.cpp @@ -44,12 +44,10 @@ void FurnaceMenu::addSlotListener(ContainerListener *listener) void FurnaceMenu::broadcastChanges() { AbstractContainerMenu::broadcastChanges(); - - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + + for (auto& listener : containerListeners) { - ContainerListener *listener = *it; //containerListeners->at(i); - if (tc != furnace->tickCount) + if (tc != furnace->tickCount) { listener->setContainerData(this, 0, furnace->tickCount); } @@ -57,7 +55,7 @@ void FurnaceMenu::broadcastChanges() { listener->setContainerData(this, 1, furnace->litTime); } - if (ld != furnace->litDuration) + if (ld != furnace->litDuration) { listener->setContainerData(this, 2, furnace->litDuration); } diff --git a/Minecraft.World/FurnaceRecipes.cpp b/Minecraft.World/FurnaceRecipes.cpp index af59884c..bed4e1b6 100644 --- a/Minecraft.World/FurnaceRecipes.cpp +++ b/Minecraft.World/FurnaceRecipes.cpp @@ -10,12 +10,12 @@ void FurnaceRecipes::staticCtor() FurnaceRecipes::instance = new FurnaceRecipes(); } -FurnaceRecipes *FurnaceRecipes::getInstance() +FurnaceRecipes *FurnaceRecipes::getInstance() { return instance; } -FurnaceRecipes::FurnaceRecipes() +FurnaceRecipes::FurnaceRecipes() { addFurnaceRecipy(Tile::ironOre_Id, new ItemInstance(Item::ironIngot), .7f); addFurnaceRecipy(Tile::goldOre_Id, new ItemInstance(Item::goldIngot), 1); @@ -33,7 +33,7 @@ FurnaceRecipes::FurnaceRecipes() addFurnaceRecipy(Tile::emeraldOre_Id, new ItemInstance(Item::emerald), 1); addFurnaceRecipy(Item::potato_Id, new ItemInstance(Item::potatoBaked), .35f); addFurnaceRecipy(Tile::netherRack_Id, new ItemInstance(Item::netherbrick), .1f); - + // special silk touch related recipes: addFurnaceRecipy(Tile::coalOre_Id, new ItemInstance(Item::coal), .1f); addFurnaceRecipy(Tile::redStoneOre_Id, new ItemInstance(Item::redStone), .7f); @@ -43,38 +43,38 @@ FurnaceRecipes::FurnaceRecipes() } -void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance *result, float value) +void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance *result, float value) { //recipies->put(itemId, result); recipies[itemId]=result; recipeValue[result->id] = value; } -bool FurnaceRecipes::isFurnaceItem(int itemId) +bool FurnaceRecipes::isFurnaceItem(int itemId) { - AUTO_VAR(it, recipies.find(itemId)); - return it != recipies.end(); + auto it = recipies.find(itemId); + return it != recipies.end(); } -ItemInstance *FurnaceRecipes::getResult(int itemId) +ItemInstance *FurnaceRecipes::getResult(int itemId) { - AUTO_VAR(it, recipies.find(itemId)); - if(it != recipies.end()) + auto it = recipies.find(itemId); + if(it != recipies.end()) { return it->second; } return NULL; } -unordered_map<int, ItemInstance *> *FurnaceRecipes::getRecipies() +unordered_map<int, ItemInstance *> *FurnaceRecipes::getRecipies() { return &recipies; } float FurnaceRecipes::getRecipeValue(int itemId) { - AUTO_VAR(it, recipeValue.find(itemId)); - if (it != recipeValue.end()) + auto it = recipeValue.find(itemId); + if (it != recipeValue.end()) { return it->second; } diff --git a/Minecraft.World/GameRules.cpp b/Minecraft.World/GameRules.cpp index 0e594520..d1d034e2 100644 --- a/Minecraft.World/GameRules.cpp +++ b/Minecraft.World/GameRules.cpp @@ -14,27 +14,6 @@ const int GameRules::RULE_DOTILEDROPS = 5; const int GameRules::RULE_NATURAL_REGENERATION = 7; const int GameRules::RULE_DAYLIGHT = 8; -GameRules::GameRules() -{ - /*registerRule(RULE_DOFIRETICK, L"1"); - registerRule(RULE_MOBGRIEFING, L"1"); - registerRule(RULE_KEEPINVENTORY, L"0"); - registerRule(RULE_DOMOBSPAWNING, L"1"); - registerRule(RULE_DOMOBLOOT, L"1"); - registerRule(RULE_DOTILEDROPS, L"1"); - registerRule(RULE_COMMANDBLOCKOUTPUT, L"1"); - registerRule(RULE_NATURAL_REGENERATION, L"1"); - registerRule(RULE_DAYLIGHT, L"1");*/ -} - -GameRules::~GameRules() -{ - /*for(AUTO_VAR(it,rules.begin()); it != rules.end(); ++it) - { - delete it->second; - }*/ -} - bool GameRules::getBoolean(const int rule) { switch(rule) @@ -60,134 +39,3 @@ bool GameRules::getBoolean(const int rule) return false; } } - -/* -void GameRules::registerRule(const wstring &name, const wstring &startValue) -{ - rules[name] = new GameRule(startValue); -} - -void GameRules::set(const wstring &ruleName, const wstring &newValue) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - gameRule->set(newValue); - } - else - { - registerRule(ruleName, newValue); - } -} - -wstring GameRules::get(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->get(); - } - return L""; -} - -int GameRules::getInt(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->getInt(); - } - return 0; -} - -double GameRules::getDouble(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->getDouble(); - } - return 0; -} - -CompoundTag *GameRules::createTag() -{ - CompoundTag *result = new CompoundTag(L"GameRules"); - - for(AUTO_VAR(it,rules.begin()); it != rules.end(); ++it) - { - GameRule *gameRule = it->second; - result->putString(it->first, gameRule->get()); - } - - return result; -} - -void GameRules::loadFromTag(CompoundTag *tag) -{ - vector<Tag *> *allTags = tag->getAllTags(); - for (AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) - { - Tag *ruleTag = *it; - wstring ruleName = ruleTag->getName(); - wstring value = tag->getString(ruleTag->getName()); - - set(ruleName, value); - } - delete allTags; -} - -// Need to delete returned vector. -vector<wstring> *GameRules::getRuleNames() -{ - vector<wstring> *out = new vector<wstring>(); - for (AUTO_VAR(it, rules.begin()); it != rules.end(); it++) out->push_back(it->first); - return out; -} - -bool GameRules::contains(const wstring &rule) -{ - AUTO_VAR(it, rules.find(rule)); - return it != rules.end(); -} - -GameRules::GameRule::GameRule(const wstring &startValue) -{ - value = L""; - booleanValue = false; - intValue = 0; - doubleValue = 0.0; - set(startValue); -} - -void GameRules::GameRule::set(const wstring &newValue) -{ - value = newValue; - booleanValue = _fromString<bool>(newValue); - intValue = _fromString<int>(newValue); - doubleValue = _fromString<double>(newValue); -} - -wstring GameRules::GameRule::get() -{ - return value; -} - -bool GameRules::GameRule::getBoolean() -{ - return booleanValue; -} - -int GameRules::GameRule::getInt() -{ - return intValue; -} - -double GameRules::GameRule::getDouble() -{ - return doubleValue; -}*/
\ No newline at end of file diff --git a/Minecraft.World/GameRules.h b/Minecraft.World/GameRules.h index 35eddc6c..179b499b 100644 --- a/Minecraft.World/GameRules.h +++ b/Minecraft.World/GameRules.h @@ -34,23 +34,9 @@ public: static const int RULE_NATURAL_REGENERATION; static const int RULE_DAYLIGHT; -private: - unordered_map<wstring, GameRule *> rules; - public: - GameRules(); - ~GameRules(); + GameRules() = default; + ~GameRules() = default; bool getBoolean(const int rule); - - // 4J: Removed unused functions - /*void set(const wstring &ruleName, const wstring &newValue); - void registerRule(const wstring &name, const wstring &startValue); - wstring get(const wstring &ruleName); - int getInt(const wstring &ruleName); - double getDouble(const wstring &ruleName); - CompoundTag *createTag(); - void loadFromTag(CompoundTag *tag); - vector<wstring> *getRuleNames(); - bool contains(const wstring &rule);*/ };
\ No newline at end of file diff --git a/Minecraft.World/GoalSelector.cpp b/Minecraft.World/GoalSelector.cpp index 3e3d99b5..49139f52 100644 --- a/Minecraft.World/GoalSelector.cpp +++ b/Minecraft.World/GoalSelector.cpp @@ -18,10 +18,10 @@ GoalSelector::GoalSelector() GoalSelector::~GoalSelector() { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& goal : goals) { - if((*it)->canDeletePointer) delete (*it)->goal; - delete (*it); + if(goal->canDeletePointer) delete goal->goal; + delete goal; } } @@ -32,15 +32,15 @@ void GoalSelector::addGoal(int prio, Goal *goal, bool canDeletePointer /*= true* void GoalSelector::removeGoal(Goal *toRemove) { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ) - { + for (auto it = goals.begin(); it != goals.end();) + { InternalGoal *ig = *it; Goal *goal = ig->goal; if (goal == toRemove) { - AUTO_VAR(it2, find(usingGoals.begin(), usingGoals.end(), ig) ); - if (it2 != usingGoals.end()) + auto it2 = find(usingGoals.begin(), usingGoals.end(), ig); + if (it2 != usingGoals.end()) { goal->stop(); usingGoals.erase(it2); @@ -63,14 +63,11 @@ void GoalSelector::tick() if(tickCount++ % newGoalRate == 0) { - //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; - //bool isUsing = usingGoals.contains(ig); - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + auto usingIt = find(usingGoals.begin(), usingGoals.end(), ig); - //if (isUsing) + //if (isUsing) if(usingIt != usingGoals.end()) { if (!canUseInSystem(ig) || !canContinueToUse(ig)) @@ -90,8 +87,8 @@ void GoalSelector::tick() } else { - for(AUTO_VAR(it, usingGoals.begin() ); it != usingGoals.end(); ) - { + for (auto it = usingGoals.begin(); it != usingGoals.end();) + { InternalGoal *ig = *it; if (!ig->goal->canContinueToUse()) { @@ -106,21 +103,14 @@ void GoalSelector::tick() } - //bool debug = false; - //if (debug && toStart.size() > 0) System.out.println("Starting: "); - //for (InternalGoal ig : toStart) - for(AUTO_VAR(it, toStart.begin()); it != toStart.end(); ++it) + for(auto & ig : toStart) { - //if (debug) System.out.println(ig.goal.toString() + ", "); - (*it)->goal->start(); + ig->goal->start(); } - //if (debug && usingGoals.size() > 0) System.out.println("Running: "); - //for (InternalGoal ig : usingGoals) - for(AUTO_VAR(it, usingGoals.begin()); it != usingGoals.end(); ++it) + for(auto& ig : usingGoals) { - //if (debug) System.out.println(ig.goal.toString()); - (*it)->goal->tick(); + ig->goal->tick(); } } @@ -137,14 +127,13 @@ bool GoalSelector::canContinueToUse(InternalGoal *ig) bool GoalSelector::canUseInSystem(GoalSelector::InternalGoal *goal) { //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; if (ig == goal) continue; - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + auto usingIt = find(usingGoals.begin(), usingGoals.end(), ig); - if (goal->prio >= ig->prio) + if (goal->prio >= ig->prio) { if (usingIt != usingGoals.end() && !canCoExist(goal, ig)) return false; } @@ -166,9 +155,8 @@ void GoalSelector::setNewGoalRate(int newGoalRate) void GoalSelector::setLevel(Level *level) { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; ig->goal->setLevel(level); } }
\ No newline at end of file diff --git a/Minecraft.World/HangingEntity.cpp b/Minecraft.World/HangingEntity.cpp index 8ba3e1fc..26261710 100644 --- a/Minecraft.World/HangingEntity.cpp +++ b/Minecraft.World/HangingEntity.cpp @@ -10,7 +10,7 @@ void HangingEntity::_init(Level *level) -{ +{ checkInterval = 0; dir = 0; xTile = yTile = zTile = 0; @@ -32,7 +32,7 @@ HangingEntity::HangingEntity(Level *level, int xTile, int yTile, int zTile, int this->zTile = zTile; } -void HangingEntity::setDir(int dir) +void HangingEntity::setDir(int dir) { this->dir = dir; yRotO = yRot = (float)(dir * 90); @@ -41,12 +41,12 @@ void HangingEntity::setDir(int dir) float h = (float)getHeight(); float d = (float)getWidth(); - if (dir == Direction::NORTH || dir == Direction::SOUTH) + if (dir == Direction::NORTH || dir == Direction::SOUTH) { d = 0.5f; yRot = yRotO = (float)(Direction::DIRECTION_OPPOSITE[dir] * 90); - } - else + } + else { w = 0.5f; } @@ -86,14 +86,14 @@ void HangingEntity::setDir(int dir) bb->set(min(x0,x1), min(y0,y1), min(z0,z1), max(x0,x1), max(y0,y1), max(z0,z1)); } -float HangingEntity::offs(int w) +float HangingEntity::offs(int w) { if (w == 32) return 0.5f; if (w == 64) return 0.5f; return 0.0f; } -void HangingEntity::tick() +void HangingEntity::tick() { xo = x; yo = y; @@ -101,7 +101,7 @@ void HangingEntity::tick() if (checkInterval++ == 20 * 5 && !level->isClientSide) { checkInterval = 0; - if (!removed && !survives()) + if (!removed && !survives()) { remove(); dropItem(nullptr); @@ -109,13 +109,13 @@ void HangingEntity::tick() } } -bool HangingEntity::survives() +bool HangingEntity::survives() { - if (level->getCubes(shared_from_this(), bb)->size()!=0)//isEmpty()) + if (level->getCubes(shared_from_this(), bb)->size()!=0)//isEmpty()) { return false; - } - else + } + else { int ws = max(1, getWidth() / 16); int hs = max(1, getHeight() / 16); @@ -131,18 +131,18 @@ bool HangingEntity::survives() for (int ss = 0; ss < ws; ss++) { - for (int yy = 0; yy < hs; yy++) + for (int yy = 0; yy < hs; yy++) { Material *m; - if (dir == Direction::NORTH || dir == Direction::SOUTH) + if (dir == Direction::NORTH || dir == Direction::SOUTH) { m = level->getMaterial(xt + ss, yt + yy, zTile); - } - else + } + else { m = level->getMaterial(xTile, yt + yy, zt + ss); } - if (!m->isSolid()) + if (!m->isSolid()) { return false; } @@ -152,11 +152,9 @@ bool HangingEntity::survives() if (entities != NULL && entities->size() > 0) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); - if( e->instanceof(eTYPE_HANGING_ENTITY) ) + if( e && e->instanceof(eTYPE_HANGING_ENTITY) ) { return false; } @@ -167,12 +165,12 @@ bool HangingEntity::survives() return true; } -bool HangingEntity::isPickable() +bool HangingEntity::isPickable() { return true; } -bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) +bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) { if(source->GetType()==eTYPE_PLAYER) { @@ -181,10 +179,10 @@ bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) return false; } -bool HangingEntity::hurt(DamageSource *source, float damage) +bool HangingEntity::hurt(DamageSource *source, float damage) { if (isInvulnerable()) return false; - if (!removed && !level->isClientSide) + if (!removed && !level->isClientSide) { if (dynamic_cast<EntityDamageSource *>(source) != NULL) { @@ -206,7 +204,7 @@ bool HangingEntity::hurt(DamageSource *source, float damage) player = dynamic_pointer_cast<Player>( e ); } - if (player != NULL && player->abilities.instabuild) + if (player != NULL && player->abilities.instabuild) { return true; } @@ -217,25 +215,25 @@ bool HangingEntity::hurt(DamageSource *source, float damage) } // 4J - added noEntityCubes parameter -void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) +void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) { - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { remove(); dropItem(nullptr); } } -void HangingEntity::push(double xa, double ya, double za) +void HangingEntity::push(double xa, double ya, double za) { - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { remove(); dropItem(nullptr); } } -void HangingEntity::addAdditonalSaveData(CompoundTag *tag) +void HangingEntity::addAdditonalSaveData(CompoundTag *tag) { tag->putByte(L"Direction", (byte) dir); tag->putInt(L"TileX", xTile); @@ -243,7 +241,7 @@ void HangingEntity::addAdditonalSaveData(CompoundTag *tag) tag->putInt(L"TileZ", zTile); // Back compat - switch (dir) + switch (dir) { case Direction::NORTH: tag->putByte(L"Dir", (byte) 0); @@ -260,15 +258,15 @@ void HangingEntity::addAdditonalSaveData(CompoundTag *tag) } } -void HangingEntity::readAdditionalSaveData(CompoundTag *tag) +void HangingEntity::readAdditionalSaveData(CompoundTag *tag) { - if (tag->contains(L"Direction")) + if (tag->contains(L"Direction")) { dir = tag->getByte(L"Direction"); - } - else + } + else { - switch (tag->getByte(L"Dir")) + switch (tag->getByte(L"Dir")) { case 0: dir = Direction::NORTH; diff --git a/Minecraft.World/Hasher.cpp b/Minecraft.World/Hasher.cpp index 954ff1e4..86030e21 100644 --- a/Minecraft.World/Hasher.cpp +++ b/Minecraft.World/Hasher.cpp @@ -19,7 +19,7 @@ wstring Hasher::getHash(wstring &name) //return new BigInteger(1, m.digest()).toString(16); // TODO 4J Stu - Will this hash us with the same distribution as the MD5? - return _toString(std::hash<wstring>{}( s ) ); + return std::to_wstring(std::hash<wstring>{}( s ) ); //} //catch (NoSuchAlgorithmException e) //{ diff --git a/Minecraft.World/HealthCriteria.cpp b/Minecraft.World/HealthCriteria.cpp index 52db9f11..33520621 100644 --- a/Minecraft.World/HealthCriteria.cpp +++ b/Minecraft.World/HealthCriteria.cpp @@ -10,9 +10,8 @@ int HealthCriteria::getScoreModifier(vector<shared_ptr<Player> > *players) { float health = 0; - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + for (auto& player : *players) { - shared_ptr<Player> player = *it; health += player->getHealth() + player->getAbsorptionAmount(); } diff --git a/Minecraft.World/HurtByTargetGoal.cpp b/Minecraft.World/HurtByTargetGoal.cpp index 32bcd3c7..076e5b6a 100644 --- a/Minecraft.World/HurtByTargetGoal.cpp +++ b/Minecraft.World/HurtByTargetGoal.cpp @@ -26,9 +26,9 @@ void HurtByTargetGoal::start() { double within = getFollowDistance(); vector<shared_ptr<Entity> > *nearby = mob->level->getEntitiesOfClass(typeid(*mob), AABB::newTemp(mob->x, mob->y, mob->z, mob->x + 1, mob->y + 1, mob->z + 1)->grow(within, 4, within)); - for(AUTO_VAR(it, nearby->begin()); it != nearby->end(); ++it) + for(auto& it : *nearby) { - shared_ptr<PathfinderMob> other = dynamic_pointer_cast<PathfinderMob>(*it); + shared_ptr<PathfinderMob> other = dynamic_pointer_cast<PathfinderMob>(it); if (this->mob->shared_from_this() == other) continue; if (other->getTarget() != NULL) continue; if (other->isAlliedTo(mob->getLastHurtByMob())) continue; // don't target allies diff --git a/Minecraft.World/ItemEntity.cpp b/Minecraft.World/ItemEntity.cpp index e6bdffa5..66d271f7 100644 --- a/Minecraft.World/ItemEntity.cpp +++ b/Minecraft.World/ItemEntity.cpp @@ -72,7 +72,7 @@ void ItemEntity::defineSynchedData() void ItemEntity::tick() { Entity::tick(); - + if (throwTime > 0) throwTime--; xo = x; yo = y; @@ -80,7 +80,7 @@ void ItemEntity::tick() yd -= 0.04f; noPhysics = checkInTile(x, (bb->y0 + bb->y1) / 2, z); - + // 4J - added parameter here so that these don't care about colliding with other entities move(xd, yd, zd, true); @@ -133,11 +133,11 @@ void ItemEntity::tick() } void ItemEntity::mergeWithNeighbours() -{ +{ vector<shared_ptr<Entity> > *neighbours = level->getEntitiesOfClass(typeid(*this), bb->grow(0.5, 0, 0.5)); - for(AUTO_VAR(it, neighbours->begin()); it != neighbours->end(); ++it) + for(auto& neighbour : *neighbours) { - shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(*it); + shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(neighbour); merge(entity); } delete neighbours; @@ -189,7 +189,7 @@ bool ItemEntity::hurt(DamageSource *source, float damage) // 4J - added next line: found whilst debugging an issue with item entities getting into a bad state when being created by a cactus, since entities insides cactuses get hurt // and therefore depending on the timing of things they could get removed from the client when they weren't supposed to be. Are there really any cases were we would want // an itemEntity to be locally hurt? - if (level->isClientSide ) return false; + if (level->isClientSide ) return false; if (isInvulnerable()) return false; if (getItem() != NULL && getItem()->id == Item::netherStar_Id && source->isExplosion()) return false; @@ -253,7 +253,7 @@ void ItemEntity::playerTouch(shared_ptr<Player> player) } #endif } - if (item->id == Item::blazeRod_Id) + if (item->id == Item::blazeRod_Id) player->awardStat(GenericStats::blazeRod(), GenericStats::param_blazeRod()); playSound(eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); diff --git a/Minecraft.World/ItemInstance.cpp b/Minecraft.World/ItemInstance.cpp index 32367b12..4dcde7aa 100644 --- a/Minecraft.World/ItemInstance.cpp +++ b/Minecraft.World/ItemInstance.cpp @@ -588,7 +588,7 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a /*if (!hasCustomHoverName() && id == Item::map_Id) { - title.text += L" #" + _toString(auxValue); + title.text += L" #" + std::to_wstring(auxValue); }*/ lines->push_back(title); @@ -652,20 +652,20 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a if (!modifiers->empty()) { // New line - lines->push_back(HtmlString(L"")); + lines->emplace_back(L""); // Modifier descriptions - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { // 4J: Moved modifier string building to AttributeModifier - lines->push_back(it->second->getHoverText(it->first)); + lines->push_back(modifier.second->getHoverText(modifier.first)); } } // Delete modifiers map - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& it : *modifiers) { - AttributeModifier *modifier = it->second; + AttributeModifier *modifier = it.second; delete modifier; } delete modifiers; @@ -674,7 +674,7 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a { if (isDamaged()) { - wstring damageStr = L"Durability: LOCALISE " + _toString<int>((getMaxDamage()) - getDamageValue()) + L" / " + _toString<int>(getMaxDamage()); + wstring damageStr = L"Durability: LOCALISE " + std::to_wstring((getMaxDamage()) - getDamageValue()) + L" / " + std::to_wstring(getMaxDamage()); lines->push_back(HtmlString(damageStr)); } } diff --git a/Minecraft.World/LeashFenceKnotEntity.cpp b/Minecraft.World/LeashFenceKnotEntity.cpp index 21f98a6a..55947d04 100644 --- a/Minecraft.World/LeashFenceKnotEntity.cpp +++ b/Minecraft.World/LeashFenceKnotEntity.cpp @@ -79,9 +79,9 @@ bool LeashFenceKnotEntity::interact(shared_ptr<Player> player) vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it, mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( *it ); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( it ); if (mob->isLeashed() && mob->getLeashHolder() == player) { mob->setLeashedTo(shared_from_this(), true); @@ -103,9 +103,9 @@ bool LeashFenceKnotEntity::interact(shared_ptr<Player> player) vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it, mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( *it ); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( it ); if (mob->isLeashed() && mob->getLeashHolder() == shared_from_this()) { mob->dropLeash(true, false); @@ -142,9 +142,9 @@ shared_ptr<LeashFenceKnotEntity> LeashFenceKnotEntity::findKnotAt(Level *level, vector<shared_ptr<Entity> > *knots = level->getEntitiesOfClass(typeid(LeashFenceKnotEntity), AABB::newTemp(x - 1.0, y - 1.0, z - 1.0, x + 1.0, y + 1.0, z + 1.0)); if (knots != NULL) { - for(AUTO_VAR(it, knots->begin()); it != knots->end(); ++it) - { - shared_ptr<LeashFenceKnotEntity> knot = dynamic_pointer_cast<LeashFenceKnotEntity>( *it ); + for (auto& it : *knots ) + { + shared_ptr<LeashFenceKnotEntity> knot = dynamic_pointer_cast<LeashFenceKnotEntity>( it ); if (knot->xTile == x && knot->yTile == y && knot->zTile == z) { delete knots; diff --git a/Minecraft.World/LeashItem.cpp b/Minecraft.World/LeashItem.cpp index d8d7b3fc..ddb7878b 100644 --- a/Minecraft.World/LeashItem.cpp +++ b/Minecraft.World/LeashItem.cpp @@ -38,9 +38,9 @@ bool LeashItem::bindPlayerMobs(shared_ptr<Player> player, Level *level, int x, i vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it,mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(*it); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(it); if (mob->isLeashed() && mob->getLeashHolder() == player) { if (activeKnot == NULL) @@ -64,9 +64,9 @@ bool LeashItem::bindPlayerMobsTest(shared_ptr<Player> player, Level *level, int if (mobs != NULL) { - for(AUTO_VAR(it,mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(*it); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(it); if (mob->isLeashed() && mob->getLeashHolder() == player) return true; } } diff --git a/Minecraft.World/Level.cpp b/Minecraft.World/Level.cpp index f9c383ed..b977ad7d 100644 --- a/Minecraft.World/Level.cpp +++ b/Minecraft.World/Level.cpp @@ -691,7 +691,7 @@ void Level::_init(shared_ptr<LevelStorage>levelStorage, const wstring& levelName //{ // dimension = Dimension::getNew(levelData->getDimension()); //} - else + else { dimension = Dimension::getNew(0); } @@ -740,7 +740,7 @@ Level::~Level() DeleteCriticalSection(&m_checkLightCS); // 4J-PB - savedDataStorage is shared between overworld and nether levels in the server, so it will already have been deleted on the first level delete - if(savedDataStorage!=NULL) delete savedDataStorage; + if(savedDataStorage!=NULL) delete savedDataStorage; DeleteCriticalSection(&m_entitiesCS); DeleteCriticalSection(&m_tileEntityListCS); @@ -934,7 +934,7 @@ bool Level::setTileAndData(int x, int y, int z, int tile, int data, int updateFl int olddata = c->getData( x & 15, y, z & 15); #endif result = c->setTileAndData(x & 15, y, z & 15, tile, data); - if( updateFlags != Tile::UPDATE_INVISIBLE_NO_LIGHT) + if( updateFlags != Tile::UPDATE_INVISIBLE_NO_LIGHT) { #ifndef _CONTENT_PACKAGE PIXBeginNamedEvent(0,"Checking light %d %d %d",x,y,z); @@ -1019,7 +1019,7 @@ bool Level::setData(int x, int y, int z, int data, int updateFlags, bool forceUp /** * Sets a tile to air without dropping resources or showing any animation. -* +* * @param x * @param y * @param z @@ -1033,7 +1033,7 @@ bool Level::removeTile(int x, int y, int z) /** * Sets a tile to air and plays a destruction animation, with option to also * drop resources. -* +* * @param x * @param y * @param z @@ -1063,10 +1063,9 @@ bool Level::setTileAndUpdate(int x, int y, int z, int tile) void Level::sendTileUpdated(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileChanged(x, y, z); + listener->tileChanged(x, y, z); } } @@ -1105,20 +1104,18 @@ void Level::lightColumnChanged(int x, int z, int y0, int y1) void Level::setTileDirty(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->setTilesDirty(x, y, z, x, y, z, this); + listener->setTilesDirty(x, y, z, x, y, z, this); } } void Level::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->setTilesDirty(x0, y0, z0, x1, y1, z1, this); + listener->setTilesDirty(x0, y0, z0, x1, y1, z1, this); } } @@ -1351,7 +1348,7 @@ int Level::getBrightness(LightLayer::variety layer, int x, int y, int z) // the level chunk once void Level::getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z) { - if( ( ( ( x & 15 ) == 0 ) || ( ( x & 15 ) == 15 ) ) || + if( ( ( ( x & 15 ) == 0 ) || ( ( x & 15 ) == 15 ) ) || ( ( ( z & 15 ) == 0 ) || ( ( z & 15 ) == 15 ) ) || ( ( y <= 0 ) || ( y >= 127 ) ) ) { @@ -1443,20 +1440,18 @@ void Level::setBrightness(LightLayer::variety layer, int x, int y, int z, int br } else { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileLightChanged(x, y, z); + listener->tileLightChanged(x, y, z); } } } void Level::setTileBrightnessChanged(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileLightChanged(x, y, z); + listener->tileLightChanged(x, y, z); } } @@ -1637,19 +1632,18 @@ HitResult *Level::clip(Vec3 *a, Vec3 *b, bool liquid, bool solidOnly) void Level::playEntitySound(shared_ptr<Entity> entity, int iSound, float volume, float pitch) { if(entity == NULL) return; - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { // 4J-PB - if the entity is a local player, don't play the sound if(entity->GetType() == eTYPE_SERVERPLAYER) { //app.DebugPrintf("ENTITY is serverplayer\n"); - (*it)->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } else { - (*it)->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } } } @@ -1657,20 +1651,18 @@ void Level::playEntitySound(shared_ptr<Entity> entity, int iSound, float volume, void Level::playPlayerSound(shared_ptr<Player> entity, int iSound, float volume, float pitch) { if (entity == NULL) return; - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playSoundExceptPlayer(entity, iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSoundExceptPlayer(entity, iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } } //void Level::playSound(double x, double y, double z, const wstring& name, float volume, float pitch) void Level::playSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); + listener->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); } } @@ -1680,10 +1672,9 @@ void Level::playLocalSound(double x, double y, double z, int iSound, float volum void Level::playStreamingMusic(const wstring& name, int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playStreamingMusic(name, x, y, z); + listener->playStreamingMusic(name, x, y, z); } } @@ -1692,22 +1683,11 @@ void Level::playMusic(double x, double y, double z, const wstring& string, float { } -// 4J removed - -/* -void Level::addParticle(const wstring& id, double x, double y, double z, double xd, double yd, double zd) -{ -AUTO_VAR(itEnd, listeners.end()); -for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) -(*it)->addParticle(id, x, y, z, xd, yd, zd); -} -*/ - // 4J-PB added void Level::addParticle(ePARTICLE_TYPE id, double x, double y, double z, double xd, double yd, double zd) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - (*it)->addParticle(id, x, y, z, xd, yd, zd); + for (auto& listener : listeners) + listener->addParticle(id, x, y, z, xd, yd, zd); } bool Level::addGlobalEntity(shared_ptr<Entity> e) @@ -1768,48 +1748,45 @@ bool Level::addEntity(shared_ptr<Entity> e) void Level::entityAdded(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->entityAdded(e); + listener->entityAdded(e); } } void Level::entityRemoved(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->entityRemoved(e); + listener->entityRemoved(e); } } // 4J added void Level::playerRemoved(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playerRemoved(e); + listener->playerRemoved(e); } } void Level::removeEntity(shared_ptr<Entity> e) { - if (e->rider.lock() != NULL) + if (e->rider.lock()) { e->rider.lock()->ride(nullptr); } - if (e->riding != NULL) + if (e->riding) { e->ride(nullptr); } e->remove(); if (e->instanceof(eTYPE_PLAYER)) { - vector<shared_ptr<Player> >::iterator it = players.begin(); - vector<shared_ptr<Player> >::iterator itEnd = players.end(); + auto it = players.begin(); + auto itEnd = players.end(); while( it != itEnd && *it != dynamic_pointer_cast<Player>(e) ) it++; @@ -1958,16 +1935,15 @@ AABBList *Level::getCubes(shared_ptr<Entity> source, AABB *box, bool noEntities/ double r = 0.25; vector<shared_ptr<Entity> > *ee = getEntities(source, box->grow(r, r, r)); - vector<shared_ptr<Entity> >::iterator itEnd = ee->end(); - for (AUTO_VAR(it, ee->begin()); it != itEnd; it++) + for (auto& it : *ee) { - AABB *collideBox = (*it)->getCollideBox(); + AABB *collideBox = it->getCollideBox(); if (collideBox != NULL && collideBox->intersects(box)) { boxes.push_back(collideBox); } - collideBox = source->getCollideAgainstBox(*it); + collideBox = source->getCollideAgainstBox(it); if (collideBox != NULL && collideBox->intersects(box)) { boxes.push_back(collideBox); @@ -2277,12 +2253,12 @@ void Level::tickEntities() EnterCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { + for (auto it = entities.begin(); it != entities.end();) + { bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) + for(auto& it2 : entitiesToRemove) { - if( (*it) == (*it2) ) + if( (*it) == it2 ) { found = true; break; @@ -2299,10 +2275,8 @@ void Level::tickEntities() } LeaveCriticalSection(&m_entitiesCS); - AUTO_VAR(itETREnd, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) + for (auto& e : entitiesToRemove) { - shared_ptr<Entity> e = *it;//entitiesToRemove.at(j); int xc = e->xChunk; int zc = e->zChunk; if (e->inChunk && hasChunk(xc, zc)) @@ -2311,12 +2285,11 @@ void Level::tickEntities() } } - itETREnd = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) + for (auto& it : entitiesToRemove) { - entityRemoved(*it); + entityRemoved(it); } - // + // entitiesToRemove.clear(); //for (int i = 0; i < entities.size(); i++) @@ -2348,7 +2321,7 @@ void Level::tickEntities() { #ifndef _FINAL_BUILD if ( !( app.DebugSettingsOn() && app.GetMobsDontTickEnabled() && e->instanceof(eTYPE_MOB) && !e->instanceof(eTYPE_PLAYER)) ) -#endif +#endif { tick(e); } @@ -2367,8 +2340,8 @@ void Level::tickEntities() // 4J Find the entity again before deleting, as things might have moved in the entity array eg // from the explosion created by tnt - AUTO_VAR(it, find(entities.begin(), entities.end(), e)); - if( it != entities.end() ) + auto it = find(entities.begin(), entities.end(), e); + if( it != entities.end() ) { entities.erase(it); } @@ -2385,8 +2358,8 @@ void Level::tickEntities() EnterCriticalSection(&m_tileEntityListCS); updatingTileEntities = true; - for (AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end();) - { + for (auto it = tileEntityList.begin(); it != tileEntityList.end();) + { shared_ptr<TileEntity> te = *it;//tilevector<shared_ptr<Entity> >.at(i); if( !te->isRemoved() && te->hasLevel() ) { @@ -2421,15 +2394,15 @@ void Level::tickEntities() // 4J-PB - Stuart - check this is correct here if (!tileEntitiesToUnload.empty()) - { + { //tileEntityList.removeAll(tileEntitiesToUnload); - for( AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end(); ) - { + for (auto it = tileEntityList.begin(); it != tileEntityList.end();) + { bool found = false; - for( AUTO_VAR(it2, tileEntitiesToUnload.begin()); it2 != tileEntitiesToUnload.end(); it2++ ) + for(auto& it2 : tileEntitiesToUnload) { - if( (*it) == (*it2) ) + if( (*it) == it2 ) { found = true; break; @@ -2453,10 +2426,9 @@ void Level::tickEntities() if( !pendingTileEntities.empty() ) { - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) + for(auto& e : pendingTileEntities) { - shared_ptr<TileEntity> e = *it; - if( !e->isRemoved() ) + if( e && !e->isRemoved() ) { if( find(tileEntityList.begin(),tileEntityList.end(),e) == tileEntityList.end() ) { @@ -2481,16 +2453,16 @@ void Level::addAllPendingTileEntities(vector< shared_ptr<TileEntity> >& entities EnterCriticalSection(&m_tileEntityListCS); if( updatingTileEntities ) { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for(auto& it : entities) { - pendingTileEntities.push_back(*it); + pendingTileEntities.push_back(it); } } else { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for(auto& it : entities) { - tileEntityList.push_back(*it); + tileEntityList.push_back(it); } } LeaveCriticalSection(&m_tileEntityListCS); @@ -2602,11 +2574,9 @@ bool Level::isUnobstructed(AABB *aabb) bool Level::isUnobstructed(AABB *aabb, shared_ptr<Entity> ignore) { vector<shared_ptr<Entity> > *ents = getEntities(nullptr, aabb); - AUTO_VAR(itEnd, ents->end()); - for (AUTO_VAR(it, ents->begin()); it != itEnd; it++) + for (auto& e : *ents) { - shared_ptr<Entity> e = *it; - if (!e->removed && e->blocksBuilding && e != ignore) return false; + if (e && !e->removed && e->blocksBuilding && e != ignore) return false; } return true; } @@ -2841,7 +2811,7 @@ shared_ptr<Explosion> Level::explode(shared_ptr<Entity> source, double x, double shared_ptr<Explosion> Level::explode(shared_ptr<Entity> source, double x, double y, double z, float r, bool fire, bool destroyBlocks) { shared_ptr<Explosion> explosion = shared_ptr<Explosion>( new Explosion(this, source, x, y, z, r) ); - explosion->fire = fire; + explosion->fire = fire; explosion->destroyBlocks = destroyBlocks; explosion->explode(); explosion->finalizeExplosion(true); @@ -2950,11 +2920,9 @@ shared_ptr<TileEntity> Level::getTileEntity(int x, int y, int z) if (tileEntity == NULL) { EnterCriticalSection(&m_tileEntityListCS); - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) + for(auto& e : pendingTileEntities) { - shared_ptr<TileEntity> e = *it; - - if (!e->isRemoved() && e->x == x && e->y == y && e->z == z) + if ( e && !e->isRemoved() && e->x == x && e->y == y && e->z == z) { tileEntity = e; break; @@ -2978,8 +2946,8 @@ void Level::setTileEntity(int x, int y, int z, shared_ptr<TileEntity> tileEntity tileEntity->z = z; // avoid adding duplicates - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end();) - { + for (auto it = pendingTileEntities.begin(); it != pendingTileEntities.end();) + { shared_ptr<TileEntity> next = *it; if (next->x == x && next->y == y && next->z == z) { @@ -3012,8 +2980,8 @@ void Level::removeTileEntity(int x, int y, int z) if (te != NULL && updatingTileEntities) { te->setRemoved(); - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) + auto it = find(pendingTileEntities.begin(), pendingTileEntities.end(), te); + if( it != pendingTileEntities.end() ) { pendingTileEntities.erase(it); } @@ -3022,13 +2990,13 @@ void Level::removeTileEntity(int x, int y, int z) { if (te != NULL) { - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) + auto it = find(pendingTileEntities.begin(), pendingTileEntities.end(), te); + if( it != pendingTileEntities.end() ) { pendingTileEntities.erase(it); } - AUTO_VAR(it2, find(tileEntityList.begin(), tileEntityList.end(), te)); - if( it2 != tileEntityList.end() ) + auto it2 = find(tileEntityList.begin(), tileEntityList.end(), te); + if( it2 != tileEntityList.end() ) { tileEntityList.erase(it2); } @@ -3126,7 +3094,7 @@ bool Level::isTopSolidBlocking(Tile *tile, int data) if (tile == NULL) return false; if (tile->material->isSolidBlocking() && tile->isCubeShaped()) return true; - if (dynamic_cast<StairTile *>(tile) != NULL) + if (dynamic_cast<StairTile *>(tile) != NULL) { return (data & StairTile::UPSIDEDOWN_BIT) == StairTile::UPSIDEDOWN_BIT; } @@ -3273,11 +3241,9 @@ void Level::toggleDownfall() void Level::buildAndPrepareChunksToPoll() { -#if 0 - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) +#if 0 + for (auto& player : players) { - shared_ptr<Player> player = *it; int xx = Mth::floor(player->x / 16); int zz = Mth::floor(player->z / 16); @@ -3295,7 +3261,7 @@ void Level::buildAndPrepareChunksToPoll() int playerCount = (int)players.size(); int *xx = new int[playerCount]; int *zz = new int[playerCount]; - for (int i = 0; i < playerCount; i++) + for (size_t i = 0; i < playerCount; i++) { shared_ptr<Player> player = players[i]; xx[i] = Mth::floor(player->x / 16); @@ -3534,7 +3500,7 @@ void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool f { int centerCurrent = getBrightnessCached(cache, layer, xc, yc, zc); int centerExpected = getExpectedLight(cache, xc, yc, zc, layer, false); - + if( centerExpected != centerCurrent && cache ) { initCacheComplete(cache, xc, yc, zc); @@ -3802,9 +3768,8 @@ shared_ptr<Entity> Level::getClosestEntityOfClass(const type_info& baseClass, AA shared_ptr<Entity> closest = nullptr; double closestDistSqr = Double::MAX_VALUE; //for (Entity entity : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for(auto& entity : *entities) { - shared_ptr<Entity> entity = *it; if (entity == source) continue; double distSqr = source->distanceToSqr(entity); if (distSqr > closestDistSqr) continue; @@ -3837,10 +3802,8 @@ unsigned int Level::countInstanceOf(BaseObject::Class *clas) { unsigned int count = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); if (clas->isAssignableFrom(e->getClass())) count++; } LeaveCriticalSection(&m_entitiesCS); @@ -3857,10 +3820,8 @@ unsigned int Level::countInstanceOf(eINSTANCEOF clas, bool singleType, unsigned if( protectedCount ) *protectedCount = 0; if( couldWanderCount ) *couldWanderCount = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); if( singleType ) { if (e->GetType() == clas) @@ -3892,11 +3853,8 @@ unsigned int Level::countInstanceOfInRange(eINSTANCEOF clas, bool singleType, in { unsigned int count = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); - float sd = e->distanceTo(x,y,z); if (sd * sd > range * range) { @@ -3925,14 +3883,13 @@ void Level::addEntities(vector<shared_ptr<Entity> > *list) //entities.addAll(list); EnterCriticalSection(&m_entitiesCS); entities.insert(entities.end(), list->begin(), list->end()); - AUTO_VAR(itEnd, list->end()); bool deleteDragons = false; - for (AUTO_VAR(it, list->begin()); it != itEnd; it++) + for (auto& it : *list) { - entityAdded(*it); + entityAdded(it); // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) + if( it->GetType() == eTYPE_ENDERDRAGON) { deleteDragons = true; } @@ -3941,14 +3898,14 @@ void Level::addEntities(vector<shared_ptr<Entity> > *list) if(deleteDragons) { deleteDragons = false; - for(AUTO_VAR(it, entities.begin()); it != entities.end(); ++it) + for(auto& it : entities) { // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) + if( it->GetType() == eTYPE_ENDERDRAGON) { if(deleteDragons) { - (*it)->remove(); + it->remove(); } else { @@ -4118,10 +4075,8 @@ shared_ptr<Player> Level::getNearestPlayer(double x, double y, double z, double MemSect(21); double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it;//players.at(i); double dist = p->distanceToSqr(x, y, z); // Allow specifying shorter distances in the vertical @@ -4142,10 +4097,8 @@ shared_ptr<Player> Level::getNearestPlayer(double x, double z, double maxDist) { double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it; double dist = p->distanceToSqr(x, p->y, z); if ((maxDist < 0 || dist < maxDist * maxDist) && (best == -1 || dist < best)) { @@ -4166,11 +4119,8 @@ shared_ptr<Player> Level::getNearestAttackablePlayer(double x, double y, double double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it; - // 4J Stu - Added privilege check if (p->abilities.invulnerable || !p->isAlive() || p->hasInvisiblePrivilege() ) { @@ -4207,28 +4157,26 @@ shared_ptr<Player> Level::getNearestAttackablePlayer(double x, double y, double shared_ptr<Player> Level::getPlayerByName(const wstring& name) { - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& player : players) { - if (name.compare( (*it)->getName()) == 0) + if (name.compare( player->getName()) == 0) { - return *it; //players.at(i); + return player; } } - return shared_ptr<Player>(); + return {}; } shared_ptr<Player> Level::getPlayerByUUID(const wstring& name) { - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& player : players) { - if (name.compare( (*it)->getUUID() ) == 0) + if (name.compare( player->getUUID() ) == 0) { - return *it; //players.at(i); + return player; } } - return shared_ptr<Player>(); + return {}; } // 4J Stu - Removed in 1.2.3 ? @@ -4355,10 +4303,9 @@ void Level::setGameTime(__int64 time) // Apply stat to each player. if ( timeDiff > 0 && levelData->getGameTime() != -1 ) { - AUTO_VAR(itEnd, players.end()); - for (vector<shared_ptr<Player> >::iterator it = players.begin(); it != itEnd; it++) + for (auto& player : players) { - (*it)->awardStat( GenericStats::timePlayed(), GenericStats::param_time(timeDiff) ); + player->awardStat( GenericStats::timePlayed(), GenericStats::param_time(timeDiff) ); } } } @@ -4538,12 +4485,11 @@ int Level::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int ce return savedDataStorage->getAuxValueForMap(xuid, dimension, centreXC, centreZC, scale); } -void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) +void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->globalLevelEvent(type, sourceX, sourceY, sourceZ, data); + listener->globalLevelEvent(type, sourceX, sourceY, sourceZ, data); } } @@ -4555,10 +4501,9 @@ void Level::levelEvent(int type, int x, int y, int z, int data) void Level::levelEvent(shared_ptr<Player> source, int type, int x, int y, int z, int data) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->levelEvent(source, type, x, y, z, data); + listener->levelEvent(source, type, x, y, z, data); } } @@ -4594,9 +4539,9 @@ bool Level::isAllEmpty() return false; } -double Level::getHorizonHeight() +double Level::getHorizonHeight() { - if (levelData->getGenerator() == LevelType::lvl_flat) + if (levelData->getGenerator() == LevelType::lvl_flat) { return 0.0; } @@ -4605,10 +4550,9 @@ double Level::getHorizonHeight() void Level::destroyTileProgress(int id, int x, int y, int z, int progress) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->destroyTileProgress(id, x, y, z, progress); + listener->destroyTileProgress(id, x, y, z, progress); } } diff --git a/Minecraft.World/LevelChunk.cpp b/Minecraft.World/LevelChunk.cpp index 920fdfc1..d4be5ac2 100644 --- a/Minecraft.World/LevelChunk.cpp +++ b/Minecraft.World/LevelChunk.cpp @@ -54,7 +54,7 @@ void LevelChunk::init(Level *level, int x, int z) biomes = byteArray(16 * 16); for(int i = 0; i < 16 * 16; i++ ) { - biomes[i] = 0xff; + biomes[i] = 0xff; } #ifdef _ENTITIES_RW_SECTION EnterCriticalRWSection(&m_csEntities, true); @@ -109,12 +109,12 @@ void LevelChunk::init(Level *level, int x, int z) // Optimisation brought forward from 1.8.2, change from int to unsigned char & this special value changed from -999 to 255 for(int i = 0; i < 16 * 16; i++ ) { - rainHeights[i] = 255; + rainHeights[i] = 255; } // 4J - lighting change brought forward from 1.8.2, introduced an array of bools called gapsToRecheck, which are now a single bit in array of nybble flags in this version for(int i = 0; i < 8 * 16; i++ ) { - columnFlags[i] = 0; + columnFlags[i] = 0; } // 4J added - to flag if any emissive tile has been added to this chunk (will be cleared when lighting has been successfully completed for this chunk). Defaulting to true @@ -128,7 +128,7 @@ void LevelChunk::init(Level *level, int x, int z) } // This ctor is used for loading a save into -LevelChunk::LevelChunk(Level *level, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, int x, int z) { init(level, x, z); lowerBlocks = new CompressedTileStorage(); @@ -160,7 +160,7 @@ LevelChunk::LevelChunk(Level *level, int x, int z) : ENTITY_BLOCKS_LENGTH( Level // 4J - note that since we now compress the block storage, the parameter blocks is used as a source of data, but doesn't get used As the source data so needs // to be deleted after calling this ctor. -LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) { init(level, x, z); @@ -189,7 +189,7 @@ LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BL // skyLight = new DataLayer(blocks.length, level->depthBits); // blockLight = new DataLayer(blocks.length, level->depthBits); - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { if(blocks.length > Level::COMPRESSED_CHUNK_SECTION_TILES) upperBlocks = new CompressedTileStorage(blocks,Level::COMPRESSED_CHUNK_SECTION_TILES); else upperBlocks = new CompressedTileStorage(true); @@ -213,7 +213,7 @@ LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BL // 4J - this ctor added to be able to make a levelchunk that shares its underlying block data between the server chunk cache & the multiplayer chunk cache. // The original version this is shared from owns all the data that is shared into this copy, so it isn't deleted in the dtor. -LevelChunk::LevelChunk(Level *level, int x, int z, LevelChunk *lc) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, int x, int z, LevelChunk *lc) { init(level, x, z); @@ -705,7 +705,7 @@ void LevelChunk::recheckGaps(bool bForce) // 4J added - otherwise we can end up doing a very broken kind of lighting since for an empty chunk, the heightmap is all zero, but it // still has an x and z of 0 which means that the level->getHeightmap references in here find a real chunk near the origin, and then attempt // to light massive gaps between the height of 0 and whatever heights are in those. - if( isEmpty() ) return; + if( isEmpty() ) return; // 4J added int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; @@ -773,7 +773,7 @@ void LevelChunk::lightGap(int x, int z, int source) { lightGap(x, z, source, height + 1); } - else if (height < source) + else if (height < source) { lightGap(x, z, height, source + 1); } @@ -900,7 +900,7 @@ void LevelChunk::recalcHeight(int x, int yStart, int z) /** * The purpose of this method is to allow the EmptyLevelChunk to be all air * but still block light. See EmptyLevelChunk.java -* +* * @param x * @param y * @param z @@ -1240,7 +1240,7 @@ void LevelChunk::removeEntity(shared_ptr<Entity> e, int yc) #endif // 4J - was entityBlocks[yc]->remove(e); - AUTO_VAR(it, find(entityBlocks[yc]->begin(),entityBlocks[yc]->end(),e)); + auto it = find(entityBlocks[yc]->begin(), entityBlocks[yc]->end(), e); if( it != entityBlocks[yc]->end() ) { entityBlocks[yc]->erase(it); @@ -1250,7 +1250,7 @@ void LevelChunk::removeEntity(shared_ptr<Entity> e, int yc) // MGH - have to sort this C++11 code static bool bShowMsg = true; if(bShowMsg) - { + { app.DebugPrintf("Need to add C++11 shrink_to_fit for PS3\n"); bShowMsg = false; } @@ -1292,7 +1292,7 @@ shared_ptr<TileEntity> LevelChunk::getTileEntity(int x, int y, int z) //shared_ptr<TileEntity> tileEntity = tileEntities[pos]; EnterCriticalSection(&m_csTileEntities); shared_ptr<TileEntity> tileEntity = nullptr; - AUTO_VAR(it, tileEntities.find(pos)); + auto it = tileEntities.find(pos); if (it == tileEntities.end()) { @@ -1320,8 +1320,8 @@ shared_ptr<TileEntity> LevelChunk::getTileEntity(int x, int y, int z) // 4J Stu - It should have been inserted by now, but check to be sure EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(newIt, tileEntities.find(pos)); - if (newIt != tileEntities.end()) + auto newIt = tileEntities.find(pos); + if (newIt != tileEntities.end()) { tileEntity = newIt->second; } @@ -1371,8 +1371,8 @@ void LevelChunk::setTileEntity(int x, int y, int z, shared_ptr<TileEntity> tileE app.DebugPrintf("Attempted to place a tile entity where there was no entity tile!\n"); return; } - AUTO_VAR(it, tileEntities.find(pos) ); - if(it != tileEntities.end()) it->second->setRemoved(); + auto it = tileEntities.find(pos); + if(it != tileEntities.end()) it->second->setRemoved(); tileEntity->clearRemoved(); @@ -1393,8 +1393,8 @@ void LevelChunk::removeTileEntity(int x, int y, int z) // removeThis.setRemoved(); // } EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(it, tileEntities.find(pos)); - if( it != tileEntities.end() ) + auto it = tileEntities.find(pos); + if( it != tileEntities.end() ) { shared_ptr<TileEntity> te = tileEntities[pos]; tileEntities.erase(pos); @@ -1456,9 +1456,9 @@ void LevelChunk::load() vector< shared_ptr<TileEntity> > values; EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) + for(auto& it : tileEntities) { - values.push_back(it->second); + values.push_back(it.second); } LeaveCriticalSection(&m_csTileEntities); level->addAllPendingTileEntities(values); @@ -1492,10 +1492,10 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter if( unloadTileEntities ) { EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) + for(auto& it : tileEntities) { // 4J-PB -m 1.7.3 was it->second->setRemoved(); - level->markForRemoval(it->second); + level->markForRemoval(it.second); } LeaveCriticalSection(&m_csTileEntities); } @@ -1531,16 +1531,13 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter EnterCriticalSection(&m_csEntities); for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { - AUTO_VAR(itEnd, entityBlocks[i]->end()); - for( vector<shared_ptr<Entity> >::iterator it = entityBlocks[i]->begin(); it != itEnd; it++ ) + for(auto& e : *entityBlocks[i]) { - shared_ptr<Entity> e = *it; CompoundTag *teTag = new CompoundTag(); if (e->save(teTag)) { entityTags->add(teTag); } - } // Clear out this list @@ -1554,13 +1551,10 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd,tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = tileEntities.begin(); - it != itEnd; it++) + for(auto& it : tileEntities) { - shared_ptr<TileEntity> te = it->second; CompoundTag *teTag = new CompoundTag(); - te->save(teTag); + it.second->save(teTag); tileEntityTags->add(teTag); } // Clear out the tileEntities list @@ -1632,20 +1626,18 @@ void LevelChunk::getEntities(shared_ptr<Entity> except, AABB *bb, vector<shared_ { vector<shared_ptr<Entity> > *entities = entityBlocks[yc]; - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) + if ( e && e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) { es.push_back(e); vector<shared_ptr<Entity> > *subs = e->getSubEntities(); if (subs != NULL) { - for (int j = 0; j < subs->size(); j++) + for (const auto& sub : *subs) { - e = subs->at(j); - if (e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) + e = sub; + if ( e && e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) { es.push_back(e); } @@ -1689,11 +1681,8 @@ void LevelChunk::getEntitiesOfClass(const type_info& ec, AABB *bb, vector<shared { vector<shared_ptr<Entity> > *entities = entityBlocks[yc]; - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - bool isAssignableFrom = false; // Some special cases where the base class is a general type that our class may be derived from, otherwise do a direct comparison of type_info if ( ec==typeid(Player) ) isAssignableFrom = e->instanceof(eTYPE_PLAYER); @@ -1929,9 +1918,9 @@ int LevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, } */ - for(AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); ++it) + for(auto& it : tileEntities) { - it->second->clearCache(); + it.second->clearCache(); } // recalcHeightmap(); @@ -2216,7 +2205,7 @@ void LevelChunk::setSkyLightDataAllBright() void LevelChunk::compressLighting() { // The lighting data is now generally not shared between host & local client, but is for a while at the start of level creation (until the point where the chunk data would be transferred by network - // data for remote clients). We'll therefore either be compressing a shared copy here or one of the server or client copies depending on + // data for remote clients). We'll therefore either be compressing a shared copy here or one of the server or client copies depending on lowerSkyLight->compress(); upperSkyLight->compress(); lowerBlockLight->compress(); @@ -2532,7 +2521,7 @@ void LevelChunk::reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, byteA //setBlocksAndData(*data, x0, y0, z0, x1, y1, z1, p); //// If it is a full chunk, we'll need to rearrange into the order the rest of the game expects - //if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) + //if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) //{ // byteArray newBuffer = byteArray(81920); // for( int x = 0; x < 16; x++ ) diff --git a/Minecraft.World/LevelChunk.h b/Minecraft.World/LevelChunk.h index bc45016b..661fbdac 100644 --- a/Minecraft.World/LevelChunk.h +++ b/Minecraft.World/LevelChunk.h @@ -29,9 +29,8 @@ class LevelChunk public: byteArray biomes; // 4J Stu - Made public - // 4J Stu - No longer static in 1.8.2 - const int ENTITY_BLOCKS_LENGTH; - static const int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added + static constexpr int ENTITY_BLOCKS_LENGTH = Level::maxBuildHeight/16; + static constexpr int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added static bool touchedSky; diff --git a/Minecraft.World/LightningBolt.cpp b/Minecraft.World/LightningBolt.cpp index 7f32c8ec..a109d96b 100644 --- a/Minecraft.World/LightningBolt.cpp +++ b/Minecraft.World/LightningBolt.cpp @@ -9,7 +9,7 @@ #include "net.minecraft.world.level.dimension.h" -LightningBolt::LightningBolt(Level *level, double x, double y, double z) : +LightningBolt::LightningBolt(Level *level, double x, double y, double z) : life( 0 ), seed( 0 ), flashes( 0 ), @@ -103,10 +103,8 @@ void LightningBolt::tick() { double r = 3; vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), AABB::newTemp(x - r, y - r, z - r, x + r, y + 6 + r, z + r)); - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); //entities->at(i); e->thunderHit(this); } } diff --git a/Minecraft.World/ListTag.h b/Minecraft.World/ListTag.h index c80c0f39..69e51aee 100644 --- a/Minecraft.World/ListTag.h +++ b/Minecraft.World/ListTag.h @@ -20,9 +20,8 @@ public: dos->writeByte(type); dos->writeInt((int)list.size()); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - (*it)->write(dos); + for ( auto& it : list ) + it->write(dos); } void load(DataInput *dis, int tagDepth) @@ -52,7 +51,7 @@ public: wstring toString() { static wchar_t buf[64]; - swprintf(buf,64,L"%d entries of type %ls",list.size(),Tag::getTagName(type)); + swprintf(buf,64,L"%zu entries of type %ls",list.size(),Tag::getTagName(type)); return wstring( buf ); } @@ -65,9 +64,8 @@ public: char *newPrefix = new char[ strlen(prefix) + 4 ]; strcpy( newPrefix, prefix); strcat( newPrefix, " "); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - (*it)->print(newPrefix, out); + for ( auto& it : list ) + it->print(newPrefix, out); delete[] newPrefix; out << prefix << "}" << endl; } @@ -95,10 +93,9 @@ public: virtual ~ListTag() { - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) + for ( auto& it : list ) { - delete *it; + delete it; } } @@ -106,10 +103,9 @@ public: { ListTag<T> *res = new ListTag<T>(getName()); res->type = type; - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) + for ( auto& it : list ) { - T *copy = (T *) (*it)->copy(); + T *copy = (T *) it->copy(); res->list.push_back(copy); } return res; @@ -126,14 +122,13 @@ public: if(list.size() == o->list.size()) { equal = true; - AUTO_VAR(itEnd, list.end()); // 4J Stu - Pretty inefficient method, but I think we can live with it give how often it will happen, and the small sizes of the data sets - for (AUTO_VAR(it, list.begin()); it != itEnd; ++it) + for ( auto& it : list ) { bool thisMatches = false; - for(AUTO_VAR(it2, o->list.begin()); it2 != o->list.end(); ++it2) + for( auto it2 : o->list ) { - if((*it)->equals(*it2)) + if(it->equals(it2)) { thisMatches = true; break; diff --git a/Minecraft.World/LivingEntity.cpp b/Minecraft.World/LivingEntity.cpp index 5f8a3dd1..ef5658c3 100644 --- a/Minecraft.World/LivingEntity.cpp +++ b/Minecraft.World/LivingEntity.cpp @@ -118,9 +118,9 @@ LivingEntity::LivingEntity( Level* level) : Entity(level) LivingEntity::~LivingEntity() { - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto& it : activeEffects) { - delete it->second; + delete it.second; } delete attributes; @@ -129,7 +129,7 @@ LivingEntity::~LivingEntity() if(lastEquipment.data != NULL) delete [] lastEquipment.data; } -void LivingEntity::defineSynchedData() +void LivingEntity::defineSynchedData() { entityData->define(DATA_EFFECT_COLOR_ID, 0); entityData->define(DATA_EFFECT_AMBIENCE_ID, (byte) 0); @@ -186,12 +186,12 @@ bool LivingEntity::isWaterMob() return false; } -void LivingEntity::baseTick() +void LivingEntity::baseTick() { oAttackAnim = attackAnim; Entity::baseTick(); - if (isAlive() && isInWall()) + if (isAlive() && isInWall()) { hurt(DamageSource::inWall, 1); } @@ -202,7 +202,7 @@ void LivingEntity::baseTick() if (isAlive() && isUnderLiquid(Material::water)) { - if(!isWaterMob() && !hasEffect(MobEffect::waterBreathing->id) && !isInvulnerable) + if(!isWaterMob() && !hasEffect(MobEffect::waterBreathing->id) && !isInvulnerable) { setAirSupply(decreaseAirSupply(getAirSupply())); if (getAirSupply() == -20) @@ -227,8 +227,8 @@ void LivingEntity::baseTick() { ride(nullptr); } - } - else + } + else { setAirSupply(TOTAL_AIR_SUPPLY); } @@ -238,7 +238,7 @@ void LivingEntity::baseTick() if (attackTime > 0) attackTime--; if (hurtTime > 0) hurtTime--; if (invulnerableTime > 0) invulnerableTime--; - if (getHealth() <= 0) + if (getHealth() <= 0) { tickDeath(); } @@ -281,9 +281,9 @@ bool LivingEntity::isBaby() } void LivingEntity::tickDeath() -{ +{ deathTime++; - if (deathTime == 20) + if (deathTime == 20) { // 4J Stu - Added level->isClientSide check from 1.2 to fix XP orbs being created client side if(!level->isClientSide && (lastHurtByPlayerTime > 0 || isAlwaysExperienceDropper()) ) @@ -301,7 +301,7 @@ void LivingEntity::tickDeath() } remove(); - for (int i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { double xa = random->nextGaussian() * 0.02; double ya = random->nextGaussian() * 0.02; @@ -422,16 +422,16 @@ void LivingEntity::addAdditonalSaveData(CompoundTag *entityTag) { ListTag<CompoundTag> *listTag = new ListTag<CompoundTag>(); - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto & it : activeEffects) { - MobEffectInstance *effect = it->second; + MobEffectInstance *effect = it.second; listTag->add(effect->save(new CompoundTag())); } entityTag->put(L"ActiveEffects", listTag); } } -void LivingEntity::readAdditionalSaveData(CompoundTag *tag) +void LivingEntity::readAdditionalSaveData(CompoundTag *tag) { setAbsorptionAmount(tag->getFloat(L"AbsorptionAmount")); @@ -481,8 +481,8 @@ void LivingEntity::readAdditionalSaveData(CompoundTag *tag) void LivingEntity::tickEffects() { bool removed = false; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();) - { + for (auto it = activeEffects.begin(); it != activeEffects.end();) + { MobEffectInstance *effect = it->second; removed = false; if (!effect->tick(dynamic_pointer_cast<LivingEntity>(shared_from_this()))) @@ -520,9 +520,9 @@ void LivingEntity::tickEffects() else { vector<MobEffectInstance *> values; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();++it) + for(auto& it : activeEffects) { - values.push_back(it->second); + values.push_back(it.second); } int colorValue = PotionBrewing::getColorValue(&values); entityData->set(DATA_EFFECT_AMBIENCE_ID, PotionBrewing::areAllEffectsAmbient(&values) ? (byte) 1 : (byte) 0); @@ -570,16 +570,12 @@ void LivingEntity::tickEffects() void LivingEntity::removeAllEffects() { - //Iterator<Integer> effectIdIterator = activeEffects.keySet().iterator(); - //while (effectIdIterator.hasNext()) - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ) - { - //Integer effectId = effectIdIterator.next(); + for (auto it = activeEffects.begin(); it != activeEffects.end();) + { MobEffectInstance *effect = it->second;//activeEffects.get(effectId); if (!level->isClientSide) { - //effectIdIterator.remove(); it = activeEffects.erase(it); onEffectRemoved(effect); delete effect; @@ -595,9 +591,9 @@ vector<MobEffectInstance *> *LivingEntity::getActiveEffects() { vector<MobEffectInstance *> *active = new vector<MobEffectInstance *>(); - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto& it : activeEffects) { - active->push_back(it->second); + active->push_back(it.second); } return active; @@ -617,8 +613,8 @@ MobEffectInstance *LivingEntity::getEffect(MobEffect *effect) { MobEffectInstance *effectInst = NULL; - AUTO_VAR(it, activeEffects.find(effect->id)); - if(it != activeEffects.end() ) effectInst = it->second; + auto it = activeEffects.find(effect->id); + if(it != activeEffects.end() ) effectInst = it->second; return effectInst; } @@ -685,8 +681,8 @@ bool LivingEntity::isInvertedHealAndHarm() void LivingEntity::removeEffectNoUpdate(int effectId) { - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) + auto it = activeEffects.find(effectId); + if (it != activeEffects.end()) { MobEffectInstance *effect = it->second; if(effect != NULL) @@ -699,8 +695,8 @@ void LivingEntity::removeEffectNoUpdate(int effectId) void LivingEntity::removeEffect(int effectId) { - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) + auto it = activeEffects.find(effectId); + if (it != activeEffects.end()) { MobEffectInstance *effect = it->second; if(effect != NULL) @@ -734,7 +730,7 @@ void LivingEntity::onEffectRemoved(MobEffectInstance *effect) if (!level->isClientSide) MobEffect::effects[effect->getId()]->removeAttributeModifiers(dynamic_pointer_cast<LivingEntity>(shared_from_this()), getAttributes(), effect->getAmplifier()); } -void LivingEntity::heal(float heal) +void LivingEntity::heal(float heal) { float health = getHealth(); if (health > 0) @@ -753,7 +749,7 @@ void LivingEntity::setHealth(float health) entityData->set(DATA_HEALTH_ID, Mth::clamp(health, 0.0f, getMaxHealth())); } -bool LivingEntity::hurt(DamageSource *source, float dmg) +bool LivingEntity::hurt(DamageSource *source, float dmg) { if (isInvulnerable()) return false; @@ -786,14 +782,14 @@ bool LivingEntity::hurt(DamageSource *source, float dmg) walkAnimSpeed = 1.5f; bool sound = true; - if (invulnerableTime > invulnerableDuration / 2.0f) + if (invulnerableTime > invulnerableDuration / 2.0f) { if (dmg <= lastHurt) return false; if(!level->isClientSide) actuallyHurt(source, dmg - lastHurt); lastHurt = dmg; sound = false; - } - else + } + else { lastHurt = dmg; lastHealth = getHealth(); @@ -837,31 +833,31 @@ bool LivingEntity::hurt(DamageSource *source, float dmg) { level->broadcastEntityEvent(shared_from_this(), EntityEvent::HURT); if (source != DamageSource::drown) markHurt(); - if (sourceEntity != NULL) + if (sourceEntity != NULL) { double xd = sourceEntity->x - x; double zd = sourceEntity->z - z; - while (xd * xd + zd * zd < 0.0001) + while (xd * xd + zd * zd < 0.0001) { xd = (Math::random() - Math::random()) * 0.01; zd = (Math::random() - Math::random()) * 0.01; } hurtDir = (float) (atan2(zd, xd) * 180 / PI) - yRot; knockback(sourceEntity, dmg, xd, zd); - } - else + } + else { hurtDir = (float) (int) ((Math::random() * 2) * 180); // 4J This cast is the same as Java } } MemSect(31); - if (getHealth() <= 0) + if (getHealth() <= 0) { if (sound) playSound(getDeathSound(), getSoundVolume(), getVoicePitch()); die(source); - } - else + } + else { if (sound) playSound(getHurtSound(), getSoundVolume(), getVoicePitch()); } @@ -888,7 +884,7 @@ void LivingEntity::breakItem(shared_ptr<ItemInstance> itemInstance) } } -void LivingEntity::die(DamageSource *source) +void LivingEntity::die(DamageSource *source) { shared_ptr<Entity> sourceEntity = source->getEntity(); shared_ptr<LivingEntity> killer = getKillCredit(); @@ -898,11 +894,11 @@ void LivingEntity::die(DamageSource *source) dead = true; - if (!level->isClientSide) + if (!level->isClientSide) { int playerBonus = 0; - shared_ptr<Player> player = nullptr; + shared_ptr<Player> player = nullptr; if ( (sourceEntity != NULL) && sourceEntity->instanceof(eTYPE_PLAYER) ) { player = dynamic_pointer_cast<Player>(sourceEntity); @@ -937,7 +933,7 @@ void LivingEntity::dropEquipment(bool byPlayer, int playerBonusLevel) { } -void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, double zd) +void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, double zd) { if (random->nextDouble() < getAttribute(SharedMonsterAttributes::KNOCKBACK_RESISTANCE)->getValue()) { @@ -959,12 +955,12 @@ void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, do if (yd > 0.4f) yd = 0.4f; } -int LivingEntity::getHurtSound() +int LivingEntity::getHurtSound() { return eSoundType_DAMAGE_HURT; } -int LivingEntity::getDeathSound() +int LivingEntity::getDeathSound() { return eSoundType_DAMAGE_HURT; } @@ -972,7 +968,7 @@ int LivingEntity::getDeathSound() /** * Drop extra rare loot. Only occurs roughly 5% of the time, rareRootLevel * is set to 1 (otherwise 0) 1% of the time. -* +* * @param rareLootLevel */ void LivingEntity::dropRareDeathLoot(int rareLootLevel) @@ -980,11 +976,11 @@ void LivingEntity::dropRareDeathLoot(int rareLootLevel) } -void LivingEntity::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) +void LivingEntity::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { } -bool LivingEntity::onLadder() +bool LivingEntity::onLadder() { int xt = Mth::floor(x); int yt = Mth::floor(bb->y0); @@ -995,24 +991,24 @@ bool LivingEntity::onLadder() return (iTile== Tile::ladder_Id) || (iTile== Tile::vine_Id); } -bool LivingEntity::isShootable() +bool LivingEntity::isShootable() { return true; } -bool LivingEntity::isAlive() +bool LivingEntity::isAlive() { return !removed && getHealth() > 0; } -void LivingEntity::causeFallDamage(float distance) +void LivingEntity::causeFallDamage(float distance) { Entity::causeFallDamage(distance); MobEffectInstance *jumpBoost = getEffect(MobEffect::jump); float padding = jumpBoost != NULL ? jumpBoost->getAmplifier() + 1 : 0; int dmg = (int) ceil(distance - 3 - padding); - if (dmg > 0) + if (dmg > 0) { // 4J - new sounds here brought forward from 1.2.3 if (dmg > 4) @@ -1026,7 +1022,7 @@ void LivingEntity::causeFallDamage(float distance) hurt(DamageSource::fall, dmg); int t = level->getTile( Mth::floor(x), Mth::floor(y - 0.2f - this->heightOffset), Mth::floor(z)); - if (t > 0) + if (t > 0) { const Tile::SoundType *soundType = Tile::tiles[t]->soundType; MemSect(31); @@ -1036,7 +1032,7 @@ void LivingEntity::causeFallDamage(float distance) } } -void LivingEntity::animateHurt() +void LivingEntity::animateHurt() { hurtTime = hurtDuration = 10; hurtDir = 0; @@ -1044,7 +1040,7 @@ void LivingEntity::animateHurt() /** * Fetches the mob's armor value, from 0 (no armor) to 20 (full armor) -* +* * @return */ int LivingEntity::getArmorValue() @@ -1111,7 +1107,7 @@ float LivingEntity::getDamageAfterMagicAbsorb(DamageSource *damageSource, float return damage; } -void LivingEntity::actuallyHurt(DamageSource *source, float dmg) +void LivingEntity::actuallyHurt(DamageSource *source, float dmg) { if (isInvulnerable()) return; dmg = getDamageAfterArmorAbsorb(source, dmg); @@ -1183,9 +1179,9 @@ void LivingEntity::swing() } } -void LivingEntity::handleEntityEvent(byte id) +void LivingEntity::handleEntityEvent(byte id) { - if (id == EntityEvent::HURT) + if (id == EntityEvent::HURT) { walkAnimSpeed = 1.5f; @@ -1197,32 +1193,32 @@ void LivingEntity::handleEntityEvent(byte id) // 4J-PB -added because villagers have no sounds int iHurtSound=getHurtSound(); if(iHurtSound!=-1) - { + { playSound(iHurtSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); } MemSect(0); hurt(DamageSource::genericSource, 0); - } - else if (id == EntityEvent::DEATH) + } + else if (id == EntityEvent::DEATH) { MemSect(31); // 4J-PB -added because villagers have no sounds int iDeathSound=getDeathSound(); if(iDeathSound!=-1) - { + { playSound(iDeathSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); } MemSect(0); setHealth(0); die(DamageSource::genericSource); - } - else + } + else { Entity::handleEntityEvent(id); } } -void LivingEntity::outOfWorld() +void LivingEntity::outOfWorld() { hurt(DamageSource::outOfWorld, 4); } @@ -1282,7 +1278,7 @@ void LivingEntity::setSprinting(bool value) } } -float LivingEntity::getSoundVolume() +float LivingEntity::getSoundVolume() { return 1; } @@ -1297,12 +1293,12 @@ float LivingEntity::getVoicePitch() return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f; } -bool LivingEntity::isImmobile() +bool LivingEntity::isImmobile() { return getHealth() <= 0; } -void LivingEntity::teleportTo(double x, double y, double z) +void LivingEntity::teleportTo(double x, double y, double z) { moveTo(x, y, z, yRot, xRot); } @@ -1352,12 +1348,12 @@ bool LivingEntity::shouldShowName() return false; } -Icon *LivingEntity::getItemInHandIcon(shared_ptr<ItemInstance> item, int layer) +Icon *LivingEntity::getItemInHandIcon(shared_ptr<ItemInstance> item, int layer) { return item->getIcon(); } -void LivingEntity::jumpFromGround() +void LivingEntity::jumpFromGround() { yd = 0.42f; if (hasEffect(MobEffect::jump)) @@ -1374,7 +1370,7 @@ void LivingEntity::jumpFromGround() this->hasImpulse = true; } -void LivingEntity::travel(float xa, float ya) +void LivingEntity::travel(float xa, float ya) { #ifdef __PSVITA__ // AP - dynamic_pointer_cast is a non-trivial call @@ -1386,7 +1382,7 @@ void LivingEntity::travel(float xa, float ya) #else shared_ptr<Player> thisPlayer = dynamic_pointer_cast<Player>(shared_from_this()); #endif - if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying) ) + if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying) ) { double yo = y; moveRelative(xa, ya, useNewAi() ? 0.04f : 0.02f); @@ -1397,12 +1393,12 @@ void LivingEntity::travel(float xa, float ya) zd *= 0.80f; yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { yd = 0.3f; } - } - else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying) ) + } + else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying) ) { double yo = y; moveRelative(xa, ya, 0.02f); @@ -1412,19 +1408,19 @@ void LivingEntity::travel(float xa, float ya) zd *= 0.50f; yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { yd = 0.3f; } - } - else + } + else { float friction = 0.91f; - if (onGround) + if (onGround) { friction = 0.6f * 0.91f; int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) + if (t > 0) { friction = Tile::tiles[t]->friction * 0.91f; } @@ -1445,16 +1441,16 @@ void LivingEntity::travel(float xa, float ya) moveRelative(xa, ya, speed); friction = 0.91f; - if (onGround) + if (onGround) { friction = 0.6f * 0.91f; int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) + if (t > 0) { friction = Tile::tiles[t]->friction * 0.91f; } } - if (onLadder()) + if (onLadder()) { float max = 0.15f; if (xd < -max) xd = -max; @@ -1469,7 +1465,7 @@ void LivingEntity::travel(float xa, float ya) move(xd, yd, zd); - if (horizontalCollision && onLadder()) + if (horizontalCollision && onLadder()) { yd = 0.2; } @@ -1570,12 +1566,12 @@ bool LivingEntity::doHurtTarget(shared_ptr<Entity> target) return false; } -bool LivingEntity::isSleeping() +bool LivingEntity::isSleeping() { return false; } -void LivingEntity::tick() +void LivingEntity::tick() { Entity::tick(); @@ -1622,17 +1618,17 @@ void LivingEntity::tick() float walkSpeed = 0; oRun = run; float tRun = 0; - if (sideDist > 0.05f * 0.05f) + if (sideDist > 0.05f * 0.05f) { tRun = 1; walkSpeed = sqrt(sideDist) * 3; yBodyRotT = ((float) atan2(zd, xd) * 180 / (float) PI - 90); } - if (attackAnim > 0) + if (attackAnim > 0) { yBodyRotT = yRot; } - if (!onGround) + if (!onGround) { tRun = 0; } @@ -1686,10 +1682,10 @@ float LivingEntity::tickHeadTurn(float yBodyRotT, float walkSpeed) return walkSpeed; } -void LivingEntity::aiStep() +void LivingEntity::aiStep() { if (noJumpDelay > 0) noJumpDelay--; - if (lSteps > 0) + if (lSteps > 0) { double xt = x + (lx - x) / lSteps; double yt = y + (ly - y) / lSteps; @@ -1716,10 +1712,8 @@ void LivingEntity::aiStep() if (collisions->size() > 0) { double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) + for (const auto& ab : *collisions) { - AABB *ab = *it; //collisions->at(i); if (ab->y1 > yTop) yTop = ab->y1; } @@ -1740,14 +1734,14 @@ void LivingEntity::aiStep() if (abs(yd) < MIN_MOVEMENT_DISTANCE) yd = 0; if (abs(zd) < MIN_MOVEMENT_DISTANCE) zd = 0; - if (isImmobile()) + if (isImmobile()) { jumping = false; xxa = 0; yya = 0; yRotA = 0; - } - else + } + else { MemSect(25); if (isEffectiveAi()) @@ -1765,13 +1759,13 @@ void LivingEntity::aiStep() MemSect(0); } - if (jumping) + if (jumping) { - if (isInWater() || isInLava() ) + if (isInWater() || isInLava() ) { yd += 0.04f; } - else if (onGround) + else if (onGround) { if (noJumpDelay == 0) { @@ -1806,13 +1800,12 @@ void LivingEntity::pushEntities() { vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) + if (entities != NULL && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (e->isPushable()) e->push(shared_from_this()); + if ( e && e->isPushable()) + e->push(shared_from_this()); } } } @@ -1822,7 +1815,7 @@ void LivingEntity::doPush(shared_ptr<Entity> e) e->push(shared_from_this()); } -void LivingEntity::rideTick() +void LivingEntity::rideTick() { Entity::rideTick(); oRun = run; @@ -1830,7 +1823,7 @@ void LivingEntity::rideTick() fallDistance = 0; } -void LivingEntity::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) +void LivingEntity::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) { heightOffset = 0; lx = x; @@ -1846,7 +1839,7 @@ void LivingEntity::serverAiMobStep() { } -void LivingEntity::serverAiStep() +void LivingEntity::serverAiStep() { noActionTime++; } @@ -1876,7 +1869,7 @@ void LivingEntity::take(shared_ptr<Entity> e, int orgCount) } } -bool LivingEntity::canSee(shared_ptr<Entity> target) +bool LivingEntity::canSee(shared_ptr<Entity> target) { HitResult *hres = level->clip(Vec3::newTemp(x, y + getHeadHeight(), z), Vec3::newTemp(target->x, target->y + target->getHeadHeight(), target->z)); bool retVal = (hres == NULL); @@ -1884,14 +1877,14 @@ bool LivingEntity::canSee(shared_ptr<Entity> target) return retVal; } -Vec3 *LivingEntity::getLookAngle() +Vec3 *LivingEntity::getLookAngle() { return getViewVector(1); } -Vec3 *LivingEntity::getViewVector(float a) +Vec3 *LivingEntity::getViewVector(float a) { - if (a == 1) + if (a == 1) { float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); @@ -1911,16 +1904,16 @@ Vec3 *LivingEntity::getViewVector(float a) return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); } -float LivingEntity::getAttackAnim(float a) +float LivingEntity::getAttackAnim(float a) { float diff = attackAnim - oAttackAnim; if (diff < 0) diff += 1; return oAttackAnim + diff * a; } -Vec3 *LivingEntity::getPos(float a) +Vec3 *LivingEntity::getPos(float a) { - if (a == 1) + if (a == 1) { return Vec3::newTemp(x, y, z); } @@ -1931,7 +1924,7 @@ Vec3 *LivingEntity::getPos(float a) return Vec3::newTemp(x, y, z); } -HitResult *LivingEntity::pick(double range, float a) +HitResult *LivingEntity::pick(double range, float a) { Vec3 *from = getPos(a); Vec3 *b = getViewVector(a); @@ -1944,17 +1937,17 @@ bool LivingEntity::isEffectiveAi() return !level->isClientSide; } -bool LivingEntity::isPickable() +bool LivingEntity::isPickable() { return !removed; } -bool LivingEntity::isPushable() +bool LivingEntity::isPushable() { return !removed; } -float LivingEntity::getHeadHeight() +float LivingEntity::getHeadHeight() { return bbHeight * 0.85f; } diff --git a/Minecraft.World/MapItem.cpp b/Minecraft.World/MapItem.cpp index a5143257..03529c1a 100644 --- a/Minecraft.World/MapItem.cpp +++ b/Minecraft.World/MapItem.cpp @@ -20,18 +20,18 @@ MapItem::MapItem(int id) : ComplexItem(id) } shared_ptr<MapItemSavedData> MapItem::getSavedData(short idNum, Level *level) -{ - std::wstring id = wstring( L"map_" ) + _toString(idNum); +{ + std::wstring id = wstring( L"map_" ) + std::to_wstring(idNum); shared_ptr<MapItemSavedData> mapItemSavedData = dynamic_pointer_cast<MapItemSavedData>(level->getSavedData(typeid(MapItemSavedData), id)); - if (mapItemSavedData == NULL) + if (mapItemSavedData == NULL) { // 4J Stu - This call comes from ClientConnection, but i don't see why we should be trying to work out // the id again when it's passed as a param. In any case that won't work with the new map setup //int aux = level->getFreeAuxValueFor(L"map"); int aux = idNum; - id = wstring( L"map_" ) + _toString(aux); + id = wstring( L"map_" ) + std::to_wstring(aux); mapItemSavedData = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); level->setSavedData(id, (shared_ptr<SavedData> ) mapItemSavedData); @@ -43,7 +43,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(short idNum, Level *level) shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> itemInstance, Level *level) { MemSect(31); - std::wstring id = wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); + std::wstring id = wstring( L"map_" ) + std::to_wstring(itemInstance->getAuxValue() ); MemSect(0); shared_ptr<MapItemSavedData> mapItemSavedData = dynamic_pointer_cast<MapItemSavedData>( level->getSavedData(typeid(MapItemSavedData), id ) ); @@ -54,7 +54,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item // In any case that won't work with the new map setup //itemInstance->setAuxValue(level->getFreeAuxValueFor(L"map")); - id = wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); + id = wstring( L"map_" ) + std::to_wstring(itemInstance->getAuxValue() ); mapItemSavedData = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); newData = true; @@ -75,7 +75,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item mapItemSavedData->z = Math::round(level->getLevelData()->getZSpawn() / scale) * scale; #endif mapItemSavedData->dimension = (byte) level->dimension->id; - + mapItemSavedData->setDirty(); level->setSavedData(id, (shared_ptr<SavedData> ) mapItemSavedData); @@ -86,7 +86,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItemSavedData> data) { - if ( (level->dimension->id != data->dimension) || !player->instanceof(eTYPE_PLAYER) ) + if ( (level->dimension->id != data->dimension) || !player->instanceof(eTYPE_PLAYER) ) { // Wrong dimension, abort return; @@ -148,8 +148,8 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem if (((ss >> 20) & 1) == 0) count[Tile::dirt_Id] += 10; else count[Tile::stone_Id] += 10; hh = 100; - } - else + } + else { for (int xs = 0; xs < scale; xs++) { @@ -157,7 +157,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem { int yy = lc->getHeightmap(xs + xso, zs + zso) + 1; int t = 0; - if (yy > 1) + if (yy > 1) { bool ok = false; do @@ -215,7 +215,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem if (diff < -0.6) br = 0; int col = 0; - if (tBest > 0) + if (tBest > 0) { MaterialColor *mc = Tile::tiles[tBest]->material->color; if (mc == MaterialColor::water) @@ -245,7 +245,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem data->colors[x + z * w] = newColor; } } - if (yd0 <= yd1) + if (yd0 <= yd1) { data->setDirty(x, yd0, yd1); } @@ -257,7 +257,7 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, if (level->isClientSide) return; shared_ptr<MapItemSavedData> data = getSavedData(itemInstance, level); - if ( owner->instanceof(eTYPE_PLAYER) ) + if ( owner->instanceof(eTYPE_PLAYER) ) { shared_ptr<Player> player = dynamic_pointer_cast<Player>(owner); @@ -276,7 +276,7 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, ownersData->tickCarriedBy(player, itemInstance ); ownersData->mergeInMapData(data); player->inventoryMenu->broadcastChanges(); - + data = ownersData; } else @@ -285,13 +285,13 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, } } - if (selected) + if (selected) { update(level, owner, data); } } -shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) +shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { charArray data = MapItem::getSavedData(itemInstance, level)->getUpdatePacket(itemInstance, level, player); @@ -302,7 +302,7 @@ shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstanc return retval; } -void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) +void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { wchar_t buf[64]; @@ -318,7 +318,7 @@ void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, s #endif itemInstance->setAuxValue(level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale)); - + swprintf(buf,64,L"map_%d", itemInstance->getAuxValue()); std::wstring id = wstring(buf); @@ -330,7 +330,7 @@ void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, s data = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); } level->setSavedData(id, (shared_ptr<SavedData> ) data); - + data->scale = mapScale; // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map data->x = centreXC; diff --git a/Minecraft.World/MapItemSavedData.cpp b/Minecraft.World/MapItemSavedData.cpp index 981bab3e..c06c3fac 100644 --- a/Minecraft.World/MapItemSavedData.cpp +++ b/Minecraft.World/MapItemSavedData.cpp @@ -64,7 +64,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta if (--sendPosTick < 0) { sendPosTick = 4; - + unsigned int playerDecorationsSize = (int)parent->decorations.size(); unsigned int nonPlayerDecorationsSize = (int)parent->nonPlayerDecorations.size(); charArray data = charArray( (playerDecorationsSize + nonPlayerDecorationsSize ) * DEC_PACKET_BYTES + 1); @@ -79,7 +79,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[i * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); #endif data[i * DEC_PACKET_BYTES + 2] = md->x; - data[i * DEC_PACKET_BYTES + 3] = md->y; + data[i * DEC_PACKET_BYTES + 3] = md->y; data[i * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; data[i * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; data[i * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; @@ -87,9 +87,9 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[i * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; } unsigned int dataIndex = playerDecorationsSize; - for(AUTO_VAR(it, parent->nonPlayerDecorations.begin()); it != parent->nonPlayerDecorations.end(); ++it) + for(auto it : parent->nonPlayerDecorations) { - MapDecoration *md = it->second; + MapDecoration *md = it.second; #ifdef _LARGE_WORLDS data[dataIndex * DEC_PACKET_BYTES + 1] = (char) (md->img); data[dataIndex * DEC_PACKET_BYTES + 8] = (char) (md->rot & 0xF); @@ -97,7 +97,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[dataIndex * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); #endif data[dataIndex * DEC_PACKET_BYTES + 2] = md->x; - data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; + data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; data[dataIndex * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; data[dataIndex * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; data[dataIndex * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; @@ -246,21 +246,21 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI delete decorations[i]; } decorations.clear(); - + // 4J Stu - Put this block back in if you want to display entity positions on a map (see below) #if 0 nonPlayerDecorations.clear(); #endif bool addedPlayers = false; - for (AUTO_VAR(it, carriedBy.begin()); it != carriedBy.end(); ) - { + for (auto it = carriedBy.begin(); it != carriedBy.end();) + { shared_ptr<HoldingPlayer> hp = *it; // 4J Stu - Players in the same dimension as an item frame with a map need to be sent this data, so don't remove them if (hp->player->removed ) //|| (!hp->player->inventory->contains(item) && !item->isFramed() )) { - AUTO_VAR(it2, carriedByPlayers.find( (shared_ptr<Player> ) hp->player )); - if( it2 != carriedByPlayers.end() ) + auto it2 = carriedByPlayers.find(shared_ptr<Player>(hp->player)); + if( it2 != carriedByPlayers.end() ) { carriedByPlayers.erase( it2 ); } @@ -275,9 +275,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI { bool atLeastOnePlayerInTheEnd = false; PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) + for( const auto& serverPlayer : players->players) { - shared_ptr<ServerPlayer> serverPlayer = *it3; if(serverPlayer->dimension == 1) { atLeastOnePlayerInTheEnd = true; @@ -285,8 +284,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI } } - AUTO_VAR(currentPortalDecoration, nonPlayerDecorations.find( END_PORTAL_DECORATION_KEY )); - if( currentPortalDecoration == nonPlayerDecorations.end() && atLeastOnePlayerInTheEnd) + auto currentPortalDecoration = nonPlayerDecorations.find(END_PORTAL_DECORATION_KEY); + if( currentPortalDecoration == nonPlayerDecorations.end() && atLeastOnePlayerInTheEnd) { float origX = 0.0f; float origZ = 0.0f; @@ -330,7 +329,7 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI if (item->isFramed()) { //addDecoration(1, player.level, "frame-" + item.getFrame().entityId, item.getFrame().xTile, item.getFrame().zTile, item.getFrame().dir * 90); - + if( nonPlayerDecorations.find( item->getFrame()->entityId ) == nonPlayerDecorations.end() ) { float xd = (float) ( item->getFrame()->xTile - x ) / (1 << scale); @@ -361,10 +360,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI // 4J Stu - Put this block back in if you want to display entity positions on a map (see above as well) #if 0 - for(AUTO_VAR(it,playerLevel->entities.begin()); it != playerLevel->entities.end(); ++it) + for(auto& ent : playerLevel->entities) { - shared_ptr<Entity> ent = *it; - if((ent->GetType() & eTYPE_ENEMY) == 0) continue; float xd = (float) ( ent->x - x ) / (1 << scale); @@ -400,9 +397,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI addedPlayers = true; PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) + for(auto& decorationPlayer : players->players) { - shared_ptr<ServerPlayer> decorationPlayer = *it3; if(decorationPlayer!=NULL && decorationPlayer->dimension == this->dimension) { float xd = (float) (decorationPlayer->x - x) / (1 << scale); @@ -481,8 +477,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI charArray MapItemSavedData::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { - AUTO_VAR(it, carriedByPlayers.find(player)); - if (it == carriedByPlayers.end() ) return charArray(); + auto it = carriedByPlayers.find(player); + if (it == carriedByPlayers.end() ) return charArray(); shared_ptr<HoldingPlayer> hp = it->second; return hp->nextUpdatePacket(itemInstance); @@ -492,10 +488,8 @@ void MapItemSavedData::setDirty(int x, int y0, int y1) { SavedData::setDirty(); - AUTO_VAR(itEnd, carriedBy.end()); - for (AUTO_VAR(it, carriedBy.begin()); it != itEnd; it++) + for (auto& hp : carriedBy) { - shared_ptr<HoldingPlayer> hp = *it; //carriedBy.at(i); if (hp->rowsDirtyMin[x] < 0 || hp->rowsDirtyMin[x] > y0) hp->rowsDirtyMin[x] = y0; if (hp->rowsDirtyMax[x] < 0 || hp->rowsDirtyMax[x] < y1) hp->rowsDirtyMax[x] = y1; } @@ -547,9 +541,9 @@ void MapItemSavedData::handleComplexItemData(charArray &data) shared_ptr<MapItemSavedData::HoldingPlayer> MapItemSavedData::getHoldingPlayer(shared_ptr<Player> player) { shared_ptr<HoldingPlayer> hp = nullptr; - AUTO_VAR(it,carriedByPlayers.find(player)); + auto it = carriedByPlayers.find(player); - if (it == carriedByPlayers.end()) + if (it == carriedByPlayers.end()) { hp = shared_ptr<HoldingPlayer>( new HoldingPlayer(player, this) ); carriedByPlayers[player] = hp; @@ -587,7 +581,7 @@ void MapItemSavedData::mergeInMapData(shared_ptr<MapItemSavedData> dataToAdd) colors[x + z * w] = newColor; } } - if (yd0 <= yd1) + if (yd0 <= yd1) { setDirty(x, yd0, yd1); } @@ -598,7 +592,7 @@ void MapItemSavedData::removeItemFrameDecoration(shared_ptr<ItemInstance> item) { if ( !item ) return; - + std::shared_ptr<ItemFrame> frame = item->getFrame(); if ( !frame ) return; diff --git a/Minecraft.World/McRegionChunkStorage.cpp b/Minecraft.World/McRegionChunkStorage.cpp index d02125a6..344ff6c7 100644 --- a/Minecraft.World/McRegionChunkStorage.cpp +++ b/Minecraft.World/McRegionChunkStorage.cpp @@ -32,7 +32,7 @@ McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const wstr m_saveFile->createFile(ConsoleSavePath(L"r.-1.0.mcr")); } - + #ifdef SPLIT_SAVES ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + wstring( L"entities.dat" ) ); @@ -64,9 +64,9 @@ McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const wstr McRegionChunkStorage::~McRegionChunkStorage() { - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) + for(auto& it : m_entityData) { - delete it->second.data; + delete it.second.data; } } @@ -80,8 +80,8 @@ LevelChunk *McRegionChunkStorage::load(Level *level, int x, int z) { __int64 index = ((__int64)(x) << 32) | (((__int64)(z))&0x00000000FFFFFFFF); - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { delete it->second.data; m_entityData.erase(it); @@ -262,8 +262,8 @@ void McRegionChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk) } else { - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { m_entityData.erase(it); } @@ -277,9 +277,9 @@ void McRegionChunkStorage::loadEntities(Level *level, LevelChunk *levelChunk) { #ifdef SPLIT_SAVES __int64 index = ((__int64)(levelChunk->x) << 32) | (((__int64)(levelChunk->z))&0x00000000FFFFFFFF); - - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { ByteArrayInputStream bais(it->second); DataInputStream dis(&bais); @@ -308,10 +308,10 @@ void McRegionChunkStorage::flush() PIXBeginNamedEvent(0,"Writing to stream"); dos.writeInt(m_entityData.size()); - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) + for(auto& it : m_entityData) { - dos.writeLong(it->first); - dos.write(it->second,0,it->second.length); + dos.writeLong(it.first); + dos.write(it.second,0,it.second.length); } bos.flush(); PIXEndNamedEvent(); diff --git a/Minecraft.World/McRegionLevelStorage.cpp b/Minecraft.World/McRegionLevelStorage.cpp index 687ee048..daf6a7ef 100644 --- a/Minecraft.World/McRegionLevelStorage.cpp +++ b/Minecraft.World/McRegionLevelStorage.cpp @@ -20,13 +20,13 @@ McRegionLevelStorage::~McRegionLevelStorage() RegionFileCache::clear(); } -ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) +ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) { //File folder = getFolder(); if (dynamic_cast<HellDimension *>(dimension) != NULL) { - + if(app.GetResetNether()) { #ifdef SPLIT_SAVES @@ -34,19 +34,19 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) if(netherFiles!=NULL) { DWORD bytesWritten = 0; - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) + for(auto& netherFile : *netherFiles) { - m_saveFile->zeroFile(*it, (*it)->getFileSize(), &bytesWritten); + m_saveFile->zeroFile(netherFile, netherFile->getFileSize(), &bytesWritten); } delete netherFiles; } #else vector<FileEntry *> *netherFiles = m_saveFile->getFilesWithPrefix(LevelStorage::NETHER_FOLDER); if(netherFiles!=NULL) - { - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) + { + for(auto& netherFile : *netherFiles) { - m_saveFile->deleteFile(*it); + m_saveFile->deleteFile(netherFile); } delete netherFiles; } @@ -56,13 +56,13 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) return new McRegionChunkStorage(m_saveFile, LevelStorage::NETHER_FOLDER); } - + if (dynamic_cast<TheEndDimension *>(dimension)) { //File dir2 = new File(folder, LevelStorage.ENDER_FOLDER); //dir2.mkdirs(); //return new ThreadedMcRegionChunkStorage(dir2); - + // 4J-PB - save version 0 at this point means it's a create new world int iSaveVersion=m_saveFile->getSaveVersion(); @@ -75,10 +75,10 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) // 4J-PB - There will be no End in early saves if(endFiles!=NULL) - { - for(AUTO_VAR(it, endFiles->begin()); it != endFiles->end(); ++it) + { + for(auto& endFile : *endFiles) { - m_saveFile->deleteFile(*it); + m_saveFile->deleteFile(endFile); } delete endFiles; } @@ -89,7 +89,7 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) return new McRegionChunkStorage(m_saveFile, L""); } -void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr<Player> > *players) +void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr<Player> > *players) { levelData->setVersion(MCREGION_VERSION_ID); MemSect(38); @@ -97,7 +97,7 @@ void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr MemSect(0); } -void McRegionLevelStorage::closeAll() +void McRegionLevelStorage::closeAll() { RegionFileCache::clear(); }
\ No newline at end of file diff --git a/Minecraft.World/McRegionLevelStorageSource.cpp b/Minecraft.World/McRegionLevelStorageSource.cpp index 0652ad84..60904fde 100644 --- a/Minecraft.World/McRegionLevelStorageSource.cpp +++ b/Minecraft.World/McRegionLevelStorageSource.cpp @@ -39,12 +39,11 @@ vector<LevelSummary *> *McRegionLevelStorageSource::getLevelList() #if 0 vector<File *> *subFolders = baseDir.listFiles(); File *file; - AUTO_VAR(itEnd, subFolders->end()); - for (AUTO_VAR(it, subFolders->begin()); it != itEnd; it++) + for (auto& subFolder : *subFolders) { - file = *it; //subFolders->at(i); + file = subFolder; //subFolders->at(i); - if (file->isDirectory()) + if (file->isDirectory()) { continue; } @@ -74,13 +73,13 @@ void McRegionLevelStorageSource::clearAll() { } -shared_ptr<LevelStorage> McRegionLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const wstring& levelId, bool createPlayerDir) +shared_ptr<LevelStorage> McRegionLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const wstring& levelId, bool createPlayerDir) { // return new LevelStorageProfilerDecorator(new McRegionLevelStorage(baseDir, levelId, createPlayerDir)); return shared_ptr<LevelStorage>(new McRegionLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); } -bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const wstring& levelId) +bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const wstring& levelId) { // check if there is old file format level data LevelData *levelData = getDataTagFor(saveFile, levelId); @@ -145,7 +144,7 @@ bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const w } int totalCount = normalRegions->size() + netherRegions->size() + enderRegions.size() + normalBaseFolders->size() + netherBaseFolders->size() + enderBaseFolders.size(); - + // System.out.println("Total conversion count is " + totalCount); 4J Jev, TODO // convert normal world @@ -173,16 +172,15 @@ bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const w #if 0 // 4J - not required anymore -void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile *> *dest, vector<File *> *firstLevelFolders) +void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile *> *dest, vector<File *> *firstLevelFolders) { FolderFilter folderFilter; ChunkFilter chunkFilter; File *folder1; vector<File *> *folderLevel1 = baseFolder.listFiles((FileFilter *) &folderFilter); - AUTO_VAR(itEnd, folderLevel1->end()); - for (AUTO_VAR(it, folderLevel1->begin()); it != itEnd; it++) - { + for (auto it = folderLevel1->begin(); it != folderLevel1->end(); it++) + { folder1 = *it; //folderLevel1->at(i1); // keep this for the clean-up process later on @@ -190,17 +188,17 @@ void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile * File *folder2; vector<File *> *folderLevel2 = folder1->listFiles(&folderFilter); - AUTO_VAR(itEnd2, folderLevel2->end()); - for (AUTO_VAR(it2, folderLevel2->begin()); it2 != itEnd; it2++) + auto itEnd2 = folderLevel2->end(); + for ( auto it2 = folderLevel2->begin(); it2 != itEnd2; it2++) { folder2 = *it2; //folderLevel2->at(i2); vector<File *> *chunkFiles = folder2->listFiles((FileFilter *) &chunkFilter); File *chunk; - AUTO_VAR(itEndFile, chunkFiles->end()); - for (AUTO_VAR(itFile, chunkFiles->begin()); itFile != itEndFile; itFile++) - { + auto itEndFile = chunkFiles->end(); + for (auto itFile = chunkFiles->begin(); itFile != itEndFile; itFile++) + { chunk = *itFile; //chunkFiles->at(i3); dest->push_back(new ChunkFile(chunk)); @@ -210,7 +208,7 @@ void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile * } #endif -void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFile *> *chunkFiles, int currentCount, int totalCount, ProgressListener *progress) +void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFile *> *chunkFiles, int currentCount, int totalCount, ProgressListener *progress) { assert( false ); @@ -222,10 +220,9 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi byteArray buffer = byteArray(4096); ChunkFile *chunkFile; - AUTO_VAR(itEnd, chunkFiles->end()); - for (AUTO_VAR(it, chunkFiles->begin()); it != itEnd; it++) + for (auto& it : *chunkFiles) { - chunkFile = *it; //chunkFiles->at(i1); + chunkFile = it; //chunkFiles->at(i1); // Matcher matcher = ChunkFilter.chunkFilePattern.matcher(chunkFile.getName()); // if (!matcher.matches()) { @@ -238,7 +235,7 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi int z = chunkFile->getZ(); RegionFile *region = RegionFileCache::getRegionFile(baseFolder, x, z); - if (!region->hasChunk(x & 31, z & 31)) + if (!region->hasChunk(x & 31, z & 31)) { FileInputStream fis = new BufferedInputStream(FileInputStream(*chunkFile->getFile())); DataInputStream istream = DataInputStream(&fis); // 4J - was new GZIPInputStream as well @@ -271,12 +268,8 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi void McRegionLevelStorageSource::eraseFolders(vector<File *> *folders, int currentCount, int totalCount, ProgressListener *progress) { - File *folder; - AUTO_VAR(itEnd, folders->end()); - for (AUTO_VAR(it, folders->begin()); it != itEnd; it++) + for (File *folder : *folders) { - folder = *it; //folders->at(i); - vector<File *> *files = folder->listFiles(); deleteRecursive(files); folder->_delete(); @@ -289,7 +282,7 @@ void McRegionLevelStorageSource::eraseFolders(vector<File *> *folders, int curre #if 0 // 4J - not required anymore -bool McRegionLevelStorageSource::FolderFilter::accept(File *file) +bool McRegionLevelStorageSource::FolderFilter::accept(File *file) { if (file->isDirectory()) { @@ -300,23 +293,23 @@ bool McRegionLevelStorageSource::FolderFilter::accept(File *file) } -bool McRegionLevelStorageSource::ChunkFilter::accept(File *dir, const wstring& name) +bool McRegionLevelStorageSource::ChunkFilter::accept(File *dir, const wstring& name) { Matcher matcher( chunkFilePattern, name ); return matcher.matches(); } -McRegionLevelStorageSource::ChunkFile::ChunkFile(File *file) +McRegionLevelStorageSource::ChunkFile::ChunkFile(File *file) { this->file = file; Matcher matcher( ChunkFilter::chunkFilePattern, file->getName() ); - if (matcher.matches()) + if (matcher.matches()) { x = Integer::parseInt(matcher.group(1), 36); z = Integer::parseInt(matcher.group(2), 36); - } + } else { x = 0; @@ -348,17 +341,17 @@ bool McRegionLevelStorageSource::ChunkFile::operator<( ChunkFile *b ) return compareTo( b ) < 0; } -File *McRegionLevelStorageSource::ChunkFile::getFile() +File *McRegionLevelStorageSource::ChunkFile::getFile() { return (File *) file; } -int McRegionLevelStorageSource::ChunkFile::getX() +int McRegionLevelStorageSource::ChunkFile::getX() { return x; } -int McRegionLevelStorageSource::ChunkFile::getZ() +int McRegionLevelStorageSource::ChunkFile::getZ() { return z; } diff --git a/Minecraft.World/MerchantRecipeList.cpp b/Minecraft.World/MerchantRecipeList.cpp index bd7a126c..c994081f 100644 --- a/Minecraft.World/MerchantRecipeList.cpp +++ b/Minecraft.World/MerchantRecipeList.cpp @@ -13,9 +13,9 @@ MerchantRecipeList::MerchantRecipeList(CompoundTag *tag) MerchantRecipeList::~MerchantRecipeList() { - for(AUTO_VAR(it, m_recipes.begin()); it != m_recipes.end(); ++it) + for(auto& it : m_recipes) { - delete (*it); + delete it; } } diff --git a/Minecraft.World/MineShaftFeature.cpp b/Minecraft.World/MineShaftFeature.cpp index 78178de0..d32af346 100644 --- a/Minecraft.World/MineShaftFeature.cpp +++ b/Minecraft.World/MineShaftFeature.cpp @@ -19,11 +19,11 @@ MineShaftFeature::MineShaftFeature(unordered_map<wstring, wstring> options) { chance = 0.01; - for(AUTO_VAR(it,options.begin()); it != options.end(); ++it) + for(auto& option : options) { - if (it->first.compare(OPTION_CHANCE) == 0) + if (option.first.compare(OPTION_CHANCE) == 0) { - chance = Mth::getDouble(it->second, chance); + chance = Mth::getDouble(option.second, chance); } } } diff --git a/Minecraft.World/MineShaftPieces.cpp b/Minecraft.World/MineShaftPieces.cpp index 844514dc..3fda1bfc 100644 --- a/Minecraft.World/MineShaftPieces.cpp +++ b/Minecraft.World/MineShaftPieces.cpp @@ -103,9 +103,9 @@ MineShaftPieces::MineShaftRoom::MineShaftRoom(int genDepth, Random *random, int MineShaftPieces::MineShaftRoom::~MineShaftRoom() { - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for(auto& it : childEntranceBoxes) { - delete (*it); + delete it; } } @@ -204,9 +204,8 @@ bool MineShaftPieces::MineShaftRoom::postProcess(Level *level, Random *random, B // room air generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0 + 1, boundingBox->z0, boundingBox->x1, min(boundingBox->y0 + 3, boundingBox->y1), boundingBox->z1, 0, 0, false); - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for(auto& entranceBox : childEntranceBoxes) { - BoundingBox *entranceBox = *it; generateBox(level, chunkBB, entranceBox->x0, entranceBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), entranceBox->z0, entranceBox->x1, entranceBox->y1, entranceBox->z1, 0, 0, false); } generateUpperHalfSphere(level, chunkBB, boundingBox->x0, boundingBox->y0 + 4, boundingBox->z0, boundingBox->x1, boundingBox->y1, boundingBox->z1, 0, false); @@ -217,9 +216,8 @@ bool MineShaftPieces::MineShaftRoom::postProcess(Level *level, Random *random, B void MineShaftPieces::MineShaftRoom::addAdditonalSaveData(CompoundTag *tag) { ListTag<IntArrayTag> *entrances = new ListTag<IntArrayTag>(L"Entrances"); - for (AUTO_VAR(it,childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for (auto& bb : childEntranceBoxes) { - BoundingBox *bb =*it; entrances->add(bb->createTag(L"")); } tag->put(L"Entrances", entrances); @@ -523,12 +521,12 @@ bool MineShaftPieces::MineShaftCorridor::postProcess(Level *level, Random *rando } // prevent air floating - for (int x = x0; x <= x1; x++) + for (int x = x0; x <= x1; x++) { - for (int z = 0; z <= length; z++) + for (int z = 0; z <= length; z++) { int block = getBlock(level, x, -1, z, chunkBB); - if (block == 0) + if (block == 0) { placeBlock(level, Tile::wood_Id, 0, x, -1, z, chunkBB); } @@ -687,12 +685,12 @@ bool MineShaftPieces::MineShaftCrossing::postProcess(Level *level, Random *rando // prevent air floating // note: use world coordinates because the corridor hasn't defined // orientation - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { int block = getBlock(level, x, boundingBox->y0 - 1, z, chunkBB); - if (block == 0) + if (block == 0) { placeBlock(level, Tile::wood_Id, 0, x, boundingBox->y0 - 1, z, chunkBB); } diff --git a/Minecraft.World/Minecart.cpp b/Minecraft.World/Minecart.cpp index 48787f55..4e1419cc 100644 --- a/Minecraft.World/Minecart.cpp +++ b/Minecraft.World/Minecart.cpp @@ -346,11 +346,9 @@ void Minecart::tick() vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), bb->grow(0.2f, 0, 0.2f)); if (entities != NULL && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); //entities->at(i); - if (e != rider.lock() && e->isPushable() && e->instanceof(eTYPE_MINECART)) + if ( e && e != rider.lock() && e->isPushable() && e->instanceof(eTYPE_MINECART)) { shared_ptr<Minecart> cart = dynamic_pointer_cast<Minecart>(e); cart->m_bHasPushedCartThisTick = false; @@ -455,7 +453,7 @@ void Minecart::moveAlongTrack(int xt, int yt, int zt, double maxSpeed, double sl xd = pow * xD / dd; zd = pow * zD / dd; - + if ( rider.lock() != NULL && rider.lock()->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> living = dynamic_pointer_cast<LivingEntity>(rider.lock()); diff --git a/Minecraft.World/Minecraft.World.vcxproj b/Minecraft.World/Minecraft.World.vcxproj index 7ab7c4ce..c9191573 100644 --- a/Minecraft.World/Minecraft.World.vcxproj +++ b/Minecraft.World/Minecraft.World.vcxproj @@ -707,6 +707,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -735,6 +738,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -753,6 +759,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_Vita|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -834,6 +843,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -852,6 +864,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='CONTENTPACKAGE_SYMBOLS|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -870,6 +885,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseForArt|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -888,6 +906,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)\$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_NO_TU|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -4958,4 +4979,4 @@ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> -</Project> +</Project>
\ No newline at end of file diff --git a/Minecraft.World/Mob.cpp b/Minecraft.World/Mob.cpp index cac25ddb..342400b4 100644 --- a/Minecraft.World/Mob.cpp +++ b/Minecraft.World/Mob.cpp @@ -152,38 +152,38 @@ void Mob::ate() { } -void Mob::defineSynchedData() +void Mob::defineSynchedData() { LivingEntity::defineSynchedData(); entityData->define(DATA_CUSTOM_NAME_VISIBLE, (byte) 0); entityData->define(DATA_CUSTOM_NAME, L""); } -int Mob::getAmbientSoundInterval() +int Mob::getAmbientSoundInterval() { return 20 * 4; } -void Mob::playAmbientSound() +void Mob::playAmbientSound() { MemSect(31); int ambient = getAmbientSound(); - if (ambient != -1) + if (ambient != -1) { playSound(ambient, getSoundVolume(), getVoicePitch()); } MemSect(0); } -void Mob::baseTick() +void Mob::baseTick() { LivingEntity::baseTick(); - if (isAlive() && random->nextInt(1000) < ambientSoundTime++) + if (isAlive() && random->nextInt(1000) < ambientSoundTime++) { ambientSoundTime = -getAmbientSoundInterval(); - playAmbientSound(); + playAmbientSound(); } } @@ -209,9 +209,9 @@ int Mob::getExperienceReward(shared_ptr<Player> killedBy) return xpReward; } } -void Mob::spawnAnim() +void Mob::spawnAnim() { - for (int i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { double xa = random->nextGaussian() * 0.02; double ya = random->nextGaussian() * 0.02; @@ -222,7 +222,7 @@ void Mob::spawnAnim() } } -void Mob::tick() +void Mob::tick() { LivingEntity::tick(); @@ -245,7 +245,7 @@ float Mob::tickHeadTurn(float yBodyRotT, float walkSpeed) } } -int Mob::getAmbientSound() +int Mob::getAmbientSound() { return -1; } @@ -255,10 +255,10 @@ int Mob::getDeathLoot() return 0; } -void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) +void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { int loot = getDeathLoot(); - if (loot > 0) + if (loot > 0) { int count = random->nextInt(3); if (playerBonusLevel > 0) @@ -270,7 +270,7 @@ void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) } } -void Mob::addAdditonalSaveData(CompoundTag *entityTag) +void Mob::addAdditonalSaveData(CompoundTag *entityTag) { LivingEntity::addAdditonalSaveData(entityTag); entityTag->putBoolean(L"CanPickUpLoot", canPickUpLoot()); @@ -288,7 +288,7 @@ void Mob::addAdditonalSaveData(CompoundTag *entityTag) ListTag<FloatTag> *dropChanceList = new ListTag<FloatTag>(); for (int i = 0; i < dropChances.length; i++) { - dropChanceList->add(new FloatTag( _toString(i), dropChances[i])); + dropChanceList->add(new FloatTag( std::to_wstring(i), dropChances[i])); } entityTag->put(L"DropChances", dropChanceList); entityTag->putString(L"CustomName", getCustomName()); @@ -316,7 +316,7 @@ void Mob::addAdditonalSaveData(CompoundTag *entityTag) } } -void Mob::readAdditionalSaveData(CompoundTag *tag) +void Mob::readAdditionalSaveData(CompoundTag *tag) { LivingEntity::readAdditionalSaveData(tag); @@ -362,16 +362,16 @@ void Mob::setSpeed(float speed) setYya(speed); } -void Mob::aiStep() +void Mob::aiStep() { LivingEntity::aiStep(); if (!level->isClientSide && canPickUpLoot() && !dead && level->getGameRules()->getBoolean(GameRules::RULE_MOBGRIEFING)) { vector<shared_ptr<Entity> > *entities = level->getEntitiesOfClass(typeid(ItemEntity), bb->grow(1, 0, 1)); - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for (auto& it : *entities) { - shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(*it); + shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(it); if (entity->removed || entity->getItem() == NULL) continue; shared_ptr<ItemInstance> item = entity->getItem(); int slot = getEquipmentSlotForItem(item); @@ -457,12 +457,12 @@ bool Mob::useNewAi() return false; } -bool Mob::removeWhenFarAway() +bool Mob::removeWhenFarAway() { return true; } -void Mob::checkDespawn() +void Mob::checkDespawn() { if (persistenceRequired) { @@ -470,23 +470,23 @@ void Mob::checkDespawn() return; } shared_ptr<Entity> player = level->getNearestPlayer(shared_from_this(), -1); - if (player != NULL) + if (player != NULL) { double xd = player->x - x; double yd = player->y - y; double zd = player->z - z; double sd = xd * xd + yd * yd + zd * zd; - if (removeWhenFarAway() && sd > 128 * 128) + if (removeWhenFarAway() && sd > 128 * 128) { remove(); } - if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && sd > 32 * 32 && removeWhenFarAway()) + if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && sd > 32 * 32 && removeWhenFarAway()) { remove(); } - else if (sd < 32 * 32) + else if (sd < 32 * 32) { noActionTime = 0; } @@ -502,7 +502,7 @@ void Mob::newServerAiStep() checkDespawn(); PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Tick sensing"); - sensing->tick(); + sensing->tick(); PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Tick target selector"); targetSelector.tick(); @@ -534,7 +534,7 @@ void Mob::newServerAiStep() PIXEndNamedEvent(); } -void Mob::serverAiStep() +void Mob::serverAiStep() { LivingEntity::serverAiStep(); @@ -544,15 +544,15 @@ void Mob::serverAiStep() checkDespawn(); float lookDistance = 8; - if (random->nextFloat() < 0.02f) + if (random->nextFloat() < 0.02f) { shared_ptr<Player> player = level->getNearestPlayer(shared_from_this(), lookDistance); - if (player != NULL) + if (player != NULL) { lookingAt = player; lookTime = 10 + random->nextInt(20); - } - else + } + else { yRotA = (random->nextFloat() - 0.5f) * 20; } @@ -561,14 +561,14 @@ void Mob::serverAiStep() if (lookingAt != NULL) { lookAt(lookingAt, 10.0f, (float) getMaxHeadXRot()); - if (lookTime-- <= 0 || lookingAt->removed || lookingAt->distanceToSqr(shared_from_this()) > lookDistance * lookDistance) + if (lookTime-- <= 0 || lookingAt->removed || lookingAt->distanceToSqr(shared_from_this()) > lookDistance * lookDistance) { lookingAt = nullptr; } - } - else + } + else { - if (random->nextFloat() < 0.05f) + if (random->nextFloat() < 0.05f) { yRotA = (random->nextFloat() - 0.5f) * 20; } @@ -581,24 +581,24 @@ void Mob::serverAiStep() if (inWater || inLava) jumping = random->nextFloat() < 0.8f; } -int Mob::getMaxHeadXRot() +int Mob::getMaxHeadXRot() { return 40; } -void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) +void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) { double xd = e->x - x; double yd; double zd = e->z - z; - + if ( e->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> mob = dynamic_pointer_cast<LivingEntity>(e); yd = (mob->y + mob->getHeadHeight()) - (y + getHeadHeight()); - } - else + } + else { yd = (e->bb->y0 + e->bb->y1) / 2 - (y + getHeadHeight()); } @@ -611,31 +611,31 @@ void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) yRot = rotlerp(yRot, yRotD, yMax); } -bool Mob::isLookingAtAnEntity() +bool Mob::isLookingAtAnEntity() { return lookingAt != NULL; } -shared_ptr<Entity> Mob::getLookingAt() +shared_ptr<Entity> Mob::getLookingAt() { return lookingAt; } -float Mob::rotlerp(float a, float b, float max) +float Mob::rotlerp(float a, float b, float max) { float diff = Mth::wrapDegrees(b - a); - if (diff > max) + if (diff > max) { diff = max; } - if (diff < -max) + if (diff < -max) { diff = -max; } return a + diff; } -bool Mob::canSpawn() +bool Mob::canSpawn() { // 4J - altered to use special containsAnyLiquid variant return level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid_NoLoad(bb); @@ -651,7 +651,7 @@ float Mob::getHeadSizeScale() return 1.0f; } -int Mob::getMaxSpawnClusterSize() +int Mob::getMaxSpawnClusterSize() { return 4; } @@ -815,7 +815,7 @@ void Mob::populateDefaultEquipmentEnchantments() /** * Added this method so mobs can handle their own spawn settings instead of * hacking MobSpawner.java -* +* * @param groupData * TODO * @return TODO @@ -918,7 +918,7 @@ bool Mob::interact(shared_ptr<Player> player) if (canBeLeashed()) { shared_ptr<TamableAnimal> tamableAnimal = nullptr; - if ( shared_from_this()->instanceof(eTYPE_TAMABLE_ANIMAL) + if ( shared_from_this()->instanceof(eTYPE_TAMABLE_ANIMAL) && (tamableAnimal = dynamic_pointer_cast<TamableAnimal>(shared_from_this()))->isTame() ) // 4J-JEV: excuse the assignment operator in here, don't want to dyn-cast if it's avoidable. { if (player->getUUID().compare(tamableAnimal->getOwnerUUID()) == 0) @@ -1007,7 +1007,7 @@ void Mob::setLeashedTo(shared_ptr<Entity> holder, bool synch) { _isLeashed = true; leashHolder = holder; - + ServerLevel *serverLevel = dynamic_cast<ServerLevel *>(level); if (!level->isClientSide && synch && serverLevel) { @@ -1024,9 +1024,9 @@ void Mob::restoreLeashFromSave() { wstring leashUuid = leashInfoTag->getString(L"UUID"); vector<shared_ptr<Entity> > *livingEnts = level->getEntitiesOfClass(typeid(LivingEntity), bb->grow(10, 10, 10)); - for(AUTO_VAR(it, livingEnts->begin()); it != livingEnts->end(); ++it) + for(auto& livingEnt : *livingEnts) { - shared_ptr<LivingEntity> le = dynamic_pointer_cast<LivingEntity>(*it); + shared_ptr<LivingEntity> le = dynamic_pointer_cast<LivingEntity>(livingEnt); if (le->getUUID().compare(leashUuid) == 0) { leashHolder = le; diff --git a/Minecraft.World/MobEffect.cpp b/Minecraft.World/MobEffect.cpp index 61aee91f..92f8c9d0 100644 --- a/Minecraft.World/MobEffect.cpp +++ b/Minecraft.World/MobEffect.cpp @@ -15,26 +15,26 @@ MobEffect *MobEffect::voidEffect; MobEffect *MobEffect::movementSpeed; MobEffect *MobEffect::movementSlowdown; MobEffect *MobEffect::digSpeed; -MobEffect *MobEffect::digSlowdown; -MobEffect *MobEffect::damageBoost; -MobEffect *MobEffect::heal; -MobEffect *MobEffect::harm; +MobEffect *MobEffect::digSlowdown; +MobEffect *MobEffect::damageBoost; +MobEffect *MobEffect::heal; +MobEffect *MobEffect::harm; MobEffect *MobEffect::jump; MobEffect *MobEffect::confusion; -MobEffect *MobEffect::regeneration; +MobEffect *MobEffect::regeneration; MobEffect *MobEffect::damageResistance; -MobEffect *MobEffect::fireResistance; -MobEffect *MobEffect::waterBreathing; -MobEffect *MobEffect::invisibility; -MobEffect *MobEffect::blindness; -MobEffect *MobEffect::nightVision; -MobEffect *MobEffect::hunger; -MobEffect *MobEffect::weakness; -MobEffect *MobEffect::poison; -MobEffect *MobEffect::wither; -MobEffect *MobEffect::healthBoost; -MobEffect *MobEffect::absorption; -MobEffect *MobEffect::saturation; +MobEffect *MobEffect::fireResistance; +MobEffect *MobEffect::waterBreathing; +MobEffect *MobEffect::invisibility; +MobEffect *MobEffect::blindness; +MobEffect *MobEffect::nightVision; +MobEffect *MobEffect::hunger; +MobEffect *MobEffect::weakness; +MobEffect *MobEffect::poison; +MobEffect *MobEffect::wither; +MobEffect *MobEffect::healthBoost; +MobEffect *MobEffect::absorption; +MobEffect *MobEffect::saturation; MobEffect *MobEffect::reserved_24; MobEffect *MobEffect::reserved_25; MobEffect *MobEffect::reserved_26; @@ -121,7 +121,7 @@ int MobEffect::getId() * This method should perform periodic updates on the player. Mainly used * for regeneration effects and the like. Other effects, such as blindness, * are in effect for the whole duration of the effect. -* +* * @param mob * @param amplification */ @@ -201,7 +201,7 @@ bool MobEffect::isInstantenous() * This parameter says if the applyEffect method should be called depending * on the remaining duration ticker. For instance, the regeneration will be * activated every 8 ticks, healing one point of health. -* +* * @param remainingDuration * @param amplification * Effect amplification, starts at 0 (weakest) @@ -355,26 +355,26 @@ unordered_map<Attribute *, AttributeModifier *> *MobEffect::getAttributeModifier void MobEffect::removeAttributeModifiers(shared_ptr<LivingEntity> entity, BaseAttributeMap *attributes, int amplifier) { - for (AUTO_VAR(it, attributeModifiers.begin()); it != attributeModifiers.end(); ++it) + for (auto& it : attributeModifiers) { - AttributeInstance *attribute = attributes->getInstance(it->first); + AttributeInstance *attribute = attributes->getInstance(it.first); if (attribute != NULL) { - attribute->removeModifier(it->second); + attribute->removeModifier(it.second); } } } void MobEffect::addAttributeModifiers(shared_ptr<LivingEntity> entity, BaseAttributeMap *attributes, int amplifier) { - for (AUTO_VAR(it, attributeModifiers.begin()); it != attributeModifiers.end(); ++it) + for (auto& it : attributeModifiers) { - AttributeInstance *attribute = attributes->getInstance(it->first); + AttributeInstance *attribute = attributes->getInstance(it.first); if (attribute != NULL) { - AttributeModifier *original = it->second; + AttributeModifier *original = it.second; attribute->removeModifier(original); attribute->addModifier(new AttributeModifier(original->getId(), getAttributeModifierValue(amplifier, original), original->getOperation())); } diff --git a/Minecraft.World/MobSpawner.cpp b/Minecraft.World/MobSpawner.cpp index 8cd60e92..e593a59f 100644 --- a/Minecraft.World/MobSpawner.cpp +++ b/Minecraft.World/MobSpawner.cpp @@ -100,12 +100,10 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie } MemSect(20); chunksToPoll.clear(); - + #if 0 - AUTO_VAR(itEnd, level->players.end()); - for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++) + for (auto& player : level->players) { - shared_ptr<Player> player = *it; //level->players.at(i); int xx = Mth::floor(player->x / 16); int zz = Mth::floor(player->z / 16); @@ -164,20 +162,20 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie #ifdef __PSVITA__ ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); + cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); + cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); + cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); #else ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); + cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); + cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); + cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); #endif @@ -224,16 +222,15 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie { SCustomMapNode *it = chunksToPoll.get(i); #else - AUTO_VAR(itEndCTP, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCTP; it++) + for (auto& it : chunksToPoll) { #endif - if( it->second ) + if( it.second ) { // don't add mobs to edge chunks, to prevent adding mobs "outside" of the active playground continue; } - ChunkPos *cp = (ChunkPos *) (&it->first); + ChunkPos *cp = (ChunkPos *) (&it.first); // 4J - don't let this actually create/load a chunk that isn't here already - we'll let the normal updateDirtyChunks etc. processes do that, so it can happen on another thread if( !level->hasChunk(cp->x,cp->z) ) continue; @@ -399,7 +396,7 @@ bool MobSpawner::isSpawnPositionOk(MobCategory *category, Level *level, int x, i // 4J - changed to spawn water things only in deep water int yo = 0; int liquidCount = 0; - + while( ( y - yo ) >= 0 && ( yo < 5 ) ) { if( level->getMaterial(x, y - yo, z)->isLiquid() ) liquidCount++; diff --git a/Minecraft.World/ModifiableAttributeInstance.cpp b/Minecraft.World/ModifiableAttributeInstance.cpp index 50aa6504..3108df4d 100644 --- a/Minecraft.World/ModifiableAttributeInstance.cpp +++ b/Minecraft.World/ModifiableAttributeInstance.cpp @@ -15,12 +15,12 @@ ModifiableAttributeInstance::ModifiableAttributeInstance(BaseAttributeMap *attri ModifiableAttributeInstance::~ModifiableAttributeInstance() { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& modifier : modifiers) { - for (AUTO_VAR(it, modifiers[i].begin()); it != modifiers[i].end(); ++it) + for (auto it : modifier) { // Delete all modifiers - delete *it; + delete it; } } } @@ -51,14 +51,12 @@ unordered_set<AttributeModifier *> *ModifiableAttributeInstance::getModifiers(in // Returns a pointer to a new vector of all modifiers void ModifiableAttributeInstance::getModifiers(unordered_set<AttributeModifier *>& result) { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& modifier : modifiers) { - unordered_set<AttributeModifier *> *opModifiers = &modifiers[i]; - - for (AUTO_VAR(it, opModifiers->begin()); it != opModifiers->end(); ++it) + for (auto& opModifier : modifier) { - result.insert(*it); - } + result.insert(opModifier); + } } } @@ -66,20 +64,20 @@ AttributeModifier *ModifiableAttributeInstance::getModifier(eMODIFIER_ID id) { AttributeModifier *modifier = NULL; - AUTO_VAR(it, modifierById.find(id)); - if(it != modifierById.end()) + auto it = modifierById.find(id); + if(it != modifierById.end()) { modifier = it->second; } - return modifier; + return modifier; } void ModifiableAttributeInstance::addModifiers(unordered_set<AttributeModifier *> *modifiers) { - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - addModifier(*it); + addModifier(modifier); } } @@ -87,7 +85,7 @@ void ModifiableAttributeInstance::addModifiers(unordered_set<AttributeModifier * void ModifiableAttributeInstance::addModifier(AttributeModifier *modifier) { // Can't add modifiers with the same ID (unless the modifier is anonymous) - if (modifier->getId() != eModifierId_ANONYMOUS && getModifier(modifier->getId()) != NULL) + if (modifier->getId() != eModifierId_ANONYMOUS && getModifier(modifier->getId()) != NULL) { assert(0); // throw new IllegalArgumentException("Modifier is already applied on this attribute!"); @@ -108,13 +106,13 @@ void ModifiableAttributeInstance::setDirty() void ModifiableAttributeInstance::removeModifier(AttributeModifier *modifier) { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& mod : modifiers) { - for (AUTO_VAR(it, modifiers[i].begin()); it != modifiers[i].end(); ++it) - { - if (modifier->equals(*it)) + for (auto& it : mod ) + { + if (modifier->equals(it)) { - modifiers[i].erase(it); + mod.erase(it); break; } } @@ -136,9 +134,9 @@ void ModifiableAttributeInstance::removeModifiers() unordered_set<AttributeModifier *> removingModifiers; getModifiers(removingModifiers); - for (AUTO_VAR(it, removingModifiers.begin()); it != removingModifiers.end(); ++it) + for (auto& it : removingModifiers) { - removeModifier(*it); + removeModifier(it); } } @@ -159,25 +157,22 @@ double ModifiableAttributeInstance::calculateValue() unordered_set<AttributeModifier *> *modifiers; modifiers = getModifiers(AttributeModifier::OPERATION_ADDITION); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; base += modifier->getAmount(); } double result = base; modifiers = getModifiers(AttributeModifier::OPERATION_MULTIPLY_BASE); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; result += base * modifier->getAmount(); } - + modifiers = getModifiers(AttributeModifier::OPERATION_MULTIPLY_TOTAL); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; result *= 1 + modifier->getAmount(); } diff --git a/Minecraft.World/MonsterPlacerItem.cpp b/Minecraft.World/MonsterPlacerItem.cpp index a2970033..e5a84122 100644 --- a/Minecraft.World/MonsterPlacerItem.cpp +++ b/Minecraft.World/MonsterPlacerItem.cpp @@ -29,7 +29,7 @@ wstring MonsterPlacerItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //elementName += " " + I18n.get("entity." + encodeId + ".name"); } else - { + { elementName = replaceAll(elementName,L"{*CREATURE*}",L""); } @@ -38,8 +38,8 @@ wstring MonsterPlacerItem::getHoverName(shared_ptr<ItemInstance> itemInstance) int MonsterPlacerItem::getColor(shared_ptr<ItemInstance> item, int spriteLayer) { - AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); - if (it != EntityIO::idsSpawnableInCreative.end()) + auto it = EntityIO::idsSpawnableInCreative.find(item->getAuxValue()); + if (it != EntityIO::idsSpawnableInCreative.end()) { EntityIO::SpawnableMobInfo *spawnableMobInfo = it->second; if (spriteLayer == 0) { @@ -193,7 +193,7 @@ bool MonsterPlacerItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr< x += Facing::STEP_X[face]; y += Facing::STEP_Y[face]; z += Facing::STEP_Z[face]; - + double yOff = 0; // 4J-PB - missing parentheses added if (face == Facing::UP && (tile == Tile::fence_Id || tile == Tile::netherFence_Id)) @@ -211,11 +211,11 @@ bool MonsterPlacerItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr< } if (spawned) - { + { if (!player->abilities.instabuild) { itemInstance->count--; - } + } } else { diff --git a/Minecraft.World/MoveThroughVillageGoal.cpp b/Minecraft.World/MoveThroughVillageGoal.cpp index d4cdde94..f112c109 100644 --- a/Minecraft.World/MoveThroughVillageGoal.cpp +++ b/Minecraft.World/MoveThroughVillageGoal.cpp @@ -87,10 +87,8 @@ shared_ptr<DoorInfo> MoveThroughVillageGoal::getNextDoorInfo(shared_ptr<Village> shared_ptr<DoorInfo> closest = nullptr; int closestDistSqr = Integer::MAX_VALUE; vector<shared_ptr<DoorInfo> > *doorInfos = village->getDoorInfos(); - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos->begin()); it != doorInfos->end(); ++it) + for(auto& di : *doorInfos) { - shared_ptr<DoorInfo> di = *it; int distSqr = di->distanceToSqr(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); if (distSqr < closestDistSqr) { @@ -104,11 +102,10 @@ shared_ptr<DoorInfo> MoveThroughVillageGoal::getNextDoorInfo(shared_ptr<Village> bool MoveThroughVillageGoal::hasVisited(shared_ptr<DoorInfo>di) { - //for (DoorInfo di2 : visited) - for(AUTO_VAR(it, visited.begin()); it != visited.end(); ) - { + for (auto it = visited.begin(); it != visited.end();) + { shared_ptr<DoorInfo> di2 = (*it).lock(); - if( di2 == NULL ) + if( di2 ) { it = visited.erase(it); } diff --git a/Minecraft.World/NbtSlotFile.cpp b/Minecraft.World/NbtSlotFile.cpp index 81880cfb..8bae14c6 100644 --- a/Minecraft.World/NbtSlotFile.cpp +++ b/Minecraft.World/NbtSlotFile.cpp @@ -89,11 +89,8 @@ vector<CompoundTag *> *NbtSlotFile::readAll(int slot) vector<int> *fileSlots = fileSlotMap[slot]; int skipped = 0; - AUTO_VAR(itEnd, fileSlots->end()); - for (AUTO_VAR(it, fileSlots->begin()); it != itEnd; it++) + for (int c : *fileSlots) { - int c = *it; //fileSlots->at(i); - int pos = 0; int continuesAt = -1; int expectedSlot = slot + 1; @@ -115,8 +112,6 @@ vector<CompoundTag *> *NbtSlotFile::readAll(int slot) goto fileSlotLoop; // 4J - used to be continue fileSlotLoop, with for loop labelled as fileSlotLoop } -// if (oldSlot != expectedSlot) throw new IOException("Wrong slot! Got " + oldSlot + ", expected " + expectedSlot); // 4J - TODO - ReadFile(raf,READ_BUFFER.data + pos,size,&numberOfBytesRead,NULL); if (continuesAt >= 0) @@ -144,12 +139,12 @@ int NbtSlotFile::getFreeSlot() // fileSlot = toReplace->back(); // toReplace->pop_back(); // } else - + if (freeFileSlots.size() > 0) { fileSlot = freeFileSlots.back(); freeFileSlots.pop_back(); - } + } else { fileSlot = totalFileSlots++; @@ -164,11 +159,9 @@ void NbtSlotFile::replaceSlot(int slot, vector<CompoundTag *> *tags) DWORD numberOfBytesWritten; toReplace = fileSlotMap[slot]; fileSlotMap[slot] = new vector<int>(); - - AUTO_VAR(itEndTags, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEndTags; it++) + + for (auto tag : *tags) { - CompoundTag *tag = *it; //tags->at(i); byteArray compressed = NbtIo::compress(tag); if (compressed.length > largest) { @@ -227,12 +220,9 @@ void NbtSlotFile::replaceSlot(int slot, vector<CompoundTag *> *tags) } delete[] compressed.data; } - - AUTO_VAR(itEndToRep, toReplace->end()); - for (AUTO_VAR(it, toReplace->begin()); it != itEndToRep; it++) - { - int c = *it; //toReplace->at(i); + for (int c : *toReplace) + { freeFileSlots.push_back(c); seekSlotHeader(c); diff --git a/Minecraft.World/NetherBridgeFeature.cpp b/Minecraft.World/NetherBridgeFeature.cpp index 2cf883c4..d661d3b7 100644 --- a/Minecraft.World/NetherBridgeFeature.cpp +++ b/Minecraft.World/NetherBridgeFeature.cpp @@ -13,7 +13,7 @@ NetherBridgeFeature::NetherBridgeFeature() : StructureFeature() bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_BLAZE, 10, 2, 3)); bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_PIGZOMBIE, 5, 4, 4)); bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_SKELETON, 10, 4, 4)); - bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); + bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); isSpotSelected=false; netherFortressPos = NULL; @@ -38,7 +38,7 @@ bool NetherBridgeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { // 4J Stu - New implementation to force a nether fortress if (!isSpotSelected) - { + { // Set the random random->setSeed(level->getSeed()); random->nextInt(); @@ -119,8 +119,8 @@ NetherBridgeFeature::NetherBridgeStart::NetherBridgeStart(Level *level, Random * while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingChildren->begin() + pos; + StructurePiece *structurePiece = *it; pendingChildren->erase(it); structurePiece->addChildren(start, &pieces, random); } diff --git a/Minecraft.World/NetherBridgePieces.cpp b/Minecraft.World/NetherBridgePieces.cpp index ff158fba..35baa71a 100644 --- a/Minecraft.World/NetherBridgePieces.cpp +++ b/Minecraft.World/NetherBridgePieces.cpp @@ -65,7 +65,7 @@ NetherBridgePieces::PieceWeight *NetherBridgePieces::bridgePieceWeights[NetherBr new PieceWeight(EPieceClass_StairsRoom, 10, 3), }; -NetherBridgePieces::PieceWeight *NetherBridgePieces::castlePieceWeights[NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = +NetherBridgePieces::PieceWeight *NetherBridgePieces::castlePieceWeights[NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = { new PieceWeight(EPieceClass_CastleStalkRoom, 30, 2), // 4J Stu - Increased weight to ensure that we have these (was 5), required for Nether Wart, and therefore required for brewing new PieceWeight(EPieceClass_CastleSmallCorridorPiece, 25, 0, true), @@ -171,10 +171,8 @@ int NetherBridgePieces::NetherBridgePiece::updatePieceWeight(list<PieceWeight *> { bool hasAnyPieces = false; int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) + for(auto& piece : *currentPieces) { - PieceWeight *piece = *it; - if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -195,9 +193,8 @@ NetherBridgePieces::NetherBridgePiece *NetherBridgePieces::NetherBridgePiece::ge numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : *currentPieces ) + { weightSelection -= piece->weight; if (weightSelection < 0) { @@ -378,7 +375,7 @@ NetherBridgePieces::BridgeStraight *NetherBridgePieces::BridgeStraight::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -444,7 +441,7 @@ NetherBridgePieces::BridgeEndFiller *NetherBridgePieces::BridgeEndFiller::create { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -552,7 +549,7 @@ NetherBridgePieces::BridgeCrossing *NetherBridgePieces::BridgeCrossing::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -8, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -671,7 +668,7 @@ NetherBridgePieces::RoomCrossing *NetherBridgePieces::RoomCrossing::createPiece( { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -741,7 +738,7 @@ NetherBridgePieces::StairsRoom *NetherBridgePieces::StairsRoom::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -815,7 +812,7 @@ NetherBridgePieces::MonsterThrone *NetherBridgePieces::MonsterThrone::createPiec { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -911,7 +908,7 @@ NetherBridgePieces::CastleEntrance *NetherBridgePieces::CastleEntrance::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1041,7 +1038,7 @@ NetherBridgePieces::CastleStalkRoom *NetherBridgePieces::CastleStalkRoom::create { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1207,7 +1204,7 @@ NetherBridgePieces::CastleSmallCorridorPiece *NetherBridgePieces::CastleSmallCor BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1271,7 +1268,7 @@ NetherBridgePieces::CastleSmallCorridorCrossingPiece *NetherBridgePieces::Castle { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1347,7 +1344,7 @@ NetherBridgePieces::CastleSmallCorridorRightTurnPiece *NetherBridgePieces::Castl { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1439,7 +1436,7 @@ NetherBridgePieces::CastleSmallCorridorLeftTurnPiece *NetherBridgePieces::Castle { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1515,7 +1512,7 @@ NetherBridgePieces::CastleCorridorStairsPiece *NetherBridgePieces::CastleCorrido { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -7, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1597,7 +1594,7 @@ NetherBridgePieces::CastleCorridorTBalconyPiece *NetherBridgePieces::CastleCorri { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -3, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) diff --git a/Minecraft.World/NetherWartTile.cpp b/Minecraft.World/NetherWartTile.cpp index 1faa57ca..add3eccf 100644 --- a/Minecraft.World/NetherWartTile.cpp +++ b/Minecraft.World/NetherWartTile.cpp @@ -107,6 +107,6 @@ void NetherWartTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < NETHER_STALK_TEXTURE_COUNT; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString<int>(i) ); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i) ); } } diff --git a/Minecraft.World/Node.cpp b/Minecraft.World/Node.cpp index 5f501a84..7059c045 100644 --- a/Minecraft.World/Node.cpp +++ b/Minecraft.World/Node.cpp @@ -28,12 +28,12 @@ hash(createHash(x, y, z)) //hash = createHash(x, y, z); } -int Node::createHash(const int x, const int y, const int z) +int Node::createHash(const int x, const int y, const int z) { return (y & 0xff) | ((x & 0x7fff) << 8) | ((z & 0x7fff) << 24) | ((x < 0) ? 0x0080000000 : 0) | ((z < 0) ? 0x0000008000 : 0); } -float Node::distanceTo(Node *to) +float Node::distanceTo(Node *to) { float xd = (float) ( to->x - x ); float yd = (float) ( to->y - y ); @@ -49,27 +49,27 @@ float Node::distanceToSqr(Node *to) return xd * xd + yd * yd + zd * zd; } -bool Node::equals(Node *o) +bool Node::equals(Node *o) { //4J Jev, never used anything other than a node. - //if (dynamic_cast<Node *>((Node *) o) != NULL) + //if (dynamic_cast<Node *>((Node *) o) != NULL) //{ return hash == o->hash && x == o->x && y == o->y && z == o->z; //} //return false; } -int Node::hashCode() +int Node::hashCode() { return hash; } -bool Node::inOpenSet() +bool Node::inOpenSet() { return heapIdx >= 0; } -wstring Node::toString() +wstring Node::toString() { - return _toString<int>(x) + L", " + _toString<int>(y) + L", " + _toString<int>(z); + return std::to_wstring(x) + L", " + std::to_wstring(y) + L", " + std::to_wstring(z); }
\ No newline at end of file diff --git a/Minecraft.World/NotGateTile.cpp b/Minecraft.World/NotGateTile.cpp index 464e0ca5..3aa9aee1 100644 --- a/Minecraft.World/NotGateTile.cpp +++ b/Minecraft.World/NotGateTile.cpp @@ -28,10 +28,9 @@ bool NotGateTile::isToggledTooFrequently(Level *level, int x, int y, int z, bool if (add) recentToggles[level]->push_back(Toggle(x, y, z, level->getGameTime())); int count = 0; - AUTO_VAR(itEnd, recentToggles[level]->end()); - for (AUTO_VAR(it, recentToggles[level]->begin()); it != itEnd; it++) + for (const auto& it : *recentToggles[level]) { - if (it->x == x && it->y == y && it->z == z) + if (it.x == x && it.y == y && it.z == z) { count++; if (count >= MAX_RECENT_TOGGLES) @@ -122,7 +121,7 @@ void NotGateTile::tick(Level *level, int x, int y, int z, Random *random) } } - if (on) + if (on) { if (neighborSignal) { @@ -153,7 +152,7 @@ void NotGateTile::tick(Level *level, int x, int y, int z, Random *random) level->setTileAndData(x, y, z, Tile::redstoneTorch_on_Id, level->getData(x, y, z), Tile::UPDATE_ALL); } else - { + { app.DebugPrintf("Torch at (%d,%d,%d) has toggled too many times\n",x,y,z); } } @@ -236,9 +235,9 @@ void NotGateTile::levelTimeChanged(Level *level, __int64 delta, __int64 newTime) if (toggles != NULL) { - for (AUTO_VAR(it,toggles->begin()); it != toggles->end(); ++it) + for (auto& toggle : *toggles) { - (*it).when += delta; + toggle.when += delta; } } } diff --git a/Minecraft.World/OldChunkStorage.cpp b/Minecraft.World/OldChunkStorage.cpp index 31f4394f..24263d0d 100644 --- a/Minecraft.World/OldChunkStorage.cpp +++ b/Minecraft.World/OldChunkStorage.cpp @@ -103,7 +103,7 @@ File OldChunkStorage::getFile(int x, int z) file = File( file, wstring( name ) ); if ( !file.exists() ) { - if (!create) + if (!create) { return File(L""); } @@ -163,7 +163,7 @@ void OldChunkStorage::save(Level *level, LevelChunk *levelChunk) { LevelData *levelData = level->getLevelData(); levelData->setSizeOnDisk( levelData->getSizeOnDisk() - file.length() ); - } + } // 4J - removed try/catch // try { @@ -202,7 +202,7 @@ bool OldChunkStorage::saveEntities(LevelChunk *lc, Level *level, CompoundTag *ta lc->lastSaveHadEntities = false; ListTag<CompoundTag> *entityTags = new ListTag<CompoundTag>(); - + #ifdef _ENTITIES_RW_SECTION EnterCriticalRWSection(&lc->m_csEntities, true); #else @@ -210,17 +210,14 @@ bool OldChunkStorage::saveEntities(LevelChunk *lc, Level *level, CompoundTag *ta #endif for (int i = 0; i < lc->ENTITY_BLOCKS_LENGTH; i++) { - AUTO_VAR(itEnd, lc->entityBlocks[i]->end()); - for( vector<shared_ptr<Entity> >::iterator it = lc->entityBlocks[i]->begin(); it != itEnd; it++ ) + for( auto& e : *lc->entityBlocks[i] ) { - shared_ptr<Entity> e = *it; lc->lastSaveHadEntities = true; CompoundTag *teTag = new CompoundTag(); - if (e->save(teTag)) + if ( e && e->save(teTag)) { entityTags->add(teTag); } - } } #ifdef _ENTITIES_RW_SECTION @@ -264,15 +261,13 @@ void OldChunkStorage::save(LevelChunk *lc, Level *level, DataOutputStream *dos) #ifndef SPLIT_SAVES saveEntities(lc, level, tag); #endif - + PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) + for(auto& it : lc->tileEntities) { - shared_ptr<TileEntity> te = it->second; + shared_ptr<TileEntity> te = it.second; CompoundTag *teTag = new CompoundTag(); te->save(teTag); tileEntityTags->add(teTag); @@ -358,11 +353,9 @@ void OldChunkStorage::save(LevelChunk *lc, Level *level, CompoundTag *tag) PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) + for(auto& it : lc->tileEntities) { - shared_ptr<TileEntity> te = it->second; + shared_ptr<TileEntity> te = it.second; CompoundTag *teTag = new CompoundTag(); te->save(teTag); tileEntityTags->add(teTag); @@ -451,7 +444,7 @@ LevelChunk *OldChunkStorage::load(Level *level, DataInputStream *dis) dis->readFully(levelChunk->heightmap); - levelChunk->terrainPopulated = dis->readShort(); + levelChunk->terrainPopulated = dis->readShort(); // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps // before this flag was added. @@ -537,13 +530,13 @@ LevelChunk *OldChunkStorage::load(Level *level, CompoundTag *tag) if( tag->get(L"TerrainPopulated") ) { // Java bool type or byte bitfield - levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); + levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); if( levelChunk->terrainPopulated >= 1 ) levelChunk->terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; // Convert from old bool type to new bitfield } else { // New style short - levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); + levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps // before this flag was added. diff --git a/Minecraft.World/Packet.cpp b/Minecraft.World/Packet.cpp index f1630db5..a37cb2ad 100644 --- a/Minecraft.World/Packet.cpp +++ b/Minecraft.World/Packet.cpp @@ -30,7 +30,7 @@ void Packet::staticCtor() map(8, true, false, true, true, typeid(SetHealthPacket), SetHealthPacket::create); map(9, true, true, true, false, typeid(RespawnPacket), RespawnPacket::create); - map(10, true, true, true, false, typeid(MovePlayerPacket), MovePlayerPacket::create); + map(10, true, true, true, false, typeid(MovePlayerPacket), MovePlayerPacket::create); map(11, true, true, true, true, typeid(MovePlayerPacket::Pos), MovePlayerPacket::Pos::create); map(12, true, true, true, true, typeid(MovePlayerPacket::Rot), MovePlayerPacket::Rot::create); map(13, true, true, true, true, typeid(MovePlayerPacket::PosRot), MovePlayerPacket::PosRot::create); @@ -182,7 +182,7 @@ int Packet::renderPos = 0; void Packet::map(int id, bool receiveOnClient, bool receiveOnServer, bool sendToAnyClient, bool renderStats, const type_info& clazz, packetCreateFn createFn) { #if 0 - if (idToClassMap.count(id) > 0) throw new IllegalArgumentException(wstring(L"Duplicate packet id:") + _toString<int>(id)); + if (idToClassMap.count(id) > 0) throw new IllegalArgumentException(wstring(L"Duplicate packet id:") + std::to_wstring(id)); if (classToIdMap.count(clazz) > 0) throw new IllegalArgumentException(L"Duplicate packet class:"); // TODO + clazz); #endif @@ -228,7 +228,7 @@ void Packet::recordOutgoingPacket(shared_ptr<Packet> packet, int playerIndex) idx = 100; } #endif - AUTO_VAR(it, outgoingStatistics.find(idx)); + auto it = outgoingStatistics.find(idx); if( it == outgoingStatistics.end() ) { @@ -248,8 +248,8 @@ void Packet::updatePacketStatsPIX() { #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - - for( AUTO_VAR(it, outgoingStatistics.begin()); it != outgoingStatistics.end(); it++ ) + + for( auto it = outgoingStatistics.begin(); it != outgoingStatistics.end(); it++ ) { Packet::PacketStatistics *stat = it->second; __int64 count = stat->getRunningCount(); @@ -265,7 +265,7 @@ void Packet::updatePacketStatsPIX() #endif } -shared_ptr<Packet> Packet::getPacket(int id) +shared_ptr<Packet> Packet::getPacket(int id) { // 4J: Removed try/catch return idToCreateMap[id](); @@ -332,16 +332,16 @@ shared_ptr<Packet> Packet::readPacket(DataInputStream *dis, bool isServer) // th //app.DebugPrintf("Bad packet id %d\n", id); __debugbreak(); assert(false); - // throw new IOException(wstring(L"Bad packet id ") + _toString<int>(id)); + // throw new IOException(wstring(L"Bad packet id ") + std::to_wstring(id)); } packet = getPacket(id); - if (packet == NULL) assert(false);//throw new IOException(wstring(L"Bad packet id ") + _toString<int>(id)); - + if (packet == NULL) assert(false);//throw new IOException(wstring(L"Bad packet id ") + std::to_wstring(id)); + //app.DebugPrintf("%s reading packet %d\n", isServer ? "Server" : "Client", packet->getId()); packet->read(dis); // } - // catch (EOFException e) + // catch (EOFException e) // { // // reached end of stream // OutputDebugString("Reached end of stream"); @@ -352,7 +352,7 @@ shared_ptr<Packet> Packet::readPacket(DataInputStream *dis, bool isServer) // th // 4J Stu - This changes a bit in 1.0.1, but we don't really use it so stick with what we have #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - AUTO_VAR(it, statistics.find(id)); + auto it = statistics.find(id); if( it == statistics.end() ) { @@ -380,7 +380,7 @@ void Packet::writePacket(shared_ptr<Packet> packet, DataOutputStream *dos) // th void Packet::writeUtf(const wstring& value, DataOutputStream *dos) // throws IOException TODO 4J JEV, should this declare a throws? { #if 0 - if (value.length() > Short::MAX_VALUE) + if (value.length() > Short::MAX_VALUE) { throw new IOException(L"String too big"); } @@ -408,7 +408,7 @@ wstring Packet::readUtf(DataInputStream *dis, int maxLength) // throws IOExcepti } wstring builder = L""; - for (int i = 0; i < stringLength; i++) + for (int i = 0; i < stringLength; i++) { wchar_t rc = dis->readChar(); builder.push_back( rc ); @@ -432,7 +432,7 @@ void Packet::PacketStatistics::addPacket(int bytes) count++; } -int Packet::PacketStatistics::getCount() +int Packet::PacketStatistics::getCount() { return count; } @@ -446,7 +446,7 @@ double Packet::PacketStatistics::getAverageSize() return (double) totalSize / count; } -int Packet::PacketStatistics::getTotalSize() +int Packet::PacketStatistics::getTotalSize() { return totalSize; } diff --git a/Minecraft.World/PathFinder.cpp b/Minecraft.World/PathFinder.cpp index 029cf582..2e11648f 100644 --- a/Minecraft.World/PathFinder.cpp +++ b/Minecraft.World/PathFinder.cpp @@ -26,14 +26,13 @@ PathFinder::~PathFinder() // references to the same things, so just need to destroy their containers delete [] neighbors->data; delete neighbors; - AUTO_VAR(itEnd, nodes.end()); - for( AUTO_VAR(it, nodes.begin()); it != itEnd; it++ ) + for(auto& node : nodes) { - delete it->second; + delete node.second; } } -Path *PathFinder::findPath(Entity *from, Entity *to, float maxDist) +Path *PathFinder::findPath(Entity *from, Entity *to, float maxDist) { return findPath(from, to->x, to->bb->y0, to->z, maxDist); } @@ -187,9 +186,9 @@ Node *PathFinder::getNode(Entity *entity, int x, int y, int z, Node *size, int j /*final*/ Node *PathFinder::getNode(int x, int y, int z) { int i = Node::createHash(x, y, z); - Node *node; - AUTO_VAR(it, nodes.find(i)); - if ( it == nodes.end() ) + Node *node = nullptr; + auto it = nodes.find(i); + if ( it == nodes.end() ) { MemSect(54); node = new Node(x, y, z); @@ -279,7 +278,7 @@ Path *PathFinder::reconstruct_path(Node *from, Node *to) NodeArray nodes = NodeArray(count); n = to; nodes.data[--count] = n; - while (n->cameFrom != NULL) + while (n->cameFrom != NULL) { n = n->cameFrom; nodes.data[--count] = n; diff --git a/Minecraft.World/PigZombie.cpp b/Minecraft.World/PigZombie.cpp index 7a736c9a..c284c323 100644 --- a/Minecraft.World/PigZombie.cpp +++ b/Minecraft.World/PigZombie.cpp @@ -70,7 +70,7 @@ void PigZombie::tick() Zombie::tick(); } -bool PigZombie::canSpawn() +bool PigZombie::canSpawn() { return level->difficulty > Difficulty::PEACEFUL && level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb); } @@ -107,11 +107,9 @@ bool PigZombie::hurt(DamageSource *source, float dmg) shared_ptr<Entity> sourceEntity = source->getEntity(); if ( sourceEntity != NULL && sourceEntity->instanceof(eTYPE_PLAYER) ) { - vector<shared_ptr<Entity> > *nearby = level->getEntities( shared_from_this(), bb->grow(32, 32, 32)); - AUTO_VAR(itEnd, nearby->end()); - for (AUTO_VAR(it, nearby->begin()); it != itEnd; it++) + vector<shared_ptr<Entity> > *nearby = level->getEntities( shared_from_this(), bb->grow(32, 32, 32)); + for (auto& e : *nearby) { - shared_ptr<Entity> e = *it; //nearby->at(i); if ( e->instanceof(eTYPE_PIGZOMBIE) ) { shared_ptr<PigZombie> pigZombie = dynamic_pointer_cast<PigZombie>(e); diff --git a/Minecraft.World/PistonPieceEntity.cpp b/Minecraft.World/PistonPieceEntity.cpp index 0d0a86d0..a915c2ff 100644 --- a/Minecraft.World/PistonPieceEntity.cpp +++ b/Minecraft.World/PistonPieceEntity.cpp @@ -123,14 +123,14 @@ void PistonPieceEntity::moveCollidedEntities(float progress, float amount) if (!entities->empty()) { vector< shared_ptr<Entity> > collisionHolder; - for( AUTO_VAR(it, entities->begin()); it != entities->end(); it++ ) + for(auto& it : *entities) { - collisionHolder.push_back(*it); + collisionHolder.push_back(it); } - for( AUTO_VAR(it, collisionHolder.begin()); it != collisionHolder.end(); it++ ) + for(auto& it : collisionHolder) { - (*it)->move(amount * Facing::STEP_X[facing], + it->move(amount * Facing::STEP_X[facing], amount * Facing::STEP_Y[facing], amount * Facing::STEP_Z[facing]); } diff --git a/Minecraft.World/PlayGoal.cpp b/Minecraft.World/PlayGoal.cpp index a3760862..72ee69d4 100644 --- a/Minecraft.World/PlayGoal.cpp +++ b/Minecraft.World/PlayGoal.cpp @@ -27,10 +27,8 @@ bool PlayGoal::canUse() vector<shared_ptr<Entity> > *children = mob->level->getEntitiesOfClass(typeid(Villager), mob->bb->grow(6, 3, 6)); double closestDistSqr = Double::MAX_VALUE; - //for (Entity c : children) - for(AUTO_VAR(it, children->begin()); it != children->end(); ++it) + for(auto& c : *children) { - shared_ptr<Entity> c = *it; if (c.get() == mob) continue; shared_ptr<Villager> friendV = dynamic_pointer_cast<Villager>(c); if (friendV->isChasing()) continue; diff --git a/Minecraft.World/Player.cpp b/Minecraft.World/Player.cpp index e0fa26ad..bd6b68a8 100644 --- a/Minecraft.World/Player.cpp +++ b/Minecraft.World/Player.cpp @@ -2,7 +2,7 @@ // All the instanceof s from Java have been converted to dynamic_cast in this file // Once all the classes are finished it may be that we do not need to use dynamic_cast -// for every test and a simple virtual function should suffice. We probably only need +// for every test and a simple virtual function should suffice. We probably only need // dynamic_cast to find one of the classes that an object derives from, and not to find // the derived class itself (which should own the virtual GetType function) @@ -348,7 +348,7 @@ void Player::tick() zCloak += zca * 0.25; yCloak += yca * 0.25; - if (riding == NULL) + if (riding == NULL) { if( minecartAchievementPos != NULL ) { @@ -458,7 +458,7 @@ void Player::tick() // minecart. For some reason some of the torches come off so it will also need some fixing along the way. static bool madeTrack = false; if( !madeTrack ) - { + { this->drop( shared_ptr<ItemInstance>( new ItemInstance( Item::minecart, 1 ) ) ); this->drop( shared_ptr<ItemInstance>( new ItemInstance( Tile::goldenRail, 10 ) ) ); this->drop( shared_ptr<ItemInstance>( new ItemInstance( Tile::lever, 10 ) ) ); @@ -631,8 +631,8 @@ void Player::ride(shared_ptr<Entity> e) LivingEntity::ride(e); } -void Player::setPlayerDefaultSkin(EDefaultSkins skin) -{ +void Player::setPlayerDefaultSkin(EDefaultSkins skin) +{ #ifndef _CONTENT_PACKAGE wprintf(L"Setting default skin to %d for player %ls\n", skin, name.c_str() ); #endif @@ -651,8 +651,8 @@ void Player::setCustomSkin(DWORD skinId) setAnimOverrideBitmask(getSkinAnimOverrideBitmask(skinId)); if( !GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { - // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a possible custom skin editor skin + { + // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a possible custom skin editor skin DWORD ugcSkinIndex = GET_UGC_SKIN_ID_FROM_BITMASK(skinId); DWORD defaultSkinIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(skinId); if( ugcSkinIndex == 0 && defaultSkinIndex > 0 ) @@ -722,7 +722,7 @@ unsigned int Player::getSkinAnimOverrideBitmask(DWORD skinId) { unsigned long bitmask = 0L; if( GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { + { // Temp check for anim override switch( GET_DLC_SKIN_ID_FROM_BITMASK(skinId) ) { @@ -785,7 +785,7 @@ void Player::setCustomCape(DWORD capeId) else { MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) + if(pMojangData) { // Cape if(pMojangData->wchCape) @@ -822,7 +822,7 @@ void Player::setCustomCape(DWORD capeId) DWORD Player::getCapeIdFromPath(const wstring &cape) { - bool dlcCape = false; + bool dlcCape = false; unsigned int capeId = 0; if(cape.size() >= 14) @@ -886,7 +886,7 @@ void Player::ChangePlayerSkin() this->customTextureUrl=L""; } else - { + { if(m_uiPlayerCurrentSkin>0) { // change this players custom texture url @@ -900,7 +900,7 @@ void Player::prepareCustomTextures() { MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) + if(pMojangData) { // Skin if(pMojangData->wchSkin) @@ -1054,11 +1054,9 @@ void Player::aiStep() vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), pickupArea); if (entities != NULL) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (!e->removed) + if ( e && !e->removed) { touch(e); } @@ -1135,11 +1133,14 @@ void Player::awardKillScore(shared_ptr<Entity> victim, int awardPoints) if(objectives) { - for (AUTO_VAR(it,objectives->begin()); it != objectives->end(); ++it) + for (auto& objective : *objectives) { - Objective *objective = *it; - Score *score = getScoreboard()->getPlayerScore(getAName(), objective); - score->increment(); + if ( objective ) + { + Score *score = getScoreboard()->getPlayerScore(getAName(), objective); + if ( score ) + score->increment(); + } } } } @@ -1546,7 +1547,7 @@ bool Player::interact(shared_ptr<Entity> entity) } if ( (item != NULL) && entity->instanceof(eTYPE_LIVINGENTITY) ) - { + { // 4J - PC Comments // Hack to prevent item stacks from decrementing if the player has // the ability to instabuild @@ -1597,7 +1598,7 @@ void Player::attack(shared_ptr<Entity> entity) int knockback = 0; float magicBoost = 0; - + if ( entity->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<Player> thisPlayer = dynamic_pointer_cast<Player>(shared_from_this()); @@ -1657,7 +1658,7 @@ void Player::attack(shared_ptr<Entity> entity) } setLastHurtMob(entity); - + if ( entity->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> mob = dynamic_pointer_cast<LivingEntity>(entity); @@ -1800,11 +1801,11 @@ Player::BedSleepingResult Player::startSleepInBed(int x, int y, int z, bool bTes } // This causes a message to be displayed, so we do want to show the tooltip in test mode - if (!bTestUse && level->isDay()) + if (!bTestUse && level->isDay()) { // may not sleep during day return NOT_POSSIBLE_NOW; - } + } } if(bTestUse) @@ -1889,7 +1890,7 @@ void Player::setBedOffset(int bedDirection) /** -* +* * @param forcefulWakeUp * If the player has been forced to wake up. When this happens, * the client will skip the wake-up animation. For example, when @@ -2193,7 +2194,7 @@ void Player::checkMovementStatistiscs(double dx, double dy, double dz) void Player::checkRidingStatistiscs(double dx, double dy, double dz) -{ +{ if (riding != NULL) { int distance = (int) Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); @@ -2215,7 +2216,7 @@ void Player::checkRidingStatistiscs(double dx, double dy, double dz) minecartAchievementPos = new Pos(Mth::floor(x), Mth::floor(y), Mth::floor(z)); } // 4J-PB - changed this because our world isn't big enough to go 1000m - else + else { // 4-JEV, changed slightly to add extra parameters for event on durango. int dist = minecartAchievementPos->dist(Mth::floor(x), Mth::floor(y), Mth::floor(z)); @@ -2242,7 +2243,7 @@ void Player::checkRidingStatistiscs(double dx, double dy, double dz) awardStat(GenericStats::onARail(), GenericStats::param_onARail(dist)); m_bAwardedOnARail=true; } -#endif +#endif } } @@ -2304,13 +2305,13 @@ void Player::killed(shared_ptr<LivingEntity> mob) case eTYPE_SKELETON: if( mob->isRiding() && mob->riding->GetType() == eTYPE_SPIDER ) awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else + else awardStat(GenericStats::killsSkeleton(), GenericStats::param_noArgs()); break; case eTYPE_SPIDER: if( mob->rider.lock() != NULL && mob->rider.lock()->GetType() == eTYPE_SKELETON ) awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else + else awardStat(GenericStats::killsSpider(), GenericStats::param_noArgs()); break; case eTYPE_ZOMBIE: @@ -2432,7 +2433,7 @@ int Player::getXpNeededForNextLevel() /** * This method adds on to the player's exhaustion, which may decrease the * player's food level. -* +* * @param amount * Amount of exhaustion to add, between 0 and 20 (setting it to * 20 will guarantee that at least 1, and at most 4, food points @@ -2769,7 +2770,7 @@ void Player::setPlayerGamePrivilege(unsigned int &uiGamePrivileges, EPlayerGameP } } else if (privilege < ePlayerGamePrivilege_MAX ) - { + { if(value!=0) { uiGamePrivileges|=(1<<privilege); @@ -3073,7 +3074,7 @@ void Player::enableAllPlayerPrivileges(unsigned int &uigamePrivileges, bool enab } void Player::enableAllPlayerPrivileges(bool enable) -{ +{ Player::enableAllPlayerPrivileges(m_uiGamePrivileges,enable); } @@ -3082,8 +3083,8 @@ bool Player::canCreateParticles() return !hasInvisiblePrivilege(); } -vector<ModelPart *> *Player::GetAdditionalModelParts() -{ +vector<ModelPart *> *Player::GetAdditionalModelParts() +{ if(m_ppAdditionalModelParts==NULL && !m_bCheckedForModelParts) { bool hasCustomTexture = !customTextureUrl.empty(); @@ -3127,8 +3128,8 @@ vector<ModelPart *> *Player::GetAdditionalModelParts() return m_ppAdditionalModelParts; } -void Player::SetAdditionalModelParts(vector<ModelPart *> *ppAdditionalModelParts) -{ +void Player::SetAdditionalModelParts(vector<ModelPart *> *ppAdditionalModelParts) +{ m_ppAdditionalModelParts=ppAdditionalModelParts; } @@ -3139,7 +3140,7 @@ Player::ePlayerNameValidState Player::GetPlayerNameValidState(void) return m_ePlayerNameValidState; } -void Player::SetPlayerNameValidState(bool bState) +void Player::SetPlayerNameValidState(bool bState) { if(bState) { diff --git a/Minecraft.World/PortalForcer.cpp b/Minecraft.World/PortalForcer.cpp index 8880399e..b3850807 100644 --- a/Minecraft.World/PortalForcer.cpp +++ b/Minecraft.World/PortalForcer.cpp @@ -19,9 +19,9 @@ PortalForcer::PortalForcer(ServerLevel *level) PortalForcer::~PortalForcer() { - for(AUTO_VAR(it,cachedPortals.begin()); it != cachedPortals.end(); ++it) + for(auto& it : cachedPortals) { - delete it->second; + delete it.second; } } @@ -96,8 +96,8 @@ bool PortalForcer::findPortal(shared_ptr<Entity> e, double xOriginal, double yOr long hash = ChunkPos::hashCode(xc, zc); bool updateCache = true; - AUTO_VAR(it, cachedPortals.find(hash)); - if (it != cachedPortals.end()) + auto it = cachedPortals.find(hash); + if (it != cachedPortals.end()) { PortalPosition *pos = it->second; @@ -271,7 +271,7 @@ bool PortalForcer::createPortal(shared_ptr<Entity> e) int XZSIZE = level->dimension->getXZSize() * 16; // XZSize is chunks, convert to blocks int XZOFFSET = (XZSIZE / 2) - 4; // Subtract 4 to stay away from the edges // TODO Make the 4 a constant in HellRandomLevelSource - // Move the positions that we want to check away from the edge of the world + // Move the positions that we want to check away from the edge of the world if( (xc - r) < -XZOFFSET ) { app.DebugPrintf("Adjusting portal creation x due to being too close to the edge\n"); @@ -339,7 +339,7 @@ bool PortalForcer::createPortal(shared_ptr<Entity> e) int yt = y + h; int zt = z + (s - 1) * za - b * xa; - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock + // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) { app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); @@ -399,7 +399,7 @@ next_first: continue; int yt = y + h; int zt = z + (s - 1) * za; - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock + // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) { app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); @@ -508,8 +508,8 @@ void PortalForcer::tick(__int64 time) { __int64 cutoff = time - SharedConstants::TICKS_PER_SECOND * 30; - for(AUTO_VAR(it,cachedPortalKeys.begin()); it != cachedPortalKeys.end();) - { + for (auto it = cachedPortalKeys.begin(); it != cachedPortalKeys.end();) + { __int64 key = *it; PortalPosition *pos = cachedPortals[key]; diff --git a/Minecraft.World/PotatoTile.cpp b/Minecraft.World/PotatoTile.cpp index 64a696ec..872622ba 100644 --- a/Minecraft.World/PotatoTile.cpp +++ b/Minecraft.World/PotatoTile.cpp @@ -55,6 +55,6 @@ void PotatoTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < 4; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString<int>(i) ); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i) ); } }
\ No newline at end of file diff --git a/Minecraft.World/PotionBrewing.cpp b/Minecraft.World/PotionBrewing.cpp index 5c454fd4..8e27a601 100644 --- a/Minecraft.World/PotionBrewing.cpp +++ b/Minecraft.World/PotionBrewing.cpp @@ -197,9 +197,8 @@ int PotionBrewing::getColorValue(vector<MobEffectInstance *> *effects) float count = 0; //for (MobEffectInstance effect : effects){ - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; int potionColor = colourTable->getColor( MobEffect::effects[effect->getId()]->getColor() ); for (int potency = 0; potency <= effect->getAmplifier(); potency++) @@ -220,9 +219,8 @@ int PotionBrewing::getColorValue(vector<MobEffectInstance *> *effects) bool PotionBrewing::areAllEffectsAmbient(vector<MobEffectInstance *> *effects) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; if (!effect->isAmbient()) return false; } @@ -233,8 +231,8 @@ int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) { if (!includeDisabledEffects) { - AUTO_VAR(colIt, cachedColors.find(brew)); - if (colIt != cachedColors.end()) + auto colIt = cachedColors.find(brew); + if (colIt != cachedColors.end()) { return colIt->second;//cachedColors.get(brew); } @@ -242,9 +240,8 @@ int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) int color = getColorValue(effects); if(effects != NULL) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; delete effect; } delete effects; @@ -566,8 +563,8 @@ vector<MobEffectInstance *> *PotionBrewing::getEffects(int brew, bool includeDis continue; } //wstring durationString = potionEffectDuration.get(effect->getId()); - AUTO_VAR(effIt, potionEffectDuration.find(effect->getId())); - if ( effIt == potionEffectDuration.end() ) + auto effIt = potionEffectDuration.find(effect->getId()); + if ( effIt == potionEffectDuration.end() ) { continue; } @@ -577,9 +574,9 @@ vector<MobEffectInstance *> *PotionBrewing::getEffects(int brew, bool includeDis if (duration > 0) { int amplifier = 0; - AUTO_VAR(ampIt, potionEffectAmplifier.find(effect->getId())); - if (ampIt != potionEffectAmplifier.end()) - { + auto ampIt = potionEffectAmplifier.find(effect->getId()); + if (ampIt != potionEffectAmplifier.end()) + { wstring amplifierString = ampIt->second; amplifier = parseEffectFormulaValue(amplifierString, 0, (int)amplifierString.length(), brew); if (amplifier < 0) diff --git a/Minecraft.World/PotionItem.cpp b/Minecraft.World/PotionItem.cpp index e302b8f9..fd8937bf 100644 --- a/Minecraft.World/PotionItem.cpp +++ b/Minecraft.World/PotionItem.cpp @@ -36,8 +36,8 @@ vector<MobEffectInstance *> *PotionItem::getMobEffects(shared_ptr<ItemInstance> if (!potion->hasTag() || !potion->getTag()->contains(L"CustomPotionEffects")) { vector<MobEffectInstance *> *effects = NULL; - AUTO_VAR(it, cachedMobEffects.find(potion->getAuxValue())); - if(it != cachedMobEffects.end()) effects = it->second; + auto it = cachedMobEffects.find(potion->getAuxValue()); + if(it != cachedMobEffects.end()) effects = it->second; if (effects == NULL) { effects = PotionBrewing::getEffects(potion->getAuxValue(), false); @@ -65,8 +65,8 @@ vector<MobEffectInstance *> *PotionItem::getMobEffects(shared_ptr<ItemInstance> vector<MobEffectInstance *> *PotionItem::getMobEffects(int auxValue) { vector<MobEffectInstance *> *effects = NULL; - AUTO_VAR(it, cachedMobEffects.find(auxValue)); - if(it != cachedMobEffects.end()) effects = it->second; + auto it = cachedMobEffects.find(auxValue); + if(it != cachedMobEffects.end()) effects = it->second; if (effects == NULL) { effects = PotionBrewing::getEffects(auxValue, false); @@ -84,10 +84,9 @@ shared_ptr<ItemInstance> PotionItem::useTimeDepleted(shared_ptr<ItemInstance> in vector<MobEffectInstance *> *effects = getMobEffects(instance); if (effects != NULL) { - //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - player->addEffect(new MobEffectInstance(*it)); + player->addEffect(new MobEffectInstance(effect)); } } } @@ -188,10 +187,8 @@ bool PotionItem::hasInstantenousEffects(int itemAuxValue) { return false; } - //for (MobEffectInstance effect : mobEffects) { - for(AUTO_VAR(it, mobEffects->begin()); it != mobEffects->end(); ++it) + for(auto& effect : *mobEffects) { - MobEffectInstance *effect = *it; if (MobEffect::effects[effect->getId()]->isInstantenous()) { return true; @@ -224,7 +221,7 @@ wstring PotionItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //String postfixString = effects.get(0).getDescriptionId(); //postfixString += ".postfix"; //return elementName + " " + I18n.get(postfixString).trim(); - + elementName = replaceAll(elementName,L"{*prefix*}",L""); elementName = replaceAll(elementName,L"{*postfix*}",app.GetString(effects->at(0)->getPostfixDescriptionId())); } @@ -232,7 +229,7 @@ wstring PotionItem::getHoverName(shared_ptr<ItemInstance> itemInstance) { //String appearanceName = PotionBrewing.getAppearanceName(itemInstance.getAuxValue()); //return I18n.get(appearanceName).trim() + " " + elementName; - + elementName = replaceAll(elementName,L"{*prefix*}",app.GetString( PotionBrewing::getAppearanceName(itemInstance->getAuxValue()))); elementName = replaceAll(elementName,L"{*postfix*}",L""); } @@ -250,9 +247,8 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p if (effects != NULL && !effects->empty()) { //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; wstring effectString = app.GetString( effect->getDescriptionId() ); MobEffect *mobEffect = MobEffect::effects[effect->getId()]; @@ -260,12 +256,12 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p if (effectModifiers != NULL && effectModifiers->size() > 0) { - for(AUTO_VAR(it, effectModifiers->begin()); it != effectModifiers->end(); ++it) + for(auto& it : *effectModifiers) { // 4J - anonymous modifiers added here are destroyed shortly? - AttributeModifier *original = it->second; + AttributeModifier *original = it.second; AttributeModifier *modifier = new AttributeModifier(mobEffect->getAttributeModifierValue(effect->getAmplifier(), original), original->getOperation()); - modifiers.insert( std::pair<eATTRIBUTE_ID, AttributeModifier*>( it->first->getId(), modifier) ); + modifiers.insert( std::pair<eATTRIBUTE_ID, AttributeModifier*>( it.first->getId(), modifier) ); } } @@ -318,20 +314,20 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p { wstring effectString = app.GetString(IDS_POTION_EMPTY); //I18n.get("potion.empty").trim(); - lines->push_back(HtmlString(effectString, eHTMLColor_7)); //"§7" + lines->push_back(HtmlString(effectString, eHTMLColor_7)); //"�7" } if (!modifiers.empty()) { // Add new line - lines->push_back(HtmlString(L"")); - lines->push_back(HtmlString(app.GetString(IDS_POTION_EFFECTS_WHENDRANK), eHTMLColor_5)); + lines->emplace_back(L""); + lines->emplace_back(app.GetString(IDS_POTION_EFFECTS_WHENDRANK), eHTMLColor_5); // Add modifier descriptions - for (AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for (auto& modifier : modifiers) { // 4J: Moved modifier string building to AttributeModifier - lines->push_back(it->second->getHoverText(it->first)); + lines->push_back(modifier.second->getHoverText(modifier.first)); } } } @@ -392,18 +388,17 @@ vector<pair<int, int> > *PotionItem::getUniquePotionValues() // 4J Stu - Based on implementation of Java List.hashCode() at http://docs.oracle.com/javase/6/docs/api/java/util/List.html#hashCode() // and adding deleting to clear up as we go int effectsHashCode = 1; - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *mei = *it; - effectsHashCode = 31*effectsHashCode + (mei==NULL ? 0 : mei->hashCode()); - delete (*it); + effectsHashCode = 31*effectsHashCode + (effect ? 0 : effect->hashCode()); + delete effect; } bool toAdd = true; - for(AUTO_VAR(it, s_uniquePotionValues.begin()); it != s_uniquePotionValues.end(); ++it) + for(auto& it : s_uniquePotionValues) { // Some potions hash the same (identical effects) but are throwable so account for that - if(it->first == effectsHashCode && !(!isThrowable(it->second) && isThrowable(brew)) ) + if(it.first == effectsHashCode && !(!isThrowable(it.second) && isThrowable(brew)) ) { toAdd = false; break; diff --git a/Minecraft.World/PressurePlateTile.cpp b/Minecraft.World/PressurePlateTile.cpp index 6a30819d..beed308a 100644 --- a/Minecraft.World/PressurePlateTile.cpp +++ b/Minecraft.World/PressurePlateTile.cpp @@ -32,9 +32,8 @@ int PressurePlateTile::getSignalStrength(Level *level, int x, int y, int z) if (entities != NULL && !entities->empty()) { - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - shared_ptr<Entity> e = *it; + for (auto& e : *entities) + { if (!e->isIgnoringTileTriggers()) { if (sensitivity != everything) delete entities; diff --git a/Minecraft.World/RandomScatteredLargeFeature.cpp b/Minecraft.World/RandomScatteredLargeFeature.cpp index 2a2290e3..bd0b70bb 100644 --- a/Minecraft.World/RandomScatteredLargeFeature.cpp +++ b/Minecraft.World/RandomScatteredLargeFeature.cpp @@ -34,11 +34,11 @@ RandomScatteredLargeFeature::RandomScatteredLargeFeature(unordered_map<wstring, { _init(); - for(AUTO_VAR(it, options.begin()); it != options.end(); ++it) + for(auto& option : options) { - if (it->first.compare(OPTION_SPACING) == 0) + if (option.first.compare(OPTION_SPACING) == 0) { - spacing = Mth::getInt(it->second, spacing, minSeparation + 1); + spacing = Mth::getInt(option.second, spacing, minSeparation + 1); } } } @@ -75,9 +75,8 @@ bool RandomScatteredLargeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat if (forcePlacement || (x == xCenterFeatureChunk && z == zCenterFeatureChunk)) { Biome *biome = level->getBiomeSource()->getBiome(x * 16 + 8, z * 16 + 8); - for (AUTO_VAR(it,allowedBiomes.begin()); it != allowedBiomes.end(); ++it) + for ( const auto& a : allowedBiomes) { - Biome *a = *it; if (biome == a) { return true; @@ -129,8 +128,8 @@ bool RandomScatteredLargeFeature::isSwamphut(int cellX, int cellY, int cellZ) return false; } StructurePiece *first = NULL; - AUTO_VAR(it, structureAt->pieces.begin()); - if(it != structureAt->pieces.end() ) first = *it; + auto it = structureAt->pieces.begin(); + if(it != structureAt->pieces.end() ) first = *it; return dynamic_cast<ScatteredFeaturePieces::SwamplandHut *>(first) != NULL; } diff --git a/Minecraft.World/Recipes.cpp b/Minecraft.World/Recipes.cpp index dbb1dbde..8dcbafdf 100644 --- a/Minecraft.World/Recipes.cpp +++ b/Minecraft.World/Recipes.cpp @@ -30,7 +30,7 @@ void Recipes::_init() recipies = new RecipyList(); } -Recipes::Recipes() +Recipes::Recipes() { int iCount=0; _init(); @@ -40,7 +40,7 @@ Recipes::Recipes() pFoodRecipies = new FoodRecipies; pOreRecipies = new OreRecipies; pStructureRecipies = new StructureRecipies; - pToolRecipies = new ToolRecipies; + pToolRecipies = new ToolRecipies; pWeaponRecipies = new WeaponRecipies; // 4J Stu - These just don't work with our crafting menu @@ -64,8 +64,8 @@ Recipes::Recipes() L"#", // L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::BIRCH_TRUNK), - L'S'); - + L'S'); + addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::DARK_TRUNK), // L"sczg", L"#", // @@ -89,7 +89,7 @@ Recipes::Recipes() L'S'); pToolRecipies->addRecipes(this); - pFoodRecipies->addRecipes(this); + pFoodRecipies->addRecipes(this); pStructureRecipies->addRecipes(this); @@ -136,8 +136,8 @@ Recipes::Recipes() L"#W#", // L'#', Item::stick, L'W', Tile::wood, - L'S'); - + L'S'); + addShapedRecipy(new ItemInstance(Tile::fence, 2), // L"sscig", L"###", // @@ -145,7 +145,7 @@ Recipes::Recipes() L'#', Item::stick, L'S'); - + addShapedRecipy(new ItemInstance(Tile::netherFence, 6), // L"ssctg", L"###", // @@ -293,10 +293,10 @@ Recipes::Recipes() L'#', Tile::quartzBlock, L'S'); - pArmorRecipes->addRecipes(this); + pArmorRecipes->addRecipes(this); //iCount=getRecipies()->size(); - pClothDyeRecipes->addRecipes(this); + pClothDyeRecipes->addRecipes(this); addShapedRecipy(new ItemInstance(Tile::snow, 1), // @@ -360,14 +360,14 @@ Recipes::Recipes() L"###", // L'#', Tile::stone, - L'S'); + L'S'); addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::COBBLESTONE_SLAB), // L"sctg", L"###", // L'#', Tile::cobblestone, L'S'); - + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::BRICK_SLAB), // L"sctg", L"###", // @@ -580,7 +580,7 @@ Recipes::Recipes() L"# X", // L" #X", // - L'X', Item::string,// + L'X', Item::string,// L'#', Item::stick, L'T'); @@ -590,8 +590,8 @@ Recipes::Recipes() L"#", // L"Y", // - L'Y', Item::feather,// - L'X', Item::flint,// + L'Y', Item::feather,// + L'X', Item::flint,// L'#', Item::stick, L'T'); @@ -751,7 +751,7 @@ Recipes::Recipes() L"~~ ", // L"~O ", // L" ~", // - + L'~', Item::string, L'O', Item::slimeBall, L'T'); @@ -773,7 +773,7 @@ Recipes::Recipes() L'#', Item::paper, L'X', Item::compass, L'T'); - + addShapedRecipy(new ItemInstance(Tile::button, 1), // L"sctg", L"#", // @@ -922,7 +922,7 @@ Recipes::Recipes() L'#', Item::stick, L'X', Item::leather, L'D'); - pOreRecipies->addRecipes(this); + pOreRecipies->addRecipes(this); addShapedRecipy(new ItemInstance(Item::goldIngot), // L"ssscig", @@ -996,17 +996,17 @@ Recipes::Recipes() // Sort so the largest recipes get checked first! /* 4J-PB - TODO - Collections.sort(recipies, new Comparator<Recipy>() + Collections.sort(recipies, new Comparator<Recipy>() { - public: int compare(Recipy r0, Recipy r1) + public: int compare(Recipy r0, Recipy r1) { // shapeless recipes are put in the back of the list - if (r0 instanceof ShapelessRecipy && r1 instanceof ShapedRecipy) + if (r0 instanceof ShapelessRecipy && r1 instanceof ShapedRecipy) { return 1; } - if (r1 instanceof ShapelessRecipy && r0 instanceof ShapedRecipy) + if (r1 instanceof ShapelessRecipy && r0 instanceof ShapedRecipy) { return -1; } @@ -1059,7 +1059,7 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) wchTypes = va_arg(vl,wchar_t *); - for(int i = 0; wchTypes[i] != L'\0'; ++i ) + for(int i = 0; wchTypes[i] != L'\0'; ++i ) { if(wchTypes[i+1]==L'\0' && wchTypes[i]!=L'g') { @@ -1153,15 +1153,15 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) ids = new ItemInstance *[width * height]; - for (int j = 0; j < width * height; j++) + for (int j = 0; j < width * height; j++) { wchar_t ch = map[j]; myMap::iterator it=mappings->find(ch); - if (it != mappings->end()) + if (it != mappings->end()) { ids[j] =it->second; - } - else + } + else { ids[j] = NULL; } @@ -1175,7 +1175,7 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) return recipe; } -void Recipes::addShapelessRecipy(ItemInstance *result,... ) +void Recipes::addShapelessRecipy(ItemInstance *result,... ) { va_list vl; wchar_t *szTypes; @@ -1194,7 +1194,7 @@ void Recipes::addShapelessRecipy(ItemInstance *result,... ) // t - Tile * szTypes = va_arg(vl,wchar_t *); - for(int i = 0; szTypes[i] != L'\0'; ++i ) + for(int i = 0; szTypes[i] != L'\0'; ++i ) { switch(szTypes[i]) { @@ -1245,10 +1245,10 @@ void Recipes::addShapelessRecipy(ItemInstance *result,... ) break; } } - recipies->push_back(new ShapelessRecipy(result, ingredients, group)); + recipies->push_back(new ShapelessRecipy(result, ingredients, group)); } -shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craftSlots, Level *level, Recipy *recipesClass /*= NULL*/) +shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craftSlots, Level *level, Recipy *recipesClass /*= NULL*/) { int count = 0; shared_ptr<ItemInstance> first = nullptr; @@ -1281,23 +1281,21 @@ shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craft } else { - AUTO_VAR(itEnd, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEnd; it++) + for (auto& r : *recipies) { - Recipy *r = *it; //recipies->at(i); if (r->matches(craftSlots, level)) return r->assemble(craftSlots); } } return nullptr; } -vector <Recipy *> *Recipes::getRecipies() +vector <Recipy *> *Recipes::getRecipies() { return recipies; } // 4J-PB - added to deal with Xb0x 'crafting' -shared_ptr<ItemInstance> Recipes::getItemForRecipe(Recipy *r) +shared_ptr<ItemInstance> Recipes::getItemForRecipe(Recipy *r) { return r->assemble(nullptr); } @@ -1312,11 +1310,8 @@ void Recipes::buildRecipeIngredientsArray(void) m_pRecipeIngredientsRequired= new Recipy::INGREDIENTS_REQUIRED [iRecipeC]; int iCount=0; - AUTO_VAR(itEndRec, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEndRec; it++) + for (auto& recipe : *recipies) { - Recipy *recipe = *it; - //wprintf(L"RECIPE - [%d] is %w\n",iCount,recipe->getResultItem()->getItem()->getName()); recipe->requires(&m_pRecipeIngredientsRequired[iCount++]); } diff --git a/Minecraft.World/RecordingItem.cpp b/Minecraft.World/RecordingItem.cpp index 3b501899..455323c2 100644 --- a/Minecraft.World/RecordingItem.cpp +++ b/Minecraft.World/RecordingItem.cpp @@ -66,8 +66,8 @@ void RecordingItem::registerIcons(IconRegister *iconRegister) RecordingItem *RecordingItem::getByName(const wstring &name) { - AUTO_VAR(it,BY_NAME.find(name)); - if(it != BY_NAME.end()) + auto it = BY_NAME.find(name); + if(it != BY_NAME.end()) { return it->second; } diff --git a/Minecraft.World/RedStoneDustTile.cpp b/Minecraft.World/RedStoneDustTile.cpp index 0107b667..a4577bd3 100644 --- a/Minecraft.World/RedStoneDustTile.cpp +++ b/Minecraft.World/RedStoneDustTile.cpp @@ -84,10 +84,8 @@ void RedStoneDustTile::updatePowerStrength(Level *level, int x, int y, int z) vector<TilePos> updates = vector<TilePos>(toUpdate.begin(), toUpdate.end()); toUpdate.clear(); - AUTO_VAR(itEnd, updates.end()); - for(AUTO_VAR(it, updates.begin()); it != itEnd; it++) + for(auto& tp : updates) { - TilePos tp = *it; level->updateNeighborsAt(tp.x, tp.y, tp.z, id); } } @@ -399,7 +397,7 @@ void RedStoneDustTile::registerIcons(IconRegister *iconRegister) icon = iconCross; } -Icon *RedStoneDustTile::getTexture(const wstring &name) +Icon *RedStoneDustTile::getTexture(const wstring &name) { #ifdef __PSVITA__ // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag diff --git a/Minecraft.World/RegionFileCache.cpp b/Minecraft.World/RegionFileCache.cpp index 23c87118..2bb370a8 100644 --- a/Minecraft.World/RegionFileCache.cpp +++ b/Minecraft.World/RegionFileCache.cpp @@ -25,22 +25,22 @@ RegionFile *RegionFileCache::_getRegionFile(ConsoleSaveFile *saveFile, const wst //File regionDir(basePath, L"region"); - //File file(regionDir, wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); + //File file(regionDir, wstring(L"r.") + std::to_wstring(chunkX>>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); MemSect(31); File file; if(useSplitSaves(saveFile->getSavePlatform())) { - file = File( prefix + wstring(L"r.") + _toString(chunkX>>4) + L"." + _toString(chunkZ>>4) + L".mcr" ); + file = File( prefix + wstring(L"r.") + std::to_wstring(chunkX>>4) + L"." + std::to_wstring(chunkZ>>4) + L".mcr" ); } else { - file = File( prefix + wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); + file = File( prefix + wstring(L"r.") + std::to_wstring(chunkX>>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); } MemSect(0); RegionFile *ref = NULL; - AUTO_VAR(it, cache.find(file)); - if( it != cache.end() ) + auto it = cache.find(file); + if( it != cache.end() ) ref = it->second; // 4J Jev, put back in. @@ -69,20 +69,14 @@ RegionFile *RegionFileCache::_getRegionFile(ConsoleSaveFile *saveFile, const wst void RegionFileCache::_clear() // 4J - TODO was synchronized { - AUTO_VAR(itEnd, cache.end()); - for( AUTO_VAR(it, cache.begin()); it != itEnd; it++ ) + for(auto& it : cache) { - // 4J - removed try/catch -// try { - RegionFile *regionFile = it->second; + RegionFile *regionFile = it.second; if (regionFile != NULL) { regionFile->close(); } delete regionFile; -// } catch (IOException e) { -// e.printStackTrace(); -// } } cache.clear(); } diff --git a/Minecraft.World/RepairMenu.cpp b/Minecraft.World/RepairMenu.cpp index d246b73f..a4c48edf 100644 --- a/Minecraft.World/RepairMenu.cpp +++ b/Minecraft.World/RepairMenu.cpp @@ -134,22 +134,22 @@ void RepairMenu::createResult() unordered_map<int, int> *additionalEnchantments = EnchantmentHelper::getEnchantments(addition); - for(AUTO_VAR(it, additionalEnchantments->begin()); it != additionalEnchantments->end(); ++it) + for(auto& it : *additionalEnchantments) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - AUTO_VAR(localIt, enchantments->find(id)); - int current = localIt != enchantments->end() ? localIt->second : 0; - int level = it->second; + auto localIt = enchantments->find(id); + int current = localIt != enchantments->end() ? localIt->second : 0; + int level = it.second; level = (current == level) ? level += 1 : max(level, current); int extra = level - current; bool compatible = enchantment->canEnchant(input); if (player->abilities.instabuild) compatible = true; - for(AUTO_VAR(it2, enchantments->begin()); it2 != enchantments->end(); ++it2) + for(auto& it2 : *enchantments) { - int other = it2->first; + int other = it2.first; if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) { compatible = false; @@ -219,11 +219,11 @@ void RepairMenu::createResult() } int count = 0; - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for(auto& it : *enchantments) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - int level = it->second; + int level = it.second; int fee = 0; count++; diff --git a/Minecraft.World/SavedDataStorage.cpp b/Minecraft.World/SavedDataStorage.cpp index 3dbd6400..422b66dc 100644 --- a/Minecraft.World/SavedDataStorage.cpp +++ b/Minecraft.World/SavedDataStorage.cpp @@ -8,7 +8,7 @@ #include "ConsoleSaveFileIO.h" -SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) +SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) { /* cache = new unordered_map<wstring, shared_ptr<SavedData> >; @@ -22,15 +22,15 @@ SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) shared_ptr<SavedData> SavedDataStorage::get(const type_info& clazz, const wstring& id) { - AUTO_VAR(it, cache.find( id )); - if (it != cache.end()) return (*it).second; + auto it = cache.find(id); + if (it != cache.end()) return (*it).second; shared_ptr<SavedData> data = nullptr; if (levelStorage != NULL) { //File file = levelStorage->getDataFile(id); ConsoleSavePath file = levelStorage->getDataFile(id); - if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) + if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) { // mob = dynamic_pointer_cast<Mob>(Mob::_class->newInstance( level )); //data = clazz.getConstructor(String.class).newInstance(id); @@ -69,18 +69,18 @@ shared_ptr<SavedData> SavedDataStorage::get(const type_info& clazz, const wstrin return data; } -void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) +void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) { if (data == NULL) { // TODO 4J Stu - throw new RuntimeException("Can't set null data"); assert( false ); } - AUTO_VAR(it, cache.find(id)); - if ( it != cache.end() ) + auto it = cache.find(id); + if ( it != cache.end() ) { - AUTO_VAR(it2, find( savedDatas.begin(), savedDatas.end(), it->second )); - if( it2 != savedDatas.end() ) + auto it2 = find(savedDatas.begin(), savedDatas.end(), it->second); + if( it2 != savedDatas.end() ) { savedDatas.erase( it2 ); } @@ -92,10 +92,8 @@ void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) void SavedDataStorage::save() { - AUTO_VAR(itEnd, savedDatas.end()); - for (AUTO_VAR(it, savedDatas.begin()); it != itEnd; it++) + for (auto& data : savedDatas) { - shared_ptr<SavedData> data = *it; //savedDatas->at(i); if (data->isDirty()) { save(data); @@ -139,16 +137,12 @@ void SavedDataStorage::loadAuxValues() CompoundTag *tags = NbtIo::read(&dis); dis.close(); - Tag *tag; vector<Tag *> *allTags = tags->getAllTags(); - AUTO_VAR(itEnd, allTags->end()); - for (AUTO_VAR(it, allTags->begin()); it != itEnd; it++) + for ( Tag *tag : *allTags ) { - tag = *it; //tags->getAllTags()->at(i); - - if (dynamic_cast<ShortTag *>(tag) != NULL) + if (dynamic_cast<ShortTag *>(tag)) { - ShortTag *sTag = (ShortTag *) tag; + ShortTag *sTag = static_cast<ShortTag *>(tag); wstring id = sTag->getName(); short val = sTag->data; usedAuxIds.insert( uaiMapType::value_type( id, val ) ); @@ -160,7 +154,7 @@ void SavedDataStorage::loadAuxValues() int SavedDataStorage::getFreeAuxValueFor(const wstring& id) { - AUTO_VAR(it, usedAuxIds.find( id )); + auto it = usedAuxIds.find(id); short val = 0; if ( it != usedAuxIds.end() ) { @@ -177,11 +171,10 @@ int SavedDataStorage::getFreeAuxValueFor(const wstring& id) CompoundTag *tag = new CompoundTag(); // TODO 4J Stu - This was iterating over the keySet in Java, so potentially we are looking at more items? - AUTO_VAR(itEndAuxIds, usedAuxIds.end()); - for(uaiMapType::iterator it2 = usedAuxIds.begin(); it2 != itEndAuxIds; it2++) + for(auto& it : usedAuxIds) { - short value = it2->second; - tag->putShort( (wchar_t *) it2->first.c_str(), value); + short value = it.second; + tag->putShort(it.first.c_str(), value); } ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); diff --git a/Minecraft.World/Sensing.cpp b/Minecraft.World/Sensing.cpp index d451f483..ae7d90c6 100644 --- a/Minecraft.World/Sensing.cpp +++ b/Minecraft.World/Sensing.cpp @@ -17,13 +17,13 @@ bool Sensing::canSee(shared_ptr<Entity> target) { //if ( find(seen.begin(), seen.end(), target) != seen.end() ) return true; //if ( find(unseen.begin(), unseen.end(), target) != unseen.end()) return false; - for(AUTO_VAR(it, seen.begin()); it != seen.end(); ++it) + for(auto& it : seen) { - if(target == (*it).lock()) return true; + if(target == it.lock()) return true; } - for(AUTO_VAR(it, unseen.begin()); it != unseen.end(); ++it) + for(auto & it : unseen) { - if(target == (*it).lock()) return false; + if(target == it.lock()) return false; } //util.Timer.push("canSee"); diff --git a/Minecraft.World/ServersideAttributeMap.cpp b/Minecraft.World/ServersideAttributeMap.cpp index ec75aa22..901854cc 100644 --- a/Minecraft.World/ServersideAttributeMap.cpp +++ b/Minecraft.World/ServersideAttributeMap.cpp @@ -14,12 +14,12 @@ AttributeInstance *ServersideAttributeMap::getInstance(Attribute *attribute) AttributeInstance *ServersideAttributeMap::getInstance(eATTRIBUTE_ID id) { AttributeInstance *result = BaseAttributeMap::getInstance(id); - + // 4J: Removed legacy name // If we didn't find it, search by legacy name /*if (result == NULL) { - AUTO_VAR(it, attributesByLegacy.find(name)); + auto it = attributesByLegacy.find(name); if(it != attributesByLegacy.end()) { result = it->second; @@ -31,15 +31,15 @@ AttributeInstance *ServersideAttributeMap::getInstance(eATTRIBUTE_ID id) AttributeInstance *ServersideAttributeMap::registerAttribute(Attribute *attribute) { - AUTO_VAR(it,attributesById.find(attribute->getId())); - if (it != attributesById.end()) + auto it = attributesById.find(attribute->getId()); + if (it != attributesById.end()) { return it->second; } AttributeInstance *instance = new ModifiableAttributeInstance(this, attribute); attributesById.insert(std::pair<eATTRIBUTE_ID, AttributeInstance *>(attribute->getId(), instance)); - + // 4J: Removed legacy name // If this is a ranged attribute also add to legacy name map /*RangedAttribute *rangedAttribute = dynamic_cast<RangedAttribute*>(attribute); diff --git a/Minecraft.World/SetPlayerTeamPacket.cpp b/Minecraft.World/SetPlayerTeamPacket.cpp index 8c605784..fe36bfff 100644 --- a/Minecraft.World/SetPlayerTeamPacket.cpp +++ b/Minecraft.World/SetPlayerTeamPacket.cpp @@ -96,9 +96,9 @@ void SetPlayerTeamPacket::write(DataOutputStream *dos) { dos->writeShort(players.size()); - for (AUTO_VAR(it,players.begin()); it != players.end(); ++it) + for (auto& player : players) { - writeUtf(*it, dos); + writeUtf(player, dos); } } } diff --git a/Minecraft.World/ShapelessRecipy.cpp b/Minecraft.World/ShapelessRecipy.cpp index 67ed0381..44bf6a54 100644 --- a/Minecraft.World/ShapelessRecipy.cpp +++ b/Minecraft.World/ShapelessRecipy.cpp @@ -39,18 +39,17 @@ bool ShapelessRecipy::matches(shared_ptr<CraftingContainer> craftSlots, Level *l { shared_ptr<ItemInstance> item = craftSlots->getItem(x, y); - if (item != NULL) + if (item) { bool found = false; - AUTO_VAR(citEnd, ingredients->end()); - for (AUTO_VAR(cit, ingredients->begin()); cit != citEnd; ++cit) + auto citEnd = ingredients->end(); + for ( ItemInstance *ingredient : *ingredients ) { - ItemInstance *ingredient = *cit; if (item->id == ingredient->id && (ingredient->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == ingredient->getAuxValue())) { found = true; - AUTO_VAR( it, find(tempList.begin(), tempList.end(), ingredient ) ); + auto it = find(tempList.begin(), tempList.end(), ingredient); if(it != tempList.end() ) tempList.erase(it); break; } @@ -86,9 +85,8 @@ bool ShapelessRecipy::requires(int iRecipe) //printf("ShapelessRecipy %d\n",iRecipe); - AUTO_VAR(citEnd, ingredients->end()); int iCount=0; - for (vector<ItemInstance *>::iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( auto ingredient = ingredients->begin(); ingredient != ingredients->end(); ingredient++) { //printf("\tIngredient %d is %d\n",iCount++,(*ingredient)->id); //if (item->id == (*ingredient)->id && ((*ingredient)->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == (*ingredient)->getAuxValue())) @@ -119,15 +117,11 @@ void ShapelessRecipy::requires(INGREDIENTS_REQUIRED *pIngReq) memset(TempIngReq.iIngAuxValA,Recipes::ANY_AUX_VALUE,sizeof(int)*9); ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); - AUTO_VAR(citEnd, ingredients->end()); - - for (vector<ItemInstance *>::const_iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( ItemInstance *expected : *ingredients ) { - ItemInstance *expected = *ingredient; - - if (expected!=NULL) + if ( expected ) { - int iAuxVal = (*ingredient)->getAuxValue(); + int iAuxVal = expected->getAuxValue(); TempIngReq.uiGridA[iCount++]=expected->id | iAuxVal<<24; // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them in a 2x2 crafting screen if(iCount==2) iCount=3; diff --git a/Minecraft.World/SharedMonsterAttributes.cpp b/Minecraft.World/SharedMonsterAttributes.cpp index f434f1e7..3ff84197 100644 --- a/Minecraft.World/SharedMonsterAttributes.cpp +++ b/Minecraft.World/SharedMonsterAttributes.cpp @@ -15,9 +15,8 @@ ListTag<CompoundTag> *SharedMonsterAttributes::saveAttributes(BaseAttributeMap * vector<AttributeInstance *> atts; attributes->getAttributes(atts); - for (AUTO_VAR(it, atts.begin()); it != atts.end(); ++it) + for (auto& attribute : atts) { - AttributeInstance *attribute = *it; list->add(saveAttribute(attribute)); } @@ -39,9 +38,8 @@ CompoundTag *SharedMonsterAttributes::saveAttribute(AttributeInstance *instance) { ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); - for (AUTO_VAR(it,modifiers.begin()); it != modifiers.end(); ++it) + for (auto& modifier : modifiers) { - AttributeModifier* modifier = *it; if (modifier->isSerializable()) { list->add(saveAttributeModifier(modifier)); diff --git a/Minecraft.World/SpawnEggItem.cpp b/Minecraft.World/SpawnEggItem.cpp index ab082bfb..9c059126 100644 --- a/Minecraft.World/SpawnEggItem.cpp +++ b/Minecraft.World/SpawnEggItem.cpp @@ -30,7 +30,7 @@ wstring SpawnEggItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //elementName += " " + I18n.get("entity." + encodeId + ".name"); } else - { + { elementName = replaceAll(elementName,L"{*CREATURE*}",L""); } @@ -39,8 +39,8 @@ wstring SpawnEggItem::getHoverName(shared_ptr<ItemInstance> itemInstance) int SpawnEggItem::getColor(shared_ptr<ItemInstance> item, int spriteLayer) { - AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); - if (it != EntityIO::idsSpawnableInCreative.end()) + auto it = EntityIO ::idsSpawnableInCreative.find(item->getAuxValue()); + if (it != EntityIO::idsSpawnableInCreative.end()) { EntityIO::SpawnableMobInfo *spawnableMobInfo = it->second; if (spriteLayer == 0) { @@ -228,7 +228,7 @@ bool SpawnEggItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr<Playe } if (result != NULL) - { + { // 4J-JEV: SetCustomName is a method for Mob not LivingEntity; so change instanceof to check for Mobs. if ( result->instanceof(eTYPE_MOB) && itemInstance->hasCustomHoverName() ) { @@ -237,7 +237,7 @@ bool SpawnEggItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr<Playe if ( !player->abilities.instabuild ) { itemInstance->count--; - } + } } else { diff --git a/Minecraft.World/Stat.cpp b/Minecraft.World/Stat.cpp index 868ff3bd..97a655c7 100644 --- a/Minecraft.World/Stat.cpp +++ b/Minecraft.World/Stat.cpp @@ -76,21 +76,21 @@ wstring Stat::TimeFormatter::format(int value) if (years > 0.5) { return decimalFormat->format(years) + L" y"; - } - else if (days > 0.5) + } + else if (days > 0.5) { return decimalFormat->format(days) + L" d"; } else if (hours > 0.5) { return decimalFormat->format(hours) + L" h"; - } - else if (minutes > 0.5) + } + else if (minutes > 0.5) { return decimalFormat->format(minutes) + L" m"; } - return _toString<double>(seconds) + L" s"; + return std::to_wstring(seconds) + L" s"; } wstring Stat::DefaultFormat::format(int value) @@ -103,13 +103,13 @@ wstring Stat::DistanceFormatter::format(int cm) double meters = cm / 100.0; double kilometers = meters / 1000.0; - if (kilometers > 0.5) + if (kilometers > 0.5) { return decimalFormat->format(kilometers) + L" km"; - } else if (meters > 0.5) + } else if (meters > 0.5) { return decimalFormat->format(meters) + L" m"; } - return _toString<int>(cm) + L" cm"; + return std::to_wstring(cm) + L" cm"; } diff --git a/Minecraft.World/Stats.cpp b/Minecraft.World/Stats.cpp index 89da587b..c8a615ff 100644 --- a/Minecraft.World/Stats.cpp +++ b/Minecraft.World/Stats.cpp @@ -216,7 +216,7 @@ void Stats::buildBlockStats() bool Stats::itemStatsLoaded = false; -void Stats::buildItemStats() +void Stats::buildItemStats() { itemStatsLoaded = true; buildCraftableStats(); @@ -239,7 +239,7 @@ void Stats::buildCraftableStats() craftableStatsLoaded = true; //Collected stats - + itemsCollected = StatArray(32000); ItemStat* newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 0, L"collectItem.egg", Item::egg->id); @@ -248,12 +248,12 @@ void Stats::buildCraftableStats() newStat->postConstruct(); // 4J Stu - The following stats were added as it was too easy to cheat the leaderboards by dropping and picking up these items - // They are now changed to mining the block which involves a tiny bit more effort + // They are now changed to mining the block which involves a tiny bit more effort newStat = new ItemStat(BLOCKS_MINED_OFFSET + 18, L"mineBlock.wheat", Tile::wheat_Id); blocksMinedStats->push_back(newStat); blocksMined[Tile::wheat_Id] = newStat; newStat->postConstruct(); - + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 19, L"mineBlock.mushroom1", Tile::mushroom_brown_Id); blocksMinedStats->push_back(newStat); blocksMined[Tile::mushroom_brown_Id] = newStat; @@ -522,7 +522,7 @@ void Stats::buildAdditionalStats() rainbowCollection = StatArray(16); for (unsigned int i = 0; i < 16; i++) { - generalStat = new GeneralStat(offset++, L"rainbowCollection." + _toString<unsigned int>(i)); + generalStat = new GeneralStat(offset++, L"rainbowCollection." + std::to_wstring(i)); generalStats->push_back(generalStat); rainbowCollection[i] = generalStat; generalStat->postConstruct(); @@ -531,7 +531,7 @@ void Stats::buildAdditionalStats() biomesVisisted = StatArray(23); for (unsigned int i = 0; i < 23; i++) { - generalStat = new GeneralStat(offset++, L"biomesVisited." + _toString<unsigned int>(i)); + generalStat = new GeneralStat(offset++, L"biomesVisited." + std::to_wstring(i)); generalStats->push_back(generalStat); biomesVisisted[i] = generalStat; generalStat->postConstruct(); @@ -548,10 +548,10 @@ void Stats::buildAdditionalStats() itemStat->postConstruct(); } #endif - + } -Stat *Stats::get(int key) +Stat *Stats::get(int key) { return statsById->at(key); } diff --git a/Minecraft.World/StringHelpers.h b/Minecraft.World/StringHelpers.h index 1b364118..dee676ba 100644 --- a/Minecraft.World/StringHelpers.h +++ b/Minecraft.World/StringHelpers.h @@ -6,19 +6,7 @@ wstring trimString(const wstring& a); wstring replaceAll(const wstring& in, const wstring& replace, const wstring& with); bool equalsIgnoreCase(const wstring& a, const wstring& b); -// 4J-PB - for use in the ::toString -template <class T> std::wstring _toString(T t) -{ - std::wostringstream oss; - oss << std::dec << t; - return oss.str(); -} -template <class T> std::wstring _toHexString(T t) -{ - std::wostringstream oss; - oss << std::hex << t; - return oss.str(); -} + template <class T> T _fromString(const std::wstring& s) { std::wistringstream stream (s); diff --git a/Minecraft.World/StrongholdFeature.cpp b/Minecraft.World/StrongholdFeature.cpp index 3aed0195..fa85dc42 100644 --- a/Minecraft.World/StrongholdFeature.cpp +++ b/Minecraft.World/StrongholdFeature.cpp @@ -53,21 +53,21 @@ StrongholdFeature::StrongholdFeature(unordered_map<wstring, wstring> options) { _init(); - for (AUTO_VAR(it, options.begin()); it != options.end(); ++it) + for (auto& option : options) { - if (it->first.compare(OPTION_DISTANCE) == 0) + if (option.first.compare(OPTION_DISTANCE) == 0) { - distance = Mth::getDouble(it->second, distance, 1); + distance = Mth::getDouble(option.second, distance, 1); } - else if (it->first.compare(OPTION_COUNT) == 0) + else if (option.first.compare(OPTION_COUNT) == 0) { // 4J-JEV: Removed, we only have the one stronghold. //strongholdPos = new ChunkPos[ Mth::getInt(it->second, strongholdPos_length, 1) ]; assert(false); } - else if (it->first.compare(OPTION_SPREAD) == 0) + else if (option.first.compare(OPTION_SPREAD) == 0) { - spread = Mth::getInt(it->second, spread, 1); + spread = Mth::getInt(option.second, spread, 1); } } } @@ -174,7 +174,7 @@ bool StrongholdFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) #ifdef _LARGE_WORLDS angle = random.nextDouble() * PI * 2.0 * circle / (double) spread; #endif - } + } while(!hasFoundValidPos && findAttempts < MAX_STRONGHOLD_ATTEMPTS); if(!hasFoundValidPos) @@ -255,8 +255,8 @@ StrongholdFeature::StrongholdStart::StrongholdStart(Level *level, Random *random while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingChildren->begin() + pos; + StructurePiece *structurePiece = *it; pendingChildren->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } diff --git a/Minecraft.World/StrongholdPieces.cpp b/Minecraft.World/StrongholdPieces.cpp index d736fb0e..383be42c 100644 --- a/Minecraft.World/StrongholdPieces.cpp +++ b/Minecraft.World/StrongholdPieces.cpp @@ -52,9 +52,9 @@ bool StrongholdPieces::PieceWeight::isValid() void StrongholdPieces::resetPieces() { - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) + for(auto& it : currentPieces) { - delete (*it); + delete it; } currentPieces.clear(); @@ -77,9 +77,8 @@ bool StrongholdPieces::updatePieceWeight() { bool hasAnyPieces = false; totalWeight = 0; - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) + for(auto& piece : currentPieces) { - PieceWeight *piece = *it; if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -166,9 +165,8 @@ StrongholdPieces::StrongholdPiece *StrongholdPieces::generatePieceFromSmallDoor( numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : currentPieces ) + { weightSelection -= piece->weight; if (weightSelection < 0) { @@ -215,10 +213,8 @@ StructurePiece *StrongholdPieces::generateAndAddPiece(StartPiece *startPiece, li // Force attempt at spawning a portal room if(startPiece->m_level->getOriginalSaveVersion() >= SAVE_FILE_VERSION_MOVED_STRONGHOLD && !startPiece->m_level->getLevelData()->getHasStrongholdEndPortal()) { - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; - + for ( PieceWeight *piece : currentPieces ) + { if(piece->pieceClass != EPieceClass_PortalRoom) continue; #ifndef _CONTENT_PACKAGE @@ -254,7 +250,7 @@ StructurePiece *StrongholdPieces::generateAndAddPiece(StartPiece *startPiece, li return newPiece; } -StrongholdPieces::StrongholdPiece::StrongholdPiece() +StrongholdPieces::StrongholdPiece::StrongholdPiece() { entryDoor = OPENING; // for reflection @@ -267,7 +263,7 @@ StrongholdPieces::StrongholdPiece::StrongholdPiece(int genDepth) : StructurePiec void StrongholdPieces::StrongholdPiece::addAdditonalSaveData(CompoundTag *tag) { - tag->putString(L"EntryDoor", _toString<int>(entryDoor)); + tag->putString(L"EntryDoor", std::to_wstring(entryDoor)); } void StrongholdPieces::StrongholdPiece::readAdditonalSaveData(CompoundTag *tag) @@ -565,7 +561,7 @@ StrongholdPieces::StairsDown *StrongholdPieces::StairsDown::createPiece(list<Str { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -676,7 +672,7 @@ StrongholdPieces::Straight *StrongholdPieces::Straight::createPiece(list<Structu { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -719,7 +715,7 @@ bool StrongholdPieces::Straight::postProcess(Level *level, Random *random, Bound return true; } -WeighedTreasure *StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::enderPearl_Id, 0, 1, 1, 10), new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), @@ -776,7 +772,7 @@ StrongholdPieces::ChestCorridor *StrongholdPieces::ChestCorridor::createPiece(li { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -848,7 +844,7 @@ StrongholdPieces::StraightStairsDown *StrongholdPieces::StraightStairsDown::crea { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -920,7 +916,7 @@ StrongholdPieces::LeftTurn *StrongholdPieces::LeftTurn::createPiece(list<Structu { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1010,7 +1006,7 @@ StrongholdPieces::RoomCrossing::RoomCrossing(int genDepth, Random *random, Bound { entryDoor = randomSmallDoor(random); orientation = direction; - boundingBox = stairsBox; + boundingBox = stairsBox; } void StrongholdPieces::RoomCrossing::addAdditonalSaveData(CompoundTag *tag) @@ -1036,7 +1032,7 @@ StrongholdPieces::RoomCrossing *StrongholdPieces::RoomCrossing::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1048,7 +1044,7 @@ StrongholdPieces::RoomCrossing *StrongholdPieces::RoomCrossing::createPiece(list return new RoomCrossing(genDepth, random, box, direction); } -WeighedTreasure *StrongholdPieces::RoomCrossing::smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::RoomCrossing::smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), @@ -1188,7 +1184,7 @@ StrongholdPieces::PrisonHall *StrongholdPieces::PrisonHall::createPiece(list<Str { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1267,7 +1263,7 @@ StrongholdPieces::Library *StrongholdPieces::Library::createPiece(list<Structure // attempt to make a tall library first BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, tallHeight, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1286,7 +1282,7 @@ StrongholdPieces::Library *StrongholdPieces::Library::createPiece(list<Structure return new Library(genDepth, random, box, direction); } -WeighedTreasure *StrongholdPieces::Library::libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::Library::libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::book_Id, 0, 1, 3, 20), new WeighedTreasure(Item::paper_Id, 0, 2, 7, 20), @@ -1467,7 +1463,7 @@ void StrongholdPieces::FiveCrossing::addChildren(StructurePiece *startPiece, lis { zOffA = depth - 3 - zOffA; zOffB = depth - 3 - zOffB; - } + } generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 5, 1); if (leftLow) generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, zOffA, 1); @@ -1480,7 +1476,7 @@ StrongholdPieces::FiveCrossing *StrongholdPieces::FiveCrossing::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1576,7 +1572,7 @@ StrongholdPieces::PortalRoom *StrongholdPieces::PortalRoom::createPiece(list<Str BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); // 4J Added so that we can check that Portals stay within the bounds of the world (which they ALWAYS should anyway) - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1684,7 +1680,7 @@ bool StrongholdPieces::PortalRoom::postProcess(Level *level, Random *random, Bou if (chunkBB->isInside(x, y, z)) { // 4J Stu - The mob spawner location is close enough for the map icon display, and this ensures that we only need to set the position once - app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal,x,z); + app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal,x,z); level->getLevelData()->setXStrongholdEndPortal(x); level->getLevelData()->setZStrongholdEndPortal(z); level->getLevelData()->setHasStrongholdEndPortal(); diff --git a/Minecraft.World/StructureFeature.cpp b/Minecraft.World/StructureFeature.cpp index 41ee5c81..dfb214a5 100644 --- a/Minecraft.World/StructureFeature.cpp +++ b/Minecraft.World/StructureFeature.cpp @@ -16,9 +16,9 @@ StructureFeature::StructureFeature() StructureFeature::~StructureFeature() { - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto& it : cachedStructures) { - delete it->second; + delete it.second; } } @@ -58,9 +58,9 @@ bool StructureFeature::postProcess(Level *level, Random *random, int chunkX, int int cz = (chunkZ << 4); // + 8; bool intersection = false; - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto& it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { @@ -84,15 +84,15 @@ bool StructureFeature::isIntersection(int cellX, int cellZ) { restoreSavedData(level); - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto & it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { if (structureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) { - AUTO_VAR(it2, structureStart->getPieces()->begin()); - while( it2 != structureStart->getPieces()->end() ) + auto it2 = structureStart->getPieces()->begin(); + while( it2 != structureStart->getPieces()->end() ) { StructurePiece *next = *it2++; if (next->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) @@ -106,7 +106,7 @@ bool StructureFeature::isIntersection(int cellX, int cellZ) return false; } -bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) +bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) { restoreSavedData(level); return getStructureAt(cellX, cellY, cellZ) != NULL; @@ -114,14 +114,13 @@ bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) StructureStart *StructureFeature::getStructureAt(int cellX, int cellY, int cellZ) { - //for (StructureStart structureStart : cachedStructures.values()) - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *pStructureStart = it->second; + StructureStart *pStructureStart = it.second; - if (pStructureStart->isValid()) + if (pStructureStart->isValid()) { - if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) + if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) { /* Iterator<StructurePiece> it = structureStart.getPieces().iterator(); @@ -133,9 +132,8 @@ StructureStart *StructureFeature::getStructureAt(int cellX, int cellY, int cellZ */ list<StructurePiece *> *pieces=pStructureStart->getPieces(); - for ( AUTO_VAR(it2, pieces->begin()); it2 != pieces->end(); it2++ ) + for (auto& piece : *pieces) { - StructurePiece* piece = *it2; if ( piece->getBoundingBox()->isInside(cellX, cellY, cellZ) ) { return pStructureStart; @@ -151,9 +149,9 @@ bool StructureFeature::isInsideBoundingFeature(int cellX, int cellY, int cellZ) { restoreSavedData(level); - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { return (structureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)); @@ -162,7 +160,7 @@ bool StructureFeature::isInsideBoundingFeature(int cellX, int cellY, int cellZ) return false; } -TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ) +TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ) { // this is a hack that will "force" the feature to generate positions // even if the player hasn't generated new chunks yet @@ -182,11 +180,11 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i double minDistance = DBL_MAX; TilePos *selected = NULL; - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *pStructureStart = it->second; + StructureStart *pStructureStart = it.second; - if (pStructureStart->isValid()) + if (pStructureStart->isValid()) { //StructurePiece *pStructurePiece = pStructureStart->getPieces().get(0); @@ -198,37 +196,37 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i int dz = locatorPosition->z - cellZ; double dist = dx * dx + dy * dy + dz * dz; - if (dist < minDistance) + if (dist < minDistance) { minDistance = dist; selected = locatorPosition; } } } - if (selected != NULL) + if (selected != NULL) { return selected; - } - else + } + else { vector<TilePos> *guesstimatedFeaturePositions = getGuesstimatedFeaturePositions(); - if (guesstimatedFeaturePositions != NULL) + if (guesstimatedFeaturePositions != NULL) { TilePos *pSelectedPos = new TilePos(0,0,0); - for(AUTO_VAR(it, guesstimatedFeaturePositions->begin()); it != guesstimatedFeaturePositions->end(); ++it) + for(const auto& it : *guesstimatedFeaturePositions) { - int dx = (*it).x - cellX; - int dy = (*it).y - cellY; - int dz = (*it).z - cellZ; + int dx = it.x - cellX; + int dy = it.y - cellY; + int dz = it.z - cellZ; double dist = dx * dx + dy * dy + dz * dz; - if (dist < minDistance) + if (dist < minDistance) { minDistance = dist; - pSelectedPos->x = (*it).x; - pSelectedPos->y = (*it).y; - pSelectedPos->z = (*it).z; + pSelectedPos->x = it.x; + pSelectedPos->y = it.y; + pSelectedPos->z = it.z; } } delete guesstimatedFeaturePositions; @@ -238,7 +236,7 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i return NULL; } -vector<TilePos> *StructureFeature::getGuesstimatedFeaturePositions() +vector<TilePos> *StructureFeature::getGuesstimatedFeaturePositions() { return NULL; } @@ -260,10 +258,9 @@ void StructureFeature::restoreSavedData(Level *level) CompoundTag *fullTag = savedData->getFullTag(); vector<Tag *> *allTags = fullTag->getAllTags(); - for (AUTO_VAR(it,allTags->begin()); it != allTags->end(); ++it) + for ( Tag *featureTag : *allTags ) { - Tag *featureTag = *it; - if (featureTag->getId() == Tag::TAG_Compound) + if ( featureTag && featureTag->getId() == Tag::TAG_Compound) { CompoundTag *ct = (CompoundTag *) featureTag; diff --git a/Minecraft.World/StructureFeatureIO.cpp b/Minecraft.World/StructureFeatureIO.cpp index d910cf3d..3e73b028 100644 --- a/Minecraft.World/StructureFeatureIO.cpp +++ b/Minecraft.World/StructureFeatureIO.cpp @@ -37,8 +37,8 @@ void StructureFeatureIO::staticCtor() wstring StructureFeatureIO::getEncodeId(StructureStart *start) { - AUTO_VAR(it, startClassIdMap.find( start->GetType() ) ); - if(it != startClassIdMap.end()) + auto it = startClassIdMap.find(start->GetType()); + if(it != startClassIdMap.end()) { return it->second; } @@ -50,8 +50,8 @@ wstring StructureFeatureIO::getEncodeId(StructureStart *start) wstring StructureFeatureIO::getEncodeId(StructurePiece *piece) { - AUTO_VAR(it, pieceClassIdMap.find( piece->GetType() ) ); - if(it != pieceClassIdMap.end()) + auto it = pieceClassIdMap.find(piece->GetType()); + if(it != pieceClassIdMap.end()) { return it->second; } @@ -65,8 +65,8 @@ StructureStart *StructureFeatureIO::loadStaticStart(CompoundTag *tag, Level *lev { StructureStart *start = NULL; - AUTO_VAR(it, startIdClassMap.find( tag->getString(L"id") ) ); - if(it != startIdClassMap.end()) + auto it = startIdClassMap.find(tag->getString(L"id")); + if(it != startIdClassMap.end()) { start = (it->second)(); } @@ -86,8 +86,8 @@ StructurePiece *StructureFeatureIO::loadStaticPiece(CompoundTag *tag, Level *lev { StructurePiece *piece = NULL; - AUTO_VAR(it, pieceIdClassMap.find( tag->getString(L"id") ) ); - if(it != pieceIdClassMap.end()) + auto it = pieceIdClassMap.find(tag->getString(L"id")); + if(it != pieceIdClassMap.end()) { piece = (it->second)(); } diff --git a/Minecraft.World/StructureFeatureSavedData.cpp b/Minecraft.World/StructureFeatureSavedData.cpp index 6c2aa412..6d580d02 100644 --- a/Minecraft.World/StructureFeatureSavedData.cpp +++ b/Minecraft.World/StructureFeatureSavedData.cpp @@ -38,7 +38,7 @@ void StructureFeatureSavedData::putFeatureTag(CompoundTag *tag, int chunkX, int wstring StructureFeatureSavedData::createFeatureTagId(int chunkX, int chunkZ) { - return L"[" + _toString<int>(chunkX) + L"," + _toString<int>(chunkZ) + L"]"; + return L"[" + std::to_wstring(chunkX) + L"," + std::to_wstring(chunkZ) + L"]"; } CompoundTag *StructureFeatureSavedData::getFullTag() diff --git a/Minecraft.World/StructurePiece.cpp b/Minecraft.World/StructurePiece.cpp index cd483a6e..85a19ab4 100644 --- a/Minecraft.World/StructurePiece.cpp +++ b/Minecraft.World/StructurePiece.cpp @@ -14,7 +14,7 @@ #include "DoorItem.h" /** -* +* * A structure piece is a construction or room, located somewhere in the world * with a given orientatino (out of Direction.java). Structure pieces have a * bounding box that says where the piece is located and its bounds, and the @@ -113,10 +113,9 @@ bool StructurePiece::isInChunk( ChunkPos* pos ) StructurePiece* StructurePiece::findCollisionPiece( list< StructurePiece* > *pieces, BoundingBox* box ) { - for ( AUTO_VAR(it, pieces->begin()); it != pieces->end(); it++ ) + for (auto& piece : *pieces) { - StructurePiece* piece = *it; - if ( piece->getBoundingBox() != NULL && piece->getBoundingBox()->intersects( box ) ) + if ( piece && piece->getBoundingBox() && piece->getBoundingBox()->intersects( box ) ) { return piece; } @@ -125,7 +124,7 @@ StructurePiece* StructurePiece::findCollisionPiece( list< StructurePiece* > *pie } // 4J-PB - Added from 1.2.3 -TilePos *StructurePiece::getLocatorPosition() +TilePos *StructurePiece::getLocatorPosition() { return new TilePos(boundingBox->getXCenter(), boundingBox->getYCenter(), boundingBox->getZCenter()); } @@ -559,7 +558,7 @@ void StructurePiece::placeBlock( Level* level, int block, int data, int x, int y * The purpose of this method is to wrap the getTile call on Level, in order * to prevent the level from generating chunks that shouldn't be loaded yet. * Returns 0 if the call is out of bounds. -* +* * @param level * @param x * @param y diff --git a/Minecraft.World/StructureStart.cpp b/Minecraft.World/StructureStart.cpp index 9e5ba0a8..3f22b4a7 100644 --- a/Minecraft.World/StructureStart.cpp +++ b/Minecraft.World/StructureStart.cpp @@ -21,9 +21,9 @@ StructureStart::StructureStart(int x, int z) StructureStart::~StructureStart() { - for(AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - delete (*it); + delete piece; } delete boundingBox; } @@ -40,9 +40,9 @@ list<StructurePiece *> *StructureStart::getPieces() void StructureStart::postProcess(Level *level, Random *random, BoundingBox *chunkBB) { - AUTO_VAR(it, pieces.begin()); + auto it = pieces.begin(); - while( it != pieces.end() ) + while( it != pieces.end() ) { if( (*it)->getBoundingBox()->intersects(chunkBB) && !(*it)->postProcess(level, random, chunkBB)) { @@ -61,9 +61,8 @@ void StructureStart::calculateBoundingBox() { boundingBox = BoundingBox::getUnknownBox(); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; boundingBox->expand(piece->getBoundingBox()); } } @@ -78,9 +77,8 @@ CompoundTag *StructureStart::createTag(int chunkX, int chunkZ) tag->put(L"BB", boundingBox->createTag(L"BB")); ListTag<CompoundTag> *childrenTags = new ListTag<CompoundTag>(L"Children"); - for(AUTO_VAR(it, pieces.begin()); it != pieces.end(); ++it) + for(auto& piece : pieces) { - StructurePiece *piece = *it; childrenTags->add(piece->createTag()); } tag->put(L"Children", childrenTags); @@ -133,9 +131,8 @@ void StructureStart::moveBelowSeaLevel(Level *level, Random *random, int offset) // move all bounding boxes int dy = y1Pos - boundingBox->y1; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } @@ -157,9 +154,8 @@ void StructureStart::moveInsideHeights(Level *level, Random *random, int lowestA // move all bounding boxes int dy = y0Pos - boundingBox->y0; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } diff --git a/Minecraft.World/SynchedEntityData.cpp b/Minecraft.World/SynchedEntityData.cpp index e6bb9ec7..655fa0c3 100644 --- a/Minecraft.World/SynchedEntityData.cpp +++ b/Minecraft.World/SynchedEntityData.cpp @@ -85,11 +85,11 @@ void SynchedEntityData::checkId(int id) #if 0 if (id > MAX_ID_VALUE) { - throw new IllegalArgumentException(L"Data value id is too big with " + _toString<int>(id) + L"! (Max is " + _toString<int>(MAX_ID_VALUE) + L")"); + throw new IllegalArgumentException(L"Data value id is too big with " + std::to_wstring(id) + L"! (Max is " + std::to_wstring(MAX_ID_VALUE) + L")"); } if (itemsById.find(id) != itemsById.end()) { - throw new IllegalArgumentException(L"Duplicate id value for " + _toString<int>(id) + L"!"); + throw new IllegalArgumentException(L"Duplicate id value for " + std::to_wstring(id) + L"!"); } #endif } @@ -223,12 +223,10 @@ bool SynchedEntityData::isDirty() void SynchedEntityData::pack(vector<shared_ptr<DataItem> > *items, DataOutputStream *output) // TODO throws IOException { - if (items != NULL) + if (items) { - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) + for (auto& dataItem : *items) { - shared_ptr<DataItem> dataItem = *it; writeDataItem(output, dataItem); } } @@ -311,7 +309,7 @@ void SynchedEntityData::writeDataItem(DataOutputStream *output, shared_ptr<DataI { case TYPE_BYTE: output->writeByte( dataItem->getValue_byte()); - break; + break; case TYPE_INT: output->writeInt( dataItem->getValue_int()); break; @@ -324,13 +322,13 @@ void SynchedEntityData::writeDataItem(DataOutputStream *output, shared_ptr<DataI case TYPE_STRING: Packet::writeUtf(dataItem->getValue_wstring(), output); break; - case TYPE_ITEMINSTANCE: + case TYPE_ITEMINSTANCE: { shared_ptr<ItemInstance> instance = (shared_ptr<ItemInstance> )dataItem->getValue_itemInstance(); Packet::writeItem(instance, output); } break; - + default: assert(false); // 4J - not implemented break; @@ -387,7 +385,7 @@ vector<shared_ptr<SynchedEntityData::DataItem> > *SynchedEntityData::unpack(Data case TYPE_STRING: item = shared_ptr<DataItem>( new DataItem(itemType, itemId, Packet::readUtf(input, MAX_STRING_DATA_LENGTH)) ); break; - case TYPE_ITEMINSTANCE: + case TYPE_ITEMINSTANCE: { item = shared_ptr<DataItem>(new DataItem(itemType, itemId, Packet::readItem(input))); } @@ -408,17 +406,14 @@ vector<shared_ptr<SynchedEntityData::DataItem> > *SynchedEntityData::unpack(Data /** * Assigns values from a list of data items. -* +* * @param items */ void SynchedEntityData::assignValues(vector<shared_ptr<DataItem> > *items) { - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) + for (auto& item : *items) { - shared_ptr<DataItem> item = *it; - shared_ptr<DataItem> itemFromId = itemsById[item->getId()]; if( itemFromId != NULL ) { @@ -479,7 +474,7 @@ int SynchedEntityData::getSizeInBytes() { case TYPE_BYTE: size += 1; - break; + break; case TYPE_SHORT: size += 2; break; diff --git a/Minecraft.World/TakeFlowerGoal.cpp b/Minecraft.World/TakeFlowerGoal.cpp index feb87093..48db34d3 100644 --- a/Minecraft.World/TakeFlowerGoal.cpp +++ b/Minecraft.World/TakeFlowerGoal.cpp @@ -24,24 +24,31 @@ bool TakeFlowerGoal::canUse() if (!villager->level->isDay()) return false; vector<shared_ptr<Entity> > *golems = villager->level->getEntitiesOfClass(typeid(VillagerGolem), villager->bb->grow(6, 2, 6)); - if (golems->size() == 0) + if ( golems == nullptr ) + return false; + + if ( golems->size() == 0) { delete golems; return false; } - //for (Entity e : golems) - for(AUTO_VAR(it,golems->begin()); it != golems->end(); ++it) - { - shared_ptr<VillagerGolem> vg = dynamic_pointer_cast<VillagerGolem>(*it); - if (vg->getOfferFlowerTick() > 0) + for (auto entity : *golems ) + { + if ( entity == nullptr ) + continue; + + // safe to call std::static_pointer_cast because of getEntitiesOfClass(typeid(VillagerGolem), ...) makes sure we do not have entities of any other type. + auto vg = std::static_pointer_cast<VillagerGolem>(entity); + if ( vg && vg->getOfferFlowerTick() > 0) { - golem = weak_ptr<VillagerGolem>(vg); - break; + golem = vg; + delete golems; + return true; } } delete golems; - return golem.lock() != NULL; + return false; } bool TakeFlowerGoal::canContinueToUse() diff --git a/Minecraft.World/TextureAndGeometryPacket.cpp b/Minecraft.World/TextureAndGeometryPacket.cpp index 70f2f516..d28fc862 100644 --- a/Minecraft.World/TextureAndGeometryPacket.cpp +++ b/Minecraft.World/TextureAndGeometryPacket.cpp @@ -6,7 +6,7 @@ -TextureAndGeometryPacket::TextureAndGeometryPacket() +TextureAndGeometryPacket::TextureAndGeometryPacket() { this->textureName = L""; this->dwTextureBytes = 0; @@ -16,21 +16,21 @@ TextureAndGeometryPacket::TextureAndGeometryPacket() uiAnimOverrideBitmask=0; } -TextureAndGeometryPacket::~TextureAndGeometryPacket() +TextureAndGeometryPacket::~TextureAndGeometryPacket() { // can't free these - they're used elsewhere // if(this->BoxDataA!=NULL) // { // delete [] this->BoxDataA; // } -// +// // if(this->pbData!=NULL) // { // delete [] this->pbData; // } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes) { this->textureName = textureName; @@ -47,7 +47,7 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P this->uiAnimOverrideBitmask=0; } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes, DLCSkinFile *pDLCSkinFile) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes, DLCSkinFile *pDLCSkinFile) { this->textureName = textureName; @@ -68,11 +68,10 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P vector<SKIN_BOX *> *pSkinBoxes=pDLCSkinFile->getAdditionalBoxes(); int iCount=0; - for(AUTO_VAR(it, pSkinBoxes->begin());it != pSkinBoxes->end(); ++it) + for(auto& pSkinBox : *pSkinBoxes) { - SKIN_BOX *pSkinBox=*it; this->BoxDataA[iCount++]=*pSkinBox; - } + } } else { @@ -80,7 +79,7 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes,vector<SKIN_BOX *> *pvSkinBoxes, unsigned int uiAnimOverrideBitmask) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes,vector<SKIN_BOX *> *pvSkinBoxes, unsigned int uiAnimOverrideBitmask) { this->textureName = textureName; @@ -105,16 +104,15 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P this->BoxDataA= new SKIN_BOX [this->dwBoxC]; int iCount=0; - for(AUTO_VAR(it, pvSkinBoxes->begin());it != pvSkinBoxes->end(); ++it) + for(auto& pSkinBox : *pvSkinBoxes) { - SKIN_BOX *pSkinBox=*it; this->BoxDataA[iCount++]=*pSkinBox; - } + } } } -void TextureAndGeometryPacket::handle(PacketListener *listener) +void TextureAndGeometryPacket::handle(PacketListener *listener) { listener->handleTextureAndGeometry(shared_from_this()); } @@ -157,7 +155,7 @@ void TextureAndGeometryPacket::read(DataInputStream *dis) //throws IOException } } -void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException +void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException { dos->writeUTF(textureName); dos->writeInt(dwSkinID); @@ -183,7 +181,7 @@ void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException } } -int TextureAndGeometryPacket::getEstimatedSize() +int TextureAndGeometryPacket::getEstimatedSize() { return 4096+ +sizeof(int) + sizeof(float)*8*4; } diff --git a/Minecraft.World/ThrownPotion.cpp b/Minecraft.World/ThrownPotion.cpp index f99a0ecb..69c096a2 100644 --- a/Minecraft.World/ThrownPotion.cpp +++ b/Minecraft.World/ThrownPotion.cpp @@ -14,7 +14,7 @@ const double ThrownPotion::SPLASH_RANGE = 4.0; const double ThrownPotion::SPLASH_RANGE_SQ = ThrownPotion::SPLASH_RANGE * ThrownPotion::SPLASH_RANGE; void ThrownPotion::_init() -{ +{ // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that // the derived version of the function is called this->defineSynchedData(); @@ -95,11 +95,9 @@ void ThrownPotion::onHit(HitResult *res) if (entitiesOfClass != NULL && !entitiesOfClass->empty()) { - //for (Entity e : entitiesOfClass) - for(AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) + for(auto & it : *entitiesOfClass) { - //shared_ptr<Entity> e = *it; - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( it ); double dist = distanceToSqr(e); if (dist < SPLASH_RANGE_SQ) { @@ -110,9 +108,8 @@ void ThrownPotion::onHit(HitResult *res) } //for (MobEffectInstance effect : mobEffects) - for(AUTO_VAR(itMEI, mobEffects->begin()); itMEI != mobEffects->end(); ++itMEI) + for(auto& effect : *mobEffects) { - MobEffectInstance *effect = *itMEI; int id = effect->getId(); if (MobEffect::effects[id]->isInstantenous()) { diff --git a/Minecraft.World/Tile.cpp b/Minecraft.World/Tile.cpp index df4e407e..a07fdfe4 100644 --- a/Minecraft.World/Tile.cpp +++ b/Minecraft.World/Tile.cpp @@ -17,14 +17,14 @@ #include "net.minecraft.h" #include "Tile.h" -wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; +wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; const float Tile::INDESTRUCTIBLE_DESTROY_TIME = -1.0f; Tile::SoundType *Tile::SOUND_NORMAL = NULL; Tile::SoundType *Tile::SOUND_WOOD = NULL; Tile::SoundType *Tile::SOUND_GRAVEL = NULL; -Tile::SoundType *Tile::SOUND_GRASS = NULL; +Tile::SoundType *Tile::SOUND_GRASS = NULL; Tile::SoundType *Tile::SOUND_STONE = NULL; Tile::SoundType *Tile::SOUND_METAL = NULL; Tile::SoundType *Tile::SOUND_GLASS = NULL; @@ -204,7 +204,7 @@ ComparatorTile *Tile::comparator_off = NULL; ComparatorTile *Tile::comparator_on = NULL; DaylightDetectorTile *Tile::daylightDetector = NULL; -Tile *Tile::redstoneBlock = NULL; +Tile *Tile::redstoneBlock = NULL; Tile *Tile::netherQuartz = NULL; HopperTile *Tile::hopper = NULL; @@ -427,7 +427,7 @@ void Tile::staticCtor() Tile::comparator_on = (ComparatorTile *) (new ComparatorTile(150, true)) ->setDestroyTime(0.0f)->setLightEmission(10 / 16.0f)->setSoundType(SOUND_WOOD)->setIconName(L"comparator_on")->setDescriptionId(IDS_TILE_COMPARATOR)->setUseDescriptionId(IDS_DESC_COMPARATOR); Tile::daylightDetector = (DaylightDetectorTile *) (new DaylightDetectorTile(151))->setDestroyTime(0.2f)->setSoundType(SOUND_WOOD)->setIconName(L"daylight_detector")->setDescriptionId(IDS_TILE_DAYLIGHT_DETECTOR)->setUseDescriptionId(IDS_DESC_DAYLIGHT_DETECTOR); - Tile::redstoneBlock = (new PoweredMetalTile(152)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_redstone)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setIconName(L"redstone_block")->setDescriptionId(IDS_TILE_REDSTONE_BLOCK)->setUseDescriptionId(IDS_DESC_REDSTONE_BLOCK); + Tile::redstoneBlock = (new PoweredMetalTile(152)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_redstone)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setIconName(L"redstone_block")->setDescriptionId(IDS_TILE_REDSTONE_BLOCK)->setUseDescriptionId(IDS_DESC_REDSTONE_BLOCK); Tile::netherQuartz = (new OreTile(153)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(SOUND_STONE)->setIconName(L"quartz_ore")->setDescriptionId(IDS_TILE_NETHER_QUARTZ)->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ_ORE); Tile::hopper = (HopperTile *)(new HopperTile(154)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_redstoneContainer, Item::eMaterial_undefined)->setDestroyTime(3.0f)->setExplodeable(8)->setSoundType(SOUND_WOOD)->setIconName(L"hopper")->setDescriptionId(IDS_TILE_HOPPER)->setUseDescriptionId(IDS_DESC_HOPPER); Tile::quartzBlock = (new QuartzBlockTile(155)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_quartz)->setSoundType(SOUND_STONE)->setDestroyTime(0.8f)->setIconName(L"quartz_block")->setDescriptionId(IDS_TILE_QUARTZ_BLOCK)->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); @@ -819,7 +819,7 @@ AABB *Tile::getTileAABB(Level *level, int x, int y, int z) return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1); } -void Tile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, shared_ptr<Entity> source) +void Tile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, shared_ptr<Entity> source) { AABB *aabb = getAABB(level, x, y, z); if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); @@ -1413,7 +1413,7 @@ Tile *Tile::setIconName(const wstring &iconName) wstring Tile::getIconName() { - return iconName.empty() ? L"MISSING_ICON_TILE_" + _toString<int>(id) + L"_" + _toString<int>(descriptionId) : iconName; + return iconName.empty() ? L"MISSING_ICON_TILE_" + std::to_wstring(id) + L"_" + std::to_wstring(descriptionId) : iconName; } void Tile::registerIcons(IconRegister *iconRegister) @@ -1527,26 +1527,26 @@ Tile::SoundType::SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, flo } float Tile::SoundType::getVolume() const -{ - return volume; +{ + return volume; } float Tile::SoundType::getPitch() const -{ - return pitch; +{ + return pitch; } //wstring getBreakSound() const { return breakSound; } //wstring getStepSound() const { return stepSound; } int Tile::SoundType::getBreakSound() const -{ - return iBreakSound; +{ + return iBreakSound; } int Tile::SoundType::getStepSound() const -{ - return iStepSound; +{ + return iStepSound; } int Tile::SoundType::getPlaceSound() const -{ - return iPlaceSound; +{ + return iPlaceSound; } diff --git a/Minecraft.World/TileEntity.cpp b/Minecraft.World/TileEntity.cpp index ded0c665..1eb9cab2 100644 --- a/Minecraft.World/TileEntity.cpp +++ b/Minecraft.World/TileEntity.cpp @@ -78,8 +78,8 @@ void TileEntity::load(CompoundTag *tag) void TileEntity::save(CompoundTag *tag) { - AUTO_VAR(it, classIdMap.find( this->GetType() )); - if ( it == classIdMap.end() ) + auto it = classIdMap.find(this->GetType()); + if ( it == classIdMap.end() ) { // TODO 4J Stu - Some sort of exception handling //throw new RuntimeException(this->getClass() + " is missing a mapping! This is a bug!"); @@ -98,17 +98,9 @@ void TileEntity::tick() shared_ptr<TileEntity> TileEntity::loadStatic(CompoundTag *tag) { shared_ptr<TileEntity> entity = nullptr; - - //try - //{ - AUTO_VAR(it, idCreateMap.find(tag->getString(L"id"))); - if (it != idCreateMap.end() ) entity = shared_ptr<TileEntity>(it->second()); - //} - //catch (Exception e) - //{ - // TODO 4J Stu - Exception handling? - // e->printStackTrace(); - //} + auto it = idCreateMap.find(tag->getString(L"id")); + if (it != idCreateMap.end()) + entity = shared_ptr<TileEntity>(it->second()); if (entity != NULL) { entity->load(tag); diff --git a/Minecraft.World/TripWireTile.cpp b/Minecraft.World/TripWireTile.cpp index 2fd7da6c..b8ae9f33 100644 --- a/Minecraft.World/TripWireTile.cpp +++ b/Minecraft.World/TripWireTile.cpp @@ -13,7 +13,7 @@ TripWireTile::TripWireTile(int id) : Tile(id, Material::decoration, isSolidRende int TripWireTile::getTickDelay(Level *level) { - // 4J: Increased (x2); quick update caused problems with shared + // 4J: Increased (x2); quick update caused problems with shared // data between client and server. return 20; // 10; } @@ -164,15 +164,14 @@ void TripWireTile::checkPressed(Level *level, int x, int y, int z) int data = level->getData(x, y, z); bool wasPressed = (data & MASK_POWERED) == MASK_POWERED; bool shouldBePressed = false; - + ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); vector<shared_ptr<Entity> > *entities = level->getEntities(nullptr, AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1)); if (!entities->empty()) { - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; - if (!e->isIgnoringTileTriggers()) + if ( e && !e->isIgnoringTileTriggers()) { shouldBePressed = true; break; diff --git a/Minecraft.World/UpdateAttributesPacket.cpp b/Minecraft.World/UpdateAttributesPacket.cpp index 45c20575..e80ebe4e 100644 --- a/Minecraft.World/UpdateAttributesPacket.cpp +++ b/Minecraft.World/UpdateAttributesPacket.cpp @@ -13,9 +13,8 @@ UpdateAttributesPacket::UpdateAttributesPacket(int entityId, unordered_set<Attri { this->entityId = entityId; - for (AUTO_VAR(it,values->begin()); it != values->end(); ++it) + for (AttributeInstance *value : *values) { - AttributeInstance *value = *it; unordered_set<AttributeModifier*> mods; value->getModifiers(mods); attributes.insert(new AttributeSnapshot(value->getAttribute()->getId(), value->getBaseValue(), &mods)); @@ -25,9 +24,9 @@ UpdateAttributesPacket::UpdateAttributesPacket(int entityId, unordered_set<Attri UpdateAttributesPacket::~UpdateAttributesPacket() { // Delete modifiers - these are always copies, either on construction or on read - for(AUTO_VAR(it,attributes.begin()); it != attributes.end(); ++it) - { - delete (*it); + for(auto& attribute : attributes) + { + delete attribute; } } @@ -54,9 +53,9 @@ void UpdateAttributesPacket::read(DataInputStream *dis) attributes.insert(new AttributeSnapshot(id, base, &modifiers)); // modifiers is copied in AttributeSnapshot ctor so delete contents - for(AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for(auto& modifier : modifiers) { - delete *it; + delete modifier; } } } @@ -66,19 +65,16 @@ void UpdateAttributesPacket::write(DataOutputStream *dos) dos->writeInt(entityId); dos->writeInt(attributes.size()); - for(AUTO_VAR(it, attributes.begin()); it != attributes.end(); ++it) + for(auto& attribute : attributes) { - AttributeSnapshot *attribute = (*it); - unordered_set<AttributeModifier *> *modifiers = attribute->getModifiers(); dos->writeShort(attribute->getId()); dos->writeDouble(attribute->getBase()); dos->writeShort(modifiers->size()); - for (AUTO_VAR(it2, modifiers->begin()); it2 != modifiers->end(); ++it2) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = (*it2); dos->writeInt(modifier->getId()); dos->writeDouble(modifier->getAmount()); dos->writeByte(modifier->getOperation()); @@ -111,17 +107,17 @@ UpdateAttributesPacket::AttributeSnapshot::AttributeSnapshot(eATTRIBUTE_ID id, d this->id = id; this->base = base; - for(AUTO_VAR(it,modifiers->begin()); it != modifiers->end(); ++it) + for(auto& modifier : *modifiers) { - this->modifiers.insert( new AttributeModifier((*it)->getId(), (*it)->getAmount(), (*it)->getOperation())); + this->modifiers.insert( new AttributeModifier(modifier->getId(), modifier->getAmount(), modifier->getOperation())); } } UpdateAttributesPacket::AttributeSnapshot::~AttributeSnapshot() { - for(AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for(auto& modifier : modifiers) { - delete (*it); + delete modifier; } } diff --git a/Minecraft.World/Village.cpp b/Minecraft.World/Village.cpp index 507bc717..a72319fe 100644 --- a/Minecraft.World/Village.cpp +++ b/Minecraft.World/Village.cpp @@ -46,9 +46,9 @@ Village::~Village() { delete accCenter; delete center; - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& aggressor : aggressors) { - delete *it; + delete aggressor; } } @@ -181,9 +181,8 @@ shared_ptr<DoorInfo> Village::getClosestDoorInfo(int x, int y, int z) shared_ptr<DoorInfo> closest = nullptr; int closestDistSqr = Integer::MAX_VALUE; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; int distSqr = dm->distanceToSqr(x, y, z); if (distSqr < closestDistSqr) { @@ -199,10 +198,8 @@ shared_ptr<DoorInfo>Village::getBestDoorInfo(int x, int y, int z) shared_ptr<DoorInfo> closest = nullptr; int closestDist = Integer::MAX_VALUE; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo>dm = *it; - int distSqr = dm->distanceToSqr(x, y, z); if (distSqr > 16 * 16) distSqr *= 1000; else distSqr = dm->getBookingsCount(); @@ -221,14 +218,13 @@ bool Village::hasDoorInfo(int x, int y, int z) return getDoorInfo(x, y, z) != NULL; } -shared_ptr<DoorInfo>Village::getDoorInfo(int x, int y, int z) +shared_ptr<DoorInfo> Village::getDoorInfo(int x, int y, int z) { if (center->distSqr(x, y, z) > radius * radius) return nullptr; - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for( auto& di : doorInfos) { - shared_ptr<DoorInfo> di = *it; - if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; + if (di->x == x && di->z == z && abs(di->y - y) <= 1) + return di; } return nullptr; } @@ -250,10 +246,8 @@ bool Village::canRemove() void Village::addAggressor(shared_ptr<LivingEntity> mob) { - //for (Aggressor a : aggressors) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& a : aggressors) { - Aggressor *a = *it; if (a->mob == mob) { a->timeStamp = _tick; @@ -267,10 +261,8 @@ shared_ptr<LivingEntity> Village::getClosestAggressor(shared_ptr<LivingEntity> f { double closestSqr = Double::MAX_VALUE; Aggressor *closest = NULL; - //for (int i = 0; i < aggressors.size(); ++i) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& a : aggressors) { - Aggressor *a = *it; //aggressors.get(i); double distSqr = a->mob->distanceToSqr(from); if (distSqr > closestSqr) continue; closest = a; @@ -284,10 +276,9 @@ shared_ptr<Player> Village::getClosestBadStandingPlayer(shared_ptr<LivingEntity> double closestSqr = Double::MAX_VALUE; shared_ptr<Player> closest = nullptr; - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it,playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - wstring player = it->first; + wstring player = it.first; if (isVeryBadStanding(player)) { shared_ptr<Player> mob = level->getPlayerByName(player); @@ -306,9 +297,8 @@ shared_ptr<Player> Village::getClosestBadStandingPlayer(shared_ptr<LivingEntity> void Village::updateAggressors() { - //for (Iterator<Aggressor> it = aggressors.iterator(); it.hasNext();) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end();) - { + for (auto it = aggressors.begin(); it != aggressors.end();) + { Aggressor *a = *it; //it.next(); if (!a->mob->isAlive() || abs(_tick - a->timeStamp) > 300) { @@ -328,8 +318,8 @@ void Village::updateDoors() bool removed = false; bool resetBookings = level->random->nextInt(50) == 0; //for (Iterator<DoorInfo> it = doorInfos.iterator(); it.hasNext();) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end();) - { + for (auto it = doorInfos.begin(); it != doorInfos.end();) + { shared_ptr<DoorInfo> dm = *it; //it.next(); if (resetBookings) dm->resetBookingCount(); if (!isDoor(dm->x, dm->y, dm->z) || abs(_tick - dm->timeStamp) > 1200) @@ -371,10 +361,9 @@ void Village::calcInfo() center->set(accCenter->x / s, accCenter->y / s, accCenter->z / s); int maxRadiusSqr = 0; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; - maxRadiusSqr = max(dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); + maxRadiusSqr = std::max<int>(dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); } int doorDist= Villages::MaxDoorDist; // Take into local int for PS4 as max takes a reference to the const int there and then needs the value to exist for the linker radius = max(doorDist, (int) sqrt((float)maxRadiusSqr) + 1); @@ -382,8 +371,8 @@ void Village::calcInfo() int Village::getStanding(const wstring &playerName) { - AUTO_VAR(it,playerStanding.find(playerName)); - if (it != playerStanding.end()) + auto it = playerStanding.find(playerName); + if (it != playerStanding.end()) { return it->second; } @@ -462,9 +451,8 @@ void Village::addAdditonalSaveData(CompoundTag *tag) ListTag<CompoundTag> *doorTags = new ListTag<CompoundTag>(L"Doors"); //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it,doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; CompoundTag *doorTag = new CompoundTag(L"Door"); doorTag->putInt(L"X", dm->x); doorTag->putInt(L"Y", dm->y); @@ -478,12 +466,12 @@ void Village::addAdditonalSaveData(CompoundTag *tag) ListTag<CompoundTag> *playerTags = new ListTag<CompoundTag>(L"Players"); //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - wstring player = it->first; + wstring player = it.first; CompoundTag *playerTag = new CompoundTag(player); playerTag->putString(L"Name", player); - playerTag->putInt(L"S", it->second); + playerTag->putInt(L"S", it.second); playerTags->add(playerTag); } tag->put(L"Players", playerTags); @@ -504,9 +492,8 @@ bool Village::isBreedTimerOk() void Village::rewardAllPlayers(int amount) { - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - modifyStanding(it->first, amount); + modifyStanding(it.first, amount); } }
\ No newline at end of file diff --git a/Minecraft.World/VillageFeature.cpp b/Minecraft.World/VillageFeature.cpp index 82974c7b..5249256c 100644 --- a/Minecraft.World/VillageFeature.cpp +++ b/Minecraft.World/VillageFeature.cpp @@ -34,15 +34,15 @@ VillageFeature::VillageFeature(unordered_map<wstring, wstring> options, int iXZS { _init(iXZSize); - for (AUTO_VAR(it,options.begin()); it != options.end(); ++it) + for (auto& option : options) { - if (it->first.compare(OPTION_SIZE_MODIFIER) == 0) + if (option.first.compare(OPTION_SIZE_MODIFIER) == 0) { - villageSizeModifier = Mth::getInt(it->second, villageSizeModifier, 0); + villageSizeModifier = Mth::getInt(option.second, villageSizeModifier, 0); } - else if (it->first.compare(OPTION_SPACING) == 0) + else if (option.first.compare(OPTION_SPACING) == 0) { - townSpacing = Mth::getInt(it->second, townSpacing, minTownSeparation + 1); + townSpacing = Mth::getInt(option.second, townSpacing, minTownSeparation + 1); } } } @@ -60,7 +60,7 @@ bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) #ifdef _LARGE_WORLDS && level->dimension->getXZSize() < 128 #endif - ) + ) { townSpacing= 16;// 4J change 32; } @@ -135,16 +135,16 @@ VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chu if (pendingRoads->empty()) { int pos = random->nextInt((int)pendingHouses->size()); - AUTO_VAR(it, pendingHouses->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingHouses->begin() + pos; + StructurePiece *structurePiece = *it; pendingHouses->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } else { int pos = random->nextInt((int)pendingRoads->size()); - AUTO_VAR(it, pendingRoads->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingRoads->begin() + pos; + StructurePiece *structurePiece = *it; pendingRoads->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } @@ -152,13 +152,12 @@ VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chu calculateBoundingBox(); - int count = 0; - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + size_t count = 0; + for(auto& piece : pieces) { - StructurePiece *piece = *it; - if (dynamic_cast<VillagePieces::VillageRoadPiece *>(piece) == NULL) + if ( piece && dynamic_cast<VillagePieces::VillageRoadPiece *>(piece) ) { - count++; + ++count; } } valid = count > 2; diff --git a/Minecraft.World/VillagePieces.cpp b/Minecraft.World/VillagePieces.cpp index 0a08d4fb..1737d6e0 100644 --- a/Minecraft.World/VillagePieces.cpp +++ b/Minecraft.World/VillagePieces.cpp @@ -66,8 +66,8 @@ list<VillagePieces::PieceWeight *> *VillagePieces::createPieceSet(Random *random newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_TwoRoomHouse, 8, Mth::nextInt(random, 0 + villageSize, 3 + villageSize * 2))); // silly way of filtering "infinite" buildings - AUTO_VAR(it, newPieces->begin()); - while( it != newPieces->end() ) + auto it = newPieces->begin(); + while( it != newPieces->end() ) { if( (*it)->maxPlaceCount == 0 ) { @@ -87,9 +87,8 @@ int VillagePieces::updatePieceWeight(list<PieceWeight *> *currentPieces) { bool hasAnyPieces = false; int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) + for(auto& piece : *currentPieces) { - PieceWeight *piece = *it; if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -158,13 +157,11 @@ VillagePieces::VillagePiece *VillagePieces::generatePieceFromSmallDoor(StartPiec numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, startPiece->pieceSet->begin()); it != startPiece->pieceSet->end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : *startPiece->pieceSet ) + { weightSelection -= piece->weight; if (weightSelection < 0) { - if (!piece->doPlace(depth) || (piece == startPiece->previousPiece && startPiece->pieceSet->size() > 1)) { break; @@ -587,9 +584,9 @@ VillagePieces::StartPiece::StartPiece(BiomeSource *biomeSource, int genDepth, Ra VillagePieces::StartPiece::~StartPiece() { - for(AUTO_VAR(it, pieceSet->begin()); it != pieceSet->end(); it++ ) + for(auto& it : *pieceSet) { - delete (*it); + delete it; } delete pieceSet; } @@ -677,14 +674,14 @@ void VillagePieces::StraightRoad::addChildren(StructurePiece *startPiece, list<S { case Direction::NORTH: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0, Direction::EAST, getGenDepth()); - break; - case Direction::SOUTH: + break; + case Direction::SOUTH: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z1 - 2, Direction::EAST, getGenDepth()); - break; - case Direction::EAST: + break; + case Direction::EAST: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 - 2, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - break; - case Direction::WEST: + break; + case Direction::WEST: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); break; } @@ -989,7 +986,7 @@ bool VillagePieces::SmallTemple::postProcess(Level *level, Random *random, Bound } - for (int z = 0; z < depth; z++) + for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { diff --git a/Minecraft.World/VillageSiege.cpp b/Minecraft.World/VillageSiege.cpp index 0f967595..e3d20ef3 100644 --- a/Minecraft.World/VillageSiege.cpp +++ b/Minecraft.World/VillageSiege.cpp @@ -78,10 +78,8 @@ void VillageSiege::tick() bool VillageSiege::tryToSetupSiege() { vector<shared_ptr<Player> > *players = &level->players; - //for (Player player : players) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) + for(auto& player : *players) { - shared_ptr<Player> player = *it; shared_ptr<Village> _village = level->villages->getClosestVillage((int) player->x, (int) player->y, (int) player->z, 1); village = _village; @@ -103,9 +101,8 @@ bool VillageSiege::tryToSetupSiege() overlaps = false; vector<shared_ptr<Village> > *villages = level->villages->getVillages(); //for (Village v : level.villages.getVillages()) - for(AUTO_VAR(itV, villages->begin()); itV != villages->end(); ++itV) + for(auto& v : *villages) { - shared_ptr<Village>v = *itV; if (v == _village) continue; if (v->isInside(spawnX, spawnY, spawnZ)) { @@ -132,16 +129,11 @@ bool VillageSiege::trySpawn() Vec3 *spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); if (spawnPos == NULL) return false; shared_ptr<Zombie> mob; - //try { mob = shared_ptr<Zombie>( new Zombie(level) ); mob->finalizeMobSpawn(NULL); mob->setVillager(false); } - //catch (Exception e) { - // e.printStackTrace(); - // return false; - //} mob->moveTo(spawnPos->x, spawnPos->y, spawnPos->z, level->random->nextFloat() * 360, 0); level->addEntity(mob); shared_ptr<Village> _village = village.lock(); diff --git a/Minecraft.World/Villager.cpp b/Minecraft.World/Villager.cpp index 1fe32a12..18ed7178 100644 --- a/Minecraft.World/Villager.cpp +++ b/Minecraft.World/Villager.cpp @@ -125,9 +125,8 @@ void Villager::serverAiMobStep() if (offers->size() > 0) { //for (MerchantRecipe recipe : offers) - for(AUTO_VAR(it, offers->begin()); it != offers->end(); ++it) + for(auto& recipe : *offers) { - MerchantRecipe *recipe = *it; if (recipe->isDeprecated()) { recipe->increaseMaxUses(random->nextInt(6) + random->nextInt(6) + 2); @@ -615,8 +614,8 @@ shared_ptr<ItemInstance> Villager::getItemTradeInValue(int itemId, Random *rando int Villager::getTradeInValue(int itemId, Random *random) { - AUTO_VAR(it,MIN_MAX_VALUES.find(itemId)); - if (it == MIN_MAX_VALUES.end()) + auto it = MIN_MAX_VALUES.find(itemId); + if (it == MIN_MAX_VALUES.end()) { return 1; } @@ -660,8 +659,8 @@ void Villager::addItemForPurchase(MerchantRecipeList *list, int itemId, Random * int Villager::getPurchaseCost(int itemId, Random *random) { - AUTO_VAR(it,MIN_MAX_PRICES.find(itemId)); - if (it == MIN_MAX_PRICES.end()) + auto it = MIN_MAX_PRICES.find(itemId); + if (it == MIN_MAX_PRICES.end()) { return 1; } @@ -677,7 +676,7 @@ void Villager::handleEntityEvent(byte id) { if (id == EntityEvent::LOVE_HEARTS) { - addParticlesAroundSelf(eParticleType_heart); + addParticlesAroundSelf(eParticleType_heart); } else if (id == EntityEvent::VILLAGER_ANGRY) { diff --git a/Minecraft.World/Villages.cpp b/Minecraft.World/Villages.cpp index ddb0e7dc..e636ed74 100644 --- a/Minecraft.World/Villages.cpp +++ b/Minecraft.World/Villages.cpp @@ -22,17 +22,16 @@ Villages::Villages(Level *level) : SavedData(VILLAGE_FILE_ID) Villages::~Villages() { - for(AUTO_VAR(it,queries.begin()); it != queries.end(); ++it) delete *it; + for(auto& querie : queries) + delete querie; } void Villages::setLevel(Level *level) { this->level = level; - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; village->setLevel(level); } } @@ -47,9 +46,8 @@ void Villages::tick() { ++_tick; //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; village->tick(_tick); } removeVillages(); @@ -64,8 +62,8 @@ void Villages::tick() void Villages::removeVillages() { - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ) - { + for (auto it = villages.begin(); it != villages.end();) + { shared_ptr<Village> village = *it; if (village->canRemove()) { @@ -88,9 +86,8 @@ shared_ptr<Village> Villages::getClosestVillage(int x, int y, int z, int maxDist { shared_ptr<Village> closest = nullptr; float closestDistSqr = Float::MAX_VALUE; - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; float distSqr = village->getCenter()->distSqr(x, y, z); if (distSqr >= closestDistSqr) continue; @@ -115,14 +112,11 @@ void Villages::processNextQuery() void Villages::cluster() { // note doesn't merge or split existing villages - for(AUTO_VAR(it, unclustered.begin()); it != unclustered.end(); ++it) + for(auto& di : unclustered) { - shared_ptr<DoorInfo> di = *it; - bool found = false; - for(AUTO_VAR(itV, villages.begin()); itV != villages.end(); ++itV) + for(auto& village : villages) { - shared_ptr<Village> village = *itV; int dist = (int) village->getCenter()->distSqr(di->x, di->y, di->z); int radius = MaxDoorDist + village->getRadius(); if (dist > radius * radius) continue; @@ -164,17 +158,15 @@ void Villages::addDoorInfos(Pos *pos) shared_ptr<DoorInfo> Villages::getDoorInfo(int x, int y, int z) { //for (DoorInfo di : unclustered) - for(AUTO_VAR(it,unclustered.begin()); it != unclustered.end(); ++it) + for( const auto& di : unclustered) { - shared_ptr<DoorInfo> di = *it; if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; } //for (Village v : villages) - for(AUTO_VAR(it,villages.begin()); it != villages.end(); ++it) + for(auto& v : villages) { - shared_ptr<Village> v = *it; shared_ptr<DoorInfo> di = v->getDoorInfo(x, y, z); - if (di != NULL) return di; + if (di != nullptr) return di; } return nullptr; } @@ -205,10 +197,10 @@ void Villages::createDoorInfo(int x, int y, int z) bool Villages::hasQuery(int x, int y, int z) { //for (Pos pos : queries) - for(AUTO_VAR(it, queries.begin()); it != queries.end(); ++it) + for(const Pos* pos : queries) { - Pos *pos = *it; - if (pos->x == x && pos->y == y && pos->z == z) return true; + if (pos->x == x && pos->y == y && pos->z == z) + return true; } return false; } @@ -237,9 +229,8 @@ void Villages::save(CompoundTag *tag) tag->putInt(L"Tick", _tick); ListTag<CompoundTag> *villageTags = new ListTag<CompoundTag>(L"Villages"); //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; CompoundTag *villageTag = new CompoundTag(L"Village"); village->addAdditonalSaveData(villageTag); villageTags->add(villageTag); diff --git a/Minecraft.World/WeighedRandom.cpp b/Minecraft.World/WeighedRandom.cpp index 8839b0c5..0c27bf32 100644 --- a/Minecraft.World/WeighedRandom.cpp +++ b/Minecraft.World/WeighedRandom.cpp @@ -4,9 +4,9 @@ int WeighedRandom::getTotalWeight(vector<WeighedRandomItem *> *items) { int totalWeight = 0; - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) + for( const auto& item : *items) { - totalWeight += (*it)->randomWeight; + totalWeight += item->randomWeight; } return totalWeight; } @@ -20,12 +20,12 @@ WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, vector<WeighedRa int selection = random->nextInt(totalWeight); - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) + for(const auto& item : *items) { - selection -= (*it)->randomWeight; + selection -= item->randomWeight; if (selection < 0) { - return *it; + return item; } } return NULL; diff --git a/Minecraft.World/Witch.cpp b/Minecraft.World/Witch.cpp index c73e9198..c697d467 100644 --- a/Minecraft.World/Witch.cpp +++ b/Minecraft.World/Witch.cpp @@ -101,9 +101,9 @@ void Witch::aiStep() vector<MobEffectInstance *> *effects = Item::potion->getMobEffects(item); if (effects != NULL) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - addEffect(new MobEffectInstance(*it)); + addEffect(new MobEffectInstance(effect)); } } delete effects; diff --git a/Minecraft.World/ZonedChunkStorage.cpp b/Minecraft.World/ZonedChunkStorage.cpp index b4ee8585..5c6bf192 100644 --- a/Minecraft.World/ZonedChunkStorage.cpp +++ b/Minecraft.World/ZonedChunkStorage.cpp @@ -11,7 +11,7 @@ // 4J Stu - There are changes to this class for 1.8.2, but since we never use it anyway lets not worry about it const int ZonedChunkStorage::BIT_TERRAIN_POPULATED = 0x0000001; - + const int ZonedChunkStorage::CHUNKS_PER_ZONE_BITS = 5; // = 32 const int ZonedChunkStorage::CHUNKS_PER_ZONE = 1 << ZonedChunkStorage::CHUNKS_PER_ZONE_BITS; // ^2 @@ -54,11 +54,11 @@ ZoneFile *ZonedChunkStorage::getZoneFile(int x, int z, bool create) // 4J - was !zoneFiles.containsKey(key) if (zoneFiles.find(key) == zoneFiles.end()) { - wchar_t xRadix36[64]; - wchar_t zRadix36[64]; - _itow(x,xRadix36,36); - _itow(z,zRadix36,36); - File file = File(dir, wstring( L"zone_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + wchar_t xRadix36[64] {}; + wchar_t zRadix36[64] {}; + _itow_s(x,xRadix36,36); + _itow_s(z,zRadix36,36); + File file = File(dir, wstring( L"zone_") + std::wstring( xRadix36 ) + L"_" + std::wstring( zRadix36 ) + L".dat" ); if ( !file.exists() ) { @@ -67,7 +67,7 @@ ZoneFile *ZonedChunkStorage::getZoneFile(int x, int z, bool create) CloseHandle(ch); } - File entityFile = File(dir, wstring( L"entities_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + File entityFile = File(dir, wstring( L"entities_") + std::wstring( xRadix36 ) + L"_" + std::wstring( zRadix36 ) + L".dat" ); zoneFiles[key] = new ZoneFile(key, file, entityFile); } @@ -147,32 +147,24 @@ void ZonedChunkStorage::tick() tickCount++; if (tickCount % (20 * 10) == 4) { - vector<__int64> toClose; + std::vector<int64_t> toClose; - AUTO_VAR(itEndZF, zoneFiles.end()); - for( unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEndZF; it++ ) + for ( auto& it : zoneFiles ) { - ZoneFile *zoneFile = it->second; - if (tickCount - zoneFile->lastUse > 20 * 60) + ZoneFile *zoneFile = it.second; + if ( zoneFile && tickCount - zoneFile->lastUse > 20 * 60) { toClose.push_back(zoneFile->key); } } - - AUTO_VAR(itEndTC, toClose.end()); - for (AUTO_VAR(it, toClose.begin()); it != itEndTC; it++) + + for ( int64_t key : toClose ) { - __int64 key = *it ; //toClose[i]; - // 4J - removed try/catch -// try { char buf[256]; sprintf(buf,"Closing zone %I64d\n",key); app.DebugPrintf(buf); zoneFiles[key]->close(); zoneFiles.erase(zoneFiles.find(key)); -// } catch (IOException e) { -// e.printStackTrace(); -// } } } } @@ -180,16 +172,12 @@ void ZonedChunkStorage::tick() void ZonedChunkStorage::flush() { - AUTO_VAR(itEnd, zoneFiles.end()); - for( unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEnd; it++ ) + auto itEnd = zoneFiles.end(); + for ( auto& it : zoneFiles ) { - ZoneFile *zoneFile = it->second; - // 4J - removed try/catch -// try { + ZoneFile *zoneFile = it.second; + if ( zoneFile ) zoneFile->close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } } zoneFiles.clear(); } @@ -200,20 +188,18 @@ void ZonedChunkStorage::loadEntities(Level *level, LevelChunk *lc) ZoneFile *zoneFile = getZoneFile(lc->x, lc->z, true); vector<CompoundTag *> *tags = zoneFile->entityFile->readAll(slot); - AUTO_VAR(itEnd, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEnd; it++) + for ( CompoundTag *tag : *tags ) { - CompoundTag *tag = *it; //tags->at(i); int type = tag->getInt(L"_TYPE"); if (type == 0) { shared_ptr<Entity> e = EntityIO::loadStatic(tag, level); - if (e != NULL) lc->addEntity(e); + if (e != nullptr) lc->addEntity(e); } else if (type == 1) { shared_ptr<TileEntity> te = TileEntity::loadStatic(tag); - if (te != NULL) lc->addTileEntity(te); + if (te != nullptr) lc->addTileEntity(te); } } } @@ -234,10 +220,8 @@ void ZonedChunkStorage::saveEntities(Level *level, LevelChunk *lc) { vector<shared_ptr<Entity> > *entities = lc->entityBlocks[i]; - AUTO_VAR(itEndTags, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEndTags; it++) + for ( auto& e : *entities ) { - shared_ptr<Entity> e = *it; //entities->at(j); CompoundTag *cp = new CompoundTag(); cp->putInt(L"_TYPE", 0); e->save(cp); diff --git a/Minecraft.World/compile_flags.txt b/Minecraft.World/compile_flags.txt new file mode 100644 index 00000000..57863c77 --- /dev/null +++ b/Minecraft.World/compile_flags.txt @@ -0,0 +1,18 @@ +-xc++ +-m64 +-std=c++14 +-Wno-unused-includes +-Wno-unsafe-buffer-usage-in-libc-call +-Wno-unsafe-buffer-usage +-Wno-unused-macros +-Wno-c++98-compat +-Wno-c++98-compat-pedantic +-Wno-pre-c++14-compat +-D_LARGE_WORLDS +-D_DEBUG_MENUS_ENABLED +-D_LIB +-D_CRT_NON_CONFORMING_SWPRINTFS +-D_CRT_SECURE_NO_WARNINGS +-D_WINDOWS64 +-I +./x64headers
\ No newline at end of file diff --git a/Minecraft.World/stdafx.h b/Minecraft.World/stdafx.h index 48e52544..37c3960c 100644 --- a/Minecraft.World/stdafx.h +++ b/Minecraft.World/stdafx.h @@ -6,7 +6,6 @@ #ifdef __PS3__ #else -#define AUTO_VAR(_var, _val) auto _var = _val #endif #if ( defined _XBOX || defined _WINDOWS64 || defined _DURANGO ) |
