Jump to content

Recommended Posts

Posted (edited)

I'm currently working on an API for my mod which uses some events and Capabilities. An abstract class I made references my Main class. Should I include the Whole class in the api or should I cut everything but the references? Or in general what should I include into my Api.jar (and how can I create it)?

Edited by _Cruelar_

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Posted

Depends on what you're wanting to put into the API, but remember this is not a Java school. We're not here to tell you how to make API's, but I'd recommend you make people interact with interfaces. 

API's definition is basically this;

Spoiler

An application programming interface (API), in the context of Java, is a collection of prewritten packages, classes, and interfaces with their respective methods, fields and constructors. Similar to a user interface, which facilitates interaction between humans and computers, an API serves as a software program interface facilitating interaction.

 

If you want to make an API so other mods can add recipes to your mod's machines, you can. But that's really up to you. 

Please give a little more info about what the API should do, then I can give you some coding advice.

Posted

I have some capabilities that should be able to be used and one of the most important things an abstract class for handles most of the registry for the Results of my recipes. My biggest Problem is that it refers to my ItemStorage (ModItems) and my CreativeTabs which refer to a lot of other stuff which would result in including around 1/4 of my mod.

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Posted (edited)
6 minutes ago, _Cruelar_ said:

I have some capabilities that should be able to be used

Your mod has the capability, you don't have to put it in an API, other programmers can make their mod as a dependency of yours. But if you want to you can just move them into an API, but make sure to include it in your gradle buildfile so it compiles.

6 minutes ago, _Cruelar_ said:

abstract class for handles most of the registry for the Results of my recipes

what kind of recipes exactly

Edited by tebreca
Posted

Cooking pot Recipes out of my mod:

Spoiler

package com.cruelar.cruelars_triforcemod.recipes;

import com.cruelar.cruelars_triforcemod.Cruelars_Triforcemod_Core;
import com.cruelar.cruelars_triforcemod.init.ModItems;
import com.cruelar.cruelars_triforcemod.inventory.Cooking_Pot_Container;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.common.crafting.IRecipeFactory;
import net.minecraftforge.common.crafting.JsonContext;
import net.minecraftforge.fml.relauncher.ReflectionHelper;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.List;

public class CookingPotRecipes extends net.minecraftforge.registries.IForgeRegistryEntry.Impl<IRecipe> implements IRecipe {

    /** Is the ItemStack that you get when craft the recipe. */
    private final ItemStack recipeOutput;
    /** Is a List of ItemStack that composes the recipe. */
    public final NonNullList<Ingredient> recipeItems;
    private final String group;
    private int id;
    private final boolean isSimple;
    public static final Field container = ReflectionHelper.findField(InventoryCrafting.class,"eventHandler","field_70465_c");

    public CookingPotRecipes(String group, ItemStack output, NonNullList<Ingredient> ingredients,int id)
    {
        this.group = group;
        this.recipeOutput = output;
        this.recipeItems = ingredients;
        boolean simple = true;
        for (Ingredient i : ingredients)
            simple &= i.isSimple();
        this.isSimple = simple;
        this.id=id;
    }

    @Override
    public boolean matches(InventoryCrafting inv, World worldIn) {
            int ingredientCount = 0;
            net.minecraft.client.util.RecipeItemHelper recipeItemHelper = new net.minecraft.client.util.RecipeItemHelper();
            List<ItemStack> inputs = Lists.newArrayList();
            List<ItemStack> inputs2;
            for (int i = 0; i < inv.getHeight(); ++i) {
                for (int j = 0; j < inv.getWidth(); ++j) {
                    ItemStack itemstack = inv.getStackInRowAndColumn(j, i);

                    if (!itemstack.isEmpty()) {
                        ++ingredientCount;
                        if (this.isSimple) {
                            recipeItemHelper.accountStack(itemstack, 1);
                            inputs.add(itemstack);
                        }
                        else
                            inputs.add(itemstack);
                    }
                }
            }
        try {
                if ((Container)container.get(inv) instanceof ContainerWorkbench){
                    return false;
                }
            if ((Container)container.get(inv) instanceof Cooking_Pot_Container){
                for (int i =0;i<inputs.size();i++){
                    if (!(CookingPotDataBase.isFood(inputs.get(i)))&&!(CookingPotDataBase.isMonster(inputs.get(i)))&&!(CookingPotDataBase.isNoUse(inputs.get(i)))){
                        return false;
                    }
                }
            }else{
                return net.minecraftforge.common.util.RecipeMatcher.findMatches(inputs, this.recipeItems) != null;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("Fatal error occurred during recipe checking");
        }
        return false;

    }

    public static CookingPotRecipes deserialize(JsonObject json)
    {
        String s = JsonUtils.getString(json, "group", "");
        NonNullList<Ingredient> nonnulllist = deserializeIngredients(JsonUtils.getJsonArray(json, "ingredients"));
        int id =0;
        if (nonnulllist.isEmpty())
        {
            Cruelars_Triforcemod_Core.logger.error(String.format("No ingredients for cooking_pot recipe: %s", json));
            throw new JsonParseException("No ingredients for cooking_pot recipe");
        }
        else if (nonnulllist.size() > 5)
        {
            Cruelars_Triforcemod_Core.logger.error(String.format("Too many ingredients for cooking_pot recipe: %s",json));
            throw new JsonParseException("Too many ingredients for cooking_pot recipe");
        }
        else
        {
            boolean hard=false;
            boolean nonFood=false;
            String[] items=new String[5];
            ItemStack itemstack = ShapedRecipes.deserializeItem(JsonUtils.getJsonObject(json, "result"), true);
            NonNullList<Item> item= NonNullList.<Item>create();
            NonNullList<Boolean> isFood= NonNullList.<Boolean>create();
            NonNullList<Boolean> isMonster= NonNullList.<Boolean>create();
            NonNullList<Boolean> isCritter= NonNullList.<Boolean>create();
            NonNullList<Boolean> isFruit= NonNullList.<Boolean>create();
            NonNullList<Boolean> isMushroom= NonNullList.<Boolean>create();
            NonNullList<Boolean> isVegetable= NonNullList.<Boolean>create();
            NonNullList<Boolean> isMeat= NonNullList.<Boolean>create();
            NonNullList<Boolean> isRedMeat= NonNullList.<Boolean>create();
            NonNullList<Boolean> isPoultry= NonNullList.<Boolean>create();
            NonNullList<Boolean> isTierOneMeat= NonNullList.<Boolean>create();
            NonNullList<Boolean> isTierTwoMeat= NonNullList.<Boolean>create();
            NonNullList<Boolean> isTierThreeMeat= NonNullList.<Boolean>create();
            NonNullList<Boolean> isSeafood= NonNullList.<Boolean>create();
            NonNullList<Boolean> isCrab= NonNullList.<Boolean>create();
            NonNullList<Boolean> isFishOrSnail= NonNullList.<Boolean>create();
            NonNullList<Boolean> isMisc= NonNullList.<Boolean>create();
            NonNullList<Boolean> isFlowerOrHerb= NonNullList.<Boolean>create();
            NonNullList<Boolean> isCarrot= NonNullList.<Boolean>create();
            NonNullList<Boolean> isRadish= NonNullList.<Boolean>create();
            NonNullList<Boolean> isVegetableOrFlowerOrHerb= NonNullList.<Boolean>create();
            NonNullList<Boolean> isNuts= NonNullList.<Boolean>create();
            NonNullList<Boolean> isPorgy= NonNullList.<Boolean>create();
            NonNullList<Boolean> isSnail= NonNullList.<Boolean>create();
            ItemStack[] itemStacks =new ItemStack[5];
            int HP=0;
            for (int i = 0; i < nonnulllist.size(); ++i) {
                ItemStack stack = nonnulllist.get(i).getMatchingStacks()[0];
                itemStacks[i]=stack;
                item.add(stack.getItem());
                isFood.add(i, false);
                isMonster.add(i, false);
                isCritter.add(i, false);
                isFruit.add(i, false);
                isMushroom.add(i, false);
                isVegetable.add(i, false);
                isMeat.add(i, false);
                isRedMeat.add(i, false);
                isPoultry.add(i, false);
                isTierOneMeat.add(i, false);
                isTierTwoMeat.add(i, false);
                isTierThreeMeat.add(i, false);
                isSeafood.add(i, false);
                isCrab.add(i, false);
                isFishOrSnail.add(i, false);
                isMisc.add(i, false);
                isFlowerOrHerb.add(i, false);
                isCarrot.add(i, false);
                isRadish.add(i, false);
                isVegetableOrFlowerOrHerb.add(i, false);
                isNuts.add(i, false);
                isPorgy.add(i, false);
                isSnail.add(i, false);
                HP += CookingPotDataBase.getHealAmount(stack);
                if (CookingPotDataBase.isHard(stack)){
                    hard=true;
                    break;
                }
                if (CookingPotDataBase.isNoUse(stack)){
                    nonFood=true;
                    break;
                }
                if (CookingPotDataBase.isFood(stack)){
                    isFood.set(i,true);
                    if (CookingPotDataBase.isFruit(stack)){
                        items[i]="fruit";
                        isFruit.set(i, true);
                    }else {
                        isFruit.set(i,false);
                    }
                    if (CookingPotDataBase.isMushroom(stack)){
                        items[i]="mushroom";
                        isMushroom.set(i, true);
                    }else {
                        isMushroom.set(i,false);
                    }
                    if (CookingPotDataBase.isVegetable(stack)){
                        items[i]="vegetable";
                        if (CookingPotDataBase.isCarrot(stack)){
                            isCarrot.set(i,true);
                        }else {
                            isCarrot.set(i,false);
                        }
                        if (CookingPotDataBase.isRadish(stack)){
                            isRadish.set(i,true);
                        }else {
                            isRadish.set(i,false);
                        }
                        isVegetable.set(i, true);
                        isVegetableOrFlowerOrHerb.set(i,true);
                    }else {
                        isCarrot.set(i,false);
                        isRadish.set(i,false);
                        isVegetable.set(i,false);
                        if (!isVegetableOrFlowerOrHerb.get(i)){
                            isVegetableOrFlowerOrHerb.set(i,false);
                        }
                    }
                    if (CookingPotDataBase.isRedMeat(stack)){
                        items[i]="red_meat";
                        isMeat.set(i, true);
                        isRedMeat.set(i, true);
                        if (CookingPotDataBase.isTierOne(stack)){
                            isTierOneMeat.set(i,true);
                        }else{
                            isTierOneMeat.set(i,false);
                        }
                        if (CookingPotDataBase.isTierTwo(stack)){
                            isTierTwoMeat.set(i,true);
                        }else{
                            isTierTwoMeat.set(i,false);
                        }
                        if (CookingPotDataBase.isTierThree(stack)){
                            isTierThreeMeat.set(i,true);
                        }else{
                            isTierThreeMeat.set(i,false);
                        }
                    }else{
                        if (!isMeat.get(i)){
                            isMeat.set(i,false);
                        }
                        isRedMeat.set(i,false);
                        isTierOneMeat.set(i,false);
                        isTierTwoMeat.set(i,false);
                        isTierThreeMeat.set(i,false);
                    }
                    if (CookingPotDataBase.isPoultry(stack)){
                        items[i]="poultry";
                        isMeat.set(i,true);
                        isPoultry.set(i, true);
                        if (CookingPotDataBase.isTierOne(stack)){
                            isTierOneMeat.set(i,true);
                        }else{
                            isTierOneMeat.set(i,false);
                        }
                        if (CookingPotDataBase.isTierTwo(stack)){
                            isTierTwoMeat.set(i,true);
                        }else{
                            isTierTwoMeat.set(i,false);
                        }
                        if (CookingPotDataBase.isTierThree(stack)){
                            isTierThreeMeat.set(i,true);
                        }else{
                            isTierThreeMeat.set(i,false);
                        }
                    }else{
                        if (!isMeat.get(i)){
                            isMeat.set(i,false);
                        }
                        isPoultry.set(i,false);
                        isTierOneMeat.set(i,false);
                        isTierTwoMeat.set(i,false);
                        isTierThreeMeat.set(i,false);
                    }
                    if (CookingPotDataBase.isCrap(stack)){
                        items[i]="crab";
                        isSeafood.set(i,true);
                        isCrab.set(i,true);
                    }else{
                        if (!isSeafood.get(i)){
                            isSeafood.set(i,false);
                        }
                        isCrab.set(i,false);
                    }
                    if (CookingPotDataBase.isFishOrSnail(stack)){
                        items[i]="fish_or_snail";
                        isSeafood.set(i,true);
                        isFishOrSnail.set(i,true);
                        if (CookingPotDataBase.isSnail(stack)){
                            isSnail.set(i,true);
                        }else{
                            isSnail.set(i,false);
                        }
                        if (CookingPotDataBase.isPorgy(stack)){
                            isPorgy.set(i,true);
                        }else{
                            isPorgy.set(i,false);
                        }
                    }else{
                        if (!isSeafood.get(i)){
                            isSeafood.set(i,false);
                        }
                        isFishOrSnail.set(i,false);
                        isPorgy.set(i,false);
                        isSnail.set(i,false);
                    }
                    if (CookingPotDataBase.isMisc(stack)&&stack.getItem()!=Items.MILK_BUCKET&&stack.getItem()!=Items.EGG){
                        items[i]="misc";
                        isMisc.set(i,true);
                        if (CookingPotDataBase.isNut(stack)){
                            isNuts.set(i,true);
                        }else{
                            isNuts.set(i,false);
                        }
                    }else{
                        isMisc.set(i,false);
                        isNuts.set(i,false);
                    }
                    if (CookingPotDataBase.isFlowerOrHerb(stack)){
                        items[i]="flower_or_herb";
                        isFlowerOrHerb.set(i,true);
                        isVegetableOrFlowerOrHerb.set(i,true);
                    }else {
                        isFlowerOrHerb.set(i,false);
                        if (!isVegetableOrFlowerOrHerb.get(i)){
                            isVegetableOrFlowerOrHerb.set(i,false);
                        }
                    }
                }
                if (CookingPotDataBase.isMonster(stack)){
                    isMonster.set(i,true);
                }else {
                    isMonster.set(i,false);
                }
                if (CookingPotDataBase.isCritter(stack)){
                    isCritter.set(i,true);
                }else {
                    isCritter.set(i,false);
                }
            }
            if (isFood.contains(true)&&(isMonster.contains(true)||isCritter.contains(true))){
                itemstack=new ItemStack(ModItems.dubios_food);
                id=0;
            }
            if ((isMonster.contains(true)&&!isCritter.contains(true))||isCritter.contains(true)&&!isMonster.contains(true)){
                itemstack=new ItemStack(ModItems.dubios_food);
                id=0;
            }
            if (item.contains(Items.WHEAT)&&item.contains(Items.REEDS)&&item.contains(ModItems.goat_butter)&&item.contains(Items.APPLE)){
                itemstack=new ItemStack(ModItems.apple_pie);
                id =2;
            }
            if (item.contains(Items.WHEAT)&&item.contains(Items.REEDS)&&item.contains(ModItems.goat_butter)&&isCarrot.contains(true)){

            }
            ...
            
            ...
            if (itemstack.getItem() instanceof ItemCookingPotResult) {
                ((ItemCookingPotResult) itemstack.getItem()).getTagCompoundSafe(itemstack).setInteger("cruelars_triforcemod.heal_amount", HP);
            }
            if (hard){
                itemstack=new ItemStack(ModItems.rock_hard_food);
                id=1;
            }else if (nonFood) {
                itemstack = new ItemStack(ModItems.dubios_food);
                id=0;
            }
            return  new CookingPotRecipes(s, itemstack, nonnulllist,id);
        }
    }

    public static NonNullList<Ingredient> deserializeIngredients(JsonArray array)
    {
        NonNullList<Ingredient> nonnulllist = NonNullList.<Ingredient>create();

        for (int i = 0; i < array.size(); ++i)
        {
            Ingredient ingredient = ShapedRecipes.deserializeIngredient(array.get(i));

            if (ingredient != Ingredient.EMPTY)
            {
                nonnulllist.add(ingredient);
            }
        }

        return nonnulllist;
    }

    @Override
    @Nonnull
    public ItemStack getCraftingResult(@Nonnull InventoryCrafting var1) {
        ItemStack newOutput = this.recipeOutput.copy();
        if (newOutput.getItem()==ModItems.dubios_food||newOutput.getItem()==ModItems.rock_hard_food){
            ((ItemCookingPotResult) newOutput.getItem()).getTagCompoundSafe(newOutput).setInteger("cruelars_triforcemod.heal_amount",
                    Math.min(((ItemCookingPotResult) newOutput.getItem()).getTagCompoundSafe(newOutput).getInteger("cruelars_triforcemod.heal_amount"), 12));
        }
        return newOutput;
    }

    @Override
    public boolean canFit(int width, int height) {
        return width * height >= this.recipeItems.size();
    }

    @Override
    public ItemStack getRecipeOutput() {
        return this.recipeOutput;
    }

    @Override
    public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {
        NonNullList<ItemStack> nonnulllist = NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);

        for (int i = 0; i < nonnulllist.size(); ++i)
        {
            ItemStack itemstack = inv.getStackInSlot(i);

            nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack));
        }

        return nonnulllist;
    }

    private static boolean fourDifferentItems(NonNullList<Boolean> booleans,NonNullList<Item> items){
        if (booleans.size()<4){
            return false;
        }
        if (booleans.size()==4){
            if (booleans.get(0)&&booleans.get(1)&&booleans.get(2)&&booleans.get(3)) {
                return items.get(0) != items.get(1) && items.get(1) != items.get(2) && items.get(2) != items.get(3);
            }
        }
        if (booleans.get(0)&&booleans.get(1)&&booleans.get(2)&&booleans.get(3)){
            return items.get(0) != items.get(1) && items.get(1) != items.get(2) && items.get(2) != items.get(3);
        }else if (booleans.get(0)&&booleans.get(1)&&booleans.get(2)&&booleans.get(4)){
            return items.get(0) != items.get(1) && items.get(1) != items.get(2) && items.get(2) != items.get(4);
        }else if (booleans.get(0)&&booleans.get(1)&&booleans.get(3)&&booleans.get(4)){
            return items.get(0) != items.get(1) && items.get(1) != items.get(3) && items.get(3) != items.get(4);
        }else if (booleans.get(0)&&booleans.get(2)&&booleans.get(3)&&booleans.get(4)){
            return items.get(0) != items.get(2) && items.get(2) != items.get(3) && items.get(3) != items.get(4);
        }else if (booleans.get(1)&&booleans.get(2)&&booleans.get(3)&&booleans.get(4)){
            return items.get(1) != items.get(2) && items.get(2) != items.get(3) && items.get(3) != items.get(4);
        }   return false;
    }

    private static boolean twoItemsOfType(NonNullList<Boolean> booleans) {
        if (booleans.size()==1){
            return false;
        }
        if (booleans.size()==2){
            return booleans.get(0) && booleans.get(1);
        }
        if (booleans.size()==3){
            return booleans.get(0) && booleans.get(1) || booleans.get(0) && booleans.get(2) ||booleans.get(1) && booleans.get(2);
        }
        if (booleans.size()==4){
            return booleans.get(0) && booleans.get(1)||booleans.get(0) && booleans.get(2)||booleans.get(0) && booleans.get(3)||booleans.get(1) && booleans.get(2)||booleans.get(1) && booleans.get(3)||
                    booleans.get(2) && booleans.get(3);

        }
        if (booleans.size()==5) {
            return booleans.get(0) && booleans.get(1) || booleans.get(0) && booleans.get(2) || booleans.get(0) && booleans.get(3) || booleans.get(0) && booleans.get(4) || booleans.get(1) && booleans.get(2) ||
                    booleans.get(1) && booleans.get(3) || booleans.get(1) && booleans.get(4) || booleans.get(2) && booleans.get(3) || booleans.get(2) && booleans.get(4) || booleans.get(3) && booleans.get(4);
        }
        return false;
    }

    private static boolean isOfTier( NonNullList<Boolean> meatType, NonNullList<Boolean> meatTier){
        for (int i = 0; i < meatType.size(); i++) {
            if (meatType.get(i)&&meatTier.get(i)){
                return true;
            }
        }
        return false;
    }

    @Override
    public NonNullList<Ingredient> getIngredients() {
        return this.recipeItems;
    }

    @Override
    public String getGroup() {
        return this.group;
    }

    public int getId(){
        return this.id;
    }

    /**
     * Example JSON recipe:<br>
     * &emsp;{<br>
     * &emsp;&emsp;"result": {<br>
     * &emsp;&emsp;&emsp;"item": "minecraft:golden_apple",<br>
     * &emsp;&emsp;&emsp;"data":0<br>
     * &emsp;&emsp;},<br>
     * &emsp;&emsp;"type": "cruelars_triforcemod:cooking_pot",<br>
     * &emsp;&emsp;"ingredients": [<br>
     * &emsp;&emsp;&emsp;{<br>
     * &emsp;&emsp;&emsp;&emsp;"item": "minecraft:apple"<br>
     * &emsp;&emsp;&emsp;},<br>
     * &emsp;&emsp;&emsp;{<br>
     * &emsp;&emsp;&emsp;&emsp;"item": "minecraft:apple"<br>
     * &emsp;&emsp;&emsp;},<br>
     * &emsp;&emsp;&emsp;{<br>
     * &emsp;&emsp;&emsp;&emsp;"item": "minecraft:apple"<br>
     * &emsp;&emsp;&emsp;},<br>
     * &emsp;&emsp;&emsp;{<br>
     * &emsp;&emsp;&emsp;&emsp;"item": "minecraft:apple"<br>
     * &emsp;&emsp;&emsp;},<br>
     * &emsp;&emsp;&emsp;{<br>
     * &emsp;&emsp;&emsp;&emsp;"item": "minecraft:apple"<br>
     * &emsp;&emsp;&emsp;}<br>
     * &emsp;&emsp;]<br>
     * &emsp;}<br>
     */

    public static class Factory implements IRecipeFactory {
        @Override
        public IRecipe parse(JsonContext context, JsonObject json) {
            return deserialize(json);
        }
    }
}

 

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Posted (edited)

You can just as I said, make your mod the library. There's not much wrong with that, just make sure you have all fields that aren't to be accessed marked private.

Quote

Your mod has the capability, you don't have to put it in an API, other programmers can make their mod as a dependency of yours.

 

 

Edited by tebreca
Posted

Ok, I just thought it could be easier for others to have only a small part of my code (looking at Data amount my mod is at around 0.8 MB)

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Posted
14 minutes ago, _Cruelar_ said:

Ok, I just thought it could be easier for others to have only a small part of my code (looking at Data amount my mod is at around 0.8 MB)

it is, but on the other hand it isn't, having to mess with api's is sometimes harder than just making a dependency of a mod

Posted

Thanks for explaining me, for the next mod I should think more about getting api stuff independent. I recently struggled with the small possibilities of the journeymap api, so yeah the whole mod should be better then I think.

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.