Jump to content

[1.8] writing json to create an structure what library is avaliable ???


perromercenary00

Recommended Posts

good days

 

im beginig whith structures later a read that i could create a json defining the blocks and their positions fro what i been reading about json its looks not hard to do but,

 

well i know minecrafts came whith a bundle of utilities,

from this itulities what is the name of the best tool to write and read jsons ??

whith that i shall begin to make mi code

 

 

  //###########################################################3
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
    {
    	
    	
    	int x = pos.getX();
    	int y = pos.getY();
    	int z = pos.getZ();
    	
    	int tx = 16;
    	int ty = 16;
    	int tz = 16;
    	
    	int xmin = x - tx ,xmax = x + tx;
    	int ymin = y - ty ,ymax = y + ty;
    	int zmin = z - tz ,zmax = z + tz;
    	
    	
    	for (int dx = xmin ; dx < xmax ; dx++ ){
        for (int dy = ymin ; dy < ymax ; dy++ ){
        for (int dz = zmin ; dz < zmax ; dz++ ){
    	
    	BlockPos dpos = new BlockPos(dx,dy,dz);
    	
    	IBlockState blkst = worldIn.getBlockState(dpos);
    	Block  blk = blkst.getBlock();
    	int blkid = Block.getIdFromBlock(blk);
    	
    	if (!worldIn.isAirBlock(dpos))
    	{
    	System.out.println(blkid+"=blkid x="+dx+" dy="+dy+" dz="+dz );
    	
    	
    	String str=blkid+" "+dx+" "+dy+" "+dz;
    	
    	
    	String[] command = {"echo ",str," >> /home/tenchi/salida.txt"};
    	try {
		final Process process = Runtime.getRuntime().exec(command);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    	
    	
    	
    	
    	
    	
    	
    	}
    	
        }}}
    	
    	    	
    	
    return false;}
    
  //###########################################################3

 

 

Link to comment
Share on other sites

I don't want to be a dick here but, could you maybe write your sentences a bit clearer? Kinda hard to understand what you want with a thousand words combined into an incomplete sentence.

I am not a cat. I know my profile picture is sexy and amazing beyond anything you could imagine but my cat like features only persist in my fierce eyes. I might be a cat.

Link to comment
Share on other sites

You might be referring to my answer in another thread.

You can use whatever libary you want to do json and you can use your own structure..

 

this is the format I use though. You might find it helpfull

 

{
    "blocklist":{
        "-1621009973":// Unique block id for THIS file. it could be anything, as long as its unique for this file
             {
            "blockid":"blockDarkstoneSlab", // The blockname you would use in    GameRegistry.findBlock(modname,blockname);
             "modid":"MagicCookie",// The modname you would use in GameRegistry.findBlock(modname,blockname);
             "metadata":8//Metadata of the block
         }
    },
, "locations":
    [
        {
        "endz":2,
        "startx":0,
        "isRange":true,// if its a range I know I have to use fillWithMetadataBlocks for a range
        "endy":6,
        "starty":6,
        "endx":1,
        "block":"-160139907",// the unique block id as defined in blocklist
        "startz":6
        }, 
        {
        "isRange":false,// no range, single block
        "block":"1676165786",// the block id as defined in blocklist
        "z":6,
        "y":5,
        "x":6
        }
    ]
}

 

full example that I use in my magic cookies mod

 

https://gist.github.com/anonymous/65ac13603d26c3f72a76

 

Please note, dont make the error I made and rely on the minecraft way to load resources, it will break in server enviroment.

 

use

Modmain.getClass().getResource("/assets/modid/structures/stufftoload.json");

 

The first / is important, that is the root folder of your jar folder. Other wise it will load relative to where your main mod class is.

 

I am planning on writing a mod that will help modders save structures more easely. I already have the code, I just need to put it in a seperate mod heh.

 

You can download my magic cookies mod for now if you want. In creative there is an item called worldgenstripper.

 

Use the red one to save single blocks, the yellow one to save air, water and lave blocks(remember to also save flowblocks seperately). This is a ranged selector it needs two taps. one to set start and one to set finish. You can have start and finish on the same block.

 

You can use the orange one to save singular blocks within the ranged cuboid. it will save them one by one. this is handy for speed trials of how a structure comes out during generation.

 

Use the whiteish one to save full ranges of the same block. for big areas of the same stuff like walls, pillars and floors and such this is the one you want. the more is done this way the more you have a speed increase because theres no need for block look up whilst placing blocks(same goes for the yellow one).

 

To save to json name the red one in an anvil and stab a pig with it.  The pig wont get hurt but the stuff will get saved to a json file in a folder in your .minecraft directory.

 

Please note, the code isnt perfect yet, its just something I hacked together for my use and not for distribution.

 

Everything you saved in the worldgen stripper will get lost when server/singleplayer client restarts.

It will get lost if you hit an entity with the red one because the saved memory space gets cleared.

 

Everything will be saved relative to where you first struck ground with a  stripper.

 

Please note! its just something that works for me! and it works good for me, but it isnt optimised yet for use by others :P Take some time to get used to it if you use it.

 

**Note, my mod is for 1.7.10 but as far as I can see not much has changed in structure gen between 1.7 and 1.8

How much wood could a woodchuck chuck if a wood chuck could chuck wood - Guybrush Treepwood

 

I wrote my own mod ish... still a few bugs to fix. http://thaumcraft.duckdns.org/downloads/MagicCookies-1.0.6.4.jar

Link to comment
Share on other sites

JSON is cool and stuff, but honestly I found it is super easy to just use text file where you put the string block name, the metadata, x, y, z. Using the string block name is better than custom ids because theoretically it could save other mod's blocks (you'd need that mod when you generated the structure of course).

 

I think a key point in structure gen is whether the structure is "regular". If it is a cube or a wall, of course the most efficient way is to just list the dimensions and block type without listing every block placed. I think JSON makes sense for this.

 

Most of the structures I use in my mods are irregular, complex shapes that don't lend well to simple fill loops. But it really depends on your mod.

 

Anyway, if you're simply listing block position info I would not use custom ids and I would simply use text format.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

I use json because its a standard, and it is interexchangeable with other applications without them needing a custom parser.

Also if you look at my json you see i save mod and blocknames and metadata. I just define them once so i save the file space so parsing will be faster. No use having 2000 times MagicCookies BlockDarkstone if i can replace it with a shorter id.

 

And there is always room for fills. Air within chambers, walls, walkways.

 

A series of short fills of 2-3 blocks is faster than singular placement of each block.

How much wood could a woodchuck chuck if a wood chuck could chuck wood - Guybrush Treepwood

 

I wrote my own mod ish... still a few bugs to fix. http://thaumcraft.duckdns.org/downloads/MagicCookies-1.0.6.4.jar

Link to comment
Share on other sites

hele

 

tanks the word Gson gives tons of tutorials and i alredy have done mi class to write and read json files and actualy works but

 

well this works this way, i create a custom class just to store the values named "blockes" whith mi class "gsonle.java" i convert this class "blockes" whith all their values to string then it writes to the json using the FileWriter method an there is all the data in the json file 

 

i wanna store the values of  IBlockState but this one crash when try to save to the json file i find is becoze the block state  has "[]=" and this breaks the json structure, per example:

 

this is the IBlockState of the yellow flower block

minecraft:yellow_flower[type=dandelion]

 

if i let it this way it breaks minecraft when try to write the json so i have to do this little changes

storing the blockstates in a ArrayList<IBlockState>

 

public void setListOfStates(ArrayList<IBlockState> listOfStates) {

int longlistOfStates=listOfStates.size();
String str0="";
stalist.clear();

for (int lst = 0 ; lst < longlistOfStates  ; lst++)
{
	str0=listOfStates.get(lst)+"";
	str0=str0.replace("[type=", ":type:");
	str0=str0.replace("[", "");
	str0=str0.replace("]", "");

	stalist.add(str0);
}
}

 

this code takes away the "[]=" and store the data like a String and let the dandelion code like this in the json

 

stalist=[minecraft:yellow_flower:type:dandelion , minecraft:gold_ore, minecraft:gold_ore, minecraft:gold_ore, modmercenario:listarBlockes, minecraft:tallgrass:type:tall_grass , minecraft:tallgrass:type:tall_grass, minecraft:tallgrass:type:tall_grass, minecraft:tallgrass:type:tall_grass, minecraft:red_flower:type:poppy]

 

and this way is not breaking the minecraft when save and the json is fine i could get again the code for the yelow flower just doing strinreplace  but how i do recreate the IBlockState object from the string  "minecraft:yellow_flower[type=dandelion]"

 

IBlockState block00 = "minecraft:yellow_flower[type=dandelion]";

this not gona works

 

 

 

 

 

 

//######

i wana store the IBlockState as well to recreat the structure kepping the blocks facings

 

how do you make this ?? 

 

 

 

 

 

Link to comment
Share on other sites

Best way to handle this is to create dictionary. You should be after something that Forge does itself with block/item IDs. As you probably know when new world is created IDs are assigned to blocks and items and are stored internally inside world.

For every .json file you should make such dictionary. eg: The structure you want to save is made of different-coloured clay blocks.

 

Your json would be saved something like this: <internalID><IBlockState>, Example:

<0><minecraft:clay[type=red]>

<1><minecraft:clay[type=yellow]>

<2><minecraft:clay[type=green]>

Then your actual structure could be saved just as those internalIDs.

 

Obviously this all hav reason:

- File size

- Speed - most important.

Why is this design important?

To recreate anything inside code - which will be answer to your question on how to recreate IBlockState, you need to scan string - scanning it once (the dictionary of .json) and using internalID to read rest will get you at least few dozen times faster processing.

 

As to recreation - you will need to split your string into parts.

GameRegistry.findBlock - to get Block instance.

As to states and types:

Only thing that comes to my head is doing it on your own, scan strings, make switch, set state. There is probably some smart way, I will probably look into it if noone comments.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

hay

 

i find this when i was maken a custom crop

 

    public IBlockState getStateFromMeta(int meta)
    {
        return this.getDefaultState().withProperty(VARIANT, BlockDirt.DirtType.byMetadata(meta));
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(IBlockState state)
    {
        return ((BlockDirt.DirtType)state.getValue(VARIANT)).getMetadata();
    }

 

and do little experiment

 

                MovingObjectPosition mov = Minecraft.getMinecraft().objectMouseOver;
	BlockPos pos = mov.getBlockPos();
	  
    	
    	IBlockState blkst = worldIn.getBlockState(pos);
    	Block blk=blkst.getBlock();
    	
    	int meta = blk.getMetaFromState(blkst);
    	
    	
	chat.chatm(playerIn, "blkst"+blkst);
	chat.chatm(playerIn, "meta="+meta);
	    
	    
	IBlockState blkst0 = blk.getStateFromMeta(meta);
	pos = pos.east(2);

    	worldIn.setBlockState(pos, blkst0);

 

when you rigth click a block whith this item its copy the block 2m to the east conserving the block state

if i rigth click a block whitout this ttwo methods, well unti now it has no crash whith any of mi custom blocks looks safe

if you click a block whitout the methods to get the metadata it just create the block whith the default blockstate

 

i gonna use this

 

 

 

Link to comment
Share on other sites

I use json because its a standard, and it is interexchangeable with other applications without them needing a custom parser.

 

You're confusing the fact that JSON tags are standard, but your actual JSON tags are not standard. No JSON parser will know what to do with your tags in terms of Minecraft structure generation. Only your mod will understand it whether it is JSON or text.

 

Also if you look at my json you see i save mod and blocknames and metadata. I just define them once so i save the file space so parsing will be faster. No use having 2000 times MagicCookies BlockDarkstone if i can replace it with a shorter id.

 

In modern computers there is no issue with file space. I have 11,000 block structures in a text file that is only 400kB.

 

And there is always room for fills. Air within chambers, walls, walkways.

 

Yes, that is my point about "regular" structures. If you know there will be walls and fills you can certainly use a more concise format. And JSON makes sense for this. However, it depends on how you're making the JSON -- are you manually creating them or trying to capture based on something that is built? Because in the latter case you'll have to detect the regular fills in order to tag them properly.

 

A series of short fills of 2-3 blocks is faster than singular placement of each block.

 

I don't think so. You still have to place every block. As long as you only loop through each position once, I don't think there is any speed advantage either way.  What fill methods are you referring to?

 

Anyway, JSON will work of course and is a valid way. I'm just pointing out that there isn't that much advantage to it. Disk space is not an issue, speed won't be different, and complexity is higher with JSON. But it seems that you're comfortable with JSON so certainly go ahead with that.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

hellow again

 

mi code works but sometimes it breaks the doors at spawn i asume some doors dont have the metod to get metadata from state later i gonna fix that

now i have a little doub and its how you set the route to the json folders

 

in the code from Tschallacka there is this

 

Modmain.getClass().getResource("/assets/modid/structures/stufftoload.json");

 

hi has something in their main class to do this

 

for now i been storing json outside of mi mod folders in

"/home/tenchi/test.json"

 

but it must go in

"/home/tenchi/Modding/forge-1.8-11.14.1.1350-src/src/main/resources/assets/modmercenario/extructuras/"

 

yes i use linux if i just let this code this way it wont gona work in any computer diferent than the  mine

Link to comment
Share on other sites

I use linux too. Java is platform independant.(granted a few caveats with external libaries, but thats all)

 

I have nothing special in my main class. The .getClass() method is available in every class, in every method.

I just like to put outside pointers starting at a logical place.

 

You can call ANYWHERE in your code

 

getClass().getResource('/assets/modmercenario/extructuras/structure.json');

 

Move the doors to the last of your json file. Doors need a block to stand on or they will break.

Doors, torches, itemframes, grass, ladders, all need to come as last.

 

The only thing that comes to my mind is... does forge make a jar when you open the test client or does it load files from disc? I can see some issues from that.

You might want to modify it that if you are on test server you load from disc.

How much wood could a woodchuck chuck if a wood chuck could chuck wood - Guybrush Treepwood

 

I wrote my own mod ish... still a few bugs to fix. http://thaumcraft.duckdns.org/downloads/MagicCookies-1.0.6.4.jar

Link to comment
Share on other sites

mi code works but sometimes it breaks the doors at spawn i asume some doors dont have the metod to get metadata from state later i gonna fix that

 

Yeah, I've found you have to do structure generation in multiple passes because some blocks have their metadata automatically changed when placed. For example a torch gets different metadata based on whether there is a wall or not. And like you said doors, beds, etc. rely on order of placement.

 

And it is further complicated with blocks like tripwire because even though the metadata is 0 it will turn into an entityItem (of string) if you place it without a block under it.

 

So I place all regular blocks with metadata 0 first, then place metadata blocks, then any special blocks. Note you need to also consider blocks with inventory, like chests because you may want to populate specific items into them. After that I place entitItems and Entities.

 

Regarding loading the resource from a jar, I use standard Java file access resources in the JAR like this:

BufferedReader readIn = new BufferedReader(new InputStreamReader(getClass().getClassLoader()

                    .getResourceAsStream("assets/magicbeans/structures/"+structName+".txt"), "UTF-8"));

 

In my case I'm using text, but with GSON library I think maybe you can pass the reader to the GSON.jsonStreamReader() method.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

    Mercenary m = new Mercenary();

    m.getClass().getResource("/assets/modmercenario/extructuras/stufftoload.json")

System.out.println( m.getClass().getResource("/assets/modmercenario/extructuras/stufftoload.json") + " " );

 

returns  null

and it creates  file named null in side eclipse folder whith the json info inside

Link to comment
Share on other sites

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

    • Yes... You're right, this mod conflicts with very many other mods causing this error.
    • Hi, the microphone mod is not working on my Mac. It says “launcher does not support MacOS microphone permissions” Thank you in advance for answering.
    • Make sure you have Optifine installed as a mod. Go into Options > Video Settings > Shaders > and then click the shader you want Make sure the shader.zip files are in the shaderpacks folder inside the minecraft folder
    • It sounds like you're probably registering the item in the wrong place, try looking at this tutorial for how to register items:  Forge Modding Tutorial - Minecraft 1.20: Custom Items & Creative Mode Tab | #2 This (free) tutorial series is excellent, by the way, and I'd highly recommend watching through some or all of the videos. There may also be an error in the code I showed above since I was in a hurry, but it should be enough for the general idea. I can't be more specific since I don't know exactly what you plan to do.
    • Realizing I was a victim of a scam was a devastating blow. My initial investment of $89,000, driven by dreams of financial success and the buzz surrounding a new cryptocurrency project, turned into a nightmare. The project promised high returns and rapid gains, attracting many eager investors like myself. However, as time passed and inconsistencies began to surface, it became evident that I had made a grave mistake by not thoroughly vetting the brokerage company handling the investment. Feeling anxious and betrayed, I desperately searched for a way to recover my funds. It was during this frantic search that I stumbled upon the Lee Ultimate Hacker tool through a Facebook post. With little left to lose, I decided to reach out to their team for help. To my relief, they were quick to respond and immediately started recovering my compromised email and regaining access to my cryptocurrency wallets. The team at Lee Ultimate Hacker was incredibly professional and transparent throughout the process. They meticulously traced the digital footprints left by the scammers, employing advanced technological methods to unravel the complex network that had ensnared my funds. Their expertise in cybersecurity and recovery strategies gradually began to turn the tide in my favor. Although the scammers had already siphoned off $30,000 worth of Bitcoin, Lee Ultimate Hacker was relentless in their pursuit. They managed to expose the fraudulent activities of the scam operators, revealing their identities and the mechanisms they used to lure investors. This exposure was crucial not only for my case but also as a warning to the wider community about the perils of unverified investment schemes. As we progressed, it became a race against time to retrieve the remaining $59,000 before the scammers could vanish completely. Each step forward was met with new challenges, as these criminals constantly shifted tactics and moved their digital assets to evade capture. Nonetheless, the determination and skill of the recovery team kept us hopeful. Throughout this ordeal, I learned the hard value of caution and due diligence in investment, especially within the volatile world of cryptocurrency. The experience has been incredibly taxing, both emotionally and financially, but the support and results provided by Lee Ultimate Hacker have been indispensable. The recovery process is ongoing, and while the final outcome remains uncertain, the progress made so far gives me hope. The battle to recover the full amount of my investment continues, and with the expertise of Lee Ultimate Hacker, I remain optimistic about the eventual recovery of my funds. Their commitment to their clients and proficiency in handling such complex cases truly sets them apart in the field of cyber recovery. LEEULTIMATEHACKER@ AOL. COM   Support @ leeultimatehacker . com.  telegram:LEEULTIMATE   wh@tsapp +1  (715) 314  -  9248     
  • Topics

×
×
  • Create New...

Important Information

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