Jump to content

Recommended Posts

Posted

Catch up with the last topic with rendering, this is something that I took a while to learn from nothing to this stage.

RiehulX.png

KGPX5Lq.png

(I only shoot from right side)

    public static List<Pair<BlockRayTraceResult, Float>> rayTraceAndPenetrateBlocks4(World world, List<Vector3d> vecs, float health, Function<BlockState, Float> getHealthReduction)
    {
        List<Pair<BlockRayTraceResult, Float>> results = new ArrayList<>();
        if (vecs.isEmpty())
            return results;
        Vector3d startVec = vecs.get(0);
        for (int i=0;i<vecs.size()-1;i++)
        {
            Vector3d vec = vecs.get(i);
            Vector3d next = vecs.get(i + 1);
            BlockPos pos = new BlockPos(vec);
            BlockPos pos2 = new BlockPos(next);
            BlockState blockstate = world.getBlockState(pos);
            BlockState blockstate2 = world.getBlockState(pos2);
            if (blockstate.getBlock() instanceof BarrierBlock && blockstate2.getBlock() instanceof BarrierBlock)
                continue;
            VoxelShape blockShape = blockstate.getCollisionShape(world, pos, ISelectionContext.dummy());
            VoxelShape blockShape2 = blockstate2.getCollisionShape(world, pos2, ISelectionContext.dummy());
            BlockRayTraceResult blockResult;
            boolean empty = blockShape.isEmpty() || blockShape.toBoundingBoxList().stream().noneMatch((bb) -> bb.offset(pos).contains(vec));
            boolean empty2 = blockShape2.isEmpty() || blockShape2.toBoundingBoxList().stream().noneMatch((bb) -> bb.offset(pos2).contains(next));
            if ((isRayTraceIgnorableBlock(blockstate, blockShape) && isRayTraceIgnorableBlock(blockstate2, blockShape2)))
                continue;
            if (empty && !empty2)
                blockResult = world.rayTraceBlocks(vec, next, pos2, blockShape2, blockstate2);
            else if (!empty && empty2)
                blockResult = world.rayTraceBlocks(next, vec, pos, blockShape, blockstate);
            else
                blockResult = world.rayTraceBlocks(vec, next, pos, blockShape, blockstate);

            if (blockResult != null)
            {
                health -= getHealthReduction.apply(blockstate);
                results.add(new Pair<>(blockResult, (float) startVec.distanceTo(blockResult.getHitVec())));
                if (health <= 0)
                    break;
            }
        }
        return results;
    }

	    public static List<Vector3d> getAllVectors2(Vector3d startVec, Vector3d endVec, int distance)
    {
        List<Vector3d> vecs = new ArrayList<>();
        Vector3d step = endVec.subtract(startVec).normalize();
        int rayTraceCount = 20;
        for (int i=0;i<distance;i++)
            for (int j=0;j<rayTraceCount;j++)
                vecs.add(startVec.add(step.scale(i).add(step.scale((float) j / (float) rayTraceCount))));
        return vecs;
    }

The vecs passed into the first method comes from the second method.

The concept is to gather a collection of vectors, and the do ray trace between each of them. The first method can be a lot more simplified but not on my case since I also do entity penetrations, with damage calculations...etc.

Anyways, if you only do normal raytracing what you will get will be something like:

 

Black Block represents a solid block

Gray Block represents air or empty shaped block

Green dots represents the positions we ray trace between.

Blue dots represents the ray trace hit result.

mXEDKTO.png

As you can see, the ray trace hit will not (unlikely) hit the surface when coming out of a block, therefore we need to detect the situation and ray trace back wards:

WTFjaEB.png

So we get the "entering" and "exiting" points.

 

Here comes the rendering part once again, once you have let the client know where is hit you can perform the rendering based on the ray trace result.

    private static void renderObjectAt(Minecraft minecraft, EnvironmentObjectEffect object, World world, MatrixStack stack, float size, float offsetScale, ResourceLocation texture)
    {
        Vector3d vec = object.getVec();
        stack.push();
        Vector3d view = Minecraft.getInstance().gameRenderer.getActiveRenderInfo().getProjectedView();
        double x = vec.x - view.getX();
        double y = vec.y - view.getY();
        double z = vec.z - view.getZ();
        if (Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)) > 100.0F)
            return;
        stack.translate(x, y, z);
        Direction direction = object.getDirection();
        if (direction != null)
        {
            Vector3i offset = direction.getDirectionVec();
            stack.translate(offset.getX() * offsetScale, offset.getY() * offsetScale, offset.getZ() * offsetScale);
            rotateByDirection(stack, direction);
        }
        else
        {
            stack.rotate(minecraft.getRenderManager().getCameraOrientation());
            stack.rotate(Vector3f.ZP.rotationDegrees(180.0F));
        }
        if (object.doBlend())
        {
            Color colour = new Color(world.getBlockState(object.getPos()).getMaterialColor(world, object.getPos()).colorValue);
            RenderSystem.color4f(colour.getRed() / 255.0F, colour.getGreen() / 255.0F, colour.getBlue() / 255.0F, object.getTransparency());
        }
        AVAClientUtil.blit(stack, texture, -size, -size, size, size);
        RenderSystem.color4f(1.0F, 1.0F, 1.0f, 1.0F);
        stack.pop();
    }

direction is facing from the BlockRayTraceResult, and doBlend is true so it will look better with the block behind it.

The offset is required otherwise it will be on the same level with the block, the offset scale is a small number so there will not be an obvious gap between the wall and the texture object, the scale also prevents multiple objects overlap, for example when I have multiple "renderable objects":

            for (EnvironmentObjectEffect bulletHole : AVACommonUtil.cap(world).getBulletHoles())
                renderObjectAt(minecraft, bulletHole, world, stack, 0.075F, 0.01F, BULLET_HOLE);
            for (EnvironmentObjectEffect blood : AVACommonUtil.cap(world).getBloods())
                renderObjectAt(minecraft, blood, world, stack, 0.525F, 0.011F, BLOOD);
            for (EnvironmentObjectEffect knifeHole : AVACommonUtil.cap(world).getKnifeHoles())
                renderObjectAt(minecraft, knifeHole, world, stack, 0.095F, 0.0105F, KNIFE_HOLE);
            for (EnvironmentObjectEffect grenadeMark : AVACommonUtil.cap(world).getGrenadeMarks())
                renderObjectAt(minecraft, grenadeMark, world, stack, 2.5F, 0.075F, GRENADE_MARK);

bullet hole < knife hole < blood < grenade mark (level)

Red Image

Spoiler

DWecVSt.png

 

 

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

    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } }  
    • All versions of Minecraft Forge suddenly black screen even without mods (tried reinstalling original Minecraft, Java, updating drivers doesn't work)
    • When i join minecraft all ok, when i join world all working fine, but when i open indentity menu, i get this The game crashed whilst unexpected error Error: java.lang.NullPointerException: Cannot invoke "top.ribs.scguns.common.Gun$Projectile.getDamage()" because "this.projectile" is null crash report here https://paste.ee/p/0vKaf
  • Topics

×
×
  • Create New...

Important Information

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