Jump to content

Recommended Posts

Posted (edited)

Hi
I'm making a block physics mod and my Physics Block entity doesn't spawn on the client when I spawn it using world.spawnEntity(), but when I tried it using /summon it spawned
I don't know what is wrong, searching on Google didn't help me

I spawn it using this:
 

Spoiler

@SubscribeEvent
    public void onExplosion(ExplosionEvent.Detonate e) {
        PhysicsMod.ready += 5;
        List<BlockPos> pos = e.getAffectedBlocks();
        World worldObj = e.getWorld();

        for(Iterator< BlockPos> i = pos.iterator(); i.hasNext();){
            BlockPos block = i.next();
            IBlockState blockState = worldObj.getBlockState(block);

            if(blockState.isFullBlock() && !worldObj.isRemote) {
                EntityPhysicsBlock pb = new EntityPhysicsBlock(worldObj, (float) block.getX(), (float) block.getY(), (float) block.getZ(), 0, new Random().nextInt(30), 0, blockState);
                pb.forceSpawn = true;
                worldObj.spawnEntity(pb);
            }
        }

        System.out.println("Rigidbody count: " + PhysicsMod.blocks.size());
    }
 
Spoiler

 

 

And this is my entity class:
 

Spoiler

package com.github.kedlub.physics.entity;

import com.bulletphysics.collision.shapes.BoxShape;
import com.bulletphysics.collision.shapes.SphereShape;
import com.bulletphysics.demos.applet.Sphere;
import com.bulletphysics.dynamics.RigidBody;
import com.bulletphysics.dynamics.RigidBodyConstructionInfo;
import com.bulletphysics.linearmath.DefaultMotionState;
import com.bulletphysics.linearmath.MotionState;
import com.bulletphysics.linearmath.Transform;
import com.github.kedlub.physics.PhysicsMod;
import com.github.kedlub.physics.model.ModelCube;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockStateBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Rotations;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Quaternion;

import javax.vecmath.Quat4f;
import javax.vecmath.Vector3f;

import static com.github.kedlub.physics.PhysicsMod.blocks;

/**
 * Created by Kubik on 08.06.2017.
 */
public class EntityPhysicsBlock extends Entity implements IEntityAdditionalSpawnData {

    public static final Block DEFAULT_BLOCK = Blocks.STONE;

    //private static final DataParameter<BlockPos> VELOCITY = EntityDataManager.createKey(EntityPhysicsBlock.class, DataSerializers.BLOCK_POS);
    protected static final DataParameter<BlockPos> ORIGIN = EntityDataManager.<BlockPos>createKey(EntityPhysicsBlock.class, DataSerializers.BLOCK_POS);
    protected static final DataParameter<Rotations> ROTATION = EntityDataManager.createKey(EntityPhysicsBlock.class, DataSerializers.ROTATIONS);
    protected static final DataParameter<Float> ROTATION_W = EntityDataManager.createKey(EntityPhysicsBlock.class, DataSerializers.FLOAT);
    protected static final DataParameter<Float> BLOCKID = EntityDataManager.createKey(EntityPhysicsBlock.class, DataSerializers.FLOAT);
    public RigidBody rigidBody;
    public int number;
    public Transform xform = new Transform();
    public ModelCube model;
    public Vector3f velocity = new Vector3f();
    public IBlockState block = DEFAULT_BLOCK.getDefaultState();
    float defaultX, defaultY, defaultZ;
    float defaultVelX, defaultVelY, defaultVelZ;


    public EntityPhysicsBlock(World worldIn) {
        super(worldIn);
    }

    public EntityPhysicsBlock(World worldIn, float x, float y, float z, float velX, float velY, float velZ, IBlockState block1) {
        super(worldIn);
        block = block1;
        defaultX = x;
        defaultY = y;
        defaultZ = z;
        defaultVelX = velX;
        defaultVelY = velY;
        defaultVelZ = velZ;
    }

    @SideOnly(Side.CLIENT)
    public World getWorldObj()
    {
        return this.world;
    }

    public void setOrigin(BlockPos p_184530_1_)
    {
        this.dataManager.set(ORIGIN, p_184530_1_);
    }

    @SideOnly(Side.CLIENT)
    public BlockPos getOrigin()
    {
        return (BlockPos)this.dataManager.get(ORIGIN);
    }

    public void setRotation(Quaternion quat)
    {
        Rotations rot = new Rotations(quat.x,quat.y,quat.z);
        this.dataManager.set(ROTATION, rot);
        this.dataManager.set(ROTATION_W, quat.w);
    }

    @SideOnly(Side.CLIENT)
    public Quaternion getRotation() {
        Rotations rot = this.dataManager.get(ROTATION);
        float rot_w = this.dataManager.get(ROTATION_W);
        Quaternion quat = new Quaternion(rot.getX(),rot.getY(),rot.getZ(),rot_w);

        return quat;
    }

    /**
     * Returns true if other Entities should be prevented from moving through this Entity.
     */
    public boolean canBeCollidedWith()
    {
        return !this.isDead;
    }

    int spawnTick = 0;

    @Override
    public void onUpdate() {
        super.onUpdate();
        if(world.isRemote) { //I don't know if onUpdate() gets called only server-side, so I check for this here
            if (PhysicsMod.ready != 0 || PhysicsMod.paused) return;
            //System.out.println("onUpdate() ");

            if (this.block == null || this.block.getMaterial() == Material.AIR) {
                //System.out.println("block is null! for entity " + entityUniqueID);
                if (spawnTick < 100) {
                    spawnTick += 1;
                } else {
                    this.setDead();
                }
                return;
            }
            //System.out.println("Previous position:" + posX + " " + posY + " " + posZ);
            if(rigidBody != null && xform != null) {
                this.rigidBody.getCenterOfMassTransform(this.xform);
                //this.posX = xform.origin.x;
                //this.posY = xform.origin.y;
                //this.posZ = xform.origin.z;
                this.setPosition(xform.origin.x, xform.origin.y, xform.origin.z);
                this.dataManager.set(BLOCKID, (float) Block.getStateId(block));

                this.rigidBody.getLinearVelocity(this.velocity);

                Quat4f quat4f = new Quat4f();
                if (xform != null) {
                    this.xform.getRotation(quat4f);
                }

                setRotation(new Quaternion(quat4f.x, quat4f.y, quat4f.z, quat4f.w));
            }
        }
        else {
            block = Block.getStateById((int)((float)this.dataManager.get(BLOCKID)));
        }



        //System.out.println("New position:" + posX + " " + posY + " " + posZ);
    }


    protected void entityInit()
    {
        if(!world.isRemote) return;
        BoxShape localBoxShape = PhysicsMod.cubeSize;
        Vector3f localVector3f = new Vector3f(0.5f,0.5f,0.5f);
        localBoxShape.calculateLocalInertia(20,localVector3f);

        this.xform = new Transform();
        this.xform.setIdentity();

        MotionState motion = new DefaultMotionState(this.xform);
        RigidBodyConstructionInfo rbinfo = new RigidBodyConstructionInfo(20.0F, motion, localBoxShape, localVector3f);
        rigidBody = new RigidBody(rbinfo);
        this.rigidBody.setRestitution(0.01F);
        this.rigidBody.setFriction(0.8F);
        this.rigidBody.setDamping(0.4F, 0.4F);

        PhysicsMod.instance.dynamicsWorld.addRigidBody(this.rigidBody);

        blocks.add(this);


        this.setOrigin(new BlockPos(this));

        this.velocity = new Vector3f(0.0F, 0.0F, 0.0F);

        this.xform.origin.set(defaultX,defaultY,defaultZ);

        this.velocity.x = ((float)defaultVelX);
        this.velocity.y = ((float)defaultVelY);
        this.velocity.z = ((float)defaultVelZ);

        this.rigidBody.setCenterOfMassTransform(xform);
        this.rigidBody.setLinearVelocity(this.velocity);
        this.rigidBody.activate();

        this.dataManager.register(ORIGIN, BlockPos.ORIGIN);
        Quat4f quat4f = new Quat4f();
        if(xform != null) {
            this.xform.getRotation(quat4f);
        }
        this.dataManager.register(ROTATION, new Rotations(quat4f.x,quat4f.y,quat4f.z));
        this.dataManager.register(ROTATION_W, quat4f.w);
        this.dataManager.register(BLOCKID, 1f);
        this.setSize(0.98F, 0.98F);
        //this.dataManager.register(VELOCITY, new BlockPos(velocity.x,velocity.y,velocity.z));
    }

    @Override
    protected void kill() {
        this.setDead();
    }

    @Override
    public void setDead() {
        if(this.rigidBody != null) {
            PhysicsMod.instance.dynamicsWorld.removeRigidBody(this.rigidBody);
        }
        if(blocks.contains(this)) {
            blocks.remove(this);
        }
        this.isDead = true;
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntityToNBT(NBTTagCompound compound)
    {
      
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntityFromNBT(NBTTagCompound compound)
    {
      
    }

    // It also seems that writeSpawnData doesn't get called
    @Override
    public void writeSpawnData(ByteBuf buffer) {
        if(this.block != null) {
            buffer.writeInt(Block.getStateId(this.block));
        }
        System.out.println("Sending block spawnData");
    }

    // And readSpawnData doesn't get called too
    @Override
    public void readSpawnData(ByteBuf additionalData) {
        System.out.println("Received block spawnData"); //line gets printed only with /summon
        block = Block.getStateById(additionalData.readInt());
        System.out.println("Block is " + block.getBlock().getLocalizedName());
        this.xform.origin.set((float)posX,(float)posY,(float)posZ);
        this.setSize(0.98F, 0.98F);
    }
}
 

 


Github repository: https://github.com/Kedlub/minecraft-physics

Edited by kedlub

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

    • I want to create block with entity, that will have height of 3 or more(configurable) and I tried to change first VoxelShape by increasing collision box on height I want and for changing block height on visual side i tried to configure BlockModelBuilder:  base.element() .from(0, 0, 0) .to(16f, 48f, 16f) .face(Direction.UP).texture("#top").end() .face(Direction.DOWN).texture("#bottom").end() .face(Direction.NORTH).texture("#side").end() .face(Direction.SOUTH).texture("#side").end() .face(Direction.WEST).texture("#side").end() .face(Direction.EAST).texture("#side").end() .end(); but, getting crash with next error: Position y out of range, must be within [-16, 32]. Found: %d [48.0]; Looks like game wont to block height modified by more than 32. Is there any way to fix that problem?
    • As long as the packets you are sending aren't lost, there's nothing wrong with what you're currently doing. Although, this sounds like something that would benefit from you making your own datapack registry instead of trying to arbitrarily sync static maps. Check out `DataPackRegistryEvent.NewRegistry`.
    • Hey all, I've been working a lot with datapacks lately, and I'm wondering what the most efficient way to get said data from server to client is.  I'm currently using packets, but given that a lot of the data I'm storing involves maps along the lines of Map<ResourceLocation, CustomDataType>, it can easily start to get messy if I need to transmit a lot of that data all at once. Recently I started looking into the ReloadableServerResources class, which is where Minecraft stores its built-ins.  I see you can access it via the server from the server's resources.managers, and it seems like this can be done even from the client to appropriately retrieve data from the server, unless I'm misunderstanding.  However, from what I can tell, this only works via built-in methods such as getRecipeManager() or getLootTables(), etc.  These are all SimpleJsonResourceReloadListeners, just like my datapack entries are, so it seems like it could be possible for me to access my datapack entries similarly?  But I don't see anywhere in ReloadableServerResources that stores loaded modded entries, so either I'm looking in the wrong place or it doesn't seem to be a thing. Are packets really the best way of doing this, or am I missing a method that would let me use ReloadableServerResources or something similar?
    • Hi, everyone! I'm new to minecraft modding stuff and want ask you some questions. 1. I checked forge references and saw there com.mojang and net.minecraft (not net.minecraftforge) and as I understand it's original game packages with all minecraft logic inside including renderers and so on, right? 2. Does it mean that forge has a limited set of instruments which doesn't cover all the aspects of the game? If make my question more specific then does forge provide such instruments that allow me totally change minecraft itself, like base mechanics and etc.? Or I have to use "original game packages" to implement such things? 3. I actively learning basic concepts with forge documentation and tutorials. So in my plans make different inventory system like in diabloids. Is that possible with forge? 4. It is last question related to the second one. So how deeply I can change minecraft with forge? I guess all my questions above because of that I haven't globally understanding what forge is and how it works inside and how it works with minecraft. It would be great if you provide some links or topics about it or explain it by yourself but I guess it's to big to be explained in that post at once. Anyway, thank you all for any help!
    • Im trying add to block a hole in center, just a usual block and in center of it on up side, there is should be a hole. I tried to add it via BlockModelBuilder, but its not working. Problem is that it only can change block size outside. I tried it to do with VoxelShape and its working, but its has been on server side and looks like its just changed collision shape, but for client, there is a texture covering this hole. I tried to use: base.renderType("cutout"); and removed some pixels from texture. I thought its should work, but game optimization makes block inside looks transparent. So, only custom model?
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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