Jump to content

Recommended Posts

Posted

I have been looking to incorporate a minimap into my mod for some time, and have been researching other mods including FTBChunks and Xaero's Minimap, except trying to just copy what they do is turning out incredibly difficult due to the huge amount of features and dependencies they have that I don't need. I've decided it's best to avoid creating a black box section of my codebase I don't understand (and have much more feature control) and just start writing my own minimap.

The naive approach to this is probably:

  1. Look at all the blocks in the vicinity of the player
  2. Get the average texture colour for each block
  3. Do logic related to elevation, water depth, etc. to adjust colour
  4. Blit a rect to the screen of that colour
  5. Repeat for every single block in range

Except of course this sounds incredibly performance taxing considering there could be 1000s of blocks around you and only gets worse when zooming out the map.

What kind of techniques do these mods use to improve performance?

I also don't want to use the vanilla map item renderer so that I can have more granular control over textures like these minimap mods do, though if there are useful techniques or helper functions it has I could use those too.

Posted

Ok so I tried the above, but am finding that drawing 40000 rectangles (100 radius square) every tick is so expensive I effectively can't play the game.

Is there an alternative to this that I can take? eg. somehow building up the image in memory before calling GuiComponent.

Credit to this old post for pointing me to right functions for updateMapColourData. Unfortuantely the post is fairly old and the repo is gone so I can't figure out what that fill function used actually was.

This is my current code:

    private static final Minecraft MC = Minecraft.getInstance();
    public static List<Integer> mapColourData = new ArrayList<>();
    public static final int RADIUS = 100;
    private static final int mapRefreshTicksMax = 100;
    private static int mapRefreshTicksCurrent = 100;

    public static void updateMapColourData()
    {
        if (MC.level == null)
            return;

        long timeBefore = System.currentTimeMillis();

        mapColourData = new ArrayList<>();
        for (int x = (int) MC.player.getX() - RADIUS; x < (int) MC.player.getX() + RADIUS; x++)
        {
            for (int z = (int) MC.player.getZ() - RADIUS; z < (int) MC.player.getZ() + RADIUS; z++) {
                int y = MC.level.getChunkAt(new BlockPos(x,0,z)).getHeight(Heightmap.Types.WORLD_SURFACE, x, z);
                int col = MC.level.getBlockState(new BlockPos(x,y,z)).getMaterial().getColor().col;

                // add 0xFF000000 to include 100% transparency
                mapColourData.add(col + (1677721600));
            }
        }

        System.out.println("updated in: " + (System.currentTimeMillis() - timeBefore) + "ms");
        System.out.println("blocks: " + mapColourData.size());
    }

    public static void renderMap(PoseStack poseStack, int x0, int y0) {
        int index = 0;

        for (int x = x0 - RADIUS; x < x0 + RADIUS; x++) {
            for (int y = y0 - RADIUS; y < y0 + RADIUS; y++) {
                if (index < mapColourData.size()) {
                    GuiComponent.fill(poseStack, x, y, x+1, y+1, mapColourData.get(index));
                    index += 1;
                }
            }
        }
    }

    @SubscribeEvent
    public static void renderOverlay(RenderGameOverlayEvent.Post evt) {
        mapRefreshTicksCurrent -= 1;

        if (mapRefreshTicksCurrent <= 0) {
            mapRefreshTicksCurrent = mapRefreshTicksMax;
            updateMapColourData();
        }
        renderMap(evt.getMatrixStack(), 0,0);
    }

 

Posted (edited)

Hi, I had actually just finish implementing a similar feature, so I find I may be able to help here.
The previous way (calling fill for every pixel) is definitely going to eat up lots of performance, thus it's not an ideal way.

This is what it looks like:

g7a7CbJ.png

 

As always, I'm not able to guarantee the efficiency and if it's the correct way/best practice to do so, so please take this as a reference only.

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

You will then get a list of integers ("packed id" of material colours), and you are able to create a new DynamicTexture, fill in all the pixels, and register a render type of RenderType.textSeeThrough() with your texture. Then, you can render the map with your renderType along with your positioned texture.

 

    
    static DynamicTexture MAP_TEXTURE;
    static RenderType MAP_RENDER_TYPE;

    public static void run(UpdateScoreboardMapMessage message)
    {
        AVAScoreboardManager manager = AVAWorldData.getInstance().scoreboardManager;
        manager.updateMap(message.compound);
        if (AVARenderer.MAP_TEXTURE != null)
            AVARenderer.MAP_TEXTURE.close();
        AVARenderer.MAP_TEXTURE = new DynamicTexture(manager.getMapWidth(), manager.getMapHeight(), true);
        NativeImage pixels = AVARenderer.MAP_TEXTURE.getPixels();
        if (pixels != null && manager.hasMap())
        {
            for (int y = 0; y < manager.getMapHeight(); y ++)
                for (int x = 0; x < manager.getMapWidth(); x ++)
                    pixels.setPixelRGBA(x, y, MaterialColor.getColorFromPackedId(manager.getMapColours().get(x + y * manager.getMapWidth())));
            AVARenderer.MAP_TEXTURE.upload();
            AVARenderer.MAP_RENDER_TYPE = RenderType.textSeeThrough(Minecraft.getInstance().textureManager.register(AVA.MODID + "_" + "scoreboard_map", AVARenderer.MAP_TEXTURE));
        }
    }

(Maybe it is not the proper way of resource managing??)

 

    private static void renderMap(PoseStack stack, Direction direction, float x, float y, float x2, float y2)
    {
        MultiBufferSource.BufferSource buffer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
        VertexConsumer consumer = buffer.getBuffer(MAP_RENDER_TYPE);
        Matrix4f matrix4f = stack.last().pose();

        putTextureVertex(consumer, matrix4f, x, y, x2, y2, AVAConstants.VANILLA_FULL_PACKED_LIGHT, 0.8F, direction);
        buffer.endBatch();
    }

 

    public static void putTextureVertex(VertexConsumer consumer, Matrix4f matrix4f, float x, float y, float x2, float y2, int light, float alpha, @Nullable Direction direction)
    {
        int a = (int) (alpha * 255.0F);
        consumer.vertex(matrix4f, x, y2, 0.0F).color(255, 255, 255, a).uv(0.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y2, 0.0F).color(255, 255, 255, a).uv(1.0F, 1.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x2, y, 0.0F).color(255, 255, 255, a).uv(1.0F, 0.0F).uv2(light).endVertex();
        consumer.vertex(matrix4f, x, y, 0.0F).color(255, 255, 255, a).uv(0.0F, 0.0F).uv2(light).endVertex();
    }

 

Hopefully this helps a bit with the direction.

Edited by poopoodice
Posted (edited)

Ok I tried this flow here and its just producing a fully black square on my screen:

The mapRefreshTicksMax timer is just 100ms

updateMapColours() is the same as the function I posted above (producing a 40000-size array of ARGB values) and is correctly producing the data

updateMapTexture() is the same as your run() function except I don't reinitialise MAP_TEXTURE every call (that was causing a crash)

renderMap() is also the same as yours, except I'm not sure what the value of light is supposed to be for putTextureVertex() (I experimented with values ranging 1-255 and found no difference)

Just to be sure its not my data causing the issue I also tried hardcoding pixels.setPixelRGBA(0x7F7F7F7F) which should have at least changed the square to a solid grey but no change.

Ok I think when removed the initialisation of MAP_TEXTURE every tick I also had to remove the MAP_TEXTURE.close(), and that solved it.

Thanks for the reference code, it was really helpful

Edited by SoLegendary
solved it
Posted (edited)

Just noticed some potential problems:
1. You are always using the same instance of DynamicTexture, but closes/dispose it every update.

2. RenderGameOverlayEvent.Post is called multiple times every render tick, it means you are refreshing your map every 1~2 seconds, depend on the render rate.

3. Continue with 2., you are rendering multiple times (it gets called whenever an element is being rendered, e.g. health bar, crosshair, helmet... if you are using 1.16, otherwise you need to register your overlay instead of using the event) every frame, check for ElementType.ALL (or something similar) and do the render.

Edited by poopoodice
Posted

Regarding the map elevation and shading effects that the vanilla map item has using MapItem.update(), how did you apply this same effect to your map? It's not quite as simple as copying the same function as it seems to be designed for use of a MapItemSavedData object as opposed to an ARGB Array. Did you first convert the array to a MapItemSavedData object or did you rewrite the function to work on an ARGB array?

Posted

You are directly using the plain material colour of the block currrently.

If you want anything more

Quote

For how to get map colours check out MapItem#update. The first two for loops are z and x coordinates, and the other two should be x2 and z2 offset coordinates (I think they are used for blending colours around... not really sure and didn't look into it).

 

Posted

Actually if I'm not mistaken, the vanilla map shading just does three things (assuming this map is north facing):

1. if the block directly north is a higher Y, shade it darker

2. if the block directly north is a lower Y, shade it lighter

3. Shade water blocks lighter for shallower, darker for deeper

image.png

Posted (edited)

Ok so it's all working now - just one last thing - How can I rotate the rendered map? I just want it to be rotated 45 degrees so it can be rendered diamond-shaped.

Similarly I want to blit a background for the map (just the map item texture as held in the players' hands) which also needs to be rotated 45 degrees.

EDIT: putting this in a new topic post

 

Edited by SoLegendary
moved to new post

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

    • Forge only supports Java Edition, you'll need to ask elsewhere for Pocket Edition support. Also, don't post in unrelated topics. I've split your post into its own topic.
    • How do I download mods for minecraft pe
    • I've tried multiple ways to get the chunk coordinates and none of them have worked, so I'm guessing it may be getChunk().  Is there another way to forcibly load a chunk on that same tick? If all else fails I guess I can just delay my action by a tick, but that's a pain in the butt and makes it more complex to provide appropriate feedback... Also welcome, Zander.  If you're searching for a similar solution, I hope this (eventually) helps you too 😅
    • My guess would be that you are not getting the chunk coordinates right, or getChunk dosnt work.
    • Hello, Recently I have been hosting an RLcraft server on Minecraft Forge Version 1.12.2 - 14.23.5.2860 I originally had lag issues and I chalked it up to playing on less than perfect hardware so I moved the server to better hardware(i9-9900k with 64GB of RAM for 1 player.) After lots of troubleshooting I discovered a couple of things. World saving was causing the MSPT to spike to over 2000Miliseconds and was happening every minute. This kind of makes sense as the world was pre-generated and is over 100GB. I learned that I could turn off world saving and just schedule that and that resolved that issue. After that issue was resolved I discovered another issue. It appears that when exploring chunks, any chunks explored stay loaded. They persist. I was originally thinking that this had to be a mod issue, but it didn't seem like anyone was talking about it. This isn't really a problem on packs with few worldgen mods or just few mods in general, but on beefier packs it becomes a problem. I went through forge changelogs and found this line. Build: 1.12.2-14.23.5.2841 - Thu Aug 29 01:58:50 GMT 2019 bs2609: Improve performance of persistent chunk checks (#5706) Is this a related item to what I am dealing with or just something else?   I went ahead and created a new dedicated server with Just Forge 14.23.5.2860, spark reforged, and it's core mods. I was able to replicate the issue and log it with spark. Hopefully you're able to see this spark profile. It basically shows that as I explored the chunk loading persisted(2000 chunks loaded over 10 minutes with one player)The view distance is set to 10 so that should be 200 chunks per player. If I don't move the loaded chunks are 200. I was however able to fix the persistent chunk issue if I save the world more frequently. My question is, is this intended function of the game or is this a bug? Everywhere I read seems to indicate Minecraft servers save every 5 minutes and not every minute. Can chunks not unload if the world does not autosave. Additionally. Autosave specifically appears to fix this issue. Manually running save-all does not resolve the issue.   I realize this is kind of a log one, sorry. Please let me know if you require further information. Thanks in advance for your time. https://spark.lucko.me/NvlMtC39Yt https://imgur.com/a/K0oyukx https://pastebin.com/z0qGu1Vh  
  • Topics

×
×
  • Create New...

Important Information

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