/
BookshelfBlock.java
488 lines (433 loc) · 15.6 KB
/
BookshelfBlock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package knightminer.inspirations.building.block;
import com.google.common.collect.ImmutableMap;
import com.mojang.datafixers.util.Pair;
import knightminer.inspirations.building.tileentity.BookshelfTileEntity;
import knightminer.inspirations.common.Config;
import knightminer.inspirations.common.IHidable;
import knightminer.inspirations.library.InspirationsRegistry;
import knightminer.inspirations.library.util.TextureBlockUtil;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.fluid.IFluidState;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.state.DirectionProperty;
import net.minecraft.state.EnumProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.Mirror;
import net.minecraft.util.NonNullList;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.IBooleanFunction;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import slimeknights.mantle.block.InventoryBlock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class BookshelfBlock extends InventoryBlock implements IHidable {
public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
public static final EnumProperty<Offset> POSITION = EnumProperty.create("pos", Offset.class);
public BookshelfBlock() {
super(Block.Properties.create(Material.WOOD)
.hardnessAndResistance(2.0F, 5.0F)
.sound(SoundType.WOOD)
);
this.setDefaultState(this.getStateContainer().getBaseState()
.with(FACING, Direction.NORTH)
.with(POSITION, Offset.FRONT)
);
}
/**
* Return the number of books this shelf can hold.
* @param state The relevant blockstate.
* @return The book count.
*/
public static int getBookCount(@Nullable BlockState state) {
if (state != null && state.get(BookshelfBlock.POSITION) == BookshelfBlock.Offset.BOTH) {
return 28;
} else {
return 14;
}
}
/** Compute which half of the shelf to access by comparing to the player's offset. */
public static boolean playerOnSecondary(World world, BlockPos pos, PlayerEntity player) {
return playerOnSecondary(world.getBlockState(pos), pos, player);
}
/** Compute which half of the shelf to access by comparing to the player's offset. */
public static boolean playerOnSecondary(BlockState state, BlockPos pos, PlayerEntity player) {
if (state.get(BookshelfBlock.POSITION) != BookshelfBlock.Offset.BOTH) {
// No secondary side.
return false;
}
// Check if the player is on the other side of the block.
Vec3d offset = player.getPositionVector().subtract(new Vec3d(pos).add(0.5, 0.5, 0.5));
return offset.dotProduct(new Vec3d(state.get(BookshelfBlock.FACING).getDirectionVec())) < 0;
}
@Override
public boolean hasTileEntity(BlockState state) {
return true;
}
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
builder.add(FACING, POSITION);
}
@Nonnull
@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new BookshelfTileEntity();
}
@Deprecated
@Nullable
@Override
public TileEntity createNewTileEntity(@Nonnull IBlockReader world) {
return new BookshelfTileEntity();
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockItemUseContext context) {
// Offset from the center of the block.
Vec3d offset = context.getHitVec().subtract(new Vec3d(context.getPos()).add(0.5, 0.5, 0.5));
Direction direction = context.getPlacementHorizontalFacing().getOpposite();
// Compute which half of the block the player clicked on.
Offset pos = (offset.dotProduct(new Vec3d(direction.getDirectionVec())) > 0) ? Offset.FRONT: Offset.BACK;
return getDefaultState().with(FACING, direction).with(POSITION, pos);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
super.onBlockPlacedBy(world, pos, state, placer, stack);
TextureBlockUtil.updateTextureBlock(world, pos, stack);
}
@Override
protected boolean openGui(PlayerEntity player, World world, BlockPos pos) {
if(!(player instanceof ServerPlayerEntity)) {
throw new AssertionError("Needs to be server!");
}
TileEntity te = world.getTileEntity(pos);
if(te instanceof BookshelfTileEntity) {
NetworkHooks.openGui((ServerPlayerEntity) player, (INamedContainerProvider) te, buf -> {
buf.writeBlockPos(pos);
buf.writeBoolean(playerOnSecondary(world, pos, player));
});
return true;
}
return false;
}
/* Enable/Disabling */
@Override
public boolean isEnabled() {
return Config.enableBookshelf.get();
}
@Override
public void fillItemGroup(@Nonnull ItemGroup group, @Nonnull NonNullList<ItemStack> items) {
if(shouldAddtoItemGroup(group)) {
super.fillItemGroup(group, items);
}
}
/* Activation */
@Override
public boolean onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult trace) {
Direction facing = state.get(FACING);
// If the player is looking at the secondary side.
boolean secHalf;
// Back side
if(facing.getOpposite() == trace.getFace()) {
switch (state.get(POSITION)) {
case BOTH:
// You have to be using a book on it.
secHalf = true;
break;
case BACK:
// Can't be upgraded, so do nothing.
return false;
case FRONT:
// No backside shelf, check to see if we can upgrade.
// The player must have an identical shelf to what we are.
ItemStack stack = player.getHeldItem(hand);
Block stackTexture = TextureBlockUtil.getTextureBlock(stack);
Block tileTexture = TextureBlockUtil.getTextureBlock(world.getTileEntity(pos));
if (stack.getItem() == asItem() && stackTexture == tileTexture) {
if (!world.isRemote) {
if (!player.isCreative()) {
stack.shrink(1);
}
return world.setBlockState(pos, state.with(POSITION, Offset.BOTH));
}
return true;
}
// No shelf and no book in hand.
return false;
default:
throw new IllegalStateException("Unexpected value: " + state.get(POSITION));
}
// Front side
} else if (facing == trace.getFace()) {
secHalf = false;
} else {
// Other sides.
// If you clicked on the exterior, we ignore that.
// But allow clicking inside the block.
Vec3d click = trace.getHitVec().subtract(new Vec3d(pos));
// The outer 1-pixel border we don't care about.
if (
click.x < 1/16.0 || click.x > 15/16.0 ||
click.y < 1/16.0 || click.y > 15/16.0 ||
click.z < 1/16.0 || click.z > 15/16.0
) {
return false;
}
// Compare postion to determine offset - if you're on the inside or outside.
secHalf = click
.add(0.5, 0.5, 0.5)
.dotProduct(new Vec3d(facing.getDirectionVec())) > 0.03125;
if(secHalf && state.get(BookshelfBlock.POSITION) != BookshelfBlock.Offset.BOTH) {
// Clicked on the back half somehow, but there's no shelf there. Bail.
return false;
}
}
// if sneaking, just do the GUI
if(player.isSneaking()) {
return world.isRemote || openGui(player, world, pos);
}
// if we did not click a book, just do the GUI as well
int book = bookClicked(facing, pos, trace.getHitVec(), secHalf);
if(book == -1) {
return world.isRemote || openGui(player, world, pos);
}
TileEntity te = world.getTileEntity(pos);
if(te instanceof BookshelfTileEntity) {
// try interacting
if(((BookshelfTileEntity) te).interact(player, hand, book)) {
return true;
}
// if the offhand can interact, return false so we can process it later
if(InspirationsRegistry.isBook(player.getHeldItemOffhand())) {
return false;
}
}
return true;
}
/** Compute the book which was clicked on.
*
* Whether the user is clicking on the primary or secondary shelf should
* have already been checked, so this doesn't re-check that.
* */
private static int bookClicked(Direction facing, BlockPos pos, Vec3d clickWorld, boolean secSide) {
Vec3d click = new Vec3d(clickWorld.x - pos.getX(), clickWorld.y - pos.getY(), clickWorld.z - pos.getZ());
// if we did not click between the shelves, ignore
if(click.y < 1/16.0 || click.y > 15/16.0) {
return -1;
}
int shelf = 0;
// if we clicked below the middle shelf, add 7 to the book
if(click.y <= 7/16.0) {
shelf = 7;
// if we clicked on the middle shelf itself, no book
} else if(click.y < 9/16.0) {
return -1;
}
// ensure we clicked within a shelf, not outside one.
// If we're along the axis we're facing,
// any position is valid. Otherwise, you must be inset 1 pixel.
int offX = facing.getXOffset();
int offZ = facing.getZOffset();
double x1 = offX != 0 ? 0 : 1/16.0;
double z1 = offZ != 0 ? 0 : 1/16.0;
double x2 = offX != 0 ? 1 : 15/16.0;
double z2 = offZ != 0 ? 1 : 15/16.0;
if(click.x < x1 || click.x > x2 || click.z < z1 || click.z > z2) {
return -1;
}
// okay, so now we know we clicked in the book area, so just take the position clicked to determine where.
// Calculate the direction along the shelf.
Direction dir;
if(secSide) {
dir = facing.rotateY();
shelf += 14;
} else {
dir = facing.rotateYCCW();
}
// subtract one pixel and multiply by our direction
double clicked = (dir.getXOffset() * click.x) + (dir.getZOffset() * click.z) - 0.0625;
// if negative, just add one to wrap back around
if(clicked < 0) {
clicked = 1 + clicked;
}
// multiply by 8 to account for extra 2 pixels
return shelf + Math.min((int) (clicked * 8), 6);
}
/*
* Bounds
*/
private static final ImmutableMap<Pair<Direction, Offset>, VoxelShape> BOUNDS;
/**
* Compute a voxelshape, rotated by the provided direction.
*/
private static VoxelShape makeRotatedShape(Direction side, int x1, int y1, int z1, int x2, int y2, int z2) {
float yaw = -(float) Math.PI / 2F * side.getHorizontalIndex();
Vec3d min = new Vec3d(x1 - 8, y1 - 8, z1 - 8).rotateYaw(yaw);
Vec3d max = new Vec3d(x2 - 8, y2 - 8, z2 - 8).rotateYaw(yaw);
return VoxelShapes.create(
0.5 + min.x / 16.0, 0.5 + min.y / 16.0, 0.5 + min.z / 16.0,
0.5 + max.x / 16.0, 0.5 + max.y / 16.0, 0.5 + max.z / 16.0
);
}
static {
// shelf bounds
ImmutableMap.Builder<Pair<Direction, Offset>, VoxelShape> builder = ImmutableMap.builder();
for(Direction side : Direction.Plane.HORIZONTAL) {
// Construct the shelf by constructing the full block, then cutting out the shelves.
// +Z is forward.
builder.put(Pair.of(side, Offset.BACK), VoxelShapes.combineAndSimplify(
// Slab
makeRotatedShape(side,0, 0, 0, 16, 16, 8),
VoxelShapes.or( // Bottom, top.
makeRotatedShape(side,1,1, 1, 15, 7, 8),
makeRotatedShape(side,1,9, 1, 15, 15, 8)
),
IBooleanFunction.ONLY_FIRST
));
builder.put(Pair.of(side, Offset.FRONT), VoxelShapes.combineAndSimplify(
// Slab
makeRotatedShape(side,0, 0, 8, 16, 16, 16),
VoxelShapes.or( // Bottom, top.
makeRotatedShape(side,1,1, 9, 15, 7, 16),
makeRotatedShape(side,1,9, 9, 15, 15, 16)
),
IBooleanFunction.ONLY_FIRST
));
builder.put(Pair.of(side, Offset.BOTH), VoxelShapes.combineAndSimplify(
VoxelShapes.fullCube(),
VoxelShapes.or( // Bottom back, top back, bottom front, top front
makeRotatedShape(side,1,1, 0, 15, 7, 7),
makeRotatedShape(side,1,9, 0, 15, 15, 7),
makeRotatedShape(side,1,1, 9, 15, 7, 16),
makeRotatedShape(side,1,9, 9, 15, 15, 16)
),
IBooleanFunction.ONLY_FIRST
));
}
BOUNDS = builder.build();
}
@Deprecated
@Nonnull
@Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
return BOUNDS.get(Pair.of(state.get(FACING), state.get(POSITION)));
}
/*
* Comparators
*/
@Override
public void onReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean isMoving) {
if(state.getBlock() != newState.getBlock()) {
TileEntity tileentity = world.getTileEntity(pos);
if(tileentity instanceof IInventory) {
InventoryHelper.dropInventoryItems(world, pos, (IInventory) tileentity);
}
}
super.onReplaced(state, world, pos, newState, isMoving);
}
@Deprecated
@Override
public boolean hasComparatorInputOverride(BlockState p_149740_1_) {
return true;
}
@Deprecated
@Override
public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof BookshelfTileEntity) {
return ((BookshelfTileEntity)te).getComparatorPower();
}
return 0;
}
/*
* Block properties
*/
@Nonnull
@Override
public BlockRenderLayer getRenderLayer() {
return BlockRenderLayer.CUTOUT;
}
@Override
public BlockState rotate(BlockState state, IWorld world, BlockPos pos, Rotation direction) {
return state.with(FACING, direction.rotate(state.get(FACING)));
}
@Deprecated
@Nonnull
@Override
public BlockState mirror(BlockState state, Mirror mirror) {
return state.with(FACING, mirror.mirror(state.get(FACING)));
}
/* Drops */
@Override
public ItemStack getPickBlock(BlockState state, RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player) {
return TextureBlockUtil.getPickBlock(world, pos, state);
}
@Override
public boolean removedByPlayer(BlockState state, World world, BlockPos pos, PlayerEntity player, boolean willHarvest, IFluidState fluid) {
// we pull up a few calls to this point in time because we still have the TE here
// the execution otherwise is equivalent to vanilla order
this.onBlockHarvested(world, pos, state, player);
if(willHarvest) {
this.harvestBlock(world, player, pos, state, world.getTileEntity(pos), player.getHeldItemMainhand());
}
world.setBlockState(pos, Blocks.AIR.getDefaultState());
// return false to prevent the above called functions to be called again
// side effect of this is that no xp will be dropped. but it shoudln't anyway from a bookshelf :P
return false;
}
@Override
public float getEnchantPowerBonus(BlockState state, IWorldReader world, BlockPos pos) {
if(!Config.bookshelvesBoostEnchanting.get()) {
return 0;
}
TileEntity te = world.getTileEntity(pos);
if(te instanceof BookshelfTileEntity) {
return ((BookshelfTileEntity) te).getEnchantPower();
}
return 0;
}
public enum Offset implements IStringSerializable {
BACK("back"),
FRONT("front"),
BOTH("both");
private final String name;
Offset(String name) {
this.name = name;
}
public String toString() {
return this.getName();
}
@Nonnull
@Override
public String getName() {
return name;
}
}
}