Jump to content

Recommended Posts

Posted (edited)

Hello, my goal is to create a mod that can protect portions of the map, something like the famous "Towny / Faction" plugin. Working daily on Android and websites have always been used to using relational databases. While here on the forge I noticed that many programmers prefer to use the internal system "WorldSavedData".

 

So I ask you that you definitely have more experience with me with the mods.

-  What is the best approach to implementing my project?
-  To save the data I use: Database; jSON; Java Sql, WorldSavedData?
-  How do I handle the Client / Server synchronization problem?

Edited by JdiJack
Posted

I forgot to say, I chose to use a custom GUI to modify the parameters of the various areas (see screenshot below).

I start the GUI client side, is it correct?

2017-10-02_10.58.24.png

Posted

Well the first thing I'd ask is whether the areas can be represented "algorithmically" or if they need to be block by block. For example, if the GUI involves drawing rectangles to define the area then really only two points need to be saved per rectangle and I'm assuming there wouldn't be a great many overall areas.

 

In other words, if you want to save rectangular areas I don't think you need to store information for every block within that area. For rectangles I'd just create a simple class to store the two corners and then make a list of those rectangles. I would probably save it on the server side as world data with a simply serializer.

 

My next question is what exactly you mean by "protect" but assuming you mean it is not modifiable by players you can basically override/intercept all the player interaction with the blocks and cancel it if is within the areas.

 

Lastly, for syncing between client and server it may happen "automatically" if the modifiability is determined by the server. I'm not sure exactly how breaking blocks works, but several things send the user input (the mouse click) to the server that then takes the action (or in your case prevents the action) and then the results are automatically synced back to client. However, there are other things like movement where the client tries to do some processing to make it smoother and that might cause visual glitches while the server sync catches up.

 

So if you want client itself to be aware of the protected area, I would simply send a custom packet to the client whenever a player joins the world and resend any updates to all players if there is a change in the area definitions.

  • Like 1

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

Posted (edited)
  On 10/3/2017 at 3:46 AM, jabelar said:

Well the first thing I'd ask is whether the areas can be represented "algorithmically" or if they need to be block by block. For example, if the GUI involves drawing rectangles to define the area then really only two points need to be saved per rectangle and I'm assuming there wouldn't be a great many overall areas.

In other words, if you want to save rectangular areas I don't think you need to store information for every block within that area. For rectangles I'd just create a simple class to store the two corners and then make a list of those rectangles. I would probably save it on the server side as world data with a simply serializer.

Expand  

No, the areas are determined by the sum of the selected blocks. Areas can also be different from simple rectangles.

 

  On 10/3/2017 at 3:46 AM, jabelar said:

My next question is what exactly you mean by "protect" but assuming you mean it is not modifiable by players you can basically override/intercept all the player interaction with the blocks and cancel it if is within the areas.

Expand  

Exactly, but this should not be a problem for the time being.

  On 10/3/2017 at 3:46 AM, jabelar said:

So if you want client itself to be aware of the protected area, I would simply send a custom packet to the client whenever a player joins the world and resend any updates to all players if there is a change in the area definitions.

Expand  

This is the logic I had imagined myself.
The problem though is to understand how to implement the packages that the server must send to the client.

Try to explain me better:

I currently have a "Area.java" class that stores all the information about a single area:

- area name
- tenant
- taxes
- permissions
- List <BlockClaim.java>

I have two questions:
1) Can I save/load the "Area.java" class in WorldSavedData?
2a) Can I send the "Area.java" class with packages?
2b) Do you want to convert the "Area.java" class to json, and send the json through packets?

Edited by JdiJack
Posted

You just need to create an NBT compound that contains your data of your area class, which may be a simple as the name to identify the compound as an Area and four integers (two sets to define two corners of the rectangle). If you have NBT tag it is very easy to append to world data and also to serialize into packets. I think the byte buffer helper class has ability to write / read NBT from packet payloads and world save data is already NBT so you just add your data and it will automatically get saved and loaded (you'll still need to read it out after loading) to and from file.

  • Like 1

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

Posted
  On 10/3/2017 at 4:09 PM, jabelar said:

Devi solo creare un composto NBT che contiene i tuoi dati della tua classe di zona, che può essere semplice come il nome per identificare il composto come area e quattro interi (due set per definire due angoli del rettangolo). Se hai un tag NBT, è molto facile aggiungere i dati del mondo e anche serializzarlo in pacchetti. Penso che la classe di assistente di buffer di byte abbia la capacità di scrivere / leggere NBT dai pacchetti di payload e i dati di salvataggio del mondo sono già NBT in modo da semplicemente aggiungere i tuoi dati e sarà automaticamente salvato e caricato (dovrai ancora leggerlo dopo il caricamento ) da e verso il file.

Expand  

thank you, I will try to get me to work and keep you up to date on the code that I will produce

Posted (edited)

I worked a bit and I produced this code:

 

AreeData class (WorldSavedData)

  Reveal hidden contents

 

methods to write/read NBT

  Reveal hidden contents

 

I want to save in my WorldSavedData class "AreeData" the result of this method

  Reveal hidden contents

 

Edited by JdiJack
Posted

Well one thing I think you're missing is the coordinates of the area itself.

 

I would have four double fields (or have a "rectangle" class) with four double fields that represent x1, z1, x2, z2 in the world. I would then have setter and getter methods for those points. In the write to NBT, I would write the four double values and in the read from NBT I would read the four double values.

 

Also, you should look at the official forge documentation for worldsavedata https://mcforge.readthedocs.io/en/latest/datastorage/worldsaveddata/.

 

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

Posted

Why doubles? Why not integers or longs?

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
  On 10/4/2017 at 3:24 PM, jabelar said:

Beh, una cosa che penso di essere mancante è la coordinazione dell'area stessa.

 

Avrei quattro campi doppio (o avere una classe "rettangolo") con quattro doppie campi che rappresentano x1, z1, x2, z2 nel mondo. Avrei poi metodi setter e getter per questi punti. Nella scrittura a NBT scrivo i quattro valori duplici e nella lettura da NBT leggerei i quattro valori doppie.

 

Inoltre, è necessario esaminare la documentazione ufficiale di forge per worldsavedata  https://mcforge.readthedocs.io/en/latest/datastorage/worldsaveddata/ .

 

Expand  

As I said before, the areas I want to get must NOT be rectangles, but they can take any shape, so I need to track every block.

Please pay attention to this aspect and help me instead of the code I have extended. I have read the documentation https://mcforge.readthedocs.io/en/latest/datastorage/worldsaveddata/ several times.

My question is:
1) Is my code correct?
2) how do i save my ntb in worldsavedata class?

Posted

First of all, we can't really tell if your code is correct. That is up to you. The general approach looks correct but you have to verify the details. Have you tried to run the code? Did it work?

 

If you read the documentation it already explains how the saving works. It happens automatically as part of extending the world data class and using the setData() method.

 

To test your code you simply need to add console statements to follow the execution. If you put console statements in the right places you will be able to easily determine whether the code runs, when it runs, and the value of any key fields during the execution.

  • Like 1

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

Posted (edited)
  On 10/5/2017 at 1:39 AM, jabelar said:

First of all, we can't really tell if your code is correct. That is up to you. The general approach looks correct but you have to verify the details.

Expand  

Thank you, my goal was to understand this.

 

  On 10/5/2017 at 1:39 AM, jabelar said:

To test your code you simply need to add console statements to follow the execution. If you put console statements in the right places you will be able to easily determine whether the code runs, when it runs, and the value of any key fields during the execution.

Expand  

Although I have not yet understood how to pass and assign the result of "getNBTListAree ()" to "writeToNBT (NBTTagCompound nbt)"

 

Nuova immagine bitmap.jpg

Edited by JdiJack
Posted (edited)

You use the tag compound's setTag() method to add other NBTBase objects, including NBTList to the compound. So in your case if you take the NBTCompound (like the world data compound or you can create a new NBTTagCompound depending on what exactly you're doing at the time.) and go setTag("area_claim_list", getNBTListArea()) it should add it to the compound.

Edited by jabelar
  • Like 1

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

Posted

I think I'm close to the solution, the problem is that the "readFromNBT" and "writeToNBT" methods are never called, although I call "markDirty ()".

Class Code "WorldSavedData":

  Reveal hidden contents

 

another class code to save a new NTB:

  Reveal hidden contents

code to recover NTB saved:

  Reveal hidden contents

 

Posted

Okay, I was playing with this a bit, coding it my own way and I have a few tips and suggestions.

 

First of all, the world saved data class should also contain the fields that you're interested in changing. Those fields can in fact be simply a list of instances of another class, but the point is that you should be doing the converting between NBT read from file and the class field values.

 

So the way I would do it is that the world saved data class will contain a list of the protected area instances. But the world saved data class should also be used to set the data in those area instances because you need to know when they change to markDirty() properly.

 

Furthermore you have to develop the writeToNBT() and readFromNBT() methods. They should basically use tag lists to hold the list of areas which in turn hold the list of blocks within the area.

 

So for example, here is my protected area class example (note that I only stored name and list of block positions, in your code you should add other things like tenant, taxes and such):

 

public class ProtectedArea 
{
	private String name;
	private List<BlockPos> listBlocks = new ArrayList<BlockPos>();

	/**
	 * Instantiates a new protected area.
	 *
	 * @param parName the par name
	 */
	public ProtectedArea(String parName)
	{
		name = parName;
	}
	
	/**
	 * Gets the name.
	 *
	 * @return the name
	 */
	public String getName() { return name; }
	
	/**
	 * Adds the block position to the protected blocks list.
	 *
	 * @param parPos the par pos
	 */
	public void addBlock(BlockPos parPos)
	{
		listBlocks.add(parPos);
	}
	
	/**
	 * Removes the block position from the protected blocks list.
	 *
	 * @param parPos the par pos
	 */
	public void removeBlock(BlockPos parPos)
	{
		listBlocks.remove(parPos);
	}
	
	/**
	 * Clears the protected blocks.
	 */
	public void clearBlocks()
	{
		listBlocks.clear();
	}
	
	/**
	 * Gets the protected block list.
	 *
	 * @return the protected block list
	 */
	public List<BlockPos> getProtectedBlockList() { return listBlocks; }
	
	/**
	 * Gets the block list tag.
	 *
	 * @return the block list tag
	 */
	public NBTTagList getBlockListTag()
	{
		NBTTagList tagList = new NBTTagList();
		Iterator<BlockPos> iterator = listBlocks.iterator();
		while (iterator.hasNext())
		{
			BlockPos pos = iterator.next();
			NBTTagCompound posCompound = new NBTTagCompound();
			posCompound.setInteger("x", pos.getX());
			posCompound.setInteger("y", pos.getY());
			posCompound.setInteger("z", pos.getZ());
			tagList.appendTag(posCompound);
		}
		return tagList;
	}
}

 

And my example of the class that extends WorldSavedData is:

 

public class ProtectedAreaData extends WorldSavedData
{
	private static final String DATA_NAME = MainMod.MODID + "_data_aree";
	private List<ProtectedArea>  listAreas = new ArrayList<ProtectedArea>();
	
	/**
	 * Instantiates a new protected area data.
	 */
	public ProtectedAreaData() 
	{
		super(DATA_NAME);
	}

	/**
	 * Instantiates a new protected area data.
	 *
	 * @param name the name
	 */
	public ProtectedAreaData(String name) 
	{
		super(name);
	}
	
	/**
	 * Gets the world saved data instance associated to a given world.
	 *
	 * @param world the world
	 * @return the data instance
	 */
	public static ProtectedAreaData getDataInstance(World world) 
	{
		MapStorage storage = world.getMapStorage();
		ProtectedAreaData instance = (ProtectedAreaData) storage.getOrLoadData(ProtectedAreaData.class, DATA_NAME);
		if (instance == null) {
			instance = new ProtectedAreaData();
			storage.setData(DATA_NAME, instance);
		}
		return instance;
	}
	
	/**
	 * Adds the area to the list of protected areas.
	 *
	 * @param parArea the par area
	 */
	public void addArea(ProtectedArea parArea)
	{
		listAreas.add(parArea);
		markDirty();
	}
	
	/**
	 * Removes the area from the list of protected areas.
	 *
	 * @param parArea the par area
	 */
	public void removeArea(ProtectedArea parArea)
	{
		listAreas.remove(parArea);
		markDirty();
	}
	
	/**
	 * Clear the protected areas list.
	 */
	public void clearAreas()
	{
		listAreas.clear();
		markDirty();
	}
	
	/**
	 * Gets the area by name.
	 *
	 * @param parName the par name
	 * @return the area by name
	 */
	@Nullable
	public ProtectedArea getAreaByName(String parName)
	{
		Iterator<ProtectedArea> iterator = listAreas.iterator();
		while (iterator.hasNext())
		{
			ProtectedArea area = iterator.next();
			if (area.getName().equals(parName))
			{
				return area;
			}
		}
		
		return new ProtectedArea(parName);
	}
	
	/**
	 * Adds the block to a given area.
	 *
	 * @param parName the par name
	 * @param parPos the par pos
	 */
	public void addBlockToArea(String parName, BlockPos parPos)
	{
		getAreaByName(parName).addBlock(parPos);
		markDirty();
	}
	
	/**
	 * Removes the block from a given area.
	 *
	 * @param parName the par name
	 * @param parPos the par pos
	 */
	public void removeBlockFromArea(String parName, BlockPos parPos)
	{
		getAreaByName(parName).removeBlock(parPos);
		markDirty();
	}
	
	/**
	 * Clear blocks from area.
	 *
	 * @param parName the par name
	 */
	public void clearBlocksFromArea(String parName)
	{
		getAreaByName(parName).clearBlocks();
		markDirty();
	}
	
	/**
	 * Checks if a block position is protected.
	 *
	 * @param parPos the par pos
	 * @return true, if is block pos protected
	 */
	public boolean isBlockPosProtected(BlockPos parPos)
	{
		Iterator<ProtectedArea> iteratorArea = listAreas.iterator();
		while (iteratorArea.hasNext())
		{
			ProtectedArea area = iteratorArea.next();
			if (area.getProtectedBlockList().contains(parPos))
			{
				return true;
			}
		}
		
		return false;
	}
	
	/* (non-Javadoc)
	 * @see net.minecraft.world.storage.WorldSavedData#readFromNBT(net.minecraft.nbt.NBTTagCompound)
	 */
	//load
	@Override
	public void readFromNBT(NBTTagCompound nbt) 
	{
		listAreas.clear();
		
		NBTTagList tagListAreas = nbt.getTagList("Protected Areas", 10); // 10 indicates a list of NBTTagCompound
		Iterator<NBTBase> iterator = tagListAreas.iterator();
		while (iterator.hasNext())
		{
			NBTTagCompound areaCompound = (NBTTagCompound) iterator.next();
			ProtectedArea area = new ProtectedArea(areaCompound.getString(areaCompound.getString("Area Name")));
			listAreas.add(area);
			NBTTagList tagListPos = areaCompound.getTagList("Block List", 10);
			
			Iterator<NBTBase> iterator2 = tagListPos.iterator();
			while (iterator2.hasNext())
			{
				NBTTagCompound posCompound = (NBTTagCompound) iterator2.next();
				BlockPos pos = new BlockPos(
						posCompound.getInteger("x"),
						posCompound.getInteger("y"),
						posCompound.getInteger("z")
						);
				area.addBlock(pos);	
			}
		}
	}

	/* (non-Javadoc)
	 * @see net.minecraft.world.storage.WorldSavedData#writeToNBT(net.minecraft.nbt.NBTTagCompound)
	 */
	//save
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt) 
	{	
		NBTTagList tagList = new NBTTagList();
		
		// cycle through the list of areas
		Iterator<ProtectedArea> iteratorArea = listAreas.iterator();
		while (iteratorArea.hasNext())
		{
			NBTTagCompound tagCompound = new NBTTagCompound();
			ProtectedArea area = iteratorArea.next();
			tagCompound.setString("Area Name", area.getName());
			tagCompound.setTag("Block List", area.getBlockListTag());
			tagList.appendTag(tagCompound);
		}

		nbt.setTag("Protected Areas", tagList);
		return nbt;
	}
}

 

NOTE: I have not tested this code yet. But I think the general approach should work well. It is very similar to the world data implemented for the ItemMap.

 

Now, when the player is changing things in your GUI you can use the methods to add the blocks and such as you need.

 

In summary, I think you need to have the informations in fields that are in the world save data class and you should furthermore implement the writeToNBT() and readFromNBT() to suit the information you want to save.

 

For syncing the client, you will have to send the world data yourself as a custom packet. The good news is that the minecraft packet can accept NBT directly as a payload.

 

I hope that helps. I need to go to be as it is past midnight ...

  • Like 1

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

Posted
  On 10/7/2017 at 8:01 AM, jabelar said:
  Reveal hidden contents

 

Expand  

Thank you very much for your help, I appreciate it very much.
Conceptually your work is perfect, but my problem is another one.
I can not call the "writeToNBT ()" and "readFromNBT ()" methods. I will probably abandon WorldSaveData and implement a system that stores NTBCompaund directly on Disk

Posted
  On 10/7/2017 at 8:17 AM, JdiJack said:

I can not call the "writeToNBT ()" and "readFromNBT ()" methods

Expand  

 

Why not?

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted (edited)

I've implemented a simple class like this and I can not get it running. I'm desperate are 7 days trying to run WorldSaveData, I'm tired

 


 

Edited by JdiJack
Posted
  On 10/7/2017 at 8:17 AM, JdiJack said:

Thank you very much for your help, I appreciate it very much.
Conceptually your work is perfect, but my problem is another one.
I can not call the "writeToNBT ()" and "readFromNBT ()" methods. I will probably abandon WorldSaveData and implement a system that stores NTBCompaund directly on Disk

Expand  

 

You should never need to call those functions. You should just need to markDirty(). If you look in my example, the whole point is that all the methods that can change data also do the markDirty().

 

You need to have the data in (or directly accessible from) the class that extends WorldSaveData, and then you should only change the data through that class -- you'll notice that I have methods in my data class that are used to access the data within the contained area classes -- you should not change the area information directly.

 

So, as long as: 

1) your world data is properly appended to the vanilla world data with the set method

2) you only change data through the world data class

3) you mark dirty every time there is a change.

 

Then you should be good.

 

Once you have that working, the next topic is to sync to client!

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

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



×
×
  • Create New...

Important Information

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