Avg tick minecraft что это

Обновлено: 08.07.2024

The Minecraft Wiki is no longer considered as official by Microsoft and therefore several changes are required to be made, including to the wiki's logo. Please read this announcement for more information.

Nearly all video games (including Minecraft) are driven by one big program loop. Just as every gear in a clock is synchronized with the pendulum, every task involved in advancing a game simulation is synchronized with the game loop. Appropriately, one cycle of the game loop is called a tick.

Chunk tick [ ]


As a part of a game tick, specific chunks are ticked on every game tick.

In Bedrock Edition, all loading chunks are ticked on every game tick. The following things will happen when a chunk gets ticked:

Random tick [ ]

Chunks consist of one subchunk per 16 blocks of height, each one being a 16×16×16=4096 block cube. Sections are distributed vertically starting at the lowest y level. Every chunk tick, some blocks are chosen at random from each section in the chunk. The blocks at those positions are given a "random tick".

In Java Edition, the number of blocks chosen from each section is specified by /gamerule randomTickSpeed (defaults to 3), and one block can be chosen multiple times in one chunk tick. In Bedrock Edition, it also depends on randomTickSpeed (defaults to 1), but it specifies only relative speed instead of the exact number.

Most blocks ignore this tick, but some use it to do something:

    may grow or uproot. may spread or uproot. may spread. may burn out or spread. and snow layers may melt. may decay. hydration is updated. , sugar cane, kelp, bamboo, chorus flowers and sweet berry bushes may grow. and mycelium may spread.
  • Grass blocks, mycelium, and nylium may decay (if and only if the condition is met). may grow into a tree. may set fires nearby.
  • Lit redstone ore turns off. may spawn a zombified piglin. crack or hatch. smoke appears. may grow an amethyst bud on one of its sides. (or any of its non-oxidized variants) may advance one stage in oxidation. may fill a cauldron below.

In Java Edition, because random block ticks are granted randomly, there is no way to predict when a block can receive its next tick. The median time between ticks is 47.30 seconds (946.03 game ticks). That is, there is a 50% chance for the interval to be equal or shorter than 47.30 seconds and a 50% chance for it to be equal or longer than 47.30. However, sometimes it is much longer or shorter: for example, there is a 1.5% chance for the interval to be less than one second and a 1% chance for the interval to be over five minutes. On average, blocks are updated every 68.27 seconds (1365.33 game ticks). For the math behind these numbers, see the Wikipedia entries for the geometric distribution.

Проблемы и решения

Главное, что нужно понимать, — все, что касается обработки игрового мира будет обрабатываться только на одном вычислительном ядре физического сервера. Так что если вдруг у вас прекрасный сервер с десятком вычислительных ядер, то загружено будет только одно. Все остальные будут фактически простаивать. Такова уж архитектура приложения, и ничего вы с этим поделать не сможете. Так что при выборе сервера следует обращать внимание не на количество ядер, а на тактовую частоту. Чем она будет выше, тем лучше будет производительность.

Что касается вопроса об объеме оперативной памяти, тут следует исходить из следующих показателей:

  • планируемое количество игроков;
  • планируемое количество миров на сервере;
  • размер каждого мира.

Для запуска серверной части рекомендуем воспользоваться флагами, указанными в статье Tuning the JVM – G1GC Garbage Collector Flags for Minecraft. Эта «черная магия» позволяет серверу грамотно настроить «сборщик мусора» и оптимизирует использование оперативной памяти. Не стоит выделять памяти больше, чем реально потребляет сервер при пиковом наплыве игроков.

Генерация карты блоков

“Вы действительно считаете, что Луна существует, только когда вы на неё смотрите?” (Альберт Эйнштейн)

Абсолютно новый сервер. Как только игрок первый раз успешно подключается, игровой персонаж появляется на общей точке сбора (спаун). Это единственное место, где игровой мир предварительно генерируется сервером. В этот же момент клиентская часть смотрит в настройки, и ключевым параметром является дальность прорисовки. Измеряется она в чанках (область карты 16x16 и высотой в 256 блоков) Сколько чанков там указано, именно столько и будет запрошено у сервера.

На сервере хранится глобальная карта мира, и если в ней еще нет сгенерированных блоков в точке появления игрового персонажа, то сервер их динамически генерирует и сохраняет у себя. Мало того, что это требует больших вычислительных ресурсов, так еще и постоянно увеличивает размер карты мира. На одном из старейших анархических серверов 2b2t (2builders2tools) размер карты уже превысил 8 Tb, а граница мира проходит на отметке в 30 млн блоков. С этим сервером связаны тысячи историй, и он заслуживает отдельной статьи серии статей.

Генерация мира вокруг одного игрока — не проблема. Генерация мира вокруг сотни игроков вызовет незначительные тормоза сервера на протяжении короткого времени, после чего нагрузка снизится. Генерация мира на дальность прорисовки клиента вокруг тысячи игроков уже способна «уронить» сервер и повыбрасывать с него всех клиентов по таймауту.

В серверном ПО имеется такое значение, как TPS (Ticks per Server — тактов в секунду). Штатно 1 такт равен 50 мс. (1 секунда реального мира равна 20 тактам игрового мира). Если обработка одного такта вырастет до 60 секунд — серверное приложение будет закрыто, выкинув всех игроков.

Выход — ограничить мир определенными координатами и выполнить предварительную генерацию блоков. Тем самым мы снимаем необходимость динамической генерации в процессе игры, и серверу будет достаточно прочитать уже существующую карту. Оба вопроса решаются одним-единственным плагином WorldBorder.

Проще всего задать границу мира в виде окружности относительно точки спауна (хотя можно ее сделать любой формы) одной командой:


Если игровой персонаж попытается пересечь границу, то будет отброшен на несколько блоков назад. Если это проделать несколько раз за ограниченное время, то нарушитель будет принудительно телепортирован на точку спауна. Предварительная генерация мира выполняется еще проще, командой:


Поскольку данное действие потенциально может затронуть игроков, находящихся на сервере, не забудьте подтвердить выполнение:


В общей сложности на то, чтобы сгенерировать мир радиусом в 5000 блоков (

40 млрд блоков) ушло примерно 2 часа на процессоре Intel® Xeon® Gold 6240. Поэтому, если хотите запустить прегенерацию большей карты, учитывайте, что этот процесс займет приличное количество времени, а TPS сервера будет серьезно снижено. Кроме того, помните, что даже радиус в 5000 блоков потребует примерно 2 Гб места на дисковом накопителе.

Несмотря на то, что крайняя версия плагина была разработана для Minecraft версии 1.14, опытным путем выяснено, что она прекрасно работает и на последующих версиях. Полный список команд с пояснениями доступен на форуме плагина.

Проблемные блоки

Разновидностей блоков в Minecraft великое множество. Однако мы бы хотели остановить внимание читателей на таком блоке, как TNT. Как следует из названия, этот блок представляет собой взрывчатку (примечание редакции — это игровой предмет виртуального мира и ничего с настоящими ВВ этот предмет не имеет). Его особенность такова, что в момент активации на него начинает действовать сила гравитации. Это заставляет сервер обсчитать все координаты, если в этот момент блок начинает падать.

Если блоков TNT несколько, то детонация одного блока вызывает детонацию и включение гравитации у соседних блоков, разбрасывая их во все стороны. Вся эта красивая механика на стороне сервера выглядит как множество операций по подсчету траектории каждого из блоков, а также взаимодействия с соседними блоками. Задача крайне ресурсоемкая, что легко может проверить каждый. Сгенерируйте и подорвите куб из блоков TNT, размером хотя бы 30x30x30. И если вы думали, что у вас хороший мощный игровой компьютер, то сильно заблуждались ;)


Подобный «эксперимент» на сервере с Intel® Xeon® Gold 6240 привел к серьезной «просадке» TPS и 80% нагрузке на CPU в течение всего времени детонации блоков. А следовательно, если кто-либо из игроков сможет проделать подобное, то проблема с производительностью затронет всех находящихся на сервере игроков.

Еще более жесткий вариант — Кристаллы Края. Если TNT все же взрывается последовательно, то Кристаллы Края детонируют все одновременно, что в теории может вообще остановить работу серверного приложения.

Избежать этого сценария можно, только полностью запретив использование данных блоков в игровом мире. Например, с помощью плагина WorldGuard. Обратите внимание, что сам по себе этот плагин не работает без другого плагина WorldEdit. Так что устанавливаете вначале WorldEdit, а затем WorldGuard.

Виды серверов

Самым простым вариантом является сервер, встроенный в клиент игры. Создали мир, нажали на одну кнопочку, и вот сервер стал доступен по локальной сети. Никакой серьезной нагрузки такой вариант выдержать не может, а поэтому мы не будем его даже рассматривать.

Vanilla

Компания Mojang Studios распространяет серверную часть игры в виде Java-приложения бесплатно на официальном сайте. Это позволяет создать свой собственный выделенный сервер и персональный мир, сделав его доступным для подключения из любой точки планеты. Для тех, кто делает это впервые, есть отличный туториал, доступный в соответствующей игровой Wiki.

У этого подхода есть один серьезный недостаток, а именно — отсутствие возможностей «из коробки» подключать плагины, расширяющие функционал сервера и позволяющие не только автоматизировать многие процессы, но и оптимизировать производительность. Кроме того, у официального сервера достаточно большое потребление оперативной памяти на каждого подключенного игрока.

Bukkit

Созданное энтузиастами на базе Vanilla-версии серверное приложение Bukkit значительно расширяло возможности игры за счет поддержки плагинов и модов (модификаций). Оно позволило не только добавлять в игровой процесс новые блоки, но и выполнять различные манипуляции, недоступные ванильному ПО. Что интересно, памяти это приложение требовало значительно меньше.

Установить Bukkit не составляет особого труда, соответствующая инструкция есть на ресурсе GamePedia. Но это не имеет смысла, так как с 2014 года команда Bukkit распалась, разработчики проекта стали сотрудниками Mojang Studios, а репозиторий заброшен. Таким образом, Bukkit фактически мертв, и имеет смысл обратить внимание на два следующих проекта.

SpigotMC

Для облегчения жизни разработчиков плагинов была необходимость в API для взаимодействия с игровым миром. Именно эту задачу и решили создатели Spigot, взяв за основу ядро Bukkit и переработав его для достижения лучшей надежности и производительности. Тем не менее, Git-репозиторий проекта был заблокирован в связи с Законом об авторском праве в цифровую эпоху (DMCA), и скачать оттуда исходники невозможно.

На текущий момент SpigotMC активно развивается и используется. Он поддерживает все плагины, созданные под Bukkit, однако с ним обратно не совместим. Чтобы обойти запрет DMCA Takedown, был придуман элегантный способ под названием BuildTools. Этот инструмент избавляет от необходимости дистрибуции скомпилированного приложения и позволяет пользователям выполнить компиляцию Spigot, CraftBukkit и Bukkit из исходного кода. Все это делает запрет DMCA бесполезным.

PaperMC

Казалось бы, все круто, и Spigot стал прекрасным вариантом. Но некоторым энтузиастам этого показалось мало, и они запилили свой собственный форк Spigot «на стероидах». На странице проекта ключевым достоинством указано, что “It's stupid fast”. Развитое коммьюнити позволяет оперативно решать возникающие вопросы, а расширенное API — делать интересные плагины. Запустить PaperMC можно одной простой командой, приведенной в документации.

С совместимостью у PaperMC все прекрасно, так что написанные плагины под SpigotMC легко заработают и на PaperMC, но без официальной поддержки. Обратная совместимость со SpigotMC также присутствует. Теперь, когда мы перечислили различные варианты создания сервера, перейдем к тем проблемам производительности, которые могут возникать.

Uses of zero-ticking [ ]

Since a comparator does not react to a 0-tick pulse and the pulse will lose its effects if it goes through a repeater, most 0-tick uses involve pistons. Pistons can be used to move blocks before the game has a chance to react as it normally would.

Embedding entities [ ]

Normally, when you power a sticky piston with a block on it towards an entity, and the entity has enough room to move, it will be pushed by the block. Zero-ticking a block places it over the space occupied by the entity without moving the entity. This can be used decoratively, e.g. creating 1-block glass 'display cases' with entities (mobs, armor stands) inside, or offensively, causing mobs to suffocate if using solid blocks, or in contraptions where you can overlay an armor stand and a solid block within the same space, e.g. for vertical signal transport using piston and tripwire, crossing with horizontal transport through the block. This can easily be done by placing a button on the side (not the back) of a piston. This will power the piston and the piston powering will instantly break the button causing a 0-tick pulse.

Fast block farms [ ]

Farms such as tree farms, cobblestone farms, and basalt farms generate blocks. Using 0-tick pistons, one can create quick harvesting cycles, as well as quickly moving the blocks from the farm output into a TNT blast chamber or wither cage.

Zero-tick plant farms [ ]

These farms are patched and no longer function as of Java Edition 1.16.

The farms worked by exploiting certain buggy behavior. When the block supporting a plant is instantly replaced with another of the same block, the plant forcibly receives a random tick. Chorus Plants require only a single random tick to grow, plants like Cactus and Sugar Cane require 16 random ticks to grow, and still other plants react differently to random ticks. In essence, the exploit allows the plants to grow and be farmed at very high speeds for relatively low build cost.

The zero-tick plant growth exploit was observed October 2016 by ToseRedstone. The corresponding bug MC-113809 was documented on the bug tracker February 2017. The bug was accidentally patched in snapshot 18w06a, and it was officially patched in snapshot 20w12a ahead of release 1.16.

Scheduled tick [ ]

Some blocks can request a tick sometime in the future. These "scheduled ticks" are used for things that have to happen in a predictable pattern—for instance, redstone repeaters schedule a tick to change state in Java Edition, water schedules a tick when it needs to move.

As a part of a game tick, each block position that has requested a scheduled block tick gets ticked on the specific game tick.

In Java Edition, there are two types of scheduled ticks: block ticks and fluid ticks. Block ticks are executed first based on priority, and then based on scheduling order. A lower value for priority results in earlier execution during the scheduled tick phase. If a redstone repeater is facing the back or side of another diode, its block tick will have a priority of -3. If a redstone repeater is depowering, it will have a priority of -2. Otherwise, the repeater will have a priority of -1. If a redstone comparator is facing the back or side of another diode, it will have a priority of -1. All other block ticks will have a priority of 0. Then, each block with a scheduled fluid tick will tick. Fluid ticks do not use priorities and are only ordered based on scheduling order.

In Java Edition, the maximum number of scheduled ticks per game tick is 65,536. In Bedrock Edition, the maximum number of scheduled ticks in a chunk per game tick is 100.

Заключение

Грамотное управление игровым сервером — задача не из простых. Сложности и снижение производительности будут поджидать на каждом шагу, особенно если не брать в расчет саму механику игрового процесса. Предусмотреть все невозможно, ведь игроки порой бывают очень изобретательны в попытках заставить сервер выполнить то, для чего он не был предназначен. Только разумный баланс между рисками и устанавливаемыми ограничениями позволит серверу работать в непрерывном режиме и не снижать свою производительность до критичных значений.

На карантине некоторые наши сотрудники соскучились по любимым офисам и решили воссоздать их внутри Minecraft. У вас тоже есть шанс заглянуть к нам в гости, не рискуя своим здоровьем и не тратя время на дорогу.

Minecraft Wiki

The Minecraft Wiki is no longer considered as official by Microsoft and therefore several changes are required to be made, including to the wiki's logo. Please read this announcement for more information.

Introduction [ ]

When a redstone signal is sent through a pulse limiter, it shortens the pulse. When the pulse is shortened enough, strange behaviors arise. If a sticky piston is powered by a 2-tick pulse, it will start extending but after two ticks, the piston will drop its block and start retracting. If a sticky piston is powered by a 1-tick pulse, the same behavior will happen, but instead of happening after 2 ticks it will only happen after one tick.

Zero-tick pulse generation [ ]

All 0-tick pulses are created by powering a redstone line, and then using pistons to remove the power source later in the tick.

Producing a 0-tick pulse using tile tick priorities


One method of doing so is using tile tick priorities. Since comparators are processed in a tick later than repeaters, one can generate a 0-tick pulse by powering a redstone line using this behavior. In this example, redstone repeater is used to power the output line, and a comparator is used to power a piston which will remove the block in front of repeater to depower the line. Since the comparator always powers after repeaters, the redstone line will always turn off after it turns on, creating a reliable 0-tick pulse. The advantage to this 0-tick generator is that it's 0-tick pulse is earlier in a tick relative to 0-tick pulses generated through other methods.


A 0-tick generator that uses budded pistons

Another common method of generating 0-tick pulses is to use budded pistons. As budded pistons only retract when updated, this can be used to control which order pistons move and therefore controlling the order in which a redstone line is powered then unpowered. One example is to have a redstone line that directly powers a sticky piston and bud-poweres two other sticky pistons. The piston directly powered by the redstone line will have a block on its face, and the last piston in the chain will have a redstone block on its face. A second redstone line will be at the bottom which is the output; it will be powered by the piston with a redstone block and is cut off by the solid block. When the redstone line on top is powered, nothing will happen. But when the input is depowered, then a 0-tick pulse is created. The redstone line will depower, but only cause the piston that is directly powered to start retracting. This will uncut the output line, turning it on. When this piston retracts it will then update the piston in the middle, causing that one to retract which will then cause the last piston to start retracting, which will remove power from the line.

Zero-tick chaining [ ]

Within a tick, 0-tick pulses happen , but 0-tick pulses can happen after other 0-tick pulses while still being in the same tick. This is known as 0-tick chaining where two or more 0-tick pulses are activated in a row.


0-tick chaining that relies on the fact that tileticks process before block events

One method of 0-tick chaining is to utilize the fact that tileticks such as repeaters and comparators will process in a tick before block events such as piston extensions and retractions. In the shown example, when the input is powered, the quartz block will be 0-ticked by both pistons causing it to instantly move two blocks, ending up above the diamond block. The 0-tick generator to the right makes use of tileticks and will activate before the 0-tick generator on the left, which uses block events. This method of chaining is very compact, but it comes at a downside that this method can only be used once per chain.


0-tick chaining that uses a long update chain before the second 0-tick generator

Another method of chaining is to utilize the fact that update chains can be used to manipulate the order in which things are processed in a tick. In the shown example, there are two 0-tick generators. The one on the left has an update chain before powering it, while the one on the right is directly powered. When the input is depowered, the 0-tick generator on the right will activate first as it is directly powered causing its output piston to instantly drop its block. While this is happening, the update chain is retracting. Then, the 0-tick generator on the left will will activate causing its output piston to instantly drop its block.

Zero-tick repeaters [ ]


The three most common forms of a 0-tick repeater

A regular redstone repeater can't be used to refresh the signal of a 0-tick pulse as they would extend the pulse to a length of 2 ticks. So one must use a 0-tick repeater. A 0-tick repeater works by receiving an input as a 0-tick pulse, which will 0-tick a redstone block that is inside of the 0-tick repeater. And right after that, the redstone block is 0-ticked back to it's original position. This can be used to repeat 0-tick signals, but one must note that they add block event delay.


Using a 0-tick repeater to chain 0-tick pulses. Powering the input will cause the quartz block to move on top of the diamond block.

One can also use 0-tick repeaters as a method of 0-tick chaining. This is possible because 0-tick repeaters add block event delay. 0-tick repeaters are very useful because they can be used to chain signals created by 0-tick clocks, as only 0-tick repeaters have the ability to reset fast enough.

Creating a zero-tick clock [ ]


This is a top down view of the clock without a block in it.

A 0-tick clock is made by putting two 0-tick block pushers facing each other and pushing a block between themselves, one line will appear on, while the other appears off, each has unique behavior, the "off" line is BUD-proof, while the "on" line allows for BUD pistons, and to set which is which, simply place a lever on the torch under the side you wish to be "on" and flip it twice, also this lever can turn it off.

Another thing to note is that if it is built right, the block WILL NOT seem to move while the piston heads will glitch through it, and the redstone lines WILL NOT pulse at all.


This is a top down view of the clock with a block in it.


Side view of a running 0-tick Clock

Tutorials/Zero-ticking

Bugs of this nature may be fixed at any time without warning. When this happens, the contraption will cease to work.
Use at your own risk.

This tutorial seeks to teach the player how to make a redstone signal turn on and off in the same tick, go over how this could be used, particularly with its uses on pistons.

Оптимизация сервера Minecraft


В нашем блоге мы уже рассказывали, как создать свой сервер Minecraft, однако с тех пор прошло 5 лет и многое поменялось. Делимся с вами актуальными способами создания и оптимизации серверной части столь популярной игры.

За свою 9-летнюю историю (если считать от даты релиза) Minecraft заработал потрясающее количество поклонников и хейтеров как среди обычных игроков, так и среди гиков. Простая концепция мира из кубиков превратилась из обычного развлечения в универсальную среду для общения и создания различных объектов из реального мира.

Помимо строительства, в игре есть возможность создавать логические схемы, которые позволяют реализовывать полноценные алгоритмы внутри Minecraft. На YouTube полно весьма впечатляющих роликов, где люди, приложив огромное количество сил и потратив множество времени, создали копию того или иного электронного устройства или построили детальную копию существующих и вымышленных архитектурных сооружений. Все ограничивается лишь фантазией геймера и возможностями игровой вселенной.

Но не будем дальше говорить о том, что именно игроки создают, а посмотрим на серверную часть приложения и осветим проблемы (порой весьма сложные), которые могут возникнуть в процессе работы под нагрузкой. Сразу оговоримся, что речь пойдет только о Java Edition.

Game process [ ]

In Java Edition, in each game loop the following actions are processed in order:

  • Functions with tick or load tag are executed
  • Each dimension is ticked in order of overworld, the nether, and the end. For each dimension:
    • The time is sent to the client
    • The world border is updated
    • Weather logic
    • Player sleeping logic
    • If this dimension is overworld:
      • The game-time and day-time increase
      • Scheduled functions are executed
      • Chunk info is sent to the client
      • Chunk tick logic
      • Scheduled block ticks
      • Scheduled fluid ticks

      Contents

      Contents

      Game tick [ ]

      A gametick is where Minecraft's game loop runs once. The game normally runs at a fixed rate of 20 ticks per second, so one tick happens every 0.05 seconds (50 milliseconds, or five hundredths of a second), making an in-game day lasts exactly 24000 ticks, or 20 minutes. However, if the computer is unable to keep up with this speed, there are fewer game ticks per second (TPS). As the vast majority of actions are timed based on tick count rather than on wall clock time, this means that many things take longer on a slower computer.

      A statistic related to ticks per second (TPS) is milliseconds per tick (MSPT), the time a server actually uses to compute a tick. The TPS can be maintained at 20 only if the MSPT is no higher than 50. The following often contribute to server-side lag:

        constantly try to search for items above them. Cover with any item with an inventory slot or a composter, as this stops the checks for items. Alternatively, use water flow-based transport which is faster in bulk.
      • Redstone machinery. Redstone components, especially redstone dust cause excessive amounts of block updates and lag. Disabling redstone contraptions and clocks when not in use can help mitigate this. AI. Use torches to guide hostile mob spawning. Use more efficient farms for animals.

      Помогите с сервером

      А Avg Tick: 17,577 ms это ответ сервера в милисекундах. Так вот я хочу выделить этому серверу больше памяти для плавной работы.

      Я проделывал такую процедуру, но с клиентом. И выдал моему клиенту 2 гб оперативной памяти.


      Вот такую команду я использовал для увеличения памяти в клиенте: -Xincgc -Xmx1024m -cp

      И зачем он тебе, их миллионы, если не миллиарды, и ты думаешь на твоём будут играть?

      Скажи пожалуйста в чём вопрос? , Какой сервер. скажи нужную информацию для операций. . .и я помогу.

      Если не ты администратор сервера, ты никак не увеличишь. там твоя виртуальная машина на сервере, попроси админа главного сервера пусть увеличит.

      Redstone tick [ ]

      In Java Edition, redstone ticks are actually not a "real" thing, but a term created by the community to make redstone easier since most redstone components have delays of multiples of 2 game ticks.

      Читайте также: