github.com/df-mc/dragonfly@v0.9.13/server/player/playerdb/inventory.go (about)

     1  package playerdb
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/df-mc/dragonfly/server/internal/nbtconv"
     6  	"github.com/df-mc/dragonfly/server/item"
     7  	"github.com/df-mc/dragonfly/server/player"
     8  	"github.com/sandertv/gophertunnel/minecraft/nbt"
     9  )
    10  
    11  func invToData(data player.InventoryData) jsonInventoryData {
    12  	d := jsonInventoryData{
    13  		MainHandSlot: data.MainHandSlot,
    14  		OffHand:      encodeItem(data.OffHand),
    15  	}
    16  	d.Items = encodeItems(data.Items)
    17  	d.Boots = encodeItem(data.Boots)
    18  	d.Leggings = encodeItem(data.Leggings)
    19  	d.Chestplate = encodeItem(data.Chestplate)
    20  	d.Helmet = encodeItem(data.Helmet)
    21  	return d
    22  }
    23  
    24  func dataToInv(data jsonInventoryData) player.InventoryData {
    25  	d := player.InventoryData{
    26  		MainHandSlot: data.MainHandSlot,
    27  		OffHand:      decodeItem(data.OffHand),
    28  		Items:        make([]item.Stack, 36),
    29  	}
    30  	decodeItems(data.Items, d.Items)
    31  	d.Boots = decodeItem(data.Boots)
    32  	d.Leggings = decodeItem(data.Leggings)
    33  	d.Chestplate = decodeItem(data.Chestplate)
    34  	d.Helmet = decodeItem(data.Helmet)
    35  	return d
    36  }
    37  
    38  func encodeItems(items []item.Stack) (encoded []jsonSlot) {
    39  	encoded = make([]jsonSlot, 0, len(items))
    40  	for slot, i := range items {
    41  		data := encodeItem(i)
    42  		if data == nil {
    43  			continue
    44  		}
    45  		encoded = append(encoded, jsonSlot{Slot: slot, Item: data})
    46  	}
    47  	return
    48  }
    49  
    50  func decodeItems(encoded []jsonSlot, items []item.Stack) {
    51  	for _, i := range encoded {
    52  		items[i.Slot] = decodeItem(i.Item)
    53  	}
    54  }
    55  
    56  func encodeItem(item item.Stack) []byte {
    57  	if item.Empty() {
    58  		return nil
    59  	}
    60  
    61  	var b bytes.Buffer
    62  	itemNBT := nbtconv.WriteItem(item, true)
    63  	encoder := nbt.NewEncoderWithEncoding(&b, nbt.LittleEndian)
    64  	err := encoder.Encode(itemNBT)
    65  	if err != nil {
    66  		return nil
    67  	}
    68  	return b.Bytes()
    69  }
    70  
    71  func decodeItem(data []byte) item.Stack {
    72  	var itemNBT map[string]any
    73  	decoder := nbt.NewDecoderWithEncoding(bytes.NewBuffer(data), nbt.LittleEndian)
    74  	err := decoder.Decode(&itemNBT)
    75  	if err != nil {
    76  		return item.Stack{}
    77  	}
    78  	return nbtconv.Item(itemNBT, nil)
    79  }