Search in sources :

Example 26 with Block

use of org.terasology.engine.world.block.Block in project Terasology by MovingBlocks.

the class LodChunkProvider method createChunks.

private void createChunks() {
    Block unloaded = blockManager.getBlock(BlockManager.UNLOADED_ID);
    try {
        while (true) {
            Vector3ic pos = neededChunks.take();
            // Actually the log scale
            Integer scale = requiredChunks.get(pos);
            if (scale == null) {
                // This chunk is being removed in the main thread.
                continue;
            }
            Chunk chunk = new PreLodChunk(scaleDown(pos, scale), blockManager, extraDataManager);
            generator.createChunk(chunk, (1 << scale) * (2f / (Chunks.SIZE_X - 2) + 1));
            InternalLightProcessor.generateInternalLighting(chunk, 1 << scale);
            // tintChunk(chunk);
            ChunkView view = new ChunkViewCoreImpl(new Chunk[] { chunk }, new BlockRegion(chunk.getPosition(new Vector3i())), new Vector3i(), unloaded);
            ChunkMesh mesh = tessellator.generateMesh(view, 1 << scale, 1);
            readyChunks.add(new LodChunk(pos, mesh, scale));
        }
    } catch (InterruptedException ignored) {
    }
}
Also used : PreLodChunk(org.terasology.engine.world.chunks.internal.PreLodChunk) ChunkViewCoreImpl(org.terasology.engine.world.internal.ChunkViewCoreImpl) ChunkMesh(org.terasology.engine.rendering.primitives.ChunkMesh) Vector3ic(org.joml.Vector3ic) Vector3i(org.joml.Vector3i) Block(org.terasology.engine.world.block.Block) BlockRegion(org.terasology.engine.world.block.BlockRegion) PreLodChunk(org.terasology.engine.world.chunks.internal.PreLodChunk) PreLodChunk(org.terasology.engine.world.chunks.internal.PreLodChunk) ChunkView(org.terasology.engine.world.ChunkView)

Example 27 with Block

use of org.terasology.engine.world.block.Block in project Terasology by MovingBlocks.

the class ExtraBlockDataManager method getFieldsFromAnnotations.

// Find requests for extensions and which blocks they apply to.
private Map<Integer, Map<String, Set<Block>>> getFieldsFromAnnotations(Context context) {
    ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment();
    Collection<Block> blocks = context.get(BlockManager.class).listRegisteredBlocks();
    Map<Integer, Map<String, Set<Block>>> fieldss = new HashMap<>();
    TERA_ARRAY_FACTORIES.forEach((size, fac) -> fieldss.put(size, new HashMap<>()));
    for (Class<?> type : environment.getTypesAnnotatedWith(ExtraDataSystem.class)) {
        for (Method method : type.getMethods()) {
            RegisterExtraData registerAnnotation = method.getAnnotation(RegisterExtraData.class);
            if (registerAnnotation != null) {
                String errorType = validRegistrationMethod(method, registerAnnotation);
                if (errorType != null) {
                    logger.error("Unable to register extra block data: " + errorType + " for {}.{}: should be \"public static boolean {}(Block block)\", and bitSize should be 4, 8 or 16.", type.getName(), method.getName(), method.getName());
                    continue;
                }
                method.setAccessible(true);
                Set<Block> includedBlocks = new HashSet<>();
                for (Block block : blocks) {
                    try {
                        if ((boolean) method.invoke(null, block)) {
                            includedBlocks.add(block);
                        }
                    } catch (IllegalAccessException e) {
                        // This should not get to this point.
                        throw new RuntimeException("Incorrect access modifier on register extra data method", e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                }
                fieldss.get(registerAnnotation.bitSize()).put(registerAnnotation.name(), includedBlocks);
            }
        }
    }
    return fieldss;
}
Also used : HashMap(java.util.HashMap) Method(java.lang.reflect.Method) ModuleManager(org.terasology.engine.core.module.ModuleManager) InvocationTargetException(java.lang.reflect.InvocationTargetException) ModuleEnvironment(org.terasology.gestalt.module.ModuleEnvironment) BlockManager(org.terasology.engine.world.block.BlockManager) Block(org.terasology.engine.world.block.Block) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 28 with Block

use of org.terasology.engine.world.block.Block in project Terasology by MovingBlocks.

the class PhysicsSystem method update.

@Override
public void update(float delta) {
    PerformanceMonitor.startActivity("Physics Renderer");
    physics.update(time.getGameDelta());
    PerformanceMonitor.endActivity();
    // Update the velocity from physics engine bodies to Components:
    Iterator<EntityRef> iter = physics.physicsEntitiesIterator();
    while (iter.hasNext()) {
        EntityRef entity = iter.next();
        RigidBodyComponent comp = entity.getComponent(RigidBodyComponent.class);
        RigidBody body = physics.getRigidBody(entity);
        // force location component to update and sync trigger state
        if (entity.hasComponent(TriggerComponent.class)) {
            physics.updateTrigger(entity);
        }
        if (body.isActive()) {
            body.getLinearVelocity(comp.velocity);
            body.getAngularVelocity(comp.angularVelocity);
            Vector3f vLocation = body.getLocation(new Vector3f());
            Vector3f vDirection = new Vector3f(comp.velocity);
            float fDistanceThisFrame = vDirection.length();
            vDirection.normalize();
            fDistanceThisFrame = fDistanceThisFrame * delta;
            while (true) {
                HitResult hitInfo = physics.rayTrace(vLocation, vDirection, fDistanceThisFrame + 0.5f, DEFAULT_COLLISION_GROUP);
                if (hitInfo.isHit()) {
                    Block hitBlock = worldProvider.getBlock(hitInfo.getBlockPosition());
                    if (hitBlock != null) {
                        Vector3f vTravelledDistance = vLocation.sub(hitInfo.getHitPoint());
                        float fTravelledDistance = vTravelledDistance.length();
                        if (fTravelledDistance > fDistanceThisFrame) {
                            break;
                        }
                        if (hitBlock.isPenetrable()) {
                            if (!hitInfo.getEntity().hasComponent(BlockComponent.class)) {
                                entity.send(new EntityImpactEvent(hitInfo.getHitPoint(), hitInfo.getHitNormal(), comp.velocity, fDistanceThisFrame, hitInfo.getEntity()));
                                break;
                            }
                            // decrease the remaining distance to check if we hit a block
                            fDistanceThisFrame = fDistanceThisFrame - fTravelledDistance;
                            vLocation = hitInfo.getHitPoint();
                        } else {
                            entity.send(new BlockImpactEvent(hitInfo.getHitPoint(), hitInfo.getHitNormal(), comp.velocity, fDistanceThisFrame, hitInfo.getEntity()));
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }
    if (networkSystem.getMode().isServer() && time.getGameTimeInMs() - TIME_BETWEEN_NETSYNCS > lastNetsync) {
        sendSyncMessages();
        lastNetsync = time.getGameTimeInMs();
    }
    List<CollisionPair> collisionPairs = physics.getCollisionPairs();
    for (CollisionPair pair : collisionPairs) {
        if (pair.b.exists()) {
            short bCollisionGroup = getCollisionGroupFlag(pair.b);
            short aCollidesWith = getCollidesWithGroupFlag(pair.a);
            if ((bCollisionGroup & aCollidesWith) != 0 || (pair.b.hasComponent(BlockComponent.class) && !pair.a.hasComponent(BlockComponent.class))) {
                pair.a.send(new CollideEvent(pair.b, pair.pointA, pair.pointB, pair.distance, pair.normal));
            }
        }
        if (pair.a.exists()) {
            short aCollisionGroup = getCollisionGroupFlag(pair.a);
            short bCollidesWith = getCollidesWithGroupFlag(pair.b);
            if ((aCollisionGroup & bCollidesWith) != 0 || (pair.a.hasComponent(BlockComponent.class) && !pair.b.hasComponent(BlockComponent.class))) {
                pair.b.send(new CollideEvent(pair.a, pair.pointB, pair.pointA, pair.distance, new Vector3f(pair.normal).mul(-1.0f)));
            }
        }
    }
}
Also used : RigidBodyComponent(org.terasology.engine.physics.components.RigidBodyComponent) HitResult(org.terasology.engine.physics.HitResult) BlockComponent(org.terasology.engine.world.block.BlockComponent) CollideEvent(org.terasology.engine.physics.events.CollideEvent) Vector3f(org.joml.Vector3f) BlockImpactEvent(org.terasology.engine.physics.events.BlockImpactEvent) OnChangedBlock(org.terasology.engine.world.OnChangedBlock) Block(org.terasology.engine.world.block.Block) EntityImpactEvent(org.terasology.engine.physics.events.EntityImpactEvent) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef)

Example 29 with Block

use of org.terasology.engine.world.block.Block in project Terasology by MovingBlocks.

the class LocalPlayerSystem method onTargetChanged.

@ReceiveEvent
public void onTargetChanged(PlayerTargetChangedEvent event, EntityRef entity) {
    EntityRef target = event.getNewTarget();
    hasTarget = target.exists();
    if (hasTarget) {
        LocationComponent location = target.getComponent(LocationComponent.class);
        if (location != null) {
            BlockComponent blockComp = target.getComponent(BlockComponent.class);
            BlockRegionComponent blockRegion = target.getComponent(BlockRegionComponent.class);
            if (blockComp != null || blockRegion != null) {
                Vector3f blockPos = location.getWorldPosition(new Vector3f());
                Block block = worldProvider.getBlock(blockPos);
                aabb.set(block.getBounds(blockPos));
            } else {
                MeshComponent mesh = target.getComponent(MeshComponent.class);
                if (mesh != null && mesh.mesh != null) {
                    aabb.set(mesh.mesh.getAABB());
                    aabb.transform(new Matrix4f().translationRotateScale(location.getWorldPosition(new Vector3f()), location.getWorldRotation(new Quaternionf()), location.getWorldScale()));
                }
            }
        }
    }
}
Also used : BlockComponent(org.terasology.engine.world.block.BlockComponent) MeshComponent(org.terasology.engine.rendering.logic.MeshComponent) Matrix4f(org.joml.Matrix4f) BlockRegionComponent(org.terasology.engine.world.block.regions.BlockRegionComponent) Vector3f(org.joml.Vector3f) Block(org.terasology.engine.world.block.Block) Quaternionf(org.joml.Quaternionf) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef) LocationComponent(org.terasology.engine.logic.location.LocationComponent) ReceiveEvent(org.terasology.engine.entitySystem.event.ReceiveEvent)

Example 30 with Block

use of org.terasology.engine.world.block.Block in project Terasology by MovingBlocks.

the class Zone method generateChunk.

/**
 * Generate the chunk for this zone, based on the rasterizers and nested zones that have been added.
 *
 * This will only change blocks for which {@link #containsBlock(int, int, int, Region)} returns true.
 *
 * @see WorldRasterizer#generateChunk(Chunk, Region)
 */
@Override
public void generateChunk(Chunk chunk, Region chunkRegion) {
    Block[][][] savedBlocks = new Block[Chunks.SIZE_X][Chunks.SIZE_Y][Chunks.SIZE_Z];
    boolean changeAllBlocks = true;
    boolean saveAllBlocks = true;
    int offsetX = chunk.getChunkWorldOffsetX();
    int offsetY = chunk.getChunkWorldOffsetY();
    int offsetZ = chunk.getChunkWorldOffsetZ();
    // Save the blocks that aren't in the zone
    for (int x = 0; x < Chunks.SIZE_X; x++) {
        for (int y = 0; y < Chunks.SIZE_Y; y++) {
            for (int z = 0; z < Chunks.SIZE_Z; z++) {
                if (!containsBlock(x + offsetX, y + offsetY, z + offsetZ, chunkRegion)) {
                    savedBlocks[x][y][z] = chunk.getBlock(x, y, z);
                    changeAllBlocks = false;
                } else {
                    saveAllBlocks = false;
                }
            }
        }
    }
    // If none of the blocks are in the zone, it doesn't need to be rasterized
    if (!saveAllBlocks) {
        // Rasterize the zone
        rasterizers.forEach(r -> r.generateChunk(chunk, chunkRegion));
        // Replace any blocks that aren't in the zone
        if (!changeAllBlocks) {
            for (int x = 0; x < Chunks.SIZE_X; x++) {
                for (int y = 0; y < Chunks.SIZE_Y; y++) {
                    for (int z = 0; z < Chunks.SIZE_Z; z++) {
                        Block block = savedBlocks[x][y][z];
                        if (block != null) {
                            chunk.setBlock(x, y, z, block);
                        }
                    }
                }
            }
        }
    }
}
Also used : Block(org.terasology.engine.world.block.Block)

Aggregations

Block (org.terasology.engine.world.block.Block)54 Vector3i (org.joml.Vector3i)23 EntityRef (org.terasology.engine.entitySystem.entity.EntityRef)13 Vector3ic (org.joml.Vector3ic)12 Vector3f (org.joml.Vector3f)9 OnChangedBlock (org.terasology.engine.world.OnChangedBlock)9 ReceiveEvent (org.terasology.engine.entitySystem.event.ReceiveEvent)7 Side (org.terasology.engine.math.Side)7 Map (java.util.Map)6 BlockFamily (org.terasology.engine.world.block.family.BlockFamily)6 EntityManager (org.terasology.engine.entitySystem.entity.EntityManager)5 BlockComponent (org.terasology.engine.world.block.BlockComponent)5 Chunk (org.terasology.engine.world.chunks.Chunk)5 BeforeEach (org.junit.jupiter.api.BeforeEach)4 EngineEntityManager (org.terasology.engine.entitySystem.entity.internal.EngineEntityManager)4 Maps (com.google.common.collect.Maps)3 Optional (java.util.Optional)3 ComponentSystemManager (org.terasology.engine.core.ComponentSystemManager)3 LocationComponent (org.terasology.engine.logic.location.LocationComponent)3 BlockEntityRegistry (org.terasology.engine.world.BlockEntityRegistry)3