что такое mixin out minecraft

Миксины для Чайников! Практика.

что такое mixin out minecraft. Смотреть фото что такое mixin out minecraft. Смотреть картинку что такое mixin out minecraft. Картинка про что такое mixin out minecraft. Фото что такое mixin out minecraft

Миксины в основном предназначены для объемных проектов, меняющих много исходного кода. Но они существенно облегчают жизнь, если грамотно настроить рабочее пространство и знать как их использовать. С их помощью можно с легкостью изменить логику работы ванильных механик и добавить свои. Также миксины могут стать интересной альтернативой IEEP и Capability от Forge.

Миксины лучше писать только на Java. На других языках (scala, kotlin) писать не рекомендуется по причине того, что будет сложно реализовывать некоторые хуки, да и с java байткодом понятнее всего взаимодействовать, используя java.

И это далеко не все )

Начало работы
Большинство примеров и действий подкреплены кодом из репозитория. GlassSpirit/JustMixins

Скопируйте проект-пример для вашей версии из репозитория

Основные изменения в build.gradle
Предпочтительно за основу взять build.gradle нужной вам версии из репозитория.

В примере на 1.7 используется форк ForgeGradle 1.2, позволяющий использовать последние версии сборщика Gradle (изначально он работает только с Gradle 2.8, который даже уже не поддерживается IntelliJ IDEA). Это позволяет нам не проводить танцы с бубном для смены IDEA JRE и без проблем пользоваться новыми возможностями.

В примере на 1.12 и 1.15 используется ForgeGradle 4+ (изначально для работы с 1.12 требовался ForgeGradle 2.3). Он позволяет нам использовать систему Миксинов и плагин MixinGradle последних версий.

Запускать и дебажить мод следует через сгенерированные скрипты запуска.
На версиях 1.12+ в раздел «runs» следует добавить дополнительные аргументы запуска:

Запуск мода после сборки
Версии 1.7 и 1.12.

Для того, чтобы система миксинов начала работать, необходимо добавить и развернуть саму либу миксинов, которой изначально нет на клиенте/сервере. В среде разработки это происходило за счет зависимости от Mixins и аргументов запуска.
Вариантов решения два: либо засовывать систему миксинов в каждый мод, использующий ее, либо поставить мой вспомогательный мод JustMixins
Правильнее всего будет поставить нормальный мод для инициализации миксинов (Grimoire для 1.7.10 и MixinBootstrap для 1.12+).

Версии 1.15+.
Версии 1.15 и 1.16 уже включают в себя систему миксинов, так что сторонних действий не требуется.

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

Простейшее дополнение существующих методов (хуки)
Ну вот мы и добрались до самого интересного. Система миксинов в сочетании со средой разработки и плагином Minecraft Dev позволяет полностью избавить мододела от бесполезной работы по поиску опкодов, линий для вставки кода, определения параметров и прочей ереси, с которой сталкивались те, кто работал с хуклибой, а не то и с кормодами.
Разберем же наиболее используемые приемы! Продолжим наш пример с эссенцией. Да, она теперь есть у игрока, но… Она не сохраняется после выгрузки игрока из памяти, да и вообще не изменяется! Исправим же это =)

Готово! Теперь, когда Minecraft будет вызывать эти методы при сохранении и загрузке игрока, он также будет сохранять и загружать значения нашей эссенции.

Использование новых методов класса
Для красоты примера добавим немного логики нашему моду-примеру. Пусть эссенция будет необходима для того, чтобы ломать блоки, а зарабатываться она будет при нанесении урона живым существам (приветик моей шизе).

Чтобы в использовать новые поля и методы, достаточно просто сделать каст объекта EntityPlayer к нашему интерфейсу (как ни странно, компилятор Java позволяет это сделать, даже если изначально класс этот интерфейс не реализует).
Создадим слушатель событий на эти два ивента:

Также для доступа к полям и методам можно использовать рефлексию, но делать этого я вам крайне не советую…

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

Подробнее про магию
В этом разделе подробнее разберем основные возможности и подводные камни системы миксинов.

Простейшее использование
Вот простейший пример использования при инъекции в void метод без параметров:

В приведенном выше примере обработчик проверяет, установлена ли позиция в (0, 0), и если условие выполнено, вместо стандартного поведения целевого метода он выполняет некоторую логику, помечая обратный вызов как завершенный, чтобы заставить целевой метод (setPos) завершиться сразу после завершения обработчика.

Больше информации про Inject тут.
SpongePowered/Mixin

Больше информации о точках внедрения тут, а также явадоках к ним.
SpongePowered/Mixin.

Источник

Что такое mixin в майнкрафт

что такое mixin out minecraft. Смотреть фото что такое mixin out minecraft. Смотреть картинку что такое mixin out minecraft. Картинка про что такое mixin out minecraft. Фото что такое mixin out minecraft

Миксины в основном предназначены для объемных проектов, меняющих много исходного кода. Но они существенно облегчают жизнь, если грамотно настроить рабочее пространство и знать как их использовать. С их помощью можно с легкостью изменить логику работы ванильных механик и добавить свои. Также миксины могут стать интересной альтернативой IEEP и Capability от Forge.

Миксины лучше писать только на Java. На других языках (scala, kotlin) писать не рекомендуется по причине того, что будет сложно реализовывать некоторые хуки, да и с java байткодом понятнее всего взаимодействовать, используя java.

Скопируйте проект-пример для вашей версии из репозитория

Основные изменения в build.gradle
Предпочтительно за основу взять build.gradle нужной вам версии из репозитория.

В примере на 1.7 используется форк ForgeGradle 1.2, позволяющий использовать последние версии сборщика Gradle (изначально он работает только с Gradle 2.8, который даже уже не поддерживается IntelliJ IDEA). Это позволяет нам не проводить танцы с бубном для смены IDEA JRE и без проблем пользоваться новыми возможностями.

В примере на 1.12 и 1.15 используется ForgeGradle 4+ (изначально для работы с 1.12 требовался ForgeGradle 2.3). Он позволяет нам использовать систему Миксинов и плагин MixinGradle последних версий.

Добавились репозиторий Sponge, плагин MixinGradle (не для 1.7), зависимость от Mixins необходимой версии (для 1.7 самой последней является 0.7.11, версии выше работают крайне нестабильно), процессор аннотаций Mixins (проверяет правильность написанных миксинов, генерирует карты имен).
Для версии 1.7 нет плагина MixinGradle, так что некоторые действия придется дописать.
Не забудьте изменить имена mixinSrg и mixinRefMapName под ваш мод.
Для того, чтобы мод определялся как миксин, добавляем информацию о миксине в MANIFEST.MF.

Запускать и дебажить мод следует через сгенерированные скрипты запуска.
На версиях 1.12+ в раздел «runs» следует добавить дополнительные аргументы запуска:

Запуск мода после сборки
Версии 1.7 и 1.12.
Для того, чтобы система миксинов начала работать, необходимо добавить и развернуть саму либу миксинов, которой изначально нет на клиенте/сервере. В среде разработки это происходило за счет зависимости от Mixins и аргументов запуска.
Вариантов решения два: либо засовывать систему миксинов в каждый мод, использующий ее, либо поставить мой вспомогательный мод JustMixins
Правильнее всего будет поставить нормальный мод для инициализации миксинов (Grimoire для 1.7.10 и MixinBootstrap для 1.12+).

Версии 1.15+.
Версии 1.15 и 1.16 уже включают в себя систему миксинов, так что сторонних действий не требуется.

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

Простейшее дополнение существующих методов (хуки)
Ну вот мы и добрались до самого интересного. Система миксинов в сочетании со средой разработки и плагином Minecraft Dev позволяет полностью избавить мододела от бесполезной работы по поиску опкодов, линий для вставки кода, определения параметров и прочей ереси, с которой сталкивались те, кто работал с хуклибой, а не то и с кормодами.
Разберем же наиболее используемые приемы! Продолжим наш пример с эссенцией. Да, она теперь есть у игрока, но… Она не сохраняется после выгрузки игрока из памяти, да и вообще не изменяется! Исправим же это =)

Готово! Теперь, когда Minecraft будет вызывать эти методы при сохранении и загрузке игрока, он также будет сохранять и загружать значения нашей эссенции.

Использование новых методов класса
Для красоты примера добавим немного логики нашему моду-примеру. Пусть эссенция будет необходима для того, чтобы ломать блоки, а зарабатываться она будет при нанесении урона живым существам (приветик моей шизе).

Чтобы в использовать новые поля и методы, достаточно просто сделать каст объекта EntityPlayer к нашему интерфейсу (как ни странно, компилятор Java позволяет это сделать, даже если изначально класс этот интерфейс не реализует).
Создадим слушатель событий на эти два ивента:

Также для доступа к полям и методам можно использовать рефлексию, но делать этого я вам крайне не советую…

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

Подробнее про магию
В этом разделе подробнее разберем основные возможности и подводные камни системы миксинов.

Простейшее использование
Вот простейший пример использования при инъекции в void метод без параметров:

В приведенном выше примере обработчик проверяет, установлена ли позиция в (0, 0), и если условие выполнено, вместо стандартного поведения целевого метода он выполняет некоторую логику, помечая обратный вызов как завершенный, чтобы заставить целевой метод (setPos) завершиться сразу после завершения обработчика.

Больше информации про Inject тут.
SpongePowered/Mixin

Больше информации о точках внедрения тут, а также явадоках к ним.
SpongePowered/Mixin.

MixinBootstrap [1.17.1] [1.16.5] [1.15.2] [1.14.4] [1.12.2]

что такое mixin out minecraft. Смотреть фото что такое mixin out minecraft. Смотреть картинку что такое mixin out minecraft. Картинка про что такое mixin out minecraft. Фото что такое mixin out minecraft

Моды требующие данную библиотеку:
Immersive Portals с загрузчиком Minecraft Forge, а последнее время таких модов стало в разы больше.

Mixin 0.7-0.8 Compatibility [1.12.2]

что такое mixin out minecraft. Смотреть фото что такое mixin out minecraft. Смотреть картинку что такое mixin out minecraft. Картинка про что такое mixin out minecraft. Фото что такое mixin out minecraft

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

Mixin Bootstrap 1.15.2

что такое mixin out minecraft. Смотреть фото что такое mixin out minecraft. Смотреть картинку что такое mixin out minecraft. Картинка про что такое mixin out minecraft. Фото что такое mixin out minecraft

MixinBootstrap – это библиотека, которая содержит неофициальный и временный способ загрузки Mixin в среду MinecraftForge. Не ожидайте поддержки от разработчика. Она требуется для работы:

Модификацию разработал LX_Gaming. Исходный код проекта лежит на Github.

Как установить мод:

1.14.4\1.15.1\1.15.2: mixinbootstrap-1.0.0.jar [1018,31 Kb]
1.14.4\1.15.2 (v0.1) : mixinbootstrap-1.0.1.jar [1 Mb]
1.14.4\1.15.2 (v0.2) : mixinbootstrap-1.0.2.jar [1,01 Mb]
1.12.2\1.14.4\1.15.2\1.16.1 (v0.3) : mixinbootstrap-1.0.3.jar [1,01 Mb]
1.12.2\1.14.4\1.15.2\1.16.x (new v0.5) : mixinbootstrap-1.0.5.jar [1,02 Mb]
1.12.2\1.14.4\1.15.2\1.16.5\1.17.1 (new v1.1) : _mixinbootstrap-1.1.0.jar [1,07 Mb]

Источник

Mixin is a framework for modifying Java bytecode. Through Mixin you will be able to modify the code of Minecraft, Forge, and even other mods. While Mixin can be very useful it is often best to treat it as a last resort or as a temporary solution. If your change would be useful to more than one mod it should probably be a Forge PR instead. It is also important to keep in mind that using Mixin on someone else’s mod can be very offensive and is also prone to regular breaking changes.

This tutorial is meant to be a basic introduction to using Mixin in a Forge environment. For in depth information about Mixin refer to the Mixin Javadocs and the official documentation.

In this tutorial we will cover

Mixin Setup

Mixin requires a bit of setup and configuration before you can use it. The first bit of setup is adding the MixinGradle plugin to your Gradle build script. This is done by defining the plugin as a classpath dependency in the buildscript section of your build.gradle file. This plugin is not available by default so you will also need to add their maven repo.

The next step is to create a Mixin config file. This file is used by Mixin to locate your changes and also to define various environmental settings. This file is commonly named modid.mixins.json and is placed in the base of your mod’s resources folder. The structure of this file is fairly self explanatory. The main thing to note is that the package refers to the base package for where your mixins will be. This package will have certain protections applied so it is often essential to separate it from the rest of your code. This is commonly done by using mixin as a subpackage name.

If you followed these steps properly your mod should now be set up to use mixins. For examples of working mods you can check out Open Loader and Extra Tags

Gradle 5+ & Annotation Processors

If you’re using Gradle 5 or newer you will need to add SpongeGradle as an annotation processor. This is a mandatory step as this is required to build a refmap file for your mixin targs, allowing them to work outside of your development environment. This is done by making a simple addition to your dependencies block.

Modifying Code with Mixin

The main benefit of Mixin is that it allows you to write simple changes that look and feel like normal code. In this example our goal will be to change ItemEntity to make all dropped items with the Fire Protection enchantment immune to fire and lava damage. The first step is to create a new class in your mixin package. On top of the normal class declaration you define an @Mixin annotation and pass the target class as the value.

Once you have created the class go back to your modid.mixin.json file and add the class name to the mixins array.

The next step is to identify the code you want to change. In this case I am changing attackEntityFrom(DamageSource source, float amount) in ItemEntity. Once you know your target you will recreate the method in your Mixin class. The new method should be modified to be private and to remove the return type if any. Mixin requires these changes for safety and simplicity reasons. You will also need to add a CallbackInfo as the last parameter, or a CallbackInfoReturnable if the method had a return type. This new parameter acts as a surrogate for the traditional return of the method.

We now need to add one of the Mixin annotations to this method. While there are several options available the @Inject annotation is primarily used. This will allow you to inject your code at various parts of the target method’s execution. This annotation has two required values.

If you run the game now you will see that items can not be destroyed by any damage source. We want to only prevent destruction if the damage source is fire and the item has Fire Protection. We already have the source as a method parameter, but how can we get the ItemStack? This is where shadows come into play. A shadow is a placeholder field or method which is replaced by the real thing at runtime. To create a shadow you simply recreate the field or method in your Mixin class and apply the @Shadow annotation. You can then use this method within your Mixin.

Tips, Best Practices, limitations

What is the overwrite annotation, is it safe to use?
The overwrite annotation will completely replace the target code with your version of the method. This can be a very powerful feature however compatibility issues will come up if you decide to use it. I prefer to use Inject and then return early instead of overwriting although in some cases you may want the compatibility errors if the mods are truly incompatible.

Can I modify a constructor?
Modifying the constructor is not supported. In some situations there are some hacks you can use to do this however it is generally not a good idea to do so.

Источник

Что такое mixin out minecraft

Mixin is a trait/mixin and bytecode weaving framework for Java using ASM

Latest commit

Git stats

Files

Failed to load latest commit information.

README.MD

Mixin is a trait/mixin framework for Java using ASM and hooking into the runtime classloading process via a set of pluggable built-in or user-provided services. Built-in services currently support Mojang’s LegacyLauncher system, though this is deprecated in favour of ModLauncher by cpw, which has greater extensibility and has support for Java 8 and later.

The main documentation for Mixin can be found in the Wiki.

Additional documentation for individual features and annotations can be found in the extensive Javadoc. For additional help use the channel #mixin on the Sponge Discord Server.

Mixin binaries are available via Jenkins and are published to the following maven repositories:

If you are using Mixin in a Minecraft Forge project then the MixinGradle plugin can be used to simplify the configuration of the Mixin Annotation Processor. It provides a simple syntax for configuring the Mixin AP for your project, see the MixinGradle README for how to configure MixinGradle.

Integration with Eclipse

When developing using Mixin, you can use the Mixin Annotation Processor within Eclipse to provide context-sensitive errors and warnings to help you more easily troubleshoot your mixins. To do so:

Integration with IntelliJ IDEA

Enhanced functionality for working with Mixin in IntelliJ IDEA is available via the Minecraft Development for IntelliJ IDEA plugin developed by DemonWav.

Specifying the minVersion property in your configurations is extrememly important. The following version history can be used to determine when features were introduced (and sometimes when major bugs are squashed) in order to help you determine which minVersion you should specify.

About

Mixin is a trait/mixin and bytecode weaving framework for Java using ASM

Источник

Mixin 0.8.4

Sometimes new Mixin releases present an opportunity to discuss different aspects of Mixin which are not covered in detail in the docs, or limitations which exist are not well understood by mixin authors, leading them to experience behaviour they aren’t anticipating. The topic of the 0.8 series has definitely bounced around the topic of Locals, in particular CallbackInjector ‘s unique ability to capture locals, so I will discuss some of the changes to Locals later in these notes. But first, the headlines:

Features

Minecraft 1.17, ModLauncher 9, Java 16, Oh My!

Minecraft 1.17 represents a significant jump in technology, adopting as it does Java 16, a big jump from the previous Java 8. Those in the modding community who remember the jump to Java 8 from Java 6 will anticipate something of what that means. Mixin has been for some time rooted in that Java 8 land because the primary consumers are using Java 8 and and (in some cases) Java 6, so supporting newer language features hasn’t been a high priority.

With the release of Mixin 0.8.4, the core functionality of Mixin now supports up to Java 13 (cheating a little since nothing of note changed between Java 11 and 13), the missing piece of the puzzle being nesting. Mixins applied to inner classes will now be properly added to the existing nest.

The internal version of ASM has been bumped to 9.x to track ModLauncher, which now provides access to class version literals up to Java 18, which have been duly contributed to the CompatibilityLevel enum, along with associated language feature flags. Records and sealed classes are now on the radar for support, but will not be immediately available as things are ahead of them in the feature queue.

Mixin itself is now built as as Java module, though classes in the final jar will still be compatible back as far as Java 8 without modification, Java 6 users will still need to compile from source.

Fixes and Improvements

Mixin 0.8.4 therefore represents the «what 0.8.3 should have been» release, and offers the promised improvements of the previous release, with fewer gotchas. Check out the release notes for 0.8.3 if you haven’t already, as they cover the major changes and bugfixes since 0.8.2.

Local Variables in Mixins

This brings us on to the bonus topic of today’s release notes: Locals.

Support for interacting with local variables has a long and storied past and has, during its tenure, overcome such obstactles as differing output from ASM in production vs. development. Yielding different results across different versions and platforms for ostensibly the same code. Failing to expose locals which seem intuitively in-scope at the capture point, and exposing others which shouldn’t be. Accidentally capturing locals added by Mixin itself. The list goes on. I can say that the 0.8 series of Mixin definitely represents a high point in the general functionality of local capture.

Those who have been on board the Mixin train for a long time have observed the growing pains of locals and treat it with the air of an unexploded bomb which might detonate at any moment, and they are justified in doing so. However I realise that I have been negligent in assuming that this feeling prevails and therefore failing to provide the appropriate caveats and warnings around the use of locals. This is especially true recently since the state of Locals is objectively quite good, and belies the dangers of change over time that still lurk beneath the surface.

So why, if it’s in such a good place, does it need to change at all?

I have two main goals for Locals in the long run:

The reason for the first should be obvious, authors of mixins should have a reasonable expectation of being able to capture variables which appear to be in-scope based on reading the decompiled source. This reduces development effort and makes for a better experience.

The second goal is the reason that things are still changing: reducing binary sensitivity is a tricky thing to achieve given that it conflicts with the third goal somewhat, this is where tuning the algorithm comes into play.

The algorithm used by Locals does a relatively simple scan of target methods from top to bottom, weaving knowledge gained from the LVT (either explicit or computed), the stack map frames, and LOAD and STORE opcodes in the method itself together to create a not unreasonable view of the available local variables at any point in the method. However, the weight given to different information sources is where the tunables come in, as the entire algorithm is essentially a hueristic which tries to blend sometimes conflicting accounts of what is available and where.

If you’re wondering why on earth different aspects of the method structure would disagree, and why there is no «universal truth» that can be easily reverse engineered from simply reading the bytecode, it’s important to understand that no part of the runtime actually needs to know the information we’re after, and the different mechanims in the bytecode (the instructions, the LVT and the stack map frames) have entirely different goals. The LVT is the closest thing we have to truth, and it’s not even required at runtime since it’s purely used for debugging. In fact in older versions of the game the LVT was stripped, and even to this day it is obfuscated.

Where am I going with this?

Mixin 0.8.3 and 0.8.4 represent changes to the locals algorithm which make it less leaky¹, however regressions reported after the release of 0.8.3 hinted that the leakiness was a useful characteristic in some cases, and justifiably so. Mixin 0.8.4 doesn’t turn the leakiness all the way back up to pre-0.8.3 levels but now uses a more intelligent algorithm to decide when to bring a variable back into scope which was previously axed, a kind of intelligent leak if you will.

Does this mean all injectors written with 0.8.2 will now work in 0.8.4? No, though fewer should break. Does it provide a good step towards more stable results in future versions of Mixin? I hope so.

Why Take This Approach?

In short, because stability of results allows Mixin to do more things with locals. I have, to date, been reluctant to expand local capture and interaction with locals (eg. via ModifyVariable ). This is because the unstable nature of locals means that interacting with the frame as a whole, or only a single variable, at least provides some safeguards in that if the frame doesn’t match what the code is expecting then it breaks quickly and predictably.

What’s Next

The next version of Mixin will be 0.8.5, which is specifically aimed at eliminating some of the pain points with selecting lambda methods to target, and limitations of some existing injectors when multiple mixins want to target the same instruction. As always, watch this space.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *